Skip to content

Commit

Permalink
fix: 🐛 scoreRecordsPerCoalition 에서 coalition 이 얻은 점수가 없는 경우에 대한 처리 추가
Browse files Browse the repository at this point in the history
- lookup 했을 때 0개가 나오는 경우, coalition 자체가 반환이 안되기 때문에 애초에 aggregate 를 coalition 기준으로 하도록 변경
-  특정 날짜에 대해 없는 경우 records 의 개수가 date 범위와 맞지 않기 때문에 이를 0 으로 채워서 반환하도록 수정

- close #332
  • Loading branch information
jpham005 committed Sep 24, 2023
1 parent ab5538d commit 56ee728
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 36 deletions.
88 changes: 55 additions & 33 deletions app/src/api/score/score.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectModel } from '@nestjs/mongoose';
import type { FilterQuery, Model } from 'mongoose';
import { TIMEZONE_CONFIG, type TimezoneConfig } from 'src/config/timezone';
import { addRank } from 'src/database/mongoose/database.mongoose.aggregation';
import type {
IntPerCoalition,
Expand All @@ -20,12 +22,18 @@ import { score } from './db/score.database.schema';

@Injectable()
export class ScoreService {
private readonly timezone: string;

constructor(
@InjectModel(score.name)
private readonly scoreModel: Model<score>,
private readonly coalitionService: CoalitionService,
private readonly cursusUserService: CursusUserService,
) {}
private readonly configService: ConfigService,
) {
this.timezone =
this.configService.getOrThrow<TimezoneConfig>(TIMEZONE_CONFIG).TIMEZONE;
}

async scoreRanking(args?: {
targetCoalitionIds?: readonly number[];
Expand Down Expand Up @@ -97,49 +105,63 @@ export class ScoreService {
const targetCoalitionIds =
args?.targetCoalitionIds ?? this.coalitionService.getSeoulCoalitionIds();

const aggregate = this.scoreModel.aggregate<ScoreRecordPerCoalition>();
const aggregate =
this.coalitionService.aggregate<ScoreRecordPerCoalition>();

// todo: 여기도 다른 record 처럼 통일하면 좋을 듯
return await aggregate
.match({
...args?.filter,
coalitionsUserId: { $ne: null },
coalitionId: { $in: targetCoalitionIds },
id: { $in: targetCoalitionIds },
})
.group({
_id: {
coalitionId: '$coalitionId',
at: {
$dateToString: {
format: '%Y-%m',
date: '$createdAt',
timezone: process.env.TZ,
.sort({ id: 1 })
.addFields({ coalition: '$$ROOT' })
.append(
lookupScores('id', 'coalitionId', [
{
$match: {
...args?.filter,
coalitionsUserId: { $ne: null },
},
},
},
value: { $sum: '$value' },
})
.sort({ '_id.at': 1 })
.group({
_id: '$_id.coalitionId',
records: {
$push: {
at: {
$dateFromString: {
dateString: '$_id.at',
timezone: process.env.TZ,
{
$group: {
_id: {
$dateFromParts: {
year: {
$year: {
date: '$createdAt',
timezone: this.timezone,
},
},
month: {
$month: {
date: '$createdAt',
timezone: this.timezone,
},
},
timezone: this.timezone,
},
},
value: { $sum: '$value' },
},
value: '$value',
},
},
})
.sort({ _id: 1 })
.append(lookupCoalition('_id', 'id'))
{
$sort: { _id: 1 },
},
]),
)
.project({
_id: 0,
coalition: { $first: '$coalitions' },
records: 1,
coalition: 1,
records: {
$map: {
input: '$scores',
as: 'arr',
in: {
at: '$$arr._id',
value: '$$arr.value',
},
},
},
});
}

Expand Down
33 changes: 30 additions & 3 deletions app/src/page/home/coalition/home.coalition.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { scoreDateRangeFilter } from 'src/api/score/db/score.database.aggregate'
import { ScoreCacheService } from 'src/api/score/score.cache.service';
import { ScoreService } from 'src/api/score/score.service';
import { CacheOnReturn } from 'src/cache/decrators/onReturn/cache.decorator.onReturn.symbol';
import type { IntRecord } from 'src/common/models/common.valueRecord.model';
import { DateRangeService } from 'src/dateRange/dateRange.service';
import { DateRange, DateTemplate } from 'src/dateRange/dtos/dateRange.dto';
import { DateWrapper } from 'src/dateWrapper/dateWrapper';
Expand Down Expand Up @@ -38,12 +39,38 @@ export class HomeCoalitionService {
end: nextMonth.toDate(),
};

return (
const scoreRecords =
cachedScoreRecords ??
(await this.scoreService.scoreRecordsPerCoalition({
filter: scoreDateRangeFilter(dateRange),
}))
);
}));

const dates: Date[] = [];

for (
let currMonth = lastYear;
currMonth.toDate() < nextMonth.toDate();
currMonth = currMonth.moveMonth(1)
) {
dates.push(currMonth.toDate());
}

return scoreRecords.map(({ coalition, records }) => {
const zeroFilledRecords = dates.reduce((newRecords, currDate) => {
const currValue = records.find(
({ at }) => currDate.getTime() === at.getTime(),
)?.value;

newRecords.push({ at: currDate, value: currValue ?? 0 });

return newRecords;
}, new Array<IntRecord>());

return {
coalition,
records: zeroFilledRecords,
};
});
}

@CacheOnReturn()
Expand Down

0 comments on commit 56ee728

Please sign in to comment.