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

Export entity references both as id and as human-readable toString #2295

Merged
merged 15 commits into from
Apr 12, 2024
Merged
60 changes: 59 additions & 1 deletion src/app/core/export/download-service/download.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,34 @@ import { Entity } from "../../entity/model/entity";
import { ConfigurableEnumValue } from "../../basic-datatypes/configurable-enum/configurable-enum.interface";
import { DatabaseField } from "../../entity/database-field.decorator";
import moment from "moment";
import { EntityMapperService } from "app/core/entity/entity-mapper/entity-mapper.service";
import { School } from "app/child-dev-project/schools/model/school";
import { Child } from "app/child-dev-project/children/model/child";
import { mockEntityMapper } from "app/core/entity/entity-mapper/mock-entity-mapper-service";

describe("DownloadService", () => {
let service: DownloadService;
let mockDataTransformationService: jasmine.SpyObj<DownloadService>;
let mockedEntityMapper;
const testSchool = School.create({ name: "Test School" });
const testChild = Child.create("Test Child");

beforeEach(() => {
mockDataTransformationService = jasmine.createSpyObj([
"queryAndTransformData",
]);
mockedEntityMapper = mockEntityMapper([testSchool, testChild]);
TestBed.configureTestingModule({
providers: [
DownloadService,
{
provide: DataTransformationService,
useValue: mockDataTransformationService,
},
{
provide: EntityMapperService,
useValue: mockedEntityMapper,
},
LoggingService,
],
});
Expand Down Expand Up @@ -78,7 +90,7 @@ describe("DownloadService", () => {
'"_id","_rev","propOne","propTwo"' +
DownloadService.SEPARATOR_ROW +
'"TestForCsvEntity:1","2","first","second"';
spyOn(service, "exportFile").and.returnValue(expected);
spyOn(service, "exportFile").and.resolveTo(expected);
const result = await service.createCsv([test]);
expect(result).toEqual(expected);
});
Expand Down Expand Up @@ -114,6 +126,52 @@ describe("DownloadService", () => {
expect(columnValues).toContain('"true"');
});

it("should add columns with entity toString for referenced entities in export", async () => {
class EntityRefDownloadTestEntity extends Entity {
@DatabaseField({ dataType: "entity", label: "referenced entity" })
relatedEntity: string;
@DatabaseField({ dataType: "entity", label: "referenced entity 2" })
relatedEntity2: string;
}
const relatedEntity = testSchool;
const relatedEntity2 = testChild;

const testEntity = new EntityRefDownloadTestEntity();
testEntity.relatedEntity = relatedEntity.getId();
testEntity.relatedEntity2 = relatedEntity2.getId();

const csvExport = await service.createCsv([testEntity]);

const rows = csvExport.split(DownloadService.SEPARATOR_ROW);
expect(rows).toHaveSize(1 + 1); // includes 1 header line
const columnValues = rows[1].split(DownloadService.SEPARATOR_COL);
expect(columnValues).toHaveSize(4);
expect(columnValues).toContain('"' + relatedEntity.getId() + '"');
expect(columnValues).toContain('"' + relatedEntity.toString() + '"');
expect(columnValues).toContain('"' + relatedEntity2.getId() + '"');
expect(columnValues).toContain('"' + relatedEntity2.toString() + '"');
});

it("should add column with entity toString for referenced array of entities in export", async () => {
class EntityRefDownloadTestEntity extends Entity {
@DatabaseField({ dataType: "entity-array", label: "referenced entities" })
relatedEntitiesArray: string[];
}
const testEntity = new EntityRefDownloadTestEntity();
testEntity.relatedEntitiesArray = [testSchool.getId(), testChild.getId()];

const csvExport = await service.createCsv([testEntity]);

const rows = csvExport.split(DownloadService.SEPARATOR_ROW);
expect(rows).toHaveSize(1 + 1); // includes 1 header line
const columnValues = rows[1].split(DownloadService.SEPARATOR_COL);
expect(columnValues).toHaveSize(4);
expect(columnValues).toContain('"' + testSchool.getId() + "");
expect(columnValues).toContain('"' + testSchool.toString() + "");
expect(columnValues).toContain("" + testChild.getId() + '"');
expect(columnValues).toContain("" + testChild.toString() + '"');
});

it("should export all properties using object keys as headers, if no schema is available", async () => {
const docs = [
{ _id: "Test:1", name: "Child 1" },
Expand Down
62 changes: 48 additions & 14 deletions src/app/core/export/download-service/download.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import { DataTransformationService } from "../data-transformation-service/data-t
import { transformToReadableFormat } from "../../common-components/entities-table/value-accessor/value-accessor";
import { Papa } from "ngx-papaparse";
import { EntitySchemaField } from "app/core/entity/schema/entity-schema-field";
import { Entity } from "app/core/entity/model/entity";
import { EntityDatatype } from "app/core/basic-datatypes/entity/entity.datatype";
import { EntityArrayDatatype } from "app/core/basic-datatypes/entity-array/entity-array.datatype";
import { EntityMapperService } from "app/core/entity/entity-mapper/entity-mapper.service";

/**
* This service allows to start a download process from the browser.
Expand All @@ -22,6 +26,7 @@ export class DownloadService {
private dataTransformationService: DataTransformationService,
private papa: Papa,
private loggingService: LoggingService,
private entityMapperService: EntityMapperService,
) {}

/**
Expand Down Expand Up @@ -110,28 +115,30 @@ export class DownloadService {
});
}

const result = this.exportFile(data, entityConstructor);
const result = await this.exportFile(data, entityConstructor);
return result;
}

exportFile(data: any[], entityConstructor: { schema: any }) {
async exportFile(data: any[], entityConstructor: { schema: any }) {
const entitySchema = entityConstructor.schema;
const columnLabels = new Map<string, EntitySchemaField>();

entitySchema.forEach((value: { label: EntitySchemaField }, key: string) => {
if (value.label) columnLabels.set(key, value.label);
});

const exportEntities = data.map((item) => {
let newItem = {};
for (const key in item) {
if (columnLabels.has(key)) {
newItem[key] = item[key];
const columnLabels = new Map<string, string>();

entitySchema.forEach((value: EntitySchemaField, key: string) => {
if (value.label) {
columnLabels.set(key, value.label);
if (
value.dataType === EntityDatatype.dataType ||
value.dataType === EntityArrayDatatype.dataType
) {
columnLabels.set(key + "_readable", value.label + "_readable");
}
}
return newItem;
});

const exportEntities = await Promise.all(
data.map(async (item) => this.mapEntity(item, columnLabels)),
);

const columnKeys: string[] = Array.from(columnLabels.keys());
const labels: any[] = Array.from(columnLabels.values());
const orderedData: any[] = exportEntities.map((item) =>
Expand All @@ -149,4 +156,31 @@ export class DownloadService {
},
);
}

private async mapEntity(item: Entity, columnLabels): Promise<Object> {
const newItem = {};
for (const key in item) {
if (columnLabels.has(key)) {
newItem[key] = item[key];
}
if (columnLabels.has(key + "_readable")) {
const relatedEntitiesIds: string[] = Array.isArray(item[key])
? item[key]
: item[key].split();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why split here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The item[key].split() was meant to build an array containing the string as single value. But [item[key]] is simpler and shorter.

let relatedEntitiesToStrings: string[] = [];
for (const relatedEntityId of relatedEntitiesIds) {
relatedEntitiesToStrings.push(
(
await this.entityMapperService.load(
Entity.extractTypeFromId(relatedEntityId),
relatedEntityId,
)
).toString(),
);
}
newItem[key + "_readable"] = relatedEntitiesToStrings;
}
}
return newItem;
}
}
Loading