Commit 1421bf63 by Jaxon

Merge branch 'feature/goods-shelf' into 'SAAS+V5.8.0'

修复(商品货架工具): 完善schemaSumBy对无效值的处理并添加单元测试

See merge request !635
2 parents 8d66a53d 649aee6d
import { get, sumBy } from "lodash-es"; import { get, sumBy } from "lodash-es";
import { isZeroOrNumber } from "@/libs/number"; import { isZeroOrNumber } from "@/libs/number";
function toFiniteNumber(value) {
if (typeof value === "number") {
return Number.isFinite(value) ? value : null;
}
if (typeof value === "string" && value.trim() !== "") {
const num = Number(value);
return Number.isFinite(num) ? num : null;
}
return null;
}
export function schemaSumBy(list, name, unit = "元") { export function schemaSumBy(list, name, unit = "元") {
const sum = sumBy(list, (item) => { const rawValues = list.map(item => get(item, name));
const value = Number(get(item, name)); const hasValidNumber = rawValues.some(item => toFiniteNumber(item) !== null);
return Number.isFinite(value) ? value * 100 : 0; if (!hasValidNumber) {
return "-";
}
const sum = sumBy(rawValues, (item) => {
const value = toFiniteNumber(item);
return value === null ? 0 : value * 100;
}) / 100; }) / 100;
const value = isZeroOrNumber(sum); const value = isZeroOrNumber(sum);
return value === "-" ? value : `${value}${unit}`; return value === "-" ? value : `${value}${unit}`;
......
import { schemaSumBy } from "@/views/goods/shelfProduct/utils/calc";
describe("schemaSumBy", () => {
test("有数字, 有字符数字, 有空值时, 返回所有 有效数字的和", () => {
const list = [
{ amount: 10 },
{ amount: "20.5" },
{ amount: undefined },
{ amount: "" },
{ amount: "abc" },
{ amount: null },
];
expect(schemaSumBy(list, "amount")).toBe("30.5元");
});
test("所有都是无效数字时 undefined null '' 'ab' NaN", () => {
const list = [
{ amount: undefined },
{ amount: null },
{ amount: "" },
{ amount: "abc" },
{ amount: NaN },
];
expect(schemaSumBy(list, "amount")).toBe("-");
});
test("所有都是数字时", () => {
const list = [
{ amount: 0 },
{ amount: 0 },
{ amount: 0 },
{ amount: 4 },
];
expect(schemaSumBy(list, "amount")).toBe("4元");
});
test("有数字, 有无效值时", () => {
const list = [
{ amount: 4 },
{ amount: null },
{ amount: undefined },
{ amount: '' },
];
expect(schemaSumBy(list, "amount")).toBe("4元");
});
test("全部都是无效值时", () => {
const list = [
{ amount: NaN },
{ amount: null },
{ amount: undefined },
{ amount: '' },
];
expect(schemaSumBy(list, "amount")).toBe("-");
});
test("既有空值, 又有null, 还有0 的时候", () => {
const list = [
{ fee: null },
{ fee: "" },
{ fee: 0 },
];
expect(schemaSumBy(list, "fee")).toBe("0元");
});
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!