Backend CI / type-check, build, tests (push) Successful in 1m16s
Server grades levels 7-13 and keeps castle attempt results separate from stored progress. Co-authored-by: Cursor <cursoragent@cursor.com>
150 lines
7.7 KiB
TypeScript
150 lines
7.7 KiB
TypeScript
/**
|
|
* Financial goal — temporary SQLite only.
|
|
*/
|
|
import assert from 'node:assert/strict'
|
|
import { mkdtempSync, rmSync } from 'node:fs'
|
|
import { tmpdir } from 'node:os'
|
|
import { join } from 'node:path'
|
|
import { ValidationPipe } from '@nestjs/common'
|
|
import { Test } from '@nestjs/testing'
|
|
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'
|
|
import { ApiExceptionFilter } from '../src/common/filters/api-exception.filter'
|
|
import { initialPlan, revisedPlan, INITIAL_RATES, EXCEPTION_RATES, CONTINUE_RATES } from '../src/gold-land/financial-goal/goal.math'
|
|
import { gradeFinancialGoalSubmission } from '../src/gold-land/financial-goal/goal.grader'
|
|
import { financialGoalMission } from '../src/gold-land/financial-goal/goal.mission'
|
|
import { GoldLandProgressionService } from '../src/gold-land/services/progression.service'
|
|
import type { DatabaseService } from '../src/database/database.service'
|
|
import { createDefaultUserState } from '../src/shared/catalog/default-user-state'
|
|
|
|
const USER = 'goal-test-user'
|
|
const testDir = mkdtempSync(join(tmpdir(), 'gold-land-goal-'))
|
|
process.env.DB_PATH = join(testDir, 'test.db')
|
|
process.env.NODE_ENV = 'test'
|
|
process.env.PORT = '3999'
|
|
process.env.JWT_SECRET = 'gold-land-dev-secret-change-in-production'
|
|
|
|
const correct = [
|
|
{ questionId: 'q-goal', answerId: 'specific' },
|
|
{ questionId: 'q-left', answerId: '90' },
|
|
{ questionId: 'q-weeks', answerId: '6' },
|
|
{ questionId: 'q-need', answerId: 'adjust' },
|
|
{ questionId: 'q-change', answerId: 'update' },
|
|
]
|
|
const wrong = ['vague', '120', '5', 'drop', 'keep']
|
|
|
|
function submission(plan: { initialWeekly: number; exceptionWeekly: number; continueWeekly: number }, count: number) {
|
|
return [
|
|
{ questionId: 'plan', plan },
|
|
...correct.map((answer, index) => (index < count ? answer : { questionId: answer.questionId, answerId: wrong[index]! })),
|
|
]
|
|
}
|
|
|
|
async function createApp(): Promise<NestFastifyApplication> {
|
|
const { AppModule } = await import('../src/app.module')
|
|
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile()
|
|
const app = moduleRef.createNestApplication<NestFastifyApplication>(new FastifyAdapter())
|
|
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))
|
|
app.useGlobalFilters(new ApiExceptionFilter())
|
|
await app.init()
|
|
await app.getHttpAdapter().getInstance().ready()
|
|
return app
|
|
}
|
|
|
|
async function run() {
|
|
assert.deepEqual(INITIAL_RATES.map((rate) => initialPlan(rate).weeks), [18, 9, 6, 5])
|
|
const sample = revisedPlan(15, 5, 15)
|
|
assert.equal(sample.balanceAfterTwo, 50)
|
|
assert.equal(sample.remainingWeeks, 5)
|
|
assert.equal(sample.totalWeeks, 7)
|
|
assert.equal(sample.finalBalance, 125)
|
|
const paused = revisedPlan(15, 0, 15)
|
|
assert.equal(paused.balanceAfterTwo, 45)
|
|
assert.equal(paused.totalWeeks, 7)
|
|
const totals: number[] = []
|
|
for (const initial of INITIAL_RATES) {
|
|
for (const exception of EXCEPTION_RATES) {
|
|
for (const cont of CONTINUE_RATES) {
|
|
const result = revisedPlan(initial, exception, cont)
|
|
assert.equal(result.totalWeeks, 2 + result.remainingWeeks)
|
|
assert.equal(result.finalBalance, result.balanceAfterTwo + result.remainingWeeks * cont)
|
|
assert.ok(result.finalBalance >= 120)
|
|
totals.push(result.totalWeeks)
|
|
}
|
|
}
|
|
}
|
|
assert.equal(Math.min(...totals), 5)
|
|
|
|
const slow = { initialWeekly: 5, exceptionWeekly: 0, continueWeekly: 5 }
|
|
const fast = { initialWeekly: 20, exceptionWeekly: 10, continueWeekly: 20 }
|
|
assert.equal(gradeFinancialGoalSubmission(submission(slow, 0)).score, 0)
|
|
assert.equal(gradeFinancialGoalSubmission(submission(fast, 2)).score, 40)
|
|
assert.equal(gradeFinancialGoalSubmission(submission(slow, 3)).score, 60)
|
|
assert.equal(gradeFinancialGoalSubmission(submission(fast, 4)).score, 80)
|
|
assert.equal(gradeFinancialGoalSubmission(submission(slow, 5)).score, 100)
|
|
assert.equal(gradeFinancialGoalSubmission(submission(fast, 5)).score, 100)
|
|
assert.throws(() => gradeFinancialGoalSubmission(submission({ initialWeekly: 15, exceptionWeekly: 5, continueWeekly: 0 }, 5)))
|
|
assert.throws(() => gradeFinancialGoalSubmission([...submission(fast, 5), correct[0]!]))
|
|
assert.throws(() => gradeFinancialGoalSubmission(submission(fast, 5).map((answer) => ({ ...answer, weeks: 7 }))))
|
|
assert.equal(JSON.stringify(financialGoalMission).includes('correctOptionId'), false)
|
|
|
|
const app = await createApp()
|
|
const database = app.get((await import('../src/database/database.service')).DatabaseService) as DatabaseService
|
|
const progression = app.get(GoldLandProgressionService)
|
|
const db = database.getDb()
|
|
try {
|
|
const now = new Date().toISOString()
|
|
db.prepare('INSERT INTO users (id, state_json, updated_at) VALUES (?, ?, ?)').run(USER, JSON.stringify(createDefaultUserState(USER)), now)
|
|
const insert = db.prepare(`
|
|
INSERT INTO user_level_progress (
|
|
user_id, level_id, best_score, stars, attempts_count, started_at, completed_at, updated_at
|
|
) VALUES (?, ?, 80, 2, 1, ?, ?, ?)
|
|
`)
|
|
for (let id = 1; id <= 10; id += 1) insert.run(USER, id, now, now, now)
|
|
assert.throws(() => progression.startLevel(USER, 12))
|
|
insert.run(USER, 11, now, now, now)
|
|
assert.equal(progression.buildLevelItems(USER).find((level) => level.id === 12)?.status, 'available')
|
|
assert.equal(progression.buildLevelItems(USER).find((level) => level.id === 13)?.status, 'locked')
|
|
assert.throws(() => progression.completeLevel(USER, 12, { answers: submission(fast, 2) }))
|
|
const first = progression.completeLevel(USER, 12, { answers: submission(slow, 3) })
|
|
assert.equal(first.score, 60)
|
|
assert.equal(first.stars, 1)
|
|
assert.equal(first.reward.xp, 50 + 5)
|
|
assert.equal(first.reward.coins, 20 + 3)
|
|
const replay = progression.completeLevel(USER, 12, { answers: submission(fast, 3) })
|
|
assert.equal(replay.reward.coins, 0)
|
|
const improved = progression.completeLevel(USER, 12, { answers: submission({ initialWeekly: 15, exceptionWeekly: 5, continueWeekly: 15 }, 5) })
|
|
assert.equal(improved.feedback?.timeline.totalWeeks, 7)
|
|
assert.equal(improved.feedback?.timeline.finalBalance, 125)
|
|
assert.equal(improved.stars, 3)
|
|
assert.equal(improved.reward.xp, 10)
|
|
assert.equal(improved.reward.coins, 6)
|
|
assert.equal(progression.buildLevelItems(USER).find((level) => level.id === 13)?.status, 'available')
|
|
assert.equal(progression.buildLevelItems(USER).length, 13)
|
|
|
|
const parallelId = 'goal-parallel-user'
|
|
db.prepare('INSERT INTO users (id, state_json, updated_at) VALUES (?, ?, ?)').run(parallelId, JSON.stringify(createDefaultUserState(parallelId)), now)
|
|
for (let id = 1; id <= 11; id += 1) insert.run(parallelId, id, now, now, now)
|
|
const { JwtService } = await import('@nestjs/jwt')
|
|
const token = app.get(JwtService).sign({ userId: parallelId })
|
|
const body = { answers: submission(fast, 5) }
|
|
const [left, right] = await Promise.all([
|
|
app.inject({ method: 'POST', url: '/api/gold-land/levels/12/complete', headers: { authorization: `Bearer ${token}` }, payload: body }),
|
|
app.inject({ method: 'POST', url: '/api/gold-land/levels/12/complete', headers: { authorization: `Bearer ${token}` }, payload: body }),
|
|
])
|
|
assert.equal(left.statusCode, 200)
|
|
assert.equal(right.statusCode, 200)
|
|
const bodies = [left, right].map((response) => JSON.parse(response.payload) as { reward: { coins: number; xp: number } })
|
|
assert.equal(bodies.reduce((sum, item) => sum + item.reward.coins, 0), 20 + 9)
|
|
assert.equal(bodies.reduce((sum, item) => sum + item.reward.xp, 0), 50 + 15)
|
|
console.log('financial-goal tests passed')
|
|
} finally {
|
|
await app.close()
|
|
try { rmSync(testDir, { recursive: true, force: true }) } catch { /* ignore */ }
|
|
}
|
|
}
|
|
|
|
run().catch((error) => {
|
|
console.error(error)
|
|
process.exit(1)
|
|
})
|