Browse Source

Comparison mode on analysis refractored with slight performance issues. See TODO in AnalyticalService.cs line 93

pull/4/head
Benjamin Arhen 2 years ago
parent
commit
6ed45ef6d6
  1. 27
      Server/Controllers/AnalyticsController.cs
  2. 285
      Server/Services/AnalyticalService.cs
  3. 11
      Server/Services/AuthenticationService.cs
  4. 2
      Server/appsettings.json
  5. 4
      Shared/Interfaces/IAnalytics.cs
  6. 2
      Shared/Interfaces/IAuthService.cs
  7. 5
      Shared/Interfaces/ITokenService.cs
  8. 50
      Shared/ServiceRepo/TokenService.cs

27
Server/Controllers/AnalyticsController.cs

@ -12,11 +12,9 @@ namespace Biskilog_Accounting.Server.Controllers
[ApiController] [ApiController]
public class AnalyticsController : ControllerBase public class AnalyticsController : ControllerBase
{ {
private readonly ITokenService m_tokenService;
private readonly IAnalytics m_analyticService; private readonly IAnalytics m_analyticService;
public AnalyticsController(ITokenService tokenService, IAnalytics a_analytics) public AnalyticsController(IAnalytics a_analytics)
{ {
m_tokenService = tokenService;
m_analyticService = a_analytics; m_analyticService = a_analytics;
} }
@ -29,9 +27,6 @@ namespace Biskilog_Accounting.Server.Controllers
[HttpGet, Route("cancelledsales/{a_start}/{a_end}")] [HttpGet, Route("cancelledsales/{a_start}/{a_end}")]
public IEnumerable<CancelledSales> GetCancelledSalesAsync(DateTime a_start, DateTime a_end) public IEnumerable<CancelledSales> GetCancelledSalesAsync(DateTime a_start, DateTime a_end)
{ {
string token = Request.Headers[HeaderNames.Authorization]!;
m_analyticService.SetContraints(token);
return m_analyticService.GetCancelledSales(a_start, a_end); return m_analyticService.GetCancelledSales(a_start, a_end);
} }
/// <summary> /// <summary>
@ -43,9 +38,6 @@ namespace Biskilog_Accounting.Server.Controllers
[HttpGet, Route("sales/{a_start}/{a_end}")] [HttpGet, Route("sales/{a_start}/{a_end}")]
public IEnumerable<Tblcart> GetSalesAsync(DateTime a_start, DateTime a_end) public IEnumerable<Tblcart> GetSalesAsync(DateTime a_start, DateTime a_end)
{ {
string token = Request.Headers[HeaderNames.Authorization]!;
m_analyticService.SetContraints(token);
return m_analyticService.GetSalesTransaction(a_start, a_end); return m_analyticService.GetSalesTransaction(a_start, a_end);
} }
/// <summary> /// <summary>
@ -57,9 +49,6 @@ namespace Biskilog_Accounting.Server.Controllers
[HttpGet, Route("debtors")] [HttpGet, Route("debtors")]
public IEnumerable<InDebtCustomers> GetInDebtCustomers() public IEnumerable<InDebtCustomers> GetInDebtCustomers()
{ {
string token = Request.Headers[HeaderNames.Authorization]!;
m_analyticService.SetContraints(token);
return m_analyticService.GetInDebtCustomers(); return m_analyticService.GetInDebtCustomers();
} }
/// <summary> /// <summary>
@ -71,9 +60,6 @@ namespace Biskilog_Accounting.Server.Controllers
[HttpGet, Route("pricechanges/{a_start}/{a_end}")] [HttpGet, Route("pricechanges/{a_start}/{a_end}")]
public IEnumerable<ProductPriceChange> GetPriceChanges(DateTime a_start, DateTime a_end) public IEnumerable<ProductPriceChange> GetPriceChanges(DateTime a_start, DateTime a_end)
{ {
string token = Request.Headers[HeaderNames.Authorization]!;
m_analyticService.SetContraints(token);
return m_analyticService.GetPriceChanges(a_start, a_end); return m_analyticService.GetPriceChanges(a_start, a_end);
} }
/// <summary> /// <summary>
@ -85,9 +71,6 @@ namespace Biskilog_Accounting.Server.Controllers
[HttpGet, Route("employeesales/{a_start}/{a_end}")] [HttpGet, Route("employeesales/{a_start}/{a_end}")]
public Dictionary<string, List<SaleItem>> GetEmployeeSales(DateTime a_start, DateTime a_end) public Dictionary<string, List<SaleItem>> GetEmployeeSales(DateTime a_start, DateTime a_end)
{ {
string token = Request.Headers[HeaderNames.Authorization]!;
m_analyticService.SetContraints(token);
return m_analyticService.GetEmployeeSales(a_start, a_end); return m_analyticService.GetEmployeeSales(a_start, a_end);
} }
/// <summary> /// <summary>
@ -100,8 +83,7 @@ namespace Biskilog_Accounting.Server.Controllers
public IEnumerable<ProductItem> GetLowOnStockItems() public IEnumerable<ProductItem> GetLowOnStockItems()
{ {
string token = Request.Headers[HeaderNames.Authorization]!; string token = Request.Headers[HeaderNames.Authorization]!;
m_analyticService.SetContraints(token);
return m_analyticService.GetOutOfStockItems(); return m_analyticService.GetOutOfStockItems();
} }
/// <summary> /// <summary>
@ -113,10 +95,7 @@ namespace Biskilog_Accounting.Server.Controllers
[HttpGet, Route("mostpurchaseditem/{a_start}/{a_end}")] [HttpGet, Route("mostpurchaseditem/{a_start}/{a_end}")]
public IEnumerable<MostPurchasedItem> GetMostPurchased(DateTime a_start, DateTime a_end) public IEnumerable<MostPurchasedItem> GetMostPurchased(DateTime a_start, DateTime a_end)
{ {
string token = Request.Headers[HeaderNames.Authorization]!; return m_analyticService.GetMostPurchasedItem(a_start, a_end);
m_analyticService.SetContraints(token);
return m_analyticService.GetMostPurchasedItem(a_start, a_end);
} }
} }
} }

285
Server/Services/AnalyticalService.cs

@ -1,14 +1,9 @@
using Azure.Core; using Biskilog_Accounting.Server.POSModels;
using Biskilog_Accounting.Server.POSModels;
using Biskilog_Accounting.ServiceRepo;
using Biskilog_Accounting.Shared.CustomModels; using Biskilog_Accounting.Shared.CustomModels;
using Biskilog_Accounting.Shared.Interfaces; using Biskilog_Accounting.Shared.Interfaces;
using Biskilog_Accounting.Shared.POSModels; using Biskilog_Accounting.Shared.POSModels;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
using System.Data.Entity; using System.Data.Entity;
using System.Runtime.CompilerServices;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
namespace Biskilog_Accounting.Server.Services namespace Biskilog_Accounting.Server.Services
{ {
@ -19,135 +14,89 @@ namespace Biskilog_Accounting.Server.Services
{ {
private readonly BiskAcdbContext m_context; private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService; private readonly ITokenService m_tokenService;
private bool m_comparisonMode; private readonly HttpContext m_httpContext;
private string m_activeBranch;
public AnalyticalService(BiskAcdbContext a_context, ITokenService a_tokenService) public AnalyticalService(BiskAcdbContext a_context, ITokenService a_tokenService, IHttpContextAccessor a_httpContextAccessor)
{ {
m_context = a_context; m_context = a_context;
m_tokenService = a_tokenService; m_tokenService = a_tokenService;
m_httpContext = a_httpContextAccessor?.HttpContext;
} }
public IEnumerable<CancelledSales> GetCancelledSales(DateTime a_start, DateTime a_end) public IEnumerable<CancelledSales> GetCancelledSales(DateTime a_start, DateTime a_end)
{ {
//If in comparison mode, the list is fetched from all branchid of the business string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (m_comparisonMode) IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
{
return from cSale in m_context.Tblcancelledtransactions return from cSale in m_context.Tblcancelledtransactions
join aSale in m_context.Tblcarts on cSale.Transno equals aSale.Transno into activeSale join aSale in m_context.Tblcarts on cSale.Transno equals aSale.Transno into activeSale
join cPurchase in m_context.Tblcustomerpurchases on cSale.Transno equals cPurchase.TransactionId into customerSales join cPurchase in m_context.Tblcustomerpurchases on cSale.Transno equals cPurchase.TransactionId into customerSales
from c in customerSales.DefaultIfEmpty() from c in customerSales.DefaultIfEmpty()
join customer in m_context.Tblcustomers on c.CustomerId equals customer.CustomerId into Customers join customer in m_context.Tblcustomers on c.CustomerId equals customer.CustomerId into Customers
from cc in Customers.DefaultIfEmpty() from cc in Customers.DefaultIfEmpty()
where cSale.DateCancelled >= a_start && cSale.DateCancelled <= a_end where cSale.DateCancelled >= a_start && cSale.DateCancelled <= a_end && accessiblebranches.Contains(cSale.BranchId)
select new CancelledSales select new CancelledSales
{ {
CancelledTransaction = cSale, CancelledTransaction = cSale,
Value = activeSale.Sum(s => s.Total), Value = (from a in activeSale where accessiblebranches.Contains(a.BranchId) select a.Total).Sum(),
Customer = !String.IsNullOrEmpty(cc.CustomerId) ? $"{cc.Firstname} {cc.Surname}" : "Walk-IN Purchase" Customer = !String.IsNullOrEmpty(cc.CustomerId) ? $"{cc.Firstname} {cc.Surname}" : "Walk-IN Purchase"
}; };
}
else
{
return from cSale in m_context.Tblcancelledtransactions
join aSale in m_context.Tblcarts on cSale.Transno equals aSale.Transno into activeSale
join cPurchase in m_context.Tblcustomerpurchases on cSale.Transno equals cPurchase.TransactionId into customerSales
from c in customerSales.DefaultIfEmpty()
join customer in m_context.Tblcustomers on c.CustomerId equals customer.CustomerId into Customers
from cc in Customers.DefaultIfEmpty()
where cSale.DateCancelled >= a_start && cSale.DateCancelled <= a_end && cSale.BranchId == m_activeBranch
select new CancelledSales
{
CancelledTransaction = cSale,
Value = (from a in activeSale where a.BranchId == m_activeBranch select a.Total).Sum(),
Customer = !String.IsNullOrEmpty(cc.CustomerId) ? $"{cc.Firstname} {cc.Surname}" : "Walk-IN Purchase"
};
}
} }
public Dictionary<string, List<SaleItem>> GetEmployeeSales(DateTime a_start, DateTime a_end) public Dictionary<string, List<SaleItem>> GetEmployeeSales(DateTime a_start, DateTime a_end)
{ {
Dictionary<string, List<SaleItem>> sales = new Dictionary<string, List<SaleItem>>(); string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (m_comparisonMode) IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
{
var employeeSales = m_context.Tblcarts.Where(c => c.Date >= a_start && c.Date <= a_end).Select(e => e.Cashier).Distinct();
foreach (string employeeName in employeeSales) Dictionary<string, List<SaleItem>> sales = new Dictionary<string, List<SaleItem>>();
{ var employeeSales = m_context.Tblcarts.Where(c => c.Date >= a_start && c.Date <= a_end
var list = (from a in employeeSales && accessiblebranches.Contains(c.BranchId)).Select(e => e.Cashier).Distinct().ToList();
join c in m_context.Tblcarts on a equals c.Cashier into Sales
from s in Sales
group s by s.Transno into saleItem
select new SaleItem
{
Total = saleItem.Sum(c => c.Total),
Transno = saleItem.Key,
Cashier = employeeName,
Date = saleItem.First().Date,
Status = saleItem.First().Status,
BranchId = saleItem.First().BranchId
}).ToList();
sales.Add(employeeName, list);
} foreach (var employeeName in employeeSales)
}
else
{ {
var employeeSales = m_context.Tblcarts.Where(c => c.Date >= a_start && c.Date <= a_end && c.BranchId == m_activeBranch).Select(e => e.Cashier).Distinct().ToList(); var list = (from a in employeeSales
join c in m_context.Tblcarts on a equals c.Cashier into Sales
foreach (var employeeName in employeeSales) from s in Sales
{ group s by s.Transno into saleItem
var list = (from a in employeeSales select new SaleItem
join c in m_context.Tblcarts on a equals c.Cashier into Sales {
from s in Sales Total = saleItem.Sum(c => c.Total),
group s by s.Transno into saleItem Transno = saleItem.Key,
select new SaleItem Cashier = employeeName,
{ Date = saleItem.First().Date,
Total = saleItem.Sum(c => c.Total), Status = saleItem.First().Status,
Transno = saleItem.Key, BranchId = saleItem.First().BranchId
Cashier = employeeName, }).ToList();
Date = saleItem.First().Date, sales.Add(employeeName, list);
Status = saleItem.First().Status,
BranchId = saleItem.First().BranchId
}).ToList();
sales.Add(employeeName, list);
}
} }
return sales; return sales;
} }
public IEnumerable<InDebtCustomers> GetInDebtCustomers() public IEnumerable<InDebtCustomers> GetInDebtCustomers()
{ {
if (m_comparisonMode) string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
{ IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
var listDebts = m_context.Customeraccounts.Where(t => t.Balance < 0).OrderByDescending(d => d.Date).Select(t => t.CustomerId).Distinct().ToList();
foreach (var customerId in listDebts) var listDebts = m_context.Customeraccounts.Where(t => t.Balance < 0 && accessiblebranches.Contains(t.BranchId)).OrderByDescending(d => d.Date).Select(t => t.CustomerId).Distinct().ToList();
{ foreach (var customerId in listDebts)
yield return new InDebtCustomers
{
Customer = m_context.Tblcustomers.FirstOrDefault(i => i.CustomerId == customerId),
Debt = m_context.Customeraccounts.OrderByDescending(d => d.Date).FirstOrDefault(t => t.Balance < 0 && t.CustomerId == customerId).Balance,
};
}
}
else
{ {
var listDebts = m_context.Customeraccounts.Where(t => t.Balance < 0 && t.BranchId == m_activeBranch).OrderByDescending(d => d.Date).Select(t => t.CustomerId).Distinct().ToList(); yield return new InDebtCustomers
foreach (var customerId in listDebts)
{ {
yield return new InDebtCustomers Customer = m_context.Tblcustomers.FirstOrDefault(i => i.CustomerId == customerId),
{ Debt = m_context.Customeraccounts.OrderByDescending(d => d.Date).FirstOrDefault(t => t.Balance < 0 && t.CustomerId == customerId).Balance,
Customer = m_context.Tblcustomers.FirstOrDefault(i => i.CustomerId == customerId), };
Debt = m_context.Customeraccounts.OrderByDescending(d => d.Date).FirstOrDefault(t => t.Balance < 0 && t.CustomerId == customerId).Balance,
};
}
} }
} }
public IEnumerable<MostPurchasedItem> GetMostPurchasedItem(DateTime a_start, DateTime a_end) public IEnumerable<MostPurchasedItem> GetMostPurchasedItem(DateTime a_start, DateTime a_end)
{ {
//TODO either rewrite query or increase memory on server to deal with comparison mode performance issue
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
var items = (from s in m_context.Tblcarts var items = (from s in m_context.Tblcarts
join p in m_context.Tblproducts on s.Id equals p.Pcode join p in m_context.Tblproducts on s.Id equals p.Pcode
where s.Date >= a_start && s.Date <= a_end where s.Date >= a_start && s.Date <= a_end && s.BranchId == accessiblebranches.First()
group s by p into g group s by p into g
orderby g.Count() descending orderby g.Count() descending
select new MostPurchasedItem select new MostPurchasedItem
@ -162,100 +111,54 @@ namespace Biskilog_Accounting.Server.Services
public IEnumerable<ProductItem> GetOutOfStockItems() public IEnumerable<ProductItem> GetOutOfStockItems()
{ {
if (m_comparisonMode) string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
{ IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
return (from item in m_context.Tblinventories
join p in m_context.Tblproducts on item.Pcode equals p.Pcode return (from item in m_context.Tblinventories
join pu in m_context.Productaltunits on item.Pcode equals pu.Pcode into AltUnit join p in m_context.Tblproducts on item.Pcode equals p.Pcode
from au in AltUnit.DefaultIfEmpty() join pu in m_context.Productaltunits on item.Pcode equals pu.Pcode into AltUnit
join rs in m_context.Restocklevels on item.Pcode equals rs.ProductId from au in AltUnit.DefaultIfEmpty()
join un in m_context.Unitofmeasures on p.BaseUnit equals un.UnitCode join rs in m_context.Restocklevels on item.Pcode equals rs.ProductId
where p.Status!.ToLower() != "inactive" && join un in m_context.Unitofmeasures on p.BaseUnit equals un.UnitCode
((rs.WarnLevel >= item.Quantity && rs.Unit == p.BaseUnit) || (rs.WarnLevel >= (item.Quantity / au.QuantityUnit) && where p.Status!.ToLower() != "inactive" && accessiblebranches.Contains(item.BranchId) &&
rs.Unit == au.UnitCode) ((rs.WarnLevel >= item.Quantity && rs.Unit == p.BaseUnit) || (rs.WarnLevel >= (item.Quantity / au.QuantityUnit) &&
) rs.Unit == au.UnitCode)
select new ProductItem )
{ select new ProductItem
Product = p, {
Stock = item, Product = p,
BaseUnit = un.Unitshort! Stock = item,
}); BaseUnit = un.Unitshort!
} });
else
{
return (from item in m_context.Tblinventories
join p in m_context.Tblproducts on item.Pcode equals p.Pcode
join pu in m_context.Productaltunits on item.Pcode equals pu.Pcode into AltUnit
from au in AltUnit.DefaultIfEmpty()
join rs in m_context.Restocklevels on item.Pcode equals rs.ProductId
join un in m_context.Unitofmeasures on p.BaseUnit equals un.UnitCode
where p.Status!.ToLower() != "inactive" && item.BranchId == m_activeBranch &&
((rs.WarnLevel >= item.Quantity && rs.Unit == p.BaseUnit) || (rs.WarnLevel >= (item.Quantity / au.QuantityUnit) &&
rs.Unit == au.UnitCode)
)
select new ProductItem
{
Product = p,
Stock = item,
BaseUnit = un.Unitshort!
});
}
//return null;
} }
public IEnumerable<ProductPriceChange> GetPriceChanges(DateTime a_start, DateTime a_end) public IEnumerable<ProductPriceChange> GetPriceChanges(DateTime a_start, DateTime a_end)
{ {
if (m_comparisonMode) string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
{ IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
return from change in m_context.Tblpricechanges
join p in m_context.Tblproducts on change.Pcode equals p.Pcode return from change in m_context.Tblpricechanges
where change.ChangeDate >= a_start && change.ChangeDate <= a_end join p in m_context.Tblproducts on change.Pcode equals p.Pcode
select new ProductPriceChange where change.ChangeDate >= a_start && change.ChangeDate <= a_end && accessiblebranches.Contains(change.BranchId)
{ select new ProductPriceChange
BranchId = change.BranchId, {
ChangeDate = change.ChangeDate, BranchId = change.BranchId,
Pcode = change.Pcode, ChangeDate = change.ChangeDate,
CountId = change.CountId, Pcode = change.Pcode,
CurrentPrice = change.CurrentPrice, CountId = change.CountId,
PreviousPrice = change.PreviousPrice, CurrentPrice = change.CurrentPrice,
ProductName = p.ProductName PreviousPrice = change.PreviousPrice,
}; ProductName = p.ProductName
} };
else
{
return from change in m_context.Tblpricechanges
join p in m_context.Tblproducts on change.Pcode equals p.Pcode
where change.ChangeDate >= a_start && change.ChangeDate <= a_end && change.BranchId == m_activeBranch
select new ProductPriceChange
{
BranchId = change.BranchId,
ChangeDate = change.ChangeDate,
Pcode = change.Pcode,
CountId = change.CountId,
CurrentPrice = change.CurrentPrice,
PreviousPrice = change.PreviousPrice,
ProductName = p.ProductName
};
}
} }
public IEnumerable<Tblcart> GetSalesTransaction(DateTime a_start, DateTime a_end) public IEnumerable<Tblcart> GetSalesTransaction(DateTime a_start, DateTime a_end)
{ {
//If in comparison mode, the list is fetched from all branchid of the business string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (m_comparisonMode) IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
{
return m_context.Tblcarts.Where(t => t.Date >= a_start && t.Date <= a_end); return m_context.Tblcarts.Where(t => t.Date >= a_start && t.Date <= a_end && accessiblebranches.Contains(t.BranchId));
}
else
{
return m_context.Tblcarts.Where(t => t.Date >= a_start && t.Date <= a_end && t.BranchId == m_activeBranch);
}
}
public void SetContraints(string a_token)
{
m_comparisonMode = m_tokenService.GetComparison(a_token)!.Value;
m_activeBranch = m_tokenService.GetBaseBranch(a_token)!;
} }
} }
} }

11
Server/Services/AuthenticationService.cs

@ -55,12 +55,12 @@ namespace Biskilog_Accounting.Server.Services
List<int> businessIds = GetSiteaccesspermission(user.ClientId, user.UserId).Select(t => t.BusinessId).ToList(); List<int> businessIds = GetSiteaccesspermission(user.ClientId, user.UserId).Select(t => t.BusinessId).ToList();
Contract? contract = GetContract(user.ClientId, businessIds); Contract? contract = GetContract(user.ClientId, businessIds);
List<Clientbusiness> businesses = GetClientbusiness(user.ClientId); List<string> businesses = GetClientbusiness(user.ClientId, user.UserId).Select(t=>t.BusinessExternalId).ToList();
if (contract == null) if (contract == null)
return AuthEnums.Invalid.ToString(); return AuthEnums.Invalid.ToString();
return m_tokenService.GenerateToken(user, contract, databasemap, businesses[0], false); return m_tokenService.GenerateToken(user, contract, databasemap, businesses, false);
} }
/// <summary> /// <summary>
@ -95,9 +95,12 @@ namespace Biskilog_Accounting.Server.Services
throw new NotImplementedException(); throw new NotImplementedException();
} }
public List<Clientbusiness> GetClientbusiness(int a_clientId) public List<Clientbusiness> GetClientbusiness(int a_clientId, int userId)
{ {
return m_context.Clientbusinesses.Where(i => i.ClientId == a_clientId).ToList(); return (from b in m_context.Clientbusinesses
join p in m_context.Siteaccesspermissions on new {b.ClientId, b.BusinessId} equals new {p.ClientId, p.BusinessId}
where p.UserId == userId && p.ClientId == a_clientId
select b).ToList();
} }
public Databasemap GetClientDB(int a_clientId) public Databasemap GetClientDB(int a_clientId)

2
Server/appsettings.json

@ -7,7 +7,7 @@
}, },
"ConnectionStrings": { "ConnectionStrings": {
"Connection": "server=54.37.19.162;database=dev_biskilogclients;user=biskilog;password=mefbuk-6niFsu-fytrew", "Connection": "server=54.37.19.162;database=dev_biskilogclients;user=biskilog;password=mefbuk-6niFsu-fytrew",
"PrivateConnection": "server={0};database={1};user=biskilog;password=mefbuk-6niFsu-fytrew" "PrivateConnection": "server={0};database={1};user=biskilog;password=mefbuk-6niFsu-fytrew;default command timeout=0;"
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"JWT": { "JWT": {

4
Shared/Interfaces/IAnalytics.cs

@ -27,7 +27,7 @@ namespace Biskilog_Accounting.Shared.Interfaces
/// <param name="a_start"></param> /// <param name="a_start"></param>
/// <param name="a_end"></param> /// <param name="a_end"></param>
/// <returns></returns> /// <returns></returns>
IEnumerable<MostPurchasedItem> GetMostPurchasedItem(DateTime a_start, DateTime a_end); IEnumerable<MostPurchasedItem> GetMostPurchasedItem(DateTime a_start, DateTime a_end);
/// <summary> /// <summary>
/// Fetches a collection of cancelled transaction within a specified date range /// Fetches a collection of cancelled transaction within a specified date range
/// </summary> /// </summary>
@ -49,6 +49,6 @@ namespace Biskilog_Accounting.Shared.Interfaces
/// <param name="a_end"></param> /// <param name="a_end"></param>
/// <returns></returns> /// <returns></returns>
IEnumerable<ProductPriceChange> GetPriceChanges(DateTime a_start, DateTime a_end); IEnumerable<ProductPriceChange> GetPriceChanges(DateTime a_start, DateTime a_end);
void SetContraints(string a_token); //void SetContraints(string a_token);
} }
} }

2
Shared/Interfaces/IAuthService.cs

@ -14,6 +14,6 @@ namespace Biskilog_Accounting.Shared.Interfaces
Contract? GetContract(int a_clientId, List<int> a_businessId); Contract? GetContract(int a_clientId, List<int> a_businessId);
Databasemap GetClientDB(int a_clientId); Databasemap GetClientDB(int a_clientId);
List<Siteaccesspermission> GetSiteaccesspermission(int a_clientId, int a_userId); List<Siteaccesspermission> GetSiteaccesspermission(int a_clientId, int a_userId);
List<Clientbusiness> GetClientbusiness(int a_clientId); List<Clientbusiness> GetClientbusiness(int a_clientId, int userId);
} }
} }

5
Shared/Interfaces/ITokenService.cs

@ -6,12 +6,13 @@ namespace Biskilog_Accounting.Shared.Interfaces
public interface ITokenService public interface ITokenService
{ {
AuthEnums ValidateToken(string a_token); AuthEnums ValidateToken(string a_token);
string GenerateToken(Userauth a_user, Contract a_clientContract, Databasemap a_database, Clientbusiness a_business, bool a_comparison); string GenerateToken(Userauth a_user, Contract a_clientContract, Databasemap a_database, List<string> a_business, bool a_comparison);
int? GetDatabaseIdFromToken(string a_token); int? GetDatabaseIdFromToken(string a_token);
int? GetUserIdFromToken(string a_token); int? GetUserIdFromToken(string a_token);
string? GetUserNameFromToken(string a_token); string? GetUserNameFromToken(string a_token);
string? GetBaseBranch(string a_token); string? GetBaseBranch(string a_token);
bool? GetComparison(string a_token); bool? GetComparison(string a_token);
IEnumerable<string> BranchIds(string a_token);
string? GetAllBranch(string a_token);
} }
} }

50
Shared/ServiceRepo/TokenService.cs

@ -43,7 +43,7 @@ namespace Biskilog_Accounting.ServiceRepo
/// Generates an access token based on the user /// Generates an access token based on the user
/// </summary> /// </summary>
/// <returns>A tokenized string</returns> /// <returns>A tokenized string</returns>
public string GenerateToken(Userauth a_user, Contract a_clientContract, Databasemap a_database, Clientbusiness a_business, bool a_comparison) public string GenerateToken(Userauth a_user, Contract a_clientContract, Databasemap a_database, List<string> a_business, bool a_comparison)
{ {
try try
{ {
@ -57,7 +57,8 @@ namespace Biskilog_Accounting.ServiceRepo
new Claim("Username", a_user.Username.ToString()), new Claim("Username", a_user.Username.ToString()),
new Claim("DbId",a_database.DbNo.ToString()), new Claim("DbId",a_database.DbNo.ToString()),
new Claim("ComparisonMode",a_comparison.ToString()), new Claim("ComparisonMode",a_comparison.ToString()),
new Claim("BranchId",a_business.BusinessExternalId.ToString()), new Claim("BranchId",a_business[0].ToString()),
new Claim("BranchAccess",string.Join(", ", a_business.ToArray())),
new Claim("ClientId", a_user.ClientId.ToString()), new Claim("ClientId", a_user.ClientId.ToString()),
}; };
@ -150,5 +151,50 @@ namespace Biskilog_Accounting.ServiceRepo
} }
return null; return null;
} }
/// <summary>
///Deserializes the token string if valid to return the specified list of branches a user has access to in the token string
/// </summary>
/// <param name="a_token"></param>
/// <returns>Username</returns>
public string? GetAllBranch(string a_token)
{
if (ValidateToken(a_token) == AuthEnums.Valid)
{
string token = a_token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return jwtToken.Claims.First(claim => claim.Type == "BranchAccess").Value;
}
return null;
}
/// <summary>
/// Return a specified list of branches a user has access if comparison mode is set otherwise returns only the
/// active branch on the list
/// </summary>
/// <param name="a_token"></param>
/// <returns></returns>
public IEnumerable<string> BranchIds(string a_token)
{
List<string> branchIds = new List<string>();
if (ValidateToken(a_token) == AuthEnums.Valid)
{
bool comparison = GetComparison(a_token)!.Value;
if (comparison)
{
string? branches = GetAllBranch(a_token);
if (branches != null)
{
string[] branchArray = branches!.Split();
branchIds.AddRange(branchArray);
}
}
else
{
string? baseBranch = GetBaseBranch(a_token);
branchIds.Add(baseBranch!);
}
}
return branchIds.AsEnumerable();
}
} }
} }

Loading…
Cancel
Save