pm_facade.js 112 KB

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