pm_facade.js 129 KB

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