tree_expr_calc.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const TreeExprCalc = (function(){
  10. const calcRela = {
  11. calcType: {zero: 0, direct: 1, cache: 2, sortCache: 4},
  12. SerialReg: new RegExp('<<f[0-9]+\\$[a-z]+>>', 'ig'),
  13. SerialFirstReg: new RegExp('^<<f[0-9]+\\$[a-z]+>>', 'i'),
  14. IdReg: new RegExp('<<[a-z0-9\-]+\\$[a-z]+>>', 'ig'),
  15. OrderReg: new RegExp('f[0-9]+', 'ig'),
  16. valueChar: '$',
  17. calcCache: {},
  18. error: { loop: '', deep: '' },
  19. // 计算必须项
  20. tree: null,
  21. decimal: null,
  22. calcField: null,
  23. getCalcNum: null,
  24. calcCacheFun: null,
  25. exprCacheKey: [],
  26. exprFieldsIndex: {},
  27. exprCacheFields: [],
  28. errorMsg: true,
  29. };
  30. const getCalcField = function(value) {
  31. return calcRela.exprFieldsIndex[value];
  32. };
  33. const init = function(setting) {
  34. calcRela.tree = setting.tree;
  35. calcRela.decimal = setting.decimal || { qty: 2, tp: 0 };
  36. calcRela.calcField = setting.calcField || { qty: 'quantity', tp: 'total_price' };
  37. setCalcType(setting.calcType || calcRela.calcType.zero);
  38. calcRela.calcCacheFun = setting.calcCacheFun;
  39. if (setting.exprFieldsIndex) calcRela.exprFieldsIndex = setting.exprFieldsIndex;
  40. if (setting.exprCacheKey) {
  41. calcRela.exprCacheKey = setting.exprCacheKey;
  42. calcRela.exprCacheFields = calcRela.exprCacheKey.map(x => { return getCalcField(x); });
  43. }
  44. calcRela.errorMsg = setting.errorMsg || true;
  45. calcRela.precision = setting.precision;
  46. };
  47. const findPrecision = function(list, unit) {
  48. if (!unit) return list.other;
  49. for (const p in list) {
  50. if (list[p].unit && list[p].unit === unit) {
  51. return list[p];
  52. }
  53. }
  54. return list.other;
  55. };
  56. const checkExprValid = function(expr, invalidOrders = []) {
  57. if (!expr) return [true, ''];
  58. const param = [];
  59. let num = '';
  60. for (let i = 0, iLen = expr.length; i < iLen; i++) {
  61. const subExpr = expr.substring(i, expr.length);
  62. if (/^[\d\.%]+/.test(expr[i])) {
  63. num = num + expr[i];
  64. } else if (calcRela.SerialFirstReg.test(subExpr)) {
  65. if (num !== '') {
  66. param.push({type: 'num', value: num});
  67. num = '';
  68. }
  69. const order = calcRela.SerialFirstReg.exec(subExpr);
  70. param.push({type: 'order', value: order[0]});
  71. i = i + order[0].length - 1;
  72. } else if (expr[i] === '(') {
  73. if (num !== '') {
  74. param.push({type: 'num', value: num});
  75. num = '';
  76. }
  77. param.push({type: 'left', value: '('});
  78. } else if (expr[i] === ')') {
  79. if (num !== '') {
  80. param.push({type: 'num', value: num});
  81. num = '';
  82. }
  83. param.push({type: 'right', value: ')'});
  84. } else if (/^[\+\-*\/]/.test(expr[i])) {
  85. if (num !== '') {
  86. param.push({type: 'num', value: num});
  87. num = '';
  88. }
  89. param.push({type: 'calc', value: expr[i]});
  90. } else {
  91. return [false, '输入的表达式含有非法字符: ' + expr[i]];
  92. }
  93. }
  94. if (num !== '') {
  95. param.push({type: 'num', value: num});
  96. num = '';
  97. }
  98. if (param.length === 0) return [true, ''];
  99. if (param.length > 1) {
  100. if (param[0].value === '-' && param[1].type === 'num') {
  101. param[1].value = '-' + param[1].value;
  102. param.shift();
  103. }
  104. }
  105. const iLen = param.length;
  106. let iLeftCount = 0, iRightCount = 0;
  107. for (const [i, p] of param.entries()) {
  108. if (p.type === 'calc') {
  109. if (i === 0 || i === iLen - 1)
  110. return [false, '输入的表达式非法:计算符号' + p.value + '前后应有数字或计算基数'];
  111. }
  112. if (p.type === 'num') {
  113. num = p.value.replace('%', '');
  114. if (p.value.length - num.length > 1)
  115. return [false, '输入的表达式非法:' + p.value + '不是一个有效的数字'];
  116. num = _.toNumber(num);
  117. if (num === undefined || num === null || _.isNaN(num))
  118. return [false, '输入的表达式非法:' + p.value + '不是一个有效的数字'];
  119. if (i > 0) {
  120. if (param[i - 1].type !== 'calc' && param[i - 1].type !== 'left') {
  121. return [false, '输入的表达式非法:' + p.value + '前应有运算符'];
  122. } else if (param[i - 1].value === '/' && num === 0) {
  123. return [false, '输入的表达式非法:请勿除0'];
  124. }
  125. }
  126. }
  127. if (p.type === 'order') {
  128. const match = invalidOrders.find(x => { p.value.indexOf(`f${x.orderStr}$`) > 0; });
  129. if (match) return [false, `输入的表达式非法:循环引用,请勿引用${match.orderStr}`];
  130. if (i > 0) {
  131. if (param[i - 1].type !== 'calc' && param[i - 1].type !== 'left') {
  132. return [false, '输入的表达式非法:' + p.value.replace(/</ig, '&lt;').replace(/>/ig, '&gt;') + '前应有运算符'];
  133. }
  134. }
  135. }
  136. if (p.type === 'left') {
  137. iLeftCount += 1;
  138. if (i !== 0 && param[i-1].type !== 'calc')
  139. return [false, '输入的表达式非法:(前应有运算符'];
  140. }
  141. if (p.type === 'right') {
  142. iRightCount += 1;
  143. if (i !== iLen - 1 && param[i+1].type !== 'calc')
  144. return [false, '输入的表达式非法:)后应有运算符'];
  145. if (iRightCount > iLeftCount)
  146. return [false, '输入的表达式非法:")"前无对应的"("'];
  147. }
  148. }
  149. if (iLeftCount > iRightCount)
  150. return [false, '输入的表达式非法:"("后无对应的")"'];
  151. return [true, ''];
  152. };
  153. const _getCalcNumZero = function (node, field) {
  154. return node.calc_expr && calcRela.exprInitFields.indexOf(field) >= 0 ? 0 : node[field] || 0;
  155. };
  156. const _getCalcNumDirect = function (node, field) {
  157. return node[field] || 0;
  158. };
  159. const _getCalcNumCache = function (node, field) {
  160. if (node.calc_expr && calcRela.exprCacheFields.indexOf(field) >= 0) {
  161. return calcRela.calcCache[node.id] ? calcRela.calcCache[node.id][field] || 0 : 0;
  162. }
  163. return node[field] || 0;
  164. };
  165. const getIdParamValue = function(idParam) {
  166. const [id, value] = idParam.substring(2, idParam.length - 2).split(calcRela.valueChar);
  167. const node = calcRela.tree.nodes.find(x => { return x.id === id; });
  168. if (!node) return 0;
  169. const calcField = getCalcField(value);
  170. if (!node.children || node.children.length === 0) {
  171. return calcRela.getCalcNum(node, calcField);
  172. } else {
  173. const posterity = calcRela.tree.getLeafPosterity(node);
  174. const calcMap = posterity.map(x => { return calcRela.getCalcNum(x, calcField) });
  175. return ZhCalc.sum(calcMap);
  176. }
  177. };
  178. const calcExpr = function(expr) {
  179. if (!expr) return 0;
  180. let formula = expr;
  181. const idParam = expr.match(calcRela.IdReg);
  182. if (idParam) {
  183. for (const ip of idParam) {
  184. formula = formula.replace(ip, getIdParamValue(ip));
  185. }
  186. }
  187. return [formula, math.evaluate(formula)];
  188. };
  189. const addCache = function(expr) {
  190. const cache = { id: expr.id };
  191. if (expr.calcField === 'qty') {
  192. const precision = findPrecision(calcRela.precision, expr.unit);
  193. cache[calcRela.calcField.qty] = ZhCalc.round(expr.value, precision.value);
  194. cache[calcRela.calcField.tp] = ZhCalc.mul(cache[calcRela.calcField.qty], expr.unit_price, calcRela.decimal.tp);
  195. } else if (expr.calcField === 'tp') {
  196. cache[calcRela.calcField.qty] = 0;
  197. cache[calcRela.calcField.tp] = ZhCalc.round(expr.value, calcRela.decimal.tp);
  198. }
  199. if (calcRela.calcCacheFun) calcRela.calcCacheFun(cache, expr);
  200. calcRela.calcCache[expr.id] = cache;
  201. };
  202. const sortExprList = function(exprList) {
  203. const exprIds = exprList.map(x => { return x.id; });
  204. exprList.forEach(x => {
  205. x.sort = calcRela.tree.nodes.findIndex(n => { return n.id === x.id; });
  206. x.relaExprId = [];
  207. const idParam = x.expr.match(calcRela.IdReg);
  208. if (idParam) {
  209. for (const ip of idParam) {
  210. const [id, value] = ip.substring(2, ip.length - 2).split(calcRela.valueChar);
  211. if (value.indexOf('bq') < 0) continue;
  212. const node = calcRela.tree.nodes.find(x => { return x.id === id; });
  213. if (!node) continue;
  214. if (!node.children || node.children.length === 0) {
  215. if (exprIds.indexOf(node.id) >= 0) x.relaExprId.push(node.id);
  216. } else {
  217. const posterity = calcRela.tree.getLeafPosterity(node);
  218. posterity.forEach(p => { if (exprIds.indexOf(p.id) >= 0) x.relaExprId.push(p.id); });
  219. }
  220. }
  221. }
  222. });
  223. exprList.forEach(x => {
  224. if (x.relaExprId.length === 0) {
  225. x.calcSort = 1;
  226. return;
  227. }
  228. let calcSort = 1;
  229. let calcExprId = [...x.relaExprId];
  230. while (calcExprId.length > 0 && calcSort <= 100) {
  231. const sortIds = [];
  232. for (const id of calcExprId) {
  233. const relaNode = exprList.find(y => { return y.id === id; });
  234. if (relaNode.relaExprId.length > 0) {
  235. sortIds.push(...relaNode.relaExprId);
  236. }
  237. }
  238. calcSort++;
  239. if (sortIds.indexOf(x.id) >= 0) {
  240. calcSort = 'max';
  241. break;
  242. }
  243. calcExprId = sortIds;
  244. }
  245. if (calcSort > 100 && !calcRela.error.deep) calcRela.error.deep = x.id;
  246. if (calcSort === 'max' && !calcRela.error.loop) calcRela.error.loop = x.id;
  247. x.calcSort = calcSort;
  248. });
  249. exprList.sort((x, y) => {
  250. if (x.calcSort === 'max') return 1000;
  251. if (x.calcSort === 'max') return -1000;
  252. return x.calcSort - y.calcSort;
  253. });
  254. };
  255. const _initCache = function() {
  256. calcRela.calcCache = {};
  257. calcRela.error.deep = '';
  258. calcRela.error.loop = '';
  259. };
  260. const checkError = function() {
  261. if (!calcRela.errorMsg) return;
  262. if (calcRela.error.loop) {
  263. const nodeIndex = calcRela.tree.nodes.findIndex(x => { return x.id === calcRela.error.loop; });
  264. const node = calcRela.tree.nodes[nodeIndex];
  265. const hintCode = (node.code || '') + (node.b_code || '');
  266. toastr.warning(`第${nodeIndex + 1}行 ${hintCode} 公式存在循环计算,请检查`);
  267. return;
  268. }
  269. if (calcRela.error.deep) {
  270. const nodeIndex = calcRela.tree.nodes.findIndex(x => { return x.id === calcRela.error.deep; });
  271. const node = calcRela.tree.nodes[nodeIndex];
  272. const hintCode = (node.code || '') + (node.b_code || '');
  273. toastr.warning(`第${nodeIndex + 1}行 ${hintCode} 公式引用层次过深,请检查`);
  274. return;
  275. }
  276. };
  277. const calcAllExpr = function(exprList) {
  278. _initCache();
  279. if (calcRela.sort) sortExprList(exprList);
  280. for (const expr of exprList) {
  281. [expr.formula, expr.value] = calcExpr(expr.expr);
  282. addCache(expr);
  283. }
  284. checkError();
  285. const result = JSON.parse(JSON.stringify(calcRela.error));
  286. _initCache();
  287. return result;
  288. };
  289. const expr2ExprStr = function(expr) {
  290. if (!expr) return '';
  291. let formula = expr;
  292. const idParam = expr.match(calcRela.IdReg);
  293. if (idParam) {
  294. for (const ip of idParam) {
  295. const [id, value] = ip.substring(2, ip.length - 2).split(calcRela.valueChar);
  296. const order = calcRela.tree.nodes.findIndex(x => { return x.id === id });
  297. const orderParam = `<<f${order + 1}$${value}>>`;
  298. formula = formula.replace(ip, orderParam);
  299. }
  300. }
  301. return formula;
  302. };
  303. const exprStr2Expr = function(exprStr) {
  304. if (!exprStr) return '';
  305. let formula = exprStr;
  306. const orderParam = exprStr.match(calcRela.SerialReg);
  307. if (orderParam) {
  308. for (const op of orderParam) {
  309. const orderStr = op.match(calcRela.OrderReg)[0];
  310. const order = parseInt(orderStr.substring(1, op.length));
  311. const node = calcRela.tree.nodes[order - 1];
  312. const idParam = op.replace(orderStr, node.id);
  313. formula = formula.replace(op, idParam);
  314. }
  315. }
  316. return formula;
  317. };
  318. const setCalcType = function (calcType) {
  319. if (calcType === calcRela.calcType.zero) calcRela.getCalcNum = _getCalcNumZero;
  320. if (calcType === calcRela.calcType.direct) calcRela.getCalcNum = _getCalcNumDirect;
  321. if (calcType === calcRela.calcType.cache) calcRela.getCalcNum = _getCalcNumCache;
  322. if (calcType === calcRela.calcType.sortCache) calcRela.getCalcNum = _getCalcNumCache;
  323. calcRela.sort = calcType === calcRela.calcType.sortCache;
  324. };
  325. return {
  326. calcType: calcRela.calcType,
  327. init, setCalcType,
  328. checkExprValid, expr2ExprStr, exprStr2Expr,
  329. calcExpr, calcAllExpr,
  330. }
  331. })();