Skip to content

Commit 8cc2ef1

Browse files
committed
cleanup
1 parent f674eb3 commit 8cc2ef1

File tree

15 files changed

+35
-89
lines changed

15 files changed

+35
-89
lines changed

backend/src/controllers/target.controller.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import { Request, Response } from 'express';
22
import TargetValuesService from '../services/target.service.js';
33
import { TargetCalculationService } from '../services/target-calculation-service.js';
4+
import logger from '../services/logger.js';
45

56
class TargetValuesController {
67
async getTargetValues(req: Request, res: Response): Promise<void> {
78
try {
89
const targetValues = await TargetValuesService.getTargetValues();
910
res.status(200).json(targetValues);
1011
} catch (error) {
12+
logger.error('Error getting target values:', error);
1113
res.status(500).json(error);
1214
}
1315
}
@@ -17,6 +19,7 @@ class TargetValuesController {
1719
const updatedTargetValues = await TargetValuesService.updateTargetValues(req.body);
1820
res.status(200).json(updatedTargetValues);
1921
} catch (error) {
22+
logger.error('Error updating target values:', error);
2023
res.status(500).json(error);
2124
}
2225
}
@@ -42,12 +45,12 @@ class TargetValuesController {
4245

4346
// Check if we have logs before sending the response
4447
if (includeLogsInResponse) {
45-
console.log(`Response will include ${result.logs?.length || 0} logs`);
48+
logger.info(`Response will include ${result.logs?.length || 0} logs`);
4649
}
4750

4851
res.status(200).json(result);
4952
} catch (error) {
50-
console.error('Error calculating target values:', error);
53+
logger.error('Error calculating target values:', error);
5154
res.status(500).json({ error: `Failed to calculate target values: ${error}` });
5255
}
5356
}

backend/src/routes/status.route.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import express from 'express';
22
import StatusService from '../services/status.service.js';
3+
import logger from '../services/logger.js';
34

45
const router = express.Router();
56
const statusService = new StatusService();
@@ -10,7 +11,7 @@ router.get('/', async (req, res) => {
1011
const status = await statusService.getStatus(req);
1112
res.json(status);
1213
} catch (error) {
13-
console.error('Error fetching status:', error);
14+
logger.error('Error fetching status:', error);
1415
res.status(500).json({ error: 'Failed to fetch status' });
1516
}
1617
});

backend/src/services/seats.service.ts

Lines changed: 16 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { SeatType } from "../models/seats.model.js";
33
import { components } from "@octokit/openapi-types";
44
import mongoose from 'mongoose';
55
import { MemberActivityType, MemberType } from 'models/teams.model.js';
6-
import fs from 'fs';
76
import adoptionService from './adoption.service.js';
87
import logger from './logger.js';
98

@@ -77,7 +76,7 @@ class SeatsService {
7776
$lte?: Date;
7877
};
7978
}
80-
79+
8180
const query: SeatQuery = {
8281
assignee: member._id // This is the MongoDB ObjectId that links to the Member document
8382
};
@@ -150,42 +149,32 @@ class SeatsService {
150149
async getSeat(identifier: string | number, params: { since?: string; until?: string; org?: string } = {}) {
151150
const Seats = mongoose.model('Seats');
152151
const Member = mongoose.model('Member');
153-
152+
154153
try {
155-
//console.log('========== SEAT LOOKUP START ==========');
156-
//console.log(`Looking up seat for identifier: ${identifier}, params:`, JSON.stringify(params));
157-
158-
// Force console output to appear immediately
159-
process.stdout.write('');
160-
161154
// Determine if identifier is numeric
162155
const isNumeric = !isNaN(Number(identifier)) && String(Number(identifier)) === String(identifier);
163156
let numericId: number | null = null;
164-
157+
165158
// If it's a login, look up the ID first
166159
if (!isNumeric) {
167160
// Ensure identifier is treated as string before calling replace
168161
const identifierString = String(identifier);
169-
162+
170163
try {
171164
// Find the member by login - exact match with explicit type casting
172165
const member = await Member.findOne({ login: identifierString }).lean() as MemberDocument | null;
173-
166+
174167
if (!member) {
175168
// Try case-insensitive search as a fallback
176169
const regex = new RegExp(`^${identifierString.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')}$`, 'i');
177-
const memberCaseInsensitive = await Member.findOne({
170+
const memberCaseInsensitive = await Member.findOne({
178171
login: regex
179172
}).lean() as MemberDocument | null;
180-
181-
// Check if we got a document and then safely access properties
182-
console.log(`Case-insensitive search result:`,
183-
memberCaseInsensitive ? `Found ${memberCaseInsensitive.login}` : 'Not found');
184-
173+
185174
if (!memberCaseInsensitive) {
186175
return []; // Return empty array if no member found
187176
}
188-
177+
189178
// Now TypeScript knows memberCaseInsensitive has these properties
190179
numericId = memberCaseInsensitive.id;
191180
} else {
@@ -198,29 +187,24 @@ class SeatsService {
198187
} else {
199188
numericId = Number(identifier);
200189
}
201-
190+
202191
const query: mongoose.FilterQuery<SeatType> = { assignee_id: numericId };
203-
192+
204193
if (params.org) {
205194
query.org = params.org;
206195
}
207-
196+
208197
if (params.since || params.until) {
209198
query.createdAt = {};
210199
if (params.since) {
211200
query.createdAt.$gte = new Date(params.since);
212-
// console.log(`Added since filter: ${params.since}`);
213201
}
214202
if (params.until) {
215203
query.createdAt.$lte = new Date(params.until);
216-
// console.log(`Added until filter: ${params.until}`);
217204
}
218205
}
219-
220-
// console.log(`Final query:`, JSON.stringify(query));
221-
206+
222207
// Execute the query
223-
//console.log(`Executing Seats.find() with query`);
224208
const results = await Seats.find(query)
225209
.sort({ createdAt: 1 })
226210
.populate({
@@ -230,19 +214,17 @@ class SeatsService {
230214
})
231215
.lean()
232216
.exec(); // Explicitly call exec()
233-
217+
234218
logger.debug(`Query complete. Found ${results?.length || 0} seat records`);
235-
//console.log('========== SEAT LOOKUP END ==========');
236-
219+
237220
return results || [];
238-
239221
} catch (error: unknown) {
240222
console.error('========== SEAT LOOKUP ERROR ==========');
241223
console.error(`Error retrieving seat data for ${identifier}:`, error);
242224
// Safe access to stack property
243225
console.error(`Stack trace:`, error instanceof Error ? error.stack : 'No stack trace available');
244226
console.error('=======================================');
245-
227+
246228
// Return empty results rather than throwing error
247229
return [];
248230
}
@@ -541,8 +523,6 @@ class SeatsService {
541523
.sort(([dateA], [dateB]) => new Date(dateA).getTime() - new Date(dateB).getTime())
542524
);
543525

544-
fs.writeFileSync('sortedActivityDays.json', JSON.stringify(sortedActivityDays, null, 2), 'utf-8');
545-
546526
return sortedActivityDays;
547527
}
548528

@@ -609,7 +589,7 @@ class SeatsService {
609589
const { org, since, until } = params;
610590
const limit = typeof params.limit === 'string' ? parseInt(params.limit) : (params.limit || 100);
611591

612-
const match: mongoose.FilterQuery<MemberActivityType> = {};
592+
const match: mongoose.FilterQuery<MemberActivityType> = {};
613593
if (org) match.org = org;
614594
if (since || until) {
615595
match.date = {

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

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ import copilotSurveyService from './survey.service.js';
66
import { SurveyType } from './survey.service.js'; // Import from survey.service.js instead
77
import app from '../index.js';
88
import dayjs from 'dayjs';
9-
import util from 'util'; // NEW
9+
import util from 'util';
10+
import logger from './logger.js';
1011

1112
// Define types for calculation logging
1213
interface CalcLogType {
@@ -91,7 +92,7 @@ export class TargetCalculationService {
9192
this.calculationLogs.push(logEntry);
9293

9394
// Also pretty print to console
94-
console.log(`
95+
logger.info(`
9596
========== CALCULATION: ${name} ==========
9697
INPUTS:
9798
${util.inspect(inputs, { depth: null, colors: false, compact: false })}
@@ -925,7 +926,7 @@ RESULT:
925926
): Promise<{ targets: Targets; logs?: CalcLogType[] }> {
926927
this.debugLogging = enableLogging;
927928
this.resetLogging(); // Reset logging state
928-
console.log(`Calculation logging ${enableLogging ? 'enabled' : 'disabled'}`);
929+
logger.info(`Calculation logging ${enableLogging ? 'enabled' : 'disabled'}`);
929930

930931
await this.fetchCalculationData(org);
931932
const targets = this.calculateAllTargets();
@@ -951,7 +952,7 @@ RESULT:
951952
enableLogging: boolean = false,
952953
includeLogsInResponse: boolean = false
953954
): Promise<{ targets: Targets; logs?: CalcLogType[] }> {
954-
console.log('Static method received params:', {
955+
logger.info('Static method received params:', {
955956
org: org || 'null',
956957
enableLogging,
957958
includeLogsInResponse
@@ -968,7 +969,7 @@ RESULT:
968969

969970
// Verify the structure of the result before returning
970971
const hasLogs = Boolean(result.logs && result.logs.length > 0);
971-
console.log(`Result has logs: ${hasLogs}, includeLogsInResponse: ${includeLogsInResponse}`);
972+
logger.info(`Result has logs: ${hasLogs}, includeLogsInResponse: ${includeLogsInResponse}`);
972973

973974
return result;
974975
}
@@ -981,7 +982,7 @@ if (import.meta.url.endsWith(process.argv[1])) {
981982
(async () => {
982983
// Example of using the static method with logs included in response
983984
const result = await TargetCalculationService.fetchAndCalculateTargets('test-org', true, true);
984-
console.log('Calculated Targets:', JSON.stringify(result.targets, null, 2));
985-
console.log(`Returned ${result.logs?.length || 0} calculation logs`);
985+
logger.info('Calculated Targets:', JSON.stringify(result.targets, null, 2));
986+
logger.info(`Returned ${result.logs?.length || 0} calculation logs`);
986987
})();
987988
}

backend/src/services/target.service.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import mongoose from 'mongoose';
22
import { AdoptionType } from './adoption.service.js'
33
import { SettingsType } from './settings.service.js';
44
import { TargetCalculationService } from './target-calculation-service.js';
5+
import logger from './logger.js';
56

67
interface Target {
78
current: number;
@@ -116,9 +117,8 @@ class TargetValuesService {
116117

117118
if (!existingTargets ) {
118119
const result = await this.calculateTargets();
119-
// Extract the targets property from the result
120120
await Targets.create(result.targets);
121-
console.log('Default targets created successfully.');
121+
logger.info('Default targets created successfully.');
122122
}
123123
} catch (error) {
124124
throw new Error(`Error initializing target values: ${error}`);

frontend/src/app/main/copilot/copilot-dashboard/dashboard-card/active-users-chart/active-users-chart.component.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,6 @@ export class ActiveUsersChartComponent implements OnChanges {
8888
) { }
8989

9090
ngOnChanges() {
91-
console.log('ngOnChanges', this.data);
9291
this._chartOptions = Object.assign({}, this.chartOptions, this._chartOptions);
9392
if (this._chartOptions?.series && this.data) {
9493
// Create an array with [total_time, login, avatar_url] for each point

frontend/src/app/main/copilot/copilot-dashboard/dashboard.component.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,6 @@ export class CopilotDashboardComponent implements OnInit, OnDestroy {
171171
this.subscriptions.push(
172172
this.targetsService.getTargets().subscribe(data => {
173173
this.targetsData = data;
174-
console.log('Dashboard targets loaded:', data); // DEBUG
175174
this.cdr.detectChanges();
176175
})
177176
);

frontend/src/app/main/copilot/copilot-metrics/copilot-metrics.component.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,6 @@ export class CopilotMetricsComponent implements OnInit, OnDestroy {
8585

8686
this.reset();
8787

88-
console.log({
89-
since: event.start.toISOString(),
90-
until: event.end.toISOString()
91-
})
9288
this.subscriptions.push(
9389
this.seatService.getActivityTotals({
9490
org: this.installation?.account?.login,

frontend/src/app/main/copilot/copilot-surveys/new-copilot-survey/new-copilot-survey.component.ts

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -297,8 +297,6 @@ export class NewCopilotSurveyComponent implements OnInit {
297297
timeUsedFor: this.surveyForm.value.timeUsedFor || ''
298298
};
299299

300-
console.log('Submitting survey:', survey);
301-
302300
if (!this.id) {
303301
this.copilotSurveyService.createSurvey(survey).pipe(
304302
catchError(error => {
@@ -359,7 +357,6 @@ export class NewCopilotSurveyComponent implements OnInit {
359357
*/
360358
onMemberSelected(event: MatAutocompleteSelectedEvent): void {
361359
const selectedMember = event.option.value as Member;
362-
console.log('Member selected:', selectedMember); // Optional: for debugging
363360

364361
// Set the value in the form and clear errors
365362
const userIdControl = this.surveyForm.get('userId');
@@ -378,11 +375,8 @@ export class NewCopilotSurveyComponent implements OnInit {
378375
const userIdControl = this.surveyForm.get('userId');
379376
const userId = userIdControl?.value;
380377

381-
console.log('onUserIdBlur called with value:', userId); // Optional: for debugging
382-
383378
// Skip validation if the value is already a Member object (meaning an option was selected)
384379
if (userId && typeof userId !== 'string' && userId.login) {
385-
console.log('Value is a Member object, skipping validation'); // Optional: for debugging
386380
return;
387381
}
388382

@@ -400,8 +394,6 @@ export class NewCopilotSurveyComponent implements OnInit {
400394
const userIdControl = this.surveyForm.get('userId');
401395
const userId = userIdControl?.value;
402396

403-
console.log('Validating userId:', userId); // Optional: for debugging
404-
405397
// Skip validation if empty (let the required validator handle this)
406398
if (!userId) {
407399
return;
@@ -413,14 +405,9 @@ export class NewCopilotSurveyComponent implements OnInit {
413405
return;
414406
}
415407

416-
// Only validate if the value is a string (user typed it in and didn't select an option)
417408
if (typeof userId === 'string') {
418-
console.log('Validating string value:', userId); // Optional: for debugging
419-
420-
// Set loading state
421409
this.isLoading$.next(true);
422410

423-
// Call validation method with exact=true for case-insensitive matching
424411
this.membersService.getMemberByLogin(userId, true).pipe(
425412
catchError(error => {
426413
console.error('Error validating user ID:', error);
@@ -437,8 +424,6 @@ export class NewCopilotSurveyComponent implements OnInit {
437424

438425
// Always update to the correctly cased username from the API
439426
userIdControl?.setValue(result);
440-
441-
console.log('User validated and updated to correct case:', result.login); // Optional: for debugging
442427
} else {
443428
// Invalid user (and not caught by catchError, e.g., API returned null)
444429
if (!userIdControl?.hasError('invalidUserId')) { // Avoid overwriting existing error

frontend/src/app/main/copilot/copilot-value-modeling/copilot-value-modeling.component.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,6 @@ export class CopilotValueModelingComponent implements OnInit {
9292
this.userDataSource = this.transformTargets(targets.user);
9393
this.impactDataSource = this.transformTargets(targets.impact);
9494
});
95-
console.log('Targets:', this.orgDataSource, this.userDataSource, this.impactDataSource);
9695
} catch (error) {
9796
console.error('Error during initialization:', error);
9897
}

0 commit comments

Comments
 (0)