Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: sum query for reports #1919

Merged
merged 2 commits into from
Jul 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/app/core/export/query.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,20 @@ describe("QueryService", () => {
expect(res).toBe(1);
});

it("should allow to sum values", () => {
const data = [
{ a: 1, b: 2 },
{ a: "4" }, // also allows strings
{ b: 5 }, // not existing as 0
{ a: -2 }, // allows negative
{ a: "three" }, // skips invalid
];

const res = service.queryData("a:sum", undefined, undefined, data);

expect(res).toBe(3);
});

function queryData(query: string, from?: Date, to?: Date, data?: any) {
return service
.cacheRequiredData(query, from, to)
Expand Down
14 changes: 14 additions & 0 deletions src/app/core/export/query.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export class QueryService {
toArray: this.toArray,
unique: this.unique,
count: this.count,
sum: this.sum,
addPrefix: this.addPrefix,
toEntities: this.toEntities.bind(this),
getRelated: this.getRelated.bind(this),
Expand Down Expand Up @@ -233,6 +234,19 @@ export class QueryService {
return data ? data.length : 0;
}

/**
* Returns the (integer) sum of the provided array.
* It can also handle integers in strings, e.g. "3"
* @param data and integer array
* @private
*/
private sum(data: any[]): number {
return data.reduce((res, cur) => {
const parsed = Number.parseInt(cur);
return Number.isNaN(parsed) ? res : res + parsed;
}, 0);
}

/**
* Turns a list of ids (with the entity prefix) into a list of entities
* @param ids the array of ids with entity prefix
Expand Down