pm_facade.js 132 KB

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