feat(reputation): add ReputationService, rank resolver integration, and GET /api/reputation
This commit is contained in:
@@ -7,6 +7,7 @@ import { HealthModule } from './health/health.module';
|
|||||||
import { HuntingModule } from './hunting/hunting.module';
|
import { HuntingModule } from './hunting/hunting.module';
|
||||||
import { InventoryModule } from './inventory/inventory.module';
|
import { InventoryModule } from './inventory/inventory.module';
|
||||||
import { RenownModule } from './renown/renown.module';
|
import { RenownModule } from './renown/renown.module';
|
||||||
|
import { ReputationModule } from './reputation/reputation.module';
|
||||||
import { TravelModule } from './travel/travel.module';
|
import { TravelModule } from './travel/travel.module';
|
||||||
import { WorldModule } from './world/world.module';
|
import { WorldModule } from './world/world.module';
|
||||||
|
|
||||||
@@ -22,6 +23,7 @@ import { WorldModule } from './world/world.module';
|
|||||||
EquipmentModule,
|
EquipmentModule,
|
||||||
InventoryModule,
|
InventoryModule,
|
||||||
RenownModule,
|
RenownModule,
|
||||||
|
ReputationModule,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
48
apps/api/src/reputation/reputation.controller.spec.ts
Normal file
48
apps/api/src/reputation/reputation.controller.spec.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { App } from 'supertest/types';
|
||||||
|
import { configureApplication } from '../app.config';
|
||||||
|
import { DEMO_CHARACTER_ID } from '../demo/demo-character.constants';
|
||||||
|
import { ReputationController } from './reputation.controller';
|
||||||
|
import { ReputationService } from './reputation.service';
|
||||||
|
|
||||||
|
describe('ReputationController', () => {
|
||||||
|
let app: INestApplication<App>;
|
||||||
|
const getCharacterReputation = jest.fn();
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
getCharacterReputation.mockReset();
|
||||||
|
const module = await Test.createTestingModule({
|
||||||
|
controllers: [ReputationController],
|
||||||
|
providers: [{ provide: ReputationService, useValue: { getCharacterReputation } }],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = module.createNestApplication<App>();
|
||||||
|
configureApplication(app);
|
||||||
|
await app.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('delegates GET /api/reputation to reputationService.getCharacterReputation', async () => {
|
||||||
|
const entries = [
|
||||||
|
{
|
||||||
|
factionKey: 'border-guard',
|
||||||
|
factionName: 'Grenzwacht',
|
||||||
|
reputation: 40,
|
||||||
|
rank: 'STRANGER',
|
||||||
|
rankLabel: 'Fremder',
|
||||||
|
nextThreshold: 100,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
getCharacterReputation.mockResolvedValue(entries);
|
||||||
|
|
||||||
|
const response = await request(app.getHttpServer()).get('/api/reputation').expect(200);
|
||||||
|
|
||||||
|
expect(getCharacterReputation).toHaveBeenCalledWith(DEMO_CHARACTER_ID);
|
||||||
|
expect(response.body).toEqual(entries);
|
||||||
|
});
|
||||||
|
});
|
||||||
13
apps/api/src/reputation/reputation.controller.ts
Normal file
13
apps/api/src/reputation/reputation.controller.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { Controller, Get } from '@nestjs/common';
|
||||||
|
import { DEMO_CHARACTER_ID } from '../demo/demo-character.constants';
|
||||||
|
import { CharacterReputationDto, ReputationService } from './reputation.service';
|
||||||
|
|
||||||
|
@Controller('reputation')
|
||||||
|
export class ReputationController {
|
||||||
|
constructor(private readonly reputationService: ReputationService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
getCharacterReputation(): Promise<CharacterReputationDto[]> {
|
||||||
|
return this.reputationService.getCharacterReputation(DEMO_CHARACTER_ID);
|
||||||
|
}
|
||||||
|
}
|
||||||
23
apps/api/src/reputation/reputation.errors.ts
Normal file
23
apps/api/src/reputation/reputation.errors.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||||
|
|
||||||
|
export type ReputationErrorCode = 'REPUTATION_FACTION_NOT_FOUND';
|
||||||
|
|
||||||
|
export class ReputationDomainError extends HttpException {
|
||||||
|
constructor(
|
||||||
|
public readonly code: ReputationErrorCode,
|
||||||
|
status: HttpStatus,
|
||||||
|
message: string,
|
||||||
|
) {
|
||||||
|
super({ statusCode: status, code, message }, status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reputationFactionNotFound(): ReputationDomainError {
|
||||||
|
return new ReputationDomainError(
|
||||||
|
'REPUTATION_FACTION_NOT_FOUND',
|
||||||
|
HttpStatus.NOT_FOUND,
|
||||||
|
'This faction could not be found.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { characterNotFound } from '../travel/travel.errors';
|
||||||
14
apps/api/src/reputation/reputation.module.ts
Normal file
14
apps/api/src/reputation/reputation.module.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { CharacterReputation } from './entities/character-reputation.entity';
|
||||||
|
import { ReputationFaction } from './entities/reputation-faction.entity';
|
||||||
|
import { ReputationController } from './reputation.controller';
|
||||||
|
import { ReputationService } from './reputation.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([ReputationFaction, CharacterReputation])],
|
||||||
|
controllers: [ReputationController],
|
||||||
|
providers: [ReputationService],
|
||||||
|
exports: [ReputationService],
|
||||||
|
})
|
||||||
|
export class ReputationModule {}
|
||||||
233
apps/api/src/reputation/reputation.service.spec.ts
Normal file
233
apps/api/src/reputation/reputation.service.spec.ts
Normal file
@@ -0,0 +1,233 @@
|
|||||||
|
import { DataSource, EntityManager, EntityTarget } from 'typeorm';
|
||||||
|
import { CharacterReputation } from './entities/character-reputation.entity';
|
||||||
|
import { ReputationFaction } from './entities/reputation-faction.entity';
|
||||||
|
import { ReputationDomainError } from './reputation.errors';
|
||||||
|
import { ReputationService } from './reputation.service';
|
||||||
|
|
||||||
|
const FACTION_ID = '80000000-0000-4000-8000-000000000001';
|
||||||
|
const CHARACTER_ID = '10000000-0000-4000-8000-000000000001';
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
factions: ReputationFaction[];
|
||||||
|
characterReputation: CharacterReputation[];
|
||||||
|
}
|
||||||
|
|
||||||
|
class FakeRepository<T extends { id: string }> {
|
||||||
|
constructor(
|
||||||
|
private readonly rows: T[],
|
||||||
|
private readonly prefix: string,
|
||||||
|
private readonly inTransaction: boolean,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
findOne(options: { where: Partial<T>; lock?: { mode: string } }): Promise<T | null> {
|
||||||
|
if (options.lock && !this.inTransaction) {
|
||||||
|
throw new Error('Pessimistic locks require a transaction');
|
||||||
|
}
|
||||||
|
return Promise.resolve(this.rows.find((row) => this.matches(row, options.where)) ?? null);
|
||||||
|
}
|
||||||
|
|
||||||
|
findOneBy(where: Partial<T>): Promise<T | null> {
|
||||||
|
return Promise.resolve(this.rows.find((row) => this.matches(row, where)) ?? null);
|
||||||
|
}
|
||||||
|
|
||||||
|
find(options: { where?: Partial<T> } = {}): Promise<T[]> {
|
||||||
|
return Promise.resolve(
|
||||||
|
options.where ? this.rows.filter((row) => this.matches(row, options.where!)) : [...this.rows],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
create(values: Partial<T>): T {
|
||||||
|
return { ...values } as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
save(entity: T): Promise<T> {
|
||||||
|
if (!entity.id) {
|
||||||
|
entity.id = `${this.prefix}-${this.rows.length + 1}`;
|
||||||
|
}
|
||||||
|
const index = this.rows.findIndex((row) => row.id === entity.id);
|
||||||
|
if (index === -1) {
|
||||||
|
this.rows.push(entity);
|
||||||
|
} else {
|
||||||
|
this.rows[index] = entity;
|
||||||
|
}
|
||||||
|
return Promise.resolve(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
private matches(row: T, where: Partial<T>): boolean {
|
||||||
|
return Object.entries(where).every(([key, value]) => row[key as keyof T] === value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class FakeDataSource {
|
||||||
|
constructor(public state: State) {}
|
||||||
|
|
||||||
|
getRepository<T extends { id: string }>(target: EntityTarget<T>) {
|
||||||
|
return this.repoFor(target, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
async transaction<T>(work: (manager: EntityManager) => Promise<T>): Promise<T> {
|
||||||
|
return work({
|
||||||
|
getRepository: <U extends { id: string }>(target: EntityTarget<U>) => this.repoFor(target, true),
|
||||||
|
} as unknown as EntityManager);
|
||||||
|
}
|
||||||
|
|
||||||
|
private repoFor<T extends { id: string }>(target: EntityTarget<T>, inTransaction: boolean) {
|
||||||
|
if (target === ReputationFaction)
|
||||||
|
return new FakeRepository(this.state.factions, 'faction', inTransaction) as never;
|
||||||
|
if (target === CharacterReputation)
|
||||||
|
return new FakeRepository(this.state.characterReputation, 'char-rep', inTransaction) as never;
|
||||||
|
throw new Error('Unsupported repository');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function faction(overrides: Partial<ReputationFaction> = {}): ReputationFaction {
|
||||||
|
return {
|
||||||
|
id: FACTION_ID,
|
||||||
|
key: 'border-guard',
|
||||||
|
name: 'Grenzwacht',
|
||||||
|
description: '',
|
||||||
|
regionKey: 'ashen-fields',
|
||||||
|
enabled: true,
|
||||||
|
...overrides,
|
||||||
|
} as ReputationFaction;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createState(overrides: Partial<State> = {}): State {
|
||||||
|
return { factions: [faction()], characterReputation: [], ...overrides };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createService(state: State) {
|
||||||
|
const dataSource = new FakeDataSource(state);
|
||||||
|
return { service: new ReputationService(dataSource as unknown as DataSource), state };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectReputationDomainError(promise: Promise<unknown>, code: string): Promise<void> {
|
||||||
|
let error: unknown;
|
||||||
|
try {
|
||||||
|
await promise;
|
||||||
|
} catch (cause) {
|
||||||
|
error = cause;
|
||||||
|
}
|
||||||
|
expect(error).toBeInstanceOf(ReputationDomainError);
|
||||||
|
if (!(error instanceof ReputationDomainError)) {
|
||||||
|
throw new Error('Expected ReputationDomainError');
|
||||||
|
}
|
||||||
|
expect(error.code).toBe(code);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ReputationService', () => {
|
||||||
|
describe('grantReputation', () => {
|
||||||
|
it('creates a reputation row starting from 0 on the first grant', async () => {
|
||||||
|
const { service, state } = createService(createState());
|
||||||
|
|
||||||
|
const result = await service.grantReputation(CHARACTER_ID, 'border-guard', 40);
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
factionKey: 'border-guard',
|
||||||
|
previousReputation: 0,
|
||||||
|
newReputation: 40,
|
||||||
|
previousRank: 'STRANGER',
|
||||||
|
newRank: 'STRANGER',
|
||||||
|
rankChanged: false,
|
||||||
|
});
|
||||||
|
expect(state.characterReputation).toHaveLength(1);
|
||||||
|
expect(state.characterReputation[0].reputation).toBe(40);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accumulates onto an existing reputation row', async () => {
|
||||||
|
const state = createState({
|
||||||
|
characterReputation: [
|
||||||
|
{ id: 'existing', characterId: CHARACTER_ID, factionId: FACTION_ID, reputation: 90 } as CharacterReputation,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const { service } = createService(state);
|
||||||
|
|
||||||
|
const result = await service.grantReputation(CHARACTER_ID, 'border-guard', 20);
|
||||||
|
|
||||||
|
expect(result.previousReputation).toBe(90);
|
||||||
|
expect(result.newReputation).toBe(110);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports rankChanged when a grant crosses a threshold', async () => {
|
||||||
|
const state = createState({
|
||||||
|
characterReputation: [
|
||||||
|
{ id: 'existing', characterId: CHARACTER_ID, factionId: FACTION_ID, reputation: 90 } as CharacterReputation,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const { service } = createService(state);
|
||||||
|
|
||||||
|
const result = await service.grantReputation(CHARACTER_ID, 'border-guard', 20);
|
||||||
|
|
||||||
|
expect(result.previousRank).toBe('STRANGER');
|
||||||
|
expect(result.newRank).toBe('TOLERATED');
|
||||||
|
expect(result.rankChanged).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports rankChanged: false when a grant stays within the same rank', async () => {
|
||||||
|
const state = createState({
|
||||||
|
characterReputation: [
|
||||||
|
{ id: 'existing', characterId: CHARACTER_ID, factionId: FACTION_ID, reputation: 120 } as CharacterReputation,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const { service } = createService(state);
|
||||||
|
|
||||||
|
const result = await service.grantReputation(CHARACTER_ID, 'border-guard', 10);
|
||||||
|
|
||||||
|
expect(result.rankChanged).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an unknown faction key', async () => {
|
||||||
|
const { service } = createService(createState());
|
||||||
|
|
||||||
|
await expectReputationDomainError(
|
||||||
|
service.grantReputation(CHARACTER_ID, 'unknown-faction', 10),
|
||||||
|
'REPUTATION_FACTION_NOT_FOUND',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getCharacterReputation', () => {
|
||||||
|
it('returns 0 Reputation / Stranger for a faction the character has never interacted with', async () => {
|
||||||
|
const { service } = createService(createState());
|
||||||
|
|
||||||
|
const result = await service.getCharacterReputation(CHARACTER_ID);
|
||||||
|
|
||||||
|
expect(result).toEqual([
|
||||||
|
{
|
||||||
|
factionKey: 'border-guard',
|
||||||
|
factionName: 'Grenzwacht',
|
||||||
|
reputation: 0,
|
||||||
|
rank: 'STRANGER',
|
||||||
|
rankLabel: 'Fremder',
|
||||||
|
nextThreshold: 100,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reflects a persisted grant', async () => {
|
||||||
|
const state = createState();
|
||||||
|
const { service } = createService(state);
|
||||||
|
await service.grantReputation(CHARACTER_ID, 'border-guard', 300);
|
||||||
|
|
||||||
|
const result = await service.getCharacterReputation(CHARACTER_ID);
|
||||||
|
|
||||||
|
expect(result[0]).toEqual({
|
||||||
|
factionKey: 'border-guard',
|
||||||
|
factionName: 'Grenzwacht',
|
||||||
|
reputation: 300,
|
||||||
|
rank: 'KNOWN',
|
||||||
|
rankLabel: 'Bekannt',
|
||||||
|
nextThreshold: 500,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits a disabled faction', async () => {
|
||||||
|
const state = createState({ factions: [faction({ enabled: false })] });
|
||||||
|
const { service } = createService(state);
|
||||||
|
|
||||||
|
const result = await service.getCharacterReputation(CHARACTER_ID);
|
||||||
|
|
||||||
|
expect(result).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
106
apps/api/src/reputation/reputation.service.ts
Normal file
106
apps/api/src/reputation/reputation.service.ts
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { DataSource, EntityManager } from 'typeorm';
|
||||||
|
import { CharacterReputation } from './entities/character-reputation.entity';
|
||||||
|
import { ReputationFaction } from './entities/reputation-faction.entity';
|
||||||
|
import { reputationFactionNotFound } from './reputation.errors';
|
||||||
|
import { resolveReputationRank } from './reputation-rank';
|
||||||
|
|
||||||
|
export interface ReputationGrantResult {
|
||||||
|
factionKey: string;
|
||||||
|
previousReputation: number;
|
||||||
|
newReputation: number;
|
||||||
|
previousRank: string;
|
||||||
|
newRank: string;
|
||||||
|
rankChanged: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CharacterReputationDto {
|
||||||
|
factionKey: string;
|
||||||
|
factionName: string;
|
||||||
|
reputation: number;
|
||||||
|
rank: string;
|
||||||
|
rankLabel: string;
|
||||||
|
nextThreshold: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepositoryScope = Pick<DataSource, 'getRepository'>;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ReputationService {
|
||||||
|
constructor(private readonly dataSource: DataSource) {}
|
||||||
|
|
||||||
|
/** Grants Regional Reputation, server-authoritative (spec §11, §30). */
|
||||||
|
async grantReputation(
|
||||||
|
characterId: string,
|
||||||
|
factionKey: string,
|
||||||
|
amount: number,
|
||||||
|
manager?: EntityManager,
|
||||||
|
): Promise<ReputationGrantResult> {
|
||||||
|
const run = async (txManager: EntityManager): Promise<ReputationGrantResult> => {
|
||||||
|
const factions = txManager.getRepository(ReputationFaction);
|
||||||
|
const reputations = txManager.getRepository(CharacterReputation);
|
||||||
|
|
||||||
|
const faction = await factions.findOneBy({ key: factionKey });
|
||||||
|
if (!faction) {
|
||||||
|
throw reputationFactionNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await reputations.findOne({
|
||||||
|
where: { characterId, factionId: faction.id },
|
||||||
|
lock: { mode: 'pessimistic_write' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const previousReputation = existing?.reputation ?? 0;
|
||||||
|
const newReputation = previousReputation + amount;
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
existing.reputation = newReputation;
|
||||||
|
await reputations.save(existing);
|
||||||
|
} else {
|
||||||
|
await reputations.save(
|
||||||
|
reputations.create({ characterId, factionId: faction.id, reputation: newReputation }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousRank = resolveReputationRank(previousReputation);
|
||||||
|
const newRank = resolveReputationRank(newReputation);
|
||||||
|
|
||||||
|
return {
|
||||||
|
factionKey,
|
||||||
|
previousReputation,
|
||||||
|
newReputation,
|
||||||
|
previousRank: previousRank.key,
|
||||||
|
newRank: newRank.key,
|
||||||
|
rankChanged: previousRank.key !== newRank.key,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
return manager ? run(manager) : this.dataSource.transaction(run);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every enabled faction, one entry each -- a faction the character has
|
||||||
|
* never interacted with reads as 0 Reputation / Stranger (spec §36,
|
||||||
|
* design R10), not as an absent entry.
|
||||||
|
*/
|
||||||
|
async getCharacterReputation(characterId: string): Promise<CharacterReputationDto[]> {
|
||||||
|
const scope: RepositoryScope = this.dataSource;
|
||||||
|
const factions = await scope.getRepository(ReputationFaction).find({ where: { enabled: true } });
|
||||||
|
const reputations = await scope.getRepository(CharacterReputation).find({ where: { characterId } });
|
||||||
|
|
||||||
|
return factions.map((faction) => {
|
||||||
|
const existing = reputations.find((row) => row.factionId === faction.id);
|
||||||
|
const reputation = existing?.reputation ?? 0;
|
||||||
|
const rank = resolveReputationRank(reputation);
|
||||||
|
|
||||||
|
return {
|
||||||
|
factionKey: faction.key,
|
||||||
|
factionName: faction.name,
|
||||||
|
reputation,
|
||||||
|
rank: rank.key,
|
||||||
|
rankLabel: rank.label,
|
||||||
|
nextThreshold: rank.nextThreshold,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user