diff --git a/app/src-tauri/src/commands/world.rs b/app/src-tauri/src/commands/world.rs index f5d820b..4a9c46a 100644 --- a/app/src-tauri/src/commands/world.rs +++ b/app/src-tauri/src/commands/world.rs @@ -3,8 +3,8 @@ use std::sync::atomic::Ordering; use chrono::{DateTime, Utc}; use serde::Serialize; use wf_core::{ - ARBITRATION_FORECAST_TRUSTED, ArbitrationSchedule, CircuitRotation, Core, ItemTable, - WorldOfferOwnership, WorldRewardAlert, + ARBITRATION_FORECAST_TRUSTED, ArbitrationSchedule, BountyAlertOptions, CircuitRotation, Core, + ItemTable, WorldBountyBoard, WorldOfferOwnership, WorldRewardAlert, }; use wf_data::store_item_to_type; use wf_worldstate::{ @@ -32,6 +32,7 @@ pub struct WorldStateView { pub prime_resurgence: Option, pub nightwave: Option, pub world_reward_alerts: Vec, + pub bounty_boards: Vec, pub daily_reset: ResetWindow, pub weekly_reset: ResetWindow, pub fetched_at: Option>, @@ -308,6 +309,7 @@ impl WorldStateView { prime_resurgence: None, nightwave: None, world_reward_alerts: Vec::new(), + bounty_boards: Vec::new(), daily_reset: daily_reset_window(now), weekly_reset: weekly_reset_window(now), fetched_at, @@ -332,6 +334,7 @@ impl WorldStateView { core.catalog().nightwave_act_text(challenge) }), world_reward_alerts: core.world_reward_alerts(now), + bounty_boards: core.bounty_boards(now), daily_reset: daily_reset_window(now), weekly_reset: weekly_reset_window(now), fetched_at, @@ -354,6 +357,12 @@ pub async fn invasion_weapon_parts(state: Shared<'_>) -> CommandResult) -> CommandResult { + let state = ready(&state).await?; + Ok(lock(&state.core).bounty_alert_options()) +} + #[tauri::command] pub async fn arbitrations(state: Shared<'_>) -> CommandResult { let state = ready(&state).await?; diff --git a/app/src-tauri/src/envelope.rs b/app/src-tauri/src/envelope.rs index 07b2b70..f3e9e03 100644 --- a/app/src-tauri/src/envelope.rs +++ b/app/src-tauri/src/envelope.rs @@ -37,6 +37,7 @@ fn kind(event: &CoreEvent) -> &'static str { CoreEvent::NewConversation { .. } => "new-conversation", CoreEvent::FissureAlert { .. } => "fissure-alert", CoreEvent::WorldRewardAlert { .. } => "world-reward-alert", + CoreEvent::WorldBountyAlert { .. } => "world-bounty-alert", CoreEvent::ArbitrationAlert { .. } => "arbitration-alert", CoreEvent::ArbitrationRunUpdated { .. } => "arbitration-run-updated", CoreEvent::ArbitrationRunRecorded { .. } => "arbitration-run-recorded", diff --git a/app/src-tauri/src/event_feed.rs b/app/src-tauri/src/event_feed.rs index 1d75d1b..31e9e9d 100644 --- a/app/src-tauri/src/event_feed.rs +++ b/app/src-tauri/src/event_feed.rs @@ -20,7 +20,7 @@ use tracing::{debug, info, warn}; use wf_core::{ ArbitrationAlert, ArbitrationRun, CoreEvent, FissureInfo, InventorySummary, ResetChecklistGroup, ResetChecklistProgress, ResetChecklistRow, ResetChecklistRowId, - RewardScreen, Trade, WorldRewardAlert, + RewardScreen, Trade, WorldBountyAlert, WorldRewardAlert, }; use crate::runtime::{AppEvent, MarketAutoClose, update_status}; @@ -120,6 +120,9 @@ pub enum FeedEvent { WorldRewardAlert { reward: WorldRewardAlert, }, + WorldBountyAlert { + alert: WorldBountyAlert, + }, ArbitrationAlert { alert: ArbitrationAlert, }, @@ -185,6 +188,9 @@ impl FeedEvent { CoreEvent::WorldRewardAlert { reward } => Some(Self::WorldRewardAlert { reward: reward.clone(), }), + CoreEvent::WorldBountyAlert { alert } => Some(Self::WorldBountyAlert { + alert: alert.clone(), + }), CoreEvent::ArbitrationAlert { alert } => Some(Self::ArbitrationAlert { alert: alert.clone(), }), diff --git a/app/src-tauri/src/lib.rs b/app/src-tauri/src/lib.rs index 00609b2..1e70108 100644 --- a/app/src-tauri/src/lib.rs +++ b/app/src-tauri/src/lib.rs @@ -181,6 +181,7 @@ fn commands() -> impl Fn(tauri::ipc::Invoke) -> bool { commands::market::market_set_auctions_visibility, commands::world::worldstate, commands::world::invasion_weapon_parts, + commands::world::bounty_alert_options, commands::world::arbitrations, commands::arbitrations::arbitration_runs, commands::arbitrations::arbitration_live_run, diff --git a/app/src-tauri/src/notice.rs b/app/src-tauri/src/notice.rs index 601e97f..d308c3d 100644 --- a/app/src-tauri/src/notice.rs +++ b/app/src-tauri/src/notice.rs @@ -2,8 +2,8 @@ use std::fmt::Write as _; use serde::Serialize; use wf_core::{ - ArbitrationAlert, ArbitrationRun, CoreEvent, FissureInfo, InventorySummary, WorldRewardAlert, - counted, thousands, + ArbitrationAlert, ArbitrationRun, CoreEvent, FissureInfo, InventorySummary, WorldBountyAlert, + WorldRewardAlert, counted, thousands, }; use wf_worldstate::{EARTH_AND_CETUS, WorldRewardSource}; @@ -40,6 +40,7 @@ impl Notice { CoreEvent::NewConversation { player, .. } => Some(Self::conversation(player)), CoreEvent::FissureAlert { fissure } => Some(Self::fissure(fissure)), CoreEvent::WorldRewardAlert { reward } => Some(Self::reward(reward)), + CoreEvent::WorldBountyAlert { alert } => Some(Self::bounty(alert)), CoreEvent::ArbitrationAlert { alert } => Some(Self::arbitration(alert)), CoreEvent::ArbitrationRunRecorded { run } => Some(Self::arbitration_run(run)), CoreEvent::TimerAlert { @@ -138,6 +139,29 @@ impl Notice { } } + pub fn bounty(alert: &WorldBountyAlert) -> Self { + let (title, listed) = match alert.bounties.as_slice() { + [bounty] => (format!("{} bounty: {bounty}", alert.syndicate), None), + bounties => ( + format!("{} {} bounties", bounties.len(), alert.syndicate), + Some(bounties.join(", ")), + ), + }; + let rewards = (!alert.rewards.is_empty()).then(|| alert.rewards.join(", ")); + let left = format!("{} left", countdown(alert.remaining_secs)); + Self { + title, + body: listed + .into_iter() + .chain(rewards) + .chain([left]) + .collect::>() + .join(". "), + tone: Tone::Warning, + in_game: Some(InGameToast::Bounty), + } + } + pub fn arbitration(alert: &ArbitrationAlert) -> Self { let node = &alert.slot.node; let mission = node.mission_type.unwrap_or("Unknown mission"); @@ -388,6 +412,30 @@ mod tests { assert_eq!(countdown(2 * 86_400 + 5 * 3600), "2d 5h"); } + #[test] + fn bounty_notice() { + let alert = |bounties: &[&str], rewards: &[&str]| WorldBountyAlert { + syndicate: String::from("Ostrons"), + bounties: bounties.iter().map(|&name| name.to_owned()).collect(), + rewards: rewards.iter().map(|&name| name.to_owned()).collect(), + expiry: DateTime::from_timestamp(9000, 0).unwrap(), + remaining_secs: 8940, + }; + let one = Notice::bounty(&alert(&["Spy Catcher (40-60)"], &["2 x Cetus Wisp"])); + let two = Notice::bounty(&alert( + &["Spy Catcher (40-60)", "Cull The Enemy (5-15)"], + &[], + )); + + assert_eq!(one.title, "Ostrons bounty: Spy Catcher (40-60)"); + assert_eq!(one.body, "2 x Cetus Wisp. 2h 29m left"); + assert_eq!(two.title, "2 Ostrons bounties"); + assert_eq!( + two.body, + "Spy Catcher (40-60), Cull The Enemy (5-15). 2h 29m left" + ); + } + #[test] fn reward_notice() { let invasion = WorldRewardAlert { diff --git a/app/src-tauri/src/runtime/mod.rs b/app/src-tauri/src/runtime/mod.rs index 64c19bb..bbee888 100644 --- a/app/src-tauri/src/runtime/mod.rs +++ b/app/src-tauri/src/runtime/mod.rs @@ -7,7 +7,7 @@ use tauri_plugin_clipboard_manager::ClipboardExt; #[cfg(not(target_os = "linux"))] use tauri_plugin_notification::NotificationExt; use tracing::{debug, error, info, warn}; -use wf_core::{ArbitrationAlert, CoreEvent}; +use wf_core::{ArbitrationAlert, CoreEvent, Trade}; use crate::envelope::CoreEventEnvelope; use crate::event_feed::{self, EventFeed}; @@ -171,22 +171,7 @@ async fn deliver(app: &AppHandle, state: &Arc, event: & } } CoreEvent::TradeCompleted { trade, .. } => { - info!( - offered = trade.offered.len(), - received = trade.received.len(), - plat = trade.plat, - "Trade completed" - ); - debug!( - offered = ?trade.offered, - received = ?trade.received, - "Trade items" - ); - count_trade(app, state); - emit(app, AppEvent::TradesUpdated); - if settings.market.market_auto_close { - auto_close(app, state, trade).await; - } + trade_completed(app, state, &settings, trade).await; } CoreEvent::FissureAlert { fissure } => { let notice = Notice::fissure(fissure); @@ -203,6 +188,10 @@ async fn deliver(app: &AppHandle, state: &Arc, event: & let notice = Notice::reward(reward); world_alert(app, state, &settings, ¬ice, DiscordMirroredAlert::Reward).await; } + CoreEvent::WorldBountyAlert { alert } => { + let notice = Notice::bounty(alert); + world_alert(app, state, &settings, ¬ice, DiscordMirroredAlert::Bounty).await; + } CoreEvent::ArbitrationAlert { alert } => { arbitration_alert(app, state, &settings, alert).await; } @@ -234,6 +223,30 @@ async fn deliver(app: &AppHandle, state: &Arc, event: & } } +async fn trade_completed( + app: &AppHandle, + state: &Arc, + settings: &Settings, + trade: &Trade, +) { + info!( + offered = trade.offered.len(), + received = trade.received.len(), + plat = trade.plat, + "Trade completed" + ); + debug!( + offered = ?trade.offered, + received = ?trade.received, + "Trade items" + ); + count_trade(app, state); + emit(app, AppEvent::TradesUpdated); + if settings.market.market_auto_close { + auto_close(app, state, trade).await; + } +} + async fn world_alert( app: &AppHandle, state: &Arc, diff --git a/app/src-tauri/src/settings.rs b/app/src-tauri/src/settings.rs index 43bd615..1bf7bb3 100644 --- a/app/src-tauri/src/settings.rs +++ b/app/src-tauri/src/settings.rs @@ -239,6 +239,7 @@ pub enum InGameToast { Trade, Fissure, Reward, + Bounty, Arbitration, Timer, MarketClose, @@ -281,6 +282,7 @@ pub enum DiscordMirroredAlert { Conversation, Fissure, Reward, + Bounty, Arbitration, Timer, } diff --git a/app/src/components/item-search.tsx b/app/src/components/item-search.tsx index 28eec7a..69156f8 100644 --- a/app/src/components/item-search.tsx +++ b/app/src/components/item-search.tsx @@ -17,11 +17,13 @@ export function ItemSearch({ items, placeholder, disabled, + listOnFocus = false, onPick, }: { items: readonly T[]; placeholder: string; disabled?: boolean; + listOnFocus?: boolean; onPick: (item: T) => void; }) { const [query, setQuery] = useState(""); @@ -30,8 +32,9 @@ export function ItemSearch({ const matches = useMemo(() => { const search = query.trim().toLowerCase(); if (!search) { - return []; + return listOnFocus ? items : []; } + return items .filter((item) => item.name.toLowerCase().includes(search)) .sort( @@ -40,7 +43,7 @@ export function ItemSearch({ Number(a.name.toLowerCase() === search), ) .slice(0, 20); - }, [items, query]); + }, [items, query, listOnFocus]); const listed = open && matches.length > 0; return ( @@ -57,7 +60,7 @@ export function ItemSearch({ setQuery(next); setOpen(true); }} - onFocus={() => setOpen(query.trim().length > 0)} + onFocus={() => setOpen(listOnFocus || query.trim().length > 0)} onBlur={() => setOpen(false)} onKeyDown={(e) => { if (e.key === "Escape") { @@ -89,11 +92,13 @@ export function ItemSearch({ onPick(item); }} > - + {item.image_name && ( + + )} {item.name} ))} diff --git a/app/src/components/option-tabs.tsx b/app/src/components/option-tabs.tsx index 8125fa3..485d293 100644 --- a/app/src/components/option-tabs.tsx +++ b/app/src/components/option-tabs.tsx @@ -1,12 +1,20 @@ +import type { ReactNode } from "react"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +export interface OptionTab { + value: T; + label: string; + icon?: ReactNode; + mark?: string | false; +} + export function OptionTabs({ value, options, onChange, }: { value: T; - options: { value: T; label: string }[]; + options: OptionTab[]; onChange: (value: T) => void; }) { return ( @@ -18,7 +26,15 @@ export function OptionTabs({ {options.map((option) => ( + {option.icon} {option.label} + {option.mark && ( + + )} ))} diff --git a/app/src/lib/bridge.ts b/app/src/lib/bridge.ts index 370d330..8bf444a 100644 --- a/app/src/lib/bridge.ts +++ b/app/src/lib/bridge.ts @@ -8,6 +8,7 @@ import type { ArbitrationRun, ArbitrationRunExportFormat, Auction, + BountyAlertOptions, CommandError, ComparedStat, CraftDetails, @@ -258,6 +259,7 @@ export const api = { call("export_arbitration_run", { id, format }), invasionWeaponParts: () => call("invasion_weapon_parts"), + bountyAlertOptions: () => call("bounty_alert_options"), appLogFile: () => call("app_log_file"), openDataFolder: () => call("open_data_folder"), openGameLogFolder: () => call("open_game_log_folder"), diff --git a/app/src/pages/reset-checklist/checklist.tsx b/app/src/pages/reset-checklist/checklist.tsx index fbd6ad4..bdb83b2 100644 --- a/app/src/pages/reset-checklist/checklist.tsx +++ b/app/src/pages/reset-checklist/checklist.tsx @@ -85,6 +85,8 @@ function progressText(progress: ResetChecklistProgress): string | null { return countedText(progress.done, progress.total); case "remaining": return `${num(progress.left)} left of ${num(progress.cap)}`; + case "unlimited": + return "No limit"; case "manual": case "yes_no": return null; diff --git a/app/src/pages/settings/bounties.tsx b/app/src/pages/settings/bounties.tsx new file mode 100644 index 0000000..99e5792 --- /dev/null +++ b/app/src/pages/settings/bounties.tsx @@ -0,0 +1,112 @@ +import { X } from "lucide-react"; +import { ItemImage } from "@/components/item-image"; +import { ItemSearch } from "@/components/item-search"; +import { Section } from "@/components/page"; +import { useAsyncData } from "@/hooks/use-async-data"; +import { api } from "@/lib/bridge"; +import type { BountyAlertOption, Settings } from "@/types"; +import { FilterColumn, FilterRows, type PatchAlerts, SwitchRow } from "./row"; + +function BountyAlertPick({ + label, + placeholder, + value, + options, + onChange, +}: { + label: string; + placeholder: string; + value: string | null; + options: BountyAlertOption[]; + onChange: (value: string | null) => void; +}) { + const picked = options.find((option) => option.value === value); + return ( + + {value === null ? ( + onChange(option.value)} + /> + ) : ( +
+ {picked?.image_name && ( + + )} + + {picked?.name} + + +
+ )} +
+ ); +} + +export function BountyAlertSettings({ + draft, + patchAlerts, +}: { + draft: Settings; + patchAlerts: PatchAlerts; +}) { + const { data: options } = useAsyncData( + "bounty-alert-options", + api.bountyAlertOptions, + ); + + return ( +
+
+ + patchAlerts({ bounty_notifications_enabled: checked }) + } + > + Notify about bounties + + + patchAlerts({ bounty_filters })} + > + {(row, patch) => ( + <> + patch({ bounty })} + /> + patch({ reward })} + /> + + )} + +
+
+ ); +} diff --git a/app/src/pages/settings/fissures.tsx b/app/src/pages/settings/fissures.tsx index 6769a47..5acaa1c 100644 --- a/app/src/pages/settings/fissures.tsx +++ b/app/src/pages/settings/fissures.tsx @@ -1,13 +1,9 @@ -import { Plus, Trash2 } from "lucide-react"; import { OptionSelect } from "@/components/option-select"; import { Section } from "@/components/page"; -import { Button } from "@/components/ui/button"; -import { Label } from "@/components/ui/label"; import { type FilterOption, plainOptions } from "@/lib/filters"; -import { occurrenceKeys } from "@/lib/keys"; import { RELIC_TIERS } from "@/lib/relics"; import type { FissureFilter, FissureSubtype, Settings } from "@/types"; -import { type PatchAlerts, SwitchRow } from "./row"; +import { FilterColumn, FilterRows, type PatchAlerts, SwitchRow } from "./row"; const ANY = "all"; @@ -83,8 +79,7 @@ function ColumnSelect({ onChange: (value: T | typeof ANY) => void; }) { return ( -
- + label={label} value={value} @@ -92,7 +87,7 @@ function ColumnSelect({ onChange={onChange} className="w-full" /> -
+ ); } @@ -103,17 +98,6 @@ export function FissureAlerts({ draft: Settings; patchAlerts: PatchAlerts; }) { - const filters = draft.alerts.fissure_filters; - const filterKeys = occurrenceKeys( - filters.map((filter) => JSON.stringify(filter)), - ); - const patchFilter = (index: number, next: Partial) => - patchAlerts({ - fissure_filters: filters.map((row, position) => - position === index ? { ...row, ...next } : row, - ), - }); - return (
- {filters.map((row, index) => ( -
- patchFilter(index, { tier })} - /> - patchFilter(index, { mission })} - /> - patchFilter(index, { location })} - /> - patchFilter(index, { subtype })} - /> - -
- ))} - - + {(row, patch) => ( + <> + patch({ tier })} + /> + patch({ mission })} + /> + patch({ location })} + /> + patch({ subtype })} + /> + + )} +
); diff --git a/app/src/pages/settings/notifications.tsx b/app/src/pages/settings/notifications.tsx index 8501958..d769de9 100644 --- a/app/src/pages/settings/notifications.tsx +++ b/app/src/pages/settings/notifications.tsx @@ -31,6 +31,7 @@ const DISCORD_MIRRORED: { value: DiscordMirroredAlert; label: string }[] = [ { value: "conversation", label: "New conversations" }, { value: "fissure", label: "Fissure alerts" }, { value: "reward", label: "Reward alerts" }, + { value: "bounty", label: "Bounty alerts" }, { value: "arbitration", label: "Arbitration alerts" }, { value: "timer", label: "Cycle timers" }, ]; @@ -40,6 +41,7 @@ const IN_GAME_TOASTS: { value: InGameToast; label: string }[] = [ { value: "trade", label: "Completed trades" }, { value: "fissure", label: "Fissure alerts" }, { value: "reward", label: "Reward alerts" }, + { value: "bounty", label: "Bounty alerts" }, { value: "arbitration", label: "Arbitration alerts" }, { value: "timer", label: "Timer alerts" }, { value: "market_close", label: "Closed orders and auctions" }, diff --git a/app/src/pages/settings/row.tsx b/app/src/pages/settings/row.tsx index 9b4489d..86010ab 100644 --- a/app/src/pages/settings/row.tsx +++ b/app/src/pages/settings/row.tsx @@ -1,9 +1,12 @@ +import { Plus, Trash2 } from "lucide-react"; import type { ReactNode } from "react"; +import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Hint } from "@/components/ui/hint"; import { Label } from "@/components/ui/label"; import { Slider } from "@/components/ui/slider"; import { Switch } from "@/components/ui/switch"; +import { occurrenceKeys } from "@/lib/keys"; import { cn } from "@/lib/utils"; import type { Settings } from "@/types"; @@ -131,3 +134,72 @@ export function SliderRow({ ); } + +export function FilterColumn({ + label, + children, +}: { + label: string; + children: ReactNode; +}) { + return ( +
+ + {children} +
+ ); +} + +export function FilterRows({ + rows, + blank, + addDisabled, + columns, + onChange, + children, +}: { + rows: T[]; + blank: T; + addDisabled: boolean; + columns: string; + onChange: (rows: T[]) => void; + children: (row: T, patch: (next: Partial) => void) => ReactNode; +}) { + const keys = occurrenceKeys(rows.map((row) => JSON.stringify(row))); + return ( + <> + {rows.map((row, index) => ( +
+ {children(row, (next) => + onChange( + rows.map((kept, position) => + position === index ? { ...kept, ...next } : kept, + ), + ), + )} + +
+ ))} + + + + ); +} diff --git a/app/src/pages/settings/settings.tsx b/app/src/pages/settings/settings.tsx index 6689b90..96a553e 100644 --- a/app/src/pages/settings/settings.tsx +++ b/app/src/pages/settings/settings.tsx @@ -11,6 +11,7 @@ import { cn, scrollToSection } from "@/lib/utils"; import { useAppStore, useSettings } from "@/stores/app-store"; import type { Settings } from "@/types"; import { ArbitrationAlertSettingsSection } from "./arbitrations"; +import { BountyAlertSettings } from "./bounties"; import { DangerZone } from "./danger-zone"; import { PricesAndData, UpdateCheckSetting } from "./data"; import { DisplaySetting } from "./display"; @@ -151,6 +152,7 @@ export function SettingsPage() { + +
+
+ {bounty.name} + {bounty.alerting && Alert} +
+
+ + Level {bounty.level_range} + + {bounty.payout} + {bounty.reward_rotation && ( + Rotation {bounty.reward_rotation} + )} +
+
+
    + {bounty.rewards.map((reward) => ( +
  • + + + {reward.label} + + + + {percent(reward.chance)} + +
  • + ))} +
+ + ); +} + +export function BountiesSection({ + boards, + now, +}: { + boards: WorldBountyBoard[]; + now: number; +}) { + const bountyHub = usePreferencesStore((state) => state.bountyHub); + const setBountyHub = usePreferencesStore((state) => state.setBountyHub); + const board = + boards.find((shown) => shown.syndicate_tag === bountyHub) ?? boards[0]; + + return ( +
({ + value: syndicate_tag, + label: syndicate, + mark: bounties.some((bounty) => bounty.alerting) && ALERT_MARK, + }))} + onChange={setBountyHub} + /> + ) + } + action={ + board && ( +
+ {board.reward_rotation && ( + + Rotation {board.reward_rotation} + + )} + +
+ ) + } + > + {board ? ( +
+ {board.bounties.map((bounty) => ( + + ))} +
+ ) : ( + + The bounties of this rotation have not been fetched yet. + + )} +
+ ); +} diff --git a/app/src/pages/world/world.tsx b/app/src/pages/world/world.tsx index b39c4e5..828571d 100644 --- a/app/src/pages/world/world.tsx +++ b/app/src/pages/world/world.tsx @@ -1,15 +1,21 @@ -import { OptionTabs } from "@/components/option-tabs"; +import { Globe, ScrollText } from "lucide-react"; +import { GameIcon } from "@/components/game-icon"; +import { type OptionTab, OptionTabs } from "@/components/option-tabs"; import { EmptyNote, Page, Section } from "@/components/page"; +import { Button } from "@/components/ui/button"; +import { CheckboxField } from "@/components/ui/checkbox"; import { useNow } from "@/hooks/use-now"; import { useRollover } from "@/hooks/use-rollover"; +import { useTabParam } from "@/hooks/use-tab-param"; import { api, reportError } from "@/lib/bridge"; +import { toggled } from "@/lib/filters"; import { secondsUntil } from "@/lib/format"; -import { cn } from "@/lib/utils"; -import { cycleCardSpan } from "@/lib/world"; +import { cycleCardSpan, timeLeft } from "@/lib/world"; import { useAppStore, useSettings } from "@/stores/app-store"; import { usePreferencesStore } from "@/stores/preferences-store"; -import type { Fissure, FissurePath } from "@/types"; +import type { Fissure, FissureKind } from "@/types"; import { WorldArbitrationCard } from "./arbitrations"; +import { ALERT_MARK, BountiesSection } from "./bounties"; import { FissuresByTier } from "./fissures"; import { MarketSalesPanel } from "./market-sales"; import { @@ -25,24 +31,36 @@ import { import { WorldRewardAlertsPanel } from "./rewards"; import { TimerChip } from "./timers"; -const PATH_FILTERS: { value: FissurePath; label: string }[] = [ - { value: "baseline", label: "Normal + Steel Path" }, +type WorldPageTab = "overview" | "bounties" | "missions" | "vendors"; + +const PANEL_COLUMNS = "grid items-start gap-4 @lg:grid-cols-2"; + +const FISSURE_KINDS: { value: FissureKind; label: string }[] = [ { value: "normal", label: "Normal" }, - { value: "hard", label: "Steel Path" }, - { value: "storm", label: "Void Storms" }, - { value: "all", label: "All" }, + { value: "steelPath", label: "Steel Path" }, + { value: "voidStorm", label: "Void Storm" }, ]; +function fissureKind(fissure: Fissure): FissureKind { + if (fissure.is_storm) { + return "voidStorm"; + } + + return fissure.steel_path ? "steelPath" : "normal"; +} + export function WorldPage() { const data = useAppStore((state) => state.world); const setWorld = useAppStore((state) => state.setWorld); const now = useNow(); - const fissurePath = usePreferencesStore((state) => state.fissurePath); - const setFissurePath = usePreferencesStore((state) => state.setFissurePath); + const [tab, setTab] = useTabParam("overview"); + const fissureKinds = usePreferencesStore((state) => state.fissureKinds); + const setFissureKinds = usePreferencesStore((state) => state.setFissureKinds); const rollovers = data ? [ ...data.timers.map((timer) => timer.ends), + ...data.bounty_boards.map((board) => board.expiry), data.daily_reset.expiry, data.weekly_reset.expiry, ] @@ -51,16 +69,9 @@ export function WorldPage() { api.worldstate().then(setWorld, reportError); }); - const shown: Record boolean> = { - all: () => true, - baseline: (fissure) => !fissure.is_storm, - normal: (fissure) => !fissure.steel_path && !fissure.is_storm, - hard: (fissure) => fissure.steel_path, - storm: (fissure) => fissure.is_storm, - }; const fissures = (data?.fissures ?? []) .filter((fissure) => secondsUntil(fissure.expiry, now) > 0) - .filter(shown[fissurePath]) + .filter((fissure) => fissureKinds.includes(fissureKind(fissure))) .sort( (left, right) => new Date(left.expiry).getTime() - new Date(right.expiry).getTime(), @@ -71,81 +82,150 @@ export function WorldPage() { const sortie = data?.sortie ?? null; const baro = data?.baro ?? null; - const baroPresent = baro !== null && "Present" in baro; - const baroPanel = ( - + const baroLeavesIn = + baro !== null && "Present" in baro + ? secondsUntil(baro.Present.leaves, now) + : 0; + const bountyBoards = (data?.bounty_boards ?? []).filter( + (board) => secondsUntil(board.expiry, now) > 0, ); + const alertingBounties = bountyBoards + .flatMap((board) => board.bounties) + .filter((bounty) => bounty.alerting).length; + + const tabs: OptionTab[] = [ + { value: "overview", label: "Overview", icon: }, + { + value: "bounties", + label: "Bounties", + icon: , + mark: alertingBounties > 0 && ALERT_MARK, + }, + { value: "missions", label: "Missions", icon: }, + { + value: "vendors", + label: "Vendors", + icon: , + mark: baroLeavesIn > 0 && "Baro Ki'Teer is here", + }, + ]; return ( - {data?.timers.length ? ( -
- {data.timers.map((timer, index) => ( - - ))} - {arbitrationShown && ( - +
+ +
+ + {tab === "overview" && ( + <> + {data?.timers.length ? ( +
+ {data.timers.map((timer, index) => ( + + ))} + {arbitrationShown && ( + + )} +
+ ) : ( + The world state has not been fetched yet. )} -
- ) : ( - The world state has not been fetched yet. - )} -
- } - > - -
- -
- {baroPresent && baroPanel} -
- {!baroPresent && baroPanel} - +
+ {baroLeavesIn > 0 && ( + + )} + {alertingBounties > 0 && ( + + )} +
+ +
+ {FISSURE_KINDS.map(({ value, label }) => ( + + setFissureKinds(toggled(fissureKinds, value, checked)) + } + > + {label} + + ))} +
+ } + > + + + - - - - -
-
- - + + )} + + {tab === "bounties" && ( + + )} + + {tab === "missions" && ( +
+
+ + + + +
-
+ )} + + {tab === "vendors" && ( +
+
+ + +
+
+ + +
+
+ )}
); } diff --git a/app/src/stores/preferences-store.ts b/app/src/stores/preferences-store.ts index 33d8b2a..405fac4 100644 --- a/app/src/stores/preferences-store.ts +++ b/app/src/stores/preferences-store.ts @@ -5,7 +5,7 @@ import type { Category } from "@/lib/foundry-filters"; import { readStored, readStoredJson } from "@/lib/storage"; import type { ArcanesTabView, - FissurePath, + FissureKind, ResourceScope, ResourceSource, StatsHistoryItem, @@ -17,7 +17,8 @@ interface PreferencesState { squadSize: number; refinement: string; era: string; - fissurePath: FissurePath; + fissureKinds: FissureKind[]; + bountyHub: string | null; timeframes: Record; historyItems: StatsHistoryItem[]; foundryCategory: Category; @@ -31,7 +32,8 @@ interface PreferencesState { setSquadSize: (squadSize: number) => void; setRefinement: (refinement: string) => void; setEra: (era: string) => void; - setFissurePath: (fissurePath: FissurePath) => void; + setFissureKinds: (fissureKinds: FissureKind[]) => void; + setBountyHub: (bountyHub: string) => void; setTimeframe: (card: TimeframeCard, timeframe: Timeframe) => void; setHistoryItems: (historyItems: StatsHistoryItem[]) => void; setFoundryCategory: (foundryCategory: Category) => void; @@ -88,10 +90,8 @@ export const usePreferencesStore = create()( squadSize: legacySquadSize ? Number(legacySquadSize) : DEFAULT_SQUAD_SIZE, refinement: legacy("merframe.relicPlanner.refinement", ANY), era: legacy("merframe.relicPlanner.era", "all"), - fissurePath: legacy( - "merframe.world.fissurePath", - "baseline", - ), + fissureKinds: ["normal", "steelPath"], + bountyHub: null, timeframes: DEFAULT_TIMEFRAMES, historyItems: DEFAULT_HISTORY_ITEMS, foundryCategory: legacy( @@ -108,7 +108,8 @@ export const usePreferencesStore = create()( setSquadSize: (squadSize) => set({ squadSize }), setRefinement: (refinement) => set({ refinement }), setEra: (era) => set({ era }), - setFissurePath: (fissurePath) => set({ fissurePath }), + setFissureKinds: (fissureKinds) => set({ fissureKinds }), + setBountyHub: (bountyHub) => set({ bountyHub }), setTimeframe: (card, timeframe) => set((state) => ({ timeframes: { ...state.timeframes, [card]: timeframe }, @@ -133,7 +134,8 @@ export const usePreferencesStore = create()( squadSize: state.squadSize, refinement: state.refinement, era: state.era, - fissurePath: state.fissurePath, + fissureKinds: state.fissureKinds, + bountyHub: state.bountyHub, timeframes: state.timeframes, historyItems: state.historyItems, foundryCategory: state.foundryCategory, diff --git a/app/src/types/generated/AlertSettings.ts b/app/src/types/generated/AlertSettings.ts index 8e08055..45e4de7 100644 --- a/app/src/types/generated/AlertSettings.ts +++ b/app/src/types/generated/AlertSettings.ts @@ -1,7 +1,8 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ArbitrationAlertSettings } from "./ArbitrationAlertSettings"; +import type { BountyAlertFilter } from "./BountyAlertFilter"; import type { FissureFilter } from "./FissureFilter"; import type { TimerAlerts } from "./TimerAlerts"; import type { WorldRewardAlertChoices } from "./WorldRewardAlertChoices"; -export type AlertSettings = { fissure_notifications_enabled: boolean, fissure_filters: Array, timers: TimerAlerts, timer_lead_secs: number, reward_notifications_enabled: boolean, rewards: WorldRewardAlertChoices, arbitrations: ArbitrationAlertSettings, }; +export type AlertSettings = { fissure_notifications_enabled: boolean, fissure_filters: Array, timers: TimerAlerts, timer_lead_secs: number, reward_notifications_enabled: boolean, rewards: WorldRewardAlertChoices, bounty_notifications_enabled: boolean, bounty_filters: Array, arbitrations: ArbitrationAlertSettings, }; diff --git a/app/src/types/generated/BountyAlertFilter.ts b/app/src/types/generated/BountyAlertFilter.ts new file mode 100644 index 0000000..5963447 --- /dev/null +++ b/app/src/types/generated/BountyAlertFilter.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type BountyAlertFilter = { bounty: string | null, reward: string | null, }; diff --git a/app/src/types/generated/BountyAlertOption.ts b/app/src/types/generated/BountyAlertOption.ts new file mode 100644 index 0000000..fa6b6f9 --- /dev/null +++ b/app/src/types/generated/BountyAlertOption.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type BountyAlertOption = { value: string, name: string, image_name: string | null, }; diff --git a/app/src/types/generated/BountyAlertOptions.ts b/app/src/types/generated/BountyAlertOptions.ts new file mode 100644 index 0000000..b6a06da --- /dev/null +++ b/app/src/types/generated/BountyAlertOptions.ts @@ -0,0 +1,4 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { BountyAlertOption } from "./BountyAlertOption"; + +export type BountyAlertOptions = { bounties: Array, rewards: Array, }; diff --git a/app/src/types/generated/CoreEvent.ts b/app/src/types/generated/CoreEvent.ts index d017ba1..45b8bc5 100644 --- a/app/src/types/generated/CoreEvent.ts +++ b/app/src/types/generated/CoreEvent.ts @@ -5,6 +5,7 @@ import type { FissureInfo } from "./FissureInfo"; import type { InventorySummary } from "./InventorySummary"; import type { RewardScreen } from "./RewardScreen"; import type { Trade } from "./Trade"; +import type { WorldBountyAlert } from "./WorldBountyAlert"; import type { WorldRewardAlert } from "./WorldRewardAlert"; -export type CoreEvent = { "InventoryUpdated": InventorySummary } | { "RelicRewardScreen": { relic: string | null, screen: RewardScreen, } } | { "TradeCompleted": { at: string, partner: string | null, trade: Trade, } } | { "NewConversation": { channel: string, player: string, } } | { "FissureAlert": { fissure: FissureInfo, } } | { "WorldRewardAlert": { reward: WorldRewardAlert, } } | { "ArbitrationAlert": { alert: ArbitrationAlert, } } | { "ArbitrationRunUpdated": { run: ArbitrationRun, } } | { "ArbitrationRunRecorded": { run: ArbitrationRun, } } | { "TimerAlert": { name: string, next_state: string, ends_at: string, remaining_secs: number, } } | "MissionWon"; +export type CoreEvent = { "InventoryUpdated": InventorySummary } | { "RelicRewardScreen": { relic: string | null, screen: RewardScreen, } } | { "TradeCompleted": { at: string, partner: string | null, trade: Trade, } } | { "NewConversation": { channel: string, player: string, } } | { "FissureAlert": { fissure: FissureInfo, } } | { "WorldRewardAlert": { reward: WorldRewardAlert, } } | { "WorldBountyAlert": { alert: WorldBountyAlert, } } | { "ArbitrationAlert": { alert: ArbitrationAlert, } } | { "ArbitrationRunUpdated": { run: ArbitrationRun, } } | { "ArbitrationRunRecorded": { run: ArbitrationRun, } } | { "TimerAlert": { name: string, next_state: string, ends_at: string, remaining_secs: number, } } | "MissionWon"; diff --git a/app/src/types/generated/DiscordMirroredAlert.ts b/app/src/types/generated/DiscordMirroredAlert.ts index 1d28e2b..6904394 100644 --- a/app/src/types/generated/DiscordMirroredAlert.ts +++ b/app/src/types/generated/DiscordMirroredAlert.ts @@ -1,3 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type DiscordMirroredAlert = "conversation" | "fissure" | "reward" | "arbitration" | "timer"; +export type DiscordMirroredAlert = "conversation" | "fissure" | "reward" | "bounty" | "arbitration" | "timer"; diff --git a/app/src/types/generated/InGameToast.ts b/app/src/types/generated/InGameToast.ts index 6cb21ac..b5a600c 100644 --- a/app/src/types/generated/InGameToast.ts +++ b/app/src/types/generated/InGameToast.ts @@ -1,3 +1,3 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type InGameToast = "inventory" | "trade" | "fissure" | "reward" | "arbitration" | "timer" | "market_close"; +export type InGameToast = "inventory" | "trade" | "fissure" | "reward" | "bounty" | "arbitration" | "timer" | "market_close"; diff --git a/app/src/types/generated/ResetChecklistProgress.ts b/app/src/types/generated/ResetChecklistProgress.ts index a175482..c30beab 100644 --- a/app/src/types/generated/ResetChecklistProgress.ts +++ b/app/src/types/generated/ResetChecklistProgress.ts @@ -1,4 +1,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ResetChecklistManualRowId } from "./ResetChecklistManualRowId"; -export type ResetChecklistProgress = { "kind": "counted", done: number, total: number, } | { "kind": "remaining", left: number, cap: number, } | { "kind": "yes_no" } | { "kind": "manual", id: ResetChecklistManualRowId, checked: boolean, } | { "kind": "unknown" }; +export type ResetChecklistProgress = { "kind": "counted", done: number, total: number, } | { "kind": "remaining", left: number, cap: number, } | { "kind": "unlimited" } | { "kind": "yes_no" } | { "kind": "manual", id: ResetChecklistManualRowId, checked: boolean, } | { "kind": "unknown" }; diff --git a/app/src/types/generated/WorldBounty.ts b/app/src/types/generated/WorldBounty.ts new file mode 100644 index 0000000..d238330 --- /dev/null +++ b/app/src/types/generated/WorldBounty.ts @@ -0,0 +1,4 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { WorldBountyReward } from "./WorldBountyReward"; + +export type WorldBounty = { key: string, name: string, level_range: string, payout: string, reward_rotation: string | null, rewards: Array, alerting: boolean, }; diff --git a/app/src/types/generated/WorldBountyAlert.ts b/app/src/types/generated/WorldBountyAlert.ts new file mode 100644 index 0000000..ce29e9a --- /dev/null +++ b/app/src/types/generated/WorldBountyAlert.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type WorldBountyAlert = { syndicate: string, bounties: Array, rewards: Array, expiry: string, remaining_secs: number, }; diff --git a/app/src/types/generated/WorldBountyBoard.ts b/app/src/types/generated/WorldBountyBoard.ts new file mode 100644 index 0000000..6747052 --- /dev/null +++ b/app/src/types/generated/WorldBountyBoard.ts @@ -0,0 +1,4 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { WorldBounty } from "./WorldBounty"; + +export type WorldBountyBoard = { syndicate_tag: string, syndicate: string, expiry: string, reward_rotation: string | null, bounties: Array, }; diff --git a/app/src/types/generated/WorldBountyReward.ts b/app/src/types/generated/WorldBountyReward.ts new file mode 100644 index 0000000..b4ecad7 --- /dev/null +++ b/app/src/types/generated/WorldBountyReward.ts @@ -0,0 +1,4 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { WorldOfferOwnership } from "./WorldOfferOwnership"; + +export type WorldBountyReward = { label: string, image_name: string | null, chance: number, wanted: boolean, ownership: WorldOfferOwnership | null, }; diff --git a/app/src/types/generated/WorldStateView.ts b/app/src/types/generated/WorldStateView.ts index 8e2888f..ef45e5b 100644 --- a/app/src/types/generated/WorldStateView.ts +++ b/app/src/types/generated/WorldStateView.ts @@ -11,6 +11,7 @@ import type { PrimeResurgence } from "./PrimeResurgence"; import type { ResetWindow } from "./ResetWindow"; import type { Sortie } from "./Sortie"; import type { Timer } from "./Timer"; +import type { WorldBountyBoard } from "./WorldBountyBoard"; import type { WorldRewardAlert } from "./WorldRewardAlert"; -export type WorldStateView = { fissures: Array, baro: BaroStatus | null, baro_manifest: Array, sortie: Sortie | null, archon_hunt: ArchonHunt | null, timers: Array, daily_deals: Array, market_sales: Array, circuit: CircuitRotation | null, prime_resurgence: PrimeResurgence | null, nightwave: NightwaveSeason | null, world_reward_alerts: Array, daily_reset: ResetWindow, weekly_reset: ResetWindow, fetched_at: string | null, }; +export type WorldStateView = { fissures: Array, baro: BaroStatus | null, baro_manifest: Array, sortie: Sortie | null, archon_hunt: ArchonHunt | null, timers: Array, daily_deals: Array, market_sales: Array, circuit: CircuitRotation | null, prime_resurgence: PrimeResurgence | null, nightwave: NightwaveSeason | null, world_reward_alerts: Array, bounty_boards: Array, daily_reset: ResetWindow, weekly_reset: ResetWindow, fetched_at: string | null, }; diff --git a/app/src/types/generated/index.ts b/app/src/types/generated/index.ts index 3ed24ff..ccaa2e8 100644 --- a/app/src/types/generated/index.ts +++ b/app/src/types/generated/index.ts @@ -37,6 +37,9 @@ export type * from "./BaroGroup"; export type * from "./BaroOffer"; export type * from "./BaroStatus"; export type * from "./Best"; +export type * from "./BountyAlertFilter"; +export type * from "./BountyAlertOption"; +export type * from "./BountyAlertOptions"; export type * from "./CategoryStatement"; export type * from "./CategoryTotals"; export type * from "./ChallengeKind"; @@ -277,6 +280,10 @@ export type * from "./VosforPackCompletion"; export type * from "./VosforPackNeededArcane"; export type * from "./VosforPackRow"; export type * from "./WindowCloseBehavior"; +export type * from "./WorldBounty"; +export type * from "./WorldBountyAlert"; +export type * from "./WorldBountyBoard"; +export type * from "./WorldBountyReward"; export type * from "./WorldOfferOwnership"; export type * from "./WorldRewardAlert"; export type * from "./WorldRewardAlertChoices"; diff --git a/app/src/types/preferences.ts b/app/src/types/preferences.ts index 976ef84..e8b5158 100644 --- a/app/src/types/preferences.ts +++ b/app/src/types/preferences.ts @@ -1,4 +1,4 @@ -export type FissurePath = "baseline" | "normal" | "hard" | "storm" | "all"; +export type FissureKind = "normal" | "steelPath" | "voidStorm"; export type ArcanesTabView = "inventory" | "collection" | "packs"; export type Timeframe = "today" | "7" | "30" | "90" | "all"; export interface StatsHistoryItem { diff --git a/crates/wf-core/src/events/alerts.rs b/crates/wf-core/src/events/alerts.rs index ee138ba..6f6695e 100644 --- a/crates/wf-core/src/events/alerts.rs +++ b/crates/wf-core/src/events/alerts.rs @@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize}; use wf_worldstate::{EARTH_AND_CETUS, Fissure, RelicTier, mission_type_name, node_and_planet}; use super::arbitrations::ArbitrationAlertSettings; +use super::bounties::BountyAlertFilter; use super::rewards::WorldRewardAlertChoices; const ANY: &str = "all"; @@ -208,6 +209,8 @@ pub struct AlertSettings { pub timer_lead_secs: i64, pub reward_notifications_enabled: bool, pub rewards: WorldRewardAlertChoices, + pub bounty_notifications_enabled: bool, + pub bounty_filters: Vec, pub arbitrations: ArbitrationAlertSettings, } @@ -220,6 +223,8 @@ impl Default for AlertSettings { timer_lead_secs: 180, reward_notifications_enabled: false, rewards: WorldRewardAlertChoices::default(), + bounty_notifications_enabled: false, + bounty_filters: Vec::new(), arbitrations: ArbitrationAlertSettings::default(), } } @@ -487,6 +492,11 @@ mod tests { ], ..WorldRewardAlertChoices::default() }, + bounty_notifications_enabled: true, + bounty_filters: vec![BountyAlertFilter { + bounty: None, + reward: Some("/Lotus/Types/Items/MiscItems/CetusWispItem".to_owned()), + }], arbitrations: ArbitrationAlertSettings { enabled: true, reminders: BTreeSet::from(["1727892000:SolNode64".to_owned()]), diff --git a/crates/wf-core/src/events/bounties.rs b/crates/wf-core/src/events/bounties.rs new file mode 100644 index 0000000..b2876a7 --- /dev/null +++ b/crates/wf-core/src/events/bounties.rs @@ -0,0 +1,662 @@ +use std::collections::{BTreeSet, HashMap}; + +use chrono::{DateTime, Utc}; +use indexmap::{IndexMap, IndexSet}; +use serde::{Deserialize, Serialize}; +use wf_data::{BountyReward, BountyTables, store_item_to_type}; +use wf_worldstate::{Bounty, BountyBoard, BountyKind, WorldState}; + +use super::CoreEvent; +use super::rewards::counted_label; +use crate::account::{Account, WorldOfferOwnership}; +use crate::catalog::{Catalog, display_name_from_path, is_part}; +use crate::identity::{ItemKind, ItemRecord, ItemTable}; +use crate::text::thousands; + +struct BountySyndicate { + tag: &'static str, + job_directory: &'static str, + paid_in: &'static str, +} + +const BOUNTY_SYNDICATES: [BountySyndicate; 3] = [ + BountySyndicate { + tag: "CetusSyndicate", + job_directory: "/Lotus/Types/Gameplay/Eidolon/Jobs/", + paid_in: "Standing", + }, + BountySyndicate { + tag: "SolarisSyndicate", + job_directory: "/Lotus/Types/Gameplay/Venus/Jobs/", + paid_in: "Standing", + }, + BountySyndicate { + tag: "EntratiSyndicate", + job_directory: "/Lotus/Types/Gameplay/InfestedMicroplanet/Jobs/", + paid_in: "Mother Tokens", + }, +]; + +const ENDO_BUNDLES: [(&str, u32); 2] = [ + ( + "/Lotus/Upgrades/Mods/FusionBundles/UncommonFusionBundle", + 50, + ), + ("/Lotus/Upgrades/Mods/FusionBundles/RareFusionBundle", 80), +]; + +const CREDITS_DIRECTORY: &str = "/Lotus/Types/PickUps/Credits/"; + +fn endo_per_bundle(item_type: &str) -> Option { + ENDO_BUNDLES + .iter() + .find(|(bundle, _)| *bundle == item_type) + .map(|(_, endo)| *endo) +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))] +#[serde(default)] +pub struct BountyAlertFilter { + pub bounty: Option, + pub reward: Option, +} + +impl BountyAlertFilter { + fn wants_reward(&self, reward: &BountyReward) -> bool { + self.reward + .as_ref() + .is_some_and(|wanted| *wanted == store_item_to_type(&reward.store_item)) + } + + fn matches(&self, bounty: &Bounty, reward_stages: &[Vec]) -> bool { + if self.bounty.is_none() && self.reward.is_none() { + return false; + } + + let bounty_matches = self.bounty.as_ref().is_none_or( + |wanted| matches!(&bounty.kind, BountyKind::Job(job_type) if job_type == wanted), + ); + let reward_matches = self.reward.is_none() + || reward_stages + .iter() + .flatten() + .any(|reward| self.wants_reward(reward)); + bounty_matches && reward_matches + } +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))] +pub struct WorldBountyReward { + pub label: String, + pub image_name: Option, + pub chance: f64, + pub wanted: bool, + pub ownership: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))] +pub struct WorldBounty { + pub key: String, + pub name: String, + pub level_range: String, + pub payout: String, + pub reward_rotation: Option, + pub rewards: Vec, + pub alerting: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))] +pub struct WorldBountyBoard { + pub syndicate_tag: String, + pub syndicate: String, + pub expiry: DateTime, + pub reward_rotation: Option, + pub bounties: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub struct WorldBountyAlert { + pub syndicate: String, + pub bounties: Vec, + pub rewards: Vec, + pub expiry: DateTime, + pub remaining_secs: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))] +pub struct BountyAlertOption { + pub value: String, + pub name: String, + pub image_name: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "bindings", derive(ts_rs::TS), ts(export))] +pub struct BountyAlertOptions { + pub bounties: Vec, + pub rewards: Vec, +} + +fn syndicate_name(catalog: &Catalog, tag: &str) -> String { + catalog + .data() + .syndicates() + .iter() + .find(|syndicate| syndicate.tag == tag) + .map_or_else(|| tag.to_owned(), |syndicate| syndicate.name.clone()) +} + +fn bounty_name(tables: &BountyTables, kind: &BountyKind) -> String { + match kind { + BountyKind::Job(job_type) => tables + .name(job_type) + .map_or_else(|| display_name_from_path(job_type), str::to_owned), + BountyKind::IsolationVault => "Isolation Vault".to_owned(), + } +} + +fn reward_image_name(record: &ItemRecord) -> Option { + if record.unique_name.starts_with(CREDITS_DIRECTORY) { + return Some("game/credits.png".to_owned()); + } + + record.image_name.clone() +} + +struct Holdings<'a> { + catalog: &'a Catalog, + items: &'a ItemTable, + account: Option<&'a Account>, +} + +impl Holdings<'_> { + fn ownership(&self, record: &ItemRecord) -> Option { + let account = self.account?; + let built_item = self + .catalog + .component_for_stock(&record.unique_name) + .filter(|(_, component)| is_part(component)) + .map(|(item, _)| item) + .or_else(|| self.catalog.item(&record.unique_name)) + .filter(|item| item.masterable()); + match (built_item, &record.kind) { + (Some(item), _) => Some(account.world_offer_ownership(&item.unique_name, self.catalog)), + (None, ItemKind::Upgrade { .. }) => { + Some(account.world_offer_ownership(&record.unique_name, self.catalog)) + } + (None, _) => None, + } + } +} + +fn world_bounty_rewards( + reward_stages: &[Vec], + holdings: &Holdings, + matching: &[&BountyAlertFilter], +) -> Vec { + let mut listed: IndexMap<(&str, u32), &BountyReward> = IndexMap::new(); + for reward in reward_stages.iter().rev().flatten() { + listed + .entry((&reward.store_item, reward.item_count)) + .or_insert(reward); + } + + let mut listed: Vec<&BountyReward> = listed.into_values().collect(); + listed.sort_by(|a, b| a.probability.total_cmp(&b.probability)); + + listed + .into_iter() + .map(|reward| { + let record = holdings.items.resolve(&reward.store_item); + let label = match endo_per_bundle(&record.unique_name) { + Some(endo) => format!("{} Endo", thousands(i64::from(reward.item_count * endo))), + None => counted_label(i64::from(reward.item_count), &record.name), + }; + WorldBountyReward { + label, + image_name: reward_image_name(&record), + chance: reward.probability, + wanted: matching.iter().any(|filter| filter.wants_reward(reward)), + ownership: holdings.ownership(&record), + } + }) + .collect() +} + +fn world_bounty( + board: &BountyBoard, + bounty: &Bounty, + holdings: &Holdings, + filters: &[BountyAlertFilter], +) -> WorldBounty { + let tables = holdings.catalog.data().bounty_tables(); + let reward_stages = tables.reward_stages(&bounty.reward_deck); + let matching: Vec<&BountyAlertFilter> = filters + .iter() + .filter(|filter| filter.matches(bounty, reward_stages)) + .collect(); + let (min_level, max_level) = bounty.levels; + let paid_in = BOUNTY_SYNDICATES + .iter() + .find(|syndicate| syndicate.tag == board.syndicate_tag) + .map_or("Standing", |syndicate| syndicate.paid_in); + + WorldBounty { + key: format!( + "{}:{}:{min_level}@{}", + board.syndicate_tag, + bounty.reward_deck, + board.expiry.timestamp() + ), + name: bounty_name(tables, &bounty.kind), + level_range: if min_level == max_level { + min_level.to_string() + } else { + format!("{min_level}-{max_level}") + }, + payout: format!("{} {paid_in}", thousands(i64::from(bounty.standing))), + reward_rotation: bounty.reward_rotation, + rewards: world_bounty_rewards(reward_stages, holdings, &matching), + alerting: !matching.is_empty(), + } +} + +fn most_common_rotation(bounties: &[Bounty]) -> Option { + let mut counts: IndexMap = IndexMap::new(); + for rotation in bounties.iter().filter_map(|bounty| bounty.reward_rotation) { + *counts.entry(rotation).or_default() += 1; + } + + counts + .into_iter() + .max_by_key(|&(_, count)| count) + .map(|(rotation, _)| rotation) +} + +pub(crate) fn world_bounty_boards( + world: &WorldState, + catalog: &Catalog, + items: &ItemTable, + account: Option<&Account>, + filters: &[BountyAlertFilter], + now: DateTime, +) -> Vec { + let holdings = Holdings { + catalog, + items, + account, + }; + let position = |board: &BountyBoard| { + BOUNTY_SYNDICATES + .iter() + .position(|syndicate| syndicate.tag == board.syndicate_tag) + .unwrap_or(BOUNTY_SYNDICATES.len()) + }; + let mut boards = world.bounty_boards(now); + boards.sort_by_key(position); + + boards + .iter() + .map(|board| { + let reward_rotation = most_common_rotation(&board.bounties); + let mut bounties: Vec = board + .bounties + .iter() + .map(|bounty| world_bounty(board, bounty, &holdings, filters)) + .collect(); + for bounty in &mut bounties { + if bounty.reward_rotation == reward_rotation { + bounty.reward_rotation = None; + } + } + + WorldBountyBoard { + syndicate_tag: board.syndicate_tag.clone(), + syndicate: syndicate_name(catalog, &board.syndicate_tag), + expiry: board.expiry, + reward_rotation, + bounties, + } + }) + .collect() +} + +impl WorldBountyAlert { + fn of(board: &WorldBountyBoard, bounties: &[&WorldBounty], now: DateTime) -> Self { + let rewards: IndexSet = bounties + .iter() + .flat_map(|bounty| &bounty.rewards) + .filter(|reward| reward.wanted) + .map(|reward| reward.label.clone()) + .collect(); + + Self { + syndicate: board.syndicate.clone(), + bounties: bounties + .iter() + .map(|bounty| format!("{} ({})", bounty.name, bounty.level_range)) + .collect(), + rewards: rewards.into_iter().collect(), + expiry: board.expiry, + remaining_secs: board.expiry.signed_duration_since(now).num_seconds(), + } + } +} + +#[derive(Default)] +pub(crate) struct BountyAnnouncer { + announced_until: HashMap>, +} + +impl BountyAnnouncer { + pub(crate) fn announce( + &mut self, + boards: &[WorldBountyBoard], + first_poll: bool, + now: DateTime, + ) -> Vec { + self.announced_until.retain(|_, until| *until > now); + + let mut alerts = Vec::new(); + for board in boards { + let unseen: Vec<&WorldBounty> = board + .bounties + .iter() + .filter(|bounty| bounty.alerting) + .filter(|bounty| { + self.announced_until + .insert(bounty.key.clone(), board.expiry) + .is_none() + }) + .collect(); + if !first_poll && !unseen.is_empty() { + alerts.push(CoreEvent::WorldBountyAlert { + alert: WorldBountyAlert::of(board, &unseen, now), + }); + } + } + + alerts + } +} + +fn sorted_by_name(mut options: Vec) -> Vec { + options.sort_by(|a, b| a.name.cmp(&b.name)); + options +} + +pub(crate) fn bounty_alert_options(catalog: &Catalog, items: &ItemTable) -> BountyAlertOptions { + let tables = catalog.data().bounty_tables(); + let bounties = tables + .names() + .filter_map(|(job_type, name)| { + let syndicate = BOUNTY_SYNDICATES + .iter() + .find(|syndicate| job_type.starts_with(syndicate.job_directory))?; + Some(BountyAlertOption { + value: job_type.to_owned(), + name: format!("{}: {name}", syndicate_name(catalog, syndicate.tag)), + image_name: None, + }) + }) + .collect(); + let rewards = tables + .rewards() + .map(|reward| store_item_to_type(&reward.store_item)) + .collect::>() + .into_iter() + .map(|item_type| { + let record = items.resolve(&item_type); + BountyAlertOption { + name: match endo_per_bundle(&item_type) { + Some(endo) => format!("Endo ({endo} per bundle)"), + None => record.name.clone(), + }, + image_name: reward_image_name(&record), + value: item_type, + } + }) + .collect(); + + BountyAlertOptions { + bounties: sorted_by_name(bounties), + rewards: sorted_by_name(rewards), + } +} + +#[cfg(test)] +mod tests { + use wf_data::{Dictionary, GameData}; + + use super::*; + use crate::catalog::fixtures::{self, at}; + + const SPY: &str = "/Lotus/Types/Gameplay/Venus/Jobs/VenusIntelJobSpy"; + const WISP: &str = "/Lotus/Types/Items/MiscItems/CetusWispItem"; + const WORLD: &str = r#"{"SyndicateMissions":[ + {"_id":{"$oid":"6a9f07790000000000000002"},"Tag":"EntratiSyndicate", + "Activation":{"$date":{"$numberLong":"1000"}},"Expiry":{"$date":{"$numberLong":"5000"}}, + "Jobs":[{"rewards":"/Lotus/Types/Game/MissionDecks/DeimosMissionRewards/VaultBountyTierATableCRewards", + "masteryReq":5,"minEnemyLevel":30,"maxEnemyLevel":40,"xpAmounts":[2,2,2,4]}]}, + {"_id":{"$oid":"6a9f07790000000000000033"},"Tag":"SolarisSyndicate", + "Activation":{"$date":{"$numberLong":"1000"}},"Expiry":{"$date":{"$numberLong":"5000"}}, + "Jobs":[{"jobType":"/Lotus/Types/Gameplay/Venus/Jobs/VenusIntelJobSpy", + "rewards":"/Lotus/Types/Game/MissionDecks/VenusJobMissionRewards/VenusTierBTableBRewards", + "masteryReq":1,"minEnemyLevel":10,"maxEnemyLevel":30,"xpAmounts":[720,720,720]}, + {"jobType":"/Lotus/Types/Gameplay/Venus/Jobs/Unlisted", + "rewards":"/Lotus/Types/Game/MissionDecks/VenusJobMissionRewards/VenusTierBTableBRewards", + "masteryReq":10,"minEnemyLevel":100,"maxEnemyLevel":100,"xpAmounts":[840]}, + {"jobType":"/Lotus/Types/Gameplay/Venus/Jobs/Unlisted", + "rewards":"/Lotus/Types/Game/MissionDecks/VenusJobMissionRewards/VenusTierCTableARewards", + "masteryReq":2,"minEnemyLevel":20,"maxEnemyLevel":40,"xpAmounts":[600]}]} + ]}"#; + const REWARDS: &str = r#"{ + "/Lotus/Types/Game/MissionDecks/VenusJobMissionRewards/VenusTierBTableBRewards": [ + [{"type":"/Lotus/StoreItems/Types/Items/MiscItems/Cryotic","itemCount":100,"probability":0.5}], + [{"type":"/Lotus/StoreItems/Types/Items/MiscItems/Cryotic","itemCount":100,"probability":0.3}, + {"type":"/Lotus/StoreItems/Types/Items/MiscItems/CetusWispItem","itemCount":2,"probability":0.2}, + {"type":"/Lotus/StoreItems/Upgrades/Mods/FusionBundles/UncommonFusionBundle","itemCount":30,"probability":0.5}] + ], + "/Lotus/Types/Game/MissionDecks/VenusJobMissionRewards/VenusTierCTableARewards": [ + [{"type":"/Lotus/StoreItems/Types/PickUps/Credits/1500Credits","itemCount":1,"probability":1.0}] + ] + }"#; + const BOUNTIES: &str = r#"{ + "/Lotus/Types/Gameplay/Venus/Jobs/VenusIntelJobSpy": {"name":"/Lotus/Language/SolarisJobs/IntelJobSpyTitle"}, + "/Lotus/Types/Gameplay/Zariman/Jobs/Elsewhere": {"name":"/Lotus/Language/SolarisJobs/IntelJobSpyTitle"} + }"#; + const DICTIONARY: &str = + r#"{"/Lotus/Language/SolarisJobs/IntelJobSpyTitle":"FINANCIAL LIBERATION"}"#; + + fn catalog() -> Catalog { + let dictionary = Dictionary::from_json(DICTIONARY).unwrap(); + let tables = BountyTables::from_json(BOUNTIES, REWARDS, &dictionary).unwrap(); + Catalog::new( + GameData::from_json("[]", "[]", "[]") + .unwrap() + .with_bounty_tables(tables), + ) + } + + fn boards_at(filters: &[BountyAlertFilter], now_ms: i64) -> Vec { + let world = WorldState::parse(WORLD).unwrap(); + world_bounty_boards( + &world, + &catalog(), + &ItemTable::default(), + None, + filters, + at(now_ms), + ) + } + + fn boards(filters: &[BountyAlertFilter]) -> Vec { + boards_at(filters, 2000) + } + + fn filter(bounty: Option<&str>, reward: Option<&str>) -> BountyAlertFilter { + BountyAlertFilter { + bounty: bounty.map(str::to_owned), + reward: reward.map(str::to_owned), + } + } + + #[test] + fn named_boards_in_hub_order() { + let boards = boards(&[]); + let [spy, unlisted, other_rotation] = &boards[0].bounties[..] else { + panic!("three Solaris bounties expected"); + }; + let vault = &boards[1].bounties[0]; + + assert_eq!(boards[0].syndicate_tag, "SolarisSyndicate"); + assert_eq!(spy.name, "Financial Liberation"); + assert_eq!(spy.level_range, "10-30"); + assert_eq!(spy.payout, "2,160 Standing"); + assert_eq!(unlisted.name, "Unlisted"); + assert_eq!(unlisted.level_range, "100"); + assert_ne!(unlisted.key, spy.key); + assert_eq!(boards[0].reward_rotation, Some('B')); + assert_eq!(spy.reward_rotation, None); + assert_eq!(other_rotation.reward_rotation, Some('A')); + assert_eq!( + other_rotation.rewards[0].image_name.as_deref(), + Some("game/credits.png") + ); + assert_eq!(vault.name, "Isolation Vault"); + assert_eq!(vault.payout, "10 Mother Tokens"); + } + + #[test] + fn rewards_once_rarest_first_with_latest_stage_chance() { + let boards = boards(&[filter(None, Some(WISP))]); + let rewards: Vec<_> = boards[0].bounties[0] + .rewards + .iter() + .map(|reward| (reward.label.as_str(), reward.chance, reward.wanted)) + .collect(); + + assert_eq!( + rewards, + [ + ("2 x Cetus Wisp Item", 0.2, true), + ("100 x Cryotic", 0.3, false), + ("1,500 Endo", 0.5, false) + ] + ); + } + + #[test] + fn alerting_rows() { + let alerting = |filters: &[BountyAlertFilter]| -> Vec { + boards(filters) + .iter() + .flat_map(|board| &board.bounties) + .map(|bounty| bounty.alerting) + .collect() + }; + + assert_eq!(alerting(&[filter(None, None)]), [false; 4]); + assert_eq!( + alerting(&[filter(Some(SPY), None)]), + [true, false, false, false] + ); + assert_eq!( + alerting(&[filter(None, Some(WISP))]), + [true, true, false, false] + ); + assert_eq!( + alerting(&[filter(Some(SPY), Some(WISP))]), + [true, false, false, false] + ); + assert_eq!( + alerting(&[filter(Some("/Lotus/Other"), Some(WISP))]), + [false; 4] + ); + } + + #[test] + fn alerting_bounties_announced_once_per_rotation() { + let wisp = boards(&[filter(None, Some(WISP))]); + let mut announcer = BountyAnnouncer::default(); + let mut alerted = |first_poll, now_ms| -> Vec> { + announcer + .announce(&wisp, first_poll, at(now_ms)) + .into_iter() + .map(|event| match event { + CoreEvent::WorldBountyAlert { alert } => { + assert_eq!(alert.rewards, ["2 x Cetus Wisp Item"]); + alert.bounties + } + other => panic!("unexpected event {other:?}"), + }) + .collect() + }; + + assert_eq!( + alerted(false, 2000), + [["Financial Liberation (10-30)", "Unlisted (100)"]] + ); + assert!(alerted(false, 3000).is_empty()); + assert!(alerted(true, 12_000).is_empty()); + } + + #[test] + fn ownership_of_what_a_reward_builds() { + let catalog = fixtures::catalog(); + let items = ItemTable::build(&catalog); + let account = Account::new(fixtures::inventory_with(|_| {}), &catalog, &items); + let excalibur = catalog.item(fixtures::EXCALIBUR).unwrap(); + let part = excalibur + .components + .iter() + .flatten() + .find(|component| component.unique_name.ends_with("Component")) + .unwrap(); + let part = &part.unique_name.replace("Component", "Blueprint"); + let ownership = |account, item_type: &str| { + Holdings { + catalog: &catalog, + items: &items, + account, + } + .ownership(&items.resolve(item_type)) + }; + + assert_eq!( + ownership(Some(&account), part), + Some(WorldOfferOwnership::Mastered) + ); + assert_eq!(ownership(Some(&account), WISP), None); + assert_eq!(ownership(None, part), None); + } + + #[test] + fn alert_options_of_the_three_hubs() { + let options = bounty_alert_options(&catalog(), &ItemTable::default()); + let names = |options: &[BountyAlertOption]| -> Vec { + options.iter().map(|option| option.name.clone()).collect() + }; + + assert_eq!( + names(&options.bounties), + ["SolarisSyndicate: Financial Liberation"] + ); + assert_eq!( + names(&options.rewards), + [ + "1500 Credits", + "Cetus Wisp Item", + "Cryotic", + "Endo (50 per bundle)" + ] + ); + } +} diff --git a/crates/wf-core/src/events/engine.rs b/crates/wf-core/src/events/engine.rs index 0652594..95b49ab 100644 --- a/crates/wf-core/src/events/engine.rs +++ b/crates/wf-core/src/events/engine.rs @@ -7,6 +7,7 @@ use wf_worldstate::{ArbitrationForecast, ArbitrationTiers, WorldState, node_info use super::alerts::{AlertSettings, fissure_planet}; use super::arbitrations::{ARBITRATION_FORECAST_TRUSTED, ArbitrationOutlook}; +use super::bounties::BountyAnnouncer; use super::rewards::world_reward_alerts; use super::{CoreEvent, FissureInfo, InventorySummary}; use crate::catalog::DUCATS_ITEM; @@ -25,6 +26,7 @@ pub(crate) struct Engine { announced_fissures: HashMap>, announced_timers: HashMap>, announced_rewards: HashMap>, + pub(crate) bounties: BountyAnnouncer, announced_arbitrations: HashMap>, seen_channels: HashMap>, } @@ -73,6 +75,7 @@ impl Engine { announced_fissures: HashMap::new(), announced_timers: HashMap::new(), announced_rewards: HashMap::new(), + bounties: BountyAnnouncer::default(), announced_arbitrations: HashMap::new(), seen_channels: HashMap::new(), } @@ -82,6 +85,10 @@ impl Engine { self.settings = settings; } + pub fn first_world_poll(&self) -> bool { + !self.world_state_polled + } + pub fn settings(&self) -> &AlertSettings { &self.settings } @@ -114,7 +121,7 @@ impl Engine { now: DateTime, ) -> Vec { let mut events = Vec::new(); - let first_poll = !self.world_state_polled; + let first_poll = self.first_world_poll(); self.world_state_polled = true; for fissure in world.fissures(now) { let key = format!("{}@{}", fissure.node_id, fissure.expiry.timestamp()); diff --git a/crates/wf-core/src/events/mod.rs b/crates/wf-core/src/events/mod.rs index d9bb2c3..132757c 100644 --- a/crates/wf-core/src/events/mod.rs +++ b/crates/wf-core/src/events/mod.rs @@ -1,5 +1,6 @@ mod alerts; mod arbitrations; +mod bounties; mod engine; mod rewards; @@ -14,6 +15,11 @@ pub use arbitrations::{ ARBITRATION_FORECAST_TRUSTED, ArbitrationAlert, ArbitrationAlertFilter, ArbitrationAlertSettings, ArbitrationSchedule, ArbitrationSlot, }; +pub use bounties::{ + BountyAlertFilter, BountyAlertOption, BountyAlertOptions, WorldBounty, WorldBountyAlert, + WorldBountyBoard, WorldBountyReward, +}; +pub(crate) use bounties::{bounty_alert_options, world_bounty_boards}; pub(crate) use engine::{Engine, inventory_events}; pub(crate) use rewards::world_reward_alerts; pub use rewards::{ @@ -104,6 +110,9 @@ pub enum CoreEvent { WorldRewardAlert { reward: WorldRewardAlert, }, + WorldBountyAlert { + alert: WorldBountyAlert, + }, ArbitrationAlert { alert: ArbitrationAlert, }, @@ -131,6 +140,7 @@ impl CoreEvent { Self::NewConversation { .. } => "NewConversation", Self::FissureAlert { .. } => "FissureAlert", Self::WorldRewardAlert { .. } => "WorldRewardAlert", + Self::WorldBountyAlert { .. } => "WorldBountyAlert", Self::ArbitrationAlert { .. } => "ArbitrationAlert", Self::ArbitrationRunUpdated { .. } => "ArbitrationRunUpdated", Self::ArbitrationRunRecorded { .. } => "ArbitrationRunRecorded", diff --git a/crates/wf-core/src/events/rewards.rs b/crates/wf-core/src/events/rewards.rs index 692026c..0984856 100644 --- a/crates/wf-core/src/events/rewards.rs +++ b/crates/wf-core/src/events/rewards.rs @@ -164,13 +164,17 @@ fn requirement(offer: &WorldRewardOffer) -> Option { } } +pub(super) fn counted_label(count: i64, name: &str) -> String { + if count > 1 { + format!("{count} x {name}") + } else { + name.to_owned() + } +} + fn world_reward_alert(offer: WorldRewardOffer, items: &ItemTable) -> WorldRewardAlert { let record = items.resolve(&offer.item_type); - let label = if offer.count > 1 { - format!("{} x {}", offer.count, record.name) - } else { - record.name.clone() - }; + let label = counted_label(offer.count, &record.name); let location = offer .node_name .map(str::to_owned) diff --git a/crates/wf-core/src/facade.rs b/crates/wf-core/src/facade.rs index 45e2e2e..0bdb46e 100644 --- a/crates/wf-core/src/facade.rs +++ b/crates/wf-core/src/facade.rs @@ -23,7 +23,8 @@ use crate::ducatering::{self, Ducatering, DucateringFilter}; use crate::error::{CoreError, Result}; use crate::events::{ self, ARBITRATION_FORECAST_TRUSTED, AlertSettings, ArbitrationOutlook, ArbitrationSchedule, - CoreEvent, Engine, ScannedRewards, ScannedTrade, WorldRewardAlert, + BountyAlertOptions, CoreEvent, Engine, ScannedRewards, ScannedTrade, WorldBountyBoard, + WorldRewardAlert, }; use crate::export::{ExportBundle, export}; use crate::favourites::Favourites; @@ -325,6 +326,23 @@ impl Core { }) } + pub fn bounty_boards(&self, now: DateTime) -> Vec { + self.world.as_ref().map_or_else(Vec::new, |world| { + events::world_bounty_boards( + world, + &self.catalog, + &self.items, + self.account.as_ref(), + &self.engine.settings().bounty_filters, + now, + ) + }) + } + + pub fn bounty_alert_options(&self) -> BountyAlertOptions { + events::bounty_alert_options(&self.catalog, &self.items) + } + pub fn invasion_weapon_parts(&self) -> Vec<&ItemRecord> { self.items.invasion_weapon_parts() } @@ -337,8 +355,16 @@ impl Core { let mut events = match self.world.as_ref() { Some(world) => { let unmastered = unmastered(self.account.as_ref(), &self.catalog); - self.engine - .handle_world_state(world, &self.items, &unmastered, now) + let first_poll = self.engine.first_world_poll(); + let mut events = + self.engine + .handle_world_state(world, &self.items, &unmastered, now); + if self.engine.settings().bounty_notifications_enabled { + let boards = self.bounty_boards(now); + events.extend(self.engine.bounties.announce(&boards, first_poll, now)); + } + + events } None => Vec::new(), }; @@ -965,7 +991,9 @@ mod tests { use super::*; use crate::arbitration_runs::ArbitrationRunStatus; use crate::catalog::fixtures::{self, TRINITY_PRIME_SYSTEMS, at, scratch_dir, synced}; - use crate::events::{CyclePhase, FissureFilter, InventorySummary, TimerAlerts}; + use crate::events::{ + BountyAlertFilter, CyclePhase, FissureFilter, InventorySummary, TimerAlerts, + }; use crate::events::{ScannedRelicReward, ScannedTradeItem}; use crate::prices::FixedPrices; use crate::reset_checklist::{ResetChecklistProgress, ResetChecklistRowId}; @@ -1618,6 +1646,30 @@ mod tests { assert!(!foundry.timers.is_empty()); } + #[test] + fn bounty_alerts_when_enabled_after_the_first_poll() { + let mut core = core(); + let alerts = |core: &mut Core, enabled, job: &str| { + core.set_alert_settings(AlertSettings { + bounty_notifications_enabled: enabled, + bounty_filters: vec![BountyAlertFilter { + bounty: Some(format!("/Lotus/Types/Gameplay/Eidolon/Jobs/{job}")), + reward: None, + }], + ..AlertSettings::default() + }); + let world_state = WorldState::parse(fixtures::WORLD_STATE).expect("world state"); + core.ingest_world_state(world_state, at(1_788_807_069_000)) + .iter() + .filter(|event| matches!(event, CoreEvent::WorldBountyAlert { .. })) + .count() + }; + + assert_eq!(alerts(&mut core, true, "AssassinateBountyCap"), 0); + assert_eq!(alerts(&mut core, false, "AttritionBountyCap"), 0); + assert_eq!(alerts(&mut core, true, "AttritionBountyCap"), 1); + } + #[test] fn export_needs_inventory() { let mut core = core(); diff --git a/crates/wf-core/src/lib.rs b/crates/wf-core/src/lib.rs index e31ff61..04c19e6 100644 --- a/crates/wf-core/src/lib.rs +++ b/crates/wf-core/src/lib.rs @@ -47,10 +47,12 @@ pub use ducatering::{ pub use error::{CoreError, Result}; pub use events::{ ARBITRATION_FORECAST_TRUSTED, AlertSettings, ArbitrationAlert, ArbitrationAlertFilter, - ArbitrationAlertSettings, ArbitrationSchedule, ArbitrationSlot, CoreEvent, CyclePhase, - FissureFilter, FissureInfo, FissureSubtype, InventorySummary, ScannedRelicReward, - ScannedRewards, ScannedTrade, ScannedTradeItem, TimerAlerts, WorldRewardAlert, - WorldRewardAlertChoices, WorldRewardAlertGroup, WorldRewardAlertWeapons, tier_name, + ArbitrationAlertSettings, ArbitrationSchedule, ArbitrationSlot, BountyAlertFilter, + BountyAlertOption, BountyAlertOptions, CoreEvent, CyclePhase, FissureFilter, FissureInfo, + FissureSubtype, InventorySummary, ScannedRelicReward, ScannedRewards, ScannedTrade, + ScannedTradeItem, TimerAlerts, WorldBounty, WorldBountyAlert, WorldBountyBoard, + WorldBountyReward, WorldRewardAlert, WorldRewardAlertChoices, WorldRewardAlertGroup, + WorldRewardAlertWeapons, tier_name, }; pub use facade::{Core, RelicPlannerTab, StatsTab}; pub use favourites::Favourites; diff --git a/crates/wf-core/src/reset_checklist/tests.rs b/crates/wf-core/src/reset_checklist/tests.rs index e8b1a83..c11b835 100644 --- a/crates/wf-core/src/reset_checklist/tests.rs +++ b/crates/wf-core/src/reset_checklist/tests.rs @@ -490,7 +490,7 @@ fn trades_and_focus() { } #[test] -fn gifts_like_trades() { +fn gifts_remaining() { let with_gifts = |gifts: Option| { fixtures::inventory_with(|value| match gifts { Some(gifts) => value["GiftsRemaining"] = gifts.into(), @@ -500,7 +500,7 @@ fn gifts_like_trades() { }) }; - let tomorrow = tab_of(&with_gifts(Some(3)), synced_at() + TimeDelta::days(1)); + let tomorrow = tab_of(&with_gifts(Some(1337)), synced_at() + TimeDelta::days(1)); assert_eq!( progress(&with_gifts(Some(3)), ResetChecklistRowId::Gifts), @@ -513,6 +513,10 @@ fn gifts_like_trades() { row(&tomorrow, ResetChecklistRowId::Gifts).progress, ResetChecklistProgress::Remaining { left: 14, cap: 14 } ); + assert_eq!( + progress(&with_gifts(Some(1337)), ResetChecklistRowId::Gifts), + (ResetChecklistProgress::Unlimited, false) + ); assert_eq!( progress(&with_gifts(None), ResetChecklistRowId::Gifts), (ResetChecklistProgress::Unknown, false) diff --git a/crates/wf-core/src/reset_checklist/trackers.rs b/crates/wf-core/src/reset_checklist/trackers.rs index f0bee21..ac37a44 100644 --- a/crates/wf-core/src/reset_checklist/trackers.rs +++ b/crates/wf-core/src/reset_checklist/trackers.rs @@ -36,6 +36,7 @@ pub enum ResetChecklistProgress { left: u32, cap: u32, }, + Unlimited, YesNo, Manual { id: ResetChecklistManualRowId, @@ -77,6 +78,10 @@ impl Tracked { Self::new(ResetChecklistProgress::Remaining { left, cap }, left == 0) } + fn unlimited() -> Self { + Self::new(ResetChecklistProgress::Unlimited, false) + } + fn manual(id: ResetChecklistManualRowId, checked: bool) -> Self { Self::new(ResetChecklistProgress::Manual { id, checked }, checked) } @@ -216,11 +221,7 @@ impl InventoryTracker { Some(inventory.trades_remaining), daily_trade_cap(inventory), ), - Self::Gifts => remaining_today( - context, - inventory.gifts_remaining, - daily_trade_cap(inventory), - ), + Self::Gifts => gifts_today(context), Self::Focus => remaining_today( context, inventory.daily_focus, @@ -239,6 +240,16 @@ fn daily_trade_cap(inventory: &Inventory) -> u32 { inventory.player_level + founder_trades } +fn gifts_today(context: &ResetChecklistContext) -> Tracked { + let gifts = context.inventory.gifts_remaining; + let cap = daily_trade_cap(context.inventory); + if context.synced_today() && gifts.is_some_and(|left| left > cap) { + return Tracked::unlimited(); + } + + remaining_today(context, gifts, cap) +} + fn remaining_today(context: &ResetChecklistContext, left: Option, cap: u32) -> Tracked { left.map_or_else(Tracked::unknown, |left| { Tracked::remaining(left_today(context.synced_today(), left, cap), cap) diff --git a/crates/wf-data/src/bounty.rs b/crates/wf-data/src/bounty.rs new file mode 100644 index 0000000..84fdbbe --- /dev/null +++ b/crates/wf-data/src/bounty.rs @@ -0,0 +1,138 @@ +use std::collections::HashMap; + +use serde::Deserialize; + +use crate::dictionary::Dictionary; +use crate::error::{DataError, Result}; +use crate::markup::title_name; + +#[derive(Debug, Deserialize)] +struct RawBounty { + name: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BountyReward { + #[serde(rename = "type")] + pub store_item: String, + pub item_count: u32, + pub probability: f64, +} + +#[derive(Debug, Clone, Default)] +pub struct BountyTables { + names: HashMap, + reward_stages: HashMap>>, +} + +const BOUNTY_REWARD_DECKS: [&str; 3] = [ + "/Lotus/Types/Game/MissionDecks/EidolonJobMissionRewards/", + "/Lotus/Types/Game/MissionDecks/VenusJobMissionRewards/", + "/Lotus/Types/Game/MissionDecks/DeimosMissionRewards/", +]; + +fn is_bounty_reward_deck(deck: &str) -> bool { + BOUNTY_REWARD_DECKS + .iter() + .any(|directory| deck.starts_with(directory)) +} + +impl BountyTables { + pub const BOUNTIES_FILE: &str = "ExportBounties.json"; + pub const REWARDS_FILE: &str = "ExportRewards.json"; + + pub fn from_json(bounties: &str, rewards: &str, dictionary: &Dictionary) -> Result { + let bounties: HashMap = + serde_json::from_str(bounties).map_err(|source| DataError::Parse("bounty", source))?; + let decks: HashMap = serde_json::from_str(rewards) + .map_err(|source| DataError::Parse("reward deck", source))?; + + let names = bounties + .into_iter() + .filter_map(|(job_type, bounty)| { + Some((job_type, title_name(dictionary.get(&bounty.name)?))) + }) + .collect(); + let reward_stages = decks + .into_iter() + .filter(|(deck, _)| is_bounty_reward_deck(deck)) + .map(|(deck, stages)| Ok((deck, serde_json::from_value(stages)?))) + .collect::>() + .map_err(|source| DataError::Parse("bounty reward deck", source))?; + + Ok(Self { + names, + reward_stages, + }) + } + + pub fn name(&self, job_type: &str) -> Option<&str> { + self.names.get(job_type).map(String::as_str) + } + + pub fn names(&self) -> impl Iterator { + self.names + .iter() + .map(|(job_type, name)| (job_type.as_str(), name.as_str())) + } + + pub fn reward_stages(&self, reward_deck: &str) -> &[Vec] { + self.reward_stages + .get(reward_deck) + .map_or(&[], Vec::as_slice) + } + + pub fn rewards(&self) -> impl Iterator { + self.reward_stages.values().flatten().flatten() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const BOUNTIES: &str = r#"{ + "/Lotus/Types/Gameplay/Eidolon/Jobs/Narmer/AssassinateBountyAss": { + "name": "/Lotus/Language/Narmer/AssassinateBountyAssTitle" + }, + "/Lotus/Types/Gameplay/Eidolon/Jobs/Untranslated": {"name": "/Lotus/Language/Missing"} + }"#; + const REWARDS: &str = r#"{ + "/Lotus/Types/Game/MissionDecks/EidolonJobMissionRewards/TierATableBRewards": [ + [{"type": "/Lotus/StoreItems/Types/Items/MiscItems/Cryotic", "itemCount": 100, "probability": 0.2}] + ], + "/Lotus/Types/Game/MissionDecks/OrokinVoidRewards": [ + [{"type": "/Lotus/StoreItems/Types/Items/MiscItems/Cryotic", "itemCount": 100, "rarity": "COMMON"}] + ] + }"#; + const DICTIONARY: &str = + r#"{"/Lotus/Language/Narmer/AssassinateBountyAssTitle": "RISE AND FALL (NARMER)"}"#; + + fn tables() -> BountyTables { + let dictionary = Dictionary::from_json(DICTIONARY).unwrap(); + BountyTables::from_json(BOUNTIES, REWARDS, &dictionary).unwrap() + } + + #[test] + fn translated_names_only() { + let tables = tables(); + let names: Vec<_> = tables.names().collect(); + + assert_eq!( + names, + [( + "/Lotus/Types/Gameplay/Eidolon/Jobs/Narmer/AssassinateBountyAss", + "Rise And Fall (Narmer)" + )] + ); + } + + #[test] + fn bounty_decks_only() { + let tables = tables(); + let rewards: Vec<_> = tables.rewards().collect(); + + assert_eq!(rewards.len(), 1); + } +} diff --git a/crates/wf-data/src/cache.rs b/crates/wf-data/src/cache.rs index 9a48783..2e32ac8 100644 --- a/crates/wf-data/src/cache.rs +++ b/crates/wf-data/src/cache.rs @@ -1,10 +1,11 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; -use futures_util::future::{join, join5, try_join_all, try_join3}; +use futures_util::future::{join4, join5, try_join_all, try_join3}; use serde::{Deserialize, Serialize}; use tracing::warn; +use crate::bounty::BountyTables; use crate::dictionary::Dictionary; use crate::error::{DataError, Result}; use crate::game_data::GameData; @@ -68,13 +69,17 @@ impl CacheMeta { } } -pub async fn load_or_fetch(dir: &Path, client: &reqwest::Client) -> Result { - tokio::fs::create_dir_all(dir) - .await - .map_err(cache_io(dir))?; - let meta_path = dir.join("etag.json"); - let mut meta = read_meta(&meta_path).await; +struct ItemFiles { + items: Vec, + relics: String, + components: String, +} +async fn fetch_item_files( + dir: &Path, + client: &reqwest::Client, + meta: &mut CacheMeta, +) -> Result { let item_files: Vec = ITEM_CATEGORIES .iter() .map(|category| format!("{category}.json")) @@ -83,10 +88,10 @@ pub async fn load_or_fetch(dir: &Path, client: &reqwest::Client) -> Result Result Result { + tokio::fs::create_dir_all(dir) + .await + .map_err(cache_io(dir))?; + let meta_path = dir.join("etag.json"); + let mut meta = read_meta(&meta_path).await; + let files = fetch_item_files(dir, client, &mut meta).await?; + let fetch_export = + |file_name| fetch_or_use_cache(dir, PUBLIC_EXPORT_PLUS, file_name, client, &meta); + + let ( + (dictionary, nightwave_acts, syndicates, booster_packs, vendors), + regions, + bounties, + rewards, + ) = join4( join5( - fetch_or_use_cache(dir, PUBLIC_EXPORT_PLUS, DICTIONARY_FILE, client, &meta), - fetch_or_use_cache(dir, PUBLIC_EXPORT_PLUS, NIGHTWAVE_ACTS_FILE, client, &meta), - fetch_or_use_cache(dir, PUBLIC_EXPORT_PLUS, SYNDICATES_FILE, client, &meta), - fetch_or_use_cache(dir, PUBLIC_EXPORT_PLUS, BOOSTER_PACKS_FILE, client, &meta), - fetch_or_use_cache(dir, PUBLIC_EXPORT_PLUS, VENDORS_FILE, client, &meta), - ), - fetch_or_use_cache( - dir, - PUBLIC_EXPORT_PLUS, - StarChart::EXPORT_FILE, - client, - &meta, + fetch_export(DICTIONARY_FILE), + fetch_export(NIGHTWAVE_ACTS_FILE), + fetch_export(SYNDICATES_FILE), + fetch_export(BOOSTER_PACKS_FILE), + fetch_export(VENDORS_FILE), ), + fetch_export(StarChart::EXPORT_FILE), + fetch_export(BountyTables::BOUNTIES_FILE), + fetch_export(BountyTables::REWARDS_FILE), ) .await; let dictionary = parsed_or_default([(DICTIONARY_FILE, dictionary)], &mut meta, |[body]| { @@ -137,14 +160,24 @@ pub async fn load_or_fetch(dir: &Path, client: &reqwest::Client) -> Result, vosfor_packs: Vec, star_chart: StarChart, + bounty_tables: BountyTables, } impl GameData { @@ -135,6 +137,7 @@ impl GameData { syndicates: Vec::new(), vosfor_packs: Vec::new(), star_chart: StarChart::default(), + bounty_tables: BountyTables::default(), }) } @@ -178,6 +181,16 @@ impl GameData { &self.vosfor_packs } + #[must_use] + pub fn with_bounty_tables(mut self, bounty_tables: BountyTables) -> Self { + self.bounty_tables = bounty_tables; + self + } + + pub fn bounty_tables(&self) -> &BountyTables { + &self.bounty_tables + } + pub fn riven_data(&self) -> &RivenData { &self.riven_data } diff --git a/crates/wf-data/src/lib.rs b/crates/wf-data/src/lib.rs index 6480e23..7e57c63 100644 --- a/crates/wf-data/src/lib.rs +++ b/crates/wf-data/src/lib.rs @@ -1,3 +1,4 @@ +mod bounty; mod dictionary; mod embedded; mod error; @@ -16,6 +17,7 @@ mod vosfor_pack; #[cfg(feature = "fetch")] mod cache; +pub use bounty::{BountyReward, BountyTables}; pub use dictionary::Dictionary; pub use error::{DataError, Result}; pub use game_data::GameData; diff --git a/crates/wf-data/src/markup.rs b/crates/wf-data/src/markup.rs index 3561e71..77cfec2 100644 --- a/crates/wf-data/src/markup.rs +++ b/crates/wf-data/src/markup.rs @@ -12,6 +12,29 @@ pub(crate) fn without_markup(text: &str) -> String { plain } +pub(crate) fn title_name(text: &str) -> String { + if text.chars().any(char::is_lowercase) { + return text.to_owned(); + } + + text.split(' ') + .map(|word| { + let (lead, letters) = word.split_at(word.find(char::is_alphabetic).unwrap_or(0)); + let mut letters = letters.chars(); + letters.next().map_or_else( + || word.to_owned(), + |first| { + lead.chars() + .chain(first.to_uppercase()) + .chain(letters.flat_map(char::to_lowercase)) + .collect() + }, + ) + }) + .collect::>() + .join(" ") +} + #[cfg(test)] mod tests { use super::*; @@ -23,4 +46,14 @@ mod tests { "Kill |COUNT| Enemies with Toxin Damage." ); } + + #[test] + fn title_case_of_capitals() { + assert_eq!(title_name("CLEARANCE: AGNESIS"), "Clearance: Agnesis"); + assert_eq!(title_name("2-for-1"), "2-for-1"); + assert_eq!( + title_name("RISE AND FALL (NARMER)"), + "Rise And Fall (Narmer)" + ); + } } diff --git a/crates/wf-data/src/syndicate.rs b/crates/wf-data/src/syndicate.rs index ceb4132..2adf822 100644 --- a/crates/wf-data/src/syndicate.rs +++ b/crates/wf-data/src/syndicate.rs @@ -4,6 +4,7 @@ use serde::Deserialize; use crate::dictionary::Dictionary; use crate::error::{DataError, Result}; +use crate::markup::title_name; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] @@ -58,25 +59,6 @@ pub struct Syndicate { pub offers: Vec, } -fn title_name(text: &str) -> String { - if text.chars().any(char::is_lowercase) { - return text.to_owned(); - } - - text.split(' ') - .map(|word| { - let mut letters = word.chars(); - letters.next().map_or_default(|first| { - first - .to_uppercase() - .chain(letters.flat_map(char::to_lowercase)) - .collect::() - }) - }) - .collect::>() - .join(" ") -} - fn syndicate(tag: String, raw: RawSyndicate, dictionary: &Dictionary) -> Option { let mut titles = raw.titles; for title in &mut titles { @@ -156,8 +138,6 @@ mod tests { syndicate("VentKidsSyndicate").titles[2].name, "Proper Felon" ); - assert_eq!(title_name("CLEARANCE: AGNESIS"), "Clearance: Agnesis"); - assert_eq!(title_name("2-for-1"), "2-for-1"); } #[test] diff --git a/crates/wf-worldstate/src/bounty.rs b/crates/wf-worldstate/src/bounty.rs new file mode 100644 index 0000000..edbb0cb --- /dev/null +++ b/crates/wf-worldstate/src/bounty.rs @@ -0,0 +1,116 @@ +use chrono::{DateTime, Utc}; +use serde::Deserialize; + +use crate::syndicate::SyndicateMission; + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RawBountyJob { + job_type: Option, + rewards: String, + min_enemy_level: u32, + max_enemy_level: u32, + xp_amounts: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BountyKind { + Job(String), + IsolationVault, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Bounty { + pub kind: BountyKind, + pub reward_deck: String, + pub reward_rotation: Option, + pub levels: (u32, u32), + pub standing: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BountyBoard { + pub syndicate_tag: String, + pub expiry: DateTime, + pub bounties: Vec, +} + +fn reward_rotation(reward_deck: &str) -> Option { + let (_, letter) = reward_deck.strip_suffix("Rewards")?.rsplit_once("Table")?; + match letter.as_bytes() { + [letter @ b'A'..=b'Z'] => Some(char::from(*letter)), + _ => None, + } +} + +impl From<&RawBountyJob> for Bounty { + fn from(job: &RawBountyJob) -> Self { + Self { + kind: job + .job_type + .clone() + .map_or(BountyKind::IsolationVault, BountyKind::Job), + reward_rotation: reward_rotation(&job.rewards), + reward_deck: job.rewards.clone(), + levels: (job.min_enemy_level, job.max_enemy_level), + standing: job.xp_amounts.iter().sum(), + } + } +} + +pub fn bounty_boards(missions: &[SyndicateMission], now: DateTime) -> Vec { + missions + .iter() + .filter(|mission| !mission.jobs.is_empty() && mission.window.contains(now)) + .map(|mission| BountyBoard { + syndicate_tag: mission.tag.clone(), + expiry: mission.window.expiry.into(), + bounties: mission.jobs.iter().map(Bounty::from).collect(), + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rotation_letter_of_reward_deck() { + let deck = |name: &str| reward_rotation(&format!("/Lotus/Types/Game/MissionDecks/{name}")); + + assert_eq!( + deck("VenusJobMissionRewards/VenusTierATableBRewards"), + Some('B') + ); + assert_eq!( + deck("DeimosMissionRewards/VaultBountyTierCTableCRewards"), + Some('C') + ); + assert_eq!( + deck("EidolonJobMissionRewards/PlagueStarTableRewards"), + None + ); + assert_eq!( + deck("EidolonJobMissionRewards/PlagueStarTableSteelPathRewards"), + None + ); + } + + #[test] + fn vault_without_job_type() { + let job: RawBountyJob = serde_json::from_value(serde_json::json!({ + "rewards": "/Lotus/Types/Game/MissionDecks/DeimosMissionRewards/VaultBountyTierATableCRewards", + "masteryReq": 5, + "minEnemyLevel": 30, + "maxEnemyLevel": 40, + "xpAmounts": [2, 2, 2, 4], + "locationTag": "ChamberB", + "isVault": true + })) + .unwrap(); + let bounty = Bounty::from(&job); + + assert_eq!(bounty.kind, BountyKind::IsolationVault); + assert_eq!(bounty.standing, 10); + } +} diff --git a/crates/wf-worldstate/src/lib.rs b/crates/wf-worldstate/src/lib.rs index bfda9aa..0ee8b29 100644 --- a/crates/wf-worldstate/src/lib.rs +++ b/crates/wf-worldstate/src/lib.rs @@ -1,6 +1,7 @@ mod arbitration; mod archimedea; mod archon; +mod bounty; mod calendar; mod circuit; mod clan_vault; @@ -30,6 +31,7 @@ pub use arbitration::{ }; pub use archimedea::{ArchimedeaKind, ArchimedeaWeek}; pub use archon::{ArchonHunt, ArchonMission}; +pub use bounty::{Bounty, BountyBoard, BountyKind}; pub use calendar::CalendarSeason; pub use circuit::Circuit; pub use clan_vault::ClanVaultBonusWeek; @@ -180,6 +182,10 @@ impl WorldState { syndicate::syndicate_mission_sets(&self.raw.syndicate_missions, now) } + pub fn bounty_boards(&self, now: DateTime) -> Vec { + bounty::bounty_boards(&self.raw.syndicate_missions, now) + } + pub fn calendar_season(&self, now: DateTime) -> Option { calendar::current_calendar_season(&self.raw.known_calendar_seasons, now) } @@ -443,6 +449,15 @@ mod tests { assert!(sets.iter().all(|set| set.nodes.len() == 7)); } + #[test] + fn bounty_boards_while_their_rotation_runs() { + let state = WorldState::parse(FIXTURE).unwrap(); + let boards = state.bounty_boards(now()); + + assert_eq!(boards.len(), 3); + assert!(state.bounty_boards(boards[0].expiry).is_empty()); + } + #[test] fn calendar_season() { let state = WorldState::parse(FIXTURE).unwrap(); diff --git a/crates/wf-worldstate/src/syndicate.rs b/crates/wf-worldstate/src/syndicate.rs index e76836b..eda1c07 100644 --- a/crates/wf-worldstate/src/syndicate.rs +++ b/crates/wf-worldstate/src/syndicate.rs @@ -2,6 +2,7 @@ use chrono::{DateTime, Utc}; use serde::Deserialize; use wf_mongo::ObjectId; +use crate::bounty::RawBountyJob; use crate::window::Window; #[derive(Debug, Clone, Deserialize)] @@ -14,6 +15,8 @@ pub struct SyndicateMission { pub tag: String, #[serde(default)] pub nodes: Vec, + #[serde(default)] + pub jobs: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -63,6 +66,7 @@ pub(crate) mod fixtures { window: window(activation_ms, expiry_ms), tag: tag.to_owned(), nodes: nodes.iter().map(|&node| node.to_owned()).collect(), + jobs: Vec::new(), } } } diff --git a/specs/sse.schema.json b/specs/sse.schema.json index 2f1f0d0..36f2a68 100644 --- a/specs/sse.schema.json +++ b/specs/sse.schema.json @@ -157,6 +157,30 @@ "data" ] }, + { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "alert": { + "$ref": "#/$defs/WorldBountyAlert" + } + }, + "required": [ + "alert" + ] + }, + "event": { + "type": "string", + "const": "world_bounty_alert" + } + }, + "required": [ + "event", + "data" + ] + }, { "type": "object", "properties": { @@ -1177,6 +1201,18 @@ "cap" ] }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "unlimited" + } + }, + "required": [ + "kind" + ] + }, { "type": "object", "properties": { @@ -1366,6 +1402,41 @@ "unknown" ] }, + "WorldBountyAlert": { + "type": "object", + "properties": { + "bounties": { + "type": "array", + "items": { + "type": "string" + } + }, + "expiry": { + "type": "string", + "format": "date-time" + }, + "remaining_secs": { + "type": "integer", + "format": "int64" + }, + "rewards": { + "type": "array", + "items": { + "type": "string" + } + }, + "syndicate": { + "type": "string" + } + }, + "required": [ + "syndicate", + "bounties", + "rewards", + "expiry", + "remaining_secs" + ] + }, "WorldRewardAlert": { "type": "object", "properties": {