ledger.js 81 KB

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