ledger.js 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902
  1. 'use strict';
  2. /**
  3. * 标段--台账 数据模型
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/12/1
  7. * @version
  8. */
  9. const needField = {
  10. id: 'ledger_id',
  11. pid: 'ledger_pid',
  12. order: 'order',
  13. level: 'level',
  14. fullPath: 'full_path',
  15. isLeaf: 'is_leaf',
  16. };
  17. const keyFields = {
  18. table: ['id'],
  19. index: ['tender_id', 'ledger_id'],
  20. };
  21. // 以下字段仅可通过树结构操作改变,不可直接通过update方式从接口提交,发现时过滤
  22. const readOnlyFields = ['id', 'tender_id', 'ledger_id', 'ledger_pid', 'order', 'level', 'full_path', 'is_leaf'];
  23. const calcFields = ['quantity', 'unit_price', 'total_price', 'deal_qty', 'deal_tp'];
  24. const qtyFields = ['quantity', 'deal_qty', 'dgn_qty1', 'dgn_qty2'];
  25. const zeroRange = 0.0000000001;
  26. const rootId = -1;
  27. const keyPre = 'tender_node_maxId:';
  28. module.exports = app => {
  29. class Ledger extends app.BaseService {
  30. /**
  31. * 构造函数
  32. *
  33. * @param {Object} ctx - egg全局变量
  34. * @return {void}
  35. */
  36. constructor(ctx) {
  37. super(ctx);
  38. this.tableName = 'ledger';
  39. }
  40. /**
  41. * 新增数据(供内部或其他service类调用, controller不可直接使用)
  42. * @param {Array|Object} data - 新增数据
  43. * @param {Number} tenderId - 标段id
  44. * @param {Object} transaction - 新增事务
  45. * @return {Promise<boolean>} - {Promise<是否正确新增成功>}
  46. */
  47. async innerAdd(data, tenderId, transaction) {
  48. const datas = data instanceof Array ? data : [data];
  49. if (tenderId <= 0) {
  50. throw '标段id错误';
  51. }
  52. if (datas.length <= 0) {
  53. throw '插入数据为空';
  54. }
  55. if (!transaction) {
  56. throw '内部错误';
  57. }
  58. // 整理数据
  59. const insertData = [];
  60. for (const tmp of datas) {
  61. tmp.ledger_id = tmp.id;
  62. tmp.ledger_pid = tmp.pid;
  63. tmp.tender_id = tenderId;
  64. delete tmp.id;
  65. delete tmp.pid;
  66. insertData.push(tmp);
  67. }
  68. const operate = await transaction.insert(this.tableName, insertData);
  69. return operate.affectedRows === datas.length;
  70. }
  71. /**
  72. * 新增数据
  73. *
  74. * @param {Object} data - 新增的数据(可批量)
  75. * @param {Number} tenderId - 标段id
  76. * @return {Boolean} - 返回新增的结果
  77. */
  78. async add(data, tenderId) {
  79. this.transaction = await this.db.beginTransaction();
  80. let result = false;
  81. try {
  82. result = await this.innerAdd(data, tenderId, this.transaction);
  83. if (!result) {
  84. throw '新增数据错误';
  85. }
  86. await this.transaction.commit();
  87. } catch (error) {
  88. await this.transaction.rollback();
  89. result = false;
  90. }
  91. return result;
  92. }
  93. /**
  94. * 根据层级获取数据
  95. *
  96. * @param {Number} tenderId - 标段id
  97. * @param {Number} showLevel - 显示层数
  98. * @return {Array} - 返回数据
  99. */
  100. async getDataByTenderId(tenderId, showLevel = 4) {
  101. if (tenderId <= 0) {
  102. return [];
  103. }
  104. this.initSqlBuilder();
  105. this.sqlBuilder.setAndWhere('tender_id', {
  106. value: tenderId,
  107. operate: '=',
  108. });
  109. if (showLevel > 0) {
  110. this.sqlBuilder.setAndWhere('level', {
  111. value: showLevel,
  112. operate: '<=',
  113. });
  114. }
  115. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  116. const data = await this.db.query(sql, sqlParam);
  117. return data;
  118. }
  119. /**
  120. * 根据节点Id获取数据
  121. *
  122. * @param {Number} tenderId - 标段id
  123. * @param {Number} nodeId - 项目节/工程量清单节点id
  124. * @return {Object} - 返回查询到的节点数据
  125. */
  126. async getDataByNodeId(tenderId, nodeId) {
  127. if ((nodeId <= 0) || (tenderId <= 0)) {
  128. return undefined;
  129. }
  130. this.initSqlBuilder();
  131. this.sqlBuilder.setAndWhere('tender_id', {
  132. value: tenderId,
  133. operate: '=',
  134. });
  135. this.sqlBuilder.setAndWhere('ledger_id', {
  136. value: nodeId,
  137. operate: '=',
  138. });
  139. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  140. const data = await this.db.queryOne(sql, sqlParam);
  141. return data;
  142. }
  143. /**
  144. * 根据节点Id获取数据
  145. * @param {Number} tenderId - 标段Id
  146. * @param {Array} nodesIds - 节点Id
  147. * @return {Array}
  148. */
  149. async getDataByNodeIds(tenderId, nodesIds) {
  150. if (tenderId <= 0) {
  151. return [];
  152. }
  153. this.initSqlBuilder();
  154. this.sqlBuilder.setAndWhere('tender_id', {
  155. value: tenderId,
  156. operate: '=',
  157. });
  158. this.sqlBuilder.setAndWhere('ledger_id', {
  159. value: nodesIds,
  160. operate: 'in',
  161. });
  162. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  163. const data = await this.db.query(sql, sqlParam);
  164. return data;
  165. }
  166. /**
  167. * 根据主键id获取数据
  168. * @param {Array|Number} id - 主键id
  169. * @return {Promise<*>}
  170. */
  171. async getDataByIds(id) {
  172. if (!id) {
  173. return;
  174. }
  175. const ids = id instanceof Array ? id : [id];
  176. if (ids.length === 0) {
  177. return;
  178. }
  179. this.initSqlBuilder();
  180. this.sqlBuilder.setAndWhere('id', {
  181. value: ids,
  182. operate: 'in',
  183. });
  184. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  185. const data = await this.db.query(sql, sqlParam);
  186. return data;
  187. }
  188. /**
  189. * 根据标准清单源检索
  190. * @param tenderId
  191. * @param source
  192. * @return {Promise<*>}
  193. */
  194. async getDataBySource(tenderId, source) {
  195. this.initSqlBuilder();
  196. this.sqlBuilder.setAndWhere('tender_id', {
  197. value: tenderId,
  198. operate: '=',
  199. });
  200. this.sqlBuilder.setAndWhere('source', {
  201. value: source,
  202. operate: '=',
  203. });
  204. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  205. const data = await this.db.query(sql, sqlParam);
  206. return data;
  207. }
  208. /**
  209. * 获取最末的子节点
  210. * @param {Number} tenderId - 标段id
  211. * @param {Number} pid - 父节点id
  212. * @return {Object}
  213. */
  214. async getLastChildData(tenderId, pid) {
  215. this.initSqlBuilder();
  216. this.sqlBuilder.setAndWhere('tender_id', {
  217. value: tenderId,
  218. operate: '=',
  219. });
  220. this.sqlBuilder.setAndWhere('ledger_pid', {
  221. value: pid,
  222. operate: '=',
  223. });
  224. this.sqlBuilder.orderBy = [['order', 'DESC']];
  225. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  226. const resultData = await this.db.queryOne(sql, sqlParam);
  227. return resultData;
  228. }
  229. /**
  230. * 根据 父节点id 和 节点排序order 获取数据
  231. *
  232. * @param {Number} tenderId - 标段id
  233. * @param {Number} pid - 父节点id
  234. * @param {Number|Array} order - 排序
  235. * @return {Object|Array} - 查询结果
  236. */
  237. async getDataByParentAndOrder(tenderId, pid, order) {
  238. if ((tenderId <= 0) || (pid <= 0) || (order <= 0)) {
  239. return undefined;
  240. }
  241. this.initSqlBuilder();
  242. this.sqlBuilder.setAndWhere('tender_id', {
  243. value: tenderId,
  244. operate: '=',
  245. });
  246. this.sqlBuilder.setAndWhere('ledger_pid', {
  247. value: pid,
  248. operate: '=',
  249. });
  250. if (order instanceof Array) {
  251. this.sqlBuilder.setAndWhere('order', {
  252. value: order,
  253. operate: 'in',
  254. });
  255. } else {
  256. this.sqlBuilder.setAndWhere('order', {
  257. value: order,
  258. operate: '=',
  259. });
  260. }
  261. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  262. let data;
  263. if (order instanceof Array) {
  264. data = await this.db.query(sql, sqlParam);
  265. } else {
  266. data = await this.db.queryOne(sql, sqlParam);
  267. }
  268. return data;
  269. }
  270. /**
  271. * 根据 父节点id 获取子节点
  272. * @param tenderId
  273. * @param nodeId
  274. * @return {Promise<*>}
  275. */
  276. async getChildrenByParentId(tenderId, nodeId) {
  277. if (tenderId <= 0 || !nodeId) {
  278. return undefined;
  279. }
  280. const nodeIds = nodeId instanceof Array ? nodeId : [nodeId];
  281. if (nodeIds.length === 0) {
  282. return [];
  283. }
  284. this.initSqlBuilder();
  285. this.sqlBuilder.setAndWhere('tender_id', {
  286. value: tenderId,
  287. operate: '=',
  288. });
  289. this.sqlBuilder.setAndWhere('ledger_pid', {
  290. value: nodeIds,
  291. operate: 'in',
  292. });
  293. this.sqlBuilder.orderBy = [['order', 'ASC']];
  294. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  295. const data = await this.db.query(sql, sqlParam);
  296. return data;
  297. }
  298. /**
  299. * 根据 父节点id 获取孙子节点
  300. * @param tenderId
  301. * @param nodeId
  302. * @return {Promise<void>}
  303. */
  304. async getPosterityByParentId(tenderId, nodeId) {
  305. if (tenderId <= 0 || !nodeId) {
  306. return undefined;
  307. }
  308. const node = await this.getDataByNodeId(tenderId, nodeId);
  309. this.initSqlBuilder();
  310. this.sqlBuilder.setAndWhere('tender_id', {
  311. value: tenderId,
  312. operate: '=',
  313. });
  314. this.sqlBuilder.setAndWhere('full_path', {
  315. value: this.db.escape(node.full_path + '.%'),
  316. operate: 'like',
  317. });
  318. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  319. const data = await this.db.query(sql, sqlParam);
  320. return data;
  321. }
  322. /**
  323. * 根据 父节点ID 和 节点排序order 获取全部后节点数据
  324. * @param {Number} tenderId - 标段id
  325. * @param {Number} pid - 父节点id
  326. * @param {Number} order - 排序
  327. * @return {Array}
  328. */
  329. async getNextsData(tenderId, pid, order) {
  330. if ((tenderId <= 0) || (order < 0)) {
  331. return undefined;
  332. }
  333. this.initSqlBuilder();
  334. this.sqlBuilder.setAndWhere('tender_id', {
  335. value: tenderId,
  336. operate: '=',
  337. });
  338. this.sqlBuilder.setAndWhere('ledger_pid', {
  339. value: pid,
  340. operate: '=',
  341. });
  342. this.sqlBuilder.setAndWhere('order', {
  343. value: order,
  344. operate: '>',
  345. });
  346. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  347. const data = await this.db.query(sql, sqlParam);
  348. return data;
  349. }
  350. /**
  351. * 根据full_path获取数据 full_path Like ‘1.2.3%’(传参full_path = '1.2.3%')
  352. * @param {Number} tenderId - 标段id
  353. * @param {String} full_path - 路径
  354. * @return {Promise<void>}
  355. */
  356. async getDataByFullPath(tenderId, full_path) {
  357. this.initSqlBuilder();
  358. this.sqlBuilder.setAndWhere('tender_id', {
  359. value: tenderId,
  360. operate: '=',
  361. });
  362. this.sqlBuilder.setAndWhere('full_path', {
  363. value: this.db.escape(full_path),
  364. operate: 'Like',
  365. });
  366. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  367. const resultData = await this.db.query(sql, sqlParam);
  368. return resultData;
  369. }
  370. /**
  371. * 根据full_path检索自己及所有父项
  372. * @param {Number} tenderId - 标段id
  373. * @param {Array|String} fullPath - 节点完整路径
  374. * @return {Promise<*>}
  375. * @private
  376. */
  377. async getFullLevelDataByFullPath(tenderId, fullPath) {
  378. const explodePath = this.ctx.helper.explodePath(fullPath);
  379. this.initSqlBuilder();
  380. this.sqlBuilder.setAndWhere('tender_id', {
  381. value: tenderId,
  382. operate: '=',
  383. });
  384. this.sqlBuilder.setAndWhere('full_path', {
  385. value: explodePath,
  386. operate: 'in',
  387. });
  388. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  389. const data = await this.db.query(sql, sqlParam);
  390. return data;
  391. }
  392. /**
  393. * 获取项目工程量
  394. * @param tenderId
  395. * @returns {Promise<*>}
  396. */
  397. async getGatherGclBills(tenderId) {
  398. const sql = 'SELECT `b_code`, `name`, `unit`, `unit_price`, ' +
  399. ' Sum(`quantity`) As `quantity`, Sum(`total_price`) As `total_price`, ' +
  400. ' Sum(`deal_qty`) As `deal_qty`, Sum(`deal_tp`) As `deal_tp` ' +
  401. ' From ?? ' +
  402. ' WHERE `tender_id` = ? And `b_code` And `is_leaf` ' +
  403. ' GROUP BY `b_code`, `name`, `unit`, `unit_price`';
  404. const sqlParam = [this.tableName, tenderId];
  405. return await this.db.query(sql, sqlParam);
  406. }
  407. /**
  408. * 获取sql条件语句片段,仅供search、searchRange方法使用
  409. * @param {Object} where - 条件参数
  410. * @return {*[]}
  411. * e.g.
  412. * where = {type: 'And', value: 'A', operate: '=', fields: ['code', 'name']}
  413. * return [sql: 'And (?? = \'A\' Or ?? = \'A\')', sqlParam: ['code', name]]
  414. * @private
  415. */
  416. _getWhereString(where) {
  417. const sqlParam = [],
  418. sqlPart = [];
  419. const values = where.value instanceof Array ? where.value : [where.value];
  420. const fields = where.fields instanceof Array ? where.fields : [where.fields];
  421. for (const field of fields) {
  422. for (const v of values) {
  423. sqlPart.push('?? ' + where.operate + ' ' + v);
  424. sqlParam.push(field);
  425. }
  426. }
  427. const sql = ' ' + (where.type ? where.type : 'And') + ' (' + sqlPart.join(' OR ') + ')';
  428. return [sql, sqlParam];
  429. }
  430. /**
  431. * 搜索台账
  432. *
  433. * @param {Number} tenderId - 标段id
  434. * @param {Object} key - 查询信息
  435. * @return {Promise<void>}
  436. */
  437. async search(tenderId, key) {
  438. let sql = 'Select * From ?? Where';
  439. let sqlParam = [this.tableName];
  440. sql = sql + ' ?? = ' + tenderId;
  441. sqlParam.push('tender_id');
  442. const [sql1, sqlParam1] = this._getWhereString(key);
  443. sql = sql + sql1;
  444. sqlParam = sqlParam.concat(sqlParam1);
  445. return this.db.query(sql, sqlParam);
  446. }
  447. /**
  448. * 范围内搜索台账
  449. *
  450. * @param {Number} tenderId - 标段id
  451. * @param {Object} key - 查询信息
  452. * @param {Array} range - 查询范围
  453. * @return {Promise<void>}
  454. */
  455. async searchRange(tenderId, key, range) {
  456. let sql = 'Select * From ?? Where';
  457. let sqlParam = [this.tableName];
  458. sql = sql + ' ?? = ' + tenderId;
  459. sqlParam.push('tender_id');
  460. let [sql1, sqlParam1] = this._getWhereString(key);
  461. sql = sql + sql1;
  462. sqlParam = sqlParam.concat(sqlParam1);
  463. for (const r of range) {
  464. [sql1, sqlParam1] = this._getWhereString(r);
  465. sql = sql + sql1;
  466. sqlParam = sqlParam.concat(sqlParam1);
  467. }
  468. return this.db.query(sql, sqlParam);
  469. }
  470. /**
  471. * 统计子节点total_price
  472. * @param {Number} tenderId - 标段id
  473. * @param {Number} pid - 父节点id
  474. * @param {Number} order - order取值
  475. * @param {String} orderOperate - order比较操作符
  476. * @return {Promise<void>}
  477. */
  478. async addUpChildren(tenderId, pid, order, orderOperate) {
  479. this.initSqlBuilder();
  480. const sql = ['SELECT SUM(??) As value FROM ?? ', ' WHERE '];
  481. const sqlParam = ['total_price', this.tableName];
  482. sql.push(' ?? = ' + tenderId);
  483. sqlParam.push('tender_id');
  484. sql.push(' And ?? = ' + pid);
  485. sqlParam.push('ledger_pid');
  486. sql.push(' And ?? ' + orderOperate + ' ' + order);
  487. sqlParam.push('order');
  488. const result = await this.db.queryOne(sql.join(''), sqlParam);
  489. return result.value;
  490. }
  491. /**
  492. * 更新order
  493. * @param {Number} tenderId - 标段id
  494. * @param {Number} parentId - 父节点id
  495. * @param {Number} order - 自增起始order(含)
  496. * @param {Number} incre - 自增量
  497. * @return {Promise<*>}
  498. * @private
  499. */
  500. async _updateChildrenOrderAfter(tenderId, parentId, order, incre = 1) {
  501. this.initSqlBuilder();
  502. this.sqlBuilder.setAndWhere('tender_id', {
  503. value: tenderId,
  504. operate: '=',
  505. });
  506. this.sqlBuilder.setAndWhere('order', {
  507. value: order,
  508. operate: '>=',
  509. });
  510. this.sqlBuilder.setAndWhere('ledger_pid', {
  511. value: parentId,
  512. operate: '=',
  513. });
  514. this.sqlBuilder.setUpdateData('order', {
  515. value: Math.abs(incre),
  516. selfOperate: incre > 0 ? '+' : '-',
  517. });
  518. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  519. const data = await this.transaction.query(sql, sqlParam);
  520. return data;
  521. }
  522. /**
  523. * select的全部后兄弟节点,Order自增
  524. *
  525. * @param {Object} select - 选中的节点
  526. * @param {Number} incre - 自增值
  527. * @return {Array} - 自增后的数据
  528. * @private
  529. */
  530. async _updateSelectNextsOrder(select, incre = 1) {
  531. return await this._updateChildrenOrderAfter(select.tender_id, select.ledger_pid, select.order + 1, incre);
  532. }
  533. /**
  534. * 从数据库获取标段的最大节点id
  535. *
  536. * @param {Number} tenderId - 标段id
  537. * @return {Number}
  538. * @private
  539. */
  540. async _getMaxNodeId(tenderId) {
  541. const sql = 'SELECT Max(??) As max_id FROM ?? Where tender_id = ' + tenderId;
  542. const sqlParam = ['ledger_id', this.tableName];
  543. const queryResult = await this.db.queryOne(sql, sqlParam);
  544. return queryResult.max_id;
  545. }
  546. /**
  547. * 根据selectData, data 新增数据(新增为selectData的后项,该方法不可单独使用)
  548. *
  549. * @param {Number} tenderId - 标段id
  550. * @param {Object} selectData - 选中节点的数据
  551. * @param {Object} data - 新增节点的初始数据
  552. * @return {Object} - 新增结果
  553. * @private
  554. */
  555. async _addNodeData(tenderId, selectData, data) {
  556. if (tenderId <= 0) {
  557. return undefined;
  558. }
  559. if (!data) {
  560. data = {};
  561. }
  562. const cacheKey = keyPre + tenderId;
  563. let maxId = parseInt(await this.cache.get(cacheKey));
  564. if (!maxId) {
  565. maxId = await this._getMaxNodeId(tenderId);
  566. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  567. }
  568. data.tender_id = tenderId;
  569. data.ledger_id = maxId + 1;
  570. data.ledger_pid = selectData.ledger_pid;
  571. data.level = selectData.level;
  572. data.order = selectData.order + 1;
  573. data.full_path = selectData.full_path.replace('.' + selectData.ledger_id, '.' + data.ledger_id);
  574. data.is_leaf = true;
  575. const result = await this.transaction.insert(this.tableName, data);
  576. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  577. return result;
  578. }
  579. /**
  580. * 根据parentData, data新增数据(新增为parentData的最后一个子项)
  581. * @param {Number} tenderId - 标段id
  582. * @param {Object} parentData - 父项数据
  583. * @param {Object} data - 新增节点,初始数据
  584. * @return {Promise<*>} - 新增结果
  585. * @private
  586. */
  587. async _addChildNodeData(tenderId, parentData, data) {
  588. if (tenderId <= 0) {
  589. return undefined;
  590. }
  591. if (!data) {
  592. data = {};
  593. }
  594. const pid = parentData ? parentData.ledger_id : rootId;
  595. const cacheKey = keyPre + tenderId;
  596. let maxId = parseInt(await this.cache.get(cacheKey));
  597. if (!maxId) {
  598. maxId = await this._getMaxNodeId(tenderId);
  599. }
  600. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  601. data.tender_id = tenderId;
  602. data.ledger_id = maxId + 1;
  603. data.ledger_pid = pid;
  604. if (data.order === undefined) {
  605. data.order = 1;
  606. }
  607. data.level = parentData ? parentData.level + 1 : 1;
  608. data.full_path = parentData ? parentData.full_path + '.' + data.ledger_id : '' + data.ledger_id;
  609. if (data.is_leaf === undefined) {
  610. data.is_leaf = true;
  611. }
  612. const result = await this.transaction.insert(this.tableName, data);
  613. return [result, data];
  614. }
  615. /**
  616. * 根据parentData, data新增数据(自动排序)
  617. * @param tenderId
  618. * @param parentData
  619. * @param data
  620. * @return {Promise<void>}
  621. * @private
  622. */
  623. async _addChildAutoOrder(tenderId, parentData, data) {
  624. const self = this;
  625. const findPreData = function(list, a) {
  626. if (!list || list.length === 0) { return null; }
  627. for (let i = 0, iLen = list.length; i < iLen; i++) {
  628. if (self.ctx.helper.compareCode(list[i].code, a.code) > 0) {
  629. return i > 0 ? list[i - 1] : null;
  630. }
  631. }
  632. return list[list.length - 1];
  633. };
  634. const pid = parentData ? parentData.ledger_id : rootId;
  635. const children = await this.getChildrenByParentId(tenderId, pid);
  636. const preData = findPreData(children, data);
  637. const parent = null;
  638. if (!preData || children.indexOf(preData) < children.length - 1) {
  639. await this._updateChildrenOrderAfter(tenderId, pid, preData ? preData.order + 1 : 1);
  640. }
  641. data.order = preData ? preData.order + 1 : 1;
  642. const [addResult, node] = await this._addChildNodeData(tenderId, parentData, data);
  643. return [addResult, node];
  644. }
  645. /**
  646. * tenderId标段中, 在selectId后新增一个节点
  647. *
  648. * @param {Number} tenderId - 标段id
  649. * @param {Number} selectId - 选中节点id
  650. * @param {Object} data - 新增节点初始化数据
  651. * @return {Array} 新增后的数据,其他被修改的数据
  652. */
  653. async addNode(tenderId, selectId, data) {
  654. if ((tenderId <= 0) || (selectId <= 0)) {
  655. return [];
  656. }
  657. const selectData = await this.getDataByNodeId(tenderId, selectId);
  658. if (!selectData) {
  659. throw '新增节点数据错误';
  660. }
  661. if (!this.transaction) {
  662. this.transaction = await this.db.beginTransaction();
  663. }
  664. try {
  665. // 选中节点的所有后兄弟节点,order+1
  666. await this._updateSelectNextsOrder(selectData);
  667. // 数据库创建新增节点数据
  668. const newNode = await this._addNodeData(tenderId, selectData, data);
  669. if (!newNode) { throw '新增节点数据错误'; }
  670. await this.transaction.commit();
  671. } catch (err) {
  672. await this.transaction.rollback();
  673. this.transaction = null;
  674. throw err;
  675. }
  676. this.transaction = null;
  677. // 查询应返回的结果
  678. const createData = await this.getDataByParentAndOrder(selectData.tender_id, selectData.ledger_pid, [selectData.order + 1]);
  679. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + 1);
  680. return { create: createData, update: updateData };
  681. }
  682. /**
  683. * 从标准数据中提取有效数据
  684. * @param {Object} stdData - 从标准库中查询所得
  685. * @returns {name, unit, source, code, b_code}
  686. * @private
  687. */
  688. _filterStdData(stdData) {
  689. const result = {
  690. name: stdData.name,
  691. unit: stdData.unit,
  692. source: stdData.source,
  693. };
  694. result.code = stdData.code ? stdData.code : '';
  695. result.b_code = stdData.b_code ? stdData.b_code : '';
  696. return result;
  697. }
  698. /**
  699. * 添加节点(来自标准清单)
  700. * @param {Number} tenderId
  701. * @param {Number} selectId
  702. * @param {Object} stdData
  703. * @return {Promise<*>}
  704. */
  705. async addStdNode(tenderId, selectId, stdData) {
  706. const newData = this._filterStdData(stdData);
  707. const result = await this.addNode(tenderId, selectId, newData);
  708. return result;
  709. }
  710. async addChild(tenderId, selectId, data) {
  711. if ((tenderId <= 0) || (selectId <= 0)) {
  712. return [];
  713. }
  714. const selectData = await this.getDataByNodeId(tenderId, selectId);
  715. if (!selectData) {
  716. throw '新增节点数据错误';
  717. }
  718. const children = await this.getChildrenByParentId(tenderId, selectId);
  719. const cacheKey = keyPre + tenderId;
  720. let maxId = parseInt(await this.cache.get(cacheKey));
  721. if (!maxId) {
  722. maxId = await this._getMaxNodeId(tenderId);
  723. this.cache.set(cacheKey, maxId, 'EX', this.ctx.app.config.cacheTime);
  724. }
  725. data.tender_id = tenderId;
  726. data.ledger_id = maxId + 1;
  727. data.ledger_pid = selectData.ledger_id;
  728. data.level = selectData.level + 1;
  729. data.order = children.length + 1;
  730. data.full_path = selectData.full_path + '.' + data.ledger_id;
  731. data.is_leaf = true;
  732. const result = await this.db.insert(this.tableName, data);
  733. this.cache.set(cacheKey, maxId + 1, 'EX', this.ctx.app.config.cacheTime);
  734. // 查询应返回的结果
  735. const createData = await this.getDataByNodeId(tenderId, data.ledger_id);
  736. return { create: createData };
  737. }
  738. async addStdNodeAsChild(tenderId, selectId, stdData) {
  739. const newData = this._filterStdData(stdData);
  740. const result = await this.addChild(tenderId, selectId, newData);
  741. return result;
  742. }
  743. /**
  744. * 添加节点,并同步添加父节点
  745. * @param {Number} tenderId - 标段id
  746. * @param {Number} selectId - 选中节点id
  747. * @param {Object} stdData - 节点数据
  748. * @param {StandardLib} stdLib - 标准库
  749. * @return {Promise<void>}
  750. */
  751. async addStdNodeWithParent(tenderId, stdData, stdLib) {
  752. const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);
  753. fullLevel.sort(function(x, y) {
  754. return x.level - y.level;
  755. });
  756. let isNew = false,
  757. node,
  758. firstNew,
  759. updateParent,
  760. addResult;
  761. const expandIds = [];
  762. this.transaction = await this.db.beginTransaction();
  763. try {
  764. for (let i = 0, len = fullLevel.length; i < len; i++) {
  765. const stdNode = fullLevel[i];
  766. if (isNew) {
  767. const newData = this._filterStdData(stdNode);
  768. newData.is_leaf = (i === len - 1);
  769. [addResult, node] = await this._addChildNodeData(tenderId, node, newData);
  770. } else {
  771. const parent = node;
  772. node = await this.getDataByCondition({
  773. tender_id: tenderId,
  774. ledger_pid: parent ? parent.ledger_id : rootId,
  775. code: stdNode.code,
  776. name: stdNode.name,
  777. });
  778. if (!node) {
  779. isNew = true;
  780. const newData = this._filterStdData(stdNode);
  781. newData.is_leaf = (i === len - 1);
  782. [addResult, node] = await this._addChildAutoOrder(tenderId, parent, newData);
  783. if (parent && parent.is_leaf) {
  784. await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false });
  785. updateParent = parent;
  786. }
  787. firstNew = node;
  788. } else {
  789. expandIds.push(node.ledger_id);
  790. }
  791. }
  792. }
  793. await this.transaction.commit();
  794. } catch (err) {
  795. await this.transaction.rollback();
  796. throw err;
  797. }
  798. // 查询应返回的结果
  799. let createData = [],
  800. updateData = [];
  801. if (firstNew) {
  802. createData = await this.getDataByFullPath(tenderId, firstNew.full_path + '%');
  803. updateData = await this.getNextsData(tenderId, firstNew.ledger_pid, firstNew.order);
  804. if (updateParent) {
  805. updateData.push(await this.getDataByCondition({ id: updateParent.id }));
  806. }
  807. }
  808. const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  809. return { create: createData, update: updateData, expand: expandData };
  810. }
  811. /**
  812. * 删除节点
  813. * @param {Number} tenderId - 标段id
  814. * @param {Object} deleteData - 删除节点数据
  815. * @return {Promise<*>}
  816. * @private
  817. */
  818. async _deleteNodeData(tenderId, deleteData) {
  819. this.initSqlBuilder();
  820. this.sqlBuilder.setAndWhere('tender_id', {
  821. value: tenderId,
  822. operate: '=',
  823. });
  824. this.sqlBuilder.setAndWhere('full_path', {
  825. value: this.db.escape(deleteData.full_path + '%'),
  826. operate: 'Like',
  827. });
  828. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'delete');
  829. const result = await this.transaction.query(sql, sqlParam);
  830. return result;
  831. }
  832. /**
  833. * tenderId标段中, 删除选中节点及其子节点
  834. *
  835. * @param {Number} tenderId - 标段id
  836. * @param {Number} selectId - 选中节点id
  837. * @return {Array} - 被删除的数据
  838. */
  839. async deleteNode(tenderId, selectId) {
  840. if ((tenderId <= 0) || (selectId <= 0)) {
  841. return [];
  842. }
  843. const selectData = await this.getDataByNodeId(tenderId, selectId);
  844. if (!selectData) {
  845. throw '删除节点数据错误';
  846. }
  847. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  848. this.transaction = await this.db.beginTransaction();
  849. let deleteData = [];
  850. try {
  851. // 获取将要被删除的数据
  852. deleteData = await this.getDataByFullPath(tenderId, selectData.full_path + '%');
  853. // 删除
  854. const operate = await this._deleteNodeData(tenderId, selectData);
  855. // 选中节点--父节点 只有一个子节点时,应升级is_leaf
  856. if (parentData) {
  857. const count = await this.db.count(this.tableName, { tender_id: tenderId, ledger_pid: selectData.ledger_pid });
  858. if (count === 1) {
  859. await this.transaction.update(this.tableName, { id: parentData.id, is_leaf: true });
  860. }
  861. }
  862. // 选中节点--全部后节点 order--
  863. await this._updateSelectNextsOrder(selectData, -1);
  864. // 删除部位明细
  865. await this.transaction.delete(this.ctx.service.pos.tableName, { tid: tenderId, lid: this._.map(deleteData, 'id') });
  866. await this.ctx.service.pos.deletePosData(this.transaction, tenderId, this._.map(deleteData, 'id'));
  867. await this.transaction.commit();
  868. } catch (err) {
  869. deleteData = [];
  870. await this.transaction.rollback();
  871. throw err;
  872. }
  873. // 查询结果
  874. let updateData = [];
  875. if (deleteData.length > 0) {
  876. updateData = await this.getNextsData(tenderId, selectData.ledger_pid, selectData.order - 1);
  877. updateData = updateData ? updateData : [];
  878. if (selectData.ledger_pid !== rootId) {
  879. const updateData1 = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  880. if (updateData1.is_leaf !== parentData.is_leaf) {
  881. updateData.push(updateData1);
  882. }
  883. }
  884. }
  885. return { delete: deleteData, update: updateData };
  886. }
  887. /**
  888. * tenderId标段中, 选中节点selectId上移
  889. *
  890. * @param {Number} tenderId - 标段id
  891. * @param {Number} selectId - 选中节点id
  892. * @return {Array} - 发生改变的数据
  893. */
  894. async upMoveNode(tenderId, selectId) {
  895. if ((tenderId <= 0) || (selectId <= 0)) {
  896. return [];
  897. }
  898. const selectData = await this.getDataByNodeId(tenderId, selectId);
  899. if (!selectData) {
  900. throw '上移节点数据错误';
  901. }
  902. const preData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order - 1);
  903. if (!preData) {
  904. throw '节点不可上移';
  905. }
  906. this.transaction = await this.db.beginTransaction();
  907. try {
  908. const sData = await this.transaction.update(this.tableName, { id: selectData.id, order: selectData.order - 1 });
  909. const pData = await this.transaction.update(this.tableName, { id: preData.id, order: preData.order + 1 });
  910. await this.transaction.commit();
  911. } catch (err) {
  912. await this.transaction.rollback();
  913. throw err;
  914. }
  915. const resultData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, [selectData.order, preData.order]);
  916. return { update: resultData };
  917. }
  918. /**
  919. * tenderId标段中, 选中节点selectId下移
  920. *
  921. * @param {Number} tenderId - 标段id
  922. * @param {Number} selectId - 选中节点id
  923. * @return {Array} - 发生改变的数据
  924. */
  925. async downMoveNode(tenderId, selectId) {
  926. if ((tenderId <= 0) || (selectId <= 0)) {
  927. return [];
  928. }
  929. const selectData = await this.getDataByNodeId(tenderId, selectId);
  930. if (!selectData) {
  931. throw '下移节点数据错误';
  932. }
  933. const nextData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order + 1);
  934. if (!nextData) {
  935. throw '节点不可下移';
  936. }
  937. this.transaction = await this.db.beginTransaction();
  938. try {
  939. const sData = await this.transaction.update(this.tableName, { id: selectData.id, order: selectData.order + 1 });
  940. const pData = await this.transaction.update(this.tableName, { id: nextData.id, order: nextData.order - 1 });
  941. await this.transaction.commit();
  942. } catch (err) {
  943. await this.transaction.rollback();
  944. throw err;
  945. }
  946. const resultData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, [selectData.order, nextData.order]);
  947. return { update: resultData };
  948. }
  949. /**
  950. * 升级selectData, 同步修改所有子节点
  951. * @param {Object} selectData - 升级操作,选中节点
  952. * @return {Object}
  953. * @private
  954. */
  955. async _syncUplevelChildren(selectData) {
  956. this.initSqlBuilder();
  957. this.sqlBuilder.setAndWhere('tender_id', {
  958. value: selectData.tender_id,
  959. operate: '=',
  960. });
  961. this.sqlBuilder.setAndWhere('full_path', {
  962. value: this.db.escape(selectData.full_path + '.%'),
  963. operate: 'like',
  964. });
  965. this.sqlBuilder.setUpdateData('level', {
  966. value: 1,
  967. selfOperate: '-',
  968. });
  969. this.sqlBuilder.setUpdateData('full_path', {
  970. value: ['`full_path`', this.db.escape(selectData.ledger_pid + '.'), this.db.escape('')],
  971. literal: 'Replace',
  972. });
  973. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  974. const data = await this.transaction.query(sql, sqlParam);
  975. return data;
  976. }
  977. /**
  978. * 选中节点的后兄弟节点,全部变为当前节点的子节点
  979. * @param {Object} selectData - 选中节点
  980. * @return {Object}
  981. * @private
  982. */
  983. async _syncUpLevelNexts(selectData) {
  984. // 查询selectData的lastChild
  985. const lastChildData = await this.getLastChildData(selectData.tender_id, selectData.ledger_id);
  986. const nextsData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order);
  987. if (nextsData && nextsData.length > 0) {
  988. // 修改nextsData pid, 排序
  989. this.initSqlBuilder();
  990. this.sqlBuilder.setUpdateData('ledger_pid', {
  991. value: selectData.ledger_id,
  992. });
  993. const orderInc = lastChildData ? lastChildData.order - selectData.order : -selectData.order;
  994. this.sqlBuilder.setUpdateData('order', {
  995. value: Math.abs(orderInc),
  996. selfOperate: orderInc > 0 ? '+' : '-',
  997. });
  998. this.sqlBuilder.setAndWhere('ledger_pid', {
  999. value: selectData.ledger_pid,
  1000. operate: '=',
  1001. });
  1002. this.sqlBuilder.setAndWhere('order', {
  1003. value: selectData.order,
  1004. operate: '>',
  1005. });
  1006. const [sql1, sqlParam1] = this.sqlBuilder.build(this.tableName, 'update');
  1007. await this.transaction.query(sql1, sqlParam1);
  1008. // 选中节点 is_leaf应为false
  1009. if (selectData.is_leaf) {
  1010. const updateData = { id: selectData.id,
  1011. is_leaf: false,
  1012. };
  1013. await this.transaction.update(this.tableName, updateData);
  1014. }
  1015. // 修改nextsData及其子节点的full_path
  1016. const oldSubStr = this.db.escape(selectData.ledger_pid + '.');
  1017. const newSubStr = this.db.escape(selectData.ledger_id + '.');
  1018. const sqlArr = [];
  1019. sqlArr.push('Update ?? SET `full_path` = Replace(`full_path`,' + oldSubStr + ',' + newSubStr + ') Where');
  1020. sqlArr.push('(`tender_id` = ' + selectData.tender_id + ')');
  1021. sqlArr.push(' And (');
  1022. for (const data of nextsData) {
  1023. sqlArr.push('`full_path` Like ' + this.db.escape(data.full_path + '%'));
  1024. if (nextsData.indexOf(data) < nextsData.length - 1) {
  1025. sqlArr.push(' Or ');
  1026. }
  1027. }
  1028. sqlArr.push(')');
  1029. const sql = sqlArr.join('');
  1030. const resultData = await this.transaction.query(sql, [this.tableName]);
  1031. return resultData;
  1032. }
  1033. }
  1034. /**
  1035. * 升级节点
  1036. *
  1037. * @param {Number} tenderId - 标段id
  1038. * @param {Number} selectId - 选中节点id
  1039. * @return {Array} - 发生改变的数据
  1040. */
  1041. async upLevelNode(tenderId, selectId) {
  1042. if ((tenderId <= 0) || (selectId <= 0)) {
  1043. return [];
  1044. }
  1045. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1046. if (!selectData) {
  1047. throw '升级节点数据错误';
  1048. }
  1049. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  1050. if (!parentData) {
  1051. throw '升级节点数据错误';
  1052. }
  1053. this.transaction = await this.db.beginTransaction();
  1054. const newFullPath = selectData.full_path.replace(selectData.ledger_pid + '.', '');
  1055. try {
  1056. // 选中节点--父节点 选中节点为firstChild时,修改is_leaf
  1057. if (selectData.order === 1) {
  1058. await this.transaction.update(this.tableName, {
  1059. id: parentData.id,
  1060. is_leaf: true,
  1061. });
  1062. }
  1063. // 选中节点--父节点--全部后兄弟节点 order+1
  1064. await this._updateSelectNextsOrder(parentData);
  1065. // 选中节点 修改pid, order, full_path
  1066. const updateData = { id: selectData.id,
  1067. ledger_pid: parentData.ledger_pid,
  1068. order: parentData.order + 1,
  1069. level: selectData.level - 1,
  1070. full_path: newFullPath,
  1071. };
  1072. await this.transaction.update(this.tableName, updateData);
  1073. // 选中节点--全部子节点(含孙) level-1, full_path变更
  1074. await this._syncUplevelChildren(selectData);
  1075. // 选中节点--全部后兄弟节点 收编为子节点 修改pid, order, full_path
  1076. await this._syncUpLevelNexts(selectData);
  1077. await this.transaction.commit();
  1078. } catch (err) {
  1079. await this.transaction.rollback();
  1080. throw err;
  1081. }
  1082. // 查询修改的数据
  1083. const resultData1 = await this.getDataByFullPath(tenderId, newFullPath + '%');
  1084. const resultData2 = await this.getNextsData(tenderId, parentData.ledger_pid, parentData.order + 1);
  1085. // 默认原Parent被刷新过,不核对total_price修改
  1086. const preParent = await this.getDataByNodeId(tenderId, parentData.ledger_id);
  1087. resultData2.push(preParent);
  1088. return { update: resultData1.concat(resultData2) };
  1089. }
  1090. /**
  1091. * 降级selectData, 同步修改所有子节点
  1092. * @param {Object} selectData - 选中节点
  1093. * @param {Object} preData - 选中节点的前一节点(降级后为父节点)
  1094. * @return {Promise<*>}
  1095. * @private
  1096. */
  1097. async _syncDownlevelChildren(selectData, preData) {
  1098. this.initSqlBuilder();
  1099. this.sqlBuilder.setAndWhere('tender_id', {
  1100. value: selectData.tender_id,
  1101. operate: '=',
  1102. });
  1103. this.sqlBuilder.setAndWhere('full_path', {
  1104. value: this.db.escape(selectData.full_path + '.%'),
  1105. operate: 'like',
  1106. });
  1107. this.sqlBuilder.setUpdateData('level', {
  1108. value: 1,
  1109. selfOperate: '+',
  1110. });
  1111. this.sqlBuilder.setUpdateData('full_path', {
  1112. value: ['`full_path`', this.db.escape('.' + selectData.ledger_id), this.db.escape('.' + preData.ledger_id + '.' + selectData.ledger_id)],
  1113. literal: 'Replace',
  1114. });
  1115. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1116. const data = await this.transaction.query(sql, sqlParam);
  1117. return data;
  1118. }
  1119. /**
  1120. * 降级节点
  1121. *
  1122. * @param {Number} tenderId - 标段id
  1123. * @param {Number} selectId - 选中节点id
  1124. * @return {Array} - 发生改变的数据
  1125. */
  1126. async downLevelNode(tenderId, selectId) {
  1127. if ((tenderId <= 0) || (selectId <= 0)) {
  1128. return [];
  1129. }
  1130. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1131. if (!selectData) {
  1132. throw '降级节点数据错误';
  1133. }
  1134. const preData = await this.getDataByParentAndOrder(tenderId, selectData.ledger_pid, selectData.order - 1);
  1135. if (!preData) {
  1136. throw '节点不可降级';
  1137. }
  1138. const preLastChildData = await this.getLastChildData(tenderId, preData.ledger_id);
  1139. this.transaction = await this.db.beginTransaction();
  1140. const orgLastPath = selectData.level === 1 ? selectData.ledger_id : '.' + selectData.ledger_id;
  1141. const newLastPath = selectData.level === 1 ? preData.ledger_id + '.' + selectData.ledger_id : '.' + preData.ledger_id + '.' + selectData.ledger_id;
  1142. const newFullPath = selectData.full_path.replace(orgLastPath, newLastPath);
  1143. try {
  1144. // 选中节点--全部后节点 order--
  1145. await this._updateSelectNextsOrder(selectData, -1);
  1146. // 选中节点 修改pid, level, order, full_path
  1147. const updateData = {
  1148. id: selectData.id,
  1149. ledger_pid: preData.ledger_id,
  1150. order: preLastChildData ? preLastChildData.order + 1 : 1,
  1151. level: selectData.level + 1,
  1152. full_path: newFullPath,
  1153. };
  1154. await this.transaction.update(this.tableName, updateData);
  1155. // 选中节点--全部子节点(含孙) level++, full_path
  1156. await this._syncDownlevelChildren(selectData, preData);
  1157. // 选中节点--前兄弟节点 is_leaf应为false
  1158. if (preData.is_leaf) {
  1159. const updateData2 = {
  1160. id: preData.id,
  1161. is_leaf: false,
  1162. };
  1163. await this.transaction.update(this.tableName, updateData2);
  1164. }
  1165. await this.transaction.commit();
  1166. } catch (err) {
  1167. await this.transaction.rollback();
  1168. throw err;
  1169. }
  1170. // 查询修改的数据
  1171. // 选中节点及子节点
  1172. const resultData1 = await this.getDataByFullPath(tenderId, newFullPath + '%');
  1173. // 选中节点--原前兄弟节点&全部后兄弟节点
  1174. const queryOrder = (preData.is_leaf || this.ctx.helper.checkZero(selectData.total_price)) ? preData.order - 1 : preData.order;
  1175. const resultData2 = await this.getNextsData(tenderId, preData.ledger_pid, queryOrder);
  1176. return { update: resultData1.concat(resultData2) };
  1177. }
  1178. /**
  1179. * 过滤data中update方式不可提交的字段
  1180. * @param {Number} id - 主键key
  1181. * @param {Object} data
  1182. * @return {Object<{id: *}>}
  1183. * @private
  1184. */
  1185. _filterUpdateInvalidField(id, data) {
  1186. const result = {
  1187. id,
  1188. };
  1189. for (const prop in data) {
  1190. if (readOnlyFields.indexOf(prop) === -1) {
  1191. result[prop] = data[prop];
  1192. }
  1193. }
  1194. return result;
  1195. }
  1196. /**
  1197. * newData中,以orgData为基准,过滤掉orgData中未定义或值相等的部分
  1198. * @param {Object} orgData
  1199. * @param {Object} newData
  1200. * @private
  1201. */
  1202. _filterChangedField(orgData, newData) {
  1203. const result = {};
  1204. let bChanged = false;
  1205. for (const prop in orgData) {
  1206. if (newData[prop] !== orgData[prop]) {
  1207. result[prop] = newData[prop];
  1208. bChanged = true;
  1209. }
  1210. }
  1211. return bChanged ? result : undefined;
  1212. }
  1213. /**
  1214. * 检查data中是否含有计算字段
  1215. * @param {Object} data
  1216. * @return {boolean}
  1217. * @private
  1218. */
  1219. _checkCalcField(data) {
  1220. for (const prop in data) {
  1221. if (calcFields.indexOf(prop) >= 0) {
  1222. return true;
  1223. }
  1224. }
  1225. return false;
  1226. }
  1227. /**
  1228. * 提交数据 - 不影响计算等未提交项
  1229. * @param {Number} tenderId - 标段id
  1230. * @param {Object} data - 提交数据
  1231. * @return {Object} - 提交后的数据
  1232. */
  1233. async updateInfo(tenderId, data) {
  1234. // 简单校验数据
  1235. if (tenderId <= 0) {
  1236. throw '标段不存在';
  1237. }
  1238. if (tenderId !== data.tender_id) {
  1239. throw '提交数据错误';
  1240. }
  1241. try {
  1242. // 过滤不可提交字段
  1243. const updateNode = await this.getDataById(data.id);
  1244. if (!updateNode || tenderId !== updateNode.tender_id || data.ledger_id !== updateNode.ledger_id) {
  1245. throw '提交数据错误';
  1246. }
  1247. const updateData = this._filterUpdateInvalidField(updateNode.id, data);
  1248. await this.db.update(this.tableName, updateData);
  1249. } catch (err) {
  1250. throw err;
  1251. }
  1252. const result = await this.getDataByNodeId(tenderId, data.ledger_id);
  1253. return result;
  1254. }
  1255. /**
  1256. * 提交多条数据 - 不影响计算等未提交项
  1257. * @param {Number} tenderId - 标段id
  1258. * @param {Array} datas - 提交数据
  1259. * @return {Array} - 提交后的数据
  1260. */
  1261. async updateInfos(tenderId, datas) {
  1262. if (tenderId <= 0) {
  1263. throw '标段不存在';
  1264. }
  1265. for (const data of datas) {
  1266. if (tenderId !== data.tender_id) {
  1267. throw '提交数据错误';
  1268. }
  1269. }
  1270. this.transaction = await this.db.beginTransaction();
  1271. try {
  1272. for (const data of datas) {
  1273. const updateNode = await this.getDataById(data.id);
  1274. if (!updateNode || tenderId !== updateNode.tender_id || data.ledger_id !== updateNode.ledger_id) {
  1275. throw '提交数据错误';
  1276. }
  1277. const updateData = this._filterUpdateInvalidField(updateNode.id, data);
  1278. await this.transaction.update(this.tableName, updateData);
  1279. }
  1280. await this.transaction.commit();
  1281. } catch (err) {
  1282. await this.transaction.rollback();
  1283. throw err;
  1284. }
  1285. const filter = [];
  1286. for (const data of datas) {
  1287. filter.push(data.id);
  1288. }
  1289. this.initSqlBuilder();
  1290. this.sqlBuilder.setAndWhere('id', {
  1291. value: filter,
  1292. operate: 'in',
  1293. });
  1294. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  1295. const resultData = await this.db.query(sql, sqlParam);
  1296. return resultData;
  1297. }
  1298. /**
  1299. * 复制粘贴整块
  1300. * @param {Number} tenderId - 标段Id
  1301. * @param {Number} selectId - 选中几点Id
  1302. * @param {Array} block - 复制节点Id
  1303. * @return {Object} - 提价后的数据(其中新增粘贴数据,只返回第一层)
  1304. */
  1305. async pasteBlock(tenderId, selectId, block) {
  1306. if ((tenderId <= 0) || (selectId <= 0)) {
  1307. return [];
  1308. }
  1309. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1310. if (!selectData) {
  1311. throw '位置数据错误';
  1312. }
  1313. const newParentPath = selectData.full_path.replace(selectData.ledger_id, '');
  1314. const copyNodes = await this.getDataByNodeIds(tenderId, block);
  1315. if (!copyNodes || copyNodes.length <= 0) {
  1316. throw '复制数据错误';
  1317. }
  1318. let bSameParent = true;
  1319. for (const node of copyNodes) {
  1320. if (node.ledger_pid !== copyNodes[0].ledger_pid) {
  1321. bSameParent = false;
  1322. break;
  1323. }
  1324. }
  1325. if (!bSameParent) {
  1326. throw '复制数据错误:仅可操作同层节点';
  1327. }
  1328. const orgParentPath = copyNodes[0].full_path.replace(copyNodes[0].ledger_id, '');
  1329. const newIds = [];
  1330. this.transaction = await this.db.beginTransaction();
  1331. try {
  1332. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1333. await this._updateSelectNextsOrder(selectData, copyNodes.length);
  1334. // 数据库创建新增节点数据
  1335. for (const node of copyNodes) {
  1336. const datas = await this.getDataByFullPath(tenderId, node.full_path + '%');
  1337. const cacheKey = keyPre + tenderId;
  1338. let maxId = parseInt(await this.cache.get(cacheKey));
  1339. if (!maxId) {
  1340. maxId = await this._getMaxNodeId(tenderId);
  1341. }
  1342. this.cache.set(cacheKey, maxId + datas.length, 'EX', this.ctx.app.config.cacheTime);
  1343. const leafBillsId = [];
  1344. // 计算粘贴数据中需更新部分
  1345. for (let index = 0; index < datas.length; index++) {
  1346. const data = datas[index];
  1347. const newId = maxId + index + 1;
  1348. const idChange = {
  1349. org: data.id,
  1350. };
  1351. delete data.id;
  1352. if (!data.is_leaf) {
  1353. for (const children of datas) {
  1354. children.full_path = children.full_path.replace('.' + data.ledger_id, '.' + newId);
  1355. if (children.ledger_pid === data.ledger_id) {
  1356. children.ledger_pid = newId;
  1357. }
  1358. }
  1359. } else {
  1360. data.full_path = data.full_path.replace('.' + data.ledger_id, '.' + newId);
  1361. }
  1362. data.ledger_id = newId;
  1363. data.full_path = data.full_path.replace(orgParentPath, newParentPath);
  1364. if (data.ledger_pid === copyNodes[0].ledger_pid) {
  1365. data.ledger_pid = selectData.ledger_pid;
  1366. data.order = selectData.order + index + 1;
  1367. }
  1368. data.level = data.level + selectData.level - copyNodes[0].level;
  1369. const newData = await this.transaction.insert(this.tableName, data);
  1370. if (data.is_leaf) {
  1371. idChange.new = newData.insertId;
  1372. leafBillsId.push(idChange);
  1373. }
  1374. newIds.push(newData.insertId);
  1375. }
  1376. for (const id of leafBillsId) {
  1377. await this.ctx.service.pos.copyBillsPosData(id.org, id.new, this.transaction);
  1378. }
  1379. }
  1380. await this.transaction.commit();
  1381. } catch (err) {
  1382. await this.transaction.rollback();
  1383. throw err;
  1384. }
  1385. // 查询应返回的结果
  1386. const order = [];
  1387. for (let i = 1; i <= copyNodes.length; i++) {
  1388. order.push(selectData.order + i);
  1389. }
  1390. const createData = await this.getDataByIds(newIds);
  1391. const updateData = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + copyNodes.length);
  1392. const posData = await this.ctx.service.pos.getPosData({ lid: newIds });
  1393. return {
  1394. ledger: { create: createData, update: updateData },
  1395. pos: posData,
  1396. };
  1397. }
  1398. /**
  1399. * 增量更新父项金额
  1400. * @param {Number} tenderId - 标段id
  1401. * @param {Object} updateMap - 增量更新数,使用更新父项的full_path为索引
  1402. * e.g: {'1.2.6.8': 30, '1.2.6.10': 40}表示'1.2.6.8'增量30,'1.2.6.10'增量40(此处同步更新'1.2.6', '1.2', '1')
  1403. * @return {Promise<void>}
  1404. * @private
  1405. */
  1406. async _increCalcParent(tenderId, updateMap) {
  1407. for (const prop in updateMap) {
  1408. this.initSqlBuilder();
  1409. this.sqlBuilder.setAndWhere('tender_id', {
  1410. value: tenderId,
  1411. operate: '=',
  1412. });
  1413. const fullPath = this.ctx.helper.explodePath(prop);
  1414. this.sqlBuilder.setAndWhere('full_path', {
  1415. value: this.ctx.helper.explodePath(prop),
  1416. operate: 'in',
  1417. });
  1418. this.sqlBuilder.setUpdateData('total_price', {
  1419. value: updateMap[prop] > 0 ? updateMap[prop] : -updateMap[prop],
  1420. selfOperate: updateMap[prop] > 0 ? '+' : '-',
  1421. });
  1422. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  1423. await this.transaction.query(sql, sqlParam);
  1424. }
  1425. }
  1426. /**
  1427. * 提交数据 - 响应计算(增量方式计算)
  1428. * @param {Number} tenderId
  1429. * @param {Object} data
  1430. * @return {Promise<*>}
  1431. */
  1432. async updateCalc(tenderId, data) {
  1433. // 简单验证数据
  1434. if (tenderId <= 0) {
  1435. throw '标段不存在';
  1436. }
  1437. if (!data) {
  1438. throw '提交数据错误';
  1439. }
  1440. const datas = data instanceof Array ? data : [data];
  1441. const ids = [];
  1442. for (const row of datas) {
  1443. if (tenderId !== row.tender_id) {
  1444. throw '提交数据错误';
  1445. }
  1446. ids.push(row.id);
  1447. }
  1448. this.transaction = await this.db.beginTransaction();
  1449. try {
  1450. for (const row of datas) {
  1451. const updateNode = await this.getDataById(row.id);
  1452. if (!updateNode || tenderId !== updateNode.tender_id || row.ledger_id !== updateNode.ledger_id) {
  1453. throw '提交数据错误';
  1454. }
  1455. let updateData;
  1456. if (this._checkCalcField(row)) {
  1457. const calcData = this.ctx.helper.updateObj(updateNode, row);
  1458. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, updateNode.unit);
  1459. this.ctx.helper.checkFieldPrecision(calcData, qtyFields, precision.value);
  1460. if (updateNode.is_leaf) {
  1461. calcData.total_price = calcData.quantity * calcData.unit_price;
  1462. calcData.deal_tp = calcData.deal_qty * calcData.unit_price;
  1463. }
  1464. const data1 = this._filterChangedField(updateNode, calcData);
  1465. updateData = this._filterUpdateInvalidField(updateNode.id, data1);
  1466. } else {
  1467. updateData = this._filterUpdateInvalidField(updateNode.id, row);
  1468. }
  1469. await this.transaction.update(this.tableName, updateData);
  1470. }
  1471. await this.transaction.commit();
  1472. } catch (err) {
  1473. await this.transaction.rollback();
  1474. throw err;
  1475. }
  1476. return { update: await this.getDataByIds(ids) };
  1477. }
  1478. /**
  1479. *
  1480. * @param tenderId
  1481. * @param xmj
  1482. * @param order
  1483. * @param parentData
  1484. * @return {Promise<*[]>}
  1485. * @private
  1486. */
  1487. async _sortBatchInsertData(tenderId, xmj, order, parentData) {
  1488. const result = [],
  1489. newIds = [];
  1490. let tp = 0;
  1491. const cacheKey = keyPre + tenderId;
  1492. let maxId = parseInt(await this.cache.get(cacheKey));
  1493. if (!maxId) {
  1494. maxId = await this._getMaxNodeId(tenderId);
  1495. }
  1496. this.cache.set(cacheKey, maxId + xmj.children.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1497. // 添加xmj数据
  1498. const parent = {
  1499. tender_id: tenderId,
  1500. ledger_id: maxId + 1,
  1501. ledger_pid: parentData.ledger_id,
  1502. is_leaf: xmj.children.length === 0,
  1503. order,
  1504. level: parentData.level + 1,
  1505. name: xmj.name,
  1506. };
  1507. parent.full_path = parentData.full_path + '.' + parent.ledger_id;
  1508. // 添加gcl数据
  1509. for (let i = 0, iLen = xmj.children.length; i < iLen; i++) {
  1510. const gcl = xmj.children[i];
  1511. const child = {
  1512. tender_id: tenderId,
  1513. ledger_id: maxId + 1 + i + 1,
  1514. ledger_pid: parent.ledger_id,
  1515. is_leaf: true,
  1516. order: i + 1,
  1517. level: parent.level + 1,
  1518. b_code: gcl.b_code,
  1519. name: gcl.name,
  1520. unit: gcl.unit,
  1521. unit_price: gcl.unit_price,
  1522. quantity: gcl.quantity,
  1523. };
  1524. child.full_path = parent.full_path + '.' + child.ledger_id;
  1525. child.total_price = child.unit_price * child.quantity;
  1526. tp = tp + child.total_price;
  1527. result.push(child);
  1528. newIds.push(child.ledger_id);
  1529. }
  1530. parent.total_price = tp;
  1531. result.push(parent);
  1532. newIds.push(parent.ledger_id);
  1533. return [result, tp, newIds];
  1534. }
  1535. /**
  1536. * 批量插入子项
  1537. * @param {Number} tenderId - 标段Id
  1538. * @param {Number} selectId - 选中节点Id
  1539. * @param {Object} data - 批量插入数据
  1540. * @return {Promise<void>}
  1541. */
  1542. async batchInsertChild(tenderId, selectId, data) {
  1543. const result = { ledger: {}, pos: null };
  1544. if ((tenderId <= 0) || (selectId <= 0)) {
  1545. return result;
  1546. }
  1547. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1548. if (!selectData) {
  1549. throw '位置数据错误';
  1550. }
  1551. this.transaction = await this.db.beginTransaction();
  1552. const newIds = [];
  1553. try {
  1554. const lastChild = await this.getLastChildData(tenderId, selectId);
  1555. // 更新父项isLeaf
  1556. if (!lastChild) {
  1557. await this.transaction.update(this.tableName, {
  1558. id: selectData.id,
  1559. is_leaf: false,
  1560. });
  1561. }
  1562. const order = lastChild ? lastChild.order : 0;
  1563. // 计算id
  1564. const cacheKey = keyPre + tenderId;
  1565. let maxId = parseInt(await this.cache.get(cacheKey));
  1566. if (!maxId) {
  1567. maxId = await this._getMaxNodeId(tenderId);
  1568. }
  1569. // 数据库创建新增节点数据
  1570. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1571. // 合并新增数据
  1572. const qd = {
  1573. tender_id: tenderId,
  1574. ledger_id: maxId + i + 1,
  1575. ledger_pid: selectData.ledger_id,
  1576. is_leaf: true,
  1577. order: order + i + 1,
  1578. level: selectData.level + 1,
  1579. b_code: data[i].b_code,
  1580. name: data[i].name,
  1581. unit: data[i].unit,
  1582. unit_price: data[i].price,
  1583. };
  1584. qd.full_path = selectData.full_path + '.' + qd.ledger_id;
  1585. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, qd.unit);
  1586. this.ctx.helper.checkFieldPrecision(qd, qtyFields, precision.value);
  1587. const insertResult = await this.transaction.insert(this.tableName, qd);
  1588. qd.id = insertResult.insertId;
  1589. newIds.push(insertResult.insertId);
  1590. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  1591. await this.calc(tenderId, insertResult.insertId, this.transaction);
  1592. }
  1593. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1594. await this.transaction.commit();
  1595. } catch (err) {
  1596. await this.transaction.rollback();
  1597. throw err;
  1598. }
  1599. // 查询应返回的结果
  1600. result.ledger.create = await this.getDataByIds(newIds);
  1601. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1602. return result;
  1603. }
  1604. /**
  1605. * 批量插入后项
  1606. * @param {Number} tenderId - 标段Id
  1607. * @param {Number} selectId - 选中节点Id
  1608. * @param {Object} data - 批量插入数据
  1609. * @return {Promise<void>}
  1610. */
  1611. async batchInsertNext(tenderId, selectId, data) {
  1612. const result = { ledger: {}, pos: null };
  1613. if ((tenderId <= 0) || (selectId <= 0)) {
  1614. return result;
  1615. }
  1616. const selectData = await this.getDataByNodeId(tenderId, selectId);
  1617. if (!selectData) {
  1618. throw '位置数据错误';
  1619. }
  1620. const parentData = await this.getDataByNodeId(tenderId, selectData.ledger_pid);
  1621. if (!parentData) {
  1622. throw '位置数据错误';
  1623. }
  1624. this.transaction = await this.db.beginTransaction();
  1625. const newIds = [];
  1626. try {
  1627. // 选中节点的所有后兄弟节点,order+粘贴节点个数
  1628. await this._updateSelectNextsOrder(selectData, data.length);
  1629. // 计算id和order
  1630. const cacheKey = keyPre + tenderId;
  1631. let maxId = parseInt(await this.cache.get(cacheKey));
  1632. if (!maxId) {
  1633. maxId = await this._getMaxNodeId(tenderId);
  1634. }
  1635. const order = selectData.order;
  1636. // 数据库创建新增节点数据
  1637. for (let i = 0, iLen = data.length; i < iLen; i++) {
  1638. // 合并新增数据
  1639. const qd = {
  1640. tender_id: tenderId,
  1641. ledger_id: maxId + i + 1,
  1642. ledger_pid: parentData.ledger_id,
  1643. is_leaf: true,
  1644. order: order + i + 1,
  1645. level: parentData.level + 1,
  1646. b_code: data[i].b_code,
  1647. name: data[i].name,
  1648. unit: data[i].unit,
  1649. unit_price: data[i].price,
  1650. };
  1651. qd.full_path = parentData.full_path + '.' + qd.ledger_id;
  1652. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, qd.unit);
  1653. this.ctx.helper.checkFieldPrecision(qd, qtyFields, precision.value);
  1654. const insertResult = await this.transaction.insert(this.tableName, qd);
  1655. qd.id = insertResult.insertId;
  1656. newIds.push(insertResult.insertId);
  1657. await this.ctx.service.pos.insertLedgerPosData(this.transaction, tenderId, qd, data[i].pos);
  1658. await this.calc(tenderId, insertResult.insertId, this.transaction);
  1659. }
  1660. this.cache.set(cacheKey, maxId + data.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1661. await this.transaction.commit();
  1662. } catch (err) {
  1663. await this.transaction.rollback();
  1664. throw err;
  1665. }
  1666. // 查询应返回的结果
  1667. result.ledger.create = await this.getDataByIds(newIds);
  1668. result.ledger.update = await this.getNextsData(selectData.tender_id, selectData.ledger_pid, selectData.order + data.length);
  1669. result.pos = await this.ctx.service.pos.getPosData({ lid: newIds });
  1670. return result;
  1671. }
  1672. /**
  1673. *
  1674. * @param {Number} tid - 标段id
  1675. * @param {Number} id - 需要计算的节点的id
  1676. * @param {Object} transaction - 操作所属事务,没有则创建
  1677. * @return {Promise<void>}
  1678. */
  1679. async calc(tid, id, transaction) {
  1680. const node = await this.getAllDataByCondition({ id });
  1681. if (!node) {
  1682. throw '数据错误';
  1683. }
  1684. const calcQtySql = 'UPDATE ??' +
  1685. ' SET `quantity` = (SELECT SUM(`quantity`) FROM ?? WHERE `lid` = ?), `total_price` = `quantity` * `unit_price`' +
  1686. ' WHERE `id` = ?';
  1687. await transaction.query(this.db.format(calcQtySql, [this.tableName, this.ctx.service.pos.tableName, id, id]));
  1688. }
  1689. /**
  1690. * 查找定位 --> 废弃
  1691. * @param tenderId
  1692. * @param nodeId
  1693. * @return {Promise<{expand: *}>}
  1694. */
  1695. async locateNode(tenderId, nodeId) {
  1696. const node = await this.getDataByNodeId(tenderId, nodeId);
  1697. if (!node) {
  1698. throw '查询数据有误';
  1699. }
  1700. const expandIds = node.full_path.split('.');
  1701. expandIds.pop();
  1702. const expandData = await this.getChildrenByParentId(tenderId, expandIds);
  1703. return { expand: expandData };
  1704. }
  1705. async _importCacheTreeNode(transaction, node) {
  1706. const data = {
  1707. tender_id: this.ctx.tender.id,
  1708. ledger_id: node.ledger_id,
  1709. ledger_pid: node.ledger_pid,
  1710. level: node.level,
  1711. order: node.order,
  1712. is_leaf: !node.children || node.children.length === 0,
  1713. full_path: node.full_path,
  1714. code: node.code,
  1715. b_code: node.b_code,
  1716. name: node.name,
  1717. unit: node.unit,
  1718. quantity: node.quantity,
  1719. unit_price: node.unit_price,
  1720. total_price: node.total_price,
  1721. dgn_qty1: node.dgn_qty1,
  1722. dgn_qty2: node.dgn_qty2,
  1723. memo: node.memo,
  1724. drawing_code: node.drawing_code,
  1725. };
  1726. const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, data.unit);
  1727. this.ctx.helper.checkFieldPrecision(data, qtyFields, precision.value);
  1728. const result = await transaction.insert(this.tableName, data);
  1729. data.id = result.insertId;
  1730. if (node.children && node.children.length > 0) {
  1731. for (const child of node.children) {
  1732. await this._importCacheTreeNode(transaction, child);
  1733. }
  1734. } else if (node.pos && node.pos.length > 0) {
  1735. await this.ctx.service.pos.insertLedgerPosData(transaction, this.ctx.tender.id, data, node.pos);
  1736. }
  1737. }
  1738. async importExcel(excelData) {
  1739. const AnalysisExcel = require('../lib/analysis_excel');
  1740. const analysisExcel = new AnalysisExcel();
  1741. const tempData = await this.ctx.service.tenderNodeTemplate.getData(true);
  1742. const cacheTree = analysisExcel.analysisData(excelData, tempData);
  1743. const cacheKey = keyPre + this.ctx.tender.id;
  1744. const orgMaxId = parseInt(await this.cache.get(cacheKey));
  1745. const transaction = await this.db.beginTransaction();
  1746. try {
  1747. await transaction.delete(this.tableName, {tender_id: this.ctx.tender.id});
  1748. await transaction.delete(this.ctx.service.pos.tableName, {tid: this.ctx.tender.id});
  1749. for (const node of cacheTree.roots) {
  1750. await this._importCacheTreeNode(transaction, node);
  1751. }
  1752. await transaction.commit();
  1753. this.cache.set(cacheKey, cacheTree.items.length + 1, 'EX', this.ctx.app.config.cacheTime);
  1754. } catch (err) {
  1755. await transaction.rollback();
  1756. if (orgMaxId) {
  1757. this.cache.set(cacheKey, orgMaxId, 'EX', this.ctx.app.config.cacheTime);
  1758. }
  1759. throw err;
  1760. }
  1761. }
  1762. }
  1763. return Ledger;
  1764. };