From 5f8717cf462f81535f40f2ab96d0ae840644c707 Mon Sep 17 00:00:00 2001 From: CWX Date: Thu, 23 Jan 2025 13:37:38 +0000 Subject: [PATCH] add nullguards and fix callback --- Libraries/Core/Helpers/InventoryHelper.cs | 25 +-- Libraries/Core/Helpers/ItemHelper.cs | 4 +- Libraries/Core/Helpers/TradeHelper.cs | 222 ++++++++++------------ Libraries/Core/Services/PaymentService.cs | 7 +- 4 files changed, 123 insertions(+), 135 deletions(-) diff --git a/Libraries/Core/Helpers/InventoryHelper.cs b/Libraries/Core/Helpers/InventoryHelper.cs index ab3cad3b..7aa95f9a 100644 --- a/Libraries/Core/Helpers/InventoryHelper.cs +++ b/Libraries/Core/Helpers/InventoryHelper.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using System.Text.Json.Serialization; using Core.Models.Eft.Common; using Core.Models.Eft.Common.Tables; @@ -13,6 +14,7 @@ using Core.Services; using Core.Utils; using Core.Utils.Cloners; using SptCommon.Annotations; +using SptCommon.Extensions; using Product = Core.Models.Eft.ItemEvent.Product; namespace Core.Helpers; @@ -76,7 +78,7 @@ public class InventoryHelper( // Add to player inventory AddItemToStash(sessionId, addItemRequest, pmcData, output); - if (output.Warnings.Count > 0) return; + if (output.Warnings?.Count > 0) return; } } @@ -116,7 +118,7 @@ public class InventoryHelper( request.UseSortingTable.GetValueOrDefault(false), output ); - if (output.Warnings.Count > 0) + if (output.Warnings?.Count > 0) // Failed to place, error out return; @@ -130,14 +132,14 @@ public class InventoryHelper( try { if (request.Callback is not null) - request.Callback(rootItemToAdd.Upd.StackObjectsCount.Value, null, null, null); + request.Callback(rootItemToAdd.Upd.StackObjectsCount.Value); } catch (Exception ex) { // Callback failed var message = ex.Message; - _httpResponseUtil.AppendErrorToOutput(output, message); + _logger.Error($"[InventoryHelper]: {ex.Message}"); return; } @@ -148,7 +150,7 @@ public class InventoryHelper( pmcData.Inventory.Items.AddRange(itemWithModsToAddClone); _logger.Debug( - $"Added ${rootItemToAdd.Upd?.StackObjectsCount ?? 1} item: ${rootItemToAdd.Template} with: ${itemWithModsToAddClone.Count - 1} mods to inventory" + $"Added {rootItemToAdd.Upd?.StackObjectsCount ?? 1} item: {rootItemToAdd.Template} with: {itemWithModsToAddClone.Count - 1} mods to inventory" ); } @@ -768,11 +770,12 @@ public class InventoryHelper( // Check each item in container foreach (var item in containerItemHash) { - var itemLocation = item?.Location as ItemLocation; + var location = (JsonElement)item.Location; + var itemLocation = location.ToObject(); if (itemLocation is null) { // item has no location property - _logger.Error("Unable to find 'location' property on item with id: ${ item._id}, skipping"); + _logger.Error($"Unable to find 'location' property on item with id: {item.Id}, skipping"); continue; } @@ -793,7 +796,7 @@ public class InventoryHelper( var rowIndex = itemLocation.Y + y; var containerRow = container2D[rowIndex.Value]; if (containerRow is null) - _logger.Error("Unable to find container: { containerId} row line: { itemLocation.y + y}"); + _logger.Error($"Unable to find container: {containerId} row line: {itemLocation.Y + y}"); // Fill the corresponding cells in the container map to show the slot is taken Array.Fill(containerRow, 1, itemLocation.X.Value, fW); @@ -950,7 +953,7 @@ public class InventoryHelper( /// /// Players id /// Dictionary of 2 values, horizontal and vertical stash size - protected Dictionary GetPlayerStashSize(string sessionId) + protected List GetPlayerStashSize(string sessionId) { var profile = _profileHelper.GetPmcProfile(sessionId); var stashRowBonus = profile.Bonuses.FirstOrDefault(bonus => bonus.Type == BonusType.StashRows); @@ -964,7 +967,7 @@ public class InventoryHelper( { _logger.Error(_localisationService.GetText("inventory-stash_not_found", stashTPL)); - return new Dictionary(); + return new List(); } var stashItemDetails = stashItemResult.Value; @@ -976,7 +979,7 @@ public class InventoryHelper( // Player has a bonus, apply to vertical size if (stashRowBonus is not null) stashV += (int)stashRowBonus.Value; - return new Dictionary { { stashH.Value, stashV.Value } }; + return [stashH.Value, stashV.Value]; } /// diff --git a/Libraries/Core/Helpers/ItemHelper.cs b/Libraries/Core/Helpers/ItemHelper.cs index fcce0289..9700e907 100644 --- a/Libraries/Core/Helpers/ItemHelper.cs +++ b/Libraries/Core/Helpers/ItemHelper.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using System.Text.Json.Serialization; using SptCommon.Annotations; using Core.Models.Eft.Common; @@ -8,6 +9,7 @@ using Core.Models.Utils; using Core.Services; using Core.Utils; using Core.Utils.Cloners; +using SptCommon.Extensions; namespace Core.Helpers; @@ -2027,7 +2029,7 @@ public class ItemHelper( Template = item.Template, ParentId = item.ParentId, SlotId = item.SlotId, - Location = item.Location, + Location = ((JsonElement)item.Location).ToObject(), Upd = item.Upd, }; } diff --git a/Libraries/Core/Helpers/TradeHelper.cs b/Libraries/Core/Helpers/TradeHelper.cs index 5da413b3..d6170235 100644 --- a/Libraries/Core/Helpers/TradeHelper.cs +++ b/Libraries/Core/Helpers/TradeHelper.cs @@ -56,11 +56,49 @@ public class TradeHelper( ) { List offerItems = []; - Action? buyCallback = null; + Action? buyCallback; if (buyRequestData.TransactionId.ToLower() == "ragfair") { - buyCallback = BuyCallback1; + buyCallback = (buyCount => + { + var allOffers = _ragfairServer.GetOffers(); + + // We store ragfair offerid in buyRequestData.item_id + var offerWithItem = allOffers.FirstOrDefault(x => x.Id == buyRequestData.ItemId); + var itemPurchased = offerWithItem.Items.FirstOrDefault(); + + // Ensure purchase does not exceed trader item limit + var assortHasBuyRestrictions = _itemHelper.HasBuyRestrictions(itemPurchased); + if (assortHasBuyRestrictions) + { + this.checkPurchaseIsWithinTraderItemLimit( + sessionID, + pmcData, + buyRequestData.TransactionId, + itemPurchased, + buyRequestData.ItemId, + buyCount + ); + + // Decrement trader item count + PurchaseDetails itemPurchaseDetails = new PurchaseDetails() + { + Items = + [ + new PurchaseItems() + { + ItemId = buyRequestData.ItemId, + Count = buyCount + } + ], + TraderId = buyRequestData.TransactionId + }; + _traderHelper.AddTraderPurchasesToPlayerProfile(sessionID, itemPurchaseDetails, itemPurchased); + } + }); + + // buyCallback = BuyCallback1; // Get raw offer from ragfair, clone to prevent altering offer itself var allOffers = _ragfairServer.GetOffers(); var offerWithItemCloned = _cloner.Clone(allOffers.FirstOrDefault(x => x.Id == buyRequestData.ItemId)); @@ -68,7 +106,17 @@ public class TradeHelper( } else if (buyRequestData.TransactionId == Traders.FENCE) { - buyCallback = BuyCallback2; + buyCallback = (buyCount => + { + // Update assort/flea item values + var traderAssorts = _traderHelper.GetTraderAssortsByTraderId(buyRequestData.TransactionId).Items; + var itemPurchased = traderAssorts.FirstOrDefault(assort => assort.Id == buyRequestData.ItemId); + + // Decrement trader item count + itemPurchased.Upd.StackObjectsCount -= buyCount; + + _fenceService.AmendOrRemoveFenceOffer(buyRequestData.ItemId, buyCount); + }); var fenceItems = _fenceService.GetRawFenceAssorts().Items; var rootItemIndex = fenceItems.FindIndex(item => item.Id == buyRequestData.ItemId); @@ -85,7 +133,57 @@ public class TradeHelper( } else { - buyCallback = BuyCallback3; + buyCallback = (buyCount => + { + // Update assort/flea item values + var traderAssorts = _traderHelper.GetTraderAssortsByTraderId(buyRequestData.TransactionId).Items; + var itemPurchased = traderAssorts.FirstOrDefault(item => item.Id == buyRequestData.ItemId); + + // Ensure purchase does not exceed trader item limit + var assortHasBuyRestrictions = _itemHelper.HasBuyRestrictions(itemPurchased); + if (assortHasBuyRestrictions) + { + // Will throw error if check fails + this.checkPurchaseIsWithinTraderItemLimit( + sessionID, + pmcData, + buyRequestData.TransactionId, + itemPurchased, + buyRequestData.ItemId, + buyCount + ); + } + + // Check if trader has enough stock + if (itemPurchased.Upd.StackObjectsCount < buyCount) + { + throw new Exception( + $"Unable to purchase {buyCount} items, this would exceed the remaining stock left {itemPurchased.Upd.StackObjectsCount} from the traders assort: {buyRequestData.TransactionId} this refresh" + ); + } + + // Decrement trader item count + itemPurchased.Upd.StackObjectsCount -= buyCount; + + if (assortHasBuyRestrictions) + { + var itemPurchaseDat = new PurchaseDetails() + { + Items = new List() + { + new PurchaseItems() + { + ItemId = buyRequestData.ItemId, + Count = buyCount + } + }, + TraderId = buyRequestData.TransactionId + }; + + _traderHelper.AddTraderPurchasesToPlayerProfile(sessionID, itemPurchaseDat, itemPurchased); + } + }); + // Get all trader assort items var traderItems = _traderAssortHelper.GetAssort(sessionID, buyRequestData.TransactionId).Items; @@ -151,121 +249,7 @@ public class TradeHelper( _httpResponseUtil.AppendErrorToOutput(output, errorMessage, BackendErrorCodes.UnknownTradingError); } } - - public void BuyCallback1( - double buyCount, - ProcessBuyTradeRequestData buyRequestData, - string sessionID, - PmcData pmcData) - { - var allOffers = _ragfairServer.GetOffers(); - - // We store ragfair offerid in buyRequestData.item_id - var offerWithItem = allOffers.FirstOrDefault(x => x.Id == buyRequestData.ItemId); - var itemPurchased = offerWithItem.Items.FirstOrDefault(); - - // Ensure purchase does not exceed trader item limit - var assortHasBuyRestrictions = _itemHelper.HasBuyRestrictions(itemPurchased); - if (assortHasBuyRestrictions) - { - this.checkPurchaseIsWithinTraderItemLimit( - sessionID, - pmcData, - buyRequestData.TransactionId, - itemPurchased, - buyRequestData.ItemId, - buyCount - ); - - // Decrement trader item count - PurchaseDetails itemPurchaseDetails = new PurchaseDetails() - { - Items = - [ - new PurchaseItems() - { - ItemId = buyRequestData.ItemId, - Count = buyCount - } - ], - TraderId = buyRequestData.TransactionId - }; - _traderHelper.AddTraderPurchasesToPlayerProfile(sessionID, itemPurchaseDetails, itemPurchased); - } - } - - public void BuyCallback2( - double buyCount, - ProcessBuyTradeRequestData buyRequestData, - string sessionID, - PmcData pmcData) - { - // Update assort/flea item values - var traderAssorts = _traderHelper.GetTraderAssortsByTraderId(buyRequestData.TransactionId).Items; - var itemPurchased = traderAssorts.FirstOrDefault(assort => assort.Id == buyRequestData.ItemId); - - // Decrement trader item count - itemPurchased.Upd.StackObjectsCount -= buyCount; - - _fenceService.AmendOrRemoveFenceOffer(buyRequestData.ItemId, buyCount); - } - - public void BuyCallback3( - double buyCount, - ProcessBuyTradeRequestData buyRequestData, - string sessionID, - PmcData pmcData) - { - // Update assort/flea item values - var traderAssorts = _traderHelper.GetTraderAssortsByTraderId(buyRequestData.TransactionId).Items; - var itemPurchased = traderAssorts.FirstOrDefault(item => item.Id == buyRequestData.ItemId); - - // Ensure purchase does not exceed trader item limit - var assortHasBuyRestrictions = _itemHelper.HasBuyRestrictions(itemPurchased); - if (assortHasBuyRestrictions) - { - // Will throw error if check fails - this.checkPurchaseIsWithinTraderItemLimit( - sessionID, - pmcData, - buyRequestData.TransactionId, - itemPurchased, - buyRequestData.ItemId, - buyCount - ); - } - - // Check if trader has enough stock - if (itemPurchased.Upd.StackObjectsCount < buyCount) - { - throw new Exception( - $"Unable to purchase {buyCount} items, this would exceed the remaining stock left {itemPurchased.Upd.StackObjectsCount} from the traders assort: {buyRequestData.TransactionId} this refresh" - ); - } - - // Decrement trader item count - itemPurchased.Upd.StackObjectsCount -= buyCount; - - if (assortHasBuyRestrictions) - { - var itemPurchaseDat = new PurchaseDetails() - { - Items = new List() - { - new PurchaseItems() - { - ItemId = buyRequestData.ItemId, - Count = buyCount - } - }, - TraderId = buyRequestData.TransactionId - }; - - _traderHelper.AddTraderPurchasesToPlayerProfile(sessionID, itemPurchaseDat, itemPurchased); - } - } - - + /// /// Sell item to trader /// diff --git a/Libraries/Core/Services/PaymentService.cs b/Libraries/Core/Services/PaymentService.cs index 19752254..3b91809b 100644 --- a/Libraries/Core/Services/PaymentService.cs +++ b/Libraries/Core/Services/PaymentService.cs @@ -10,7 +10,6 @@ using Core.Models.Spt.Config; using Core.Models.Utils; using Core.Servers; using Core.Utils; -using Product = Core.Models.Eft.ItemEvent.Product; namespace Core.Services; @@ -64,13 +63,13 @@ public class PaymentService( itemRequest.Count = 0; } else { // If the item is money, add its count to the currencyAmounts object. - currencyAmounts.TryAdd(item.Template, (currencyAmounts[item.Template] ?? 0) + itemRequest.Count); + currencyAmounts.TryAdd(item.Template, (currencyAmounts.GetValueOrDefault(item.Template, 0)) + itemRequest.Count); } } else { // Used by `SptInsure` // Handle differently, `id` is the money type tpl var currencyTpl = itemRequest.Id; - currencyAmounts.TryAdd(currencyTpl, (currencyAmounts[currencyTpl] ?? 0) + itemRequest.Count); + currencyAmounts.TryAdd(currencyTpl, (currencyAmounts.GetValueOrDefault(currencyTpl, 0)) + itemRequest.Count); } } @@ -87,7 +86,7 @@ public class PaymentService( AddPaymentToOutput(pmcData, currencyTpl.Key, (int)currencyAmount, sessionID, output); // If there are warnings, exit early. - if (output.Warnings.Count > 0) { + if (output.Warnings?.Count > 0) { return; }