Skip to content

Commit b81f46b

Browse files
committed
Made some improvements to the target calc logging....added a comment for later on the highcharts service
1 parent 73d141a commit b81f46b

5 files changed

Lines changed: 76 additions & 18 deletions

File tree

backend/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"start": "node --enable-source-maps dist/index.js | bunyan -o short -l info",
99
"test": "vitest",
1010
"build": "tsc",
11-
"dev": "tsx watch src/index.ts | bunyan -o short -l info",
11+
"dev": "NODE_OPTIONS='--max-old-space-size=8192' tsx watch src/index.ts | bunyan -o short -l info",
1212
"lint": "eslint src/**/*.ts",
1313
"compose:start": "docker-compose -f ../compose.yml up -d",
1414
"db:start": "docker-compose -f ../compose.yml up -d mongo",

backend/src/controllers/target.controller.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,19 @@ class TargetValuesController {
2929
try {
3030
const org = req.query.org || 'enterprise';
3131
const enableLogging = req.query.enableLogging === 'true';
32+
const includeLogsInResponse = req.query.includeLogs === 'true';
3233

3334
// Create an instance of the calculation service
3435
const calculationService = new TargetCalculationService();
3536

36-
// Fetch data and calculate targets with optional logging
37-
const targets = await calculationService.fetchAndCalculateTargets(org, enableLogging);
37+
// Fetch data and calculate targets with optional logging and logs in response
38+
const result = await calculationService.fetchAndCalculateTargets(
39+
org as string,
40+
enableLogging,
41+
includeLogsInResponse
42+
);
3843

39-
return res.status(200).json(targets);
44+
return res.status(200).json(result);
4045
} catch (error) {
4146
console.error('Error calculating target values:', error);
4247
return res.status(500).json({ error: 'Failed to calculate target values' });

backend/src/services/target-calculation-service.ts

Lines changed: 65 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,43 @@ export class TargetCalculationService {
6363
// Flag to enable/disable calculation logging
6464
debugLogging: boolean = false;
6565

66+
// Replace individual boolean flags with a Set to track logged calculation names
67+
private loggedCalculations: Set<string> = new Set();
68+
6669
// Tracks calculation readiness
6770
dataFetched: boolean = false;
6871

72+
// Collection of logs to return with the response
73+
calculationLogs: Array<{
74+
name: string;
75+
inputs: Record<string, any>;
76+
formula: string;
77+
result: any;
78+
}> = [];
79+
6980
/**
7081
* Log calculation details if debug logging is enabled
82+
* Each calculation name will only be logged once
7183
*/
7284
private logCalculation(name: string, inputs: Record<string, any>, formula: string, result: any): void {
73-
if (!this.debugLogging) return;
74-
75-
console.log(`
85+
// Only log if we haven't logged this calculation name before
86+
if (!this.loggedCalculations.has(name)) {
87+
// Mark this calculation name as logged
88+
this.loggedCalculations.add(name);
89+
90+
const logEntry = {
91+
name,
92+
inputs,
93+
formula,
94+
result
95+
};
96+
97+
// Store the log entry if debug logging is enabled
98+
if (this.debugLogging) {
99+
this.calculationLogs.push(logEntry);
100+
101+
// Also print to console
102+
console.log(`
76103
========== CALCULATION: ${name} ==========
77104
INPUTS:
78105
${Object.entries(inputs).map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`).join('\n')}
@@ -84,6 +111,14 @@ RESULT:
84111
${JSON.stringify(result)}
85112
========================================
86113
`);
114+
}
115+
}
116+
}
117+
118+
// Reset the logged calculations set when starting a new calculation run
119+
private resetLogging(): void {
120+
this.loggedCalculations.clear();
121+
this.calculationLogs = [];
87122
}
88123

89124
/**
@@ -816,32 +851,50 @@ RESULT:
816851
* One-step method to fetch data and perform all calculations
817852
* The instance method - used when you already have a service instance
818853
*/
819-
async fetchAndCalculateTargets(org: string | null, enableLogging: boolean = false): Promise<Targets> {
854+
async fetchAndCalculateTargets(
855+
org: string | null,
856+
enableLogging: boolean = false,
857+
includeLogsInResponse: boolean = false
858+
): Promise<{ targets: Targets; logs?: Array<any> }> {
820859
this.debugLogging = enableLogging;
860+
this.resetLogging(); // Reset logging state
821861
console.log(`Calculation logging ${enableLogging ? 'enabled' : 'disabled'}`);
822862

823-
// Use 'enterprise' as default when org is null or undefined
824-
// const orgName = org || 'enterprise';
825863
await this.fetchCalculationData(org);
826-
return this.calculateAllTargets();
864+
const targets = this.calculateAllTargets();
865+
866+
// Return both targets and logs if requested
867+
if (includeLogsInResponse && this.debugLogging) {
868+
return {
869+
targets,
870+
logs: this.calculationLogs
871+
};
872+
}
873+
874+
return { targets };
827875
}
828876

829877
/**
830878
* Static method to create an instance and calculate targets in one step
831879
* Used for convenience when you don't want to create an instance first
832880
* This is a facade that creates an instance and calls the instance method
833881
*/
834-
static async fetchAndCalculateTargets(org: string | null, enableLogging: boolean = false): Promise<Targets> {
882+
static async fetchAndCalculateTargets(
883+
org: string | null,
884+
enableLogging: boolean = false,
885+
includeLogsInResponse: boolean = false
886+
): Promise<{ targets: Targets; logs?: Array<any> }> {
835887
const service = new TargetCalculationService();
836-
return service.fetchAndCalculateTargets(org, enableLogging);
888+
return service.fetchAndCalculateTargets(org, enableLogging, includeLogsInResponse);
837889
}
838890
}
839891

840892
// Allow isolated testing
841893
if (import.meta.url.endsWith(process.argv[1])) {
842894
(async () => {
843-
// Example of using the static method
844-
const targets = await TargetCalculationService.fetchAndCalculateTargets('test-org', true);
845-
console.log('Calculated Targets:', JSON.stringify(targets, null, 2));
895+
// Example of using the static method with logs included in response
896+
const result = await TargetCalculationService.fetchAndCalculateTargets('test-org', true, true);
897+
console.log('Calculated Targets:', JSON.stringify(result.targets, null, 2));
898+
console.log(`Returned ${result.logs?.length || 0} calculation logs`);
846899
})();
847900
}

backend/src/services/target.service.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ class TargetValuesService {
106106
}
107107

108108
calculateTargets(settings: SettingsType, adoptions: AdoptionType[]): Promise<Targets> {
109-
return TargetCalculationService.fetchAndCalculateTargets(null, true); //always true for now to audit calculations
109+
return TargetCalculationService.fetchAndCalculateTargets(null, false, false); //always true for enableLogging for now to audit calculations, always false for includeLogsInResponse.
110110
}
111111

112112
//create default targets if they don't exist

frontend/src/app/services/highcharts.service.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -649,7 +649,7 @@ export class HighchartsService {
649649

650650
if (dateSurveys.length > 0) {
651651
const avgPercentTimeSaved = dateSurveys.reduce((sum, survey) => sum + survey.percentTimeSaved, 0)
652-
acc[dateKey].sum = avgPercentTimeSaved * 0.01 * 0.3 * 40; // TODO pull settings
652+
acc[dateKey].sum = avgPercentTimeSaved * 0.01 * 0.3 * 40; // TODO pull settings value, right now fixed at 30% time spent coding
653653
acc[dateKey].count = dateSurveys.length;
654654
}
655655

0 commit comments

Comments
 (0)