Skip to content

Commit

Permalink
Issue #1893
Browse files Browse the repository at this point in the history
Pushing for my partner on the project, as she was not added as a collaborator and couldn't make a PR.

Added functionality to DemoDataInitializerService:
    •    Reads demo_entities.json from the assets folder.
    •    Logs a message if the file is found or defaults to the existing hardcoded setup if not.
    •    Prepares for future insertion of JSON data into the database for scenario-specific demo customization.

Co-Authored-By: Mira Panjaitan <[email protected]>
  • Loading branch information
kumarannathan and mnauli committed Dec 10, 2024
1 parent 451f1f8 commit de263d5
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 1 deletion.
47 changes: 46 additions & 1 deletion src/app/core/demo-data/demo-data-initializer.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { fakeAsync, TestBed, tick } from "@angular/core/testing";

import {
HttpClientTestingModule,
HttpTestingController,
} from "@angular/common/http/testing";
import { DemoDataInitializerService } from "./demo-data-initializer.service";
import { DemoDataService } from "./demo-data.service";
import { DemoUserGeneratorService } from "../user/demo-user-generator.service";
Expand Down Expand Up @@ -32,6 +35,7 @@ describe("DemoDataInitializerService", () => {
let mockLocalAuth: jasmine.SpyObj<LocalAuthService>;
let sessionManager: jasmine.SpyObj<SessionManagerService>;
let mockDialog: jasmine.SpyObj<MatDialog>;
let httpTestingController: HttpTestingController;
let demoUserDBName: string;
let adminDBName: string;

Expand All @@ -47,6 +51,7 @@ describe("DemoDataInitializerService", () => {
sessionManager = jasmine.createSpyObj(["offlineLogin"]);

TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
DemoDataInitializerService,
LoginStateSubject,
Expand All @@ -59,19 +64,59 @@ describe("DemoDataInitializerService", () => {
],
});
service = TestBed.inject(DemoDataInitializerService);
httpTestingController = TestBed.inject(HttpTestingController);
});

afterEach(async () => {
localStorage.clear();
const tmpDB = new PouchDatabase();
await tmpDB.initInMemoryDB(demoUserDBName).destroy();
await tmpDB.initInMemoryDB(adminDBName).destroy();
httpTestingController.verify();
});

it("should be created", () => {
expect(service).toBeTruthy();
});

it("should load demo_entities.json if available", fakeAsync(() => {
const mockEntities = {
docs: [
{ _id: "Config:CONFIG_ENTITY", otherField: "xyz" },
{ _id: "User:USER_ENTITY", username: "demoUser", role: "admin" },
],
};

service.run();

const req = httpTestingController.expectOne("assets/demo_entities.json");
expect(req.request.method).toBe("GET");

req.flush(mockEntities);

tick();

expect(console.log).toHaveBeenCalledWith(
"Loaded demo_entities.json:",
mockEntities,
);
}));

it("should proceed without demo_entities.json if not available", fakeAsync(() => {
service.run();

const req = httpTestingController.expectOne("assets/demo_entities.json");
expect(req.request.method).toBe("GET");

req.error(new ErrorEvent("404 Not Found"), { status: 404 });

tick();

expect(console.log).toHaveBeenCalledWith(
"No demo_entities.json found, proceeding with default demo setup.",
);
}));

it("should save the default users", () => {
service.run();

Expand Down
24 changes: 24 additions & 0 deletions src/app/core/demo-data/demo-data-initializer.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { LoginState } from "../session/session-states/login-state.enum";
import { LoginStateSubject, SessionType } from "../session/session-type";
import memory from "pouchdb-adapter-memory";
import PouchDB from "pouchdb-browser";
import { HttpClient } from "@angular/common/http";

/**
* This service handles everything related to the demo-mode
Expand Down Expand Up @@ -46,6 +47,7 @@ export class DemoDataInitializerService {
private database: Database,
private loginState: LoginStateSubject,
private sessionInfo: SessionSubject,
private http: HttpClient,
) {}

async run() {
Expand All @@ -62,13 +64,35 @@ export class DemoDataInitializerService {

this.localAuthService.saveUser(this.normalUser);
this.localAuthService.saveUser(this.adminUser);

await this.sessionManager.offlineLogin(this.normalUser);

// Load and parse the demo_entities.json file before publishing demo data
const demoDataFromJson = await this.loadDemoEntities();
if (demoDataFromJson?.docs) {
console.log("Loaded demo_entities.json:", demoDataFromJson);
} else {
console.log(
"No demo_entities.json found, proceeding with default demo setup.",
);
}

await this.demoDataService.publishDemoData();

dialogRef.close();
this.syncDatabaseOnUserChange();
}

private async loadDemoEntities(): Promise<any> {
try {
// Adjust the file name if you plan to have scenario-specific variants
return await this.http.get("assets/demo_entities.json").toPromise();
} catch (error) {
// It's okay if the file doesn't exist; proceed with defaults
return null;
}
}

private syncDatabaseOnUserChange() {
this.loginState.subscribe((state) => {
if (
Expand Down
27 changes: 27 additions & 0 deletions src/assets/demo_entities.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"docs": [
{
"_id": "Config:NOTE",
"subject": "Weekly Meeting Notes",
"text": "Summary of weekly staff meeting.",
"date": "2024-12-01",
"authors": ["User:1"],
"category": "Education",
"warningLevel": "INFO"
},
{
"_id": "Child:1",
"name": "John Doe",
"gender": "Male",
"admissionDate": "2024-01-01",
"schoolId": "School:1"
},
{
"_id": "School:1",
"name": "Springfield High School",
"language": "English",
"privateSchool": false
}
]
}

0 comments on commit de263d5

Please sign in to comment.