ledger.js 79 KB

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