Skip to content

Commit

Permalink
Just some minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
RenderBr committed Dec 14, 2023
1 parent 8824ff0 commit 1391267
Show file tree
Hide file tree
Showing 9 changed files with 105 additions and 62 deletions.
8 changes: 4 additions & 4 deletions TSEconomy/Configuration/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace TSEconomy.Configuration
[JsonObject(MemberSerialization.OptIn)]
public class Configuration
{
private static string s_path = Path.Combine(TSEconomy.PluginDirectory, "TSEconomy.json");
private static string configPath = Path.Combine(TSEconomy.PluginDirectory, "TSEconomy.json");
public static Configuration Instance { get; set; }

[JsonProperty("UseMySQL", Order = 0)]
Expand All @@ -31,9 +31,9 @@ public class Configuration

public static void Load()
{
if (File.Exists(s_path))
if (File.Exists(configPath))
{
string json = File.ReadAllText(s_path);
string json = File.ReadAllText(configPath);
try
{
Instance = JsonConvert.DeserializeObject<Configuration>(json);
Expand All @@ -56,7 +56,7 @@ public static void Save()
if (!Directory.Exists(TSEconomy.PluginDirectory))
Directory.CreateDirectory(TSEconomy.PluginDirectory);

File.WriteAllText(s_path, JsonConvert.SerializeObject(Instance, Formatting.Indented));
File.WriteAllText(configPath, JsonConvert.SerializeObject(Instance, Formatting.Indented));
}
}
}
8 changes: 4 additions & 4 deletions TSEconomy/Database/Database.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ public void InitializeDB(bool useMySQL, string customSQLitePath = "")
}
catch (Exception ex)
{
TShock.Log.Info(Localization.TryGetString("TSEconomy experienced a database error! (MySQL)", "InitializeDB"));
TShock.Log.Info(ex.Message);
TShock.Log.ConsoleError(Localization.TryGetString("TSEconomy experienced a database error! (MySQL)", "InitializeDB"));
TShock.Log.ConsoleError(ex.Message);
}

}
Expand All @@ -57,8 +57,8 @@ public void InitializeDB(bool useMySQL, string customSQLitePath = "")
}
catch (Exception ex)
{
TShock.Log.Info(Localization.TryGetString("TSEconomy experienced a database error! (SQLite)", "InitializeDB"));
TShock.Log.Info(ex.Message);
TShock.Log.ConsoleError(Localization.TryGetString("TSEconomy experienced a database error! (SQLite)", "InitializeDB"));
TShock.Log.ConsoleError(ex.Message);
}

}
Expand Down
78 changes: 49 additions & 29 deletions TSEconomy/Database/Models/BankAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@

namespace TSEconomy.Database.Models
{
/// <summary>
/// Represents a user's bank account, tied to a currency in database
/// </summary>
[TableName("BankAccounts")]
[PrimaryKey("ID")]
public class BankAccount
Expand All @@ -32,6 +35,15 @@ public class BankAccount

public double Balance { get { return _balance; } private set { } }

/// <summary>
/// Attempts to create a new bank account for the specified user, with the specified currency.
/// </summary>
/// <param name="initialbalance">Starting balance for bank account</param>
/// <param name="internalCurrencyName">The internal currency ID</param>
/// <param name="userID">TShock UserAccount's ID</param>
/// <param name="flags">BankAccount properties</param>
/// <param name="transLog">Transaction message for logging</param>
/// <returns></returns>
public static BankAccount? TryCreateNewAccount(double initialbalance, string internalCurrencyName, int userID, BankAccountProperties flags = BankAccountProperties.Default,
string transLog = "{0} has created a new bank account ({1}), with the initial value of {2}.")
{
Expand Down Expand Up @@ -72,48 +84,56 @@ public class BankAccount

}

// we have two variants as we might not want the logs to show -amount
public bool TryAddBalance(double amount, string transLog = "{0}'s balance has been increased by {1}. Old bal: {2} new bal: {3}")
/// <summary>
/// Attempts to modify the balance of the bank account.
/// </summary>
/// <param name="amount">The amount to increment/reduce by</param>
/// <param name="operationType">Whether the option is an adding or subtraction operation</param>
/// <param name="transLog">Overrides default transaction log message</param>
/// <returns>Whether the transaction can be completed</returns>
public bool TryModifyBalance(double amount, BalanceOperation operationType, string transLog = null)

Check warning on line 94 in TSEconomy/Database/Models/BankAccount.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
{
if (transLog == "{0}'s balance has been increased by {1}. Old bal: {2} new bal: {3}")
transLog = Localization.TryGetString("{0}'s balance has been increased by {1}. Old bal: {2} new bal: {3}");

if (amount < 0)
return TryAddBalance(-amount, transLog);

_balance += amount;

Api.UpdateBankAccount(this);

if (IsWorldAccount())
return true;
if (operationType == BalanceOperation.Add)
{
transLog ??= Localization.TryGetString("{0}'s balance has been increased by {1}. Old bal: {2} new bal: {3}");

Api.AddTransaction(UserID, InternalCurrencyName, amount, transLog.SFormat(Helpers.GetAccountName(UserID), amount, Balance - amount, Balance),
TransactionProperties.Add);
if (amount < 0)
return false;

return true;
}
_balance += amount;
}
else if(operationType == BalanceOperation.Subtract)
{
transLog ??= Localization.TryGetString("{0}'s balance has been decreased by {1}. Old bal: {2} new bal: {3}");

public bool TryRemoveBalance(double amount, string transLog = "{0}'s balance has been decreased by {1}. Old bal: {2} new bal: {3}")
{
if (transLog == "{0}'s balance has been decreased by {1}. Old bal: {2} new bal: {3}")
transLog = Localization.TryGetString("{0}'s balance has been decreased by {1}. Old bal: {2} new bal: {3}");
if (_balance < amount && !IsWorldAccount())
return false;

if (_balance < amount && !IsWorldAccount())
_balance -= amount;
}
else
{
return false;
}

_balance -= amount;
Api.UpdateBankAccount(this);

if (IsWorldAccount())
return true;

Api.AddTransaction(UserID, InternalCurrencyName, amount, transLog.SFormat(Helpers.GetAccountName(UserID), amount, Balance + amount, Balance),
TransactionProperties.Add);
if (!IsWorldAccount())
{
if (operationType == BalanceOperation.Add)
{
Api.AddTransaction(UserID, InternalCurrencyName, amount, transLog.SFormat(Helpers.GetAccountName(UserID), amount, Balance - amount, Balance), TransactionProperties.Add);
}
else
{
Api.AddTransaction(UserID, InternalCurrencyName, amount, transLog.SFormat(Helpers.GetAccountName(UserID), amount, Balance + amount, Balance), TransactionProperties.Add);
}
}

return true;
}


// UNDONE
/// <summary>
/// once implemented we'll want tryremovebalance and tryaddbalance to use it to with the world account.
Expand Down
8 changes: 8 additions & 0 deletions TSEconomy/Database/Models/Properties/BalanceOperation.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace TSEconomy.Database.Models.Properties
{
public enum BalanceOperation
{
Add,
Subtract
}
}
3 changes: 3 additions & 0 deletions TSEconomy/Database/Models/Properties/TransactionProperties.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
namespace TSEconomy.Database.Models.Properties
{
/// <summary>
/// Flags that determine a transaction type
/// </summary>
public enum TransactionProperties
{
Set,
Expand Down
33 changes: 18 additions & 15 deletions TSEconomy/Database/Models/Transaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@

namespace TSEconomy.Database.Models
{
/// <summary>
/// Represents a transaction in the database.
/// </summary>
[TableName("Transactions")]
[PrimaryKey("ID")]
public class Transaction
Expand All @@ -27,25 +30,25 @@ public class Transaction

[Column("Flags")]
public TransactionProperties Flags { get; set; }

public Transaction(int UserID, string internalCurrencyName, double amountChanged, string transDetails, DateTime timeStamp, TransactionProperties flags)
public Transaction(int userId, string internalCurrencyName, double amountChanged, string transDetails, DateTime timeStamp, TransactionProperties flags)
{
this.UserID = UserID;
this.InternalCurrencyName = internalCurrencyName;
this.Amount = amountChanged;
this.TransactionDetails = transDetails;
this.Timestamp = timeStamp;
this.Flags = flags;
UserID = userId;
InternalCurrencyName = internalCurrencyName;
Amount = amountChanged;
TransactionDetails = transDetails;
Timestamp = timeStamp;
Flags = flags;
}

public Transaction(int UserID, string internalCurrencyName, double amountChanged, string transDetails, TransactionProperties flags)
public Transaction(int userId, string internalCurrencyName, double amountChanged, string transDetails, TransactionProperties flags)
{
this.UserID = UserID;
this.InternalCurrencyName = internalCurrencyName;
this.Amount = amountChanged;
this.TransactionDetails = transDetails;
this.Timestamp = DateTime.UtcNow;
this.Flags = flags;
UserID = userId;
InternalCurrencyName = internalCurrencyName;
Amount = amountChanged;
TransactionDetails = transDetails;
Timestamp = DateTime.UtcNow;
Flags = flags;
}
}
}
27 changes: 18 additions & 9 deletions TSEconomy/Database/SqlGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,28 @@ public static string GenerateCreateTableStatement(Type type, DBType dbProvider)

return sb.ToString();
}

private static string GetColumnType(Type type, DBType dbProvider)
{
// Simplified mapping, needs to be expanded based on actual requirements
if (type == typeof(int) || type == typeof(BankAccountProperties)
|| type == typeof(TransactionProperties)) return "INTEGER";
if (type == typeof(double)) return "REAL";
if (type == typeof(string)) return dbProvider == DBType.SQLite ? "TEXT" : "VARCHAR(255)";
if (type == typeof(DateTime)) return "DATETIME";
if (type == typeof(byte[])) return "BLOB";
if (type == typeof(bool)) return dbProvider == DBType.MySQL ? "BOOLEAN" : "INTEGER";
var supportedTypeMappings = new Dictionary<Type, string>
{
{ typeof(int), "INTEGER" },
{ typeof(BankAccountProperties), "INTEGER" },
{ typeof(TransactionProperties), "INTEGER" },
{ typeof(double), "REAL" },
{ typeof(string), dbProvider == DBType.SQLite ? "TEXT" : "VARCHAR(255)" },
{ typeof(DateTime), "DATETIME" },
{ typeof(byte[]), "BLOB" },
{ typeof(bool), dbProvider == DBType.MySQL ? "BOOLEAN" : "INTEGER" }
};

if (supportedTypeMappings.TryGetValue(type, out var columnType))
{
return columnType;
}

throw new NotSupportedException($"Type {type} not supported.");
}


}
}
1 change: 0 additions & 1 deletion TSEconomy/Lang/Localization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ private static void getFileName(out string name)
else
{
name = "Lang_en.xml";

TShock.Log.ConsoleError($"[TSEconomy Lang] Set value of the 'Language' property in configs is not valid, defaulting to 'en-CA'.\n here are the supported languages: {string.Join(", ", SupportedLanguages)}");
}
}
Expand Down
1 change: 1 addition & 0 deletions TSEconomy/TSEconomy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public override void Initialize()

public static void OnInitialize(EventArgs args)
{
// initialize localization files
Localization.SetupLanguage();

// register commands
Expand Down

0 comments on commit 1391267

Please sign in to comment.