pm_facade.js 132 KB

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