pm_facade.js 129 KB

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