pm_facade.js 132 KB

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