287 lines
12 KiB
TypeScript
287 lines
12 KiB
TypeScript
/**
|
|
* Pure domain rules for external inventory coupon consumption, item recycling, generator
|
|
* exchanges (chest opening and workshop/recycle crafting), and GJN marketplace coupon purchases. Wire JSON formatting lives in `inventory-wire.ts`.
|
|
*/
|
|
import type { BlkBlock, BlkParam } from '@wto/blk';
|
|
import type { ItemCatalogue } from '../items/item-catalogue.ts';
|
|
import { grantItem } from '../items/item-grants.ts';
|
|
import { balanceOf, canAfford, pay, payGjnCents } from '../profile/profile-currency.ts';
|
|
import {
|
|
consumeExternalItem,
|
|
externalItemByUid,
|
|
grantExternalItem,
|
|
type StoredExternalItem,
|
|
} from '../profile/profile-external-inventory.ts';
|
|
import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts';
|
|
import { ownedItem, removeItem, setItemCount } from '../profile/profile-items.ts';
|
|
import { addResource, ownsResource } from '../profile/profile-resources.ts';
|
|
import { appendUserLog, EULT_OPEN_TROPHY, incrementTrophyOpenCount } from '../profile/profile-trophies-log.ts';
|
|
import { addUnlock, earnedUnlocks } from '../profile/profile-unlocks.ts';
|
|
import type { ServerTime } from '../profile/server-time.ts';
|
|
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
|
|
import type { ExchangeMaterialInput } from './inventory-wire.ts';
|
|
import type { InventoryCatalogue } from './itemdef-catalogue.ts';
|
|
import type { GeneratorDefinition, GeneratorDrop } from './itemdef-types.ts';
|
|
|
|
export function pickWeighted<T extends { readonly weight: number }>(entries: readonly T[]): T {
|
|
const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
|
|
let roll = Math.random() * total;
|
|
for (const entry of entries) {
|
|
roll -= entry.weight;
|
|
if (roll <= 0) return entry;
|
|
}
|
|
return entries[entries.length - 1]!;
|
|
}
|
|
|
|
/** `cln_consume_inventory_item` (char_send_blk): consume coupon(s) into vehicles, decor, unlocks or items. */
|
|
export function consumeInventoryCoupon(
|
|
profile: BlkBlock,
|
|
catalogue: InventoryCatalogue,
|
|
classicItems: ItemCatalogue,
|
|
itemUid: string,
|
|
quantity: number,
|
|
now: ServerTime,
|
|
): RuleOutcome {
|
|
if (!Number.isSafeInteger(quantity) || quantity < 1) return refused('BAD_PARAMS');
|
|
const held = externalItemByUid(profile, itemUid);
|
|
if (!held || held.quantity < quantity) return refused('NOT_AVAILABLE');
|
|
|
|
const action = catalogue.couponAction(held.itemDefId);
|
|
if (!action) return refused('NOT_AVAILABLE');
|
|
|
|
switch (action.kind) {
|
|
case 'vehicle': {
|
|
if (ownsVehicle(profile, action.unitName) || !consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
|
|
addOwnedVehicle(profile, action.unitName);
|
|
for (const part of action.parts) addOwnedVehicle(profile, part);
|
|
return ACCEPTED;
|
|
}
|
|
case 'decor': {
|
|
if (ownsResource(profile, action.resourceKey) || !consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
|
|
addResource(profile, action.resourceKey, { silverLions: 0, goldenEagles: 0 });
|
|
return ACCEPTED;
|
|
}
|
|
case 'unlock': {
|
|
if (earnedUnlocks(profile).has(action.unlockId) || !consumeExternalItem(profile, itemUid, 1)) return refused('NOT_AVAILABLE');
|
|
addUnlock(profile, action.unlockId);
|
|
return ACCEPTED;
|
|
}
|
|
case 'classic-item': {
|
|
const def = classicItems.item(action.itemName);
|
|
if (!def) return refused('BAD_PARAMS');
|
|
if (!consumeExternalItem(profile, itemUid, quantity)) return refused('NOT_AVAILABLE');
|
|
grantItem(profile, def, action.count * quantity, now);
|
|
return ACCEPTED;
|
|
}
|
|
}
|
|
}
|
|
|
|
/** `cln_multi_consume_inventory_item_json`: batch auto-consume of external items. */
|
|
export function multiConsumeInventoryItems(
|
|
profile: BlkBlock,
|
|
catalogue: InventoryCatalogue,
|
|
classicItems: ItemCatalogue,
|
|
requests: ReadonlyArray<{ readonly itemId: number; readonly quantity: number }>,
|
|
now: ServerTime,
|
|
): { readonly revertedItems: number[] } {
|
|
const revertedItems: number[] = [];
|
|
for (const req of requests) {
|
|
const outcome = consumeInventoryCoupon(profile, catalogue, classicItems, String(req.itemId), req.quantity, now);
|
|
if (!outcome.ok) revertedItems.push(req.itemId);
|
|
}
|
|
return { revertedItems };
|
|
}
|
|
|
|
/** `cln_inventory_purchase_item`: buy external inventory chests/items priced in GetItemPrices. */
|
|
export function purchaseExternalInventoryItem(
|
|
profile: BlkBlock,
|
|
catalogue: InventoryCatalogue,
|
|
itemDefId: number,
|
|
amount: number,
|
|
offeredWp: number,
|
|
offeredGold: number,
|
|
): RuleOutcome {
|
|
if (!Number.isSafeInteger(amount) || amount < 1 || amount > 100) return refused('BAD_PARAMS');
|
|
const unitPrice = catalogue.priceOf(itemDefId);
|
|
if (!unitPrice) return refused('NOT_AVAILABLE');
|
|
if (offeredWp !== unitPrice.silverLions || offeredGold !== unitPrice.goldenEagles) return refused('PRICE_CHANGED');
|
|
|
|
const totalPrice = { silverLions: unitPrice.silverLions * amount, goldenEagles: unitPrice.goldenEagles * amount };
|
|
if (!canAfford(profile, totalPrice)) return refused('NOT_ENOUGH_MONEY');
|
|
|
|
pay(profile, totalPrice);
|
|
grantExternalItem(profile, itemDefId, amount);
|
|
return ACCEPTED;
|
|
}
|
|
|
|
/** `cln_recycle_items`: convert classic profile items into external craft_part items (299000..299004). */
|
|
export function recycleClassicItems(
|
|
profile: BlkBlock,
|
|
classicItems: ItemCatalogue,
|
|
requests: ReadonlyArray<{ readonly uid: string; readonly count: number }>,
|
|
): RuleOutcome {
|
|
if (requests.length === 0) return refused('BAD_PARAMS');
|
|
const countsByUid = new Map<string, number>();
|
|
for (const entry of requests) {
|
|
if (!entry.uid || !Number.isSafeInteger(entry.count) || entry.count < 1) return refused('BAD_PARAMS');
|
|
countsByUid.set(entry.uid, (countsByUid.get(entry.uid) ?? 0) + entry.count);
|
|
}
|
|
|
|
const validated: Array<{ readonly uid: string; readonly count: number; readonly remaining: number; readonly partId: number }> = [];
|
|
for (const [uid, count] of countsByUid) {
|
|
const owned = ownedItem(profile, uid);
|
|
if (!owned || owned.count < count) return refused('NOT_AVAILABLE');
|
|
const partId = classicItems.item(owned.id)?.recycleItemResult;
|
|
if (!partId) return refused('NOT_AVAILABLE');
|
|
validated.push({ uid, count, remaining: owned.count - count, partId });
|
|
}
|
|
|
|
const nowIso = new Date().toISOString();
|
|
for (const item of validated) {
|
|
if (item.remaining <= 0) removeItem(profile, item.uid);
|
|
else setItemCount(profile, item.uid, item.remaining);
|
|
grantExternalItem(profile, item.partId, item.count, nowIso);
|
|
}
|
|
return ACCEPTED;
|
|
}
|
|
|
|
export interface ExchangeItemDelta {
|
|
readonly itemId: string;
|
|
readonly itemDefId: number;
|
|
readonly quantity: number;
|
|
readonly timestamp: string;
|
|
}
|
|
|
|
export type ExchangeOutcome =
|
|
| { readonly ok: true; readonly delta: ExchangeItemDelta[] }
|
|
| { readonly ok: false; readonly code: string };
|
|
|
|
/** `ExchangeItems` / `cln_inventory_exchange_items`: execute a generator recipe and roll drops. */
|
|
export function exchangeInventoryItems(
|
|
profile: BlkBlock,
|
|
catalogue: InventoryCatalogue,
|
|
outputItemDefId: number,
|
|
quantity: number,
|
|
materials: readonly ExchangeMaterialInput[],
|
|
nowSec = Math.floor(Date.now() / 1000),
|
|
): ExchangeOutcome {
|
|
if (!Number.isSafeInteger(quantity) || quantity < 1 || quantity > 100 || materials.length === 0) {
|
|
return { ok: false, code: 'BAD_PARAMS' };
|
|
}
|
|
const gen = catalogue.generator(outputItemDefId);
|
|
if (!gen || gen.drops.length === 0) return { ok: false, code: 'UNKNOWN_GENERATOR' };
|
|
|
|
const validationError = validateRecipeMaterials(profile, gen, quantity, materials);
|
|
if (validationError) return { ok: false, code: validationError };
|
|
|
|
const nowIso = new Date(nowSec * 1000).toISOString();
|
|
const deltaByUid = new Map<string, ExchangeItemDelta>();
|
|
|
|
for (const mat of materials) {
|
|
const uid = String(mat.itemid);
|
|
const consumed = consumeExternalItem(profile, uid, mat.quantity, nowIso);
|
|
if (!consumed) return { ok: false, code: 'NOT_ENOUGH_ITEMS' };
|
|
deltaByUid.set(uid, { itemId: uid, itemDefId: consumed.itemDefId, quantity: consumed.remaining, timestamp: nowIso });
|
|
}
|
|
|
|
rollGeneratorOutputs(profile, gen, quantity, nowSec, nowIso, deltaByUid);
|
|
return { ok: true, delta: [...deltaByUid.values()] };
|
|
}
|
|
|
|
function validateRecipeMaterials(
|
|
profile: BlkBlock,
|
|
gen: GeneratorDefinition,
|
|
quantity: number,
|
|
materials: readonly ExchangeMaterialInput[],
|
|
): string | undefined {
|
|
const providedByDef = new Map<number, number>();
|
|
const providedByStack = new Map<string, number>();
|
|
for (const mat of materials) {
|
|
if (!mat.itemid || !Number.isSafeInteger(mat.quantity) || mat.quantity < 1) return 'BAD_MATERIALS';
|
|
const held = externalItemByUid(profile, mat.itemid);
|
|
const stackQuantity = (providedByStack.get(mat.itemid) ?? 0) + mat.quantity;
|
|
if (!held || (mat.itemdefid !== undefined && held.itemDefId !== mat.itemdefid) || held.quantity < stackQuantity) {
|
|
return 'NOT_ENOUGH_ITEMS';
|
|
}
|
|
providedByStack.set(mat.itemid, stackQuantity);
|
|
providedByDef.set(held.itemDefId, (providedByDef.get(held.itemDefId) ?? 0) + mat.quantity);
|
|
}
|
|
const matches = gen.recipes.some((recipe) =>
|
|
recipe.components.length === providedByDef.size
|
|
&& recipe.components.every((comp) => providedByDef.get(comp.itemdefId) === comp.quantity * quantity));
|
|
return matches ? undefined : 'RECIPE_MISMATCH';
|
|
}
|
|
|
|
function rollGeneratorOutputs(
|
|
profile: BlkBlock,
|
|
gen: GeneratorDefinition,
|
|
quantity: number,
|
|
nowSec: number,
|
|
nowIso: string,
|
|
deltaByUid: Map<string, ExchangeItemDelta>,
|
|
): void {
|
|
for (let i = 0; i < quantity; i += 1) {
|
|
const dropDefId = pickWeighted<GeneratorDrop>(gen.drops).itemdefId;
|
|
const granted = grantExternalItem(profile, dropDefId, 1, nowIso);
|
|
deltaByUid.set(granted.itemId, granted);
|
|
|
|
if (gen.isChestGenerator && gen.chestItemdefId !== undefined) {
|
|
// Allocate a unique monotonically increasing open sequence ID so opening multiple chests
|
|
// in one batch never overwrites same-itemDefId entries in buyAndOpenChestWnd.nut.
|
|
const uniqueOpenId = incrementTrophyOpenCount(profile, 'trophyFromInventory', 1);
|
|
const logParams: BlkParam[] = [
|
|
{ name: 'id', value: { type: 'string', value: 'trophyFromInventory' } },
|
|
{ name: 'fromInventory', value: { type: 'bool', value: true } },
|
|
{ name: 'itemDefId', value: { type: 'int', value: gen.chestItemdefId } },
|
|
{ name: 'itemId', value: { type: 'int', value: uniqueOpenId } },
|
|
{ name: 'item', value: { type: 'int', value: dropDefId } },
|
|
{ name: 'count', value: { type: 'int', value: 1 } },
|
|
];
|
|
appendUserLog(profile, { type: EULT_OPEN_TROPHY, timeSec: nowSec, bodyParams: logParams });
|
|
}
|
|
}
|
|
}
|
|
|
|
export type MarketBuyOutcome =
|
|
| { readonly ok: true; readonly item: StoredExternalItem }
|
|
| { readonly ok: false; readonly reason: 'NOT_FOUND' | 'NOT_ENOUGH_GJN' };
|
|
|
|
export function buyMarketplaceCoupon(
|
|
profile: BlkBlock,
|
|
catalogue: InventoryCatalogue,
|
|
itemdefId: number,
|
|
quantity: number,
|
|
maxPerPurchase: number,
|
|
): MarketBuyOutcome {
|
|
const listing = validCouponPurchase(catalogue, itemdefId, quantity, maxPerPurchase);
|
|
if (!listing) return { ok: false, reason: 'NOT_FOUND' };
|
|
const totalCost = listing.gjnCostCents * quantity;
|
|
if (balanceOf(profile).gjnCents < totalCost) return { ok: false, reason: 'NOT_ENOUGH_GJN' };
|
|
|
|
payGjnCents(profile, totalCost);
|
|
return { ok: true, item: grantExternalItem(profile, itemdefId, quantity) };
|
|
}
|
|
|
|
/** Claim a marketplace coupon with the free offline payment method. */
|
|
export function buyFreeMarketplaceCoupon(
|
|
profile: BlkBlock,
|
|
catalogue: InventoryCatalogue,
|
|
itemdefId: number,
|
|
quantity: number,
|
|
maxPerPurchase: number,
|
|
): MarketBuyOutcome {
|
|
const listing = validCouponPurchase(catalogue, itemdefId, quantity, maxPerPurchase);
|
|
if (!listing) return { ok: false, reason: 'NOT_FOUND' };
|
|
return { ok: true, item: grantExternalItem(profile, itemdefId, quantity) };
|
|
}
|
|
|
|
function validCouponPurchase(
|
|
catalogue: InventoryCatalogue,
|
|
itemdefId: number,
|
|
quantity: number,
|
|
maxPerPurchase: number,
|
|
) {
|
|
if (!Number.isSafeInteger(quantity) || quantity < 1 || quantity > maxPerPurchase) return undefined;
|
|
return catalogue.marketplaceListing(itemdefId);
|
|
}
|