fix(engine): finalize united events and auctions compatibly
This commit is contained in:
@@ -33,6 +33,7 @@ interface AuctionBidRow {
|
||||
id: number;
|
||||
generalId: number;
|
||||
amount: number;
|
||||
meta: unknown;
|
||||
}
|
||||
|
||||
interface AuctionDetail {
|
||||
@@ -49,6 +50,16 @@ const parseDetail = (detail: unknown): AuctionDetail => {
|
||||
return detail as AuctionDetail;
|
||||
};
|
||||
|
||||
const toFiniteNumber = (value: unknown): number => {
|
||||
const parsed = typeof value === 'string' ? Number(value) : value;
|
||||
return typeof parsed === 'number' && Number.isFinite(parsed) ? parsed : 0;
|
||||
};
|
||||
|
||||
const readRankTrackedAmount = (bid: AuctionBidRow | null): number => {
|
||||
if (!bid?.meta || typeof bid.meta !== 'object' || Array.isArray(bid.meta)) return 0;
|
||||
return Math.max(0, toFiniteNumber((bid.meta as Record<string, unknown>).inheritSpentTrackedAmount));
|
||||
};
|
||||
|
||||
const extendCloseDate = (options: {
|
||||
now: Date;
|
||||
closeAt: Date;
|
||||
@@ -107,14 +118,14 @@ const loadHighestBid = async (
|
||||
const rows = await prisma.$queryRaw<AuctionBidRow[]>(
|
||||
isReverse
|
||||
? GamePrisma.sql`
|
||||
SELECT id, general_id as "generalId", amount
|
||||
SELECT id, general_id as "generalId", amount, meta
|
||||
FROM auction_bid
|
||||
WHERE auction_id = ${auctionId}
|
||||
ORDER BY amount ASC, id ASC
|
||||
LIMIT 1
|
||||
`
|
||||
: GamePrisma.sql`
|
||||
SELECT id, general_id as "generalId", amount
|
||||
SELECT id, general_id as "generalId", amount, meta
|
||||
FROM auction_bid
|
||||
WHERE auction_id = ${auctionId}
|
||||
ORDER BY amount DESC, id ASC
|
||||
@@ -133,14 +144,14 @@ const loadMyPrevBid = async (
|
||||
const rows = await prisma.$queryRaw<AuctionBidRow[]>(
|
||||
isReverse
|
||||
? GamePrisma.sql`
|
||||
SELECT id, general_id as "generalId", amount
|
||||
SELECT id, general_id as "generalId", amount, meta
|
||||
FROM auction_bid
|
||||
WHERE auction_id = ${auctionId} AND general_id = ${generalId}
|
||||
ORDER BY amount ASC, id ASC
|
||||
LIMIT 1
|
||||
`
|
||||
: GamePrisma.sql`
|
||||
SELECT id, general_id as "generalId", amount
|
||||
SELECT id, general_id as "generalId", amount, meta
|
||||
FROM auction_bid
|
||||
WHERE auction_id = ${auctionId} AND general_id = ${generalId}
|
||||
ORDER BY amount DESC, id ASC
|
||||
@@ -340,6 +351,8 @@ export const createAuctionBidder = async (options: {
|
||||
|
||||
const eventId = randomUUID();
|
||||
const eventAt = now;
|
||||
const rankTrackedAmount = auction.type === 'UNIQUE_ITEM' ? readRankTrackedAmount(myPrevBid) + morePoint : 0;
|
||||
const previousRankTrackedAmount = readRankTrackedAmount(highestBid);
|
||||
|
||||
try {
|
||||
const persistBid = async (tx: GamePrisma.TransactionClient): Promise<void> => {
|
||||
@@ -352,7 +365,12 @@ export const createAuctionBidder = async (options: {
|
||||
${command.amount},
|
||||
${eventId},
|
||||
${eventAt},
|
||||
${JSON.stringify({ tryExtendCloseDate: command.tryExtendCloseDate ?? true })}::jsonb
|
||||
${JSON.stringify({
|
||||
tryExtendCloseDate: command.tryExtendCloseDate ?? true,
|
||||
...(auction.type === 'UNIQUE_ITEM'
|
||||
? { inheritSpentTrackedAmount: rankTrackedAmount }
|
||||
: {}),
|
||||
})}::jsonb
|
||||
)
|
||||
`
|
||||
);
|
||||
@@ -396,21 +414,42 @@ export const createAuctionBidder = async (options: {
|
||||
if (deductedRows.length === 0) {
|
||||
throw new Error('INSUFFICIENT_POINT');
|
||||
}
|
||||
await tx.$executeRaw(
|
||||
GamePrisma.sql`
|
||||
INSERT INTO rank_data (nation_id, general_id, type, value)
|
||||
SELECT nation_id, id, 'inherit_spent_dyn', ${morePoint}
|
||||
FROM general
|
||||
WHERE id = ${command.generalId}
|
||||
ON CONFLICT (general_id, type)
|
||||
DO UPDATE SET
|
||||
nation_id = EXCLUDED.nation_id,
|
||||
value = rank_data.value + EXCLUDED.value
|
||||
`
|
||||
);
|
||||
|
||||
if (highestBid && highestBid.generalId !== command.generalId && !myPrevBid) {
|
||||
const prevUserId = await resolveUserId(tx, highestBid.generalId);
|
||||
if (prevUserId) {
|
||||
await tx.$executeRaw(
|
||||
GamePrisma.sql`
|
||||
INSERT INTO inheritance_point (user_id, key, value, updated_at)
|
||||
VALUES (${prevUserId}, 'previous', ${highestBid.amount}, ${eventAt})
|
||||
ON CONFLICT (user_id, key)
|
||||
DO UPDATE SET
|
||||
value = inheritance_point.value + EXCLUDED.value,
|
||||
updated_at = EXCLUDED.updated_at
|
||||
`
|
||||
);
|
||||
if (!prevUserId) {
|
||||
throw new Error('USER_NOT_FOUND');
|
||||
}
|
||||
await tx.$executeRaw(
|
||||
GamePrisma.sql`
|
||||
INSERT INTO inheritance_point (user_id, key, value, updated_at)
|
||||
VALUES (${prevUserId}, 'previous', ${highestBid.amount}, ${eventAt})
|
||||
ON CONFLICT (user_id, key)
|
||||
DO UPDATE SET
|
||||
value = inheritance_point.value + EXCLUDED.value,
|
||||
updated_at = EXCLUDED.updated_at
|
||||
`
|
||||
);
|
||||
await tx.$executeRaw(
|
||||
GamePrisma.sql`
|
||||
UPDATE rank_data
|
||||
SET value = GREATEST(0, value - ${previousRankTrackedAmount})
|
||||
WHERE general_id = ${highestBid.generalId}
|
||||
AND type = 'inherit_spent_dyn'
|
||||
`
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -453,7 +492,36 @@ export const createAuctionBidder = async (options: {
|
||||
};
|
||||
}
|
||||
|
||||
if (auction.type !== 'UNIQUE_ITEM') {
|
||||
if (auction.type === 'UNIQUE_ITEM') {
|
||||
world.updateGeneral(command.generalId, {
|
||||
inheritancePoints: {
|
||||
...general.inheritancePoints,
|
||||
previous: toFiniteNumber(general.inheritancePoints?.previous) - morePoint,
|
||||
},
|
||||
meta: {
|
||||
...general.meta,
|
||||
inherit_spent_dyn: toFiniteNumber(general.meta.inherit_spent_dyn) + morePoint,
|
||||
},
|
||||
});
|
||||
if (highestBid && highestBid.generalId !== command.generalId && !myPrevBid) {
|
||||
const prev = world.getGeneralById(highestBid.generalId);
|
||||
if (prev) {
|
||||
world.updateGeneral(prev.id, {
|
||||
inheritancePoints: {
|
||||
...prev.inheritancePoints,
|
||||
previous: toFiniteNumber(prev.inheritancePoints?.previous) + highestBid.amount,
|
||||
},
|
||||
meta: {
|
||||
...prev.meta,
|
||||
inherit_spent_dyn: Math.max(
|
||||
0,
|
||||
toFiniteNumber(prev.meta.inherit_spent_dyn) - previousRankTrackedAmount
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const resourceType = auction.type === 'BUY_RICE' ? 'gold' : 'rice';
|
||||
world.updateGeneral(command.generalId, {
|
||||
gold: resourceType === 'gold' ? general.gold - morePoint : general.gold,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { TurnGeneral } from './types.js';
|
||||
|
||||
const DEX_LIMIT = 1_275_975;
|
||||
|
||||
export const STORED_INHERITANCE_KEYS = [
|
||||
'lived_month',
|
||||
'max_domestic_critical',
|
||||
'active_action',
|
||||
'unifier',
|
||||
'tournament',
|
||||
] as const;
|
||||
|
||||
export const ALL_MERGED_INHERITANCE_KEYS = [
|
||||
...STORED_INHERITANCE_KEYS,
|
||||
'max_belong',
|
||||
'combat',
|
||||
'sabotage',
|
||||
'dex',
|
||||
'betting',
|
||||
] as const;
|
||||
|
||||
export type MergedInheritanceKey = (typeof ALL_MERGED_INHERITANCE_KEYS)[number];
|
||||
|
||||
const readNumber = (source: Record<string, unknown>, key: string): number => {
|
||||
const value = source[key];
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
||||
if (typeof value === 'string') {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
const computeDexPoint = (general: TurnGeneral): number => {
|
||||
let totalDexterity = 0;
|
||||
for (let index = 1; index <= 5; index += 1) {
|
||||
let dexterity = readNumber(general.meta, `dex${index}`);
|
||||
if (dexterity > DEX_LIMIT) {
|
||||
totalDexterity += (dexterity - DEX_LIMIT) / 3;
|
||||
dexterity = DEX_LIMIT;
|
||||
}
|
||||
totalDexterity += dexterity;
|
||||
}
|
||||
return totalDexterity * 0.001;
|
||||
};
|
||||
|
||||
const computeBettingPoint = (general: TurnGeneral): number => {
|
||||
const wins = readNumber(general.meta, 'betwin');
|
||||
const gold = readNumber(general.meta, 'betgold');
|
||||
const wonGold = readNumber(general.meta, 'betwingold');
|
||||
const winRate = wonGold / Math.max(1000, gold);
|
||||
return wins * 10 * winRate ** 2;
|
||||
};
|
||||
|
||||
export const computeActiveInheritancePoint = (
|
||||
general: TurnGeneral,
|
||||
key: MergedInheritanceKey,
|
||||
storedOverride?: number
|
||||
): number => {
|
||||
const stored = storedOverride ?? general.inheritancePoints?.[key] ?? 0;
|
||||
switch (key) {
|
||||
case 'lived_month': {
|
||||
const value = readNumber(general.meta, 'inherit_lived_month');
|
||||
return value !== 0 ? value : stored;
|
||||
}
|
||||
case 'max_domestic_critical': {
|
||||
const value = readNumber(general.meta, 'max_domestic_critical');
|
||||
return value !== 0 ? value : stored;
|
||||
}
|
||||
case 'active_action': {
|
||||
const value = readNumber(general.meta, 'inherit_active_action');
|
||||
return value !== 0 ? value * 3 : stored;
|
||||
}
|
||||
case 'unifier':
|
||||
case 'tournament':
|
||||
return stored;
|
||||
case 'max_belong':
|
||||
return (
|
||||
Math.max(
|
||||
readNumber(general.meta, 'belong'),
|
||||
readNumber(general.meta, 'max_belong'),
|
||||
readNumber(general.meta, 'inherit_max_belong')
|
||||
) * 10
|
||||
);
|
||||
case 'combat':
|
||||
return readNumber(general.meta, 'rank_warnum') * 5;
|
||||
case 'sabotage':
|
||||
return readNumber(general.meta, 'firenum') * 20;
|
||||
case 'dex':
|
||||
return computeDexPoint(general);
|
||||
case 'betting':
|
||||
return computeBettingPoint(general);
|
||||
}
|
||||
};
|
||||
@@ -209,12 +209,16 @@ const parseActions = (raw: unknown): Array<{ name: string; args: readonly unknow
|
||||
});
|
||||
};
|
||||
|
||||
export interface ScenarioEventCalendarHandler extends TurnCalendarHandler {
|
||||
dispatchTarget(targetCode: string, context: TurnCalendarContext): Promise<void>;
|
||||
}
|
||||
|
||||
export const createMonthlyEventHandler = (options: {
|
||||
getWorld: () => InMemoryTurnWorld | null;
|
||||
startYear: number;
|
||||
actions?: MonthlyEventActionRegistry;
|
||||
}): TurnCalendarHandler => {
|
||||
const dispatch = async (targetCode: 'pre_month' | 'month', context: TurnCalendarContext): Promise<void> => {
|
||||
}): ScenarioEventCalendarHandler => {
|
||||
const dispatchTarget = async (targetCode: string, context: TurnCalendarContext): Promise<void> => {
|
||||
const world = options.getWorld();
|
||||
if (!world) {
|
||||
return;
|
||||
@@ -249,7 +253,8 @@ export const createMonthlyEventHandler = (options: {
|
||||
};
|
||||
|
||||
return {
|
||||
beforeMonthChanged: (context) => dispatch('pre_month', context),
|
||||
onMonthChanged: (context) => dispatch('month', context),
|
||||
beforeMonthChanged: (context) => dispatchTarget('pre_month', context),
|
||||
onMonthChanged: (context) => dispatchTarget('month', context),
|
||||
dispatchTarget,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -13,26 +13,11 @@ import {
|
||||
import { simpleSerialize } from '@sammo-ts/logic/war/utils.js';
|
||||
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
import { ALL_MERGED_INHERITANCE_KEYS, computeActiveInheritancePoint } from './inheritancePointCalculation.js';
|
||||
import type { MonthlyEventActionHandler } from './monthlyEventHandler.js';
|
||||
import type { TurnGeneral } from './types.js';
|
||||
|
||||
const LEGACY_ITEM_SLOTS: readonly ItemSlot[] = ['horse', 'weapon', 'book', 'item'];
|
||||
const DEX_LIMIT = 1_275_975;
|
||||
const STORED_INHERITANCE_KEYS = [
|
||||
'lived_month',
|
||||
'max_domestic_critical',
|
||||
'active_action',
|
||||
'unifier',
|
||||
'tournament',
|
||||
] as const;
|
||||
const ALL_MERGED_INHERITANCE_KEYS = [
|
||||
...STORED_INHERITANCE_KEYS,
|
||||
'max_belong',
|
||||
'combat',
|
||||
'sabotage',
|
||||
'dex',
|
||||
'betting',
|
||||
] as const;
|
||||
|
||||
const readNumber = (source: Record<string, unknown>, key: string): number => {
|
||||
const value = source[key];
|
||||
@@ -163,60 +148,6 @@ export const createLostUniqueItemHandler = (options: {
|
||||
};
|
||||
};
|
||||
|
||||
const computeDexPoint = (general: TurnGeneral): number => {
|
||||
let totalDexterity = 0;
|
||||
for (let index = 1; index <= 5; index += 1) {
|
||||
let dexterity = readNumber(general.meta, `dex${index}`);
|
||||
if (dexterity > DEX_LIMIT) {
|
||||
totalDexterity += (dexterity - DEX_LIMIT) / 3;
|
||||
dexterity = DEX_LIMIT;
|
||||
}
|
||||
totalDexterity += dexterity;
|
||||
}
|
||||
return totalDexterity * 0.001;
|
||||
};
|
||||
|
||||
const computeBettingPoint = (general: TurnGeneral): number => {
|
||||
const wins = readNumber(general.meta, 'betwin');
|
||||
const gold = readNumber(general.meta, 'betgold');
|
||||
const wonGold = readNumber(general.meta, 'betwingold');
|
||||
const winRate = wonGold / Math.max(1000, gold);
|
||||
return wins * 10 * winRate ** 2;
|
||||
};
|
||||
|
||||
const computeActiveInheritancePoint = (general: TurnGeneral, key: string): number => {
|
||||
const stored = general.inheritancePoints?.[key] ?? 0;
|
||||
switch (key) {
|
||||
case 'lived_month': {
|
||||
const value = readNumber(general.meta, 'inherit_lived_month');
|
||||
return value !== 0 ? value : stored;
|
||||
}
|
||||
case 'max_domestic_critical': {
|
||||
const value = readNumber(general.meta, 'max_domestic_critical');
|
||||
return value !== 0 ? value : stored;
|
||||
}
|
||||
case 'active_action': {
|
||||
const value = readNumber(general.meta, 'inherit_active_action');
|
||||
return value !== 0 ? value * 3 : stored;
|
||||
}
|
||||
case 'unifier':
|
||||
case 'tournament':
|
||||
return stored;
|
||||
case 'max_belong':
|
||||
return Math.max(readNumber(general.meta, 'belong'), readNumber(general.meta, 'inherit_max_belong')) * 10;
|
||||
case 'combat':
|
||||
return readNumber(general.meta, 'rank_warnum') * 5;
|
||||
case 'sabotage':
|
||||
return readNumber(general.meta, 'firenum') * 20;
|
||||
case 'dex':
|
||||
return computeDexPoint(general);
|
||||
case 'betting':
|
||||
return computeBettingPoint(general);
|
||||
default:
|
||||
return stored;
|
||||
}
|
||||
};
|
||||
|
||||
export const createMergeInheritPointRankHandler = (options: {
|
||||
getWorld: () => InMemoryTurnWorld | null;
|
||||
}): MonthlyEventActionHandler => {
|
||||
|
||||
@@ -36,6 +36,7 @@ import { loadTurnCommandProfile } from './turnCommandProfile.js';
|
||||
import { loadTurnWorldFromDatabase } from './worldLoader.js';
|
||||
import { shouldUseAi } from './ai/generalAi.js';
|
||||
import { createUnificationHandler } from './unificationHandler.js';
|
||||
import { loadPendingUnificationAuctionCancellations } from './unificationAuctionCancellation.js';
|
||||
import { createAuctionFinalizer } from '../auction/finalizer.js';
|
||||
import { createAuctionBidder } from '../auction/bidder.js';
|
||||
import { createNeutralAuctionRegistrar } from '../auction/neutralRegistrar.js';
|
||||
@@ -224,12 +225,6 @@ const createTurnDaemonRuntimeWithLease = async (
|
||||
snapshot.scenarioConfig.environment.scenarioEffect
|
||||
);
|
||||
const monthlyCommandEnv = buildCommandEnv(snapshot.scenarioConfig, snapshot.unitSet);
|
||||
const unification = options.calendarHandler
|
||||
? null
|
||||
: createUnificationHandler({
|
||||
profileName: options.profileName ?? options.profile,
|
||||
getWorld: () => worldRef,
|
||||
});
|
||||
const incomeHandler = createIncomeHandler({
|
||||
getWorld: () => worldRef,
|
||||
scenarioConfig: snapshot.scenarioConfig,
|
||||
@@ -404,6 +399,16 @@ const createTurnDaemonRuntimeWithLease = async (
|
||||
startYear: snapshot.scenarioMeta?.startYear ?? state.currentYear,
|
||||
actions: eventActions,
|
||||
});
|
||||
const unification = options.calendarHandler
|
||||
? null
|
||||
: createUnificationHandler({
|
||||
profileName: options.profileName ?? options.profile,
|
||||
getWorld: () => worldRef,
|
||||
loadPendingUniqueAuctions: databaseFlushEnabled
|
||||
? () => loadPendingUnificationAuctionCancellations(options.databaseUrl)
|
||||
: undefined,
|
||||
dispatchUnitedEvents: (context) => monthlyEventHandler.dispatchTarget('united', context),
|
||||
});
|
||||
const nationTurnMonthlyHandler = createNationTurnMonthlyHandler({
|
||||
getWorld: () => worldRef,
|
||||
});
|
||||
|
||||
@@ -118,6 +118,18 @@ export interface PendingUnificationFinalization {
|
||||
year: number;
|
||||
month: number;
|
||||
completedAt: Date;
|
||||
auctionCancellations: PendingUnificationAuctionCancellation[];
|
||||
}
|
||||
|
||||
export interface PendingUnificationAuctionCancellation {
|
||||
auctionId: number;
|
||||
status: 'OPEN' | 'FINALIZING';
|
||||
closeAt: Date;
|
||||
title: string;
|
||||
highestBidId: number | null;
|
||||
bidderGeneralId: number | null;
|
||||
amount: number | null;
|
||||
rankTrackedAmount: number;
|
||||
}
|
||||
|
||||
export interface TurnWorldSnapshot extends Omit<
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import { createGamePostgresConnector, GamePrisma } from '@sammo-ts/infra';
|
||||
|
||||
import type { PendingUnificationAuctionCancellation } from './types.js';
|
||||
|
||||
interface PendingAuctionRow {
|
||||
auctionId: number;
|
||||
status: 'OPEN' | 'FINALIZING';
|
||||
closeAt: Date;
|
||||
detail: unknown;
|
||||
highestBidId: number | null;
|
||||
bidderGeneralId: number | null;
|
||||
amount: number | null;
|
||||
highestBidMeta: unknown;
|
||||
}
|
||||
|
||||
export const loadPendingUnificationAuctionCancellations = async (
|
||||
databaseUrl: string
|
||||
): Promise<PendingUnificationAuctionCancellation[]> => {
|
||||
const connector = createGamePostgresConnector({ url: databaseUrl });
|
||||
await connector.connect();
|
||||
try {
|
||||
const rows = await connector.prisma.$queryRaw<PendingAuctionRow[]>(GamePrisma.sql`
|
||||
SELECT
|
||||
auction.id AS "auctionId",
|
||||
auction.status,
|
||||
auction.close_at AS "closeAt",
|
||||
auction.detail,
|
||||
highest.id AS "highestBidId",
|
||||
highest.general_id AS "bidderGeneralId",
|
||||
highest.amount,
|
||||
highest.meta AS "highestBidMeta"
|
||||
FROM auction
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT bid.id, bid.general_id, bid.amount, bid.meta
|
||||
FROM auction_bid bid
|
||||
WHERE bid.auction_id = auction.id
|
||||
ORDER BY bid.amount DESC, bid.id ASC
|
||||
LIMIT 1
|
||||
) highest ON TRUE
|
||||
WHERE auction.type = 'UNIQUE_ITEM'
|
||||
AND auction.status IN ('OPEN', 'FINALIZING')
|
||||
ORDER BY auction.close_at ASC, auction.id ASC
|
||||
`);
|
||||
return rows.map((row) => {
|
||||
const title = asRecord(row.detail).title;
|
||||
if (typeof title !== 'string' || !title.trim()) {
|
||||
throw new Error(`Unification auction ${row.auctionId} has no title.`);
|
||||
}
|
||||
const hasBid = row.highestBidId !== null;
|
||||
if (hasBid && (row.bidderGeneralId === null || row.amount === null || row.amount <= 0)) {
|
||||
throw new Error(`Unification auction ${row.auctionId} has an invalid highest bid.`);
|
||||
}
|
||||
return {
|
||||
auctionId: row.auctionId,
|
||||
status: row.status,
|
||||
closeAt: new Date(row.closeAt.getTime()),
|
||||
title,
|
||||
highestBidId: row.highestBidId,
|
||||
bidderGeneralId: row.bidderGeneralId,
|
||||
amount: row.amount,
|
||||
rankTrackedAmount: Math.max(0, Number(asRecord(row.highestBidMeta).inheritSpentTrackedAmount) || 0),
|
||||
};
|
||||
});
|
||||
} finally {
|
||||
await connector.disconnect();
|
||||
}
|
||||
};
|
||||
@@ -1,9 +1,12 @@
|
||||
import { asNumber, asRecord, JosaUtil } from '@sammo-ts/common';
|
||||
import { LogCategory, LogFormat, LogScope, type LogEntryDraft } from '@sammo-ts/logic';
|
||||
|
||||
import type { InMemoryTurnWorld, TurnCalendarHandler } from './inMemoryWorld.js';
|
||||
import type { InMemoryTurnWorld, TurnCalendarContext, TurnCalendarHandler } from './inMemoryWorld.js';
|
||||
import type { PendingUnificationAuctionCancellation } from './types.js';
|
||||
import { queueYearbookSnapshot } from './yearbookHandler.js';
|
||||
|
||||
const UNIFIER_POINT = 2000;
|
||||
|
||||
const buildUnificationLog = (nationName: string): LogEntryDraft => ({
|
||||
scope: LogScope.SYSTEM,
|
||||
category: LogCategory.HISTORY,
|
||||
@@ -39,9 +42,11 @@ const resolveServerId = (world: InMemoryTurnWorld, fallback: string): string =>
|
||||
export const createUnificationHandler = (options: {
|
||||
profileName: string;
|
||||
getWorld: () => InMemoryTurnWorld | null;
|
||||
loadPendingUniqueAuctions?: () => Promise<PendingUnificationAuctionCancellation[]>;
|
||||
dispatchUnitedEvents: (context: TurnCalendarContext) => Promise<void>;
|
||||
}): { handler: TurnCalendarHandler } => ({
|
||||
handler: {
|
||||
onMonthChanged: (context) => {
|
||||
onMonthChanged: async (context) => {
|
||||
const world = options.getWorld();
|
||||
if (!world) return;
|
||||
|
||||
@@ -57,12 +62,57 @@ export const createUnificationHandler = (options: {
|
||||
if (cities.length === 0 || cities.some((city) => city.nationId !== winner.id)) return;
|
||||
|
||||
const serverId = resolveServerId(world, options.profileName);
|
||||
world.pushLog(buildNationHistoryLog(winner.id, winner.name));
|
||||
|
||||
const auctionCancellations = (await options.loadPendingUniqueAuctions?.()) ?? [];
|
||||
for (const cancellation of auctionCancellations) {
|
||||
if (cancellation.highestBidId === null) continue;
|
||||
const bidderId = cancellation.bidderGeneralId;
|
||||
const amount = cancellation.amount;
|
||||
if (bidderId === null || amount === null || amount <= 0) {
|
||||
throw new Error(`Unification auction ${cancellation.auctionId} has an invalid refund plan.`);
|
||||
}
|
||||
const bidder = world.getGeneralById(bidderId);
|
||||
if (!bidder?.userId) {
|
||||
throw new Error(`Unification auction ${cancellation.auctionId} bidder is unavailable.`);
|
||||
}
|
||||
const spentDynamic = asNumber(bidder.meta.inherit_spent_dyn, 0);
|
||||
if (cancellation.rankTrackedAmount > spentDynamic) {
|
||||
throw new Error(`Unification auction ${cancellation.auctionId} rank refund exceeds tracked spend.`);
|
||||
}
|
||||
world.updateGeneral(bidder.id, {
|
||||
inheritancePoints: {
|
||||
...bidder.inheritancePoints,
|
||||
previous: asNumber(bidder.inheritancePoints?.previous, 0) + amount,
|
||||
},
|
||||
meta: {
|
||||
...bidder.meta,
|
||||
inherit_spent_dyn: spentDynamic - cancellation.rankTrackedAmount,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
for (const general of world
|
||||
.listGenerals()
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.userId && entry.npcState < 2 && entry.nationId === winner.id && entry.officerLevel > 4
|
||||
)) {
|
||||
world.updateGeneral(general.id, {
|
||||
inheritancePoints: {
|
||||
...general.inheritancePoints,
|
||||
unifier: asNumber(general.inheritancePoints?.unifier, 0) + UNIFIER_POINT,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await options.dispatchUnitedEvents(context);
|
||||
|
||||
world.updateWorldMeta({
|
||||
isUnited: 2,
|
||||
isunited: 2,
|
||||
refreshLimit: asNumber(meta.refreshLimit, 0) * 100,
|
||||
});
|
||||
world.pushLog(buildNationHistoryLog(winner.id, winner.name));
|
||||
for (const general of world.listGenerals().filter((entry) => entry.nationId === winner.id)) {
|
||||
world.pushLog(buildGeneralActionLog(general.id, winner.id, winner.name));
|
||||
}
|
||||
@@ -77,6 +127,7 @@ export const createUnificationHandler = (options: {
|
||||
year: context.currentYear,
|
||||
month: context.currentMonth,
|
||||
completedAt: new Date(state.lastTurnTime.getTime()),
|
||||
auctionCancellations,
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { asRecord, HALL_OF_FAME_TYPES, resolveLegacyTextColor, type HallOfFameType } from '@sammo-ts/common';
|
||||
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
|
||||
import { LogCategory, LogScope } from '@sammo-ts/logic';
|
||||
import { LogCategory, LogScope, sendMessage, type MessageDraft, type MessageRecordDraft } from '@sammo-ts/logic';
|
||||
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
import { ALL_MERGED_INHERITANCE_KEYS, computeActiveInheritancePoint } from './inheritancePointCalculation.js';
|
||||
import type { PendingUnificationAuctionCancellation, TurnGeneral } from './types.js';
|
||||
|
||||
const UNIFIER_POINT = 2000;
|
||||
const asJson = (value: unknown): InputJsonValue => value as InputJsonValue;
|
||||
@@ -15,6 +17,7 @@ export interface UnificationFinalizationInput {
|
||||
readonly year: number;
|
||||
readonly month: number;
|
||||
readonly completedAt: Date;
|
||||
readonly auctionCancellations: readonly PendingUnificationAuctionCancellation[];
|
||||
}
|
||||
|
||||
export interface UnificationFinalizationResult {
|
||||
@@ -41,6 +44,17 @@ const ownerDisplayName = (meta: Record<string, unknown>): string | null => {
|
||||
return null;
|
||||
};
|
||||
|
||||
export const resolveStoredInheritancePoint = (
|
||||
currentPoints: ReadonlyMap<string, number>,
|
||||
general: Pick<TurnGeneral, 'inheritancePoints'>,
|
||||
key: (typeof ALL_MERGED_INHERITANCE_KEYS)[number],
|
||||
unifierAward: number
|
||||
): number =>
|
||||
currentPoints.get(key) ??
|
||||
(key === 'unifier'
|
||||
? Math.max(0, (general.inheritancePoints?.[key] ?? 0) - unifierAward)
|
||||
: (general.inheritancePoints?.[key] ?? 0));
|
||||
|
||||
const formatHistogram = (value: unknown): string =>
|
||||
Object.entries(asRecord(value))
|
||||
.filter((entry): entry is [string, number] => typeof entry[1] === 'number' && Number.isFinite(entry[1]))
|
||||
@@ -88,6 +102,160 @@ const claimGeneration = async (
|
||||
return 'CLAIMED';
|
||||
};
|
||||
|
||||
interface LockedUnificationAuctionRow {
|
||||
auctionId: number;
|
||||
status: 'OPEN' | 'FINALIZING';
|
||||
closeAt: Date;
|
||||
detail: unknown;
|
||||
}
|
||||
|
||||
interface HighestUnificationBidRow {
|
||||
bidId: number;
|
||||
bidderGeneralId: number;
|
||||
amount: number;
|
||||
meta: unknown;
|
||||
}
|
||||
|
||||
const insertMessage = async (transaction: GamePrisma.TransactionClient, draft: MessageRecordDraft): Promise<number> => {
|
||||
const rows = await transaction.$queryRaw<Array<{ id: number }>>`
|
||||
INSERT INTO message (mailbox, type, src, dest, time, valid_until, message)
|
||||
VALUES (
|
||||
${draft.mailbox},
|
||||
${draft.msgType},
|
||||
${draft.srcId},
|
||||
${draft.destId},
|
||||
${draft.time},
|
||||
${draft.validUntil},
|
||||
CAST(${JSON.stringify(draft.payload)} AS jsonb)
|
||||
)
|
||||
RETURNING id
|
||||
`;
|
||||
const id = rows[0]?.id;
|
||||
if (!id) throw new Error('Failed to persist unification auction cancellation message.');
|
||||
return id;
|
||||
};
|
||||
|
||||
const cancelPendingUniqueAuctions = async (
|
||||
transaction: GamePrisma.TransactionClient,
|
||||
input: UnificationFinalizationInput,
|
||||
world: InMemoryTurnWorld
|
||||
): Promise<void> => {
|
||||
const lockedRows = await transaction.$queryRaw<LockedUnificationAuctionRow[]>`
|
||||
SELECT
|
||||
auction.id AS "auctionId",
|
||||
auction.status,
|
||||
auction.close_at AS "closeAt",
|
||||
auction.detail
|
||||
FROM auction
|
||||
WHERE auction.type = 'UNIQUE_ITEM'
|
||||
AND auction.status IN ('OPEN', 'FINALIZING')
|
||||
ORDER BY auction.close_at ASC, auction.id ASC
|
||||
FOR UPDATE OF auction
|
||||
`;
|
||||
if (lockedRows.length !== input.auctionCancellations.length) {
|
||||
throw new Error(
|
||||
`Unification auction set changed: planned=${input.auctionCancellations.length}, actual=${lockedRows.length}.`
|
||||
);
|
||||
}
|
||||
|
||||
for (const [index, row] of lockedRows.entries()) {
|
||||
const planned = input.auctionCancellations[index]!;
|
||||
const title = asRecord(row.detail).title;
|
||||
if (
|
||||
row.auctionId !== planned.auctionId ||
|
||||
row.status !== planned.status ||
|
||||
row.closeAt.getTime() !== planned.closeAt.getTime() ||
|
||||
title !== planned.title
|
||||
) {
|
||||
throw new Error(`Unification auction plan mismatch: ${planned.auctionId}.`);
|
||||
}
|
||||
|
||||
const highestRows = await transaction.$queryRaw<HighestUnificationBidRow[]>`
|
||||
SELECT id AS "bidId", general_id AS "bidderGeneralId", amount, meta
|
||||
FROM auction_bid
|
||||
WHERE auction_id = ${row.auctionId}
|
||||
ORDER BY amount DESC, id ASC
|
||||
LIMIT 1
|
||||
`;
|
||||
const highest = highestRows[0] ?? null;
|
||||
const highestRankTrackedAmount = Math.max(
|
||||
0,
|
||||
readNumber(highest ? asRecord(highest.meta).inheritSpentTrackedAmount : 0)
|
||||
);
|
||||
if (
|
||||
(highest?.bidId ?? null) !== planned.highestBidId ||
|
||||
(highest?.bidderGeneralId ?? null) !== planned.bidderGeneralId ||
|
||||
(highest?.amount ?? null) !== planned.amount ||
|
||||
highestRankTrackedAmount !== planned.rankTrackedAmount
|
||||
) {
|
||||
throw new Error(`Unification auction highest bid changed: ${planned.auctionId}.`);
|
||||
}
|
||||
|
||||
if (highest) {
|
||||
const bidder = world.getGeneralById(highest.bidderGeneralId);
|
||||
const dbBidder = await transaction.general.findUnique({
|
||||
where: { id: highest.bidderGeneralId },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!bidder?.userId || bidder.userId !== dbBidder?.userId) {
|
||||
throw new Error(`Unification auction refund owner is unavailable: ${planned.auctionId}.`);
|
||||
}
|
||||
await transaction.inheritancePoint.upsert({
|
||||
where: { userId_key: { userId: bidder.userId, key: 'previous' } },
|
||||
update: { value: { increment: highest.amount } },
|
||||
create: { userId: bidder.userId, key: 'previous', value: highest.amount },
|
||||
});
|
||||
await transaction.rankData.upsert({
|
||||
where: {
|
||||
generalId_type: { generalId: bidder.id, type: 'inherit_spent_dyn' },
|
||||
},
|
||||
update: {
|
||||
nationId: bidder.nationId,
|
||||
value: readNumber(bidder.meta.inherit_spent_dyn),
|
||||
},
|
||||
create: {
|
||||
generalId: bidder.id,
|
||||
nationId: bidder.nationId,
|
||||
type: 'inherit_spent_dyn',
|
||||
value: readNumber(bidder.meta.inherit_spent_dyn),
|
||||
},
|
||||
});
|
||||
|
||||
const nation = world.getNationById(bidder.nationId);
|
||||
const message: MessageDraft = {
|
||||
msgType: 'private',
|
||||
src: {
|
||||
generalId: 0,
|
||||
generalName: '',
|
||||
nationId: 0,
|
||||
nationName: 'System',
|
||||
color: '#000000',
|
||||
icon: '',
|
||||
},
|
||||
dest: {
|
||||
generalId: bidder.id,
|
||||
generalName: bidder.name,
|
||||
nationId: bidder.nationId,
|
||||
nationName: nation?.name ?? '재야',
|
||||
color: nation?.color ?? '#000000',
|
||||
icon: bidder.picture ?? '',
|
||||
},
|
||||
text: `${planned.auctionId}번 ${planned.title}가 취소되었습니다.`,
|
||||
time: input.completedAt,
|
||||
validUntil: new Date('9999-12-31T00:00:00.000Z'),
|
||||
};
|
||||
await sendMessage({ insertMessage: (draft) => insertMessage(transaction, draft) }, message, {
|
||||
sendDestOnly: true,
|
||||
});
|
||||
}
|
||||
|
||||
await transaction.auction.update({
|
||||
where: { id: row.auctionId },
|
||||
data: { status: 'CANCELED', finishedAt: input.completedAt },
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const persistUnificationFinalization = async (
|
||||
transaction: GamePrisma.TransactionClient,
|
||||
input: UnificationFinalizationInput,
|
||||
@@ -127,6 +295,10 @@ export const persistUnificationFinalization = async (
|
||||
const nations = world.listNations();
|
||||
const eligibleGenerals = generals.filter((general) => general.userId && general.npcState < 2);
|
||||
|
||||
// Ref cancels and refunds every unfinished unique auction before it merges
|
||||
// inheritance. Keep that order inside the generation transaction.
|
||||
await cancelPendingUniqueAuctions(transaction, input, world);
|
||||
|
||||
const pointRows = eligibleGenerals.length
|
||||
? await transaction.inheritancePoint.findMany({
|
||||
where: { userId: { in: eligibleGenerals.map((general) => general.userId!) } },
|
||||
@@ -142,24 +314,18 @@ export const persistUnificationFinalization = async (
|
||||
|
||||
for (const general of eligibleGenerals) {
|
||||
const userId = general.userId!;
|
||||
const generalMeta = asRecord(general.meta);
|
||||
const currentPoints = pointsByUser.get(userId) ?? new Map<string, number>();
|
||||
const previous = currentPoints.get('previous') ?? 0;
|
||||
const livedMonth = readNumber(generalMeta.inherit_lived_month);
|
||||
const maxDomestic = readNumber(generalMeta.max_domestic_critical);
|
||||
const activeAction = readNumber(generalMeta.inherit_active_action);
|
||||
const combat = readNumber(generalMeta.rank_warnum) * 5;
|
||||
const sabotage = readNumber(generalMeta.firenum) * 20;
|
||||
const dex =
|
||||
Object.entries(generalMeta).reduce(
|
||||
(sum, [key, value]) => (key.startsWith('dex') ? sum + readNumber(value) : sum),
|
||||
0
|
||||
) * 0.001;
|
||||
const unifier = currentPoints.get('unifier') ?? 0;
|
||||
const unifierAward = general.nationId === input.winnerNationId && general.officerLevel > 4 ? UNIFIER_POINT : 0;
|
||||
const total = Math.floor(
|
||||
previous + livedMonth + maxDomestic + activeAction * 3 + combat + sabotage + dex + unifier + unifierAward
|
||||
);
|
||||
const mergedPoints = Object.fromEntries(
|
||||
ALL_MERGED_INHERITANCE_KEYS.map((key) => {
|
||||
const stored = resolveStoredInheritancePoint(currentPoints, general, key, unifierAward);
|
||||
const effectiveStored = key === 'unifier' ? stored + unifierAward : stored;
|
||||
return [key, computeActiveInheritancePoint(general, key, effectiveStored)];
|
||||
})
|
||||
) as Record<(typeof ALL_MERGED_INHERITANCE_KEYS)[number], number>;
|
||||
const total = Math.floor(previous + Object.values(mergedPoints).reduce((sum, value) => sum + value, 0));
|
||||
|
||||
await transaction.inheritancePoint.upsert({
|
||||
where: { userId_key: { userId, key: 'previous' } },
|
||||
@@ -176,13 +342,8 @@ export const persistUnificationFinalization = async (
|
||||
month: input.month,
|
||||
value: {
|
||||
previous,
|
||||
lived_month: livedMonth,
|
||||
max_domestic_critical: maxDomestic,
|
||||
active_action: activeAction,
|
||||
combat,
|
||||
sabotage,
|
||||
dex,
|
||||
unifier,
|
||||
...mergedPoints,
|
||||
unifierBeforeAward: unifier,
|
||||
unifierAward,
|
||||
total,
|
||||
generationKey: input.generationKey,
|
||||
|
||||
@@ -1506,6 +1506,10 @@ async function handleAuctionOpen(
|
||||
ctx: CommandHandlerContext,
|
||||
command: Extract<TurnDaemonCommand, { type: 'auctionOpen' }>
|
||||
): Promise<TurnDaemonCommandResult> {
|
||||
const worldMeta = asRecord(ctx.world.getState().meta);
|
||||
if (Number(worldMeta.isUnited ?? 0) !== 0 || Number(worldMeta.isunited ?? 0) !== 0) {
|
||||
return { type: 'auctionOpen', ok: false, reason: '천하통일 후에는 경매를 이용할 수 없습니다.' };
|
||||
}
|
||||
return openAuction(command, ctx.world, ctx.commandDb);
|
||||
}
|
||||
|
||||
@@ -1513,6 +1517,15 @@ async function handleAuctionBid(
|
||||
ctx: CommandHandlerContext,
|
||||
command: Extract<TurnDaemonCommand, { type: 'auctionBid' }>
|
||||
): Promise<TurnDaemonCommandResult> {
|
||||
const worldMeta = asRecord(ctx.world.getState().meta);
|
||||
if (Number(worldMeta.isUnited ?? 0) !== 0 || Number(worldMeta.isunited ?? 0) !== 0) {
|
||||
return {
|
||||
type: 'auctionBid',
|
||||
ok: false,
|
||||
auctionId: command.auctionId,
|
||||
reason: '천하통일 후에는 경매를 이용할 수 없습니다.',
|
||||
};
|
||||
}
|
||||
if (!ctx.auctionBidder) {
|
||||
return {
|
||||
type: 'auctionBid',
|
||||
|
||||
Reference in New Issue
Block a user