diff --git a/src/hihapi/Controllers/Finance/FinanceReportsController.cs b/src/hihapi/Controllers/Finance/FinanceReportsController.cs index 1ea9f7c..3e2c9bb 100644 --- a/src/hihapi/Controllers/Finance/FinanceReportsController.cs +++ b/src/hihapi/Controllers/Finance/FinanceReportsController.cs @@ -10,7 +10,7 @@ using Microsoft.AspNetCore.OData.Formatter; using System.Threading.Tasks; -namespace hihapi.Controllers.Finance +namespace hihapi.Controllers { [Authorize] public class FinanceReportsController : ODataController @@ -55,9 +55,7 @@ public IActionResult GetReportByTranType([FromBody] ODataActionParameters parame { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) - { throw new UnauthorizedAccessException(); - } } catch { @@ -67,9 +65,7 @@ public IActionResult GetReportByTranType([FromBody] ODataActionParameters parame // 2. Check the Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == hid && p.User == usrName).Count(); if (hms <= 0) - { throw new UnauthorizedAccessException(); - } // 3. Calculate the amount DateTime dtlow = new DateTime(year, month == null ? 1 : month.Value, 1); @@ -107,7 +103,15 @@ public IActionResult GetReportByTranType([FromBody] ODataActionParameters parame return Ok(listResult); } - + + /// + /// Get report by Account + /// + /// + /// HomeID: Home ID + /// + /// + /// [HttpPost] public IActionResult GetReportByAccount([FromBody]ODataActionParameters parameters) { @@ -133,9 +137,7 @@ public IActionResult GetReportByAccount([FromBody]ODataActionParameters paramete { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) - { throw new UnauthorizedAccessException(); - } } catch { @@ -145,9 +147,7 @@ public IActionResult GetReportByAccount([FromBody]ODataActionParameters paramete // 2. Check the Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == hid && p.User == usrName).Count(); if (hms <= 0) - { throw new UnauthorizedAccessException(); - } // 3. Calculate the amount var results = ( @@ -157,7 +157,7 @@ on docitem.DocID equals docheader.ID join trantype in _context.FinTransactionType on docitem.TranType equals trantype.ID join account in _context.FinanceAccount - on new { docitem.AccountID, IsNormal = true } equals new { AccountID = account.ID, IsNormal = account.Status == null || account.Status == (byte)FinanceAccountStatus.Normal } + on new { docitem.AccountID, IsNormal = true } equals new { AccountID = account.ID, IsNormal = account.Status == null || account.Status == (byte)FinanceAccountStatus.Normal } where docheader.HomeID == hid select new { @@ -181,7 +181,7 @@ into docitem2 UseCurr2 = docitem3.Key.UseCurr2, ExgRate = docitem3.Key.ExgRate, ExgRate2 = docitem3.Key.ExgRate2, - TranAmount = docitem3.Sum(p => p.TranAmount) + TranAmount = docitem3.Sum(p => (Double)p.TranAmount) }).ToList(); List listResults = new List(); @@ -195,14 +195,14 @@ into docitem2 { if (rst.ExgRate2 != null && rst.ExgRate2.GetValueOrDefault() > 0) { - amountLC *= rst.ExgRate2.GetValueOrDefault(); + amountLC *= (Double)rst.ExgRate2.GetValueOrDefault(); } } else { if (rst.ExgRate != null && rst.ExgRate.GetValueOrDefault() > 0) { - amountLC *= rst.ExgRate.GetValueOrDefault(); + amountLC *= (Double)rst.ExgRate.GetValueOrDefault(); } } @@ -214,18 +214,18 @@ into docitem2 nrst.HomeID = hid; nrst.AccountID = rst.AccountID; if (rst.IsExpense) - nrst.CreditBalance += amountLC; + nrst.CreditBalance += (Decimal)amountLC; else - nrst.DebitBalance += amountLC; + nrst.DebitBalance += (Decimal)amountLC; nrst.Balance = nrst.DebitBalance + nrst.CreditBalance; listResults.Add(nrst); } else { if (rst.IsExpense) - listResults[acntidx].CreditBalance += amountLC; + listResults[acntidx].CreditBalance += (Decimal)amountLC; else - listResults[acntidx].DebitBalance += amountLC; + listResults[acntidx].DebitBalance += (Decimal)amountLC; listResults[acntidx].Balance = listResults[acntidx].DebitBalance + listResults[acntidx].CreditBalance; } } @@ -233,6 +233,14 @@ into docitem2 return Ok(listResults); } + /// + /// Get report by Control Center + /// + /// + /// HomeID: Home ID + /// + /// + /// [HttpPost] public IActionResult GetReportByControlCenter([FromBody] ODataActionParameters parameters) { @@ -258,9 +266,7 @@ public IActionResult GetReportByControlCenter([FromBody] ODataActionParameters p { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) - { throw new UnauthorizedAccessException(); - } } catch { @@ -270,9 +276,7 @@ public IActionResult GetReportByControlCenter([FromBody] ODataActionParameters p // 2. Check the Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == hid && p.User == usrName).Count(); if (hms <= 0) - { throw new UnauthorizedAccessException(); - } // 3. Calculate the amount var results = ( @@ -304,7 +308,7 @@ into docitem2 UseCurr2 = docitem3.Key.UseCurr2, ExgRate = docitem3.Key.ExgRate, ExgRate2 = docitem3.Key.ExgRate2, - TranAmount = docitem3.Sum(p => p.TranAmount) + TranAmount = docitem3.Sum(p => (Double)p.TranAmount) }).ToList(); List listResults = new List(); @@ -318,14 +322,14 @@ into docitem2 { if (rst.ExgRate2 != null && rst.ExgRate2.GetValueOrDefault() > 0) { - amountLC *= rst.ExgRate2.GetValueOrDefault(); + amountLC *= (Double)rst.ExgRate2.GetValueOrDefault(); } } else { if (rst.ExgRate != null && rst.ExgRate.GetValueOrDefault() > 0) { - amountLC *= rst.ExgRate.GetValueOrDefault(); + amountLC *= (Double)rst.ExgRate.GetValueOrDefault(); } } @@ -337,18 +341,18 @@ into docitem2 nrst.HomeID = hid; nrst.ControlCenterID = rst.ControlCenterID.GetValueOrDefault(); if (rst.IsExpense) - nrst.CreditBalance += amountLC; + nrst.CreditBalance += (Decimal)amountLC; else - nrst.DebitBalance += amountLC; + nrst.DebitBalance += (Decimal)amountLC; nrst.Balance = nrst.DebitBalance + nrst.CreditBalance; listResults.Add(nrst); } else { if (rst.IsExpense) - listResults[ccidx].CreditBalance += amountLC; + listResults[ccidx].CreditBalance += (Decimal)amountLC; else - listResults[ccidx].DebitBalance += amountLC; + listResults[ccidx].DebitBalance += (Decimal)amountLC; listResults[ccidx].Balance = listResults[ccidx].DebitBalance + listResults[ccidx].CreditBalance; } } @@ -384,9 +388,7 @@ public IActionResult GetReportByOrder([FromBody] ODataActionParameters parameter { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) - { throw new UnauthorizedAccessException(); - } } catch { @@ -396,9 +398,7 @@ public IActionResult GetReportByOrder([FromBody] ODataActionParameters parameter // 2. Check the Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == hid && p.User == usrName).Count(); if (hms <= 0) - { throw new UnauthorizedAccessException(); - } // 3. Calculate the amount List listResults = new List(); @@ -590,9 +590,7 @@ public IActionResult GetFinanceOverviewKeyFigure([FromBody] ODataActionParameter { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) - { throw new UnauthorizedAccessException(); - } } catch { @@ -602,9 +600,7 @@ public IActionResult GetFinanceOverviewKeyFigure([FromBody] ODataActionParameter // 2. Check the Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == hid && p.User == usrName).Count(); if (hms <= 0) - { throw new UnauthorizedAccessException(); - } // 3. Calculate the key figure of current month. FinanceOverviewKeyFigure keyfigure = new FinanceOverviewKeyFigure(); diff --git a/src/hihapi/Utilities/IQueryableExtensions.cs b/src/hihapi/Utilities/IQueryableExtensions.cs deleted file mode 100644 index 705c22f..0000000 --- a/src/hihapi/Utilities/IQueryableExtensions.cs +++ /dev/null @@ -1,66 +0,0 @@ -using Microsoft.EntityFrameworkCore.Internal; -using Microsoft.EntityFrameworkCore.Query; -using Microsoft.EntityFrameworkCore.Query.Internal; -using Microsoft.EntityFrameworkCore.Query.SqlExpressions; -using Microsoft.EntityFrameworkCore.Storage; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Threading.Tasks; - -namespace hihapi.Utilities -{ - public static class IQueryableExtensions - { - private static readonly TypeInfo QueryCompilerTypeInfo = typeof(QueryCompiler).GetTypeInfo(); - - private static readonly FieldInfo QueryCompilerField = typeof(EntityQueryProvider).GetTypeInfo().DeclaredFields.First(x => x.Name == "_queryCompiler"); - - private static readonly PropertyInfo NodeTypeProviderField = QueryCompilerTypeInfo.DeclaredProperties.Single(x => x.Name == "NodeTypeProvider"); - - private static readonly MethodInfo CreateQueryParserMethod = QueryCompilerTypeInfo.DeclaredMethods.First(x => x.Name == "CreateQueryParser"); - - private static readonly FieldInfo DataBaseField = QueryCompilerTypeInfo.DeclaredFields.Single(x => x.Name == "_database"); - - private static readonly FieldInfo QueryCompilationContextFactoryField = typeof(Database).GetTypeInfo().DeclaredFields.Single(x => x.Name == "_queryCompilationContextFactory"); - - //public static string ToSql(this IQueryable query) where TEntity : class - //{ - // if (!(query is EntityQueryable) && !(query is InternalDbSet)) - // { - // throw new ArgumentException("Invalid query"); - // } - - // var queryCompiler = (IQueryCompiler)QueryCompilerField.GetValue(query.Provider); - // var nodeTypeProvider = (INodeTypeProvider)NodeTypeProviderField.GetValue(queryCompiler); - // var parser = (IQueryParser)CreateQueryParserMethod.Invoke(queryCompiler, new object[] { nodeTypeProvider }); - // var queryModel = parser.GetParsedQuery(query.Expression); - // var database = DataBaseField.GetValue(queryCompiler); - // var queryCompilationContextFactory = (IQueryCompilationContextFactory)QueryCompilationContextFactoryField.GetValue(database); - // var queryCompilationContext = queryCompilationContextFactory.Create(false); - // var modelVisitor = (RelationalQueryModelVisitor)queryCompilationContext.CreateQueryModelVisitor(); - // modelVisitor.CreateQueryExecutor(queryModel); - // var sql = modelVisitor.Queries.First().ToString(); - - // return sql; - //} - public static string ToSql(this IQueryable query) where TEntity : class - { - var enumerator = query.Provider.Execute>(query.Expression).GetEnumerator(); - var relationalCommandCache = enumerator.Private("_relationalCommandCache"); - var selectExpression = relationalCommandCache.Private("_selectExpression"); - var factory = relationalCommandCache.Private("_querySqlGeneratorFactory"); - - var sqlGenerator = factory.Create(); - var command = sqlGenerator.GetCommand(selectExpression); - - string sql = command.CommandText; - - return sql; - } - - private static object Private(this object obj, string privateField) => obj?.GetType().GetField(privateField, BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(obj); - private static T Private(this object obj, string privateField) => (T)obj?.GetType().GetField(privateField, BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(obj); - } -} diff --git a/test/hihapi.integrationtest/CustomWebApplicationFactory.cs b/test/hihapi.integrationtest/CustomWebApplicationFactory.cs index 372963c..fd1f8db 100644 --- a/test/hihapi.integrationtest/CustomWebApplicationFactory.cs +++ b/test/hihapi.integrationtest/CustomWebApplicationFactory.cs @@ -110,9 +110,8 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { // Utilities.InitializeDbForTests(db); } - catch (Exception exp) - { - + catch (Exception) + { //logger.LogError(ex, "An error occurred seeding the " + // "database with test messages. Error: {Message}", ex.Message); } diff --git a/test/hihapi.test/UnitTests/Finance/Report/FinanceReportsControllerTest.cs b/test/hihapi.test/UnitTests/Finance/Report/FinanceReportsControllerTest.cs index 1e81494..3b536f3 100644 --- a/test/hihapi.test/UnitTests/Finance/Report/FinanceReportsControllerTest.cs +++ b/test/hihapi.test/UnitTests/Finance/Report/FinanceReportsControllerTest.cs @@ -2,7 +2,7 @@ using Xunit; using System.Threading.Tasks; using System.Collections.Generic; -using hihapi.Controllers.Finance; +using hihapi.Controllers; using Microsoft.AspNetCore.OData.Formatter; using hihapi.test.common; using hihapi.Exceptions; @@ -168,6 +168,8 @@ public async Task TestCase_GetReportByTranTypeMOM_InvalidModel() [Theory] [InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID, DataSetupUtility.TranType_Expense1, "1", null)] [InlineData(DataSetupUtility.UserB, DataSetupUtility.Home1ID, DataSetupUtility.TranType_Expense1, "1", false)] + [InlineData(DataSetupUtility.UserB, DataSetupUtility.Home1ID, DataSetupUtility.TranType_Expense2, "2", false)] + [InlineData(DataSetupUtility.UserB, DataSetupUtility.Home1ID, DataSetupUtility.TranType_Expense2, "3", false)] public async Task TestCase_ReportByTranTypeMOM(string user, int hid, int ttid, string period, Boolean? child) { @@ -202,6 +204,219 @@ public async Task TestCase_ReportByTranTypeMOM(string user, int hid, int ttid, await context.DisposeAsync(); } + + [Fact] + public async Task TestCase_GetReportByAccount_InvalidModel() + { + var context = this.fixture.GetCurrentDataContext(); + FinanceReportsController control = new FinanceReportsController(context); + control.ModelState.AddModelError("HomeID", "The HomeIDfield is required."); + try + { + control.GetReportByAccount(new ODataActionParameters()); + } + catch (Exception exp) + { + Assert.IsType(exp); + } + + await context.DisposeAsync(); + } + + [Theory] + [InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID)] + [InlineData(DataSetupUtility.UserB, DataSetupUtility.Home2ID)] + public async Task TestCase_GetReportByAccount(String user, int hid) + { + var context = this.fixture.GetCurrentDataContext(); + this.fixture.InitHomeTestData(hid, context); + + FinanceReportsController control = new FinanceReportsController(context); + + ODataActionParameters parameters = new ODataActionParameters(); + parameters.Add("HomeID", hid); + + // 1. No authorization + try + { + control.GetReportByAccount(parameters); + } + catch (Exception exp) + { + Assert.IsType(exp); + } + var userclaim = DataSetupUtility.GetClaimForUser(user); + control.ControllerContext = new ControllerContext() + { + HttpContext = new DefaultHttpContext() { User = userclaim } + }; + var rst = control.GetReportByAccount(parameters); + Assert.NotNull(rst); + + await context.DisposeAsync(); + } + + [Fact] + public async Task TestCase_GetReportByAccountMOM_InvalidModel() + { + var context = this.fixture.GetCurrentDataContext(); + FinanceReportsController control = new FinanceReportsController(context); + control.ModelState.AddModelError("HomeID", "The HomeIDfield is required."); + try + { + control.GetReportByAccountMOM(new ODataActionParameters()); + } + catch (Exception exp) + { + Assert.IsType(exp); + } + + await context.DisposeAsync(); + } + + [Theory] + [InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID)] + [InlineData(DataSetupUtility.UserB, DataSetupUtility.Home2ID)] + public async Task TestCase_GetReportByControlCenter(String user, int hid) + { + var context = this.fixture.GetCurrentDataContext(); + this.fixture.InitHomeTestData(hid, context); + + FinanceReportsController control = new FinanceReportsController(context); + + ODataActionParameters parameters = new ODataActionParameters(); + parameters.Add("HomeID", hid); + + // 1. No authorization + try + { + control.GetReportByControlCenter(parameters); + } + catch (Exception exp) + { + Assert.IsType(exp); + } + var userclaim = DataSetupUtility.GetClaimForUser(user); + control.ControllerContext = new ControllerContext() + { + HttpContext = new DefaultHttpContext() { User = userclaim } + }; + var rst = control.GetReportByControlCenter(parameters); + Assert.NotNull(rst); + + await context.DisposeAsync(); + } + + [Theory] + [InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID, DataSetupUtility.Home1CashAccount1ID, "1")] + [InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID, DataSetupUtility.Home1CashAccount1ID, "2")] + [InlineData(DataSetupUtility.UserB, DataSetupUtility.Home1ID, DataSetupUtility.Home1CashAccount3ID, "3")] + public async Task TestCase_ReportByAccountMOM(string user, int hid, int acntid, string period) + { + var context = this.fixture.GetCurrentDataContext(); + this.fixture.InitHomeTestData(hid, context); + + FinanceReportsController control = new FinanceReportsController(context); + + ODataActionParameters parameters = new ODataActionParameters(); + parameters.Add("HomeID", hid); + parameters.Add("AccountID", acntid); + parameters.Add("Period", period); + + // 1. No authorization + try + { + control.GetReportByAccountMOM(parameters); + } + catch (Exception exp) + { + Assert.IsType(exp); + } + var userclaim = DataSetupUtility.GetClaimForUser(user); + control.ControllerContext = new ControllerContext() + { + HttpContext = new DefaultHttpContext() { User = userclaim } + }; + var rst = control.GetReportByAccountMOM(parameters); + Assert.NotNull(rst); + + await context.DisposeAsync(); + } + + [Fact] + public async Task TestCase_GetReportByControlCenter_InvalidModel() + { + var context = this.fixture.GetCurrentDataContext(); + FinanceReportsController control = new FinanceReportsController(context); + control.ModelState.AddModelError("HomeID", "The HomeIDfield is required."); + try + { + control.GetReportByControlCenter(new ODataActionParameters()); + } + catch (Exception exp) + { + Assert.IsType(exp); + } + + await context.DisposeAsync(); + } + + [Fact] + public async Task TestCase_GetReportByControlCenterMOM_InvalidModel() + { + var context = this.fixture.GetCurrentDataContext(); + FinanceReportsController control = new FinanceReportsController(context); + control.ModelState.AddModelError("HomeID", "The HomeIDfield is required."); + try + { + control.GetReportByControlCenterMOM(new ODataActionParameters()); + } + catch (Exception exp) + { + Assert.IsType(exp); + } + + await context.DisposeAsync(); + } + + [Theory] + [InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID, DataSetupUtility.Home1ControlCenter1ID, "1", true)] + [InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID, DataSetupUtility.Home1ControlCenter1ID, "2", true)] + [InlineData(DataSetupUtility.UserB, DataSetupUtility.Home1ID, DataSetupUtility.Home1ControlCenter2ID, "3", null)] + public async Task TestCase_ReportByControlCenterMOM(string user, int hid, int ccid, + string period, Boolean? child) + { + var context = this.fixture.GetCurrentDataContext(); + this.fixture.InitHomeTestData(hid, context); + + FinanceReportsController control = new FinanceReportsController(context); + + ODataActionParameters parameters = new ODataActionParameters(); + parameters.Add("HomeID", hid); + parameters.Add("ControlCenterID", ccid); + parameters.Add("Period", period); + if (child != null) + parameters.Add("IncludeChildren", child.Value); + + // 1. No authorization + try + { + control.GetReportByControlCenterMOM(parameters); + } + catch (Exception exp) + { + Assert.IsType(exp); + } + var userclaim = DataSetupUtility.GetClaimForUser(user); + control.ControllerContext = new ControllerContext() + { + HttpContext = new DefaultHttpContext() { User = userclaim } + }; + var rst = control.GetReportByControlCenterMOM(parameters); + Assert.NotNull(rst); + + await context.DisposeAsync(); + } } }