From 57414da788ebf593c492bf4b00e281a452870fef Mon Sep 17 00:00:00 2001 From: Timotej Zatko Date: Thu, 10 Sep 2026 16:40:01 +0200 Subject: [PATCH] fix: export the tombola level for octoberfest bribes The level was read as `response.construction_id || data.enhance`, and an octoberfest bribe/upgrade carries neither: the request sends no `enhance`, and the bribe response has no `construction_id`, reporting the level as `enhance` on itself instead. The level came out undefined, and jQuery deletes an undefined value from the ajax data rather than sending it empty, so /service/tombola-export rejected every bribe spin with "Level is not defined!". Normal spins, which do send `enhance`, were unaffected, so only part of each event went missing. Regressed in 14a9728, which swapped `response.enhance` for `data.enhance` to fix the easter level. Read the enhance from the request first and the response second, by first defined rather than with `||`, since 0 is a real level - the un-enhanced spin. `construction_id` is no longer a source: it is 0 on every octoberfest spin and no recorded level has ever come from it (every tombola page from 2022 on shows only 0, 25, 150 and 800), so reading it first would mask the real level. It only appeared to work because `||` skipped it while it was falsy. Two things kept this quiet. A spin with no resolvable level now reports through the error tracker instead of firing a request that cannot succeed, keeping the local stats, which do not use the level. And exportSpin passed only a success callback, so a rejected export vanished; it now warns and reports on every failure. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_017pYtZPqMDyRYtvJ7Jqxqw9 --- src/@types/the-west/index.d.ts | 3 +- .../tombola/tombola-exporter.spec.ts | 141 ++++++++++++++++++ src/components/tombola/tombola-exporter.ts | 72 ++++++--- 3 files changed, 198 insertions(+), 18 deletions(-) create mode 100644 src/components/tombola/tombola-exporter.spec.ts diff --git a/src/@types/the-west/index.d.ts b/src/@types/the-west/index.d.ts index 7adce4d..5f80485 100644 --- a/src/@types/the-west/index.d.ts +++ b/src/@types/the-west/index.d.ts @@ -304,6 +304,7 @@ export interface WheelofFortuneGambleXHRResponse { failed?: boolean; outcome?: { itemEnhance: number; itemId: number }; construction_id?: number; // independence day + enhance?: number; // octoberfest, reported here instead of in the request data after a bribe streak?: number; // easter cost?: unknown; // dotd stages?: Array<{ rewards: { item: number } }>; // dotd @@ -329,7 +330,7 @@ export interface WheelofFortuneConsructor { export interface WofData { wofid: number; action: string; - enhance: number; + enhance?: number; // absent on some actions, e.g. an octoberfest bribe payid: string | number; } diff --git a/src/components/tombola/tombola-exporter.spec.ts b/src/components/tombola/tombola-exporter.spec.ts new file mode 100644 index 0000000..d8b4678 --- /dev/null +++ b/src/components/tombola/tombola-exporter.spec.ts @@ -0,0 +1,141 @@ +import { Config } from '../config/config'; +import { ErrorTracker } from '../error-tracker/error-tracker'; +import { Language } from '../language/language'; +import { Logger } from '../logger/logger'; +import { Mock } from 'ts-mocks'; +import { TheWestWindow, WheelofFortuneGambleXHRResponse, WofContext, WofData } from '../../@types/the-west'; +import { TombolaExporter } from './tombola-exporter'; +import { Storage as TWCalcStorage } from '../storage/storage'; + +type Response = Partial; + +const tombolaId = 60; + +/** Minimal stand-in for the jqXHR that `$.get` returns. */ +function fakeJqXHR(): unknown { + const xhr = { + done(cb: (resp: unknown) => void) { + cb({ saved: true }); + return xhr; + }, + fail() { + return xhr; + }, + }; + return xhr; +} + +describe('TombolaExporter', () => { + const website = 'https://tw-calc.net'; + + let get: jasmine.Spy; + let track: jasmine.Spy; + let wheelPrototype: { process: Function }; + + /** + * Wires the exporter up to a stand-in for the game's wheel of fortune. The stubbed + * `process` hands `response` straight to its callback, which is the seam the exporter + * patches itself into, so a call to `spin()` drives the real export path end to end. + */ + function setup(event: string, response: Response): void { + const polls: Array<() => void> = []; + + get = jasmine.createSpy('get').and.callFake(() => fakeJqXHR()); + track = jasmine.createSpy('track'); + + wheelPrototype = { + process(_action: string, _data: WofData, callback: Function, context: WofContext) { + callback.call(context, response); + }, + }; + + const win = { + $: { get } as unknown as TheWestWindow['$'], + Game: { sesData: { [event]: {} } }, + west: { wof: { WheelofFortune: { prototype: wheelPrototype } } }, + // collect the polls rather than running them inline: wofPatch clears the interval + // from inside the callback, which is only initialised once setInterval has returned + setInterval: ((fn: () => void) => { + polls.push(fn); + return 0; + }) as unknown as Window['setInterval'], + clearInterval: () => undefined, + } as unknown as TheWestWindow; + + const exporter = new TombolaExporter( + win, + {} as WindowLocalStorage['localStorage'], + new Mock({ + has: () => true, + getObject: () => ({} as T), + setObject: Mock.ANY_FUNC, + }).Object, + new Mock({ log: Mock.ANY_FUNC, warn: Mock.ANY_FUNC, error: Mock.ANY_FUNC }).Object, + new Mock({ website }).Object, + new Mock().Object, + new Mock({ track, execute: (fn: () => T) => fn() }).Object, + ); + + exporter.init(); + // first poll: applies the wheel of fortune patch. The dotd patch is skipped because this + // window has no WofDotdCardgameWindow. + polls.forEach(poll => poll()); + } + + function spin(action: string, data: Partial): void { + wheelPrototype.process.call( + { id: tombolaId }, + action, + data as WofData, + () => undefined, + {} as WofContext, + undefined, + () => undefined, + ); + } + + function exportedSpin(): Record { + expect(get).toHaveBeenCalled(); + const [url, payload] = get.calls.mostRecent().args; + expect(url).toBe(website + '/service/tombola-export'); + return payload; + } + + it('exports level 0 for an un-enhanced octoberfest spin', () => { + // construction_id is 0 on every octoberfest spin, and 0 is also a real level here + setup('Octoberfest', { construction_id: 0, itemId: 2354000, itemEnhance: 0, failed: false }); + + spin('main', { enhance: 0, payid: 2 }); + + expect(exportedSpin()).toEqual({ tombolaId, prize: 2354000, category: 0, level: 0 }); + expect(track).not.toHaveBeenCalled(); + }); + + it('exports the level from the response for an octoberfest bribe', () => { + // a bribe/upgrade carries no `enhance` in the request and reports it on the response + setup('Octoberfest', { outcome: { itemId: 54931000, itemEnhance: 25 }, enhance: 25, failed: false }); + + spin('bribe', { payid: 2 }); + + expect(exportedSpin()).toEqual({ tombolaId, prize: 54931000, category: 1, level: 25 }); + expect(track).not.toHaveBeenCalled(); + }); + + it('ignores construction_id, which is not a tombola level', () => { + setup('Independence', { construction_id: 3, itemId: 54931000, itemEnhance: 150, failed: false }); + + spin('main', { enhance: 0, payid: 2 }); + + expect(exportedSpin()).toEqual({ tombolaId, prize: 54931000, category: 2, level: 0 }); + }); + + it('prefers the request enhance over the one on the response', () => { + // the stake the spin was played at is the request's, so the response only stands in when + // the request carries none - as on a bribe + setup('Easter', { enhance: 800, itemId: 54931000, itemEnhance: 25, failed: false }); + + spin('main', { enhance: 25, payid: 2 }); + + expect(exportedSpin()).toEqual({ tombolaId, prize: 54931000, category: 1, level: 25 }); + }); +}); diff --git a/src/components/tombola/tombola-exporter.ts b/src/components/tombola/tombola-exporter.ts index 4dd3eb7..fc3c621 100644 --- a/src/components/tombola/tombola-exporter.ts +++ b/src/components/tombola/tombola-exporter.ts @@ -12,6 +12,7 @@ import { Component } from '../component.types'; import { Config } from '../config/config'; import { ErrorTracker } from '../error-tracker/error-tracker'; import { inject, singleton } from 'tsyringe'; +import { InvisibleError } from '../error-tracker/invisible-error'; import { Language } from '../language/language'; import { Logger } from '../logger/logger'; import { StorageKey } from '../storage/storage.types'; @@ -115,7 +116,7 @@ export class TombolaExporter implements Component { if (response && !response.failed && (response.itemId || response.outcome)) { const categoryType = response.itemEnhance || (response.outcome && response.outcome.itemEnhance); const prize = response.itemId || (response.outcome && response.outcome.itemId) || 0; - const level = response.construction_id || data.enhance; + const level = getLevel(data, response); let category = 0; switch (categoryType) { @@ -130,15 +131,24 @@ export class TombolaExporter implements Component { break; } - this.save( - { - tombolaId, - prize, - category, - level, - }, - true, - ); // TODO: change isFree from constant + const spin = { tombolaId, prize, category, level }; + + if (typeof level === 'undefined') { + // Every event that reaches this branch is exported with a level, and jQuery + // drops an undefined value from the query string instead of sending it empty, + // so the export would fail with "Level is not defined!". Keep the player's own + // stats - those do not use the level - and report where the level went instead + // of firing a request that cannot succeed. + this.addSpinToStorage(spin, true); + throw InvisibleError.of( + new Error( + `Unable to resolve the tombola level! event=${eventType} ` + + `data=${JSON.stringify(data)} response=[${Object.keys(response).join(', ')}]`, + ), + ); + } + + this.save(spin, true); // TODO: change isFree from constant } else { this.logger.warn('Unable to process WoF response!', response); } @@ -186,14 +196,21 @@ export class TombolaExporter implements Component { private exportSpin(spin: Spin): void { const { $ } = this.window; - $.get( - this.config.website + '/service/tombola-export', - spin, - resp => { + $.get(this.config.website + '/service/tombola-export', spin, null, 'jsonp') + .done(resp => { this.logger.log('tombola exported', resp); - }, - 'jsonp', - ); + }) + .fail((_jqXHR, textStatus: string, error: unknown) => { + this.logger.warn('unable to export the tombola spin', spin, textStatus, error); + this.errorTracker.track( + InvisibleError.of( + new Error( + `Unable to export the tombola spin! status=${textStatus} ` + `spin=${JSON.stringify(spin)}`, + ), + ), + 'TombolaExporter.exportSpin', + ); + }); } private addSpinToStorage(spin: Spin, isFree: boolean): void { @@ -289,6 +306,27 @@ export class TombolaExporter implements Component { } } +/** + * Reads the tombola level, which is the enhance the spin was played at - every event exported with + * a level has only ever recorded 0, 25, 150 or 800. It is normally in the spin request, but an + * octoberfest bribe/upgrade request carries no `enhance` and reports it on the response instead. + * + * A level of 0 is the un-enhanced spin, so the two sources are tried by *first defined*: a `||` + * chain would fall through a real 0 to the next source. `construction_id` is deliberately not a + * source - it is 0 on every octoberfest spin, and no recorded level has ever come from it. + * + * Returns undefined when neither source carries a level. + */ +function getLevel(data: WofData, response: WheelofFortuneGambleXHRResponse): number | undefined { + for (const level of [data.enhance, response.enhance]) { + if (typeof level !== 'undefined' && level !== null) { + return level; + } + } + + return undefined; +} + function getId(key: number | TombolaKey): number { if (typeof key === 'number') { return key;