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

Other entity login #2143

Merged
merged 30 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
097373e
session manager can load other entities
TheSlimvReal Dec 21, 2023
7bf56b9
removed deprecated todo?
TheSlimvReal Dec 21, 2023
64c48bc
user security component is entity agnostic
TheSlimvReal Dec 21, 2023
3d2daa8
mage todo completion entity agnostic
TheSlimvReal Dec 22, 2023
4df0a8f
added test
TheSlimvReal Dec 22, 2023
9cf9313
entity select can handle foreign entity references
TheSlimvReal Dec 22, 2023
d50d44a
fix display entity array to show entities again
TheSlimvReal Dec 22, 2023
15ad1ab
display entity array shows foreign entities
TheSlimvReal Dec 22, 2023
079ab70
display single entity allows foreign entities to be displayed
TheSlimvReal Dec 22, 2023
a830f9c
improved error message in MockEntityMapper
TheSlimvReal Dec 22, 2023
79506e4
added support for foreign entities in DisplayEntityComponent
TheSlimvReal Dec 22, 2023
9e15830
use local storage to save paginator settings
TheSlimvReal Dec 22, 2023
409169d
Merge branch 'master' into other_entity_login
TheSlimvReal Feb 5, 2024
5f93ef1
fixed tests
TheSlimvReal Feb 5, 2024
7282b5f
removed further usages of short id
TheSlimvReal Feb 5, 2024
a437de6
made user entity optional
TheSlimvReal Feb 6, 2024
dd03437
made `username` claim optional
TheSlimvReal Feb 6, 2024
cdfee7f
fixed issue with unassigned default values on array properties
TheSlimvReal Feb 6, 2024
4c6f3e4
only loading missing entities of other types in entity select
TheSlimvReal Feb 6, 2024
fb6b4b2
using ID as username in keycloak
TheSlimvReal Feb 6, 2024
fc112fc
some code cleanup
TheSlimvReal Feb 6, 2024
878d5a6
Merge branch 'master' into other_entity_login
TheSlimvReal Feb 6, 2024
74f45cc
Update src/app/core/session/session-service/session-manager.service.s…
TheSlimvReal Feb 7, 2024
2e261a7
added interface for parsed JWT
TheSlimvReal Feb 7, 2024
8b663a4
automatically adding User prefix to tokens with short entityId
TheSlimvReal Feb 7, 2024
d1ec5c0
showing linked user entity in user account page
TheSlimvReal Feb 7, 2024
211e229
removed account manager role from demo mode
TheSlimvReal Feb 7, 2024
f97689a
improve user profile ui
sleidig Feb 8, 2024
91216b8
Merge branch 'master' into other_entity_login
TheSlimvReal Feb 8, 2024
2ca6de3
removed unused styles
TheSlimvReal Feb 8, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,16 @@ describe("DisplayEntityArrayComponent", () => {

expect(component.entities).toEqual(expectedEntities);
});

it("should load entities of not configured type", async () => {
component.config = School.ENTITY_TYPE;
const existingChild = testEntities.find(
(e) => e.getType() === Child.ENTITY_TYPE,
);
component.value = [existingChild.getId(true)];

await component.ngOnInit();

expect(component.entities).toEqual([existingChild]);
});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, OnInit } from "@angular/core";
import { ChangeDetectorRef, Component, OnInit } from "@angular/core";
import { Entity } from "../../../entity/model/entity";
import { EntityMapperService } from "../../../entity/entity-mapper/entity-mapper.service";
import { ViewDirective } from "../../../entity/default-datatype/view.directive";
Expand All @@ -22,21 +22,24 @@ export class DisplayEntityArrayComponent

entities: Entity[];

constructor(private entityMapper: EntityMapperService) {
constructor(
private entityMapper: EntityMapperService,
private changeDetector: ChangeDetectorRef,
) {
super();
}

async ngOnInit() {
const entityIds: string[] = this.value || [];
if (entityIds.length < this.aggregationThreshold) {
const entityPromises = entityIds.map((entityId) => {
const type =
typeof this.config === "string"
? this.config
: Entity.extractTypeFromId(entityId);
const type = entityId.includes(":")
? Entity.extractTypeFromId(entityId)
: this.config;
return this.entityMapper.load(type, entityId);
});
this.entities = await Promise.all(entityPromises);
this.changeDetector.detectChanges();
TheSlimvReal marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,25 @@ import {
componentRegistry,
ComponentRegistry,
} from "../../../../dynamic-components";
import {
mockEntityMapper,
MockEntityMapperService,
} from "../../../entity/entity-mapper/mock-entity-mapper-service";
import { LoggingService } from "../../../logging/logging.service";

describe("DisplayEntityComponent", () => {
let component: DisplayEntityComponent;
let fixture: ComponentFixture<DisplayEntityComponent>;
let mockEntityMapper: jasmine.SpyObj<EntityMapperService>;
let entityMapper: MockEntityMapperService;
let mockRouter: jasmine.SpyObj<Router>;

beforeEach(async () => {
mockEntityMapper = jasmine.createSpyObj(["load"]);
mockEntityMapper.load.and.resolveTo(new Child());
entityMapper = mockEntityMapper();
mockRouter = jasmine.createSpyObj(["navigate"]);
await TestBed.configureTestingModule({
imports: [DisplayEntityComponent],
providers: [
{ provide: EntityMapperService, useValue: mockEntityMapper },
{ provide: EntityMapperService, useValue: entityMapper },
{ provide: EntityRegistry, useValue: entityRegistry },
{ provide: ComponentRegistry, useValue: componentRegistry },
{ provide: Router, useValue: mockRouter },
Expand All @@ -48,7 +52,7 @@ describe("DisplayEntityComponent", () => {

it("should use the block component when available", async () => {
const school = new School();
mockEntityMapper.load.and.resolveTo(school);
entityMapper.add(school);

component.entity = new ChildSchoolRelation();
component.id = "schoolId";
Expand All @@ -57,10 +61,6 @@ describe("DisplayEntityComponent", () => {
await component.ngOnInit();

expect(component.entityBlockComponent).toEqual(School.getBlockComponent());
expect(mockEntityMapper.load).toHaveBeenCalledWith(
school.getType(),
school.getId(),
);
expect(component.entityToDisplay).toEqual(school);
});

Expand All @@ -71,4 +71,29 @@ describe("DisplayEntityComponent", () => {

expect(mockRouter.navigate).toHaveBeenCalledWith(["/child", "1"]);
});

it("should show entities which are not of the configured type", async () => {
const child = new Child();
entityMapper.add(child);
component.entityId = child.getId(true);
component.config = School.ENTITY_TYPE;

await component.ngOnInit();

expect(component.entityToDisplay).toEqual(child);
});

it("should log a warning if entity cannot be loaded", async () => {
const warnSpy = spyOn(TestBed.inject(LoggingService), "warn");
const child = new Child("not_existing");
component.entityId = child.getId(true);
component.config = School.ENTITY_TYPE;

await component.ngOnInit();

expect(warnSpy).toHaveBeenCalledWith(
jasmine.stringContaining(child.getId(true)),
);
expect(component.entityToDisplay).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { EntityMapperService } from "../../../entity/entity-mapper/entity-mapper
import { Router } from "@angular/router";
import { NgClass, NgIf } from "@angular/common";
import { DynamicComponentDirective } from "../../../config/dynamic-components/dynamic-component.directive";
import { LoggingService } from "../../../logging/logging.service";

@DynamicComponent("DisplayEntity")
@Component({
Expand Down Expand Up @@ -35,29 +36,38 @@ export class DisplayEntityComponent
constructor(
private entityMapper: EntityMapperService,
private router: Router,
private logger: LoggingService,
private changeDetector: ChangeDetectorRef,
) {
super();
}

async ngOnInit() {
if (!this.entityToDisplay) {
this.entityType = this.entityType ?? this.config;
this.entityId = this.entityId ?? this.value;
this.entityType = this.entityId.includes(":")
? Entity.extractTypeFromId(this.entityId)
: this.entityType ?? this.config;
if (!this.entityType || !this.entityId) {
return;
}
this.entityToDisplay = await this.entityMapper.load(
this.entityType,
this.entityId,
);
this.changeDetector.detectChanges();
try {
this.entityToDisplay = await this.entityMapper.load(
this.entityType,
this.entityId,
);
TheSlimvReal marked this conversation as resolved.
Show resolved Hide resolved
} catch (e) {
this.logger.warn(
`[DISPLAY_ENTITY] Could not find entity with ID: ${this.entityId}: ${e}`,
);
}
}
if (this.entityToDisplay) {
this.entityBlockComponent = this.entityToDisplay
.getConstructor()
.getBlockComponent();
}
this.changeDetector.detectChanges();
}

showDetailsPage() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,20 @@ import { ChildSchoolRelation } from "../../../../child-dev-project/children/mode
import { School } from "../../../../child-dev-project/schools/model/school";
import { MockedTestingModule } from "../../../../utils/mocked-testing.module";
import { FormControl } from "@angular/forms";
import { Child } from "../../../../child-dev-project/children/model/child";
import { LoggingService } from "../../../logging/logging.service";

describe("EditSingleEntityComponent", () => {
let component: EditSingleEntityComponent;
let fixture: ComponentFixture<EditSingleEntityComponent>;
let loadTypeSpy: jasmine.Spy;
let entityMapper: EntityMapperService;

beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [EditSingleEntityComponent, MockedTestingModule.withState()],
providers: [EntityFormService],
}).compileComponents();
loadTypeSpy = spyOn(TestBed.inject(EntityMapperService), "loadType");
entityMapper = TestBed.inject(EntityMapperService);
}));

beforeEach(() => {
Expand All @@ -45,11 +47,39 @@ describe("EditSingleEntityComponent", () => {
it("should load all entities of the given type as options", async () => {
const school1 = School.create({ name: "First School" });
const school2 = School.create({ name: "Second School " });
loadTypeSpy.and.resolveTo([school1, school2]);
await entityMapper.saveAll([school1, school2]);
component.formFieldConfig.additional = School.ENTITY_TYPE;

await component.ngOnInit();

expect(loadTypeSpy).toHaveBeenCalled();
expect(component.entities).toEqual([school1, school2]);
expect(component.entities).toEqual(
jasmine.arrayWithExactContents([school1, school2]),
);
});

it("should add selected entity of a not-configured type to available entities", async () => {
const someSchools = [new School(), new School()];
const selectedChild = new Child();
await entityMapper.saveAll(someSchools.concat(selectedChild));
component.formFieldConfig.additional = School.ENTITY_TYPE;
component.formControl.setValue(selectedChild.getId(true));

await component.ngOnInit();

expect(component.entities).toEqual(
jasmine.arrayWithExactContents(someSchools.concat(selectedChild)),
);
});

it("should log warning if entity is selected that cannot be found", async () => {
const warnSpy = spyOn(TestBed.inject(LoggingService), "warn");
component.formFieldConfig.additional = Child.ENTITY_TYPE;
component.formControl.setValue("missing_child");

await component.ngOnInit();

expect(warnSpy).toHaveBeenCalledWith(
jasmine.stringContaining("missing_child"),
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { MatFormFieldModule } from "@angular/material/form-field";
import { FontAwesomeModule } from "@fortawesome/angular-fontawesome";
import { NgIf } from "@angular/common";
import { ErrorHintComponent } from "../../../common-components/error-hint/error-hint.component";
import { LoggingService } from "../../../logging/logging.service";

@DynamicComponent("EditSingleEntity")
@Component({
Expand All @@ -32,17 +33,37 @@ export class EditSingleEntityComponent
implements OnInit
{
entities: Entity[] = [];
entityToId = (e: Entity) => e?.getId();
entityToId = (e: Entity) => e?.getId(true);

constructor(private entityMapperService: EntityMapperService) {
constructor(
private entityMapper: EntityMapperService,
private logger: LoggingService,
) {
super();
}

async ngOnInit() {
super.ngOnInit();
this.entities = await this.entityMapperService.loadType(
this.formFieldConfig.additional,
const availableEntities = await this.entityMapper.loadType(this.additional);
const selected = this.formControl.value;
if (
selected &&
!availableEntities.some(
(e) => e.getId(true) === selected || e.getId() === selected,
)
) {
try {
const type = Entity.extractTypeFromId(selected);
const entity = await this.entityMapper.load(type, selected);
availableEntities.push(entity);
} catch (e) {
this.logger.warn(
`[EDIT_SINGLE_ENTITY] Could not find entity with ID: ${selected}: ${e}`,
);
}
}
this.entities = availableEntities.sort((e1, e2) =>
e1.toString().localeCompare(e2.toString()),
);
this.entities.sort((e1, e2) => e1.toString().localeCompare(e2.toString()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ interface SelectableOption<O, V> {
selected: boolean;
}

/** Custom `MatFormFieldControl` for telephone number input. */
@Component({
selector: "app-basic-autocomplete",
templateUrl: "basic-autocomplete.component.html",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,15 +180,15 @@ describe("EntityFormService", () => {

schema.defaultValue = PLACEHOLDERS.CURRENT_USER;
form = service.createFormGroup([{ id: "test" }], new Entity());
expect(form.get("test")).toHaveValue(TEST_USER);
expect(form.get("test")).toHaveValue(`User:${TEST_USER}`);

schema.dataType = ArrayDatatype.dataType;
form = service.createFormGroup([{ id: "test" }], new Entity());
expect(form.get("test")).toHaveValue([TEST_USER]);
expect(form.get("test")).toHaveValue([`User:${TEST_USER}`]);

schema.dataType = EntityArrayDatatype.dataType;
form = service.createFormGroup([{ id: "test" }], new Entity());
expect(form.get("test")).toHaveValue([TEST_USER]);
expect(form.get("test")).toHaveValue([`User:${TEST_USER}`]);

Entity.schema.delete("test");
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export class EntityFormService {
newVal = new Date();
break;
case PLACEHOLDERS.CURRENT_USER:
newVal = this.currentUser.value.getId();
newVal = this.currentUser.value.getId(true);
TheSlimvReal marked this conversation as resolved.
Show resolved Hide resolved
break;
default:
newVal = schema.defaultValue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Child } from "../../../child-dev-project/children/model/child";
import { School } from "../../../child-dev-project/schools/model/school";
import { MockedTestingModule } from "../../../utils/mocked-testing.module";
import { LoginState } from "../../session/session-states/login-state.enum";
import { LoggingService } from "../../logging/logging.service";

describe("EntitySelectComponent", () => {
let component: EntitySelectComponent<any>;
Expand Down Expand Up @@ -139,12 +140,10 @@ describe("EntitySelectComponent", () => {

component.unselectEntity(testUsers[0]);

const remainingChildren = testUsers
.filter((c) => c.getId() !== testUsers[0].getId())
.map((c) => c.getId());
expect(component.selectionChange.emit).toHaveBeenCalledWith(
remainingChildren,
);
const remainingUsers = testUsers
.filter((u) => u.getId() !== testUsers[0].getId())
.map((u) => u.getId(true));
expect(component.selectionChange.emit).toHaveBeenCalledWith(remainingUsers);
});

it("adds a new entity if it matches a known entity", fakeAsync(() => {
Expand Down Expand Up @@ -224,6 +223,30 @@ describe("EntitySelectComponent", () => {
expect(component.filteredEntities).toEqual([...testUsers, ...testChildren]);
}));

it("should show selected entities of type that is not configured", fakeAsync(() => {
component.entityType = [User.ENTITY_TYPE];
component.selection = [testUsers[0].getId(), testChildren[0].getId(true)];
tick();
fixture.detectChanges();
expect(component.selectedEntities).toEqual([testUsers[0], testChildren[0]]);
expect(component.allEntities).toEqual(testUsers);
expect(component.filteredEntities).toEqual(
jasmine.arrayWithExactContents(testUsers.slice(1)),
);
}));

it("should not fail if entity cannot be found", fakeAsync(() => {
const warnSpy = spyOn(TestBed.inject(LoggingService), "warn");
component.entityType = User.ENTITY_TYPE;
component.selection = [testUsers[0].getId(), "missing_user"];
tick();
fixture.detectChanges();
expect(warnSpy).toHaveBeenCalledWith(
jasmine.stringContaining("missing_user"),
);
expect(component.selectedEntities).toEqual([testUsers[0]]);
}));

it("should be able to select entities from different types", fakeAsync(() => {
component.entityType = [User.ENTITY_TYPE, Child.ENTITY_TYPE];
component.selection = [
Expand Down
Loading