pm_facade.js 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301
  1. /**
  2. * Created by zhang on 2018/4/17.
  3. */
  4. const projectType = {
  5. folder: 'Folder',
  6. tender: 'Tender',
  7. project: 'Project',
  8. engineering: 'Engineering',
  9. };
  10. //先导出后require可以解决循环引用问题
  11. module.exports={
  12. prepareShareList,
  13. getShareList,
  14. addShareList,
  15. updateShareList,
  16. deleteShareList,
  17. getShareInfoMap,
  18. getRecentShareList,
  19. moveProject:moveProject,
  20. copyProject:copyProject,
  21. copyExample: copyExample,
  22. getSummaryInfo: getSummaryInfo,
  23. getSummaryInfoByTender: getSummaryInfoByTender,
  24. getIndexReportData: getIndexReportData,
  25. getTendersFeeInfo: getTendersFeeInfo,
  26. getConstructionProject: getConstructionProject,
  27. getFullPath: getFullPath,
  28. projectType: projectType,
  29. getPosterityProjects: getPosterityProjects,
  30. isShare: isShare,
  31. isFirst: isFirst,
  32. getShareInfo: getShareInfo,
  33. prepareInitialData: prepareInitialData,
  34. changeFile:changeFile,
  35. getBasicInfo: getBasicInfo,
  36. getProjectFeature: getProjectFeature,
  37. getProjectByGranularity: getProjectByGranularity,
  38. importProject: importProject,
  39. getProjectPlaceholder: getProjectPlaceholder,
  40. exportProject:exportProject,
  41. importProjects:importProjects,//建筑这里重名了,这比养护加多了个s
  42. initOverHeightItems: initOverHeightItems,
  43. uploadToken:uploadToken,
  44. downLoadProjectFile:downLoadProjectFile,
  45. importProcessChecking:importProcessChecking,
  46. importInterface,
  47. isTenderOverrun
  48. };
  49. let mongoose = require('mongoose');
  50. let _ = require("lodash");
  51. let feeRate_facade = require('../../fee_rates/facade/fee_rates_facade');
  52. let glj_facade = require('../../glj/facade/glj_facade');
  53. let project_facade = require('../../main/facade/project_facade');
  54. let logger = require("../../../logs/log_helper").logger;
  55. const uuidV1 = require('uuid/v1');
  56. let projectModel = mongoose.model('projects');
  57. let projectSettingModel = mongoose.model('proj_setting');
  58. let billsModel = mongoose.model('bills');
  59. let rationModel = mongoose.model('ration');
  60. let gljListModel = mongoose.model("glj_list");
  61. let calcProgramsModel = mongoose.model('calc_programs');
  62. let labourCoesModel = mongoose.model('labour_coes');
  63. let feeRateModel = mongoose.model('fee_rates');
  64. let feeRateFileModel = mongoose.model('fee_rate_file');
  65. let unitPriceFileModel = mongoose.model("unit_price_file");
  66. let mixRatioModel = mongoose.model("mix_ratio");
  67. let unitPriceModel = mongoose.model("unit_price");
  68. let installationFeeModel = mongoose.model("installation_fee");
  69. let rationGLJModel = mongoose.model('ration_glj');
  70. let rationCoeModel = mongoose.model('ration_coe');
  71. let rationInstallationModel = mongoose.model('ration_installation');
  72. let quantityDetailModel = mongoose.model('quantity_detail');
  73. let rationTemplateModel = mongoose.model('ration_template');
  74. let userModel = mongoose.model('user');
  75. let compleGljSectionModel = mongoose.model('complementary_glj_section');
  76. let compleGljSectionTModel = mongoose.model('complementary_glj_section_templates');
  77. let compilationModel = mongoose.model('compilation');
  78. let engineeringModel = mongoose.model('engineering_lib');
  79. let basicInfoModel = mongoose.model('std_basic_info_lib');
  80. let projectFeatureModel = mongoose.model('std_project_feature_lib');
  81. let productModel = mongoose.model('product');
  82. let stdRationItemModel = mongoose.model('std_ration_lib_ration_items');
  83. let stdGljItemModel = mongoose.model('std_glj_lib_gljList');
  84. import BillsTemplateModel from "../models/templates/bills_template_model";
  85. let evaluateListModel = mongoose.model("evaluate_list");
  86. let bidListModel = mongoose.model("bid_evaluation_list");
  87. let contractorListModel = mongoose.model("contractor_list");
  88. let featureLibModel = mongoose.model("std_project_feature_lib");
  89. let importLogsModel = mongoose.model("import_logs");
  90. const overHeightLibModel = mongoose.model('std_over_height_lib');
  91. const shareListModel = mongoose.model('share_list');
  92. let scMathUtil = require('../../../public/scMathUtil').getUtil();
  93. let counter = require('../../../public/counter/counter');
  94. import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
  95. let sectionTreeDao = new SectionTreeDao();
  96. import CounterModel from "../../glj/models/counter_model";
  97. import moment from 'moment-timezone';
  98. import billsFlags from '../../common/const/bills_fixed';
  99. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  100. import {
  101. defaultDecimal,
  102. billsQuantityDecimal,
  103. displaySetting,
  104. calcOptions,
  105. tenderSetting,
  106. G_FILE_VER
  107. } from '../models/project_property_template';
  108. let labourCoeFacade = require('../../main/facade/labour_coe_facade');
  109. let calcProgramFacade = require('../../main/facade/calc_program_facade');
  110. let mainColLibModel = mongoose.model('std_main_col_lib');
  111. import EngineeringLibModel from "../../users/models/engineering_lib_model";
  112. let installationFacade = require('../../main/facade/installation_facade');
  113. let cipher = require('../../../public/cipher');
  114. let qiniu = require("qiniu");
  115. let fs = require("fs");
  116. let path = require("path");
  117. let request = require("request");
  118. const systemSettingMiddleware = require('../../main/middleware/system_setting');
  119. let qiniu_config = {
  120. "AccessKey": "_gR1ed4vi1vT2G2YITGSf4_H0fJu_nRS9Tzk3T4z",
  121. "SecretKey": "ty4zd0FHqgEDaiVzSLC8DfHlai99aS7bspLkw6s6",
  122. "Bucket": "yun-update",
  123. "Domain": "http://serverupdate.smartcost.com.cn"
  124. };
  125. let mac = new qiniu.auth.digest.Mac(qiniu_config.AccessKey, qiniu_config.SecretKey);
  126. // 重构了分享的数据结构,原本存在projects表的shareInfo数组中
  127. // 为了更好地适应新功能及以后拓展功能,现将分享信息存放在单独的share_list表中
  128. // 为了适应旧数据,需要在share_list没有数据的时候,将原本的分享信息复制到share_list中,同时生成联系人
  129. // TODO: 上线后这个方法执行过后,应该删除此方法
  130. async function prepareShareList() {
  131. const shareListCount = await shareListModel.count({});
  132. console.log(shareListCount);
  133. if (shareListCount) {
  134. return;
  135. }
  136. logger.info('================================enterPrepareShareList================================================');
  137. // 将项目的shareInfo数据复制到share_list表中
  138. const projects = await projectModel.find({'shareInfo.0': {$exists: true}}, '-_id ID userID shareInfo').lean();
  139. if (!projects.length) {
  140. return;
  141. }
  142. const shareList = [];
  143. const userMap = {}; // 给生成联系人做准备
  144. projects.forEach(project => {
  145. const ownerContacts = userMap[project.userID] || (userMap[project.userID] = []);
  146. project.shareInfo.forEach(shareItem => {
  147. if (!shareItem.shareDate) {
  148. return;
  149. }
  150. const receiverContacts = userMap[shareItem.userID] || (userMap[shareItem.userID] = []);
  151. receiverContacts.push(project.userID);
  152. const newItem = {
  153. ID: uuidV1(),
  154. projectID: project.ID,
  155. owner: project.userID,
  156. receiver: shareItem.userID,
  157. allowCopy: shareItem.allowCopy,
  158. allowCooperate: shareItem.allowCooperate,
  159. shareDate: shareItem.shareDate,
  160. updateDate: shareItem.shareDate
  161. };
  162. ownerContacts.push(shareItem.userID);
  163. shareList.push(newItem);
  164. });
  165. });
  166. // 插入分享信息
  167. const shareListPromise = shareListModel.insertMany(shareList);
  168. const tasks = [shareListPromise];
  169. // 更新用户信息
  170. const userTasks = [];
  171. Object.entries(userMap).forEach(([userID, contacts]) => {
  172. contacts = [...new Set(contacts)]
  173. .map(user => ({ userID: user }));
  174. const task = {
  175. updateOne: {
  176. filter: {
  177. _id: mongoose.Types.ObjectId(userID)
  178. },
  179. update: {
  180. contacts
  181. }
  182. }
  183. };
  184. userTasks.push(task);
  185. });
  186. if (userTasks.length) {
  187. tasks.push(userModel.bulkWrite(userTasks));
  188. }
  189. await Promise.all(tasks);
  190. }
  191. // 获取分享列表
  192. async function getShareList(query) {
  193. return await shareListModel.find(query, '-_id').lean();
  194. }
  195. async function addShareList(docs) {
  196. await shareListModel.insertMany(docs);
  197. }
  198. async function deleteShareList(query) {
  199. await shareListModel.deleteMany(query);
  200. }
  201. async function updateShareList(updateData) {
  202. const bulks = updateData.map(item => (
  203. {
  204. updateOne: {
  205. filter: item.query,
  206. update: item.update
  207. }
  208. }
  209. ));
  210. if (bulks.length) {
  211. await shareListModel.bulkWrite(bulks);
  212. }
  213. }
  214. // 根据项目ID获取项目shareInfo字段的数据映射(前端旧逻辑依赖项目本身的shareInfo字段)
  215. async function getShareInfoMap(projectIDs, shareList = null) {
  216. if (!shareList) {
  217. shareList = await getShareList({projectID: {$in: projectIDs}});
  218. }
  219. // 将相同项目的分享信息进行映射
  220. const map = {};
  221. shareList.forEach(item => {
  222. const shareInfo = map[item.projectID] || (map[item.projectID] = []);
  223. shareInfo.push({
  224. userID: item.receiver,
  225. shareDate: item.shareDate,
  226. updateDate: item.updateDate,
  227. allowCopy: item.allowCopy,
  228. allowCooperate: item.allowCooperate
  229. });
  230. });
  231. return map;
  232. }
  233. // 获取最近分享(只算分享出去的记录)
  234. async function getRecentShareList(userID, count) {
  235. const shareList = await getShareList({owner: userID});
  236. shareList.sort((a, b) => Date.parse(b.shareDate) - Date.parse(a.shareDate));
  237. const set = new Set();
  238. for(const item of shareList) {
  239. if (set.size === count) {
  240. break;
  241. }
  242. set.add(item.receiver);
  243. }
  244. const sortedIDList = [...set];
  245. const userIDList = sortedIDList.map(userID => mongoose.Types.ObjectId(userID));
  246. const users = await userModel.find({_id: {$in: userIDList}}, 'real_name mobile company').lean();
  247. users.sort((a, b) => sortedIDList.indexOf(a._id.toString()) - sortedIDList.indexOf(b._id.toString()));
  248. return users;
  249. }
  250. //拷贝例题项目
  251. //@param {String}userID {Array}projIDs拷贝的例题项目ID(建设项目、文件夹)@return {Boolean}
  252. async function copyExample(userID, compilation, projIDs){
  253. let allProjs = [],
  254. IDMapping = {},
  255. projMapping = {};
  256. //例题项目不可为单项工程、单位工程、只能是建设项目、文件夹,否则不自动新建例题项目(这里不报错,让用户没有感觉)
  257. let parentExample = await projectModel.find({ID: {$in: projIDs}, $or: notDeleted}).lean();
  258. if (parentExample.length === 0) {
  259. return false;
  260. }
  261. allProjs = allProjs.concat(parentExample);
  262. for (let i = 0; i < parentExample.length; i++) {
  263. let data = parentExample[i];
  264. if (data.projType === projectType.tender || data.projType === projectType.engineering) {
  265. return false;
  266. }
  267. //设置成顶节点,最后一个节点设置成末节
  268. data.ParentID = -1;
  269. if (i === parentExample.length - 1) {
  270. data.NextSiblingID = -1;
  271. }
  272. }
  273. //获取所有的子项目
  274. let posterityProjs = await getPosterityProjects(projIDs);
  275. allProjs = allProjs.concat(posterityProjs);
  276. let projCounter = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, allProjs.length);
  277. //旧ID与新ID映射
  278. for (let i = 0; i < allProjs.length; i++) {
  279. let data = allProjs[i];
  280. let newID = projCounter.sequence_value - (allProjs.length - 1) + i;
  281. IDMapping[data.ID] = newID;
  282. projMapping[newID] = data;
  283. }
  284. //return;
  285. //设置新的树结构数据
  286. let newDate = new Date(),
  287. parentBulks = [];
  288. for (let data of allProjs) {
  289. let orgID = data.ID;
  290. data.ID = IDMapping[data.ID];
  291. data.ParentID = IDMapping[data.ParentID] ? IDMapping[data.ParentID] : -1;
  292. data.NextSiblingID = IDMapping[data.NextSiblingID] ? IDMapping[data.NextSiblingID] : -1;
  293. data.createDateTime = newDate;
  294. data.userID = userID;
  295. data.compilation = compilation;
  296. data.shareInfo = [];
  297. if (data.projType !== projectType.tender) {
  298. let newData = _.cloneDeep(data);
  299. delete newData._id;
  300. // await projectModel.create(newData);
  301. parentBulks.push({insertOne: {document: newData}});
  302. } else {
  303. //拷贝单位工程
  304. let rootProjectID = projMapping[data.ParentID].ParentID;
  305. let projectMap = {
  306. copy: {
  307. document: {userID: userID, ID: orgID, NextSiblingID: data.NextSiblingID, ParentID: data.ParentID, name: data.name, shareInfo: [],
  308. compilation: compilation, fileVer: data.fileVer, projType: data.projType, property: {rootProjectID: rootProjectID}}
  309. }
  310. };
  311. await copyProject(userID, compilation, {projectMap}, data.ID);
  312. }
  313. }
  314. //最末顶层项目(兼容测试时已存在有项目,正常用户第一次进费用定额,该费用定额不存在项目)
  315. let lastProj = await projectModel.findOne({userID: userID, compilation: compilation, ParentID: -1, NextSiblingID: -1, $or: notDeleted});
  316. if (lastProj) {
  317. parentBulks.push({updateOne: {filter: {ID: lastProj.ID}, update: {$set: {NextSiblingID: parentExample[0].ID}}}});
  318. }
  319. //拷贝父级文件
  320. await projectModel.bulkWrite(parentBulks);
  321. return true;
  322. }
  323. async function copyProject(userID, compilationID,data,newProjectID = null) {
  324. let projectMap = data.projectMap;
  325. let originalID = projectMap['copy'].document.ID;
  326. if (!newProjectID) {
  327. newProjectID = await getCounterID("projects");
  328. }
  329. let newFeeName = null,newUnitName = null;
  330. let calcProgramFileID = uuidV1();//新的计算程序文件ID
  331. let labourCoeFileID = uuidV1();//新的人工调整系数文件ID
  332. let feeRateFileID = uuidV1();//新的费率文件ID
  333. let unitPriceFileID = await getCounterID("unit_price_file");//新的单价文件ID
  334. let originalProject = await projectModel.findOne({'ID':originalID});//查找最新的那项目信息,前端缓存的数据有可能不是最新的
  335. if(!originalProject){
  336. throw new Error('没有找到对应的项目,复制失败!');
  337. }
  338. let property = originalProject.property;
  339. if(projectMap['copy'].document.property){//更新项目属性信息
  340. setProperty(property,projectMap['copy'].document.property);
  341. }
  342. let originalProperty = _.cloneDeep(property);
  343. projectMap['copy'].document.property = property;
  344. logger.info("复制项目: 旧项目ID: "+originalID+ " ------- 新项目ID: "+newProjectID);
  345. //费率文件、单价文件重名检查
  346. let feeRate = await feeRateFileModel.findOne({rootProjectID:originalProperty.rootProjectID,name:originalProperty.feeFile.name,deleteInfo:null});
  347. if(feeRate){//存在重名的文件
  348. newFeeName = originalProperty.feeFile.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '复制)';
  349. projectMap['copy'].document.property.feeFile.name = newFeeName;
  350. }
  351. let unitPriceFile = await unitPriceFileModel.findOne({root_project_id: originalProperty.rootProjectID,name:originalProperty.unitPriceFile.name,deleteInfo: null});
  352. if(unitPriceFile){//存在重名的文件
  353. newUnitName = originalProperty.unitPriceFile.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '复制)';
  354. projectMap['copy'].document.property.unitPriceFile.name = newUnitName;
  355. }
  356. //更新项目的属性;
  357. projectMap['copy'].document.ID = newProjectID;
  358. if(projectMap['copy'].document.property.calcProgramFile){
  359. projectMap['copy'].document.property.calcProgramFile.ID = calcProgramFileID;
  360. }
  361. if(projectMap['copy'].document.property.labourCoeFile){
  362. projectMap['copy'].document.property.labourCoeFile.ID = labourCoeFileID;
  363. }
  364. if(projectMap['copy'].document.property.feeFile){
  365. projectMap['copy'].document.property.feeFile.id = feeRateFileID;
  366. }
  367. if(projectMap['copy'].document.property.unitPriceFile){
  368. projectMap['copy'].document.property.unitPriceFile.id = unitPriceFileID;
  369. }
  370. projectMap['copy'].document.userID = userID;
  371. projectMap['copy'].document.compilation = compilationID;
  372. projectMap['copy'].document.createDateTime = new Date();
  373. //清单、定额ID生成任务
  374. let IDtasks = [
  375. createIDsAndReturn(originalID,billsModel),
  376. createIDsAndReturn(originalID,rationModel),
  377. getProjectGLJIDAndReturn(originalID,newProjectID)
  378. ];
  379. let [billMap,rationMap,projectGLJMap] = await Promise.all(IDtasks);
  380. //所有复制任务异步处理,提升效率 复制清单,定额,4个文件,项目工料机, 定额工料机,人工系数,工程量明细,定额安装增加费,安装增加费
  381. let copyTasks = [
  382. createProject(projectMap),
  383. copyProjectSetting(originalID,newProjectID),
  384. copyBills(newProjectID,billMap),
  385. copyRations(newProjectID,billMap.uuidMaping,rationMap,projectGLJMap.IDMap),
  386. copyProjectGLJ(projectGLJMap.datas),
  387. copyInstallFee(originalID,newProjectID),
  388. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationGLJModel),
  389. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationCoeModel),
  390. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,quantityDetailModel),
  391. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationInstallationModel),
  392. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationTemplateModel),
  393. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,evaluateListModel),
  394. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,bidListModel),
  395. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,contractorListModel),
  396. ];
  397. if(originalProperty.calcProgramFile){
  398. copyTasks.push(commonCopy(newProjectID,originalProperty.calcProgramFile.ID,calcProgramFileID,calcProgramsModel));
  399. }
  400. if(originalProperty.labourCoeFile){
  401. copyTasks.push(commonCopy(newProjectID,originalProperty.labourCoeFile.ID,labourCoeFileID,labourCoesModel));
  402. }
  403. if(originalProperty.feeFile){
  404. copyTasks.push(copyFeeRate(originalProperty.rootProjectID,userID,originalProperty.feeFile.id,feeRateFileID,newFeeName));
  405. }
  406. if(originalProperty.unitPriceFile){
  407. copyTasks.push(copyUnitPriceFile(newProjectID,originalProperty.rootProjectID,userID,originalProperty.unitPriceFile.id,unitPriceFileID,newUnitName));
  408. }
  409. let p = await Promise.all(copyTasks);
  410. return p[0];
  411. }
  412. async function createIDsAndReturn(originalID,model) {
  413. let uuidMaping = {};//做ID映射
  414. let datas = [];
  415. let result = await model.find({"projectID": originalID}, '-_id');
  416. uuidMaping['-1'] = -1;
  417. //建立uuid-ID映射
  418. for(let d of result){
  419. uuidMaping[d.ID] = uuidV1();
  420. datas.push(d._doc);
  421. }
  422. return{uuidMaping:uuidMaping,datas:datas};
  423. }
  424. async function getProjectGLJIDAndReturn(originalID,newProjectID) {
  425. let IDMap = {};
  426. let datas = [];
  427. let result = await gljListModel.find({project_id:originalID}, '-_id');
  428. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, result.length);
  429. for(let i = 0; i < result.length; i++){
  430. let d = result[i];
  431. let newID = gljCount.sequence_value - (result.length - 1) + i;
  432. //let newID = await getCounterID("glj_list");
  433. IDMap[d.id] = newID;
  434. d._doc.project_id = newProjectID;
  435. d._doc.id = newID;
  436. datas.push(d._doc);
  437. }
  438. return{IDMap:IDMap,datas:datas};
  439. }
  440. async function createProject(projectMap) {//复制项目
  441. let tasks = [];
  442. if(projectMap['update']){//如果复制后存在前一个节点,则更新其NextSiblingID
  443. tasks.push({updateOne:{filter : projectMap['update'].query, update : {NextSiblingID:projectMap['copy'].document.ID}}});
  444. }
  445. tasks.push({insertOne: {document: projectMap['copy'].document}});//复制任务
  446. await projectModel.bulkWrite(tasks);
  447. return projectMap;
  448. }
  449. async function copyProjectSetting(originalID,newProjectID) {
  450. let result = null;
  451. let setting = await projectSettingModel.findOne({"projectID": originalID}, '-_id');
  452. if(setting){
  453. setting._doc.projectID =newProjectID;
  454. result = await projectSettingModel.create(setting._doc);
  455. }
  456. return result;
  457. }
  458. async function copyBills(newProjectID,billMap) {
  459. let uuidMaping = billMap.uuidMaping;//做ID映射
  460. for(let doc of billMap.datas){
  461. doc = getCopyBillDatas(doc,newProjectID,uuidMaping);
  462. }
  463. await insertMany(billMap.datas,billsModel);
  464. return billMap.datas;
  465. }
  466. function getCopyBillDatas(doc,newProjectID,uuidMaping) {
  467. doc.projectID = newProjectID;
  468. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  469. doc.ParentID = uuidMaping[doc.ParentID] ? uuidMaping[doc.ParentID] : -1;
  470. doc.NextSiblingID = uuidMaping[doc.NextSiblingID] ? uuidMaping[doc.NextSiblingID] : -1;
  471. //对于有基数计算的节点,需要替换计算基数中引用的ID为新的ID
  472. if(doc.calcBase && doc.calcBase != ""){
  473. let idArr = scMathUtil.getFIDArr(doc.calcBase);
  474. for(let re of idArr){
  475. let oID = re.substr(1);//去掉开头的@字符
  476. if(!uuidMaping[oID]) continue;
  477. doc.calcBase = doc.calcBase.replace(new RegExp(oID, "g"),uuidMaping[oID]);
  478. }
  479. }
  480. return doc;
  481. }
  482. async function copyRations(newProjectID,billsIDMap,rationMap,projectGLJIDMap) {
  483. let uuidMaping = rationMap.uuidMaping;
  484. for(let doc of rationMap.datas){
  485. doc = getCopyRationData(doc,newProjectID,billsIDMap,uuidMaping,projectGLJIDMap);
  486. }
  487. if(rationMap.datas.length > 0){
  488. await insertMany(rationMap.datas,rationModel);
  489. }
  490. return rationMap.datas;
  491. }
  492. function getCopyRationData(doc,newProjectID,billsIDMap,uuidMaping,projectGLJIDMap){
  493. doc.projectID = newProjectID;
  494. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  495. if(doc.billsItemID){
  496. doc.billsItemID = billsIDMap[doc.billsItemID]?billsIDMap[doc.billsItemID]:-1;
  497. }
  498. if(doc.referenceRationID) doc.referenceRationID = uuidMaping[doc.referenceRationID]?uuidMaping[doc.referenceRationID]:undefined;
  499. //绑定定类型的工料机 项目工料机ID
  500. doc.type==3&&doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  501. return doc;
  502. }
  503. async function copyProjectGLJ(gljList) {
  504. await insertMany(gljList,gljListModel);
  505. }
  506. async function commonCopy(newProjectID,oldID,newID,model) { //对于只需更新ID和projectID的文件的复制
  507. let result = null;
  508. let file = await model.findOne({"ID": oldID}, '-_id');
  509. if(file){
  510. file._doc.ID = newID;
  511. file._doc.projectID =newProjectID;
  512. result = await model.create(file._doc);
  513. }
  514. return result;
  515. }
  516. async function copyFeeRate(rootProjectID,userID,originalFeeRateFileID,feeRateFileID,newName) {//复制费率和费率文件
  517. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(originalFeeRateFileID);
  518. let newFeeRateID = uuidV1();
  519. if(feeRate){
  520. feeRate._doc.ID = newFeeRateID;
  521. await feeRateModel.create(feeRate._doc);
  522. }
  523. if(feeRateFile){
  524. feeRateFile._doc.ID = feeRateFileID;
  525. newName?feeRateFile._doc.name = newName:'';
  526. feeRateFile._doc.userID = userID;
  527. feeRateFile._doc.rootProjectID = rootProjectID;
  528. feeRateFile._doc.feeRateID = newFeeRateID;
  529. await feeRateFileModel.create(feeRateFile._doc);
  530. }
  531. }
  532. async function copyUnitPriceFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName) {//复制单价文件、组成物
  533. let taskList = [
  534. copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName),
  535. copySubList(originaluUnitPriceFileID,unitPriceFileID,mixRatioModel),
  536. copySubList(originaluUnitPriceFileID,unitPriceFileID,unitPriceModel)
  537. ];
  538. return await Promise.all(taskList);
  539. async function copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName){
  540. let unitPriceFile = await unitPriceFileModel.findOne({id:originaluUnitPriceFileID}, '-_id');
  541. if(unitPriceFile){
  542. unitPriceFile._doc.id = unitPriceFileID;
  543. newName?unitPriceFile._doc.name = newName:'';
  544. unitPriceFile._doc.project_id = newProjectID;
  545. unitPriceFile._doc.user_id = userID;
  546. unitPriceFile._doc.root_project_id = rootProjectID
  547. }
  548. await unitPriceFileModel.create(unitPriceFile._doc);
  549. }
  550. async function copySubList(srcFID,newFID,model) {
  551. let mList = await model.find({unit_price_file_id: srcFID}, '-_id');
  552. let rList = [];
  553. for(let m of mList){
  554. m._doc.unit_price_file_id = newFID;
  555. m._doc.id = await getCounterID(model.modelName);
  556. rList.push(m._doc);
  557. }
  558. await insertMany(rList,model)
  559. }
  560. }
  561. async function copyInstallFee(originalPID,newProjectID) {
  562. let result = null;
  563. let installationFee = await installationFeeModel.find({projectID:originalPID}, '-_id');
  564. let newList = [];
  565. for(let i of installationFee ){
  566. i._doc.ID = uuidV1();
  567. i._doc.projectID = newProjectID;
  568. newList.push(i._doc);
  569. }
  570. if(newList.length >0){
  571. result = await installationFeeModel.insertMany(newList);
  572. }
  573. return result;
  574. }
  575. async function copyRationSubList(originalPID,newProjectID,billIDMap,rationIDMap,projectGLJIDMap,model) {// 定额工料机,附注条件,工程量明细,定额安装增加费,模板子目
  576. let subList = await model.find({projectID:originalPID}, '-_id');
  577. let newList =[];
  578. for(let s of subList){
  579. s._doc = getCopyRationSubData(s._doc,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  580. /* s._doc.ID = uuidV1();
  581. s._doc.projectID = newProjectID;
  582. s._doc.rationID&&rationIDMap[s._doc.rationID]?s._doc.rationID = rationIDMap[s._doc.rationID]:'';
  583. s._doc.billID&&billIDMap[s._doc.billID]?s._doc.billID = billIDMap[s._doc.billID]:'';
  584. s._doc.billsItemID&&billIDMap[s._doc.billsItemID]?s._doc.billsItemID = billIDMap[s._doc.billsItemID]:'';
  585. s._doc.projectGLJID&&projectGLJIDMap[s._doc.projectGLJID]?s._doc.projectGLJID = projectGLJIDMap[s._doc.projectGLJID]:'';
  586. if(s._doc.templateList && s._doc.templateList.length > 0 ){
  587. for(let t of s._doc.templateList){
  588. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  589. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  590. }
  591. }*/
  592. newList.push(s._doc);
  593. }
  594. await insertMany(newList,model);
  595. }
  596. async function copyMaterialList(originalPID,newProjectID,projectGLJIDMap,model) {//暂估材料等信息
  597. let materialList = await model.find({projectID:originalPID}, '-_id').lean();
  598. let newList = [];
  599. for(let m of materialList){
  600. newList.push(getNewMaterial(m,newProjectID,projectGLJIDMap))
  601. }
  602. await insertMany(newList,model);
  603. }
  604. function getNewMaterial(m,newProjectID,projectGLJIDMap) {
  605. m.ID = uuidV1();
  606. m.projectID = newProjectID;
  607. if(projectGLJIDMap[m.projectGLJID]) m.projectGLJID = projectGLJIDMap[m.projectGLJID];
  608. return m;
  609. }
  610. function getCopyRationSubData(doc,newProjectID,billIDMap,rationIDMap,projectGLJIDMap){
  611. doc.ID = uuidV1();
  612. doc.projectID = newProjectID;
  613. doc.rationID&&rationIDMap[doc.rationID]?doc.rationID = rationIDMap[doc.rationID]:'';
  614. doc.billID&&billIDMap[doc.billID]?doc.billID = billIDMap[doc.billID]:'';
  615. doc.billsItemID&&billIDMap[doc.billsItemID]?doc.billsItemID = billIDMap[doc.billsItemID]:'';
  616. doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  617. if(doc.templateList && doc.templateList.length > 0 ){
  618. for(let t of doc.templateList){
  619. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  620. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  621. }
  622. }
  623. return doc;
  624. }
  625. async function moveProject(data) {
  626. data = JSON.parse(data);
  627. let projectMap = data.projectMap,feeRateMap = data.feeRateMap,unitPriceMap = data.unitPriceMap;
  628. let projectTasks = [],feeRateTask=[],feeRateFileTask=[],unitPriceTask=[],unitPriceFileTask=[],mixRatioTask=[];
  629. let feeUniqMap=[],priceUniqMap={};//费率、单价文件唯一映射表当移动多个项目时,任务有可能出现重复的情况
  630. if(!_.isEmpty(feeRateMap)&&data.rootProjectID){//如果费率有修改
  631. let feeRates =await feeRate_facade.getFeeRatesByProject(data.rootProjectID);//取目标建设项目的所有费率文件,重名检查
  632. for(let projectID in feeRateMap){
  633. let rename = feeRateMap[projectID].name;
  634. let feeRateID = feeRateMap[projectID].query.ID;
  635. let checkFee = _.find(feeRates,{'name':rename});
  636. let newID = feeRateID;
  637. if(checkFee){//说明费率名字已存在,需要重命名
  638. rename = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  639. projectMap[projectID]['update']['property.feeFile.name'] = rename;
  640. if(feeRateMap[projectID].action == 'move'){
  641. feeRateMap[projectID].update.name = rename;
  642. }
  643. }
  644. if(feeRateMap[projectID].action == 'copy'){
  645. newID = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].ID:uuidV1();
  646. feeRateMap[projectID].name = rename;
  647. feeRateMap[projectID].ID = newID;
  648. projectMap[projectID]['update']['property.feeFile.id'] = newID;
  649. }
  650. if(!feeUniqMap[feeRateID]){
  651. await generateFeeRateTask(feeRateMap[projectID],feeRateTask,feeRateFileTask);
  652. feeUniqMap[feeRateID] = {name:rename,ID:newID};
  653. }
  654. }
  655. }
  656. if(!_.isEmpty(unitPriceMap)&&data.rootProjectID) {//如果单价文件有修改
  657. let unitPriceFiles = await unitPriceFileModel.find({root_project_id: data.rootProjectID, deleteInfo: null});
  658. for(let projectID in unitPriceMap){
  659. let checkUn = _.find(unitPriceFiles,{'name':unitPriceMap[projectID].name});
  660. let rename = unitPriceMap[projectID].name;
  661. let unitPriceID = unitPriceMap[projectID].query.id;
  662. let newID = unitPriceID;
  663. if(checkUn){//重名检查
  664. rename = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  665. projectMap[projectID]['update']['property.unitPriceFile.name'] = rename;
  666. if(unitPriceMap[projectID].action =='move'){
  667. unitPriceMap[projectID].update.name = rename;
  668. }
  669. }
  670. if(unitPriceMap[projectID].action =='copy'){
  671. newID = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].id: await getCounterID("unit_price_file");
  672. unitPriceMap[projectID].name = rename;
  673. unitPriceMap[projectID].id = newID;
  674. projectMap[projectID]['update']['property.unitPriceFile.id'] = newID;
  675. }
  676. if(!priceUniqMap[unitPriceID]){
  677. await generateUnitPriceTask(unitPriceMap[projectID],projectID,data.user_id,unitPriceTask,unitPriceFileTask,mixRatioTask);
  678. priceUniqMap[unitPriceID] = {name:rename,id:newID};
  679. }
  680. }
  681. }
  682. if(!_.isEmpty(projectMap)){
  683. for(let projectID in projectMap){
  684. projectTasks.push({updateOne:{filter : projectMap[projectID].query, update : projectMap[projectID].update}});
  685. }
  686. }
  687. projectTasks.length>0?await projectModel.bulkWrite(projectTasks):'';
  688. feeRateTask.length>0?await feeRateModel.bulkWrite(feeRateTask):'';
  689. feeRateFileTask.length>0?await feeRateFileModel.bulkWrite(feeRateFileTask):'';
  690. unitPriceFileTask.length>0?await unitPriceFileModel.bulkWrite(unitPriceFileTask):'';
  691. unitPriceTask.length>0?await insertMany(unitPriceTask,unitPriceModel):'';
  692. mixRatioTask.length>0?await insertMany(mixRatioTask,mixRatioModel):'';
  693. return projectMap;
  694. }
  695. async function generateFeeRateTask(data,feeRateTask,feeRateFileTask) {
  696. if(data.action == 'move'){
  697. let task = {
  698. updateOne:{
  699. filter : data.query,
  700. update : data.update
  701. }
  702. };
  703. feeRateFileTask.push(task);
  704. }
  705. if(data.action == 'copy'){//copy 费率的时候用insertOne方法
  706. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(data.query.ID);
  707. let newFeeRateID = uuidV1();
  708. let newFeeRate = {
  709. ID:newFeeRateID,
  710. rates:feeRate.rates
  711. };
  712. let newFeeRateFile = {
  713. ID:data.ID,
  714. rootProjectID:data.rootProjectID,
  715. userID:feeRateFile.userID,
  716. name:data.name,
  717. libID:feeRateFile.libID,
  718. libName:feeRateFile.libName,
  719. feeRateID:newFeeRateID
  720. };
  721. feeRateTask.push({insertOne :{document:newFeeRate}});
  722. feeRateFileTask.push({insertOne :{document:newFeeRateFile}});
  723. }
  724. }
  725. async function generateUnitPriceTask(data,projectID,user_id,unitPriceTask,unitPriceFileTask,mixRatioTask){
  726. if(data.action == 'move'){
  727. let task = {
  728. updateOne:{
  729. filter : data.query,
  730. update : data.update
  731. }
  732. };
  733. unitPriceFileTask.push(task);
  734. }
  735. if(data.action == 'copy'){
  736. let newUnitFile = {
  737. id:data.id,
  738. name: data.name,
  739. project_id:projectID,
  740. user_id:user_id,
  741. root_project_id: data.rootProjectID
  742. };
  743. unitPriceFileTask.push({insertOne :{document:newUnitFile}});
  744. let mixRatios = await mixRatioModel.find({unit_price_file_id: data.query.id});
  745. mixRatios = JSON.stringify(mixRatios);
  746. mixRatios = JSON.parse(mixRatios);
  747. for(let m of mixRatios){
  748. delete m._id; // 删除原有id信息
  749. delete m.id;
  750. m.unit_price_file_id = data.id;
  751. m.id = await getCounterID('mix_ratio');
  752. mixRatioTask.push(m);
  753. }
  754. let unitPrices = await unitPriceModel.find({unit_price_file_id: data.query.id});//unit_price_file_id
  755. unitPrices = JSON.stringify(unitPrices);
  756. unitPrices = JSON.parse(unitPrices);
  757. for(let u of unitPrices){
  758. delete u._id; // 删除原有id信息
  759. delete u.id;
  760. u.unit_price_file_id = data.id;
  761. u.id = await getCounterID('unit_price');
  762. unitPriceTask.push(u);
  763. }
  764. }
  765. }
  766. async function getCounterID(collectionName){
  767. let counterModel = new CounterModel();
  768. return await counterModel.getId(collectionName);
  769. }
  770. async function insertMany(datas,model) {
  771. while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
  772. let newList = datas.splice(0,1000);//一次插入1000条
  773. await model.insertMany(newList);
  774. }
  775. await model.insertMany(datas);
  776. }
  777. function setProperty(Obj,updateData) {
  778. for(let ukey in updateData){
  779. if(_.isObject(updateData[ukey]) && _.isObject(Obj[ukey])){
  780. setProperty(Obj[ukey],updateData[ukey]);
  781. }else {
  782. Obj[ukey] = updateData[ukey];
  783. }
  784. }
  785. }
  786. function isDef(v){
  787. return typeof v !== 'undefined' && v !== null;
  788. }
  789. function getTotalFee(bills, feeName) {
  790. if(!isDef(bills)){
  791. return 0;
  792. }
  793. if(!isDef(bills.fees) || bills.fees.length <= 0){
  794. return 0;
  795. }
  796. for(let fee of bills.fees){
  797. if(isDef(fee.fieldName) && fee.fieldName === feeName){
  798. return isDef(fee.totalFee) ? fee.totalFee : 0;
  799. }
  800. }
  801. return 0;
  802. }
  803. function summarizeToParent(parent, child, fields = null) {
  804. const decimal = -2;
  805. if (!fields) {
  806. fields = ['engineeringCost', 'subEngineering', 'measure', 'safetyConstruction', 'other', 'charge', 'tax', 'estimate'];
  807. }
  808. for (let field of fields) {
  809. parent[field] = scMathUtil.roundTo(parseFloat(parent[field]) + parseFloat(child[field]), decimal);
  810. }
  811. }
  812. function getBuildingArea(projFeature){
  813. if(!projFeature || projFeature.length === 0){
  814. return null;
  815. }
  816. for(let f of projFeature){
  817. if(f.key === 'buildingArea'){
  818. return f.value;
  819. }
  820. }
  821. return null;
  822. }
  823. //根据单位工程ID获取经济指标信息
  824. //@param {Number}prj_id @return {Object}
  825. async function getIndexReportData(prj_id, filters) {
  826. return await project_facade.getIndexReportData(prj_id, filters);
  827. }
  828. // 根据树结构数据排序
  829. function getSortedDataByTree(data) {
  830. // NextSiblingID-数据映射
  831. const mapping = {};
  832. data.forEach(item => {
  833. // 错误数据兼容处理
  834. // 由于之前的导入建设项目,会导致最后的一个项目的NextSiblingID为空,为非正确的-1
  835. // 因此把项目中NextSibling为空的数据设置为NextSiblingID为-1
  836. if (!item.NextSiblingID) {
  837. item.NextSiblingID = -1;
  838. }
  839. mapping[item.NextSiblingID] = item;
  840. });
  841. let lastItem = data.find(item => +item.NextSiblingID === -1);
  842. if (!lastItem) {
  843. return data;
  844. }
  845. const rst = [lastItem];
  846. let preItem = mapping[lastItem.ID];
  847. while (preItem) {
  848. rst.unshift(preItem);
  849. preItem = mapping[preItem.ID];
  850. }
  851. // 根据树结构排序形成的新数组与旧数组项数不同,说明树结构数据有问题(断链),则返回原本数据。
  852. return rst.length === data.length ? rst : data;
  853. }
  854. //根据单位工程ID获取汇总信息
  855. //@param {Number}tenderID {String}summaryType @return {Object}
  856. async function getSummaryInfoByTender(tenderID, summaryType) {
  857. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  858. let tender = await projectModel.findOne({ID: tenderID, $or: notDeleted});
  859. let parent,
  860. parentName,
  861. compilationIllustration;
  862. let summaryList = [];
  863. if(!tender){
  864. return null;
  865. }
  866. let engineering = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
  867. if(!engineering){
  868. return null;
  869. }
  870. let project = await projectModel.findOne({ID: engineering.ParentID, $or: notDeleted});
  871. if(!project){
  872. return null;
  873. }
  874. let summaryInfo = await getSummaryInfo([project.ID]);
  875. if(summaryType === projectType.engineering){ // 汇总到单项工程级别
  876. parent = engineering;
  877. let tenders = await projectModel.find({ParentID: engineering.ID, $or: notDeleted}).lean();
  878. tenders = getSortedDataByTree(tenders);
  879. for(let t of tenders){
  880. if(summaryInfo[t.ID]){
  881. summaryInfo[t.ID]['name'] = t.name ? t.name : '';
  882. summaryList.push(summaryInfo[t.ID]);
  883. }
  884. }
  885. } else { // 汇总到建设项目级别
  886. parent = project;
  887. let engs = await projectModel.find({ParentID: project.ID, $or: notDeleted}).lean();
  888. engs = getSortedDataByTree(engs);
  889. for(let e of engs){
  890. if(summaryInfo[e.ID]){
  891. summaryInfo[e.ID]['name'] = e.name ? e.name : '';
  892. summaryList.push(summaryInfo[e.ID]);
  893. }
  894. }
  895. }
  896. // 项目名称
  897. parentName = parent && parent.name
  898. ? parent.name
  899. : '';
  900. // 编制说明
  901. compilationIllustration = parent && parent.property && parent.property.compilationIllustration
  902. ? parent.property.compilationIllustration
  903. : '';
  904. return {
  905. parent: {
  906. name: parentName,
  907. compilationIllustration: compilationIllustration},
  908. subList: summaryList
  909. };
  910. }
  911. //获取单位工程的各标段费用信息(不进行汇总)
  912. async function getTendersFeeInfo(tenders) {
  913. let IDMapping = {};
  914. //固定清单类别与汇总金额字段映射
  915. let flagFieldMapping = {};
  916. flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  917. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  918. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  919. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  920. flagFieldMapping[billsFlags.OTHER] = 'other';
  921. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  922. flagFieldMapping[billsFlags.TAX] = 'tax';
  923. let tenderIDs = [];
  924. if(tenders.length > 0){
  925. for(let tender of tenders){
  926. tenderIDs.push(tender.ID);
  927. IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  928. IDMapping[tender.ID]['buildingArea'] = '';
  929. }
  930. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
  931. let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  932. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];
  933. //获取单位工程汇总金额需要用到的所有清单
  934. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
  935. '-_id projectID fees flags');
  936. //进行单位工程级别的汇总
  937. for(let bills of allBills){
  938. let billsFlag = bills.flags[0]['flag'];
  939. let costField = flagFieldMapping[billsFlag];
  940. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  941. //暂估合价(工程造价暂估合价)
  942. if (billsFlag === billsFlags.ENGINEERINGCOST){
  943. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  944. }
  945. }
  946. //占造价比例、单方造价
  947. for(let tender of tenders){
  948. let tenderInfo = IDMapping[tender.ID];
  949. tenderInfo.rate = '';
  950. //单方造价
  951. tenderInfo.perCost = '';
  952. }
  953. }
  954. return IDMapping;
  955. }
  956. async function getSummaryInfo(projectIDs, feeFields = null){
  957. function initFees(obj, feeFields) {
  958. for (let data of feeFields) {
  959. obj[data.v] = 0;
  960. }
  961. }
  962. if (!feeFields) {
  963. feeFields = [
  964. {k: billsFlags.ENGINEERINGCOST, v: 'engineeringCost'},
  965. {k: billsFlags.SUB_ENGINERRING, v: 'subEngineering'},
  966. {k: billsFlags.MEASURE, v: 'measure'},
  967. {k: billsFlags.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  968. {k: billsFlags.OTHER, v: 'other'},
  969. {k: billsFlags.CHARGE, v: 'charge'},
  970. {k: billsFlags.TAX, v: 'tax'}
  971. ];
  972. }
  973. //ID与汇总信息映射
  974. let IDMapping = {};
  975. //固定清单类别与汇总金额字段映射
  976. let flagFieldMapping = {};
  977. for (let data of feeFields) {
  978. flagFieldMapping[data.k] = data.v;
  979. }
  980. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  981. //设置建设项目的总建筑面积
  982. for(let project of projects){
  983. let grossArea = '';
  984. if(project.property && project.property.basicInformation){
  985. for(let basicInfo of project.property.basicInformation){
  986. if(basicInfo.key === 'basicInfo'){
  987. for(let k of basicInfo.items){
  988. if(k.key === 'grossArea'){
  989. grossArea = k.value;
  990. }
  991. }
  992. }
  993. }
  994. }
  995. IDMapping[project.ID] = {estimate: 0, rate: 0, buildingArea: grossArea, perCost: ''};
  996. initFees(IDMapping[project.ID], feeFields);
  997. console.log(IDMapping[project.ID]);
  998. }
  999. //单项工程
  1000. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1001. //单位工程
  1002. let tenders = [];
  1003. let engIDs = [];
  1004. for(let eng of engineerings){
  1005. engIDs.push(eng.ID);
  1006. IDMapping[eng.ID] = {estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  1007. initFees(IDMapping[eng.ID], feeFields);
  1008. }
  1009. if(engIDs.length > 0){
  1010. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1011. }
  1012. let tenderIDs = [];
  1013. if(tenders.length > 0){
  1014. for(let tender of tenders){
  1015. tenderIDs.push(tender.ID);
  1016. IDMapping[tender.ID] = {rate: 0, estimate: 0, buildingArea: '', perCost: '', changeMark:tender.changeMark,property:tender.property};
  1017. initFees(IDMapping[tender.ID], feeFields);
  1018. let buildingArea = getBuildingArea(tender.property.projectFeature);
  1019. if(buildingArea){
  1020. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  1021. }
  1022. }
  1023. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金...
  1024. let needFlags = feeFields.map(data => data.k);
  1025. //获取单位工程汇总金额需要用到的所有清单
  1026. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  1027. '-_id projectID fees flags');
  1028. //进行单位工程级别的汇总
  1029. for(let bills of allBills){
  1030. let billsFlag = bills.flags[0]['flag'];
  1031. let costField = flagFieldMapping[billsFlag];
  1032. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  1033. //暂估合价(工程造价暂估合价)
  1034. if (billsFlag === billsFlags.ENGINEERINGCOST){
  1035. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  1036. }
  1037. }
  1038. let summaryFields = feeFields.map(data => data.v);
  1039. summaryFields.push('estimate');
  1040. //进行单项工程级别的汇总
  1041. for(let tender of tenders){
  1042. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID], summaryFields);
  1043. }
  1044. //进行建设项目级别的汇总
  1045. for(let eng of engineerings){
  1046. summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID], summaryFields);
  1047. }
  1048. //占造价比例、单方造价
  1049. const rateDecimal = -2;
  1050. const perCostDecimal = -2;
  1051. for(let tender of tenders){
  1052. let tenderInfo = IDMapping[tender.ID];
  1053. let engInfo = IDMapping[tender.ParentID];
  1054. tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
  1055. //单方造价
  1056. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0
  1057. ? tenderInfo.buildingArea.toString().trim()
  1058. : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  1059. }
  1060. for(let eng of engineerings){
  1061. let engInfo = IDMapping[eng.ID];
  1062. let projInfo = IDMapping[eng.ParentID];
  1063. engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
  1064. }
  1065. //建设项目占造价比例及单方造价
  1066. for(let project of projects){
  1067. let projectInfo = IDMapping[project.ID];
  1068. projectInfo.rate = 100;
  1069. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0
  1070. ? projectInfo.buildingArea.toString().trim()
  1071. : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  1072. }
  1073. }
  1074. return IDMapping;
  1075. }
  1076. //根据项目ID获取所属建设项目
  1077. //@param {Number}projectID @return {Object}
  1078. async function getConstructionProject(projectID){
  1079. function returnProject(project){
  1080. if(!project || project.projType === projectType.folder){
  1081. return null;
  1082. }
  1083. if(project.projType === projectType.project){
  1084. return project;
  1085. }
  1086. }
  1087. let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
  1088. let returnV = returnProject(project);
  1089. if(returnV !== undefined){
  1090. return returnV;
  1091. }
  1092. let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
  1093. returnV = returnProject(parent);
  1094. if(returnV !== undefined){
  1095. return returnV;
  1096. }
  1097. let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
  1098. returnV = returnProject(grandParent);
  1099. return returnV !== undefined ? returnV : null;
  1100. }
  1101. //获取单位工程完整目录结构
  1102. //@param {Number}projectID @return {Arry}
  1103. async function getFullPath(projectID) {
  1104. let fullPath = [];
  1105. let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
  1106. if(project){
  1107. fullPath.push(project.name);
  1108. await getParent(project.ParentID);
  1109. }
  1110. fullPath = fullPath.reverse();
  1111. return fullPath;
  1112. async function getParent(ParentID) {
  1113. if(ParentID != -1){
  1114. let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
  1115. if(parent){
  1116. fullPath.push(parent.name);
  1117. await getParent(parent.ParentID);
  1118. }
  1119. }
  1120. }
  1121. }
  1122. // 获取项目链上,自身、父项、爷爷项...的ID
  1123. async function getUpChainIDs(projectID) {
  1124. const rst = [];
  1125. while (projectID != -1) {
  1126. rst.push(projectID);
  1127. const project = await projectModel.findOne({ ID: projectID }, '-_id ParentID').lean();
  1128. projectID = project ? project.ParentID : -1;
  1129. }
  1130. return rst;
  1131. }
  1132. //获取projectIDs文件下所有子项目(不包括projectIDs本身)
  1133. async function getPosterityProjects(projectIDs) {
  1134. let rst = [];
  1135. async function getProjects(parentIDs) {
  1136. if (parentIDs.length > 0) {
  1137. let newIDs = [];
  1138. let projs = await projectModel.find({ParentID: {$in: parentIDs}, $or: notDeleted}, '-_id').lean();
  1139. for (let proj of projs) {
  1140. // 兼容旧的错误数据,可能ParentID和ID相同
  1141. if (parentIDs.includes(proj.ID)) {
  1142. continue;
  1143. }
  1144. rst.push(proj);
  1145. newIDs.push(proj.ID);
  1146. }
  1147. await getProjects(newIDs);
  1148. }
  1149. }
  1150. await getProjects(projectIDs);
  1151. return rst;
  1152. }
  1153. //根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
  1154. async function getShareInfo(userID, projectID) {
  1155. // 接受到的分享项目
  1156. const upChainIDs = await getUpChainIDs(projectID);
  1157. const shareList = await getShareList({receiver: userID, projectID: {$in: upChainIDs}});
  1158. // 返回最新的分享
  1159. //return shareList.sort((a, b) => Date.parse(b.shareDate) - Date.parse(a.shareDate))[0];
  1160. return shareList.sort((a, b) => Date.parse(b.updateDate) - Date.parse(a.updateDate))[0];
  1161. }
  1162. //打开的单位工程是否是被分享的.
  1163. async function isShare(userId, project){
  1164. //判断是否是打开分享的项目,属于分享文件的子项也算
  1165. while (project) {
  1166. for(let shareData of project.shareInfo){
  1167. if(shareData.userID === userId){
  1168. return true;
  1169. }
  1170. }
  1171. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  1172. }
  1173. return false;
  1174. }
  1175. //用户是否第一次进入费用定额
  1176. async function isFirst(userId, compilationId) {
  1177. let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
  1178. let first = false;
  1179. if (userData) {
  1180. first = !_.find(userData.used_list, function (o) {
  1181. return o.compilationId === compilationId;
  1182. });;
  1183. }
  1184. return first;
  1185. }
  1186. //用户第一次进入费用定额的数据准备
  1187. async function prepareInitialData(userId, compilation, example) {
  1188. let first = await isFirst(userId, compilation);
  1189. if (first) {
  1190. await updateUsedList(userId, compilation);
  1191. let prepareTask = [
  1192. copyCompleRationSection(userId, compilation),
  1193. copyCompleGljSection(userId, compilation)
  1194. ];
  1195. if (example && example.length > 0) {
  1196. prepareTask.push(copyExample(userId, compilation, example));
  1197. }
  1198. await Promise.all(prepareTask);
  1199. }
  1200. }
  1201. async function updateUsedList(userId, compilation) {
  1202. await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
  1203. }
  1204. //拷贝补充定额章节树
  1205. async function copyCompleRationSection(userId, compilationId) {
  1206. await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
  1207. }
  1208. //拷贝补充人材机分类树
  1209. async function copyCompleGljSection(userId, compilationId) {
  1210. let templateData = await compleGljSectionTModel.find({compilationId: compilationId});
  1211. if (templateData.length > 0) {
  1212. let insertDatas = [],
  1213. uuidMapping = {};
  1214. //将ID替换成UUID
  1215. for (let temData of templateData) {
  1216. uuidMapping[temData.ID] = uuidV1();
  1217. }
  1218. for(let temData of templateData) {
  1219. let insertD = {
  1220. userId: userId,
  1221. compilationId: compilationId,
  1222. Name: temData.Name,
  1223. ID: uuidMapping[temData.ID],
  1224. ParentID: uuidMapping[temData.ParentID] || -1,
  1225. NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
  1226. };
  1227. insertDatas.push(insertD);
  1228. }
  1229. //插入数据
  1230. await compleGljSectionModel.insertMany(insertDatas);
  1231. }
  1232. }
  1233. async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件,type从单前建设项目还是从其它建设项目中复制
  1234. let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件,选中多个的时候只需复制一次
  1235. let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
  1236. for(let d of datas){
  1237. let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
  1238. if(type == 1 && tem_file){//从建设项目复制时,只有第一次需要复制,剩下的就相当于使用同个建设项目的情况了
  1239. let newID = from == "feeRateFile"?tem_file.ID:tem_file.id;
  1240. newFile = {id:newID,name:tem_file.name};
  1241. type = 0;
  1242. }
  1243. projectIDs.push({ID:d.projectID})
  1244. }
  1245. await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态
  1246. }
  1247. //获取费用定额绑定的基本信息库数据
  1248. async function getBasicInfo(compilationID, fileKind = null) {
  1249. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(compilationID)});
  1250. if (!compilation) {
  1251. return null;
  1252. }
  1253. let billValuation = compilation.bill_valuation.find(function (data) {
  1254. return data.enable;
  1255. });
  1256. if (!billValuation) {
  1257. return null;
  1258. }
  1259. let engineerings = await engineeringModel.find({valuationID: billValuation.id});
  1260. let engineering = engineerings.find(function (data) {
  1261. return data.info_lib && data.info_lib.length > 0;
  1262. });
  1263. if (!engineering || !engineering.info_lib || !engineering.info_lib[0]) {
  1264. return null;
  1265. }
  1266. let infoLib = await basicInfoModel.findOne({ID: engineering.info_lib[0].id});
  1267. //提取文件类型中需要的数据 (投标项目可能不需要招标的一些信息)
  1268. if (fileKind && infoLib && infoLib.info && infoLib.info.length) {
  1269. let strMap = {
  1270. 1: 'tender', //投标
  1271. 2: 'bid', //招标
  1272. 3: 'control' //控制价
  1273. };
  1274. let needfulData = infoLib.info.filter(data => !data.fileKind || data.fileKind === strMap[fileKind]);
  1275. needfulData.forEach(nData => {
  1276. let needfulSub = nData.items.filter(sData => !sData.fileKind || sData.fileKind === strMap[fileKind]);
  1277. nData.items = needfulSub;
  1278. });
  1279. infoLib.info = needfulData;
  1280. }
  1281. return infoLib;
  1282. }
  1283. async function getProjectFeature(valuationID, engineeringName, feeName) {
  1284. let engineering = await engineeringModel.findOne({valuationID: valuationID, name: engineeringName, feeName: feeName});
  1285. if (!engineering || !engineering.feature_lib || !engineering.feature_lib[0]) {
  1286. return null;
  1287. }
  1288. let featureLib = await projectFeatureModel.findOne({ID: engineering.feature_lib[0].id});
  1289. return featureLib;
  1290. }
  1291. //根据单位工程,获取建设项目-单项工程-单位工程,不包含无单位工程的单项工程
  1292. //@param {Number}tenderID(单位工程ID) {Number}granularity(颗粒度 1:建设项目 2:单项工程 3:单位工程)
  1293. async function getProjectByGranularity(tenderID, granularity, userID, versionName) {
  1294. const GRANULARITY = {
  1295. PROJECT: 1,
  1296. ENGINEERING: 2,
  1297. TENDER: 3
  1298. };
  1299. let theTender = await projectModel.findOne({userID: userID, ID: tenderID}).lean(); //加上session的userID,防止tenderID被篡改过
  1300. if (!theTender) {
  1301. return null;
  1302. }
  1303. let theEngineering = await projectModel.findOne({ID: theTender.ParentID}).lean();
  1304. if (!theEngineering) {
  1305. return null;
  1306. }
  1307. let constructionProject = await projectModel.findOne({ID: theEngineering.ParentID}).lean();
  1308. if (!constructionProject) {
  1309. return null;
  1310. }
  1311. let engineerings;
  1312. if (granularity === GRANULARITY.PROJECT) {
  1313. engineerings = await projectModel.find({ParentID: constructionProject.ID, $or: notDeleted}).lean();
  1314. for (let eng of engineerings) {
  1315. eng.children = await projectModel.find({ParentID: eng.ID, $or: notDeleted}).lean();
  1316. }
  1317. } else {
  1318. engineerings = [theEngineering];
  1319. if (granularity === GRANULARITY.ENGINEERING) {
  1320. theEngineering.children = await projectModel.find({ParentID: theEngineering.ID, $or: notDeleted}).lean();
  1321. } else {
  1322. theEngineering.children = [theTender];
  1323. }
  1324. }
  1325. constructionProject.children = engineerings;
  1326. //获取汇总信息
  1327. let feeFields = [
  1328. {k: billsFlags.ENGINEERINGCOST, v: 'engineeringCost'},
  1329. {k: billsFlags.SUB_ENGINERRING, v: 'subEngineering'},
  1330. {k: billsFlags.MEASURE, v: 'measure'},
  1331. {k: billsFlags.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  1332. {k: billsFlags.OTHER, v: 'other'},
  1333. {k: billsFlags.CHARGE, v: 'charge'},
  1334. {k: billsFlags.PROVISIONAL, v: 'provisional'},
  1335. {k: billsFlags.MATERIAL_PROVISIONAL, v: 'materialProvisional'},
  1336. {k: billsFlags.ENGINEERING_ESITIMATE, v: 'engineeringEstimate'},
  1337. {k: billsFlags.DAYWORK, v: 'daywork'},
  1338. {k: billsFlags.TURN_KEY_CONTRACT, v: 'turnKeyContract'},
  1339. {k: billsFlags.CLAIM_VISA, v: 'claimVisa'},
  1340. {k: billsFlags.TAX, v: 'tax'}
  1341. ];
  1342. constructionProject.summaryInfo = await getSummaryInfo([constructionProject.ID], feeFields);
  1343. //获取编制软件信息: 软件公司;软件名;版本号;授权信息; base64
  1344. let product = await productModel.findOne({});
  1345. let company = product.company || '珠海纵横创新软件有限公司',
  1346. version = product.version || '';
  1347. constructionProject.softInfo = `${company};${versionName};${version};${userID}`;
  1348. return constructionProject;
  1349. }
  1350. //获取项目数据占位ID
  1351. async function getProjectPlaceholder(data) {
  1352. let rst = {};
  1353. //项目本身数据
  1354. if (data.projectCount) {
  1355. let projectCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, data.projectCount);
  1356. rst.project = projectCount.sequence_value - data.projectCount + 1;
  1357. }
  1358. //项目人材机数据
  1359. if (data.projectGLJCount) {
  1360. let projectGLJCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJCount);
  1361. rst.projectGLJ = projectGLJCount.sequence_value - data.projectGLJCount + 1;
  1362. }
  1363. //组成物数据
  1364. if (data.ratioCount) {
  1365. let ratioCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.mix_ratio, data.ratioCount);
  1366. rst.ratio = ratioCount.sequence_value - data.ratioCount + 1;
  1367. }
  1368. //单价文件数据
  1369. if (data.unitPriceFileCount) {
  1370. let unitPriceFileCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price_file, data.unitPriceFileCount);
  1371. rst.unitPriceFile = unitPriceFileCount.sequence_value - data.unitPriceFileCount + 1;
  1372. }
  1373. //单价数据
  1374. if (data.unitPriceCount) {
  1375. let unitPriceCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price, data.unitPriceCount);
  1376. rst.unitPrice = unitPriceCount.sequence_value - data.unitPriceCount + 1;
  1377. }
  1378. return rst;
  1379. }
  1380. /*
  1381. * 接口导入 项目详细数据都导入完成了,再生成项目数据(项目管理界面数据)
  1382. * */
  1383. async function importProject(importObj, userID, compilationID) {
  1384. let toInsertProjects = [importObj]; //待新增项目数据
  1385. await setupProject(importObj);
  1386. //设置项目ID及相关数据
  1387. for (let curEng of importObj.engs) {
  1388. await setupProject(curEng);
  1389. toInsertProjects.push(curEng);
  1390. for (let curTender of curEng.tenders) {
  1391. await setupProject(curTender.tender);
  1392. //插入单位工程的详细数据
  1393. await importTenderDetail(curTender);
  1394. toInsertProjects.push(curTender.tender);
  1395. }
  1396. delete curEng.tenders;
  1397. }
  1398. delete importObj.engs;
  1399. //项目内部数据设置、新增完毕后,插入项目本身的数据,更新前节点数据
  1400. let bulks = [];
  1401. //如果有前节点,更新前节点
  1402. if (importObj.preID !== -1) {
  1403. bulks.push({
  1404. updateOne: {filter: {ID: importObj.preID}, update: {$set: {NextSiblingID: importObj.ID}}}
  1405. });
  1406. }
  1407. for (let insertP of toInsertProjects) {
  1408. bulks.push({
  1409. insertOne: {document: insertP}
  1410. });
  1411. }
  1412. if (bulks.length > 0) {
  1413. await projectModel.bulkWrite(bulks);
  1414. }
  1415. let summaryInfo = await getSummaryInfo([importObj.ID]);
  1416. //设置汇总字段
  1417. for(let proj of toInsertProjects){
  1418. let summaryProj = summaryInfo[proj.ID];
  1419. if(summaryProj){
  1420. proj.engineeringCost = summaryProj.engineeringCost;
  1421. proj.subEngineering = summaryProj.subEngineering;
  1422. proj.measure = summaryProj.measure;
  1423. proj.safetyConstruction = summaryProj.safetyConstruction;
  1424. proj.other = summaryProj.other;
  1425. proj.charge = summaryProj.charge;
  1426. proj.tax = summaryProj.tax;
  1427. proj.rate = summaryProj.rate;
  1428. proj.buildingArea = summaryProj.buildingArea;
  1429. proj.perCost = summaryProj.perCost;
  1430. }
  1431. }
  1432. return toInsertProjects;
  1433. //给项目数据设置一些需要的数据
  1434. async function setupProject(data) {
  1435. data.userID = userID;
  1436. data.compilation = compilationID;
  1437. data.fileVer = G_FILE_VER;
  1438. data.createDateTime = new Date();
  1439. if (data.projType === 'Project') {
  1440. await setupConstruct(data);
  1441. } else if (data.projType === 'Tender') {
  1442. await setupTender(data);
  1443. }
  1444. }
  1445. //给建设项目设置一些数据
  1446. async function setupConstruct(data) {
  1447. //更新基本信息, 按照key匹配
  1448. let infoLib = await getBasicInfo(data.compilation, data.property.fileKind);
  1449. if (infoLib) {
  1450. //标准基本信息库的数据打平
  1451. let flatDatas = [];
  1452. infoLib.info.forEach(ifData => flatDatas.push(...ifData.items));
  1453. data.basicInformation.forEach(importI => {
  1454. flatDatas.forEach(item => {
  1455. if (item.key === 'engineeringName') {
  1456. item.value = data.name;
  1457. } else if (item.key === 'fileKind') {
  1458. item.value = {'1': '投标', '2': '招标'}[data.property.fileKind]
  1459. } else if (item.key === 'taxModel') {
  1460. item.value = {'1': '一般计税法', '2': '简易计税法'}[data.property.taxType]
  1461. }
  1462. if (item.key === importI.key) {
  1463. item.value = importI.value;
  1464. }
  1465. });
  1466. });
  1467. }
  1468. data.property.basicInformation = infoLib ? infoLib.info : [];
  1469. }
  1470. //给单位工程设置一些数据
  1471. async function setupTender(data) {
  1472. //小数位数 需要修改,所以深拷贝
  1473. data.property.decimal = JSON.parse(JSON.stringify(defaultDecimal));
  1474. // 定额工程量、人材机消耗量精度设为最大6
  1475. data.property.decimal.ration.quantity = 6;
  1476. data.property.decimal.glj.quantity = 6;
  1477. //清单工程量精度 需要修改,所以深拷贝
  1478. data.property.billsQuantityDecimal = JSON.parse(JSON.stringify(billsQuantityDecimal));
  1479. // 清单工程量精度设置最大4
  1480. data.property.billsQuantityDecimal.forEach(data => data.decimal = 4);
  1481. //呈现选项
  1482. data.property.displaySetting = displaySetting;
  1483. data.property.billsCalcMode = 0;
  1484. data.property.zanguCalcMode = 0;
  1485. //计算选项
  1486. data.property.calcOptions = calcOptions;
  1487. //安装增加费
  1488. if(data.property.isInstall === true || data.property.isInstall === 'true'){//判断是否安装工程
  1489. await installationFacade.copyInstallationFeeFromLib(data.ID, data.property.engineering_id);
  1490. }
  1491. //锁定清单
  1492. data.property.lockBills = true;
  1493. //工料机单价调整系数
  1494. data.property.tenderSetting = tenderSetting;
  1495. //工程特征相关更新
  1496. let featureLib = await getProjectFeature(data.property.valuation, data.property.engineeringName, data.property.feeStandardName);
  1497. if (featureLib) {
  1498. //把导入的数据设置到默认生成的数据中,按名称匹配 (导入项不确定,因此无法确定获取项的key)
  1499. data.projectFeature.forEach(importF => {
  1500. let matchData = featureLib.feature.find(f => f.dispName === importF.name);
  1501. if (matchData) {
  1502. matchData.value = importF.value;
  1503. }
  1504. });
  1505. //设置工程专业的值为费用标准的值..
  1506. featureLib.feature.forEach(f => {
  1507. if (f.key === 'engineering') {
  1508. f.value = data.property.feeStandardName;
  1509. }
  1510. });
  1511. }
  1512. data.property.projectFeature = featureLib ? featureLib.feature : [];
  1513. // 指标信息相关设置
  1514. await project_facade.setSEILibData(data.property);
  1515. }
  1516. }
  1517. //插入单位工程内部详细数据
  1518. async function importTenderDetail(tenderData) {
  1519. //单价文件
  1520. let upFile = {
  1521. id: tenderData.tender.property.unitPriceFile.id,
  1522. name: tenderData.tender.name,
  1523. project_id: tenderData.tender.ID,
  1524. user_id: tenderData.tender.userID,
  1525. root_project_id: tenderData.tender.property.rootProjectID
  1526. };
  1527. await unitPriceFileModel.create(upFile);
  1528. //费率文件
  1529. let feeRateFileID = await feeRate_facade.newFeeRateFile(tenderData.tender.userID, tenderData.tender);
  1530. tenderData.tender.property.feeFile = feeRateFileID ? feeRateFileID : -1;
  1531. //人工系数文件
  1532. let lcFile = await labourCoeFacade.newProjectLabourCoe(tenderData.tender);
  1533. tenderData.tender.property.labourCoeFile = lcFile ? lcFile : null;
  1534. let cpFile = await calcProgramFacade.newProjectCalcProgramFile(tenderData.tender);
  1535. tenderData.tender.property.calcProgramFile = cpFile ? cpFile : null;
  1536. //列设置
  1537. let engineeringModel = new EngineeringLibModel();
  1538. let engineering = await engineeringModel.getEngineering(tenderData.tender.property.engineering_id);
  1539. let mainTreeCol = await mainColLibModel.findOne({ID: tenderData.tender.property.colLibID});
  1540. await projectSettingModel.create({projectID: tenderData.tender.ID, main_tree_col: mainTreeCol.main_tree_col, glj_col: engineering.glj_col});
  1541. //清单
  1542. if (tenderData.bills.length) {
  1543. await billsModel.insertMany(tenderData.bills);
  1544. }
  1545. //投标文件中,才会有下面这些数据
  1546. if (enterDetail(tenderData)) {
  1547. //匹配标准数据,更新一些标准数据
  1548. await setupStdData(tenderData);
  1549. let task = [];
  1550. //定额
  1551. if (tenderData.ration.length) {
  1552. task.push(rationModel.insertMany(tenderData.ration))
  1553. }
  1554. //定额人材机
  1555. if (tenderData.rationGLJ.length) {
  1556. task.push(rationGLJModel.insertMany(tenderData.rationGLJ));
  1557. }
  1558. //定额调整系数
  1559. if (tenderData.rationCoe.length) {
  1560. task.push(rationCoeModel.insertMany(tenderData.rationCoe));
  1561. }
  1562. //项目人材机
  1563. if (tenderData.projectGLJ.length) {
  1564. task.push(gljListModel.insertMany(tenderData.projectGLJ));
  1565. }
  1566. // 承包人材料
  1567. if (tenderData.contractorList.length) {
  1568. task.push(contractorListModel.insertMany(tenderData.contractorList));
  1569. }
  1570. // 评标材料表
  1571. if (tenderData.bidEvaluationList.length) {
  1572. task.push(bidListModel.insertMany(tenderData.bidEvaluationList));
  1573. }
  1574. // 暂估价材料表
  1575. if (tenderData.evaluationList.length) {
  1576. task.push(evaluateListModel.insertMany(tenderData.evaluationList));
  1577. }
  1578. //组成物
  1579. if (tenderData.mixRatio.length) {
  1580. task.push(mixRatioModel.insertMany(tenderData.mixRatio));
  1581. }
  1582. //单价文件
  1583. if (tenderData.unitPrice.length) {
  1584. task.push(unitPriceModel.insertMany(tenderData.unitPrice));
  1585. }
  1586. await Promise.all(task);
  1587. }
  1588. //继续处理定额等数据
  1589. function enterDetail(tenderData) {
  1590. return tenderData.ration.length ||
  1591. tenderData.rationGLJ.length ||
  1592. tenderData.projectGLJ.length ||
  1593. tenderData.mixRatio.length ||
  1594. tenderData.unitPrice.length;
  1595. }
  1596. }
  1597. //匹配标准数据,需要匹配标准定额,更新导入的定额人材机的定额消耗量等数据
  1598. async function setupStdData(tenderData) {
  1599. //获取标准定额数据 (定额子目的编码查找)
  1600. let matchRationCodes = [...new Set(tenderData.ration.map(ration => ration.code))];
  1601. if (!matchRationCodes.length) {
  1602. return;
  1603. }
  1604. //限制在当前费用定额可用的定额库里查找
  1605. let stdRations = await stdRationItemModel.find({code: {$in: matchRationCodes}, rationRepId: {$in: tenderData.tender.rationLibIDs}},
  1606. '-_id -rationAssList -rationCoeList -rationInstList');
  1607. //标准定额code - 映射
  1608. let stdRationCodeMap = {};
  1609. stdRations.forEach(stdRation => stdRationCodeMap[stdRation.code] = stdRation);
  1610. //获取标准人材机数据 (人材机汇总的编码查找)
  1611. let matchGLJCodes = [...new Set(tenderData.projectGLJ.map(pGLJ => pGLJ.original_code))];
  1612. if (!matchGLJCodes.length) {
  1613. return;
  1614. }
  1615. //限制在当前费用定额可用的人材机库里查找
  1616. let stdGLJs = await stdGljItemModel.find({code: {$in: matchGLJCodes}, repositoryId: {$in: tenderData.tender.gljLibIDs}},
  1617. '-_id -component -priceProperty');
  1618. //标准人材机code - 映射
  1619. let stdGLJCodeMap = {};
  1620. stdGLJs.forEach(stdGLJ => stdGLJCodeMap[stdGLJ.code] = stdGLJ);
  1621. //更新定额数据
  1622. tenderData.ration.forEach(r => {
  1623. let stdRation = stdRationCodeMap[r.code];
  1624. if (stdRation) {
  1625. r.caption = stdRation.caption;
  1626. r.from = 'std';
  1627. r.libID = stdRation.rationRepId;
  1628. r.stdID = stdRation.ID;
  1629. r.prefix = stdRation.rationRepId == tenderData.tender.defaultRationLib ? '' : '借';
  1630. r.content = stdRation.jobContent;
  1631. if (stdRation.feeType) {
  1632. r.programID = stdRation.feeType;
  1633. } else {
  1634. // 是标准定额,但是该标准定额取费专业为空,取定额取费专业(后台配置项)
  1635. r.programID = tenderData.tender.property.engineering;
  1636. }
  1637. } else {
  1638. r.from = 'cpt';
  1639. r.prefix = '补';
  1640. }
  1641. });
  1642. //更新定额人材机数据
  1643. tenderData.rationGLJ.forEach(rGLJ => {
  1644. rGLJ.from = 'cpt';
  1645. //匹配定额
  1646. let stdRation = stdRationCodeMap[rGLJ.rationCode];
  1647. if (stdRation) {
  1648. //根据导入数据的定额人材机编码匹配人材机
  1649. let stdGLJ = stdGLJCodeMap[rGLJ.original_code];
  1650. if (stdGLJ) {
  1651. rGLJ.from = 'std';
  1652. rGLJ.GLJID = stdGLJ.ID;
  1653. rGLJ.type = stdGLJ.gljType;
  1654. rGLJ.shortName = stdGLJ.shortName;
  1655. rGLJ.repositoryId = stdGLJ.repositoryId;
  1656. rGLJ.model = stdGLJ.model;
  1657. rGLJ.adjCoe = stdGLJ.adjCoe;
  1658. //找匹配到的标准定额中定额人材机的相应人材机,更新定额消耗
  1659. let stdRationGLJ = stdRation.rationGljList.find(data => data.gljId === stdGLJ.ID);
  1660. if (stdRationGLJ) {
  1661. rGLJ.rationItemQuantity = stdRationGLJ.consumeAmt;
  1662. }
  1663. }
  1664. }
  1665. });
  1666. //更新人材机汇总数据
  1667. tenderData.projectGLJ.forEach(pGLJ => {
  1668. if (!pGLJ.specs) {
  1669. pGLJ.specs = null;
  1670. }
  1671. let stdGLJ = stdGLJCodeMap[pGLJ.original_code];
  1672. if (stdGLJ) {
  1673. pGLJ.glj_id = stdGLJ.ID;
  1674. pGLJ.model = stdGLJ.model;
  1675. if (pGLJ.type !== stdGLJ.gljType) { //更新组成物connect_key
  1676. let keyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', pGLJ.type].join('|-|');
  1677. let ratios = tenderData.mixRatio.filter(ratio =>
  1678. ratio.connect_key === keyStr);
  1679. let newKeyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', stdGLJ.gljType || 'null'].join('|-|');
  1680. ratios.forEach(ratio => ratio.connect_key = newKeyStr);
  1681. }
  1682. pGLJ.type = stdGLJ.gljType; //更新类型,标准的数据类型更准确,导入的类型数据有细分识别不了
  1683. }
  1684. });
  1685. //更新单价文件数据
  1686. tenderData.unitPrice.forEach(up => {
  1687. let stdGLJ = stdGLJCodeMap[up.original_code];
  1688. if (stdGLJ) {
  1689. up.glj_id = stdGLJ.ID;
  1690. up.type = stdGLJ.gljType;
  1691. up.short_name = stdGLJ.shortName;
  1692. }
  1693. });
  1694. //更新组成物数据
  1695. tenderData.mixRatio.forEach(ratio => {
  1696. let stdGLJ = stdGLJCodeMap[ratio.code];
  1697. if (stdGLJ) {
  1698. ratio.glj_id = stdGLJ.ID;
  1699. ratio.type = stdGLJ.gljType;
  1700. }
  1701. });
  1702. }
  1703. async function exportProject(userID,data){//导出建设项目
  1704. if(data.type == 'main'){
  1705. return await exportMainData(userID,data.projectID);
  1706. }else {
  1707. return await exportTenderData(data);
  1708. }
  1709. }
  1710. async function exportMainData(userID,projectID) {
  1711. let result = {userID:userID,projects:[],type:'Project'};//type 备用属性,表示导出的类型,目前导出的都是整个建设项目
  1712. let tenderIDs = [];
  1713. let project = await projectModel.findOne({ID:projectID});
  1714. if(!project) throw new Error("没有找到该建设项目:"+projectID);
  1715. result['compilationID'] = project.compilation;
  1716. result['from'] = "construction";
  1717. result.projects.push(project);
  1718. let subProjects = await projectModel.find({"$or": [{'ParentID':projectID}, {"property.rootProjectID": projectID}]});
  1719. for(let s of subProjects){
  1720. if(!s.deleteInfo || !s.deleteInfo.deleted){
  1721. result.projects.push(s);
  1722. if(s.projType =="Tender") tenderIDs.push(s.ID);
  1723. }
  1724. }
  1725. let files = {unitFiles:await exportUnitFiles(projectID),feeRateFiles:await exportFeeRateFiles(projectID)};
  1726. result.files = files;
  1727. result = cipher.aesEncrypt(JSON.stringify(result));
  1728. result +="|----|" +JSON.stringify(tenderIDs);
  1729. return result;
  1730. }
  1731. async function exportUnitFiles(rootProjectID){
  1732. let unitFiles = [];
  1733. let files = await unitPriceFileModel.find({root_project_id:rootProjectID});
  1734. for(let f of files){
  1735. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1736. let tem = {unitFile:f};
  1737. tem.unitPrices = await unitPriceModel.find({unit_price_file_id:f.id});
  1738. tem.mixRatios = await mixRatioModel.find({unit_price_file_id:f.id});
  1739. unitFiles.push(tem);
  1740. }
  1741. return unitFiles;
  1742. }
  1743. async function exportFeeRateFiles(rootProjectID) {
  1744. let feeRateFiles = [];
  1745. let files = await feeRateFileModel.find({rootProjectID:rootProjectID});
  1746. for(let f of files){
  1747. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1748. let tem = {feeRateFile:f};
  1749. tem.feeRate = await feeRateModel.findOne({ID:f.feeRateID});
  1750. feeRateFiles.push(tem);
  1751. }
  1752. return feeRateFiles;
  1753. }
  1754. async function exportTenderData(data){
  1755. let result = {};
  1756. let projectSetting = await projectSettingModel.findOne({"projectID": data.projectID}, '-_id');
  1757. if(projectSetting) result['projSetting'] = projectSetting;
  1758. result.bills = await billsModel.find({"projectID": data.projectID});
  1759. result.rations = await rationModel.find({'$or': [{projectID: data.projectID, deleteInfo: null}, {projectID: data.projectID, 'deleteInfo.deleted': {$in: [null, false]}}]});
  1760. result.projectGLJs = await gljListModel.find({'project_id':data.projectID});
  1761. result.installationFees = await installationFeeModel.find({projectID:data.projectID});
  1762. result.rationGLJs = await rationGLJModel.find({projectID:data.projectID});
  1763. result.rationCoes = await rationCoeModel.find({projectID:data.projectID});
  1764. result.quantityDetails = await quantityDetailModel.find({projectID:data.projectID});
  1765. result.rationInstallations = await rationInstallationModel.find({projectID:data.projectID});
  1766. result.rationTemplates = await rationTemplateModel.find({projectID:data.projectID});
  1767. result.calcProgramsFile = await calcProgramsModel.findOne({projectID:data.projectID});
  1768. result.labourCoes = await labourCoesModel.findOne({projectID:data.projectID});
  1769. result.evaluateList = await evaluateListModel.find({projectID:data.projectID}, '-_id').lean();
  1770. result.bidList = await bidListModel.find({projectID:data.projectID}, '-_id').lean();
  1771. result.contractorList = await contractorListModel.find({projectID:data.projectID}, '-_id').lean();
  1772. return cipher.aesEncrypt(JSON.stringify(result));
  1773. }
  1774. async function downLoadProjectFile(info) {
  1775. let result = {error:0};
  1776. let bucketManager2 = new qiniu.rs.BucketManager(mac, null);
  1777. let publicBucketDomain = qiniu_config.Domain;// "http://serverupdate.smartcost.com.cn";//这里不支持https
  1778. let deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
  1779. let privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, info.key, deadline);
  1780. console.log(privateDownloadUrl);
  1781. let data = {
  1782. key:info.key,
  1783. userID:info.session.sessionUser.id,
  1784. status:"start",
  1785. create_time:+new Date()
  1786. };
  1787. await importLogsModel.create(data);
  1788. doDownLoadAndImport(privateDownloadUrl,info);
  1789. return result;
  1790. }
  1791. async function doDownLoadAndImport(privateDownloadUrl,info) {
  1792. let stream = fs.createWriteStream(path.join(__dirname, "../../../tmp/"+info.key));//
  1793. request(privateDownloadUrl).pipe(stream).on("close", async function (err) {
  1794. console.log("文件[" + info.key + "]下载完毕");
  1795. let doc = {status:"finish"};
  1796. try {
  1797. let data = fs.readFileSync(stream.path,'utf-8');
  1798. let result = await importProjects(data,{session:info.session},info.updateData);
  1799. if(result.error == 1){
  1800. doc.errorMsg = result.msg;
  1801. doc.status = "error";
  1802. }
  1803. }catch (error){
  1804. console.log(error);
  1805. doc.errorMsg = "导入失败,请检查文件!";
  1806. doc.status = "error";
  1807. }finally {
  1808. await importLogsModel.update({key:info.key},doc);
  1809. fs.unlinkSync(stream.path);
  1810. }
  1811. });
  1812. }
  1813. async function importProcessChecking(data){
  1814. let result = {error:0};
  1815. let log = await importLogsModel.findOne({key:data.key});
  1816. if(log){
  1817. if(log.status == "finish"){
  1818. result.status = "complete";
  1819. await importLogsModel.remove({key:data.key});
  1820. }else if(log.status == "start"){
  1821. result.status = "processing";
  1822. }else if(log.status == "error"){
  1823. result.error = 1;
  1824. result.msg = log.errorMsg;
  1825. await importLogsModel.remove({key:data.key});
  1826. }
  1827. }else {
  1828. result.error = 1;
  1829. result.msg = `导入过程中发生错误!`;
  1830. }
  1831. return result;
  1832. }
  1833. // 从cdn服务器下载文件,key就是文件名
  1834. async function downloadFileSync(key) {
  1835. const filePath = path.join(__dirname, '../../../tmp/', key);
  1836. const bucketManager2 = new qiniu.rs.BucketManager(mac, null);
  1837. const publicBucketDomain = qiniu_config.Domain; // "http://serverupdate.smartcost.com.cn";//这里不支持https
  1838. const deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
  1839. const privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, key, deadline);
  1840. const stream = fs.createWriteStream(filePath);
  1841. return new Promise((resolve, reject) => {
  1842. request(privateDownloadUrl)
  1843. .pipe(stream)
  1844. .on('close', () => {
  1845. // 读取文件返回字符串
  1846. const srcData = fs.readFileSync(stream.path,'utf-8');
  1847. resolve({
  1848. path: stream.path,
  1849. srcData: srcData
  1850. });
  1851. })
  1852. .on('error', reject);
  1853. });
  1854. }
  1855. // 导入接口
  1856. async function importInterface(key, session) {
  1857. // 源文件内容文本
  1858. let downloadFilePath = '';
  1859. try {
  1860. const { path, srcData } = await downloadFileSync(key);
  1861. downloadFilePath = path;
  1862. if (!srcData) {
  1863. throw '无有效数据';
  1864. }
  1865. const userID = session.sessionUser.id;
  1866. const compilationID = session.sessionCompilation._id;
  1867. const importData = JSON.parse(srcData);
  1868. let tenderCount = 0;
  1869. importData.engs.forEach(eng => {
  1870. eng.tenders.forEach(tender => {
  1871. tenderCount += 1;
  1872. });
  1873. });
  1874. if (await isTenderOverrun(tenderCount, session)) {
  1875. throw '您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。';
  1876. }
  1877. const projectData = await importProject(importData, userID, compilationID);
  1878. return projectData;
  1879. } catch (err) {
  1880. throw err;
  1881. } finally {
  1882. fs.unlinkSync(downloadFilePath);
  1883. }
  1884. }
  1885. async function importProjects(data,req,updateData) {
  1886. let result = {error:0};
  1887. let stringArr = data.split("|----|");
  1888. let datas = [];
  1889. for(let s of stringArr){
  1890. datas.push(JSON.parse(cipher.aesDecrypt(s)));
  1891. }
  1892. let mainData = datas.length > 0 ?datas[0]:null;
  1893. if(mainData){
  1894. if(mainData.from && mainData.from != "construction"){
  1895. result.error = 1;
  1896. result.msg = "导入失败:您要导入的文件是由“纵横公路养护云版”导出,当前软件是“大司空云计价”,请选择正确的软件再进行操作!";
  1897. }else if(mainData.compilationID != req.session.sessionCompilation._id){
  1898. const fileCompilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(mainData.compilationID)}, 'name');
  1899. const fileCompilationName = fileCompilation ? fileCompilation.name : '未知的费用定额';
  1900. const curCompilationName = req.session.sessionCompilation.name;
  1901. result.error = 1;
  1902. result.msg = `导入失败:您要导入的文件是由“${fileCompilationName}”导出,当前软件是“${curCompilationName}”,请选择正确的费用定额再进行操作!`;
  1903. }else {
  1904. const tenders = mainData.projects.filter(item => item.projType === projectType.tender);
  1905. const tenderOverrun = await isTenderOverrun(tenders.length, req.session);
  1906. if (tenderOverrun) {
  1907. result.error = 1;
  1908. result.msg = `您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。`;
  1909. }
  1910. let [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,updateData,req.session.sessionUser.id);
  1911. if(datas.length > 1 ){
  1912. for(let i = 1;i<datas.length;i++){
  1913. await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
  1914. }
  1915. }
  1916. }
  1917. }
  1918. return result;
  1919. }
  1920. async function handleEachProject(data,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap){
  1921. let bills = [],rations = [],projectGLJs = [],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[],evaluateList=[],bidList=[],contractorList=[];
  1922. let newProjectSetting =null,newCalcProgramsFile = null,newLabourCoe = null;
  1923. let billsIDMap = {},projectGLJIDMap={},rationIDMap = {};
  1924. let newProjectID = projectIDMap[data.projSetting.projectID];
  1925. //生成新的清单;
  1926. if(data.bills && data.bills.length > 0){
  1927. for(let b of data.bills){
  1928. billsIDMap[b.ID] = uuidV1();
  1929. }
  1930. for(let b of data.bills){
  1931. delete b._id;
  1932. b = getCopyBillDatas(b,newProjectID,billsIDMap);
  1933. bills.push(b);
  1934. }
  1935. }
  1936. //生成项目工料机数据
  1937. if(data.projectGLJs && data.projectGLJs.length > 0){
  1938. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJs.length);
  1939. for(let i = 0; i < data.projectGLJs.length; i++){
  1940. let d = data.projectGLJs[i];
  1941. delete d._id;
  1942. let newID = gljCount.sequence_value - (data.projectGLJs.length - 1) + i;
  1943. projectGLJIDMap[d.id] = newID;
  1944. d.project_id = newProjectID;
  1945. d.id = newID;
  1946. projectGLJs.push(d);
  1947. }
  1948. }
  1949. //生成新的定额
  1950. if(data.rations && data.rations.length > 0){
  1951. for(let r of data.rations){
  1952. rationIDMap[r.ID] = uuidV1();
  1953. }
  1954. for(let r of data.rations){
  1955. delete r._id;
  1956. r = getCopyRationData(r,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1957. rations.push(r);
  1958. }
  1959. }
  1960. //生成定额下挂的定额工料机等等数据
  1961. if(data.rationGLJs && data.rationGLJs.length > 0) rationGLJs = setRationSubList(data.rationGLJs,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1962. if(data.rationCoes && data.rationCoes.length > 0) rationCoes = setRationSubList(data.rationCoes,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1963. if(data.quantityDetails && data.quantityDetails.length > 0) quantityDetails = setRationSubList(data.quantityDetails,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1964. if(data.rationInstallations && data.rationInstallations.length > 0) rationInstallations = setRationSubList(data.rationInstallations,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1965. if(data.rationTemplates && data.rationTemplates.length > 0) rationTemplates = setRationSubList(data.rationTemplates,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1966. if(data.evaluateList && data.evaluateList.length > 0) evaluateList = setMaterialList(data.evaluateList,newProjectID,projectGLJIDMap);
  1967. if(data.bidList && data.bidList.length > 0) bidList = setMaterialList(data.bidList,newProjectID,projectGLJIDMap);
  1968. if(data.contractorList && data.contractorList.length > 0) contractorList = setMaterialList(data.contractorList,newProjectID,projectGLJIDMap);
  1969. //生成projectSetting 文件
  1970. if(data.projSetting){
  1971. data.projSetting.projectID =newProjectID;
  1972. newProjectSetting = data.projSetting;
  1973. delete newProjectSetting._id;
  1974. }
  1975. //生成计算程序文件,系数文件
  1976. if(data.calcProgramsFile && calcProgramFileIDMap[data.calcProgramsFile.ID]){
  1977. data.calcProgramsFile.ID = calcProgramFileIDMap[data.calcProgramsFile.ID];
  1978. data.calcProgramsFile.projectID = newProjectID;
  1979. newCalcProgramsFile = data.calcProgramsFile;
  1980. delete newCalcProgramsFile._id;
  1981. }
  1982. if(data.labourCoes && labourCoeFileIDMap[data.labourCoes.ID]){
  1983. data.labourCoes.ID = labourCoeFileIDMap[data.labourCoes.ID];
  1984. data.labourCoes.projectID = newProjectID;
  1985. newLabourCoe = data.labourCoes;
  1986. delete newLabourCoe._id;
  1987. }
  1988. if(newProjectSetting) await projectSettingModel.create(newProjectSetting);
  1989. if(bills.length > 0) await insertMany(bills,billsModel);
  1990. if(rations.length > 0) await insertMany(rations,rationModel);
  1991. if(projectGLJs.length > 0) await insertMany(projectGLJs,gljListModel);
  1992. if(rationGLJs.length > 0) await insertMany(rationGLJs,rationGLJModel);
  1993. if(rationCoes.length > 0) await insertMany(rationCoes,rationCoeModel);
  1994. if(quantityDetails.length > 0) await insertMany(quantityDetails,quantityDetailModel);
  1995. if(rationInstallations.length > 0) await insertMany(rationInstallations,rationInstallationModel);
  1996. if(rationTemplates.length > 0) await insertMany(rationTemplates,rationTemplateModel);
  1997. if(evaluateList.length > 0) await insertMany(evaluateList,evaluateListModel);
  1998. if(bidList.length > 0) await insertMany(bidList,bidListModel);
  1999. if(contractorList.length > 0) await insertMany(contractorList,contractorListModel);
  2000. if(newCalcProgramsFile) await calcProgramsModel.create(newCalcProgramsFile);
  2001. if(newLabourCoe) await labourCoesModel.create(newLabourCoe);
  2002. }
  2003. function setMaterialList(datas,newProjectID,projectGLJIDMap){
  2004. let arrs = [];
  2005. for(let d of datas){
  2006. arrs.push(getNewMaterial(d,newProjectID,projectGLJIDMap))
  2007. }
  2008. return arrs
  2009. }
  2010. function setRationSubList(datas,newProjectID,billIDMap,rationIDMap,projectGLJIDMap) {
  2011. let arrs = [];
  2012. for(let d of datas){
  2013. delete d._id;
  2014. d = getCopyRationSubData(d,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  2015. arrs.push(d);
  2016. }
  2017. return arrs;
  2018. }
  2019. async function handleMainProjectDatas(mainData,updateData,userID) {
  2020. let mainProjectID = -1;
  2021. let projectIDMap = {},feeRateFileIDMap={},unitPriceFileIDMap={},labourCoeFileIDMap={},calcProgramFileIDMap={};
  2022. let tasks = [];
  2023. projectIDMap[-1] = -1;//最后一个项目的nextID为-1的情况
  2024. //生成新的projectID
  2025. for(let p of mainData.projects){
  2026. let newProjectID = await getCounterID("projects");
  2027. projectIDMap[p.ID] = newProjectID;
  2028. if(p.projType == "Project") mainProjectID = newProjectID;
  2029. if(p.projType == "Tender"){
  2030. if(p.property.calcProgramFile) calcProgramFileIDMap[p.property.calcProgramFile.ID] = uuidV1();//新的计算程序文件ID
  2031. if(p.property.labourCoeFile) labourCoeFileIDMap[p.property.labourCoeFile.ID] = uuidV1();//新的人工调整系数文件ID
  2032. if(p.property.feeFile) feeRateFileIDMap[p.property.feeFile.id] = uuidV1();//新的费率文件ID
  2033. if(p.property.unitPriceFile) unitPriceFileIDMap[p.property.unitPriceFile.id] = await getCounterID("unit_price_file");//新的单价文件ID
  2034. }
  2035. }
  2036. if(mainProjectID == -1) throw new Error("文件里面没包含建设项目信息!");
  2037. //处理项目信息 ----- 费率文件,单价文件ID信息要重新生成----to do
  2038. for(let p of mainData.projects){
  2039. delete p._id;
  2040. delete p.__v;
  2041. p.ID = projectIDMap[p.ID];
  2042. if(p.ID == mainProjectID){//对于建设项目,要父和下一节点ID要使用前端传入的位置ID
  2043. p.ParentID = updateData.self.ParentID;
  2044. p.NextSiblingID = updateData.self.NextSiblingID;
  2045. if(updateData.update){//树节构中的上一节点的下一节点设置为本建设项目ID;
  2046. tasks.push({updateOne:{filter : updateData.update.query, update : {NextSiblingID:mainProjectID}}});
  2047. }
  2048. //查看是否重名;
  2049. let temp = await projectModel.findOne({userID:userID,ParentID:p.ParentID,name:p.name});
  2050. if(temp) p.name = p.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '导入)';
  2051. }else {
  2052. p.ParentID = projectIDMap[p.ParentID];
  2053. p.NextSiblingID = projectIDMap[p.NextSiblingID];
  2054. }
  2055. p.userID =userID;
  2056. p.shareInfo=[];
  2057. if(p.projType == "Tender"){
  2058. if(p.property.calcProgramFile) p.property.calcProgramFile.ID = calcProgramFileIDMap[p.property.calcProgramFile.ID];
  2059. if(p.property.labourCoeFile) p.property.labourCoeFile.ID = labourCoeFileIDMap[p.property.labourCoeFile.ID];
  2060. if(p.property.feeFile) p.property.feeFile.id = feeRateFileIDMap[p.property.feeFile.id];
  2061. if(p.property.unitPriceFile) p.property.unitPriceFile.id = unitPriceFileIDMap[p.property.unitPriceFile.id];
  2062. p.property.rootProjectID = mainProjectID
  2063. }
  2064. tasks.push({insertOne: {document: p}})
  2065. }
  2066. //项目树节构数据生成:
  2067. await projectModel.bulkWrite(tasks);
  2068. //生成所有的费率文件
  2069. await importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID);
  2070. //生成所有的单价文件
  2071. await importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID);
  2072. return [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap]
  2073. }
  2074. async function importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID) {
  2075. if(!mainData.files.unitFiles) return;
  2076. let unitFiles = [],unitPrices =[],mixRatios=[],freights=[],originals=[];
  2077. for(let f of mainData.files.unitFiles){
  2078. let file = f.unitFile,prices = f.unitPrices,mixs = f.mixRatios,fres = f.freights,ors = f.originals;
  2079. //生成单价文件
  2080. delete file._id;
  2081. file.id = unitPriceFileIDMap[file.id]?unitPriceFileIDMap[file.id]:await getCounterID("unit_price_file");
  2082. file.project_id = projectIDMap[file.project_id];
  2083. file.root_project_id = projectIDMap[file.root_project_id];
  2084. file.user_id = userID;
  2085. unitFiles.push(file);
  2086. //生成子数据
  2087. if(prices) await setSubList(prices,unitPrices,file.id,unitPriceModel);
  2088. if(mixs) await setSubList(mixs,mixRatios,file.id,mixRatioModel);
  2089. }
  2090. if(unitFiles.length > 0) await insertMany(unitFiles,unitPriceFileModel);
  2091. if(unitPrices.length > 0) await insertMany(unitPrices,unitPriceModel);
  2092. if(mixRatios.length > 0) await insertMany(mixRatios,mixRatioModel);
  2093. async function setSubList(oList,nList,fileID,model,UUID=false) {
  2094. for(let o of oList){
  2095. delete o._id;
  2096. o.unit_price_file_id = fileID;
  2097. UUID == true?o.ID = uuidV1():o.id = await getCounterID(model.modelName);
  2098. nList.push(o)
  2099. }
  2100. }
  2101. }
  2102. async function importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID) {
  2103. let feeRateFiles = [], feeRates = [];
  2104. if(!mainData.files.feeRateFiles) return;
  2105. for(let f of mainData.files.feeRateFiles){
  2106. //生成费率记录
  2107. let rate = f.feeRate;
  2108. delete rate._id;
  2109. rate.ID = uuidV1();
  2110. feeRates.push(rate);
  2111. //生成费率文件记录
  2112. let file = f.feeRateFile;
  2113. delete file._id;
  2114. file.ID = feeRateFileIDMap[file.ID]?feeRateFileIDMap[file.ID]:uuidV1();
  2115. file.userID = userID;
  2116. file.rootProjectID = projectIDMap[file.rootProjectID];
  2117. file.feeRateID = rate.ID;
  2118. feeRateFiles.push(file);
  2119. }
  2120. if(feeRateFiles.length > 0) await insertMany(feeRateFiles,feeRateFileModel);
  2121. if(feeRates.length > 0) await insertMany(feeRates,feeRateModel);
  2122. }
  2123. // 初始化
  2124. async function initOverHeightItems(engineeringID) {
  2125. const defaultData = [];
  2126. const engineering = await engineeringModel.findById(engineeringID);
  2127. const overHeightLibs = engineering.over_height_lib;
  2128. if (!overHeightLibs || !overHeightLibs.length) {
  2129. return defaultData;
  2130. }
  2131. const overHeightLibID = overHeightLibs[0].id;
  2132. const overHeightLib = await overHeightLibModel.findOne({ID: overHeightLibID});
  2133. return overHeightLib ? overHeightLib.list : defaultData;
  2134. }
  2135. function uploadToken() {
  2136. let options = {
  2137. scope: qiniu_config.Bucket,
  2138. deleteAfterDays: 1,
  2139. returnBody:
  2140. '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
  2141. };
  2142. let putPolicy = new qiniu.rs.PutPolicy(options);
  2143. let token = putPolicy.uploadToken(mac);
  2144. let result = {
  2145. uptoken: token,
  2146. domain: qiniu_config.Domain
  2147. }
  2148. return result
  2149. }
  2150. // 有些方法无法通过中间件就检查单位工程数量是否超限
  2151. // 需要到具体的业务代码中进行判断
  2152. // 这个方法就是具体业务代码中,需要检查单位工程数量是否超限用
  2153. async function isTenderOverrun(tenderCount, session) {
  2154. const userID = session.sessionUser.id;
  2155. const compilation = session.sessionCompilation._id;
  2156. const compilationVersion = session.compilationVersion || '免费';
  2157. let systemSetting = session.systemSetting || (session.systemSetting = await systemSettingMiddleware.getSystemSetting());
  2158. // 这种情况只有在刚上线此功能时会出现,不考虑时间差
  2159. if (!systemSetting) {
  2160. return false;
  2161. }
  2162. const type = compilationVersion.includes('免费') ? 'normal' : 'professional';
  2163. const limit = systemSetting[type].project;
  2164. const curTenderCount = await projectModel.count({userID, compilation, projType: 'Tender', '$or':[{deleteInfo: null}, {'deleteInfo.completeDeleted': false}]});
  2165. return tenderCount + curTenderCount > limit;
  2166. }