ledger.js 85 KB

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