Home > Blockchain >  How to get total annual sales
How to get total annual sales

Time:10-04

In my ASP.NET Core 6 Web API, I have used the code below to calculate Total Annual Sales (from Transactions):

private async Task<decimal> GetAllTotalMonthlyTransactions()
{
    string transactionMonth = DateTime.Now.ToString("MM");
    decimal totalMonthlyTransactions = 0;

    var sales = await _dbContext.Sales.ToListAsync();

    foreach (var item in saless)
    {
        var salesDate = item.CreatedAt.ToString();
        var salesMonth = salesDate.Substring(3, 2);

        if (transactionMonth == salesMonth)
        {
            totalMonthlyTransactions  = item.Amount;
        }
    }

    return totalMonthlyTransactions;
}

How to I re-write the code above to get TotalAnnualSales (Transactions)?

CodePudding user response:

Instead of converting the datetimes to strings, try accessing them as ints. You can do this with .Month or .Year respectively

CodePudding user response:

You can try to calculate from and to date range based on a specified month, then query/filter sales data with these from and to date range, like below.

var date1 = DateTime.Now;
var days = DateTime.DaysInMonth(date1.Year, date1.Month);

var from = new DateTime(date1.Year, date1.Month, 1, 0, 0, 0);
var to = new DateTime(date1.Year, date1.Month, days, 23, 59, 59);          

var totalMonthlyTransactions = sales.AsEnumerable().Where(s => s.CreatedAt >= from && s.CreatedAt <= to).Select(s => s.Amount).Sum();
        

CodePudding user response:

private async Task<decimal> GetAllTotalMonthlyTransactions()
{
    int currentYear  = DateTime.Now.Year;

    return (await dbContext.Sales.Where(t=>t.CreatedAt.Year==currentYear).ToListAsync()).Sum();

}

CodePudding user response:

I hope following code will work for you...

private async Task<IEnumerable<object>> GetMonthlyTransactions(int year)
    {
        var starting = new DateTime(year, 1, 1).Date;
        var sales = await context.Sales.Where(f => f.SalesDate >= starting).Select(s => new
        {
            Date = s.SalesDate.ToString("MM-yyyy"),
            Amount = s.NetAmount
        }).ToListAsync();
        var finaldata = sales.GroupBy(s => s.Date, (d, a) => new { Date = d, Am = a }).Select(l => new
        {
            Date = l.Date,
            Amount = l.Am.Sum(h => h.Amount)
        });
        return finaldata;
       
    }
  • Related