feat: rotation shops (daily/weekly) + items insurance + season pass
Build & Deploy / build (push) Successful in 10s
Build & Deploy / build (push) Successful in 10s
- RequestStoreRotationData: rotation daily (reset 00:00 UTC) + weekly (lundi) avec storeIDs rotatifs déterministes et timers d'expiration corrects. - EnterMatchmakingStation: traite purchaseInsuranceRequest au déploiement — marque les items assurés (Insurance + owner) et débite la prime (TitleData InventoryInsurance). - FYPurchaseInventoryInsuranceRequest: modèle complété (insuranceId + itemIds). - RequestClaimFortunaPassRewards: claim saison-correct (S2/S3 séparés, plus d'écrasement) + octroi des récompenses depuis catalogue TitleData optionnel (repli sûr sinon). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
31aa20abd8
commit
1e79360b6e
@@ -1,18 +1,107 @@
|
|||||||
using Prospect.Server.Api.Services.CloudScript.Models;
|
using System.Text.Json;
|
||||||
|
using Prospect.Server.Api.Models.Data;
|
||||||
|
using Prospect.Server.Api.Services.Auth.Extensions;
|
||||||
|
using Prospect.Server.Api.Services.CloudScript.Models;
|
||||||
|
using Prospect.Server.Api.Services.CloudScript.Models.Data;
|
||||||
|
using Prospect.Server.Api.Services.UserData;
|
||||||
|
|
||||||
namespace Prospect.Server.Api.Services.CloudScript.Functions;
|
namespace Prospect.Server.Api.Services.CloudScript.Functions;
|
||||||
|
|
||||||
|
// Config d'une police d'assurance (TitleData "InventoryInsurance").
|
||||||
|
public class InventoryInsurancePolicy
|
||||||
|
{
|
||||||
|
public string InsuranceId { get; set; }
|
||||||
|
public double Cost { get; set; }
|
||||||
|
public double Payout { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
[CloudScriptFunction("EnterMatchmakingStation")]
|
[CloudScriptFunction("EnterMatchmakingStation")]
|
||||||
public class EnterMatchmakingStationFunction : ICloudScriptFunction<FYEnterMatchAzureFunction, FYEnterMatchmakingResult>
|
public class EnterMatchmakingStationFunction : ICloudScriptFunction<FYEnterMatchAzureFunction, FYEnterMatchmakingResult>
|
||||||
{
|
{
|
||||||
public Task<FYEnterMatchmakingResult> ExecuteAsync(FYEnterMatchAzureFunction request)
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||||
|
private readonly UserDataService _userDataService;
|
||||||
|
private readonly TitleDataService _titleDataService;
|
||||||
|
private readonly ILogger<EnterMatchmakingStationFunction> _logger;
|
||||||
|
|
||||||
|
public EnterMatchmakingStationFunction(
|
||||||
|
IHttpContextAccessor httpContextAccessor,
|
||||||
|
UserDataService userDataService,
|
||||||
|
TitleDataService titleDataService,
|
||||||
|
ILogger<EnterMatchmakingStationFunction> logger)
|
||||||
{
|
{
|
||||||
return Task.FromResult(new FYEnterMatchmakingResult
|
_httpContextAccessor = httpContextAccessor;
|
||||||
|
_userDataService = userDataService;
|
||||||
|
_titleDataService = titleDataService;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<FYEnterMatchmakingResult> ExecuteAsync(FYEnterMatchAzureFunction request)
|
||||||
|
{
|
||||||
|
// Au déploiement, le client peut demander d'assurer une partie de l'inventaire.
|
||||||
|
var insurance = request.PurchaseInventoryInsurances;
|
||||||
|
var context = _httpContextAccessor.HttpContext;
|
||||||
|
if (context != null && insurance?.ItemIds is { Count: > 0 })
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await ApplyInsuranceAsync(context.User.FindAuthUserId(), insurance);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
// Ne jamais bloquer le déploiement à cause de l'assurance.
|
||||||
|
_logger.LogWarning(e, "Failed to apply inventory insurance on deploy");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new FYEnterMatchmakingResult
|
||||||
{
|
{
|
||||||
Success = true,
|
Success = true,
|
||||||
ErrorMessage = "",
|
ErrorMessage = "",
|
||||||
SingleplayerStation = true, // NOTE: This will always travel to single player station
|
SingleplayerStation = true, // NOTE: This will always travel to single player station
|
||||||
IsMatchTravel = false,
|
IsMatchTravel = false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Marque les items choisis comme assurés (Insurance + propriétaire) et débite la
|
||||||
|
// prime en InsuranceCurrency selon le coût de la police (TitleData InventoryInsurance).
|
||||||
|
private async Task ApplyInsuranceAsync(string userId, FYPurchaseInventoryInsuranceRequest req)
|
||||||
|
{
|
||||||
|
var titleData = _titleDataService.Find(new List<string> { "InventoryInsurance" });
|
||||||
|
var policies = JsonSerializer.Deserialize<Dictionary<string, InventoryInsurancePolicy>>(titleData["InventoryInsurance"]);
|
||||||
|
var insuranceId = string.IsNullOrEmpty(req.InsuranceId) ? "Default" : req.InsuranceId;
|
||||||
|
if (policies == null || !policies.TryGetValue(insuranceId, out var policy))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Unknown insurance policy {InsuranceId}", insuranceId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var userData = await _userDataService.FindAsync(userId, userId, new List<string> { "Inventory", "Balance" });
|
||||||
|
var inventory = JsonSerializer.Deserialize<List<FYCustomItemInfo>>(userData["Inventory"].Value);
|
||||||
|
var balance = JsonSerializer.Deserialize<PlayerBalance>(userData["Balance"].Value);
|
||||||
|
|
||||||
|
var toInsure = new HashSet<string>(req.ItemIds);
|
||||||
|
var insuredCount = 0;
|
||||||
|
foreach (var item in inventory)
|
||||||
|
{
|
||||||
|
if (!toInsure.Contains(item.ItemId)) continue;
|
||||||
|
item.Insurance = insuranceId;
|
||||||
|
item.InsuranceOwnerPlayfabId = userId;
|
||||||
|
insuredCount++;
|
||||||
|
}
|
||||||
|
if (insuredCount == 0) return;
|
||||||
|
|
||||||
|
// Prime = coût de la police × nombre d'items assurés (arrondi au supérieur),
|
||||||
|
// plafonnée au solde disponible pour ne jamais passer en négatif.
|
||||||
|
var premium = (int)Math.Ceiling(policy.Cost * insuredCount);
|
||||||
|
premium = Math.Min(premium, balance.InsuranceCurrency);
|
||||||
|
balance.InsuranceCurrency -= premium;
|
||||||
|
|
||||||
|
await _userDataService.UpdateAsync(userId, userId, new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["Inventory"] = JsonSerializer.Serialize(inventory),
|
||||||
|
["Balance"] = JsonSerializer.Serialize(balance),
|
||||||
});
|
});
|
||||||
|
_logger.LogInformation("Insured {Count} item(s) under policy {Policy} for user {User} (premium {Premium})",
|
||||||
|
insuredCount, insuranceId, userId, premium);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+90
-14
@@ -1,5 +1,6 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
using Prospect.Server.Api.Models.Data;
|
||||||
using Prospect.Server.Api.Services.Auth.Extensions;
|
using Prospect.Server.Api.Services.Auth.Extensions;
|
||||||
using Prospect.Server.Api.Services.CloudScript;
|
using Prospect.Server.Api.Services.CloudScript;
|
||||||
using Prospect.Server.Api.Services.UserData;
|
using Prospect.Server.Api.Services.UserData;
|
||||||
@@ -9,6 +10,15 @@ public class FYFortunaPassClaimedRewards {
|
|||||||
public List<string> RewardsIDs { get; set; }
|
public List<string> RewardsIDs { get; set; }
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Récompense d'un palier de la passe (catalogue optionnel TitleData "FortunaPass2_Rewards").
|
||||||
|
// itemId "SoftCurrency"/"Aurum"/"InsuranceCurrency" = monnaie, sinon item d'inventaire.
|
||||||
|
public class FortunaPassRewardDef {
|
||||||
|
[JsonPropertyName("itemId")]
|
||||||
|
public string ItemId { get; set; }
|
||||||
|
[JsonPropertyName("amount")]
|
||||||
|
public int Amount { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
public class RequestClaimFortunaPassRewardsRequest
|
public class RequestClaimFortunaPassRewardsRequest
|
||||||
{
|
{
|
||||||
[JsonPropertyName("rewardsIds")]
|
[JsonPropertyName("rewardsIds")]
|
||||||
@@ -34,11 +44,13 @@ public class RequestClaimFortunaPassRewardsFunction : ICloudScriptFunction<Reque
|
|||||||
{
|
{
|
||||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||||
private readonly UserDataService _userDataService;
|
private readonly UserDataService _userDataService;
|
||||||
|
private readonly TitleDataService _titleDataService;
|
||||||
|
|
||||||
public RequestClaimFortunaPassRewardsFunction(IHttpContextAccessor httpContextAccessor, UserDataService userDataService)
|
public RequestClaimFortunaPassRewardsFunction(IHttpContextAccessor httpContextAccessor, UserDataService userDataService, TitleDataService titleDataService)
|
||||||
{
|
{
|
||||||
_httpContextAccessor = httpContextAccessor;
|
_httpContextAccessor = httpContextAccessor;
|
||||||
_userDataService = userDataService;
|
_userDataService = userDataService;
|
||||||
|
_titleDataService = titleDataService;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RequestClaimFortunaPassRewardsResponse> ExecuteAsync(RequestClaimFortunaPassRewardsRequest request)
|
public async Task<RequestClaimFortunaPassRewardsResponse> ExecuteAsync(RequestClaimFortunaPassRewardsRequest request)
|
||||||
@@ -49,28 +61,92 @@ public class RequestClaimFortunaPassRewardsFunction : ICloudScriptFunction<Reque
|
|||||||
throw new CloudScriptException("CloudScript was not called within a http request");
|
throw new CloudScriptException("CloudScript was not called within a http request");
|
||||||
}
|
}
|
||||||
var userId = context.User.FindAuthUserId();
|
var userId = context.User.FindAuthUserId();
|
||||||
var userData = await _userDataService.FindAsync(userId, userId, new List<string>{"FortunaPass2_ClaimedRewards"});
|
|
||||||
var claimedRewards = JsonSerializer.Deserialize<FYFortunaPassClaimedRewards>(userData["FortunaPass2_ClaimedRewards"].Value);
|
// Clé de la saison courante (déterminée par la config de build) — évite d'écraser
|
||||||
foreach (var rewardId in request.RewardsIDs) {
|
// la progression de l'autre saison (l'ancien code écrasait S2 ET S3).
|
||||||
|
#if SEASON_3_RELEASE || SEASON_3_DEBUG
|
||||||
|
const string claimedKey = "FortunaPass3_ClaimedRewards";
|
||||||
|
const string rewardsCatalogKey = "FortunaPass3_Rewards";
|
||||||
|
#else
|
||||||
|
const string claimedKey = "FortunaPass2_ClaimedRewards";
|
||||||
|
const string rewardsCatalogKey = "FortunaPass2_Rewards";
|
||||||
|
#endif
|
||||||
|
|
||||||
|
var userData = await _userDataService.FindAsync(userId, userId, new List<string>{ claimedKey, "Inventory", "Balance" });
|
||||||
|
var claimedRewards = JsonSerializer.Deserialize<FYFortunaPassClaimedRewards>(userData[claimedKey].Value)
|
||||||
|
?? new FYFortunaPassClaimedRewards { RewardsIDs = new List<string>() };
|
||||||
|
claimedRewards.RewardsIDs ??= new List<string>();
|
||||||
|
|
||||||
|
// Catalogue des récompenses (optionnel) : rewardId -> {itemId, amount}.
|
||||||
|
Dictionary<string, FortunaPassRewardDef> catalog = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var td = _titleDataService.Find(new List<string> { rewardsCatalogKey });
|
||||||
|
if (td.TryGetValue(rewardsCatalogKey, out var raw) && !string.IsNullOrWhiteSpace(raw))
|
||||||
|
catalog = JsonSerializer.Deserialize<Dictionary<string, FortunaPassRewardDef>>(raw);
|
||||||
|
}
|
||||||
|
catch { /* pas de catalogue → on enregistre seulement la réclamation */ }
|
||||||
|
|
||||||
|
var inventory = JsonSerializer.Deserialize<List<FYCustomItemInfo>>(userData["Inventory"].Value) ?? new List<FYCustomItemInfo>();
|
||||||
|
var balance = JsonSerializer.Deserialize<PlayerBalance>(userData["Balance"].Value);
|
||||||
|
var grantedItems = new List<FYCustomItemInfo>();
|
||||||
|
var changedCurrencies = new List<FYCurrencyItem>();
|
||||||
|
|
||||||
|
foreach (var rewardId in request.RewardsIDs)
|
||||||
|
{
|
||||||
|
// Ne pas re-créditer un palier déjà réclamé.
|
||||||
|
if (claimedRewards.RewardsIDs.Contains(rewardId)) continue;
|
||||||
claimedRewards.RewardsIDs.Add(rewardId);
|
claimedRewards.RewardsIDs.Add(rewardId);
|
||||||
|
|
||||||
|
if (catalog == null || !catalog.TryGetValue(rewardId, out var def) || def == null) continue;
|
||||||
|
|
||||||
|
switch (def.ItemId)
|
||||||
|
{
|
||||||
|
case "SoftCurrency":
|
||||||
|
balance.SoftCurrency += def.Amount;
|
||||||
|
changedCurrencies.Add(new FYCurrencyItem { CurrencyName = "SoftCurrency", Amount = balance.SoftCurrency });
|
||||||
|
break;
|
||||||
|
case "Aurum":
|
||||||
|
balance.HardCurrency += def.Amount;
|
||||||
|
changedCurrencies.Add(new FYCurrencyItem { CurrencyName = "Aurum", Amount = balance.HardCurrency });
|
||||||
|
break;
|
||||||
|
case "InsuranceCurrency":
|
||||||
|
balance.InsuranceCurrency += def.Amount;
|
||||||
|
changedCurrencies.Add(new FYCurrencyItem { CurrencyName = "InsuranceCurrency", Amount = balance.InsuranceCurrency });
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
var item = new FYCustomItemInfo {
|
||||||
|
ItemId = Guid.NewGuid().ToString(),
|
||||||
|
Amount = def.Amount <= 0 ? 1 : def.Amount,
|
||||||
|
BaseItemId = def.ItemId,
|
||||||
|
Durability = 0,
|
||||||
|
Insurance = "",
|
||||||
|
InsuranceOwnerPlayfabId = "",
|
||||||
|
ModData = new FYModItems { M = [] },
|
||||||
|
Origin = new FYItemOriginBackend { G = "", P = "", T = "" },
|
||||||
|
InsuredAttachmentId = "",
|
||||||
|
PrimaryVanityId = 0,
|
||||||
|
SecondaryVanityId = 0,
|
||||||
|
RolledPerks = [],
|
||||||
|
};
|
||||||
|
inventory.Add(item);
|
||||||
|
grantedItems.Add(item);
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var output = JsonSerializer.Serialize(claimedRewards);
|
var changes = new Dictionary<string, string> { [claimedKey] = JsonSerializer.Serialize(claimedRewards) };
|
||||||
await _userDataService.UpdateAsync(
|
if (grantedItems.Count > 0) changes["Inventory"] = JsonSerializer.Serialize(inventory);
|
||||||
userId, userId,
|
if (changedCurrencies.Count > 0) changes["Balance"] = JsonSerializer.Serialize(balance);
|
||||||
new Dictionary<string, string>{
|
await _userDataService.UpdateAsync(userId, userId, changes);
|
||||||
["FortunaPass2_ClaimedRewards"] = output,
|
|
||||||
["FortunaPass3_ClaimedRewards"] = output, // TODO: Separate logic for S2 and S3
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return new RequestClaimFortunaPassRewardsResponse
|
return new RequestClaimFortunaPassRewardsResponse
|
||||||
{
|
{
|
||||||
UserId = userId,
|
UserId = userId,
|
||||||
ErrorType = 3, // EYFortunaPassToastReponseType::Ok
|
ErrorType = 3, // EYFortunaPassToastReponseType::Ok
|
||||||
Error = "",
|
Error = "",
|
||||||
GrantedItems = [],
|
GrantedItems = grantedItems.ToArray(),
|
||||||
ChangedCurrencies = [],
|
ChangedCurrencies = changedCurrencies.ToArray(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,11 @@ public class RequestStoreRotationDataFunction : ICloudScriptFunction<RequestStor
|
|||||||
_httpContextAccessor = httpContextAccessor;
|
_httpContextAccessor = httpContextAccessor;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Nombre de variantes de rotation (les storeId "DailyShop_N" / "WeeklyShop_N"
|
||||||
|
// permettent au client de distinguer chaque rotation et de rafraîchir son cache).
|
||||||
|
private const int DailyVariants = 8;
|
||||||
|
private const int WeeklyVariants = 4;
|
||||||
|
|
||||||
public async Task<RequestStoreRotationDataResponse> ExecuteAsync(RequestStoreRotationDataRequest request)
|
public async Task<RequestStoreRotationDataResponse> ExecuteAsync(RequestStoreRotationDataRequest request)
|
||||||
{
|
{
|
||||||
var context = _httpContextAccessor.HttpContext;
|
var context = _httpContextAccessor.HttpContext;
|
||||||
@@ -43,18 +48,33 @@ public class RequestStoreRotationDataFunction : ICloudScriptFunction<RequestStor
|
|||||||
throw new CloudScriptException("CloudScript was not called within a http request");
|
throw new CloudScriptException("CloudScript was not called within a http request");
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Get and save store rotation data
|
var now = DateTime.UtcNow;
|
||||||
|
|
||||||
|
// Rotation quotidienne : expire au prochain minuit UTC ; l'index de rotation
|
||||||
|
// est le nombre de jours écoulés depuis l'epoch (déterministe, stable).
|
||||||
|
var todayUtc = now.Date;
|
||||||
|
var dailyExpiration = todayUtc.AddDays(1);
|
||||||
|
var dayIndex = (int)(todayUtc - DateTime.UnixEpoch.Date).TotalDays;
|
||||||
|
var dailyStoreId = $"DailyShop_{dayIndex % DailyVariants}";
|
||||||
|
|
||||||
|
// Rotation hebdomadaire : expire au prochain lundi 00:00 UTC.
|
||||||
|
// DayOfWeek : dimanche=0 ; on ramène lundi=0.
|
||||||
|
var daysSinceMonday = ((int)todayUtc.DayOfWeek + 6) % 7;
|
||||||
|
var weekStart = todayUtc.AddDays(-daysSinceMonday);
|
||||||
|
var weeklyExpiration = weekStart.AddDays(7);
|
||||||
|
var weekIndex = (int)Math.Floor((weekStart - DateTime.UnixEpoch.Date).TotalDays / 7);
|
||||||
|
var weeklyStoreId = $"WeeklyShop_{weekIndex % WeeklyVariants}";
|
||||||
|
|
||||||
return new RequestStoreRotationDataResponse
|
return new RequestStoreRotationDataResponse
|
||||||
{
|
{
|
||||||
Error = "",
|
Error = "",
|
||||||
DailyStoreData = new StoreRotationData {
|
DailyStoreData = new StoreRotationData {
|
||||||
StoreID = "DailyShop",
|
StoreID = dailyStoreId,
|
||||||
ExpirationData = DateTime.UtcNow.AddDays(1)
|
ExpirationData = dailyExpiration
|
||||||
},
|
},
|
||||||
WeeklyStoreData = new StoreRotationData {
|
WeeklyStoreData = new StoreRotationData {
|
||||||
StoreID = "WeeklyShop",
|
StoreID = weeklyStoreId,
|
||||||
ExpirationData = DateTime.UtcNow.AddDays(1)
|
ExpirationData = weeklyExpiration
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-3
@@ -1,7 +1,14 @@
|
|||||||
namespace Prospect.Server.Api.Services.CloudScript.Models.Data;
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Prospect.Server.Api.Services.CloudScript.Models.Data;
|
||||||
|
|
||||||
|
// Envoyé par le client au déploiement (dans FYEnterMatchAzureFunction) : quels items
|
||||||
|
// de l'inventaire assurer, avec quelle police (voir TitleData "InventoryInsurance").
|
||||||
public class FYPurchaseInventoryInsuranceRequest
|
public class FYPurchaseInventoryInsuranceRequest
|
||||||
{
|
{
|
||||||
// m_insuranceId
|
[JsonPropertyName("insuranceId")]
|
||||||
// m_itemIds
|
public string InsuranceId { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("itemIds")]
|
||||||
|
public List<string> ItemIds { get; set; }
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user