This commit is contained in:
2025-12-10 12:38:55 +01:00
parent 0f7fe67d3c
commit fbbcf414a4
87 changed files with 11972 additions and 390 deletions

View File

@@ -0,0 +1,390 @@
/**
* Domain Entity: Achievement
*
* Represents an achievement that can be earned by users.
* Achievements are categorized by role (driver, steward, admin) and type.
*/
export type AchievementCategory = 'driver' | 'steward' | 'admin' | 'community';
export type AchievementRarity = 'common' | 'uncommon' | 'rare' | 'epic' | 'legendary';
export interface AchievementProps {
id: string;
name: string;
description: string;
category: AchievementCategory;
rarity: AchievementRarity;
iconUrl?: string;
points: number;
requirements: AchievementRequirement[];
isSecret: boolean;
createdAt: Date;
}
export interface AchievementRequirement {
type: 'races_completed' | 'wins' | 'podiums' | 'clean_races' | 'protests_handled' |
'leagues_managed' | 'seasons_completed' | 'consecutive_clean' | 'rating_threshold' |
'trust_threshold' | 'events_stewarded' | 'members_managed' | 'championships_won';
value: number;
operator: '>=' | '>' | '=' | '<' | '<=';
}
export class Achievement {
readonly id: string;
readonly name: string;
readonly description: string;
readonly category: AchievementCategory;
readonly rarity: AchievementRarity;
readonly iconUrl?: string;
readonly points: number;
readonly requirements: AchievementRequirement[];
readonly isSecret: boolean;
readonly createdAt: Date;
private constructor(props: AchievementProps) {
this.id = props.id;
this.name = props.name;
this.description = props.description;
this.category = props.category;
this.rarity = props.rarity;
this.iconUrl = props.iconUrl;
this.points = props.points;
this.requirements = props.requirements;
this.isSecret = props.isSecret;
this.createdAt = props.createdAt;
}
static create(props: Omit<AchievementProps, 'createdAt'> & { createdAt?: Date }): Achievement {
if (!props.id || props.id.trim().length === 0) {
throw new Error('Achievement ID is required');
}
if (!props.name || props.name.trim().length === 0) {
throw new Error('Achievement name is required');
}
if (props.requirements.length === 0) {
throw new Error('Achievement must have at least one requirement');
}
return new Achievement({
...props,
createdAt: props.createdAt ?? new Date(),
});
}
/**
* Check if user stats meet all requirements
*/
checkRequirements(stats: Record<string, number>): boolean {
return this.requirements.every(req => {
const value = stats[req.type] ?? 0;
switch (req.operator) {
case '>=': return value >= req.value;
case '>': return value > req.value;
case '=': return value === req.value;
case '<': return value < req.value;
case '<=': return value <= req.value;
default: return false;
}
});
}
/**
* Get rarity color for display
*/
getRarityColor(): string {
const colors: Record<AchievementRarity, string> = {
common: '#9CA3AF',
uncommon: '#22C55E',
rare: '#3B82F6',
epic: '#A855F7',
legendary: '#F59E0B',
};
return colors[this.rarity];
}
/**
* Get display text for hidden achievements
*/
getDisplayName(): string {
if (this.isSecret) {
return '???';
}
return this.name;
}
getDisplayDescription(): string {
if (this.isSecret) {
return 'This achievement is secret. Keep playing to unlock it!';
}
return this.description;
}
}
// Predefined achievements for drivers
export const DRIVER_ACHIEVEMENTS: Omit<AchievementProps, 'createdAt'>[] = [
{
id: 'first-race',
name: 'First Steps',
description: 'Complete your first race',
category: 'driver',
rarity: 'common',
points: 10,
requirements: [{ type: 'races_completed', value: 1, operator: '>=' }],
isSecret: false,
},
{
id: 'ten-races',
name: 'Getting Started',
description: 'Complete 10 races',
category: 'driver',
rarity: 'common',
points: 25,
requirements: [{ type: 'races_completed', value: 10, operator: '>=' }],
isSecret: false,
},
{
id: 'fifty-races',
name: 'Regular Racer',
description: 'Complete 50 races',
category: 'driver',
rarity: 'uncommon',
points: 50,
requirements: [{ type: 'races_completed', value: 50, operator: '>=' }],
isSecret: false,
},
{
id: 'hundred-races',
name: 'Veteran',
description: 'Complete 100 races',
category: 'driver',
rarity: 'rare',
points: 100,
requirements: [{ type: 'races_completed', value: 100, operator: '>=' }],
isSecret: false,
},
{
id: 'first-win',
name: 'Victory Lane',
description: 'Win your first race',
category: 'driver',
rarity: 'uncommon',
points: 50,
requirements: [{ type: 'wins', value: 1, operator: '>=' }],
isSecret: false,
},
{
id: 'ten-wins',
name: 'Serial Winner',
description: 'Win 10 races',
category: 'driver',
rarity: 'rare',
points: 100,
requirements: [{ type: 'wins', value: 10, operator: '>=' }],
isSecret: false,
},
{
id: 'first-podium',
name: 'Podium Finisher',
description: 'Finish on the podium',
category: 'driver',
rarity: 'common',
points: 25,
requirements: [{ type: 'podiums', value: 1, operator: '>=' }],
isSecret: false,
},
{
id: 'clean-streak-5',
name: 'Clean Racer',
description: 'Complete 5 consecutive races without incidents',
category: 'driver',
rarity: 'uncommon',
points: 50,
requirements: [{ type: 'consecutive_clean', value: 5, operator: '>=' }],
isSecret: false,
},
{
id: 'clean-streak-10',
name: 'Safety First',
description: 'Complete 10 consecutive races without incidents',
category: 'driver',
rarity: 'rare',
points: 100,
requirements: [{ type: 'consecutive_clean', value: 10, operator: '>=' }],
isSecret: false,
},
{
id: 'championship-win',
name: 'Champion',
description: 'Win a championship',
category: 'driver',
rarity: 'epic',
points: 200,
requirements: [{ type: 'championships_won', value: 1, operator: '>=' }],
isSecret: false,
},
{
id: 'triple-crown',
name: 'Triple Crown',
description: 'Win 3 championships',
category: 'driver',
rarity: 'legendary',
points: 500,
requirements: [{ type: 'championships_won', value: 3, operator: '>=' }],
isSecret: false,
},
{
id: 'elite-driver',
name: 'Elite Driver',
description: 'Reach Elite driver rating',
category: 'driver',
rarity: 'epic',
points: 250,
requirements: [{ type: 'rating_threshold', value: 90, operator: '>=' }],
isSecret: false,
},
];
// Predefined achievements for stewards
export const STEWARD_ACHIEVEMENTS: Omit<AchievementProps, 'createdAt'>[] = [
{
id: 'first-protest',
name: 'Justice Served',
description: 'Handle your first protest',
category: 'steward',
rarity: 'common',
points: 15,
requirements: [{ type: 'protests_handled', value: 1, operator: '>=' }],
isSecret: false,
},
{
id: 'ten-protests',
name: 'Fair Judge',
description: 'Handle 10 protests',
category: 'steward',
rarity: 'uncommon',
points: 50,
requirements: [{ type: 'protests_handled', value: 10, operator: '>=' }],
isSecret: false,
},
{
id: 'fifty-protests',
name: 'Senior Steward',
description: 'Handle 50 protests',
category: 'steward',
rarity: 'rare',
points: 100,
requirements: [{ type: 'protests_handled', value: 50, operator: '>=' }],
isSecret: false,
},
{
id: 'hundred-protests',
name: 'Chief Steward',
description: 'Handle 100 protests',
category: 'steward',
rarity: 'epic',
points: 200,
requirements: [{ type: 'protests_handled', value: 100, operator: '>=' }],
isSecret: false,
},
{
id: 'event-steward-10',
name: 'Event Official',
description: 'Steward 10 race events',
category: 'steward',
rarity: 'uncommon',
points: 50,
requirements: [{ type: 'events_stewarded', value: 10, operator: '>=' }],
isSecret: false,
},
{
id: 'trusted-steward',
name: 'Trusted Steward',
description: 'Achieve highly-trusted status',
category: 'steward',
rarity: 'rare',
points: 150,
requirements: [{ type: 'trust_threshold', value: 75, operator: '>=' }],
isSecret: false,
},
];
// Predefined achievements for admins
export const ADMIN_ACHIEVEMENTS: Omit<AchievementProps, 'createdAt'>[] = [
{
id: 'first-league',
name: 'League Founder',
description: 'Create your first league',
category: 'admin',
rarity: 'common',
points: 25,
requirements: [{ type: 'leagues_managed', value: 1, operator: '>=' }],
isSecret: false,
},
{
id: 'first-season',
name: 'Season Organizer',
description: 'Complete your first full season',
category: 'admin',
rarity: 'uncommon',
points: 50,
requirements: [{ type: 'seasons_completed', value: 1, operator: '>=' }],
isSecret: false,
},
{
id: 'five-seasons',
name: 'Experienced Organizer',
description: 'Complete 5 seasons',
category: 'admin',
rarity: 'rare',
points: 100,
requirements: [{ type: 'seasons_completed', value: 5, operator: '>=' }],
isSecret: false,
},
{
id: 'ten-seasons',
name: 'Veteran Organizer',
description: 'Complete 10 seasons',
category: 'admin',
rarity: 'epic',
points: 200,
requirements: [{ type: 'seasons_completed', value: 10, operator: '>=' }],
isSecret: false,
},
{
id: 'large-league',
name: 'Community Builder',
description: 'Manage a league with 50+ members',
category: 'admin',
rarity: 'rare',
points: 150,
requirements: [{ type: 'members_managed', value: 50, operator: '>=' }],
isSecret: false,
},
{
id: 'huge-league',
name: 'Empire Builder',
description: 'Manage a league with 100+ members',
category: 'admin',
rarity: 'epic',
points: 300,
requirements: [{ type: 'members_managed', value: 100, operator: '>=' }],
isSecret: false,
},
];
// Community achievements (for all roles)
export const COMMUNITY_ACHIEVEMENTS: Omit<AchievementProps, 'createdAt'>[] = [
{
id: 'community-leader',
name: 'Community Leader',
description: 'Achieve community leader trust level',
category: 'community',
rarity: 'legendary',
points: 500,
requirements: [{ type: 'trust_threshold', value: 90, operator: '>=' }],
isSecret: false,
},
];

View File

@@ -0,0 +1,151 @@
/**
* Domain Entity: SponsorAccount
*
* Represents a sponsor's login account in the identity bounded context.
* Separate from the racing domain's Sponsor entity which holds business data.
*/
import { UserId } from '../value-objects/UserId';
import type { EmailValidationResult } from '../value-objects/EmailAddress';
import { validateEmail } from '../value-objects/EmailAddress';
export interface SponsorAccountProps {
id: UserId;
sponsorId: string; // Reference to racing domain's Sponsor entity
email: string;
passwordHash: string;
companyName: string;
isActive: boolean;
createdAt: Date;
lastLoginAt?: Date;
}
export class SponsorAccount {
private readonly id: UserId;
private readonly sponsorId: string;
private email: string;
private passwordHash: string;
private companyName: string;
private isActive: boolean;
private readonly createdAt: Date;
private lastLoginAt?: Date;
private constructor(props: SponsorAccountProps) {
this.id = props.id;
this.sponsorId = props.sponsorId;
this.email = props.email;
this.passwordHash = props.passwordHash;
this.companyName = props.companyName;
this.isActive = props.isActive;
this.createdAt = props.createdAt;
this.lastLoginAt = props.lastLoginAt;
}
public static create(props: Omit<SponsorAccountProps, 'createdAt' | 'isActive'> & {
createdAt?: Date;
isActive?: boolean;
}): SponsorAccount {
if (!props.sponsorId || !props.sponsorId.trim()) {
throw new Error('SponsorAccount sponsorId is required');
}
if (!props.companyName || !props.companyName.trim()) {
throw new Error('SponsorAccount companyName is required');
}
if (!props.passwordHash || !props.passwordHash.trim()) {
throw new Error('SponsorAccount passwordHash is required');
}
const emailResult: EmailValidationResult = validateEmail(props.email);
if (!emailResult.success) {
throw new Error(emailResult.error);
}
return new SponsorAccount({
...props,
email: emailResult.email,
createdAt: props.createdAt ?? new Date(),
isActive: props.isActive ?? true,
});
}
public getId(): UserId {
return this.id;
}
public getSponsorId(): string {
return this.sponsorId;
}
public getEmail(): string {
return this.email;
}
public getPasswordHash(): string {
return this.passwordHash;
}
public getCompanyName(): string {
return this.companyName;
}
public getIsActive(): boolean {
return this.isActive;
}
public getCreatedAt(): Date {
return this.createdAt;
}
public getLastLoginAt(): Date | undefined {
return this.lastLoginAt;
}
public canLogin(): boolean {
return this.isActive;
}
public recordLogin(): SponsorAccount {
return new SponsorAccount({
id: this.id,
sponsorId: this.sponsorId,
email: this.email,
passwordHash: this.passwordHash,
companyName: this.companyName,
isActive: this.isActive,
createdAt: this.createdAt,
lastLoginAt: new Date(),
});
}
public deactivate(): SponsorAccount {
return new SponsorAccount({
id: this.id,
sponsorId: this.sponsorId,
email: this.email,
passwordHash: this.passwordHash,
companyName: this.companyName,
isActive: false,
createdAt: this.createdAt,
lastLoginAt: this.lastLoginAt,
});
}
public updatePassword(newPasswordHash: string): SponsorAccount {
if (!newPasswordHash || !newPasswordHash.trim()) {
throw new Error('Password hash cannot be empty');
}
return new SponsorAccount({
id: this.id,
sponsorId: this.sponsorId,
email: this.email,
passwordHash: newPasswordHash,
companyName: this.companyName,
isActive: this.isActive,
createdAt: this.createdAt,
lastLoginAt: this.lastLoginAt,
});
}
}

View File

@@ -0,0 +1,83 @@
/**
* Domain Entity: UserAchievement
*
* Represents an achievement earned by a specific user.
*/
export interface UserAchievementProps {
id: string;
userId: string;
achievementId: string;
earnedAt: Date;
notifiedAt?: Date;
progress?: number; // For partial progress tracking (0-100)
}
export class UserAchievement {
readonly id: string;
readonly userId: string;
readonly achievementId: string;
readonly earnedAt: Date;
readonly notifiedAt?: Date;
readonly progress: number;
private constructor(props: UserAchievementProps) {
this.id = props.id;
this.userId = props.userId;
this.achievementId = props.achievementId;
this.earnedAt = props.earnedAt;
this.notifiedAt = props.notifiedAt;
this.progress = props.progress ?? 100;
}
static create(props: UserAchievementProps): UserAchievement {
if (!props.id || props.id.trim().length === 0) {
throw new Error('UserAchievement ID is required');
}
if (!props.userId || props.userId.trim().length === 0) {
throw new Error('UserAchievement userId is required');
}
if (!props.achievementId || props.achievementId.trim().length === 0) {
throw new Error('UserAchievement achievementId is required');
}
return new UserAchievement(props);
}
/**
* Mark achievement as notified to user
*/
markNotified(): UserAchievement {
return new UserAchievement({
...this,
notifiedAt: new Date(),
});
}
/**
* Update progress towards achievement
*/
updateProgress(progress: number): UserAchievement {
const clampedProgress = Math.max(0, Math.min(100, progress));
return new UserAchievement({
...this,
progress: clampedProgress,
});
}
/**
* Check if achievement is fully earned
*/
isComplete(): boolean {
return this.progress >= 100;
}
/**
* Check if user has been notified
*/
isNotified(): boolean {
return this.notifiedAt !== undefined;
}
}

View File

@@ -0,0 +1,28 @@
/**
* Repository Interface: IAchievementRepository
*
* Defines operations for Achievement and UserAchievement entities
*/
import type { Achievement, AchievementCategory } from '../entities/Achievement';
import type { UserAchievement } from '../entities/UserAchievement';
export interface IAchievementRepository {
// Achievement operations
findAchievementById(id: string): Promise<Achievement | null>;
findAllAchievements(): Promise<Achievement[]>;
findAchievementsByCategory(category: AchievementCategory): Promise<Achievement[]>;
createAchievement(achievement: Achievement): Promise<Achievement>;
// UserAchievement operations
findUserAchievementById(id: string): Promise<UserAchievement | null>;
findUserAchievementsByUserId(userId: string): Promise<UserAchievement[]>;
findUserAchievementByUserAndAchievement(userId: string, achievementId: string): Promise<UserAchievement | null>;
hasUserEarnedAchievement(userId: string, achievementId: string): Promise<boolean>;
createUserAchievement(userAchievement: UserAchievement): Promise<UserAchievement>;
updateUserAchievement(userAchievement: UserAchievement): Promise<UserAchievement>;
// Stats
getAchievementLeaderboard(limit: number): Promise<{ userId: string; points: number; count: number }[]>;
getUserAchievementStats(userId: string): Promise<{ total: number; points: number; byCategory: Record<AchievementCategory, number> }>;
}

View File

@@ -0,0 +1,16 @@
/**
* Repository Interface: ISponsorAccountRepository
*
* Defines persistence operations for SponsorAccount entities.
*/
import type { SponsorAccount } from '../entities/SponsorAccount';
import type { UserId } from '../value-objects/UserId';
export interface ISponsorAccountRepository {
save(account: SponsorAccount): Promise<void>;
findById(id: UserId): Promise<SponsorAccount | null>;
findBySponsorId(sponsorId: string): Promise<SponsorAccount | null>;
findByEmail(email: string): Promise<SponsorAccount | null>;
delete(id: UserId): Promise<void>;
}

View File

@@ -0,0 +1,49 @@
/**
* Repository Interface: IUserRatingRepository
*
* Defines operations for UserRating value objects
*/
import type { UserRating } from '../value-objects/UserRating';
export interface IUserRatingRepository {
/**
* Find rating by user ID
*/
findByUserId(userId: string): Promise<UserRating | null>;
/**
* Find ratings by multiple user IDs
*/
findByUserIds(userIds: string[]): Promise<UserRating[]>;
/**
* Save or update a user rating
*/
save(rating: UserRating): Promise<UserRating>;
/**
* Get top rated drivers
*/
getTopDrivers(limit: number): Promise<UserRating[]>;
/**
* Get top trusted users
*/
getTopTrusted(limit: number): Promise<UserRating[]>;
/**
* Get eligible stewards (based on trust and fairness thresholds)
*/
getEligibleStewards(): Promise<UserRating[]>;
/**
* Get ratings by driver tier
*/
findByDriverTier(tier: 'rookie' | 'amateur' | 'semi-pro' | 'pro' | 'elite'): Promise<UserRating[]>;
/**
* Delete rating by user ID
*/
delete(userId: string): Promise<void>;
}

View File

@@ -0,0 +1,255 @@
/**
* Value Object: UserRating
*
* Multi-dimensional rating system for users covering:
* - Driver skill: racing ability, lap times, consistency
* - Admin competence: league management, event organization
* - Steward fairness: protest handling, penalty consistency
* - Trust score: reliability, sportsmanship, rule compliance
* - Fairness score: clean racing, incident involvement
*/
export interface RatingDimension {
value: number; // Current rating value (0-100 scale)
confidence: number; // Confidence level based on sample size (0-1)
sampleSize: number; // Number of events contributing to this rating
trend: 'rising' | 'stable' | 'falling';
lastUpdated: Date;
}
export interface UserRatingProps {
userId: string;
driver: RatingDimension;
admin: RatingDimension;
steward: RatingDimension;
trust: RatingDimension;
fairness: RatingDimension;
overallReputation: number;
createdAt: Date;
updatedAt: Date;
}
const DEFAULT_DIMENSION: RatingDimension = {
value: 50,
confidence: 0,
sampleSize: 0,
trend: 'stable',
lastUpdated: new Date(),
};
export class UserRating {
readonly userId: string;
readonly driver: RatingDimension;
readonly admin: RatingDimension;
readonly steward: RatingDimension;
readonly trust: RatingDimension;
readonly fairness: RatingDimension;
readonly overallReputation: number;
readonly createdAt: Date;
readonly updatedAt: Date;
private constructor(props: UserRatingProps) {
this.userId = props.userId;
this.driver = props.driver;
this.admin = props.admin;
this.steward = props.steward;
this.trust = props.trust;
this.fairness = props.fairness;
this.overallReputation = props.overallReputation;
this.createdAt = props.createdAt;
this.updatedAt = props.updatedAt;
}
static create(userId: string): UserRating {
if (!userId || userId.trim().length === 0) {
throw new Error('UserRating userId is required');
}
const now = new Date();
return new UserRating({
userId,
driver: { ...DEFAULT_DIMENSION, lastUpdated: now },
admin: { ...DEFAULT_DIMENSION, lastUpdated: now },
steward: { ...DEFAULT_DIMENSION, lastUpdated: now },
trust: { ...DEFAULT_DIMENSION, lastUpdated: now },
fairness: { ...DEFAULT_DIMENSION, lastUpdated: now },
overallReputation: 50,
createdAt: now,
updatedAt: now,
});
}
static restore(props: UserRatingProps): UserRating {
return new UserRating(props);
}
/**
* Update driver rating based on race performance
*/
updateDriverRating(
newValue: number,
weight: number = 1
): UserRating {
const updated = this.updateDimension(this.driver, newValue, weight);
return this.withUpdates({ driver: updated });
}
/**
* Update admin rating based on league management feedback
*/
updateAdminRating(
newValue: number,
weight: number = 1
): UserRating {
const updated = this.updateDimension(this.admin, newValue, weight);
return this.withUpdates({ admin: updated });
}
/**
* Update steward rating based on protest handling feedback
*/
updateStewardRating(
newValue: number,
weight: number = 1
): UserRating {
const updated = this.updateDimension(this.steward, newValue, weight);
return this.withUpdates({ steward: updated });
}
/**
* Update trust score based on reliability and sportsmanship
*/
updateTrustScore(
newValue: number,
weight: number = 1
): UserRating {
const updated = this.updateDimension(this.trust, newValue, weight);
return this.withUpdates({ trust: updated });
}
/**
* Update fairness score based on clean racing incidents
*/
updateFairnessScore(
newValue: number,
weight: number = 1
): UserRating {
const updated = this.updateDimension(this.fairness, newValue, weight);
return this.withUpdates({ fairness: updated });
}
/**
* Calculate weighted overall reputation
*/
calculateOverallReputation(): number {
// Weight dimensions by confidence and importance
const weights = {
driver: 0.25 * this.driver.confidence,
admin: 0.15 * this.admin.confidence,
steward: 0.15 * this.steward.confidence,
trust: 0.25 * this.trust.confidence,
fairness: 0.20 * this.fairness.confidence,
};
const totalWeight = Object.values(weights).reduce((sum, w) => sum + w, 0);
if (totalWeight === 0) {
return 50; // Default when no ratings yet
}
const weightedSum =
this.driver.value * weights.driver +
this.admin.value * weights.admin +
this.steward.value * weights.steward +
this.trust.value * weights.trust +
this.fairness.value * weights.fairness;
return Math.round(weightedSum / totalWeight);
}
/**
* Get rating tier for display
*/
getDriverTier(): 'rookie' | 'amateur' | 'semi-pro' | 'pro' | 'elite' {
if (this.driver.value >= 90) return 'elite';
if (this.driver.value >= 75) return 'pro';
if (this.driver.value >= 60) return 'semi-pro';
if (this.driver.value >= 40) return 'amateur';
return 'rookie';
}
/**
* Get trust level for matchmaking
*/
getTrustLevel(): 'unverified' | 'trusted' | 'highly-trusted' | 'community-leader' {
if (this.trust.value >= 90 && this.trust.sampleSize >= 50) return 'community-leader';
if (this.trust.value >= 75 && this.trust.sampleSize >= 20) return 'highly-trusted';
if (this.trust.value >= 60 && this.trust.sampleSize >= 5) return 'trusted';
return 'unverified';
}
/**
* Check if user is eligible to be a steward
*/
canBeSteward(): boolean {
return (
this.trust.value >= 70 &&
this.fairness.value >= 70 &&
this.trust.sampleSize >= 10
);
}
/**
* Check if user is eligible to be an admin
*/
canBeAdmin(): boolean {
return (
this.trust.value >= 60 &&
this.trust.sampleSize >= 5
);
}
private updateDimension(
dimension: RatingDimension,
newValue: number,
weight: number
): RatingDimension {
const clampedValue = Math.max(0, Math.min(100, newValue));
const newSampleSize = dimension.sampleSize + weight;
// Exponential moving average with decay based on sample size
const alpha = Math.min(0.3, 1 / (dimension.sampleSize + 1));
const updatedValue = dimension.value * (1 - alpha) + clampedValue * alpha;
// Calculate confidence (asymptotic to 1)
const confidence = 1 - Math.exp(-newSampleSize / 20);
// Determine trend
const valueDiff = updatedValue - dimension.value;
let trend: 'rising' | 'stable' | 'falling' = 'stable';
if (valueDiff > 2) trend = 'rising';
if (valueDiff < -2) trend = 'falling';
return {
value: Math.round(updatedValue * 10) / 10,
confidence: Math.round(confidence * 100) / 100,
sampleSize: newSampleSize,
trend,
lastUpdated: new Date(),
};
}
private withUpdates(updates: Partial<UserRatingProps>): UserRating {
const newRating = new UserRating({
...this,
...updates,
updatedAt: new Date(),
});
// Recalculate overall reputation
return new UserRating({
...newRating,
overallReputation: newRating.calculateOverallReputation(),
});
}
}

View File

@@ -1,6 +1,18 @@
export * from './domain/value-objects/EmailAddress';
export * from './domain/value-objects/UserId';
export * from './domain/value-objects/UserRating';
export * from './domain/entities/User';
export * from './domain/entities/SponsorAccount';
export * from './domain/entities/Achievement';
export * from './domain/entities/UserAchievement';
export * from './domain/repositories/IUserRepository';
export * from './domain/repositories/ISponsorAccountRepository';
export * from './domain/repositories/IUserRatingRepository';
export * from './domain/repositories/IAchievementRepository';
export * from './infrastructure/repositories/InMemoryUserRatingRepository';
export * from './infrastructure/repositories/InMemoryAchievementRepository';
export * from './application/dto/AuthenticatedUserDTO';
export * from './application/dto/AuthSessionDTO';

View File

@@ -0,0 +1,170 @@
/**
* Infrastructure Adapter: InMemoryAchievementRepository
*
* In-memory implementation of IAchievementRepository
*/
import {
Achievement,
AchievementCategory,
DRIVER_ACHIEVEMENTS,
STEWARD_ACHIEVEMENTS,
ADMIN_ACHIEVEMENTS,
COMMUNITY_ACHIEVEMENTS,
} from '../../domain/entities/Achievement';
import { UserAchievement } from '../../domain/entities/UserAchievement';
import type { IAchievementRepository } from '../../domain/repositories/IAchievementRepository';
export class InMemoryAchievementRepository implements IAchievementRepository {
private achievements: Map<string, Achievement> = new Map();
private userAchievements: Map<string, UserAchievement> = new Map();
constructor() {
// Seed with predefined achievements
this.seedAchievements();
}
private seedAchievements(): void {
const allAchievements = [
...DRIVER_ACHIEVEMENTS,
...STEWARD_ACHIEVEMENTS,
...ADMIN_ACHIEVEMENTS,
...COMMUNITY_ACHIEVEMENTS,
];
for (const props of allAchievements) {
const achievement = Achievement.create(props);
this.achievements.set(achievement.id, achievement);
}
}
// Achievement operations
async findAchievementById(id: string): Promise<Achievement | null> {
return this.achievements.get(id) ?? null;
}
async findAllAchievements(): Promise<Achievement[]> {
return Array.from(this.achievements.values());
}
async findAchievementsByCategory(category: AchievementCategory): Promise<Achievement[]> {
return Array.from(this.achievements.values())
.filter(a => a.category === category);
}
async createAchievement(achievement: Achievement): Promise<Achievement> {
if (this.achievements.has(achievement.id)) {
throw new Error('Achievement with this ID already exists');
}
this.achievements.set(achievement.id, achievement);
return achievement;
}
// UserAchievement operations
async findUserAchievementById(id: string): Promise<UserAchievement | null> {
return this.userAchievements.get(id) ?? null;
}
async findUserAchievementsByUserId(userId: string): Promise<UserAchievement[]> {
return Array.from(this.userAchievements.values())
.filter(ua => ua.userId === userId);
}
async findUserAchievementByUserAndAchievement(
userId: string,
achievementId: string
): Promise<UserAchievement | null> {
for (const ua of this.userAchievements.values()) {
if (ua.userId === userId && ua.achievementId === achievementId) {
return ua;
}
}
return null;
}
async hasUserEarnedAchievement(userId: string, achievementId: string): Promise<boolean> {
const ua = await this.findUserAchievementByUserAndAchievement(userId, achievementId);
return ua !== null && ua.isComplete();
}
async createUserAchievement(userAchievement: UserAchievement): Promise<UserAchievement> {
if (this.userAchievements.has(userAchievement.id)) {
throw new Error('UserAchievement with this ID already exists');
}
this.userAchievements.set(userAchievement.id, userAchievement);
return userAchievement;
}
async updateUserAchievement(userAchievement: UserAchievement): Promise<UserAchievement> {
if (!this.userAchievements.has(userAchievement.id)) {
throw new Error('UserAchievement not found');
}
this.userAchievements.set(userAchievement.id, userAchievement);
return userAchievement;
}
// Stats
async getAchievementLeaderboard(limit: number): Promise<{ userId: string; points: number; count: number }[]> {
const userStats = new Map<string, { points: number; count: number }>();
for (const ua of this.userAchievements.values()) {
if (!ua.isComplete()) continue;
const achievement = this.achievements.get(ua.achievementId);
if (!achievement) continue;
const existing = userStats.get(ua.userId) ?? { points: 0, count: 0 };
userStats.set(ua.userId, {
points: existing.points + achievement.points,
count: existing.count + 1,
});
}
return Array.from(userStats.entries())
.map(([userId, stats]) => ({ userId, ...stats }))
.sort((a, b) => b.points - a.points)
.slice(0, limit);
}
async getUserAchievementStats(userId: string): Promise<{
total: number;
points: number;
byCategory: Record<AchievementCategory, number>
}> {
const userAchievements = await this.findUserAchievementsByUserId(userId);
const completedAchievements = userAchievements.filter(ua => ua.isComplete());
const byCategory: Record<AchievementCategory, number> = {
driver: 0,
steward: 0,
admin: 0,
community: 0,
};
let points = 0;
for (const ua of completedAchievements) {
const achievement = this.achievements.get(ua.achievementId);
if (achievement) {
points += achievement.points;
byCategory[achievement.category]++;
}
}
return {
total: completedAchievements.length,
points,
byCategory,
};
}
// Test helpers
clearUserAchievements(): void {
this.userAchievements.clear();
}
clear(): void {
this.achievements.clear();
this.userAchievements.clear();
}
}

View File

@@ -0,0 +1,48 @@
/**
* Infrastructure: InMemorySponsorAccountRepository
*
* In-memory implementation of ISponsorAccountRepository for development/testing.
*/
import type { ISponsorAccountRepository } from '../../domain/repositories/ISponsorAccountRepository';
import type { SponsorAccount } from '../../domain/entities/SponsorAccount';
import type { UserId } from '../../domain/value-objects/UserId';
export class InMemorySponsorAccountRepository implements ISponsorAccountRepository {
private accounts: Map<string, SponsorAccount> = new Map();
async save(account: SponsorAccount): Promise<void> {
this.accounts.set(account.getId().value, account);
}
async findById(id: UserId): Promise<SponsorAccount | null> {
return this.accounts.get(id.value) ?? null;
}
async findBySponsorId(sponsorId: string): Promise<SponsorAccount | null> {
return Array.from(this.accounts.values()).find(
a => a.getSponsorId() === sponsorId
) ?? null;
}
async findByEmail(email: string): Promise<SponsorAccount | null> {
const normalizedEmail = email.toLowerCase().trim();
return Array.from(this.accounts.values()).find(
a => a.getEmail().toLowerCase() === normalizedEmail
) ?? null;
}
async delete(id: UserId): Promise<void> {
this.accounts.delete(id.value);
}
// Helper for testing
clear(): void {
this.accounts.clear();
}
// Helper for seeding demo data
seed(accounts: SponsorAccount[]): void {
accounts.forEach(a => this.accounts.set(a.getId().value, a));
}
}

View File

@@ -0,0 +1,65 @@
/**
* Infrastructure Adapter: InMemoryUserRatingRepository
*
* In-memory implementation of IUserRatingRepository
*/
import { UserRating } from '../../domain/value-objects/UserRating';
import type { IUserRatingRepository } from '../../domain/repositories/IUserRatingRepository';
export class InMemoryUserRatingRepository implements IUserRatingRepository {
private ratings: Map<string, UserRating> = new Map();
async findByUserId(userId: string): Promise<UserRating | null> {
return this.ratings.get(userId) ?? null;
}
async findByUserIds(userIds: string[]): Promise<UserRating[]> {
const results: UserRating[] = [];
for (const userId of userIds) {
const rating = this.ratings.get(userId);
if (rating) {
results.push(rating);
}
}
return results;
}
async save(rating: UserRating): Promise<UserRating> {
this.ratings.set(rating.userId, rating);
return rating;
}
async getTopDrivers(limit: number): Promise<UserRating[]> {
return Array.from(this.ratings.values())
.filter(r => r.driver.sampleSize > 0)
.sort((a, b) => b.driver.value - a.driver.value)
.slice(0, limit);
}
async getTopTrusted(limit: number): Promise<UserRating[]> {
return Array.from(this.ratings.values())
.filter(r => r.trust.sampleSize > 0)
.sort((a, b) => b.trust.value - a.trust.value)
.slice(0, limit);
}
async getEligibleStewards(): Promise<UserRating[]> {
return Array.from(this.ratings.values())
.filter(r => r.canBeSteward());
}
async findByDriverTier(tier: 'rookie' | 'amateur' | 'semi-pro' | 'pro' | 'elite'): Promise<UserRating[]> {
return Array.from(this.ratings.values())
.filter(r => r.getDriverTier() === tier);
}
async delete(userId: string): Promise<void> {
this.ratings.delete(userId);
}
// Test helper
clear(): void {
this.ratings.clear();
}
}