From 3e08e9314e242b9217f8d49d4551b3f799c504cd Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:16:42 +0800 Subject: [PATCH] Edit research branches in local saves --- apps/launcher/src/main/ipc/handlers.ts | 5 +- .../src/main/services/saves/manage-saves.ts | 14 ++- .../src/main/workers/save-protocol.ts | 6 +- apps/launcher/src/main/workers/save-worker.ts | 10 +- .../src/renderer/src/i18n/locales/en.json | 32 +++++++ .../src/renderer/src/i18n/locales/zh-CN.json | 32 +++++++ .../renderer/src/pages/saves/SaveResearch.tsx | 91 +++++++++++++++++++ .../renderer/src/pages/saves/SavesPage.tsx | 8 +- .../src/renderer/src/styles/pages.css | 4 + apps/launcher/src/shared/ipc/contract.ts | 10 +- apps/launcher/src/shared/schemas/saves.ts | 13 +++ apps/server/src/index.ts | 1 + apps/server/src/saves/save-editor.ts | 6 +- apps/server/src/saves/save-research.ts | 74 +++++++++++++++ 14 files changed, 291 insertions(+), 15 deletions(-) create mode 100644 apps/launcher/src/renderer/src/pages/saves/SaveResearch.tsx create mode 100644 apps/server/src/saves/save-research.ts diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 5ad403b..68d4328 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -13,7 +13,7 @@ import { createCopyDraft, listCopies, readInstallRecord, renameCopy, setCurrentC import { readInstalledLab } from '../services/launch/lab-handoff.ts'; import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts'; import { resourcePaths } from '../services/resources/resource-paths.ts'; -import { createSave, exportSave, getSaveDetails, getSaveList, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts'; +import { changeSaveResearch, createSave, exportSave, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts'; import { broadcast, handle } from './register.ts'; /** Registers the handler of every contract channel. One line per channel; the work is in services/. */ @@ -124,6 +124,9 @@ export function registerIpcHandlers(): void { handle('saves:importOfficial', ({ copyId, userId, paths, options }) => importSelectedBackups(copyId, userId, paths, options)); + handle('saves:research', ({ copyId, userId, branch }) => getSaveResearch(copyId, userId, branch)); + handle('saves:editResearch', ({ copyId, userId, branch, action }) => changeSaveResearch(copyId, userId, branch, action)); + handle('launch:getState', () => getLaunchState()); handle('launch:getLabInfo', () => readInstalledLab().catch(() => null)); handle('launch:start', () => { diff --git a/apps/launcher/src/main/services/saves/manage-saves.ts b/apps/launcher/src/main/services/saves/manage-saves.ts index 2f90861..6cb5588 100644 --- a/apps/launcher/src/main/services/saves/manage-saves.ts +++ b/apps/launcher/src/main/services/saves/manage-saves.ts @@ -3,7 +3,7 @@ import { app, dialog, utilityProcess, type BrowserWindow } from 'electron'; import { compareVersions, isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { InstallRecord } from '@shared/schemas/install.ts'; -import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer } from '@shared/schemas/saves.ts'; +import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveResearch } from '@shared/schemas/saves.ts'; import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts'; import { maintenanceInProgress } from '../copies/copy-maintenance.ts'; import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts'; @@ -198,6 +198,18 @@ async function verifyBackupLocations(copy: InstallRecord, paths: readonly string })); } +export async function getSaveResearch(copyId: string, userId: string, branch: ResearchBranch | undefined): Promise { + const copy = await requireCopy(copyId); + return await run({ operation: 'readResearch', ...location(copy), userId, ...(branch ? { branch } : {}) }) as SaveResearch; +} + +export async function changeSaveResearch(copyId: string, userId: string, branch: ResearchBranch, action: ResearchOperation): Promise { + return write(async () => { + const copy = await requireCopy(copyId); + return await run({ operation: 'editResearch', ...location(copy), userId, branch, action }) as SaveResearch; + }); +} + async function validateProfile(archive: SaveArchive, copy: InstallRecord): Promise { const profile = archive.files['profile.blk']; if (!profile) return; diff --git a/apps/launcher/src/main/workers/save-protocol.ts b/apps/launcher/src/main/workers/save-protocol.ts index 341bbd2..25b6abb 100644 --- a/apps/launcher/src/main/workers/save-protocol.ts +++ b/apps/launcher/src/main/workers/save-protocol.ts @@ -1,5 +1,5 @@ import type { AppErrorCode } from '@shared/errors.ts'; -import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveDetails, SaveList } from '@shared/schemas/saves.ts'; +import type { CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts'; interface Location { readonly gameFolder: string; @@ -12,9 +12,11 @@ export type SaveTask = Location & ( | { readonly operation: 'edit'; readonly userId: string; readonly values: CurrencyEdits } | { readonly operation: 'previewOfficial'; readonly paths: readonly string[]; readonly includeUsedVehicles: boolean } | { readonly operation: 'importOfficial'; readonly paths: readonly string[]; readonly userId: string; readonly options: OfficialImportOptions } + | { readonly operation: 'readResearch'; readonly userId: string; readonly branch?: ResearchBranch } + | { readonly operation: 'editResearch'; readonly userId: string; readonly branch: ResearchBranch; readonly action: ResearchOperation } | { readonly operation: 'remove'; readonly userId: string } | { readonly operation: 'filter'; readonly profile: Uint8Array; readonly filter: boolean } | { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string } ); -export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | { userId: string } | Uint8Array | null; +export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | null; export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode }; diff --git a/apps/launcher/src/main/workers/save-worker.ts b/apps/launcher/src/main/workers/save-worker.ts index 78f7f35..587b6bf 100644 --- a/apps/launcher/src/main/workers/save-worker.ts +++ b/apps/launcher/src/main/workers/save-worker.ts @@ -1,5 +1,5 @@ import type { MessageEvent } from 'electron'; -import { AccountStore, editSaveCurrencies, importOfficialBackup, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveDetails } from '@wto/server'; +import { AccountStore, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveDetails, readSaveResearch } from '@wto/server'; import type { SaveTask, SaveReply } from './save-protocol.ts'; function execute(task: SaveTask): SaveReply { @@ -17,6 +17,14 @@ function execute(task: SaveTask): SaveReply { return { ok: true, result: previewOfficialBackup(task, task.paths, task.includeUsedVehicles) }; case 'importOfficial': return { ok: true, result: importOfficialBackup(task, task.userId, task.paths, task.options) }; + case 'readResearch': { + const result = readSaveResearch(task, task.userId, task.branch); + return result ? { ok: true, result } : { ok: false, error: 'save_not_found' }; + } + case 'editResearch': { + const result = editSaveResearch(task, task.userId, task.branch, task.action); + return result ? { ok: true, result } : { ok: false, error: 'save_operation_failed' }; + } case 'remove': return new AccountStore(task.dataFolder).remove(task.userId) ? { ok: true, result: null } : { ok: false, error: 'save_not_found' }; diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 7a556b2..46dbb0c 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -261,6 +261,38 @@ "official": "Import official backup", "backup": "Backup and restore" }, + "tree": { + "branch": "Country and vehicle type", + "country": "Country", + "type": "Vehicle type", + "actions": "Bulk actions", + "research": "Research all", + "purchase": "Grant regular vehicles", + "equipment": "Unlock modifications", + "empty": "This copy has no eligible research branches.", + "rank": "Rank {{rank}}", + "owned": "Owned", + "points": "{{earned}} / {{needed}} RP", + "countries": { + "country_usa": "United States", + "country_germany": "Germany", + "country_ussr": "USSR", + "country_britain": "Great Britain", + "country_japan": "Japan", + "country_china": "China", + "country_italy": "Italy", + "country_france": "France", + "country_sweden": "Sweden", + "country_israel": "Israel" + }, + "types": { + "Aircraft": "Aircraft", + "Tank": "Ground vehicles", + "Ship": "Bluewater fleet", + "Boat": "Coastal fleet", + "Helicopter": "Helicopters" + } + }, "official": { "files": "Backup files", "fileHint": "Select copies of global.blk, machine.blk or storage.blk.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index e057880..7a2b5b4 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -261,6 +261,38 @@ "official": "导入正版备份", "backup": "备份与还原" }, + "tree": { + "branch": "国家与兵种", + "country": "国家", + "type": "兵种", + "actions": "批量操作", + "research": "全部研发", + "purchase": "获得常规载具", + "equipment": "解锁改装件", + "empty": "此副本没有可编辑的研发分支。", + "rank": "等级 {{rank}}", + "owned": "已拥有", + "points": "{{earned}} / {{needed}} 研发点", + "countries": { + "country_usa": "美国", + "country_germany": "德国", + "country_ussr": "苏联", + "country_britain": "英国", + "country_japan": "日本", + "country_china": "中国", + "country_italy": "意大利", + "country_france": "法国", + "country_sweden": "瑞典", + "country_israel": "以色列" + }, + "types": { + "Aircraft": "空军", + "Tank": "陆军", + "Ship": "远洋舰队", + "Boat": "近岸舰队", + "Helicopter": "直升机" + } + }, "official": { "files": "备份文件", "fileHint": "请选择复制备份的 global.blk、machine.blk 或 storage.blk。", diff --git a/apps/launcher/src/renderer/src/pages/saves/SaveResearch.tsx b/apps/launcher/src/renderer/src/pages/saves/SaveResearch.tsx new file mode 100644 index 0000000..9a35df6 --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/saves/SaveResearch.tsx @@ -0,0 +1,91 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { ResearchBranch, ResearchOperation, SaveResearch as ResearchData } from '@shared/schemas/saves.ts'; +import { Row } from '../../components/Row.tsx'; +import { ipcInvoke } from '../../ipc.ts'; + +interface Props { + readonly copyId: string; + readonly userId: string; + readonly readOnly: boolean; + readonly onError: (error: unknown) => void; +} + +const ACTIONS = ['research', 'purchase', 'equipment'] as const; + +export function SaveResearch({ copyId, userId, readOnly, onError }: Props) { + const { t, i18n } = useTranslation(); + const [research, setResearch] = useState(null); + const [busy, setBusy] = useState(false); + const [done, setDone] = useState(false); + const keys = { copyId, userId }; + + useEffect(() => { + let mounted = true; + ipcInvoke('saves:research', { copyId, userId }).then((result) => { + if (mounted) setResearch(result); + }).catch(onError); + return () => { mounted = false; }; + }, [copyId, userId, onError]); + + function choose(branch: ResearchBranch | undefined): void { + if (!branch) return; + setBusy(true); + setDone(false); + ipcInvoke('saves:research', { ...keys, branch }).then(setResearch).catch(onError).finally(() => setBusy(false)); + } + + function run(action: ResearchOperation): void { + if (!research?.selected) return; + setBusy(true); + setDone(false); + ipcInvoke('saves:editResearch', { ...keys, branch: research.selected, action }).then((result) => { + setResearch(result); + setDone(true); + }).catch(onError).finally(() => setBusy(false)); + } + + if (!research) return

{t('saves.loading')}

; + const selected = research.selected; + if (!selected) return

{t('saves.tree.empty')}

; + const countries = [...new Set(research.branches.map(({ country }) => country))]; + const types = research.branches.filter(({ country }) => country === selected.country); + const ranks = [...new Set(research.vehicles.map(({ rank }) => rank))]; + const number = new Intl.NumberFormat(i18n.language); + return ( + <> + + + + + + {ACTIONS.map((action) => )} + + {readOnly &&

{t('saves.readOnly')}

} + {done &&

{t('saves.saved')}

} + {ranks.map((rank) => ( +
+

{t('saves.tree.rank', { rank })}

+
+ {research.vehicles.filter((vehicle) => vehicle.rank === rank).map((vehicle) => ( +
+ {vehicle.name} + {vehicle.owned ? t('saves.tree.owned') : t('saves.tree.points', { earned: number.format(vehicle.points), needed: number.format(vehicle.needed) })} +
+ ))} +
+
+ ))} + + ); +} diff --git a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx index 79a821a..94f3ac0 100644 --- a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx +++ b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx @@ -7,6 +7,7 @@ import { Sheet } from '../../components/Sheet.tsx'; import { ipcInvoke } from '../../ipc.ts'; import type { SaveSection } from '../../shell/navigation.ts'; import { OfficialSaveImport } from './OfficialSaveImport.tsx'; +import { SaveResearch } from './SaveResearch.tsx'; import { SaveBackups } from './SaveBackups.tsx'; interface SavesPageProps { @@ -239,12 +240,7 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag )} {section === 'official' && } {section === 'backup' && } - {section === 'vehicles' && ( - <> - {details.owned.length ? details.owned.join(', ') : '—'} - {details.research.length ? details.research.map(({ name, points }) => `${name} · ${format.format(points)}`).join(', ') : '—'} - - )} + {section === 'vehicles' && } ); } diff --git a/apps/launcher/src/renderer/src/styles/pages.css b/apps/launcher/src/renderer/src/styles/pages.css index 3ebad07..aee21b1 100644 --- a/apps/launcher/src/renderer/src/styles/pages.css +++ b/apps/launcher/src/renderer/src/styles/pages.css @@ -307,6 +307,10 @@ margin-top: 12px; } +.save-research-group { + margin-top: 16px; +} + /* ===== About ===== */ .about-head { display: flex; diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index c2596d6..e720748 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -15,7 +15,7 @@ import { } from '../schemas/install.ts'; import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts'; import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts'; -import { OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts'; +import { ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts'; import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts'; /** @@ -188,6 +188,14 @@ export const ipcContract = { input: SaveOfficialRequestSchema.extend({ options: OfficialImportOptionsSchema }), output: OfficialPreviewSchema, }, + 'saves:research': { + input: SaveKeysSchema.extend({ branch: ResearchBranchSchema.optional() }), + output: SaveResearchSchema, + }, + 'saves:editResearch': { + input: SaveKeysSchema.extend({ branch: ResearchBranchSchema, action: ResearchOperationSchema }), + output: SaveResearchSchema, + }, 'launch:getState': { input: z.void(), output: LaunchStateSchema, diff --git a/apps/launcher/src/shared/schemas/saves.ts b/apps/launcher/src/shared/schemas/saves.ts index c778de8..b77686c 100644 --- a/apps/launcher/src/shared/schemas/saves.ts +++ b/apps/launcher/src/shared/schemas/saves.ts @@ -64,6 +64,19 @@ export const OfficialPreviewSchema = z.object({ vehicles: z.array(z.string()), omitted: z.array(z.string()), }); +export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) }); +export const ResearchOperationSchema = z.enum(['research', 'purchase', 'equipment']); +export const SaveResearchSchema = z.object({ + branches: z.array(ResearchBranchSchema), + selected: ResearchBranchSchema.nullable(), + vehicles: z.array(z.object({ + name: z.string(), rank: z.number(), owned: z.boolean(), points: z.number(), needed: z.number(), + })), +}); +export type ResearchBranch = z.output; +export type ResearchOperation = z.output; +export type SaveResearch = z.output; + export type OfficialPreview = z.output; export type OfficialImportOptions = z.output; diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index 56fff21..31211e0 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -6,6 +6,7 @@ export { LOOPBACK, startServer, type ServerOptions, type RunningServer } from '. export { AccountStore, type RegistrationResult } from './accounts/account-store.ts'; export { REGISTRATION_PATH } from './accounts/registration-service.ts'; export { HEALTH_PATH } from './transport/http-listener.ts'; +export { editSaveResearch, readSaveResearch } from './saves/save-research.ts'; export { editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.ts'; export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts'; export { prepareTransferredProfile } from './saves/transferred-profile.ts'; diff --git a/apps/server/src/saves/save-editor.ts b/apps/server/src/saves/save-editor.ts index 0ab26c7..f0501bd 100644 --- a/apps/server/src/saves/save-editor.ts +++ b/apps/server/src/saves/save-editor.ts @@ -41,7 +41,7 @@ function summary(account: Account, profile: BlkBlock | undefined) { }; } -function snapshot(dataFolder: string, userId: string): BlkBlock | undefined { +export function readSaveSnapshot(dataFolder: string, userId: string): BlkBlock | undefined { if (!/^\d+$/.test(userId)) throw new Error('Invalid local account id.'); try { return decodeBlk(readFileSync(join(dataFolder, 'saves', userId, 'profile.blk'))); @@ -72,13 +72,13 @@ function battleEntries(profile: BlkBlock) { } export function listSaveSummaries(dataFolder: string) { - return new AccountStore(dataFolder).all().map((account) => summary(account, snapshot(dataFolder, account.userId))); + return new AccountStore(dataFolder).all().map((account) => summary(account, readSaveSnapshot(dataFolder, account.userId))); } export function readSaveDetails(dataFolder: string, userId: string) { const account = new AccountStore(dataFolder).byUserId(userId); if (!account) return null; - const profile = snapshot(dataFolder, userId); + const profile = readSaveSnapshot(dataFolder, userId); const owned = profile ? [...ownedVehicles(profile)].sort() : []; const research = profile ? (findBlock(profile, 'unitResearch')?.blocks ?? []).map(({ name }) => ({ name, points: researchPointsOf(profile, name) })) diff --git a/apps/server/src/saves/save-research.ts b/apps/server/src/saves/save-research.ts new file mode 100644 index 0000000..e248003 --- /dev/null +++ b/apps/server/src/saves/save-research.ts @@ -0,0 +1,74 @@ +import { AccountStore } from '../accounts/account-store.ts'; +import { ClanStore } from '../clans/clan-store.ts'; +import { DatasetCache } from '../game-data/datasets/dataset-cache.ts'; +import { vehicleCatalogue } from '../game-data/datasets/vehicle-catalogue.ts'; +import { GameFiles } from '../game-data/game-files.ts'; +import { addOwnedVehicle, ownedVehicles } from '../profile/profile-hangar.ts'; +import { ownsModification, writeModificationRecord } from '../profile/profile-modifications.ts'; +import { researchPointsOf, setResearchPoints } from '../profile/profile-vehicle-research.ts'; +import { setUpProfiles } from '../profiles-setup.ts'; +import { TechTree } from '../research/tech-tree.ts'; +import { loadTuning } from '../tuning/tuning.ts'; +import { readSaveSnapshot, type SaveLocation } from './save-editor.ts'; + +export interface ResearchBranch { + readonly country: string; + readonly type: string; +} +export type ResearchOperation = 'research' | 'purchase' | 'equipment'; + +function tree(location: SaveLocation) { + const gameFiles = new GameFiles(location.gameFolder); + const datasets = new DatasetCache(location.dataFolder, gameFiles, () => {}); + const vehicles = datasets.load(vehicleCatalogue); + return { gameFiles, datasets, vehicles, catalogue: new TechTree(vehicles) }; +} + +export function readSaveResearch(location: SaveLocation, userId: string, selection?: ResearchBranch) { + if (!new AccountStore(location.dataFolder).byUserId(userId)) return null; + const { catalogue } = tree(location); + const branches = catalogue.branches().map(({ country, type }) => ({ country, type })); + const selected = branches.find((branch) => branch.country === selection?.country && branch.type === selection?.type) ?? branches[0] ?? null; + const save = readSaveSnapshot(location.dataFolder, userId); + const owned = save ? ownedVehicles(save) : new Set(); + const vehicles = [...catalogue.all()] + .filter((unit) => unit.inTechTree && unit.country === selected?.country && unit.type === selected?.type) + .sort((a, b) => a.rank - b.rank || a.treeOrder - b.treeOrder || a.name.localeCompare(b.name)) + .map((unit) => ({ + name: unit.name, rank: unit.rank, owned: owned.has(unit.name), + points: save ? researchPointsOf(save, unit.name) : 0, needed: unit.researchPoints, + })); + return { branches, selected, vehicles }; +} + +export function editSaveResearch(location: SaveLocation, userId: string, branch: ResearchBranch, operation: ResearchOperation) { + const accounts = new AccountStore(location.dataFolder); + if (!accounts.byUserId(userId)) return null; + const { gameFiles, datasets, vehicles, catalogue } = tree(location); + const units = [...catalogue.all()].filter((unit) => unit.inTechTree && unit.country === branch.country && unit.type === branch.type); + if (!units.length) return null; + const tuning = loadTuning(location.dataFolder, () => {}); + const clans = new ClanStore(location.dataFolder, tuning.clans); + const { profiles, equipment } = setUpProfiles(location.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles); + profiles.update(userId, (profile) => { + const owned = ownedVehicles(profile); + for (const unit of units) { + if (operation === 'research' && unit.kind === 'research' && !owned.has(unit.name)) { + setResearchPoints(profile, unit.name, Math.max(researchPointsOf(profile, unit.name), unit.researchPoints)); + } + if (operation === 'purchase' && (unit.kind === 'research' || unit.kind === 'purchase')) { + addOwnedVehicle(profile, unit.name); + for (const part of unit.parts) addOwnedVehicle(profile, part); + } + if (operation === 'equipment' && owned.has(unit.name)) { + for (const mod of equipment.vehicle(unit.name)?.modifications ?? []) { + if (ownsModification(profile, unit.name, mod.name)) continue; + writeModificationRecord(profile, unit.name, mod.name, { + silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: true, count: Math.max(1, mod.maxCount), + }); + } + } + } + }); + return readSaveResearch(location, userId, branch); +}