在遊戲網站上,每筆儲值或是消費,都會有一筆記錄,有的網站會從交易記錄中算出目前這個使用者的點數餘額,因為相對來說會比較準確,但相對時間一長,這個計算量就會變大,所以適時的壓縮筆數是很重要的。

接下來的程式碼單純是本人的突然奇想,先看下列的類別宣告:

public enum TransactionType
{
    Deposit,
    Withdrawal,
    Used,
    Winning,
    History, // after the settlement, for the history record
    Settlement, // for the settlement record
}

public class TransactionRecord
{
    public string TransactionId { get; set; } = Guid.NewGuid().ToString();
    public decimal Amount { get; set; }
    public DateTime? SettlementDate { get; set; } = null;
    public DateTime Date { get; set; }
    public string Description { get; set; } = string.Empty;
    public TransactionType Type { get; set; }

    public async Task Settle(List<TransactionRecord> records)
    {
        // Calculate the total amount for the settlement
        decimal totalAmount = 0;
        foreach (var record in records)
        {
            totalAmount += record.Amount;
            record.SettlementDate = DateTime.Now;
            record.Type = TransactionType.History; // Mark as history after settlement
            record.Description = "Settled Transaction";
        }

        Amount = totalAmount;
        SettlementDate = DateTime.Now;
        Date = DateTime.Now;
        Description = "Zip Transaction";
        Type = TransactionType.Settlement;
    }
}

其中的method:Settle,做的事很單純,就是把舊資料標記為歷史記錄,並更新自身的狀態(例如餘客)。

接下來是測試程式碼:

DateTime startDate = new DateTime(2024, 1, 1);
DateTime endDate = new DateTime(2026, 6, 18);
//Test Data
List<TransactionRecord> transactions = new List<TransactionRecord>
{
    new TransactionRecord { Amount = 100.50m, Date = new DateTime(2024, 2, 15), Description = "Grocery Shopping" },
    new TransactionRecord { Amount = 250.00m, Date = new DateTime(2024, 3, 10), Description = "Electronics Purchase" },
    new TransactionRecord { Amount = 75.25m, Date = new DateTime(2024, 4, 5), Description = "Restaurant Bill" },
    new TransactionRecord { Amount = 500.00m, Date = new DateTime(2024, 5, 20), Description = "Rent Payment" },
    new TransactionRecord { Amount = 120.00m, Date = new DateTime(2024, 6, 18), Description = "Utility Bill" }
};

List<TransactionRecord> settlementTransactions = transactions
    .Where(t => t.Date >= startDate && t.Date <= endDate)
    .ToList();

TransactionRecord record = new TransactionRecord();
await record.Settle(settlementTransactions);

可以看到把過去的資料抓出來,然後再呼叫Settle即可,這類型的工作其實做成定時Job即可,處理的資料盡量不要抓太近期的,以免影響到近期交易記錄的查詢,因為近期的交易有時可能出錯,需要線上人員做處理。