초기커밋

This commit is contained in:
2025-05-01 07:20:41 +09:00
commit 98bb2e3c5c
2747 changed files with 646947 additions and 0 deletions

View File

@@ -0,0 +1,424 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
using META_ID = System.UInt32;
namespace GameServer;
public class PurchaseShopProductAction : EntityActionBase
{
public PurchaseShopProductAction(MyShopProduct owner) : base(owner)
{
}
public override async Task<Result> onInit()
{
await Task.CompletedTask;
var result = new Result();
return result;
}
public override void onClear()
{
return;
}
public (DiscountType discount_type, int discount_rate) checkPurchaseDiscountType(int productId)
{
var discount_type = DiscountType.None;
int discount_rate = 0;
var player = getOwner().getRootParent() as Player;
ArgumentNullException.ThrowIfNull(player);
var item_first_purchase_history_agent_action = player.getEntityAction<ItemFirstPurchaseHistoryAgentAction>();
ArgumentNullException.ThrowIfNull(item_first_purchase_history_agent_action);
if (!MetaData.Instance._ShopProductMetaTable.TryGetValue(productId, out var shop_product_meta_data))
return (discount_type, discount_rate);
if (null != shop_product_meta_data.ProductData.Item)
{
if (!MetaData.Instance._ItemTable.TryGetValue(shop_product_meta_data.ProductData.Item.Id, out var item_meta_data))
return (discount_type, discount_rate);
if (item_first_purchase_history_agent_action.isItemFirstPurchase(item_meta_data.ItemId))
{
discount_type = DiscountType.ItemFirstPurchase;
discount_rate = item_meta_data.Buy_Discount_Rate;
}
}
return (discount_type, discount_rate);
}
public (Result result, MetaAssets.ShopProductMetaData? product_data) checkPurchaseShopProductConditions(int shop_id, int product_id, int purchase_count)
{
var result = new Result();
string err_msg;
// 1. shop_id 체크
var check_shop_id = ShopHelper.checkShopIdFromTableData(shop_id);
if (check_shop_id.result.isFail())
{
err_msg = $"Fail to get shop data : shop id - {shop_id}";
result.setFail(ServerErrorCode.NotFoundShopId, err_msg);
Log.getLogger().error(err_msg);
return (result, null);
}
// 2. product_id 체크
var check_product_id = ShopHelper.checkProductIdFromTableData(product_id);
if (check_product_id.result.isFail())
{
err_msg = $"Fail to get product data : product id - {product_id}";
result.setFail(ServerErrorCode.NotFoundProductId, err_msg);
Log.getLogger().error(err_msg);
return (result, null);
}
// 3. 구매 시간 체크
var shop_meter_attribute = getOwner().getEntityAttribute<ShopProductTradingMeterAttribute>();
if (null == shop_meter_attribute)
{
err_msg = $"Fail to get ShopProductTradingMeter Attribute : {nameof(ShopProductTradingMeterAttribute)}.";
result.setFail(ServerErrorCode.EntityAttributeIsNull, err_msg);
Log.getLogger().error(err_msg);
return (result, null);
}
if (shop_meter_attribute.EndTime < DateTime.UtcNow.ToTimestamp())
{
err_msg = $"Fail to buy Shop Item : Shop EndTime - {shop_meter_attribute.EndTime}";
result.setFail(ServerErrorCode.NotFoundShopId, err_msg);
Log.getLogger().error(err_msg);
return (result, null);
}
// 4. 구매 가능 수량 체크
var shop_meter_sub_attribute = getShopTradingMeterSubAttribute(product_id);
if (null == shop_meter_sub_attribute)
{
err_msg = $"Fail to get shop product info : {nameof(ShopProductTradingMeterSubAttribute)}";
result.setFail(ServerErrorCode.EntityAttributeNotFound, err_msg);
Log.getLogger().error(err_msg);
return (result, null);
}
if (shop_meter_sub_attribute.LeftCount < purchase_count || purchase_count <= 0)
{
err_msg = $"Fail to check purchased product count : left count - {shop_meter_sub_attribute.LeftCount} / purchase count - {purchase_count}";
result.setFail(ServerErrorCode.InvalidItemCount, err_msg);
Log.getLogger().error(err_msg);
return (result, null);
}
// 5. 첫 구매 아이템이 1개가 아닌경우 체크
NullReferenceCheckHelper.throwIfNull(check_product_id.product_data, () => $"check_product_id.product_data is null !!!");
if (check_product_id.product_data.ProductData.Item != null)
{
var player = getOwner().getRootParent() as Player;
ArgumentNullException.ThrowIfNull(player);
result = player.checkItemFirstPurchaseItemCount(check_product_id.product_data.ProductData.Item.Id, purchase_count);
if (result.isFail())
{
return (result, null);
}
}
return (result, check_product_id.product_data);
}
public Result checkPurchaseCharacterConditions(MetaAssets.ShopProductMetaData? product_data)
{
var result = new Result();
if (null == product_data)
{
var err_msg = $"Fail to get product data";
result.setFail(ServerErrorCode.NotFoundProductId, err_msg);
Log.getLogger().error(err_msg);
return result;
}
// 1. 속성 조건 체크
result = checkAbilityCondition(product_data.Attribute_Key, product_data.Attribute_Value);
if (result.isFail()) return result;
// 2. 성별 조건 체크
result = checkGenderCondition(product_data.Gender);
if (result.isFail()) return result;
return result;
}
private Result checkAbilityCondition(string attribute_key, int attribute_value)
{
var result = new Result();
string err_msg;
if (string.IsNullOrEmpty(attribute_key) || attribute_key == "None")
{
return result;
}
var ability_action = getOwner().getRootParent().getEntityAction<AbilityAction>();
ArgumentNullException.ThrowIfNull(ability_action);
if (false == EnumHelper.tryParse<AttributeType>(attribute_key, out var attribute_type))
{
err_msg =
$"Fail to check AbilityCondition!!! : invalid attribute_key - attribute_key[{attribute_key}]";
result.setFail(ServerErrorCode.NotEnoughAttribute, err_msg);
Log.getLogger().info(err_msg);
return result;
}
var ability = ability_action.getAbility(attribute_type) ?? 0;
if (attribute_value > ability)
{
err_msg =
$"Fail to check AbilityCondition!!! : attribute_value - {attribute_value} / ability - {ability}";
result.setFail(ServerErrorCode.NotEnoughAttribute, err_msg);
Log.getLogger().info(err_msg);
}
return result;
}
private Result checkGenderCondition(MetaAssets.EGenderType gender)
{
var result = new Result();
string err_msg;
var player = getOwner().getRootParent() as Player;
ArgumentNullException.ThrowIfNull(player);
var action = player?.getEntityAction<PlayerAction>();
if (null == action)
{
err_msg =
$"Fail to check Gender Condition !!! : {nameof(PlayerAction)} is null";
result.setFail(ServerErrorCode.EntityActionNotFound, err_msg);
Log.getLogger().info(err_msg);
return result;
}
var select_character = action.getSelectedCharacter();
ArgumentNullException.ThrowIfNull(select_character);
var own_appearance_profile = select_character.getOriginAppearanceProfile();
var check_gender = ShopHelper.checkBasicStyleDataFromTableData(own_appearance_profile.BasicStyle);
if (check_gender.result.isFail()) return check_gender.result;
if (MetaAssets.EGenderType.ALL != gender && gender != check_gender.basic_style_data!.Gender)
{
err_msg = $"Invalid Gender. user Gender : {gender}, need Gender : {check_gender.basic_style_data.Gender}";
result.setFail(ServerErrorCode.InvalidGender, err_msg);
Log.getLogger().info(err_msg);
}
return result;
}
public async Task<Result> processPurchase(MetaAssets.ShopProductMetaData product_data, int purchase_count, int discountRate, ShopPurchaseInfo shopPurchaseInfo)
{
var result = new Result();
if (product_data.ProductData.Item != null)
{
var process_for_item = await processForItem(product_data, product_data.ProductData.Item.Id, purchase_count, discountRate);
if (process_for_item.result.isFail()) return process_for_item.result;
shopPurchaseInfo.m_spent = process_for_item.spent_info;
shopPurchaseInfo.m_purchase = new PurchaseInfo();
shopPurchaseInfo.m_purchase.m_purchase_items = process_for_item.purchased_items;
}
else if (product_data.ProductData.Currency != null)
{
var process_for_currency = await processForCurrency(product_data, product_data.ProductData.Currency.Id, purchase_count);
if (process_for_currency.result.isFail()) return process_for_currency.result;
shopPurchaseInfo.m_spent = process_for_currency.spent_info;
shopPurchaseInfo.m_purchase = new PurchaseInfo();
var check_currency_data = ShopHelper.checkCurrencyDataFromProductIdInTableData(product_data.ProductData.Currency.Id);
if (check_currency_data.result.isFail()) return result;
NullReferenceCheckHelper.throwIfNull(check_currency_data.currency_data, () => $"check_currency_data.currency_data is null !!!");
shopPurchaseInfo.m_purchase.m_purchase_currency_type = check_currency_data.currency_data.CurrencyType;
shopPurchaseInfo.m_purchase.m_purchase_currency = product_data.ProductData.Currency.Value * purchase_count;
}
return result;
}
private async Task<(Result result, SpentInfo? spent_info, List<GameServer.Item>? purchased_items)> processForItem(MetaAssets.ShopProductMetaData product_data, int item_id, int purchase_count, int discountRate)
{
var result = new Result();
var my_shop_product = getOwner();
ArgumentNullException.ThrowIfNull(my_shop_product);
var player = my_shop_product.getRootParent() as Player;
ArgumentNullException.ThrowIfNull(player);
// 1. 아이템 지급
var inventory_action = player?.getEntityAction<InventoryActionBase>();
if (null == inventory_action)
{
var err_msg = $"Fail to get Inventory Action : {nameof(InventoryActionBase)}.";
result.setFail(ServerErrorCode.EntityActionNotFound, err_msg);
Log.getLogger().error(err_msg);
return (result, null, null);
}
(result, var changed_items) = await inventory_action.tryTakalbleToBag((META_ID)item_id, (ushort)purchase_count);
if (result.isFail()) return (result, null, null);
// 2. 요구 재화 체크
var required_purchase = await ShopHelper.checkRequiredPurchaseFromProductMeta(product_data, purchase_count, discountRate);
return (required_purchase.result, required_purchase.spent_info, changed_items);
}
private async Task<(Result result, SpentInfo? spent_info, List<GameServer.Item>? purchased_items)> processForCurrency(MetaAssets.ShopProductMetaData product_data, int currency_id, int purchase_count)
{
var result = new Result();
var my_shop_product = getOwner();
ArgumentNullException.ThrowIfNull(my_shop_product);
var player = my_shop_product.getRootParent() as Player;
ArgumentNullException.ThrowIfNull(player);
// 1. 재화 지급
var money_action = player?.getEntityAction<MoneyAction>();
if (null == money_action)
{
var err_msg = $"Fail to get Money Action : {nameof(MoneyAction)}.";
result.setFail(ServerErrorCode.EntityActionNotFound, err_msg);
Log.getLogger().error(err_msg);
return (result, null, null);
}
var check = ShopHelper.checkCurrencyDataFromProductIdInTableData(currency_id);
if (check.result.isFail() || null == check.currency_data)
{
var err_msg = $"Fail to get Currency Data : {nameof(ShopHelper.checkCurrencyDataFromProductIdInTableData)}. product id - {currency_id}";
result.setFail(ServerErrorCode.NotFoundItemTableId, err_msg);
Log.getLogger().error(err_msg);
return (result, null, null);
}
result = await money_action.changeMoney(check.currency_data.CurrencyType, product_data.ProductData.Currency.Value * purchase_count);
if (result.isFail()) return (result, null, null);
var required = await ShopHelper.checkRequiredPurchaseFromProductMeta(product_data, purchase_count, 0);
return (required.result, required.spent_info, null);
}
public async Task<(Result result, IEnumerable<GameServer.Item>? del_items)> processSpent(SpentInfo spentInfo)
{
var result = new Result();
var my_shop_product = getOwner();
ArgumentNullException.ThrowIfNull(my_shop_product);
var player = my_shop_product.getRootParent() as Player;
ArgumentNullException.ThrowIfNull(player);
List<GameServer.Item>? del_items = null;
switch (spentInfo.m_buy_type)
{
// 재화 감소
case ShopBuyType.Currency:
var money_action = player?.getEntityAction<MoneyAction>();
ArgumentNullException.ThrowIfNull(money_action);
result = await money_action.changeMoney(spentInfo.m_currency_type, -1 * spentInfo.m_spent);
break;
// 아이템 차감
case ShopBuyType.Item:
var inventory_action = player?.getEntityAction<InventoryActionBase>();
ArgumentNullException.ThrowIfNull(inventory_action);
var delete_item = await inventory_action.tryDeleteItemByMetaId((uint)spentInfo.m_item_id, (ushort)spentInfo.m_spent);
result = delete_item.Item1;
del_items = delete_item.Item2;
break;
//
case ShopBuyType.None:
default:
var err_msg = $"fail to spent purchase !!! : invalid shop buy type - {spentInfo.m_buy_type}";
result.setFail(ServerErrorCode.InvalidShopBuyType, err_msg);
Log.getLogger().error(err_msg);
return (result, null);
}
return (result, del_items);
}
public async Task<Result> updateShopProductMeter(int product_id, int count)
{
var result = new Result();
var shop_trading_meter_action = getOwner().getEntityAction<ShopProductTradingMeterAction>();
if (null == shop_trading_meter_action)
{
var err_msg = $"Fail to get ShopProductTradingMeter Action : {nameof(ShopProductTradingMeterAction)}.";
result.setFail(ServerErrorCode.EntityActionNotFound, err_msg);
Log.getLogger().error(err_msg);
return result;
}
result = await shop_trading_meter_action.updateTradingMeter(product_id, -1 * count);
return result;
}
public async Task<Result> updateItemFirstPurchaseHistory(DiscountType discountType, int itemMetaId)
{
var result = new Result();
var player = getOwner().getRootParent();
ArgumentNullException.ThrowIfNull(player);
if (discountType != DiscountType.ItemFirstPurchase)
return result;
var item_first_purchase_history_agent_action = player.getEntityAction<ItemFirstPurchaseHistoryAgentAction>();
ArgumentNullException.ThrowIfNull(item_first_purchase_history_agent_action);
result = await item_first_purchase_history_agent_action.tryAddItemFirstPurchaseHistoryFromMetaId(itemMetaId);
if (result.isFail())
{
return result;
}
return result;
}
private ShopProductTradingMeterSubAttribute? getShopTradingMeterSubAttribute(int product_id)
{
var shop_meter_attribute = getOwner().getEntityAttribute<ShopProductTradingMeterAttribute>();
if (null == shop_meter_attribute) return null;
var sub_attribute = shop_meter_attribute.getMeterSubAttribute(product_id);
return sub_attribute ?? null;
}
}

View File

@@ -0,0 +1,276 @@
using System.Collections.Concurrent;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
using ITEM_GUID = System.String;
using META_ID = System.UInt32;
namespace GameServer;
public class ShopAction : EntityActionBase
{
private readonly ConcurrentDictionary<int, MyShopProduct> m_my_shop_products = new();
private readonly MySoldProduct m_my_sold_product;
public ShopAction(Player owner) : base(owner)
{
m_my_sold_product = new MySoldProduct(owner);
}
public override async Task<Result> onInit()
{
await Task.CompletedTask;
var result = new Result();
return result;
}
public override void onClear()
{
return;
}
public MySoldProduct getMySoldProduct() => m_my_sold_product;
public ShopSoldProductAction getSolProductAction()
{
var shop_sold_product_action = m_my_sold_product.getEntityAction<ShopSoldProductAction>();
NullReferenceCheckHelper.throwIfNull(shop_sold_product_action, () => $"shop_sold_product_action is null !!!");
return shop_sold_product_action;
}
public IEnumerable<MyShopProduct> getMyShopProducts() => m_my_shop_products.Select(shop => shop.Value).ToList();
public MyShopProduct getMyShopProduct(int shop_id)
{
if (m_my_shop_products.TryGetValue(shop_id, out var my_shop_product))
{
return my_shop_product;
}
var owner = getOwner() as Player;
my_shop_product = new MyShopProduct(owner!);
setMyShopProduct(shop_id, my_shop_product);
return my_shop_product;
}
public async Task<Result> setMyShopProductFromDoc(ShopProductTradingMeterDoc docBase)
{
var result = new Result();
string err_msg;
var owner = getOwner() as Player;
NullReferenceCheckHelper.throwIfNull(owner, () => $"owner is null !!!");
var doc_attr = docBase.getAttrib<ShopProductTradingMeterAttrib>();
if (null == doc_attr)
{
err_msg = $"Fail to get doc attrib : {nameof(ShopProductTradingMeterDoc)} is null";
result.setFail(ServerErrorCode.EntityAttributeNotFound, err_msg);
Log.getLogger().error(err_msg);
return result;
}
var my_shop_product = getMyShopProduct(doc_attr.ShopId);
var my_shop_attribute = my_shop_product.getEntityAttribute<ShopProductTradingMeterAttribute>();
if (null == my_shop_attribute)
{
err_msg = $"Fail to get entity attribute : {nameof(ShopProductTradingMeterAttribute)} is null";
result.setFail(ServerErrorCode.EntityAttributeIsNull, err_msg);
Log.getLogger().error(err_msg);
return result;
}
// doc 에서 직접 copy 된 경우 pk, sk 를 셋팅해야 한다.
docBase.setCombinationKeyForPK(owner.getUserGuid());
docBase.setCombinationKeyForSK(doc_attr.ShopId.ToString());
var is_apply = docBase.onApplyPKSK();
if (ServerErrorCode.Success != is_apply)
{
err_msg = $"Fail to copy to attribute from doc : invalid argument {nameof(setMyShopProductFromDoc)}";
result.setFail(is_apply, err_msg);
Log.getLogger().error(err_msg);
return result;
}
var is_success = my_shop_attribute.copyEntityAttributeFromDoc(docBase);
if (false == is_success)
{
err_msg = $"Fail to copy shop product trading meter attribute : to {nameof(ShopProductTradingMeterAttribute)} from {nameof(ShopProductTradingMeterDoc)}";
result.setFail(ServerErrorCode.DynamoDbDocCopyToEntityAttributeFailed, err_msg);
Log.getLogger().error(err_msg);
}
return await Task.FromResult(result);
}
public async Task<Result> cheatInitResetTime()
{
foreach (var shop_product in m_my_shop_products)
{
var attribute = shop_product.Value.getEntityAttribute<ShopProductTradingMeterAttribute>();
if (attribute == null) continue;
attribute.initEndTime();
attribute.modifiedEntityAttribute();
}
return await Task.FromResult(new Result());
}
public async Task<Result> cheatInitShopRenewalCount(Int32 shopId)
{
await Task.CompletedTask;
var shop = getMyShopProduct(shopId);
var result = new Result();
var attribute = shop.getEntityAttribute<ShopProductTradingMeterAttribute> ();
var owner = getOwner();
if (attribute is null)
{
Log.getLogger().error($"Shop Product Attribute not exist shopId : {shopId}, owner : {owner.toBasicString()}");
return result;
}
attribute.setCurrentRenewalCount(0);
attribute.modifiedEntityAttribute();
return result;
}
private void setMyShopProduct(int shop_id, MyShopProduct product) => m_my_shop_products.TryAdd(shop_id, product);
public async Task<(Result result, GameServer.Item? changed_item, CurrencyType spent_currency_type, double spent_currency)> processRePurchase(MetaAssets.ItemMetaData item_data, SoldProduct sold)
{
var result = new Result();
var player = getOwner() as Player;
// 1. inventory 아이템 추가
var inventory_action = player?.getEntityAction<InventoryActionBase>();
if (null == inventory_action)
{
var err_msg = $"Fail to get Inventory Action : {nameof(InventoryActionBase)}.";
result.setFail(ServerErrorCode.EntityActionNotFound, err_msg);
Log.getLogger().error(err_msg);
return (result, null, CurrencyType.None, 0);
}
var item_attrib = sold.ItemDoc.getAttrib<ItemAttrib>();
NullReferenceCheckHelper.throwIfNull(item_attrib, () => $"item_attrib is null !!! - {player?.toBasicString()}");
(result, var changed_item) = await inventory_action.tryTakableToBag(sold.ItemDoc);
if(result.isFail() || null == changed_item) return (result, null, CurrencyType.None, 0);
// 2. sold item list 갱신
var sold_action = player?.getEntityAction<ShopAction>().getMySoldProduct().getEntityAction<ShopSoldProductAction>();
if (null == sold_action)
{
var err_msg = $"Fail to get Sold Product Action : {nameof(ShopSoldProductAction)}.";
result.setFail(ServerErrorCode.EntityActionNotFound, err_msg);
Log.getLogger().error(err_msg);
return (result, null, CurrencyType.None, 0);
}
result = await sold_action.updateSoldProduct(item_attrib.ItemGuid, -1 * item_attrib.ItemStackCount);
var check_currency_type = ShopHelper.checkCurrencyTypeFromCurrencyId(item_data.SellId);
if (check_currency_type.result.isFail()) return (check_currency_type.result, null, CurrencyType.None, 0);
return (result, changed_item, check_currency_type.currencyType, item_data.SellPrice * item_attrib.ItemStackCount);
}
public async Task<Result> processSpent(CurrencyType spent_currency_type, double spent_currency)
{
var result = new Result();
var my_shop_product = getOwner();
var player = my_shop_product.getRootParent() as Player;
var money_action = player?.getEntityAction<MoneyAction>();
if (null == money_action)
{
var err_msg = $"Fail to get Money Action : {nameof(MoneyAction)}.";
result.setFail(ServerErrorCode.EntityActionNotFound, err_msg);
Log.getLogger().error(err_msg);
return result;
}
result = await money_action.changeMoney(spent_currency_type, -1 * spent_currency);
return result;
}
public Result checkItemSellConditionAsync(ItemAttributeBase attribute, int sellCount)
{
var result = new Result();
string err_msg;
var player = getOwner() as Player;
NullReferenceCheckHelper.throwIfNull(player, () => $"player is null !!!");
// 0. 재판매 여부 확인
var check_item = ShopHelper.checkItemIdFromTableData((int)attribute.ItemMetaId);
if (check_item.result.isFail() || null == check_item.item_data) return check_item.result;
if (false == check_item.item_data.IsSystemTradable)
{
err_msg = $"failed to check sell item : cannot sell item !! - itemId[{attribute.ItemMetaId}] , isSystemTrade[{check_item.item_data.IsSystemTradable}]";
result.setFail(ServerErrorCode.ShopItemCannotSell, err_msg);
Log.getLogger().error(result.toBasicString());
return result;
}
// 1. 착용 여부 확인
if (InvenEquipType.None != attribute.EquipedIvenType)
{
err_msg = $"Failed to check equipped item : already equipped - {attribute.ItemGuid}";
result.setFail(ServerErrorCode.SlotsAlreadyEquiped, err_msg);
Log.getLogger().error(err_msg);
return result;
}
// 2. 마이홈 배치 여부 확인
var myhome_agent_action = player.getEntityAction<MyhomeAgentAction>();
NullReferenceCheckHelper.throwIfNull(myhome_agent_action, () => $"myhome_agent_action is null !!! - {player.toBasicString()}");
if (false == myhome_agent_action.tryGetSelectedMyhome(out var my_home)) return result;
var myhome_inventory_action = my_home.getEntityAction<MyhomeInventoryAction>();
NullReferenceCheckHelper.throwIfNull(myhome_inventory_action, () => $"myhome_inventory_action is null !!! - {player.toBasicString()}");
if (myhome_inventory_action.tryGetItemByItemGuid(attribute.ItemGuid) != null)
{
err_msg = $"Failed to check setting my home item : item guid - {attribute.ItemGuid}";
result.setFail(ServerErrorCode.ShopIsMyHomeItem, err_msg);
Log.getLogger().error(err_msg);
}
// 3. stack 수량 체크
if (attribute.ItemStackCount < sellCount)
{
err_msg =
$"Failed to check stack count : stackCount[{attribute.ItemStackCount}] / sellCount[{sellCount}]";
result.setFail(ServerErrorCode.InvalidItemCount, err_msg);
Log.getLogger().error(err_msg);
}
return result;
}
}

View File

@@ -0,0 +1,53 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer;
public class ShopProductTradingMeterAction : EntityActionBase
{
public ShopProductTradingMeterAction(MyShopProduct owner) : base(owner)
{
}
public override async Task<Result> onInit()
{
await Task.CompletedTask;
var result = new Result();
return result;
}
public override void onClear()
{
return;
}
public async Task<Result> updateTradingMeter(int product_id, int delta)
{
var result = new Result();
var attribute = getOwner().getEntityAttribute<ShopProductTradingMeterAttribute>();
if (null == attribute)
{
var err_msg = $"Fail to get attribute() !!! : {nameof(ShopProductTradingMeterAttribute)}";
result.setFail(ServerErrorCode.EntityAttributeNotFound, err_msg);
Log.getLogger().error(err_msg);
return result;
}
result = attribute.changeProductTradingMeter(product_id, delta);
if (result.isFail()) return result;
attribute.modifiedEntityAttribute();
return await Task.FromResult(new Result());
}
}

View File

@@ -0,0 +1,104 @@
using Newtonsoft.Json;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
using ITEM_GUID = System.String;
namespace GameServer;
public class SoldProduct
{
[JsonProperty("item_guid")] public ITEM_GUID ItemGuid { get; set; } = ITEM_GUID.Empty;
[JsonProperty("item")] public ItemDoc ItemDoc { get; set; } = null!;
}
// ==============================================================
// 기획 의도 : 채널이동 및 로그아웃시 해당 데이터 초기화
// attribute 별도 제작 안함
// ==============================================================
public class ShopSoldProductAction : EntityActionBase
{
public ShopSoldProductAction(MySoldProduct owner) : base(owner)
{
m_sold_products = new List<SoldProduct>();
}
public override async Task<Result> onInit()
{
await Task.CompletedTask;
var result = new Result();
return result;
}
public override void onClear()
{
return;
}
public async Task<Result> setSoldProduct(ITEM_GUID item_guid, ItemDoc itemDoc)
{
var result = new Result();
var is_exist = m_sold_products.Any(product => product.ItemGuid == item_guid);
if (is_exist) return result;
var sold = new SoldProduct { ItemGuid = item_guid, ItemDoc = itemDoc};
m_sold_products.Add(sold);
return await Task.FromResult(result);
}
public async Task<Result> updateSoldProduct(ITEM_GUID item_guid, int delta_count)
{
var result = new Result();
var sold = findSoldProduct(item_guid);
if (null == sold)
{
var err_msg = $"Fail to get item info : {nameof(updateSoldProduct)} - {item_guid}";
result.setFail(ServerErrorCode.NotFoundItemTableId, err_msg);
Log.getLogger().error(err_msg);
return result;
}
var item_attrib = sold.ItemDoc.getAttrib<ItemAttrib>();
NullReferenceCheckHelper.throwIfNull(item_attrib, () => $"itemAttrib is null !! - itemGuid:{item_guid}");
var delta = item_attrib.ItemStackCount + delta_count;
if (delta <= 0)
{
deleteSoldProduct(item_guid);
return result;
}
item_attrib.ItemStackCount = (ushort)delta;
return await Task.FromResult(result);
}
private void deleteSoldProduct(ITEM_GUID item_guid)
{
foreach (var sold in m_sold_products.Where(sold => sold.ItemGuid == item_guid))
{
m_sold_products.Remove(sold);
break;
}
}
private List<SoldProduct> m_sold_products { get; set; }
public List<SoldProduct> getSoldList() => m_sold_products;
public SoldProduct? findSoldProduct(ITEM_GUID item_guid) => m_sold_products.FirstOrDefault(sold => sold.ItemGuid == item_guid);
}

View File

@@ -0,0 +1,101 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer;
public class DBQShopProductTradingMeterReadAll : QueryExecutorBase
{
private string m_pk { get; set; } = string.Empty;
private readonly string m_combination_key_for_pk;
private readonly List<ShopProductTradingMeterDoc> m_to_read_meter_docs = new();
public DBQShopProductTradingMeterReadAll(string combinationKeyForPk)
: base(nameof(DBQShopProductTradingMeterReadAll))
{
m_combination_key_for_pk = combinationKeyForPk;
}
//=====================================================================================
// DB 쿼리 직전에 준비해야 할 로직들을 작성한다.
//=====================================================================================
public override async Task<Result> onPrepareQuery()
{
var result = new Result();
var owner = getOwner();
NullReferenceCheckHelper.throwIfNull(owner, () => $"owner is null !!!");
var doc = new ShopProductTradingMeterDoc();
doc.setCombinationKeyForPK(m_combination_key_for_pk);
var error_code = doc.onApplyPKSK();
if (error_code.isFail())
{
var err_msg = $"Failed to onApplyPKSK() !!! : {error_code.toBasicString()} - {toBasicString()}, {owner.toBasicString()}";
result.setFail(error_code, err_msg);
Log.getLogger().error(result.toBasicString());
return result;
}
m_pk = doc.getPK();
return await Task.FromResult(result);
}
//=====================================================================================
// onPrepareQuery()를 성공할 경우 호출된다.
//=====================================================================================
public override async Task<Result> onQuery()
{
var result = new Result();
var err_msg = string.Empty;
var owner = getOwner();
NullReferenceCheckHelper.throwIfNull(owner, () => $"owner is null !!!");
var query_batch = getQueryBatch();
NullReferenceCheckHelper.throwIfNull(query_batch, () => $"query_batch is null !!!");
var db_connector = query_batch.getDynamoDbConnector();
var query_config = db_connector.makeQueryConfigForReadByPKOnly(m_pk);
(result, var read_docs) = await db_connector.simpleQueryDocTypesWithQueryOperationConfig<ShopProductTradingMeterDoc>(query_config, eventTid: query_batch.getTransId());
if (result.isFail())
{
return result;
}
var shop_action = owner.getEntityAction<ShopAction>();
NullReferenceCheckHelper.throwIfNull(shop_action, () => $"shop_action is null !!!");
foreach (var read_doc in read_docs)
{
result = await shop_action.setMyShopProductFromDoc(read_doc);
if (result.isFail()) return result;
m_to_read_meter_docs.Add(read_doc);
}
return await Task.FromResult(result);
}
//=====================================================================================
// DB 쿼리를 성공하고, doFnCommit()가 QueryResultType.NotCalledQueryFunc를 반환할 경우 호출된다.
//=====================================================================================
public override async Task onQueryResponseCommit() => await Task.CompletedTask;
//=====================================================================================
// DB 쿼리를 실패하고, doFnRollback()가 QueryResultType.NotCalledQueryFunc를 반환할 경우 호출된다.
//=====================================================================================
public override async Task onQueryResponseRollback(Result errorResult) => await Task.CompletedTask;
private new Player? getOwner() => getQueryBatch()?.getLogActor() as Player;
}

View File

@@ -0,0 +1,337 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
using USER_GUID = System.String;
namespace GameServer;
public class ShopPurchaseInfo
{
public int m_shop_id { get; set; }
public int m_shop_product_id { get; set; }
public int m_shop_product_count { get; set; }
public SpentInfo? m_spent { get; set; }
public PurchaseInfo? m_purchase { get; set; }
}
public class SpentInfo
{
public ShopBuyType m_buy_type { get; set; }
public CurrencyType m_currency_type { get; set; }
public int m_item_id { get; set; }
public double m_spent { get; set; }
}
public class PurchaseInfo
{
public ShopBuyType m_purchase_type { get; set; }
public List<GameServer.Item>? m_purchase_items { get; set; }
public List<GameServer.Item>? m_spend_items { get; set; }
public CurrencyType m_purchase_currency_type { get; set; } = CurrencyType.None;
public double m_purchase_currency { get; set; }
}
public static class ShopHelper
{
public static (Result result, MetaAssets.ShopMetaData? shop_data) checkShopIdFromTableData(int shop_id)
{
var result = new Result();
if (MetaData.Instance._ShopMetaTable.TryGetValue(shop_id, out var shop_products) == false)
{
result.setFail(ServerErrorCode.NotFoundShopId, $"Not Found ShopDataTable Shop Id : {shop_id}");
}
return (result, shop_products);
}
public static IEnumerable<ShopMetaData> getShopMetaData() => MetaData.Instance._ShopMetaTable.Select(data => data.Value).ToList();
public static (Result result, MetaAssets.ShopProductMetaData? product_data) checkProductIdFromTableData(int product_id)
{
var result = new Result();
if (MetaData.Instance._ShopProductMetaTable.TryGetValue(product_id, out var product_data) == false)
{
result.setFail(ServerErrorCode.NotFoundProductId, $"Not Found ProductDataTable Product Id : {product_id}");
}
return (result, product_data);
}
public static (Result result, MetaAssets.ItemMetaData? item_data) checkItemIdFromTableData(int item_id)
{
var result = new Result();
if (MetaData.Instance._ItemTable.TryGetValue(item_id, out var item_data) == false)
{
result.setFail(ServerErrorCode.NotFoundItemTableId, $"Not Found ItemDataTable Item Id : {item_id}");
}
return (result, item_data);
}
public static (Result result, MetaAssets.CurrencyMetaData? currency_data) checkCurrencyDataFromProductIdInTableData(int product_id)
{
var result = new Result();
if (MetaData.Instance.Meta.CurrencyMetaTable.CurrencyMetaDataListbyId.TryGetValue(product_id, out var currency_data) == false)
{
result.setFail(ServerErrorCode.NotFoundItemTableId, $"Not Found CurrencyData Product Id : {product_id}");
}
return (result, currency_data);
}
public static (Result result, CurrencyType currencyType) checkCurrencyTypeFromCurrencyId(int currencyId)
{
var result = new Result();
(result, var currency_type) = checkCurrencyDataFromProductIdInTableData(currencyId);
if (result.isFail()) return (result, CurrencyType.None);
NullReferenceCheckHelper.throwIfNull(currency_type, () => $"currency_type is null !!!");
return (result, currency_type.CurrencyType);
}
public static (Result result, MetaAssets.BasicStyleMetaData? basic_style_data) checkBasicStyleDataFromTableData(UInt32 basic_style_id)
{
var result = new Result();
if (MetaData.Instance._BasicStyleMetaTable.TryGetValue((int)basic_style_id, out var basic_style_data) == false)
{
result.setFail(ServerErrorCode.NotFoundTable, $"Not Found BasicStyleDataTable basic style id : {basic_style_id}");
}
return (result, basic_style_data);
}
public static bool createNewShopProductTradingMetersAttribute(ShopProductTradingMeterAttribute attribute, int shop_id, USER_GUID owner_guid)
{
var check = checkShopIdFromTableData(shop_id);
if (check.result.isFail()) return false;
attribute.ShopId = shop_id;
// 1. 신규 생성 여부 체크
var is_create = attribute.ShopProductTradingMeterSubs.Count <= 0;
// 2. sub data 초기화
attribute.ShopProductTradingMeterSubs.Clear();
// 3. 판매 종료시간 갱신
attribute.EndTime = calculateSaleEndTime(check.shop_data!.ResetTime);
var product_max_count = check.shop_data.ShopProduct_List;
// 4. 판매 물품 갱신
product_max_count = addNecessaryProductByGroupIdTable(check.shop_data.ShopProduct_Group_Id, product_max_count, attribute);
addRandomProductByGroupIdTable(check.shop_data.ShopProduct_Group_Id, product_max_count, attribute);
// 5. renewalCount 초기화
attribute.initRenewalCount();
if (is_create)
{
attribute.newEntityAttribute();
}
else
{
attribute.modifiedEntityAttribute();
}
return true;
}
private static int addNecessaryProductByGroupIdTable(int group_id, int max_count, ShopProductTradingMeterAttribute attribute)
{
if (MetaData.Instance._ShopNecessaryProductByGroupIdTable.TryGetValue(group_id, out var shopNecessaryProductList) != true) return max_count;
foreach (var productInfo in shopNecessaryProductList)
{
if (max_count <= 0)
{
break;
}
var sub_attribute = new ShopProductTradingMeterSubAttribute
{
ProductId = productInfo.ID,
LeftCount = productInfo.ProductType_BuyCount
};
attribute.ShopProductTradingMeterSubs.Add(sub_attribute);
max_count -= 1;
}
return max_count;
}
private static void addRandomProductByGroupIdTable(int group_id, int max_count, ShopProductTradingMeterAttribute attribute)
{
if (MetaData.Instance._ShopRandomProductByGroupIdTable.TryGetValue(group_id, out var shop_random_group) != true) return;
var total_weight = shop_random_group.TotalWeight;
List<ShopProductTradingMeterSubAttribute> added_products = new();
while (true)
{
if (max_count <= 0 || total_weight <= 0)
{
break;
}
// randomProduct 에서 선택되지 않을 수 있음 ( 선택이 되지 않아도 상점 리스트는 차감됨 )
var spent_weight = selectRandomProduct(added_products, shop_random_group, total_weight);
total_weight -= spent_weight;
max_count -= 1;
}
attribute.ShopProductTradingMeterSubs.AddRange(added_products);
}
private static int selectRandomProduct(List<ShopProductTradingMeterSubAttribute> added_list, ShopProductRandomGroupInfo shop_random_group, int total_weight)
{
var weight = 0;
var random_weight = RandomHelper.next(0, total_weight);
var spend_weight = 0;
foreach (var productInfo in shop_random_group.RandomGroupList)
{
// 이미 추가되어 있으면 패스
var breakCheck = added_list.Any(randomProduct => randomProduct.ProductId == productInfo.ID);
if (breakCheck) continue;
weight += productInfo.Weight;
// productInfo.Weight 가 0 인 경우 선택 자체가 되지 않음 ( random_weight >= 0 )
if (weight <= random_weight) continue;
var sub_attribute = new ShopProductTradingMeterSubAttribute
{
ProductId = productInfo.ID,
LeftCount = productInfo.ProductType_BuyCount
};
added_list.Add(sub_attribute);
spend_weight = productInfo.Weight;
break;
}
return spend_weight;
}
public static Timestamp calculateSaleEndTime(int resetTime)
{
var interval_count = (DateTime.UtcNow.Ticks - ServerCommon.Constant.SHOP_DEFINE_TIME.Ticks) / (resetTime * TimeSpan.TicksPerMinute);
return ServerCommon.Constant.SHOP_DEFINE_TIME.AddMinutes((interval_count + 1) * resetTime).ToTimestamp();
}
public static async Task<(Result result, SpentInfo? spent_info)> checkRequiredPurchaseFromProductMeta(ShopProductMetaData productData, int purchaseCount, int discountRate)
{
var result = new Result();
var spent_info = new SpentInfo();
spent_info.m_buy_type = productData.Buy_Price_Type;
switch (productData.Buy_Price_Type)
{
case ShopBuyType.Currency:
var currency_data = ShopHelper.checkCurrencyDataFromProductIdInTableData(productData.Buy_Id);
if (currency_data.result.isFail()) return (currency_data.result, null);
NullReferenceCheckHelper.throwIfNull(currency_data.currency_data, () => $"currency_data.currency_data is null !!!");
spent_info.m_currency_type = currency_data.currency_data.CurrencyType;
var price = await checkCaliumCurrency(spent_info.m_currency_type, productData.Buy_Price, discountRate);
spent_info.m_spent = purchaseCount * price;
break;
case ShopBuyType.Item:
spent_info.m_item_id = productData.Buy_Id;
spent_info.m_spent = purchaseCount * productData.Buy_Price;
break;
case ShopBuyType.None:
default:
var err_msg = $"fail to get shop product meta data !!! : invalid shop buy type {productData.Buy_Price_Type}";
result.setFail(ServerErrorCode.InvalidShopBuyType, err_msg);
Log.getLogger().error(err_msg);
return (result, null);
}
return (result, spent_info);
}
public static bool checkRenewallableTime(ShopProductTradingMeterAttribute attribute)
{
bool is_renewallable_time = false;
var now = DateTimeHelper.Current;
var end_time = attribute.EndTime.ToDateTime();
var timeDifference = Math.Abs((now - end_time).TotalSeconds);
// 차이가 ShopRenewalBlockTime초 이상이면 true, 그렇지 않으면 false
if (timeDifference >= MetaHelper.GameConfigMeta.ShopRenewalBlockTime)
{
is_renewallable_time = true;
}
return is_renewallable_time;
}
public static bool renewalNewShopProductTradingMetersAttribute(USER_GUID owner_guid, ShopProductTradingMeterAttribute attribute, ShopMetaData shopData)
{
attribute.ShopId = shopData.Id;
// 1. 신규 생성 여부 체크
//var is_create = attribute.ShopProductTradingMeterSubs.Count <= 0;
// 2. sub data 초기화
attribute.ShopProductTradingMeterSubs.Clear();
var product_max_count = shopData.ShopProduct_List;
// 3. 판매 물품 갱신
product_max_count = addNecessaryProductByGroupIdTable(shopData.ShopProduct_Group_Id, product_max_count, attribute);
addRandomProductByGroupIdTable(shopData.ShopProduct_Group_Id, product_max_count, attribute);
// 4. renewal count 중가
attribute.increaseRenewalCount();
// 리뉴얼은 무조건 상점이 존재해야 하므로 modified만 체크
attribute.modifiedEntityAttribute();
return true;
}
public static async Task<double> checkCaliumCurrency(CurrencyType currencyType, double price, int discountRate)
{
var calculate_price = price;
if (currencyType == CurrencyType.Calium)
{
calculate_price = await CaliumStorageHelper.calculateCaliumFromSapphire(price, true);
}
return (calculate_price * 100 - calculate_price * discountRate) / 100;
}
}

View File

@@ -0,0 +1,34 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer;
public class CheatRenewalShopProductBusinessLog : ILogInvokerEx
{
private RenewalShopProductsLogInfo m_info;
public CheatRenewalShopProductBusinessLog(Int32 shopId)
:base(LogDomainType.CheatRenewalShopProducts)
{
m_info = new RenewalShopProductsLogInfo(this, shopId, 0, 0, 0, 0, new());
}
public override bool hasLog()
{
return true;
}
protected override void fillup(ref BusinessLog.LogBody body)
{
body.append(m_info);
}
}

View File

@@ -0,0 +1,35 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer;
public class RenewalShopProductsBusinessLog : ILogInvokerEx
{
private RenewalShopProductsLogInfo m_info;
public RenewalShopProductsBusinessLog(Int32 shopId, Int32 maxCount, Int32 currentRenewalCount, Int32 currencyType,
Int32 currencyValue, List<ShopProductTradingMeterSubAttribute> productTrandingMeters)
:base(LogDomainType.RenewalShopProducts)
{
m_info = new RenewalShopProductsLogInfo(this, shopId, maxCount, currentRenewalCount, currencyType,
currencyValue, productTrandingMeters);
}
public override bool hasLog()
{
return true;
}
protected override void fillup(ref BusinessLog.LogBody body)
{
body.append(m_info);
}
}

View File

@@ -0,0 +1,46 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer;
public class MyShopProduct : EntityBase
{
public MyShopProduct(Player parent) : base(EntityType.MyShopProductMeter, parent)
{
onInit().GetAwaiter().GetResult();
}
public sealed override async Task<Result> onInit()
{
var owner = getRootParent() as Player;
ArgumentNullException.ThrowIfNull(owner);
var direct_parent = getDirectParent();
NullReferenceCheckHelper.throwIfNull(direct_parent, () => $"direct_parent is null !!!");
addEntityAttribute(new ShopProductTradingMeterAttribute(this, owner.getUserGuid(), direct_parent));
addEntityAction(new ShopProductTradingMeterAction(this));
addEntityAction(new PurchaseShopProductAction(this));
return await base.onInit();
}
public override string toBasicString()
{
return $"{this.getTypeName()} - {getRootParent().toBasicString()}";
}
public override string toSummaryString()
{
return $"{this.getTypeName()} - {getRootParent().toBasicString()}";
}
}

View File

@@ -0,0 +1,38 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer;
public class MySoldProduct : EntityBase
{
public MySoldProduct(Player parent) : base(EntityType.ShopSoldProduct, parent)
{
onInit().GetAwaiter().GetResult();
}
public sealed override async Task<Result> onInit()
{
addEntityAction(new ShopSoldProductAction(this));
return await base.onInit();
}
public override string toBasicString()
{
return $"{this.getTypeName()} - {getRootParent().toBasicString()}";
}
public override string toSummaryString()
{
return $"{this.getTypeName()} - {getRootParent().toBasicString()}";
}
}

View File

@@ -0,0 +1,159 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer.PacketHandler;
[PacketHandler(typeof(ClientToGameReq), typeof(ClientToGameReq.Types.GetShopProductListReq), typeof(GetShopProductListPacketHandler), typeof(GameLoginListener))]
public class GetShopProductListPacketHandler : PacketRecvHandler
{
private static void send_S2C_ACK_GET_SHOP_PRODUCT_LIST(Player owner, Result result, MyShopProduct? shop_product, Int32 renewalMaxCount = 0)
{
var ack_packet = new ClientToGame
{
Response = new ClientToGameRes
{
ErrorCode = result.ErrorCode,
GetShopProductListRes = new ClientToGameRes.Types.GetShopProductListRes()
}
};
if (result.isSuccess())
{
ArgumentNullReferenceCheckHelper.throwIfNull(shop_product, () => $"QuestMailAction is null !!! - player:{owner.toBasicString()}");
var attribute = shop_product.getOriginEntityAttribute<ShopProductTradingMeterAttribute>();
if (null == attribute)
{
ack_packet.Response.ErrorCode = ServerErrorCode.EntityAttributeIsNull;
Log.getLogger().error($"Fail to get entity attribute: {nameof(ShopProductTradingMeterAttribute)}");
result.setFail(ServerErrorCode.EntityAttributeIsNull);
}
ack_packet.Response.GetShopProductListRes.ProductInfo = new ShopPacketInfo
{
LeftTimeAsSecond = (int)(attribute!.EndTime - Timestamp.FromDateTime(DateTime.UtcNow)).Seconds
};
foreach (var meter in attribute.ShopProductTradingMeterSubs)
{
var info = new ShopItemInfo
{
ProductID = meter.ProductId,
LeftCount = meter.LeftCount
};
ack_packet.Response.GetShopProductListRes.ProductInfo.ShopItemList.Add(info);
}
ack_packet.Response.GetShopProductListRes.ProductInfo.MaxRenewalCount = renewalMaxCount;
ack_packet.Response.GetShopProductListRes.ProductInfo.CurrentRenewalCount = attribute.CurrentRenewalCount;
}
GameServerApp.getServerLogic().onSendPacket(owner!, ack_packet);
}
public override async Task<Result> onProcessPacket(ISession entityWithSession, IMessage recvMessage)
{
var result = new Result();
string err_msg;
var entity_player = entityWithSession as Player;
NullReferenceCheckHelper.throwIfNull(entity_player, () => "player is null !!!");
// 1. 기본 정보 체크
var request = (recvMessage as ClientToGame)!.Request.GetShopProductListReq;
if (null == request)
{
err_msg = $"Failed to get request type !!! : {nameof(ClientToGame.Request.GetShopProductListReq)}";
result.setFail(ServerErrorCode.InvalidArgument, err_msg);
Log.getLogger().error(result.toBasicString());
send_S2C_ACK_GET_SHOP_PRODUCT_LIST(entity_player, result, null);
return result;
}
// 2. shop 정보 체크
var check = ShopHelper.checkShopIdFromTableData(request.ShopID);
if (check.result.isFail())
{
err_msg = $"Failed to check Shop Id from Table Data !!! : {request.ShopID}";
result.setFail(ServerErrorCode.NotFoundShopId, err_msg);
Log.getLogger().error(result.toBasicString());
send_S2C_ACK_GET_SHOP_PRODUCT_LIST(entity_player, result, null);
return result;
}
NullReferenceCheckHelper.throwIfNull(check.shop_data, () => $"ShopData is null shop id : {request.ShopID}");
result = await entity_player.runTransactionRunnerSafely(TransactionIdType.PrivateContents, "GetShopProductList", getShopProductDelegate);
if (result.isFail())
{
err_msg = $"Failed to runTransactionRunnerSafely()!!! : {result.toBasicString()} - {entity_player.toBasicString()}";
Log.getLogger().error(err_msg);
}
var action = entity_player.getEntityAction<ShopAction>();
NullReferenceCheckHelper.throwIfNull(action, () => $"ShopAction is null !!! - player:{entity_player.toBasicString()}");
var shop_product = action.getMyShopProduct(request.ShopID);
send_S2C_ACK_GET_SHOP_PRODUCT_LIST(entity_player, result, shop_product, check.shop_data.RenewalMaxCount);
return result;
async Task<Result> getShopProductDelegate() => await getShopProductListAsync(entity_player, request.ShopID);
}
private async Task<Result> getShopProductListAsync(Player entity_player, int shop_id)
{
var result = new Result();
// 2. my shop product 체크
var action = entity_player.getEntityAction<ShopAction>();
NullReferenceCheckHelper.throwIfNull(action, () => $"ShopAction is null !!! - player:{entity_player.toBasicString()}");
var my_shop_product = action.getMyShopProduct(shop_id);
// 3. attribute 가져오기
var attribute = my_shop_product.getEntityAttribute<ShopProductTradingMeterAttribute>();
if (null == attribute)
{
result.setFail(ServerErrorCode.EntityAttributeIsNull, $"Failed to getEntityAttribute() !!!: {nameof(ShopProductTradingMeterAttribute)}");
Log.getLogger().error(result.toBasicString());
return result;
}
// 4. attribute 에 유효기간이 지나지 않으면, 데이터 활용
if ( attribute.ShopProductTradingMeterSubs.Count > 0 && attribute.EndTime > DateTime.UtcNow.ToTimestamp())
{
return result;
}
// 5. data load ( 유효기간이 지나서 갱신하는 처리도 같이 처리 )
var is_create = ShopHelper.createNewShopProductTradingMetersAttribute(attribute, shop_id, entity_player.getUserGuid());
if (false == is_create)
{
var err_msg = $"Failed to create new shop product trading meter data !!! : {nameof(ShopHelper.createNewShopProductTradingMetersAttribute)} - {shop_id}";
result.setFail(ServerErrorCode.EntityActionNotFound, err_msg);
Log.getLogger().error(result.toBasicString());
return result;
}
// 6. db 갱신
var batch = new QueryBatchEx<QueryRunnerWithDocument>( entity_player, LogActionType.ShopGetProductTradingMeter, GameServerApp.getServerLogic().getDynamoDbClient(), true);
{
batch.addQuery(new DBQWriteToAttributeAllWithTransactionRunner());
batch.addQuery(new QueryFinal());
}
result = await QueryHelper.sendQueryAndBusinessLog(batch);
return result;
}
}

View File

@@ -0,0 +1,81 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer.PacketHandler;
[PacketHandler(typeof(ClientToGameReq), typeof(ClientToGameReq.Types.GetRePurchaseListReq), typeof(GetShopRePurchaseListPacketHandler), typeof(GameLoginListener))]
public class GetShopRePurchaseListPacketHandler : PacketRecvHandler
{
private static void send_S2C_ACK_GET_SHOP_RE_PURCHASE_LIST(Player owner, Result result, List<SelledItem>? soldItems)
{
var ack_packet = new ClientToGame
{
Response = new ClientToGameRes
{
ErrorCode = result.ErrorCode,
GetRePurchaseListRes = new ClientToGameRes.Types.GetRePurchaseListRes()
}
};
if (result.isSuccess())
{
ArgumentNullReferenceCheckHelper.throwIfNull(soldItems, () => $"SelledItems is null !!! - player:{owner.toBasicString()}");
ack_packet.Response.GetRePurchaseListRes.SelledItem.AddRange(soldItems);
}
GameServerApp.getServerLogic().onSendPacket(owner, ack_packet);
}
public override async Task<Result> onProcessPacket(ISession entityWithSession, IMessage recvMessage)
{
var result = new Result();
var entity_player = entityWithSession as Player;
NullReferenceCheckHelper.throwIfNull(entity_player, () => "player is null !!!");
// 1. 기본 정보 체크
var message = recvMessage as ClientToGame;
ArgumentNullReferenceCheckHelper.throwIfNull(message, () => $"Message is null !!! - player:{entity_player.toBasicString()}");
// 2. sold product 가져오기
var shop_action = entity_player.getEntityAction<ShopAction>();
NullReferenceCheckHelper.throwIfNull(shop_action, () => $"ShopAction is null !!! - player:{entity_player.toBasicString()}");
var sold_action = shop_action.getMySoldProduct().getEntityAction<ShopSoldProductAction>();
NullReferenceCheckHelper.throwIfNull(sold_action, () => $"ShopSoldProductAction is null !!! - player:{entity_player.toBasicString()}");
// 3. list 추가
var list = new List<SelledItem>();
foreach (var sold in sold_action.getSoldList())
{
var data = new SelledItem();
data.ItemGuid = sold.ItemGuid;
var attrib = sold.ItemDoc.getAttrib<ItemAttrib>();
if (null == attrib)
{
Log.getLogger().error($"Fail to read sold item doc !!! - item guid[{data.ItemGuid}]");
continue;
}
data.ItemId = (int)attrib.ItemMetaId;
data.Count = attrib.ItemStackCount;
list.Add(data);
}
send_S2C_ACK_GET_SHOP_RE_PURCHASE_LIST(entity_player, result, list);
return await Task.FromResult(result);
}
}

View File

@@ -0,0 +1,165 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer.PacketHandler;
[PacketHandler(typeof(ClientToGameReq), typeof(ClientToGameReq.Types.RePurchaseItemReq), typeof(RePurchaseItemPacketHandler), typeof(GameLoginListener))]
public class RePurchaseItemPacketHandler : PacketRecvHandler
{
private static void send_S2C_ACK_SHOP_RE_PURCHASE_LIST(Player? owner, Result result, List<Item>? rePurchaseItems)
{
var ack_packet = new ClientToGame
{
Response = new ClientToGameRes
{
ErrorCode = result.ErrorCode,
RePurchaseItemRes = new ClientToGameRes.Types.RePurchaseItemRes()
}
};
// 데이터 가져오기
if (result.isSuccess())
{
if (null != rePurchaseItems)
{
foreach (var info in rePurchaseItems)
{
var attribute = info.getEntityAttribute<ItemAttributeBase>();
var item = new global::Item
{
ItemGuid = attribute!.ItemGuid,
ItemId = (int)attribute.ItemMetaId,
Count = attribute.ItemStackCount,
Level = attribute.Level,
Slot = attribute.EquipedPos
};
item.Attributeids.AddRange(attribute.Attributes.Select(attrib => (int)attrib));
ack_packet.Response.RePurchaseItemRes.Items.Add(item);
}
}
var account_attribute = owner!.getEntityAttribute<AccountAttribute>();
var level_attribute = owner.getEntityAttribute<LevelAttribute>();
var money_attribute = owner.getEntityAttribute<MoneyAttribute>();
var nickname_attribute = owner.getEntityAttribute<NicknameAttribute>();
var char_info = new CharInfo
{
Level = (int)level_attribute!.Level,
Exp = (int)level_attribute.Exp,
Gold = money_attribute!.Gold,
Sapphire = money_attribute.Sapphire,
Calium = money_attribute.Calium,
Ruby = money_attribute.Ruby,
Usergroup = account_attribute!.AuthAdminLevelType.ToString(),
Operator = (int)account_attribute.AuthAdminLevelType,
DisplayName = nickname_attribute!.Nickname,
LanguageInfo = (int)account_attribute.LanguageType,
IsIntroComplete = 1
};
ack_packet.Response.RePurchaseItemRes.CurrencyInfo = char_info;
}
GameServerApp.getServerLogic().onSendPacket(owner!, ack_packet);
}
public override async Task<Result> onProcessPacket(ISession entityWithSession, IMessage recvMessage)
{
var result = new Result();
string err_msg;
var entity_player = entityWithSession as Player;
NullReferenceCheckHelper.throwIfNull(entity_player, () => $"entity_player is null !!!");
// 1. 기본 정보 체크
var request = (recvMessage as ClientToGame)?.Request.RePurchaseItemReq;
if (null == request)
{
err_msg = $"Failed to get Request !!! : {nameof(ClientToGame.Request.RePurchaseItemReq)}";
result.setFail(ServerErrorCode.InvalidArgument, err_msg);
Log.getLogger().error(result.toBasicString());
send_S2C_ACK_SHOP_RE_PURCHASE_LIST(entity_player, result, null);
return result;
}
result = await entity_player.runTransactionRunnerSafely(TransactionIdType.PrivateContents, "RePurchaseSoldItem", rePurchaseItemDelegate);
if (result.isFail())
{
err_msg = $"Failed to runTransactionRunnerSafely()!!! : {result.toBasicString()} - {entity_player.toBasicString()}";
Log.getLogger().error(err_msg);
send_S2C_ACK_SHOP_RE_PURCHASE_LIST(entity_player, result, null);
}
return result;
async Task<Result> rePurchaseItemDelegate() => await rePurchaseItemAsync(entity_player, request.ItemGuid);
}
private async Task<Result> rePurchaseItemAsync(Player entity_player, string item_guid)
{
var result = new Result();
string err_msg;
var shop_action = entity_player.getEntityAction<ShopAction>();
var sold_action = shop_action.getSolProductAction();
// 1. 재구매 아이템 체크
var sold_item = sold_action.findSoldProduct(item_guid);
if (null == sold_item)
{
err_msg = $"Fail to get item info () !!! : {nameof(ShopSoldProductAction.findSoldProduct)} - {item_guid}";
result.setFail(ServerErrorCode.NotFoundItemTableId, err_msg);
Log.getLogger().error(err_msg);
return result;
}
// 2. item 정보 체크
var item_attrib = sold_item.ItemDoc.getAttrib<ItemAttrib>();
NullReferenceCheckHelper.throwIfNull(item_attrib, () => $"item_attrib is null !!! - {entity_player.toBasicString()}");
(result, var item_data) = ShopHelper.checkItemIdFromTableData((int)item_attrib.ItemMetaId);
if (result.isFail()) return result;
NullReferenceCheckHelper.throwIfNull(item_data, () => $"item_data is null !!! - {entity_player.toBasicString()}");
// 3. 아이템 지급
var process_re_purchase = await shop_action.processRePurchase(item_data, sold_item);
if (process_re_purchase.result.isFail()) return process_re_purchase.result;
NullReferenceCheckHelper.throwIfNull(process_re_purchase.changed_item, () => $"process_re_purchase.changed_item is null !!! - {entity_player.toBasicString()}");
// 4. 재화 감소
result = await shop_action.processSpent(process_re_purchase.spent_currency_type, process_re_purchase.spent_currency);
if (result.isFail()) return result;
// 5. DB 갱신
var batch = new QueryBatchEx<QueryRunnerWithDocument>( entity_player, LogActionType.ShopRePurchase, GameServerApp.getServerLogic().getDynamoDbClient());
{
batch.addQuery(new DBQWriteToAttributeAllWithTransactionRunner());
batch.addQuery(new QueryFinal());
}
result = await QueryHelper.sendQueryAndBusinessLog(batch);
if (result.isFail()) return result;
send_S2C_ACK_SHOP_RE_PURCHASE_LIST(entity_player, result, new List<Item> { process_re_purchase.changed_item } );
return result;
}
}

View File

@@ -0,0 +1,221 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer.PacketHandler;
[PacketHandler(typeof(ClientToGameReq), typeof(ClientToGameReq.Types.C2GS_REQ_RENEWAL_SHOP_PRODUCTS), typeof(RenewalShopProductsPacketHandler), typeof(GameLoginListener))]
public class RenewalShopProductsPacketHandler : PacketRecvHandler
{
public override async Task<Result> onProcessPacket(ISession entityWithSession, IMessage recvMessage)
{
await Task.CompletedTask;
string err_msg = string.Empty;
CommonResult common_result = new();
var entity_player = entityWithSession as Player;
NullReferenceCheckHelper.throwIfNull(entity_player, () => "player is null !!!");
var result = new Result();
// 1. 기본 정보 체크
var request = (recvMessage as ClientToGame)!.Request.ReqRenewalShopProducts;
if (null == request)
{
err_msg = $"Failed to get request type !!! : {nameof(ClientToGame.Request.ReqRenewalShopProducts)}";
result.setFail(ServerErrorCode.InvalidArgument, err_msg);
Log.getLogger().error(result.toBasicString());
send_GS2C_ACK_REFRESH_SHOP_PRODUCTS(entity_player, result, null, common_result, 0, 0);
return result;
}
// 2. shop 정보 체크
var check = ShopHelper.checkShopIdFromTableData(request.ShopID);
if (check.result.isFail())
{
err_msg = $"Failed to check Shop Id from Table Data !!! : {request.ShopID}";
result.setFail(ServerErrorCode.NotFoundShopId, err_msg);
Log.getLogger().error(result.toBasicString());
send_GS2C_ACK_REFRESH_SHOP_PRODUCTS(entity_player, result, null, common_result, 0, 0);
return result;
}
NullReferenceCheckHelper.throwIfNull(check.shop_data, () => $"check.shop_data is null !!!, shopId : {request.ShopID}");
// 3. transaction 처리
var refresh_shop_products_func = async delegate()
{
var result = new Result();
var shop_id = check.shop_data.Id;
// 1. my shop product 체크
var action = entity_player.getEntityAction<ShopAction>();
NullReferenceCheckHelper.throwIfNull(action, () => $"ShopAction is null !!! - player:{entity_player.toBasicString()}");
var my_shop_product = action.getMyShopProduct(shop_id);
// 2.리뉴얼 안되는 상점이면 리턴
if (check.shop_data.is_Renewal == false)
{
result.setFail(ServerErrorCode.ShopProductCannotRenwal, $"this shop can not rewal shop Id : {shop_id}");
Log.getLogger().error(result.toBasicString());
return result;
}
// 3. attribute 가져오기
var attribute = my_shop_product.getEntityAttribute<ShopProductTradingMeterAttribute>();
if (null == attribute)
{
result.setFail(ServerErrorCode.EntityAttributeIsNull, $"Failed to getEntityAttribute() !!!: {nameof(ShopProductTradingMeterAttribute)}");
Log.getLogger().error(result.toBasicString());
return result;
}
//4.갱신 시간 전후로 1분 사이에는 갱신 못한다.
var is_renewallable_time = ShopHelper.checkRenewallableTime(attribute);
if (is_renewallable_time == false)
{
result.setFail(ServerErrorCode.ShopProductNotRenwalTime, $"this shop can not renewal shop Id : {shop_id}");
Log.getLogger().error(result.toBasicString());
return result;
}
//5. 현재 currentCount 가 maxCount보다 크거나 같으면 갱신 못한다.
if (attribute.CurrentRenewalCount >= check.shop_data.RenewalMaxCount)
{
result.setFail(ServerErrorCode.ShopProductRenewalCountAlreadyMax, $"shop renewal count already max currenct : {attribute.CurrentRenewalCount}, meta maxCount : {check.shop_data.RenewalMaxCount}");
Log.getLogger().error(result.toBasicString());
return result;
}
// 6. Shop data 갱신
var is_create = ShopHelper.renewalNewShopProductTradingMetersAttribute(entity_player.getUserGuid(), attribute, check.shop_data);
if (false == is_create)
{
var err_msg = $"Failed to create new shop product trading meter data !!! : {nameof(ShopHelper.createNewShopProductTradingMetersAttribute)} - {shop_id}";
result.setFail(ServerErrorCode.EntityActionNotFound, err_msg);
Log.getLogger().error(result.toBasicString());
return result;
}
// 7. 재화 차감
var currency_type_int = check.shop_data.RenewalCurrency;
var currency_value = check.shop_data.RenewalCurrencyValue;
var money_action = entity_player.getEntityAction<MoneyAction>();
NullReferenceCheckHelper.throwIfNull(money_action, () => $"money_action is null !!!");
var cirrency_type = MetaHelper.intToCurrencyType(currency_type_int);
result = await money_action.changeMoney(cirrency_type, -1 * currency_value);
if (result.isFail())
{
var err_msg = $"renewal shop product change money result is false !!! : {result.toBasicString()}";
Log.getLogger().error(err_msg);
return result;
}
// 6. db 갱신
var batch = new QueryBatchEx<QueryRunnerWithDocument>( entity_player, LogActionType.RenewalShopProducts, GameServerApp.getServerLogic().getDynamoDbClient(), true);
{
batch.addQuery(new DBQWriteToAttributeAllWithTransactionRunner());
batch.addQuery(new QueryFinal());
}
//로그 추가 해야된다.
batch.appendBusinessLog(new RenewalShopProductsBusinessLog(shop_id, check.shop_data.RenewalMaxCount, attribute.CurrentRenewalCount,
currency_type_int, currency_value, attribute.ShopProductTradingMeterSubs));
result = await QueryHelper.sendQueryAndBusinessLog(batch);
if (result.isFail()) return result;
//완료 됐으면 갱신 된 정보 전달
var found_transaction_runner = entity_player.findTransactionRunner(TransactionIdType.PrivateContents);
NullReferenceCheckHelper.throwIfNull(found_transaction_runner, () => $"found_transaction_runner is null !!! - {entity_player.toBasicString()}");
common_result = found_transaction_runner.getCommonResult();
var shop_action = entity_player.getEntityAction<ShopAction>();
NullReferenceCheckHelper.throwIfNull(shop_action, () => $"ShopAction is null !!! - player:{entity_player.toBasicString()}");
var shop_product = action.getMyShopProduct(check.shop_data.Id);
send_GS2C_ACK_REFRESH_SHOP_PRODUCTS(entity_player, result, shop_product, common_result, attribute.CurrentRenewalCount, check.shop_data.RenewalMaxCount);
return result;
};
result = await entity_player.runTransactionRunnerSafely(TransactionIdType.PrivateContents, "RefreshShopPoducts", refresh_shop_products_func);
if (result.isFail())
{
err_msg = $"Failed to runTransactionRunnerSafely()!!! : {result.toBasicString()} - {entity_player.toBasicString()}";
Log.getLogger().error(err_msg);
send_GS2C_ACK_REFRESH_SHOP_PRODUCTS(entity_player, result, null, common_result, 0, 0);
}
return result;
}
private static void send_GS2C_ACK_REFRESH_SHOP_PRODUCTS(Player owner, Result result, MyShopProduct? shop_product, CommonResult commonResult, Int32 currentCount, Int32 maxCount)
{
var ack_packet = new ClientToGame
{
Response = new ClientToGameRes
{
ErrorCode = result.ErrorCode,
AckRenewalShopProducts = new ClientToGameRes.Types.GS2C_ACK_RENEWAL_SHOP_PRODUCTS()
}
};
if (result.isSuccess())
{
ArgumentNullReferenceCheckHelper.throwIfNull(shop_product, () => $"shop_product is null !!! - player:{owner.toBasicString()}");
var attribute = shop_product.getOriginEntityAttribute<ShopProductTradingMeterAttribute>();
if (null == attribute)
{
ack_packet.Response.ErrorCode = ServerErrorCode.EntityAttributeIsNull;
Log.getLogger().error($"Fail to get entity attribute: {nameof(ShopProductTradingMeterAttribute)}");
result.setFail(ServerErrorCode.EntityAttributeIsNull);
}
ack_packet.Response.AckRenewalShopProducts.ProductInfo = new ShopPacketInfo
{
LeftTimeAsSecond = (int)(attribute!.EndTime - Timestamp.FromDateTime(DateTime.UtcNow)).Seconds
};
foreach (var meter in attribute.ShopProductTradingMeterSubs)
{
var info = new ShopItemInfo
{
ProductID = meter.ProductId,
LeftCount = meter.LeftCount
};
ack_packet.Response.AckRenewalShopProducts.ProductInfo.ShopItemList.Add(info);
}
ack_packet.Response.AckRenewalShopProducts.ProductInfo.CurrentRenewalCount = currentCount;
ack_packet.Response.AckRenewalShopProducts.ProductInfo.MaxRenewalCount = maxCount;
ack_packet.Response.AckRenewalShopProducts.CommonResult = commonResult;
}
GameServerApp.getServerLogic().onSendPacket(owner!, ack_packet);
}
}

View File

@@ -0,0 +1,200 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
using ITEM_GUID = System.String;
namespace GameServer.PacketHandler;
[PacketHandler(typeof(ClientToGameReq), typeof(ClientToGameReq.Types.SellItemReq), typeof(SellItemPacketHandler), typeof(GameLoginListener))]
public class SellItemPacketHandler : PacketRecvHandler
{
private static void send_S2C_ACK_SELL_MY_ITEM(Player? owner, Result result, ITEM_GUID item_guid, int sell_count)
{
var ack_packet = new ClientToGame
{
Response = new ClientToGameRes
{
ErrorCode = result.ErrorCode,
SellItemRes = new ClientToGameRes.Types.SellItemRes()
}
};
if (result.isSuccess())
{
ack_packet.Response.SellItemRes.ItemGuid = item_guid;
ack_packet.Response.SellItemRes.Count = sell_count;
var account_attribute = owner!.getOriginEntityAttribute<AccountAttribute>();
var level_attribute = owner.getOriginEntityAttribute<LevelAttribute>();
var money_attribute = owner.getOriginEntityAttribute<MoneyAttribute>();
var nickname_attribute = owner.getOriginEntityAttribute<NicknameAttribute>();
var char_info = new CharInfo
{
Level = (int)level_attribute!.Level,
Exp = (int)level_attribute.Exp,
Gold = money_attribute!.Gold,
Sapphire = money_attribute.Sapphire,
Calium = money_attribute.Calium,
Ruby = money_attribute.Ruby,
Usergroup = account_attribute!.AuthAdminLevelType.ToString(),
Operator = (int)account_attribute.AuthAdminLevelType,
DisplayName = nickname_attribute!.Nickname,
LanguageInfo = (int)account_attribute.LanguageType,
IsIntroComplete = 1
};
ack_packet.Response.SellItemRes.CurrencyInfo = char_info;
}
GameServerApp.getServerLogic().onSendPacket(owner!, ack_packet);
}
public override async Task<Result> onProcessPacket(ISession entityWithSession, IMessage recvMessage)
{
var result = new Result();
string err_msg;
var entity_player = entityWithSession as Player;
NullReferenceCheckHelper.throwIfNull(entity_player, () => $"entity_player is null !!!");
// 1. 기본 정보 체크
var request = (recvMessage as ClientToGame)?.Request.SellItemReq;
if (null == request)
{
err_msg = $"Failed to get Request !!! : {nameof(ClientToGame.Request.SellItemReq)}";
result.setFail(ServerErrorCode.InvalidArgument, err_msg);
Log.getLogger().error(result.toBasicString());
send_S2C_ACK_SELL_MY_ITEM(entity_player, result, string.Empty, 0);
return result;
}
var inventory_action = entity_player.getEntityAction<InventoryActionBase>();
var found_item = inventory_action.tryGetItemByItemGuid(request.ItemGuid);
var item_id = found_item?.getItemMeta()?.ItemId ?? 0;
if (item_id <= 0)
{
err_msg = $"Failed to get item_id !!! : {nameof(ClientToGame.Request.SellItemReq)}";
result.setFail(ServerErrorCode.InvalidArgument, err_msg);
Log.getLogger().error(result.toBasicString());
send_S2C_ACK_SELL_MY_ITEM(entity_player, result, string.Empty, 0);
return result;
}
result = await entity_player.runTransactionRunnerSafely(TransactionIdType.PrivateContents, "SellMyItem", sellItemDelegate);
if (result.isFail())
{
err_msg = $"Failed to runTransactionRunnerSafely()!!! : {result.toBasicString()} - {entity_player.toBasicString()}";
Log.getLogger().error(err_msg);
send_S2C_ACK_SELL_MY_ITEM(entity_player, result, string.Empty, 0);
return result;
}
await QuestManager.It.QuestCheck(entity_player, new QuestItem(EQuestEventTargetType.ITEM, EQuestEventNameType.SOLD, item_id));
return result;
async Task<Result> sellItemDelegate() =>
await sellItemAsync(entity_player, request.ItemGuid, request.Count);
}
private async Task<Result> sellItemAsync(Player player, string item_guid, int sell_count)
{
var result = new Result();
string err_msg;
var shop_action = player.getEntityAction<ShopAction>();
var inventory_action = player.getEntityAction<InventoryActionBase>();
// 1. 아이템 소유 확인
var found_item = inventory_action.tryGetItemByItemGuid(item_guid);
if (null == found_item)
{
err_msg = $"Failed to find item : {item_guid}";
result.setFail(ServerErrorCode.NotFoundItem, err_msg);
Log.getLogger().error(err_msg);
return result;
}
var found_attribute = found_item.getEntityAttribute<ItemAttributeBase>();
NullReferenceCheckHelper.throwIfNull(found_attribute, () => $"found_attribute is null !!!");
// 2. 아이템 판매 조건 체크
result = shop_action.checkItemSellConditionAsync(found_attribute, sell_count);
if (result.isFail()) return result;
// 3. 아이템 삭제
(result, var delete_item) = await inventory_action.tryDeleteItemByGuid(item_guid, (ushort)sell_count);
if (result.isFail())
{
err_msg = $"Failed to tryDeleteItem() !!! : {result.toBasicString()} - {item_guid} - {sell_count}";
Log.getLogger().error(err_msg);
return result;
}
var delete_item_attribute = delete_item?.getEntityAttribute<UserItemAttribute>();
if (null == delete_item_attribute)
{
err_msg = $"Failed to get item attribute : {nameof(UserItemAttribute)}";
result.setFail(ServerErrorCode.EntityAttributeIsNull, err_msg);
Log.getLogger().error(err_msg);
return result;
}
// 4. 재화 지급
// 4-1. item data 가져오기
var check_item = ShopHelper.checkItemIdFromTableData((int)delete_item_attribute.ItemMetaId);
if (check_item.result.isFail() || null == check_item.item_data)
{
Log.getLogger().error(check_item.result.ResultString);
return check_item.result;
}
// 4-2. 재화 지급
var money_action = player.getEntityAction<MoneyAction>();
var check_currency_type = ShopHelper.checkCurrencyTypeFromCurrencyId(check_item.item_data.SellId);
if (check_currency_type.result.isFail()) return check_currency_type.result;
result = await money_action.changeMoney(check_currency_type.currencyType, sell_count * check_item.item_data.SellPrice);
if (result.isFail()) return result;
// 5. sold list 의 item 수정
var sold_action = shop_action.getSolProductAction();
var item_doc = delete_item_attribute.makeDocBase();
var attrib = item_doc.getAttrib<ItemAttrib>();
NullReferenceCheckHelper.throwIfNull(attrib, () => $"attrib is null !!!");
attrib.ItemStackCount = (ushort)sell_count;
result = await sold_action.setSoldProduct(delete_item_attribute.ItemGuid, item_doc);
if (result.isFail()) return result;
// 6. DB 갱신
var batch = new QueryBatchEx<QueryRunnerWithDocument>( player, LogActionType.ShopSell, GameServerApp.getServerLogic().getDynamoDbClient());
batch.addQuery(new DBQWriteToAttributeAllWithTransactionRunner());
batch.addQuery(new QueryFinal());
result = await QueryHelper.sendQueryAndBusinessLog(batch);
if (result.isFail()) return result;
send_S2C_ACK_SELL_MY_ITEM(player, result, item_guid, delete_item_attribute.ItemStackCount);
return result;
}
}

View File

@@ -0,0 +1,232 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
using META_ID = System.UInt32;
namespace GameServer.PacketHandler;
[PacketHandler(typeof(ClientToGameReq), typeof(ClientToGameReq.Types.ShopPurchaseItemReq), typeof(ShopPurchaseItemPacketHandler), typeof(GameLoginListener))]
public class ShopPurchaseItemPacketHandler : PacketRecvHandler
{
private static void send_S2C_ACK_SHOP_PURCHASE_ITEM(Player owner, int shop_id, Result result, List<Item>? purchasedItems, List<Item>? spendItems)
{
var ack_packet = new ClientToGame
{
Response = new ClientToGameRes
{
ErrorCode = result.ErrorCode,
ShopPurchaseItemRes = new ClientToGameRes.Types.ShopPurchaseItemRes()
}
};
var purchase_action = owner.getEntityAction<ShopAction>().getMyShopProduct(shop_id)
.getEntityAction<PurchaseShopProductAction>();
if (null == purchase_action)
{
ack_packet.Response.ErrorCode = ServerErrorCode.EntityActionNotFound;
var err_msg = $"Fail to get entity action: {nameof(PurchaseShopProductAction)}";
Log.getLogger().error(err_msg);
result.setFail(ack_packet.Response.ErrorCode, err_msg);
}
if (result.isSuccess())
{
if (null != purchasedItems)
{
foreach (var item in purchasedItems.Select(info => info.toItemData4Client()))
{
ack_packet.Response.ShopPurchaseItemRes.Items.Add(item);
}
}
if (null != spendItems)
{
foreach (var del in spendItems.Select(info => info.toItemData4Client()))
{
ack_packet.Response.ShopPurchaseItemRes.DelItems.Add(del);
}
}
var account_attribute = owner.getOriginEntityAttribute<AccountAttribute>();
var level_attribute = owner.getOriginEntityAttribute<LevelAttribute>();
var money_attribute = owner.getOriginEntityAttribute<MoneyAttribute>();
var nickname_attribute = owner.getOriginEntityAttribute<NicknameAttribute>();
var char_info = new CharInfo
{
Level = (int)level_attribute!.Level,
Exp = (int)level_attribute.Exp,
Gold = money_attribute!.Gold,
Sapphire = money_attribute.Sapphire,
Calium = money_attribute.Calium,
Ruby = money_attribute.Ruby,
Usergroup = account_attribute!.AuthAdminLevelType.ToString(),
Operator = (int)account_attribute.AuthAdminLevelType,
DisplayName = nickname_attribute!.Nickname,
LanguageInfo = (int)account_attribute.LanguageType,
IsIntroComplete = 1
};
ack_packet.Response.ShopPurchaseItemRes.CurrencyInfo = char_info;
}
GameServerApp.getServerLogic().onSendPacket(owner, ack_packet);
}
public override async Task<Result> onProcessPacket(ISession entityWithSession, IMessage recvMessage)
{
var result = new Result();
string err_msg;
var entity_player = entityWithSession as Player;
NullReferenceCheckHelper.throwIfNull(entity_player, () => $"entity_player is null !!!");
// 1. 기본 정보 체크
var request = (recvMessage as ClientToGame)?.Request.ShopPurchaseItemReq;
if (null == request)
{
err_msg = $"Failed to get Request !!! : {nameof(ClientToGame.Request.ShopPurchaseItemReq)}";
result.setFail(ServerErrorCode.InvalidArgument, err_msg);
Log.getLogger().error(result.toBasicString());
send_S2C_ACK_SHOP_PURCHASE_ITEM(entity_player, 0, result, null, null);
return result;
}
var check = ShopHelper.checkShopIdFromTableData(request.ShopID);
if (check.result.isFail())
{
err_msg = $"Failed to check Shop Id from Table Data !!! : {request.ShopID}";
result.setFail(ServerErrorCode.NotFoundShopId, err_msg);
Log.getLogger().error(result.toBasicString());
send_S2C_ACK_SHOP_PURCHASE_ITEM(entity_player, request.ShopID, result, null, null);
return result;
}
// 2. 구매 로직 시행
result = await entity_player.runTransactionRunnerSafely(TransactionIdType.PrivateContents, "ShopPurchase", purchaseShopItemDelegate);
if (result.isFail())
{
err_msg = $"Failed to runTransactionRunnerSafely()!!! : {result.toBasicString()} - {entity_player.toBasicString()}";
Log.getLogger().error(err_msg);
send_S2C_ACK_SHOP_PURCHASE_ITEM(entity_player, request.ShopID, result, null, null);
return result;
}
if (true == MetaData.Instance._ShopProductMetaTable.TryGetValue(request.ProductID, out var shop_product_meta_data))
{
if (shop_product_meta_data.ProductData.Item is not null)
{
await QuestManager.It.QuestCheck(entity_player, new QuestItem(EQuestEventTargetType.ITEM, EQuestEventNameType.BOUGHT, shop_product_meta_data.ProductData.Item.Id));
}
}
return result;
async Task<Result> purchaseShopItemDelegate() =>
await purchaseShopItemAsync(entity_player, request.ShopID, request.ProductID, request.Count);
}
private async Task<Result> purchaseShopItemAsync(Player entity_player, int shop_id, int product_id, int purchase_count)
{
var result = new Result();
string err_msg;
var shop_purchase_info = new ShopPurchaseInfo();
shop_purchase_info.m_shop_id = shop_id;
shop_purchase_info.m_shop_product_id = product_id;
shop_purchase_info.m_shop_product_count = purchase_count;
// 0. action 가져오기
var purchase_action = entity_player.getEntityAction<ShopAction>().getMyShopProduct(shop_id).getEntityAction<PurchaseShopProductAction>();
if (null == purchase_action)
{
err_msg =
$"Failed to get EntityAction !!! : EntityActionType:PurchaseShopProductAction - {entity_player.toBasicString()}";
result.setFail(ServerErrorCode.EntityActionNotFound, err_msg);
Log.getLogger().error(result.toBasicString());
return result;
}
// 0. 구매 타입 체크 ( get discount type / discount rate )
var discount = purchase_action.checkPurchaseDiscountType(product_id);
// 1. 구매 조건 체크 : 상품 조건
var check_shop_product_conditions = purchase_action.checkPurchaseShopProductConditions(shop_id, product_id, purchase_count);
if (check_shop_product_conditions.result.isFail()) return check_shop_product_conditions.result;
NullReferenceCheckHelper.throwIfNull(check_shop_product_conditions.product_data, () => $"check_shop_product_conditions.product_data is null !!!");
// 2. 구매 조건 체크 : 캐릭터 조건
result = purchase_action.checkPurchaseCharacterConditions(check_shop_product_conditions.product_data);
if (result.isFail()) return result;
// 3. 구매 처리
result = await purchase_action.processPurchase(check_shop_product_conditions.product_data, purchase_count, discount.discount_rate, shop_purchase_info);
if (result.isFail()) return result;
NullReferenceCheckHelper.throwIfNull(shop_purchase_info.m_spent, () => $"shop_purchase_info.m_spent is null !!!");
NullReferenceCheckHelper.throwIfNull(shop_purchase_info.m_purchase, () => $"shop_purchase_info.m_purchase is null !!!");
// 4. 재화 소모
var spent = await purchase_action.processSpent(shop_purchase_info.m_spent);
if (spent.result.isFail()) return spent.result;
shop_purchase_info.m_purchase.m_spend_items = spent.del_items?.ToList();
// 5. 상점 물품 갱신
result = await purchase_action.updateShopProductMeter(product_id, purchase_count);
if (result.isFail()) return result;
// 6. 첫 구매 히스토리 갱신
if (check_shop_product_conditions.product_data.ProductData.Item != null)
{
result = await purchase_action.updateItemFirstPurchaseHistory(discount.discount_type, check_shop_product_conditions.product_data.ProductData.Item.Id);
if (result.isFail()) return result;
}
// 7. DB 갱신
var batch = new QueryBatchEx<QueryRunnerWithDocument>( entity_player, LogActionType.ShopPurchase
, GameServerApp.getServerLogic().getDynamoDbClient(), true);
{
batch.addQuery(new DBQWriteToAttributeAllWithTransactionRunner());
batch.addQuery(new QueryFinal());
}
// 8. Business Log 기록
writeBusinessLog(batch, shop_purchase_info);
result = await QueryHelper.sendQueryAndBusinessLog(batch);
send_S2C_ACK_SHOP_PURCHASE_ITEM(entity_player, shop_id, result, shop_purchase_info.m_purchase.m_purchase_items, shop_purchase_info.m_purchase.m_spend_items?.ToList());
return result;
}
private void writeBusinessLog(QueryBatchBase queryBatchBase, ShopPurchaseInfo shopPurchaseInfo)
{
// Shop 정보 기록
var shop_log_data = new ShopLogData
{
ShopMId = (META_ID)shopPurchaseInfo.m_shop_id,
ProductMId = (META_ID)shopPurchaseInfo.m_shop_product_id,
ProductCount = shopPurchaseInfo.m_shop_product_count
};
var shop_business_log = new ShopBusinessLog(shop_log_data);
queryBatchBase.appendBusinessLog(shop_business_log);
}
}

View File

@@ -0,0 +1,116 @@
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using ServerCore;
using ServerBase;
using ServerCommon;
using ServerCommon.BusinessLogDomain;
using MetaAssets;
namespace GameServer;
[ChatCommandAttribute("storereset", typeof(ChatCommandStoreReset), AuthAdminLevelType.Developer, AuthAdminLevelType.GmNormal, AuthAdminLevelType.GmSuper)]
internal class ChatCommandStoreReset : ChatCommandBase
{
public override async Task invoke(Player player, string token, string[] args)
{
var result = new Result();
var err_msg = string.Empty;
Log.getLogger().info($"HandleStoreReset");
var shop_action = player.getEntityAction<ShopAction>();
var server_logic = GameServerApp.getServerLogic();
var fn_transaction_runner = async delegate ()
{
var result = new Result();
await shop_action.cheatInitResetTime();
var batch = new QueryBatchEx<QueryRunnerWithDocument>( player, LogActionType.CheatCommandShopProductInit
, server_logic.getDynamoDbClient());
{
batch.addQuery(new DBQWriteToAttributeAllWithTransactionRunner());
}
result = await QueryHelper.sendQueryAndBusinessLog(batch);
if (result.isFail())
{
err_msg = $"Failed to sendQueryAndBusinessLog() !!! : {result.toBasicString()} - {player.toBasicString()}";
Log.getLogger().error(err_msg);
return result;
}
return result;
};
result = await player.runTransactionRunnerSafely(TransactionIdType.PrivateContents, "Cheat.ShopProductInit", fn_transaction_runner);
if (result.isFail())
{
err_msg = $"Failed to runTransactionRunnerSafely() !!! : {result.toBasicString()} - {player.toBasicString()}";
Log.getLogger().error(err_msg);
}
}
}
[ChatCommandAttribute("storerenewal", typeof(ChatCommandStoreRenewal), AuthAdminLevelType.Developer, AuthAdminLevelType.GmNormal, AuthAdminLevelType.GmSuper)]
internal class ChatCommandStoreRenewal : ChatCommandBase
{
public override async Task invoke(Player player, string token, string[] args)
{
var result = new Result();
var err_msg = string.Empty;
var shop_action = player.getEntityAction<ShopAction>();
var server_logic = GameServerApp.getServerLogic();
int shop_id = 0;
try
{
var arg = args[0];
shop_id = int.Parse(args[0]);
}
catch (Exception e)
{
Log.getLogger().error($"storerenewal parameter parse error {e.StackTrace}");
return;
}
var fn_transaction_runner = async delegate ()
{
var result = new Result();
await shop_action.cheatInitShopRenewalCount(shop_id);
var batch = new QueryBatchEx<QueryRunnerWithDocument>(player, LogActionType.CheatCommandShopProductRenewal
, server_logic.getDynamoDbClient());
{
batch.addQuery(new DBQWriteToAttributeAllWithTransactionRunner());
}
//로그 추가
batch.appendBusinessLog(new CheatRenewalShopProductBusinessLog(shop_id));
result = await QueryHelper.sendQueryAndBusinessLog(batch);
if (result.isFail())
{
err_msg = $"Failed to sendQueryAndBusinessLog() !!! : {result.toBasicString()} - {player.toBasicString()}";
Log.getLogger().error(err_msg);
return result;
}
return result;
};
result = await player.runTransactionRunnerSafely(TransactionIdType.PrivateContents, "Cheat.ShopProductRenewal", fn_transaction_runner);
if (result.isFail())
{
err_msg = $"Failed to runTransactionRunnerSafely() !!! : {result.toBasicString()} - {player.toBasicString()}";
Log.getLogger().error(err_msg);
}
}
}