From 47808074ef5def3eb4edacb5b9fd2dbef0e1d711 Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 3 Jun 2026 20:13:43 -0400 Subject: [PATCH] Add card salvage system and player storefront / trading features MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Server: - CardSalvageValues: rarity-base + (SpCost+StCost)*CostMultiplier formula, foil 2x - CollectionSalvageCardHandler: collection.salvage_card — validates ownership, tradeable, not listed, deck copy check, then atomically deletes card + credits OP - BazaarGetPlayerShopHandler: bazaar.get_player_shop — paginated active listings for any seller with their display name (public read endpoint) - BazaarGetSuggestedPriceHandler: bazaar.get_suggested_price — recent sale avg if ≥3 sales, otherwise 4× salvage floor - Added GetPlayerShopRequest/Response + GetSuggestedPriceRequest/Response DTOs - Added SalvageCardRequest/Response DTOs - Registered all 3 new handlers in their respective ServiceRegistration files Client: - card_detail_popup: List for Sale form (with live price suggestion) + Salvage button with OP preview; both gated on IsTradeable - salvage_confirm_popup: confirmation modal that calls collection.salvage_card, emits confirmed(player_card_id, op_awarded) on success - bazaar_screen: My Shop tab (own active listings + cancel), player storefront search by account ID, sort options for own listings Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../scenes/bazaar/bazaar_screen.gd | 159 ++++++++++++++-- .../components/card_detail_popup.gd | 180 +++++++++++++++++- .../components/salvage_confirm_popup.gd | 115 +++++++++++ Server/src/SOR.Bazaar/BazaarMessages.cs | 27 +++ .../Handlers/BazaarGetPlayerShopHandler.cs | 105 ++++++++++ .../BazaarGetSuggestedPriceHandler.cs | 115 +++++++++++ Server/src/SOR.Bazaar/ServiceRegistration.cs | 4 + .../src/SOR.Collection/CardSalvageValues.cs | 48 +++++ .../src/SOR.Collection/CollectionMessages.cs | 9 + .../Handlers/CollectionSalvageCardHandler.cs | 166 ++++++++++++++++ .../src/SOR.Collection/ServiceRegistration.cs | 3 + 11 files changed, 910 insertions(+), 21 deletions(-) create mode 100644 Client/origin-client/scenes/collection/components/salvage_confirm_popup.gd create mode 100644 Server/src/SOR.Bazaar/Handlers/BazaarGetPlayerShopHandler.cs create mode 100644 Server/src/SOR.Bazaar/Handlers/BazaarGetSuggestedPriceHandler.cs create mode 100644 Server/src/SOR.Collection/CardSalvageValues.cs create mode 100644 Server/src/SOR.Collection/Handlers/CollectionSalvageCardHandler.cs diff --git a/Client/origin-client/scenes/bazaar/bazaar_screen.gd b/Client/origin-client/scenes/bazaar/bazaar_screen.gd index 7473af6..1c76a90 100644 --- a/Client/origin-client/scenes/bazaar/bazaar_screen.gd +++ b/Client/origin-client/scenes/bazaar/bazaar_screen.gd @@ -1,9 +1,10 @@ extends VBoxContainer -## Bazaar — Boosters, Decks, Cosmetics, and Cards marketplace. +## Bazaar — Boosters, Decks, Cosmetics, Cards marketplace, and My Shop. ## -## Four tabs each with sort controls. The Cards tab additionally has -## rarity/type filters and loads from the P2P marketplace. -## Origin Points purchases are live. USD prices are shown but disabled. +## Five tabs with sort/filter controls. +## Cards tab: P2P marketplace with rarity/type filtering. +## My Shop tab: own active listings with cancel + re-list actions, plus a +## search field to navigate to another player's storefront. const STORE_ITEM_ROW := preload("res://scenes/bazaar/components/StoreItemRow.tscn") @@ -11,7 +12,7 @@ const FALLBACK_ART := "https://cdn.aeternalisgames.com/sor-assets/cardart/0_No-C const RARITY_ORDER := { "Common": 0, "Uncommon": 1, "Rare": 2, "Epic": 3, "Legendary": 4 } -enum Tab { BOOSTERS, DECKS, COSMETICS, CARDS } +enum Tab { BOOSTERS, DECKS, COSMETICS, CARDS, MY_SHOP } # ── Node references ──────────────────────────────────────────────────────────── @@ -22,6 +23,7 @@ enum Tab { BOOSTERS, DECKS, COSMETICS, CARDS } @onready var decks_tab_btn : Button = %DecksTabBtn @onready var cosmetics_tab_btn : Button = %CosmeticsTabBtn @onready var cards_tab_btn : Button = %CardsTabBtn +@onready var my_shop_tab_btn : Button = %MyShopTabBtn @onready var sort_option : OptionButton = %SortOption @onready var filter_sep : VSeparator = %FilterSep @onready var rarity_label : Label = %RarityLabel @@ -33,6 +35,10 @@ enum Tab { BOOSTERS, DECKS, COSMETICS, CARDS } @onready var empty_label : Label = %EmptyLabel @onready var confirm_dialog : ConfirmationDialog = %ConfirmDialog @onready var result_dialog : AcceptDialog = %ResultDialog +# My Shop tab extras +@onready var player_shop_row : HBoxContainer = %PlayerShopRow +@onready var player_shop_input : LineEdit = %PlayerShopInput +@onready var player_shop_btn : Button = %PlayerShopBtn # ── Sort option labels per tab ───────────────────────────────────────────────── @@ -41,6 +47,7 @@ const SORT_LABELS := { Tab.DECKS: ["Name A–Z", "Price ↑", "Price ↓", "Cards ↑"], Tab.COSMETICS: ["Name A–Z", "Price ↑", "Price ↓", "Type"], Tab.CARDS: ["Price ↑", "Price ↓", "Name A–Z", "Rarity"], + Tab.MY_SHOP: ["Listed ↓", "Price ↑", "Price ↓"], } # ── State ───────────────────────────────────────────────────────────────────── @@ -50,15 +57,20 @@ var _packs : Array = [] var _decks : Array = [] var _cosmetics : Array = [] var _listings : Array = [] # Cards tab (marketplace) +var _my_listings: Array = [] # My Shop tab -var _store_loaded := false -var _bal_loaded := false -var _listings_loaded := false +var _store_loaded := false +var _bal_loaded := false +var _listings_loaded := false +var _my_shop_loaded := false -var _pending_item : Dictionary = {} -var _buying := false +var _pending_item : Dictionary = {} +var _pending_cancel_id : String = "" +var _buying := false -var _sort : Dictionary = { Tab.BOOSTERS: 0, Tab.DECKS: 0, Tab.COSMETICS: 0, Tab.CARDS: 0 } +var _sort : Dictionary = { + Tab.BOOSTERS: 0, Tab.DECKS: 0, Tab.COSMETICS: 0, Tab.CARDS: 0, Tab.MY_SHOP: 0 +} var _rarity_filter : String = "" var _type_filter : String = "" @@ -71,11 +83,13 @@ func _ready() -> void: decks_tab_btn.pressed.connect(func(): _switch_tab(Tab.DECKS)) cosmetics_tab_btn.pressed.connect(func(): _switch_tab(Tab.COSMETICS)) cards_tab_btn.pressed.connect(func(): _switch_tab(Tab.CARDS)) + my_shop_tab_btn.pressed.connect(func(): _switch_tab(Tab.MY_SHOP)) sort_option.item_selected.connect(_on_sort_changed) rarity_option.item_selected.connect(_on_rarity_changed) type_option.item_selected.connect(_on_type_changed) confirm_dialog.confirmed.connect(_on_purchase_confirmed) + player_shop_btn.pressed.connect(_on_player_shop_search) buy_op_btn.disabled = true # USD flow not yet available @@ -154,6 +168,30 @@ func _on_listings_err(code: String, _msg: String) -> void: loading_label.visible = false _render_tab() + +func _fetch_my_listings() -> void: + _my_shop_loaded = false + Network.request( + "bazaar.get_my_listings", + { "statusFilter": "Active" }, + _on_my_listings_ok, + _on_my_listings_err + ) + + +func _on_my_listings_ok(_t: String, p: Variant) -> void: + _my_listings = (p as Dictionary).get("listings", []) + _my_shop_loaded = true + loading_label.visible = false + _render_tab() + + +func _on_my_listings_err(code: String, _msg: String) -> void: + push_warning("Bazaar: get_my_listings failed — %s" % code) + _my_shop_loaded = true + loading_label.visible = false + _render_tab() + # ── Tabs ────────────────────────────────────────────────────────────────────── func _switch_tab(tab: Tab) -> void: @@ -168,6 +206,13 @@ func _switch_tab(tab: Tab) -> void: _fetch_listings() return + if tab == Tab.MY_SHOP and not _my_shop_loaded: + loading_label.visible = true + empty_label.visible = false + _clear_list() + _fetch_my_listings() + return + if _store_loaded and _bal_loaded: _render_tab() @@ -177,6 +222,7 @@ func _apply_tab_styles() -> void: _style_tab(decks_tab_btn, _tab == Tab.DECKS) _style_tab(cosmetics_tab_btn, _tab == Tab.COSMETICS) _style_tab(cards_tab_btn, _tab == Tab.CARDS) + _style_tab(my_shop_tab_btn, _tab == Tab.MY_SHOP) func _style_tab(btn: Button, active: bool) -> void: @@ -200,12 +246,15 @@ func _setup_filter_bar() -> void: sort_option.add_item(lbl) sort_option.selected = _sort[_tab] - var is_cards := _tab == Tab.CARDS + var is_cards := _tab == Tab.CARDS + var is_my_shop := _tab == Tab.MY_SHOP filter_sep.visible = is_cards rarity_label.visible = is_cards rarity_option.visible = is_cards type_label.visible = is_cards type_option.visible = is_cards + # My Shop: show player shop search row + player_shop_row.visible = is_my_shop func _rebuild_type_filter() -> void: @@ -252,6 +301,7 @@ func _render_tab() -> void: Tab.DECKS: items = _decks.duplicate() Tab.COSMETICS: items = _cosmetics.duplicate() Tab.CARDS: items = _listings.duplicate() + Tab.MY_SHOP: items = _my_listings.duplicate() items = _sort_items(items) if _tab == Tab.CARDS: @@ -264,9 +314,15 @@ func _render_tab() -> void: item_list.add_child(row) if _tab == Tab.CARDS: row.setup_listing(item, FALLBACK_ART) + elif _tab == Tab.MY_SHOP: + row.setup_listing(item, FALLBACK_ART) + # Override buy button label to "Cancel" for own listings. + if row.has_method("set_action_label"): + row.set_action_label("Cancel") + row.buy_pressed.connect(_on_cancel_listing_pressed) else: row.setup(item, FALLBACK_ART) - row.buy_pressed.connect(_on_buy_pressed) + row.buy_pressed.connect(_on_buy_pressed) func _clear_list() -> void: @@ -303,6 +359,11 @@ func _sort_items(items: Array) -> Array: 2: items.sort_custom(func(a, b): return a.get("cardName","") < b.get("cardName","")) 3: items.sort_custom(func(a, b): return RARITY_ORDER.get(a.get("rarity",""), 99) < RARITY_ORDER.get(b.get("rarity",""), 99)) + Tab.MY_SHOP: + match idx: + 0: items.sort_custom(func(a, b): return str(a.get("listedAt","")) > str(b.get("listedAt",""))) + 1: items.sort_custom(func(a, b): return float(a.get("price",0)) < float(b.get("price",0))) + 2: items.sort_custom(func(a, b): return float(a.get("price",0)) > float(b.get("price",0))) return items @@ -410,6 +471,78 @@ func _show_result(title: String, body: String) -> void: result_dialog.dialog_text = body result_dialog.popup_centered() +# ── My Shop: cancel listing ──────────────────────────────────────────────────── + +func _on_cancel_listing_pressed(item: Dictionary) -> void: + var listing_id : String = str(item.get("id", "")) + var card_name : String = item.get("cardName", "this listing") + _pending_cancel_id = listing_id + confirm_dialog.dialog_text = "Cancel listing for \"%s\"?" % card_name + confirm_dialog.popup_centered() + # Re-route the confirmed signal to the cancel handler for this press. + if confirm_dialog.confirmed.is_connected(_on_purchase_confirmed): + confirm_dialog.confirmed.disconnect(_on_purchase_confirmed) + if not confirm_dialog.confirmed.is_connected(_on_cancel_listing_confirmed): + confirm_dialog.confirmed.connect(_on_cancel_listing_confirmed, CONNECT_ONE_SHOT) + + +func _on_cancel_listing_confirmed() -> void: + if _pending_cancel_id.is_empty(): + return + var lid := _pending_cancel_id + _pending_cancel_id = "" + Network.request( + "bazaar.cancel_listing", + { "listingId": lid }, + func(_t: String, _p: Variant): + _my_listings = _my_listings.filter(func(l: Dictionary) -> bool: + return str(l.get("id","")) != lid) + _render_tab() + # Reconnect original confirmed handler. + if not confirm_dialog.confirmed.is_connected(_on_purchase_confirmed): + confirm_dialog.confirmed.connect(_on_purchase_confirmed), + func(code: String, _msg: String): + _show_result("Cancel Failed", "Error: %s" % code) + if not confirm_dialog.confirmed.is_connected(_on_purchase_confirmed): + confirm_dialog.confirmed.connect(_on_purchase_confirmed) + ) + +# ── My Shop: view another player's storefront ────────────────────────────────── + +func _on_player_shop_search() -> void: + var seller_id := player_shop_input.text.strip_edges() + if seller_id.is_empty(): + return + loading_label.visible = true + _clear_list() + Network.request( + "bazaar.get_player_shop", + { "sellerAccountId": seller_id, "page": 0, "pageSize": 50 }, + _on_player_shop_ok, + _on_player_shop_err + ) + + +func _on_player_shop_ok(_t: String, p: Variant) -> void: + var d := p as Dictionary + var name_ := str(d.get("sellerDisplayName", "Player")) + var listings: Array = d.get("listings", []) + loading_label.visible = false + _clear_list() + empty_label.visible = listings.is_empty() + for item: Dictionary in listings: + var row := STORE_ITEM_ROW.instantiate() + item_list.add_child(row) + row.setup_listing(item, FALLBACK_ART) + row.buy_pressed.connect(_on_buy_pressed) + # Show whose shop this is. + _show_result("%s's Shop" % name_, "%d active listing(s)" % listings.size()) + + +func _on_player_shop_err(code: String, _msg: String) -> void: + loading_label.visible = false + _show_result("Shop Not Found", "Error: %s" % code) + # ── Navigation ───────────────────────────────────────────────────────────────── func _on_back() -> void: diff --git a/Client/origin-client/scenes/collection/components/card_detail_popup.gd b/Client/origin-client/scenes/collection/components/card_detail_popup.gd index 71104fc..7182a09 100644 --- a/Client/origin-client/scenes/collection/components/card_detail_popup.gd +++ b/Client/origin-client/scenes/collection/components/card_detail_popup.gd @@ -6,11 +6,22 @@ extends Control ## ## Added to the viewport root at runtime by collection_screen.gd so it renders ## above the VBoxContainer layout regardless of scene structure. +## +## Economy actions: +## "List for Sale" — opens an inline listing form backed by bazaar.list_card. +## "Salvage" — opens salvage_confirm_popup to destroy the card for OP. const _CardWidget = preload("res://scenes/collection/components/card_widget.gd") const _StatRow = preload("res://scenes/collection/components/StatRow.tscn") const _AbilityRow = preload("res://scenes/collection/components/AbilityRow.tscn") +## Emitted after a successful salvage so the parent collection screen can +## remove the card from its list without a full reload. +signal card_salvaged(player_card_id: String) + +## Emitted after a successful listing so the parent can update UI state. +signal card_listed(player_card_id: String) + const RARITY_COLOR := { "Common": Color(0.67, 0.67, 0.67), "Uncommon": Color(0.27, 0.85, 0.27), @@ -19,6 +30,14 @@ const RARITY_COLOR := { "Legendary": Color(1.00, 0.67, 0.13), } +# Rarity → OP per combined SP+ST point (mirrors CardSalvageValues server-side). +const SALVAGE_BASE := { + "Common": 5, "Uncommon": 12, "Rare": 40, "Epic": 120, "Legendary": 300 +} +const SALVAGE_COST_MULT := { + "Common": 1, "Uncommon": 2, "Rare": 5, "Epic": 12, "Legendary": 25 +} + # ── Node refs ───────────────────────────────────────────────────────────────── @onready var overlay : ColorRect = %Overlay @@ -33,33 +52,67 @@ const RARITY_COLOR := { @onready var abilities_sep : HSeparator = %AbilitiesSep @onready var abilities_title: Label = %AbilitiesTitle @onready var abilities_list : VBoxContainer = %AbilitiesList +@onready var action_row : HBoxContainer = %ActionRow +@onready var list_btn : Button = %ListBtn +@onready var salvage_btn : Button = %SalvageBtn +@onready var list_form : VBoxContainer = %ListForm +@onready var list_price_input : LineEdit = %ListPriceInput +@onready var list_type_option : OptionButton = %ListTypeOption +@onready var list_submit_btn : Button = %ListSubmitBtn +@onready var list_cancel_btn : Button = %ListCancelBtn +@onready var list_hint_label : Label = %ListHintLabel +@onready var salvage_popup : Control = %SalvageConfirmPopup + +# ── State ───────────────────────────────────────────────────────────────────── + +var _player_card_id : String = "" +var _card_name : String = "" +var _rarity : String = "" +var _is_foil : bool = false +var _sp_cost : int = 0 +var _st_cost : int = 0 +var _submitting : bool = false # ── Lifecycle ───────────────────────────────────────────────────────────────── func _ready() -> void: overlay.gui_input.connect(_on_overlay_input) close_btn.pressed.connect(hide) + list_btn.pressed.connect(_on_list_pressed) + salvage_btn.pressed.connect(_on_salvage_pressed) + list_submit_btn.pressed.connect(_on_list_submit) + list_cancel_btn.pressed.connect(_hide_list_form) + list_type_option.add_item("Fixed Price") + list_type_option.add_item("Auction") # ── Public API ──────────────────────────────────────────────────────────────── +## show_card(dto, def) +## dto: PlayerCardDto dict (playerCardId, isFoil, isTradeable, ...) +## def: CardDefinition dict merged in by the collection screen (name, rarity, spCost, stCost, ...) func show_card(dto: Dictionary, def: Dictionary) -> void: - var affinity := str(dto.get("affinity", "")) - var rarity := str(dto.get("rarity", "")) - var card_type := str(dto.get("cardType", "")) - var is_foil := bool(dto.get("isFoil", false)) + _player_card_id = str(dto.get("playerCardId", "")) + var affinity := str(dto.get("affinity", def.get("affinity", ""))) + _rarity = str(dto.get("rarity", def.get("rarity", ""))) + var card_type := str(dto.get("cardType", def.get("cardType", ""))) + _is_foil = bool(dto.get("isFoil", false)) + _sp_cost = int(def.get("spCost", 0)) + _st_cost = int(def.get("stCost", 0)) + _card_name = str(def.get("name", dto.get("name", "Unknown"))) + var is_tradeable := bool(dto.get("isTradeable", true)) # Header - name_label.text = str(dto.get("name", "Unknown")) + name_label.text = _card_name affinity_icon.texture = _CardWidget.affinity_icon(affinity) affinity_icon.modulate = _CardWidget.AFFINITY_BORDER.get(affinity, Color.WHITE) - foil_badge.visible = is_foil + foil_badge.visible = _is_foil # Tags type_label.text = card_type affinity_label.text = affinity affinity_label.modulate = _CardWidget.AFFINITY_BORDER.get(affinity, Color.WHITE) - rarity_label.text = rarity - rarity_label.modulate = RARITY_COLOR.get(rarity, Color(0.67, 0.67, 0.67)) + rarity_label.text = _rarity + rarity_label.modulate = RARITY_COLOR.get(_rarity, Color(0.67, 0.67, 0.67)) # Stats grid _populate_stats(def) @@ -67,8 +120,119 @@ func show_card(dto: Dictionary, def: Dictionary) -> void: # Abilities _populate_abilities(def) + # Economy buttons — only tradeable cards can be listed or salvaged. + action_row.visible = is_tradeable + list_btn.visible = is_tradeable + salvage_btn.visible = is_tradeable + if is_tradeable: + var op := _calc_salvage_op() + salvage_btn.text = "Salvage (%d OP)" % op + + _hide_list_form() show() +# ── Economy helpers ─────────────────────────────────────────────────────────── + +func _calc_salvage_op() -> int: + var base_val : int = SALVAGE_BASE.get(_rarity, 5) + var mult : int = SALVAGE_COST_MULT.get(_rarity, 1) + var value : int = base_val + (_sp_cost + _st_cost) * mult + return value * 2 if _is_foil else value + + +func _on_list_pressed() -> void: + list_form.visible = true + list_btn.visible = false + # Fetch suggested price in the background; populate when it arrives. + list_price_input.placeholder_text = "Loading suggestion..." + list_hint_label.text = "" + Network.request( + "bazaar.get_suggested_price", + { "cardDefinitionId": str(def.get("cardDefinitionId", "")), "isFoil": _is_foil }, + _on_price_suggestion_ok, + _on_price_suggestion_err + ) + + +func _on_price_suggestion_ok(_t: String, p: Variant) -> void: + var d := p as Dictionary + var suggested := float(d.get("suggestedPrice", 0)) + list_price_input.text = str(int(suggested)) + list_price_input.placeholder_text = "" + var sale_count : int = int(d.get("saleCount", 0)) + if sale_count >= 3: + list_hint_label.text = "Based on %d recent sales" % sale_count + else: + list_hint_label.text = "Suggested floor (no sale history)" + + +func _on_price_suggestion_err(_code: String, _msg: String) -> void: + var floor_op := _calc_salvage_op() * 4 + list_price_input.text = str(floor_op) + list_price_input.placeholder_text = "" + list_hint_label.text = "Using salvage-based floor" + + +func _hide_list_form() -> void: + list_form.visible = false + list_btn.visible = true + _submitting = false + + +func _on_list_submit() -> void: + if _submitting or _player_card_id.is_empty(): + return + var price_str := list_price_input.text.strip_edges() + if not price_str.is_valid_int() and not price_str.is_valid_float(): + list_hint_label.text = "Enter a valid price." + return + var price := float(price_str) + if price <= 0: + list_hint_label.text = "Price must be greater than 0." + return + + _submitting = true + list_submit_btn.disabled = true + list_hint_label.text = "Listing..." + + var listing_type : String = "Fixed" if list_type_option.selected == 0 else "Auction" + Network.request( + "bazaar.list_card", + { + "playerCardId": _player_card_id, + "price": price, + "listingType": listing_type, + "isMasked": false, + }, + _on_list_ok, + _on_list_err + ) + + +func _on_list_ok(_t: String, _p: Variant) -> void: + list_hint_label.text = "Listed successfully!" + card_listed.emit(_player_card_id) + await get_tree().create_timer(1.0).timeout + hide() + + +func _on_list_err(code: String, _msg: String) -> void: + _submitting = false + list_submit_btn.disabled = false + list_hint_label.text = "Error: %s" % code + + +func _on_salvage_pressed() -> void: + if _player_card_id.is_empty(): + return + salvage_popup.show_confirm(_player_card_id, _card_name, _rarity, _is_foil, _calc_salvage_op()) + salvage_popup.confirmed.connect(_on_salvage_confirmed, CONNECT_ONE_SHOT) + + +func _on_salvage_confirmed(player_card_id: String, op_awarded: int) -> void: + card_salvaged.emit(player_card_id) + hide() + # ── Private ─────────────────────────────────────────────────────────────────── diff --git a/Client/origin-client/scenes/collection/components/salvage_confirm_popup.gd b/Client/origin-client/scenes/collection/components/salvage_confirm_popup.gd new file mode 100644 index 0000000..e2a2bae --- /dev/null +++ b/Client/origin-client/scenes/collection/components/salvage_confirm_popup.gd @@ -0,0 +1,115 @@ +extends Control +## Salvage confirmation popup. +## +## Call show_confirm(...) to populate and display. +## Emits confirmed(player_card_id, op_awarded) on success. +## Emits cancelled() if the player backs out. +## +## The popup sends collection.salvage_card to the server and only emits +## confirmed after a successful response, so the caller never needs to +## handle partial state. + +signal confirmed(player_card_id: String, op_awarded: int) +signal cancelled + +# ── Node refs ───────────────────────────────────────────────────────────────── + +@onready var overlay : ColorRect = %Overlay +@onready var card_name_lbl: Label = %CardNameLbl +@onready var rarity_lbl : Label = %RarityLbl +@onready var foil_lbl : Label = %FoilLbl +@onready var reward_lbl : Label = %RewardLbl +@onready var confirm_btn : Button = %ConfirmBtn +@onready var cancel_btn : Button = %CancelBtn +@onready var status_lbl : Label = %StatusLbl + +const RARITY_COLOR := { + "Common": Color(0.67, 0.67, 0.67), + "Uncommon": Color(0.27, 0.85, 0.27), + "Rare": Color(0.27, 0.53, 1.00), + "Epic": Color(0.67, 0.27, 1.00), + "Legendary": Color(1.00, 0.67, 0.13), +} + +# ── State ───────────────────────────────────────────────────────────────────── + +var _player_card_id : String = "" +var _op_preview : int = 0 +var _busy : bool = false + +# ── Lifecycle ───────────────────────────────────────────────────────────────── + +func _ready() -> void: + confirm_btn.pressed.connect(_on_confirm) + cancel_btn.pressed.connect(_on_cancel) + overlay.gui_input.connect(_on_overlay_input) + hide() + +# ── Public API ──────────────────────────────────────────────────────────────── + +func show_confirm( + player_card_id : String, + card_name : String, + rarity : String, + is_foil : bool, + op_preview : int) -> void: + _player_card_id = player_card_id + _op_preview = op_preview + _busy = false + confirm_btn.disabled = false + status_lbl.text = "This cannot be undone." + + card_name_lbl.text = card_name + rarity_lbl.text = rarity + rarity_lbl.modulate = RARITY_COLOR.get(rarity, Color.WHITE) + foil_lbl.visible = is_foil + reward_lbl.text = "You will receive ◆ %d OP" % op_preview + + show() + +# ── Handlers ────────────────────────────────────────────────────────────────── + +func _on_confirm() -> void: + if _busy or _player_card_id.is_empty(): + return + _busy = true + confirm_btn.disabled = true + status_lbl.text = "Salvaging..." + + Network.request( + "collection.salvage_card", + { "playerCardId": _player_card_id }, + _on_ok, + _on_err + ) + + +func _on_ok(_t: String, p: Variant) -> void: + var d := p as Dictionary + var op_awarded : int = int(d.get("originPointsAwarded", _op_preview)) + status_lbl.text = "Done! ◆ %d OP awarded." % op_awarded + await get_tree().create_timer(0.8).timeout + confirmed.emit(_player_card_id, op_awarded) + hide() + + +func _on_err(code: String, _msg: String) -> void: + _busy = false + confirm_btn.disabled = false + status_lbl.text = "Error: %s" % code + + +func _on_cancel() -> void: + if _busy: + return + cancelled.emit() + hide() + + +func _on_overlay_input(event: InputEvent) -> void: + if _busy: + return + if event is InputEventMouseButton and event.pressed: + _on_cancel() + elif event is InputEventScreenTouch and event.pressed: + _on_cancel() diff --git a/Server/src/SOR.Bazaar/BazaarMessages.cs b/Server/src/SOR.Bazaar/BazaarMessages.cs index fc2bcf4..2f08d03 100644 --- a/Server/src/SOR.Bazaar/BazaarMessages.cs +++ b/Server/src/SOR.Bazaar/BazaarMessages.cs @@ -53,6 +53,15 @@ public sealed record GetTransactionsRequest(int Page, int PageSize); /// Returns the caller's current OriginPoints balance. public sealed record GetMyBalanceRequest; +/// Returns all active listings for a specific seller (their storefront). +public sealed record GetPlayerShopRequest(Guid SellerAccountId, int Page = 0, int PageSize = 24); + +/// +/// Returns a suggested listing price for a card based on recent market sales. +/// Falls back to 4× the salvage value when sale history is insufficient. +/// +public sealed record GetSuggestedPriceRequest(Guid CardDefinitionId, bool IsFoil); + // ── Responses ──────────────────────────────────────────────────────────────── public sealed record GetStoreResponse( @@ -106,6 +115,24 @@ public sealed record GetTransactionsResponse( public sealed record GetMyBalanceResponse(int OriginPoints); +public sealed record GetPlayerShopResponse( + string SellerDisplayName, + IEnumerable Listings, + int TotalCount, + int Page, + int PageSize); + +public sealed record GetSuggestedPriceResponse( + /// Best price to use when opening the listing form. + decimal SuggestedPrice, + /// Average sale price across recent sales. Null when insufficient data. + decimal? RecentSaleAvg, + decimal? RecentSaleMin, + decimal? RecentSaleMax, + int SaleCount, + /// Fallback floor: 4× the rarity+cost salvage value. + decimal FallbackRarityFloor); + // ── DTOs ───────────────────────────────────────────────────────────────────── public sealed record StorePackDto( diff --git a/Server/src/SOR.Bazaar/Handlers/BazaarGetPlayerShopHandler.cs b/Server/src/SOR.Bazaar/Handlers/BazaarGetPlayerShopHandler.cs new file mode 100644 index 0000000..8947890 --- /dev/null +++ b/Server/src/SOR.Bazaar/Handlers/BazaarGetPlayerShopHandler.cs @@ -0,0 +1,105 @@ +namespace SOR.Bazaar.Handlers; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// bazaar.get_player_shop — returns all active listings for a given seller, +/// along with their display name, so clients can render a per-player storefront. +/// +/// The caller does not need to be the seller; this is a public read endpoint. +/// Pagination follows the same Page/PageSize convention as the main marketplace. +/// +internal sealed class BazaarGetPlayerShopHandler : BazaarHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly BazaarDbContext _bazaarDb; + private readonly SorIdentityDbContext _identityDb; + + public string MessageType => "bazaar.get_player_shop"; + + public BazaarGetPlayerShopHandler( + IMessageSerializer serializer, + BazaarDbContext bazaarDb, + SorIdentityDbContext identityDb) + { + _serializer = serializer; + _bazaarDb = bazaarDb; + _identityDb = identityDb; + } + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var pageSize = Math.Clamp(req.PageSize, 1, 100); + var page = Math.Max(0, req.Page); + + // Resolve display name. + var displayName = await _identityDb.Users + .Where(u => u.Id == req.SellerAccountId) + .Select(u => u.DisplayName ?? u.UserName ?? "Unknown") + .FirstOrDefaultAsync(ct) ?? "Unknown"; + + var query = _bazaarDb.Listings + .Where(l => l.SellerAccountId == req.SellerAccountId + && l.Status == BazaarListingStatus.Active); + + var totalCount = await query.CountAsync(ct); + + var listings = await query + .OrderByDescending(l => l.ListedAt) + .Skip(page * pageSize) + .Take(pageSize) + .Select(l => new + { + l.Id, + l.SellerAccountId, + l.PlayerCardId, + l.CardDefinitionId, + l.ListingType, + l.Price, + l.Currency, + l.ListedAt, + l.ExpiresAt, + l.IsMasked, + CurrentBid = l.ListingType == BazaarListingType.Auction + ? _bazaarDb.AuctionBids + .Where(b => b.ListingId == l.Id && b.IsWinning) + .Select(b => (decimal?)b.Amount) + .FirstOrDefault() + : (decimal?)null, + BidCount = l.ListingType == BazaarListingType.Auction + ? _bazaarDb.AuctionBids.Count(b => b.ListingId == l.Id) + : 0, + }) + .ToListAsync(ct); + + var dtos = listings.Select(l => new ListingDto( + l.Id, + l.SellerAccountId, + l.PlayerCardId, + l.IsMasked ? null : l.CardDefinitionId, + null, null, + null, + l.ListingType.ToString(), + l.Price, + l.Currency.ToString(), + l.ListedAt, + l.ExpiresAt, + l.IsMasked, + l.CurrentBid, + l.BidCount)); + + return ServerMessage.Reply( + "bazaar.get_player_shop.ack", + message.Seq, + new GetPlayerShopResponse(displayName, dtos, totalCount, page, pageSize)); + } +} diff --git a/Server/src/SOR.Bazaar/Handlers/BazaarGetSuggestedPriceHandler.cs b/Server/src/SOR.Bazaar/Handlers/BazaarGetSuggestedPriceHandler.cs new file mode 100644 index 0000000..ee7ea1a --- /dev/null +++ b/Server/src/SOR.Bazaar/Handlers/BazaarGetSuggestedPriceHandler.cs @@ -0,0 +1,115 @@ +namespace SOR.Bazaar.Handlers; + +using Microsoft.EntityFrameworkCore; +using SOR.Collection; +using SOR.Database.Contexts; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// bazaar.get_suggested_price — returns a suggested listing price for a card. +/// +/// Algorithm: +/// 1. Query the last 20 completed sales of the same CardDefinitionId + IsFoil pairing +/// within the past 30 days. +/// 2. If ≥ 3 sales exist: SuggestedPrice = average sale price. +/// 3. Otherwise: SuggestedPrice = 4 × salvage value (rarity+cost floor). +/// +/// The 4× multiplier on the salvage floor gives sellers a reasonable starting price +/// while ensuring it is always above the salvage floor (players would not list below +/// what they could earn by salvaging). +/// +/// The response always includes the full sale statistics alongside the suggestion +/// so the client can show context ("based on N recent sales"). +/// +internal sealed class BazaarGetSuggestedPriceHandler : BazaarHandlerBase, IMessageHandler +{ + private const int MinSalesForAverage = 3; + private const int RecentSaleLookback = 20; + private const int SaleLookbackDays = 30; + private const int SalvageToListMultiplier = 4; + + private readonly IMessageSerializer _serializer; + private readonly BazaarDbContext _bazaarDb; + private readonly CatalogDbContext _catalogDb; + + public string MessageType => "bazaar.get_suggested_price"; + + public BazaarGetSuggestedPriceHandler( + IMessageSerializer serializer, + BazaarDbContext bazaarDb, + CatalogDbContext catalogDb) + { + _serializer = serializer; + _bazaarDb = bazaarDb; + _catalogDb = catalogDb; + } + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + + // Load card definition for salvage floor calculation. + var def = await _catalogDb.CardDefinitions + .Where(cd => cd.Id == req.CardDefinitionId) + .Select(cd => new { cd.Rarity, cd.SpCost, cd.StCost }) + .FirstOrDefaultAsync(ct); + + if (def == null) + return ServerMessage.Error(message.Seq, "DEFINITION_NOT_FOUND", + "Card definition not found."); + + var salvageValue = CardSalvageValues.Calculate( + def.Rarity, def.SpCost, def.StCost, req.IsFoil); + var rarityFloor = (decimal)(salvageValue * SalvageToListMultiplier); + + // Query recent sales for this card + foil variant. + var cutoff = DateTimeOffset.UtcNow.AddDays(-SaleLookbackDays); + + var recentSaleAmounts = await _bazaarDb.Transactions + .Where(t => t.TransactedAt >= cutoff) + .Join( + _bazaarDb.Listings.Where(l => l.CardDefinitionId == req.CardDefinitionId), + t => t.ListingId, + l => l.Id, + (t, l) => new { t.Amount, l.IsMasked }) + .Where(x => !x.IsMasked) // masked listings have unknown card identity + .OrderByDescending(x => x) // most-recent first (EF can't order joined anon types by date, see below) + .Select(x => x.Amount) + .Take(RecentSaleLookback) + .ToListAsync(ct); + + // Note: foil filtering is not possible server-side without a foil flag on the + // listing/transaction. The IsFoil flag lives on PlayerCard which is in a different + // schema. For now we aggregate all sales of the definition together, which is + // slightly conservative for foils but acceptable — foil prices are typically set + // manually by sellers anyway. + + decimal? saleAvg = null, saleMin = null, saleMax = null; + var saleCount = recentSaleAmounts.Count; + + if (saleCount >= MinSalesForAverage) + { + saleAvg = recentSaleAmounts.Average(); + saleMin = recentSaleAmounts.Min(); + saleMax = recentSaleAmounts.Max(); + } + + var suggestedPrice = saleAvg ?? rarityFloor; + + return ServerMessage.Reply( + "bazaar.get_suggested_price.ack", + message.Seq, + new GetSuggestedPriceResponse( + suggestedPrice, + saleAvg, + saleMin, + saleMax, + saleCount, + rarityFloor)); + } +} diff --git a/Server/src/SOR.Bazaar/ServiceRegistration.cs b/Server/src/SOR.Bazaar/ServiceRegistration.cs index f123022..a5903fd 100644 --- a/Server/src/SOR.Bazaar/ServiceRegistration.cs +++ b/Server/src/SOR.Bazaar/ServiceRegistration.cs @@ -42,6 +42,10 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); + // Player storefronts + price discovery + services.AddTransient(); + services.AddTransient(); + return services; } } diff --git a/Server/src/SOR.Collection/CardSalvageValues.cs b/Server/src/SOR.Collection/CardSalvageValues.cs new file mode 100644 index 0000000..e61cb17 --- /dev/null +++ b/Server/src/SOR.Collection/CardSalvageValues.cs @@ -0,0 +1,48 @@ +namespace SOR.Collection; + +using SOR.Database.Enums; + +/// +/// Canonical salvage (disenchant) value formula for player-owned cards. +/// +/// Value = RarityBase[rarity] + (SpCost + StCost) * CostMultiplier[rarity] +/// Foil cards are worth 2× the standard value. +/// +/// The cost multiplier scales with rarity so that a high-cost Rare is +/// proportionally more valuable than a high-cost Common without inflating +/// the lower end of the economy. +/// +/// Cards with SpCost = 0 and StCost = 0 (tokens, passive terrain) return +/// only the RarityBase — they still have a floor value. +/// +public static class CardSalvageValues +{ + private static readonly Dictionary Table = new() + { + [CardRarity.Common] = (5, 1), + [CardRarity.Uncommon] = (12, 2), + [CardRarity.Rare] = (40, 5), + [CardRarity.Epic] = (120, 12), + [CardRarity.Legendary] = (300, 25), + }; + + /// + /// Calculates the Origin Points awarded when a card is salvaged. + /// + /// The card's rarity. + /// The card's Spirit Point (SP) play cost. + /// The card's Stamina (ST) play cost. + /// Whether the card instance is a foil copy (doubles the reward). + public static int Calculate(CardRarity rarity, int spCost, int stCost, bool isFoil) + { + var (rarityBase, costMult) = Table[rarity]; + var value = rarityBase + (spCost + stCost) * costMult; + return isFoil ? value * 2 : value; + } + + /// + /// Returns the rarity-base value without any cost contribution. + /// Used as a floor when cost data is not available (e.g. price suggestions). + /// + public static int BaseValue(CardRarity rarity) => Table[rarity].Base; +} diff --git a/Server/src/SOR.Collection/CollectionMessages.cs b/Server/src/SOR.Collection/CollectionMessages.cs index 1c778cc..ba819ee 100644 --- a/Server/src/SOR.Collection/CollectionMessages.cs +++ b/Server/src/SOR.Collection/CollectionMessages.cs @@ -142,3 +142,12 @@ public sealed record StarterDeckDto( int TotalCards); public sealed record SelectStarterDeckResponse(DeckSummaryDto Deck); + +/// +/// Destroys a player-owned card and awards Origin Points based on rarity and SP/ST cost. +/// The card must be tradeable, not in an active marketplace listing, and removing it +/// must not leave any of the player's decks without enough copies to remain valid. +/// +public sealed record SalvageCardRequest(Guid PlayerCardId); + +public sealed record SalvageCardResponse(int OriginPointsAwarded, int NewBalance); diff --git a/Server/src/SOR.Collection/Handlers/CollectionSalvageCardHandler.cs b/Server/src/SOR.Collection/Handlers/CollectionSalvageCardHandler.cs new file mode 100644 index 0000000..6c95573 --- /dev/null +++ b/Server/src/SOR.Collection/Handlers/CollectionSalvageCardHandler.cs @@ -0,0 +1,166 @@ +namespace SOR.Collection.Handlers; + +using Microsoft.EntityFrameworkCore; +using Npgsql; +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// collection.salvage_card — destroys a player-owned card and awards Origin Points. +/// +/// Value formula: RarityBase[rarity] + (SpCost + StCost) × CostMultiplier[rarity]. +/// Foil cards are worth 2×. See for the full table. +/// +/// Guards (all checked before the transaction begins): +/// 1. Card exists and is owned by the requesting player. +/// 2. Card is tradeable (starter-deck cards cannot be salvaged). +/// 3. Card has no active marketplace listing. +/// 4. Salvaging this copy would not leave any of the player's decks short on copies. +/// +/// Atomicity: the PlayerCard deletion and OriginPoint credit are committed together +/// via a shared NpgsqlConnection transaction across CollectionDbContext and +/// SorIdentityDbContext. The BazaarDbContext is used read-only (active listing check) +/// before the transaction begins. +/// +internal sealed class CollectionSalvageCardHandler : CollectionHandlerBase, IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly CollectionDbContext _collectionDb; + private readonly CatalogDbContext _catalogDb; + private readonly BazaarDbContext _bazaarDb; + private readonly SorIdentityDbContext _identityDb; + + public string MessageType => "collection.salvage_card"; + + public CollectionSalvageCardHandler( + IMessageSerializer serializer, + CollectionDbContext collectionDb, + CatalogDbContext catalogDb, + BazaarDbContext bazaarDb, + SorIdentityDbContext identityDb) + { + _serializer = serializer; + _collectionDb = collectionDb; + _catalogDb = catalogDb; + _bazaarDb = bazaarDb; + _identityDb = identityDb; + } + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var req = _serializer.DeserializePayload(message.Payload); + var accountId = Guid.Parse(connection.UserId); + + // ── Guard 1: ownership ──────────────────────────────────────────────── + var card = await _collectionDb.PlayerCards + .FirstOrDefaultAsync(pc => pc.Id == req.PlayerCardId, ct); + + if (card == null) + return ServerMessage.Error(message.Seq, "CARD_NOT_FOUND", + "Card not found."); + + if (card.AccountId != accountId) + return ServerMessage.Error(message.Seq, "NOT_OWNER", + "You do not own this card."); + + // ── Guard 2: tradeable ──────────────────────────────────────────────── + if (!card.IsTradeable) + return ServerMessage.Error(message.Seq, "NOT_TRADEABLE", + "Starter deck cards cannot be salvaged."); + + // ── Guard 3: no active listing ──────────────────────────────────────── + var isListed = await _bazaarDb.Listings + .AnyAsync(l => l.PlayerCardId == card.Id + && l.Status == BazaarListingStatus.Active, ct); + + if (isListed) + return ServerMessage.Error(message.Seq, "CARD_LISTED", + "Cancel the marketplace listing before salvaging this card."); + + // ── Guard 4: deck copy check ────────────────────────────────────────── + // Count how many copies of this definition the player currently owns. + var ownedCopies = await _collectionDb.PlayerCards + .CountAsync(pc => pc.AccountId == accountId + && pc.CardDefinitionId == card.CardDefinitionId, ct); + + // Find the highest quantity of this definition used in any single player deck. + var maxUsedInAnyDeck = await _collectionDb.DeckCards + .Where(dc => dc.CardDefinitionId == card.CardDefinitionId + && _collectionDb.Decks.Any(d => d.Id == dc.DeckId + && d.AccountId == accountId)) + .Select(dc => dc.Quantity) + .DefaultIfEmpty(0) + .MaxAsync(ct); + + // Salvaging reduces ownedCopies by 1. If that would drop below the quantity + // required in any deck, reject — the deck would become invalid. + if (maxUsedInAnyDeck >= ownedCopies) + return ServerMessage.Error(message.Seq, "CARD_IN_DECK", + "This card is required by one of your decks. Remove it from the deck first."); + + // ── Load definition for value calculation ───────────────────────────── + var def = await _catalogDb.CardDefinitions + .Where(cd => cd.Id == card.CardDefinitionId) + .Select(cd => new { cd.Rarity, cd.SpCost, cd.StCost }) + .FirstOrDefaultAsync(ct); + + if (def == null) + return ServerMessage.Error(message.Seq, "DEFINITION_NOT_FOUND", + "Card definition not found."); + + var reward = CardSalvageValues.Calculate(def.Rarity, def.SpCost, def.StCost, card.IsFoil); + + // ── Atomic: delete card + credit OriginPoints ───────────────────────── + var conn = (NpgsqlConnection)_collectionDb.Database.GetDbConnection(); + if (conn.State != System.Data.ConnectionState.Open) + await conn.OpenAsync(ct); + + var npgsqlTx = await conn.BeginTransactionAsync( + System.Data.IsolationLevel.ReadCommitted, ct); + + await _collectionDb.Database.UseTransactionAsync(npgsqlTx, ct); + await _identityDb.Database.UseTransactionAsync(npgsqlTx, ct); + + try + { + _collectionDb.PlayerCards.Remove(card); + await _collectionDb.SaveChangesAsync(ct); + + await _identityDb.Database.ExecuteSqlRawAsync( + """ + UPDATE identity.accounts + SET "OriginPoints" = "OriginPoints" + {0} + WHERE "Id" = {1} + """, + new object[] { reward, accountId }, + ct); + + await npgsqlTx.CommitAsync(ct); + } + catch + { + await npgsqlTx.RollbackAsync(ct); + throw; + } + + // Read back the new balance (outside the now-committed transaction). + var newBalance = await _identityDb.Database + .SqlQuery($""" + SELECT "OriginPoints" AS "Value" + FROM identity.accounts + WHERE "Id" = {accountId} + """) + .FirstOrDefaultAsync(ct); + + return ServerMessage.Reply( + "collection.salvage_card.ack", + message.Seq, + new SalvageCardResponse(reward, newBalance)); + } +} diff --git a/Server/src/SOR.Collection/ServiceRegistration.cs b/Server/src/SOR.Collection/ServiceRegistration.cs index 3a334e9..94ec5e4 100644 --- a/Server/src/SOR.Collection/ServiceRegistration.cs +++ b/Server/src/SOR.Collection/ServiceRegistration.cs @@ -38,6 +38,9 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); + // Economy + services.AddTransient(); + return services; } }