pm_facade.js 128 KB

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