pm_facade.js 130 KB

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