public async Task <IActionResult> Put([FromODataUri] int id, [FromBody] BlogCollection update) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } // User string usrName; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } if (String.CompareOrdinal(update.Owner, usrName) != 0) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check setting var setting = _context.BlogUserSettings.SingleOrDefault(p => p.Owner == usrName); if (setting == null) { throw new BadRequestException(" User has no setting "); } // Check ID if (id != update.ID) { return(BadRequest()); } _context.Entry(update).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!_context.BlogCollections.Any(p => p.ID == id)) { return(NotFound()); } else { throw; } } return(Updated(update)); }
public IActionResult GetRepeatedDatesWithAmountAndInterest([FromBody] RepeatDatesWithAmountAndInterestCalInput input) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } return(Ok(CommonUtility.WorkoutRepeatedDatesWithAmountAndInterest(input))); }
public IActionResult GetRepeatedDates([FromBody] RepeatDatesCalculationInput input) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } return(Ok(CommonUtility.WorkoutRepeatedDates(input))); }
public async Task <IActionResult> Patch([FromODataUri] int key, [FromBody] Delta <FinanceControlCenter> coll) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } var entity = await _context.FinanceControlCenter.FindAsync(key); if (entity == null) { return(NotFound()); } // User string usrName; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } if (String.CompareOrdinal(entity.Owner, usrName) != 0) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Patch it coll.Patch(entity); try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!_context.FinanceControlCenter.Any(p => p.ID == key)) { return(NotFound()); } else { throw; } } return(Updated(entity)); }
public async Task <IActionResult> Post([FromBody] FinanceDocument document) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } // Check document type, DP, Asset, loan document is not allowed if (document.DocType == FinanceDocumentType.DocType_AdvancePayment || document.DocType == FinanceDocumentType.DocType_AdvanceReceive || document.DocType == FinanceDocumentType.DocType_AssetBuyIn || document.DocType == FinanceDocumentType.DocType_AssetSoldOut || document.DocType == FinanceDocumentType.DocType_AssetValChg || document.DocType == FinanceDocumentType.DocType_BorrowFrom || document.DocType == FinanceDocumentType.DocType_LendTo) { throw new BadRequestException("Document type is not allowed"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == document.HomeID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } if (!document.IsValid(this._context)) { return(BadRequest()); } document.CreatedAt = DateTime.Now; document.Createdby = usrName; _context.FinanceDocument.Add(document); await _context.SaveChangesAsync(); return(Created(document)); }
public async Task <IActionResult> Post([FromBody] FinanceTransactionType ctgy) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } // Check if (!ctgy.IsValid(this._context) || !ctgy.HomeID.HasValue) { throw new BadRequestException("Inputted ID mismatched"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == ctgy.HomeID.Value && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } if (!ctgy.IsValid(this._context)) { throw new BadRequestException("Inputted Object IsValid failed"); } ctgy.CreatedAt = DateTime.Now; ctgy.Createdby = usrName; _context.FinTransactionType.Add(ctgy); await _context.SaveChangesAsync(); return(Created(ctgy)); }
public async Task <IActionResult> Post([FromBody] BlogCollection coll) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } // User string usrName; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } if (coll.Owner != null) { if (String.CompareOrdinal(coll.Owner, usrName) != 0) { throw new UnauthorizedAccessException(); } } else { coll.Owner = usrName; } } catch { throw new UnauthorizedAccessException(); } // Check setting var setting = _context.BlogUserSettings.SingleOrDefault(p => p.Owner == usrName); if (setting == null) { throw new BadRequestException(" User has no setting "); } _context.BlogCollections.Add(coll); await _context.SaveChangesAsync(); return(Created(coll)); }
public async Task <IActionResult> Post([FromBody] FinancePlan plan) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } // Check if (!plan.IsValid(this._context)) { throw new BadRequestException("Check IsValid failed"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == plan.HomeID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } plan.Createdby = usrName; plan.CreatedAt = DateTime.Now; _context.FinancePlan.Add(plan); await _context.SaveChangesAsync(); return(Created(plan)); }
public async Task <IActionResult> Post([FromBody] HomeDefine homedef) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } if (!homedef.IsValid(this._context)) { throw new BadRequestException("Inputted object IsValid Failed"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } homedef.Createdby = usrName; homedef.CreatedAt = DateTime.Now; foreach (var hmem in homedef.HomeMembers) { hmem.CreatedAt = homedef.CreatedAt; hmem.Createdby = usrName; } _context.HomeDefines.Add(homedef); await _context.SaveChangesAsync(); return(Created(homedef)); }
public async Task <IActionResult> PostLoanDocument([FromBody] FinanceLoanDocumentCreateContext createContext) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } if (createContext == null || createContext.DocumentInfo == null || createContext.AccountInfo == null || createContext.AccountInfo.HomeID <= 0 || createContext.AccountInfo.Status != (Byte)FinanceAccountStatus.Normal || createContext.DocumentInfo.HomeID <= 0 || createContext.DocumentInfo.HomeID != createContext.AccountInfo.HomeID || createContext.AccountInfo.ExtraLoan == null || createContext.AccountInfo.ExtraLoan.LoanTmpDocs.Count <= 0) { throw new BadRequestException("Invalid inputted data"); } // Check tmp doc ID var tmpdocids = new Dictionary <int, int>(); foreach (var tmpdoc in createContext.AccountInfo.ExtraLoan.LoanTmpDocs) { if (tmpdoc.DocumentID <= 0) { throw new BadRequestException("Invalid document ID"); } if (tmpdocids.ContainsKey(tmpdoc.DocumentID)) { throw new BadRequestException("Duplicated Document ID found: " + tmpdoc.DocumentID); } tmpdocids.Add(tmpdoc.DocumentID, tmpdoc.DocumentID); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == createContext.AccountInfo.HomeID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } if (!(createContext.DocumentInfo.DocType == FinanceDocumentType.DocType_BorrowFrom || createContext.DocumentInfo.DocType == FinanceDocumentType.DocType_LendTo)) { throw new BadRequestException("Invalid document type"); } if (createContext.DocumentInfo.Items.Count != 1) { throw new BadRequestException("Only one item doc is supported by far"); } foreach (var tdoc in createContext.AccountInfo.ExtraLoan.LoanTmpDocs) { if (!tdoc.ControlCenterID.HasValue && !tdoc.OrderID.HasValue) { throw new BadRequestException("Either control center or order shall be specified in Loan Template doc"); } if (tdoc.TransactionAmount <= 0) { throw new BadRequestException("Amount is zero!"); } tdoc.Createdby = usrName; tdoc.CreatedAt = DateTime.Now; } // Database update var errorString = ""; var errorOccur = false; var origdocid = 0; var dpaccountid = 0; using (var transaction = _context.Database.BeginTransaction()) { try { // 1. Create document createContext.DocumentInfo.Createdby = usrName; createContext.DocumentInfo.CreatedAt = DateTime.Now; var docEntity = _context.FinanceDocument.Add(createContext.DocumentInfo); await _context.SaveChangesAsync(); origdocid = docEntity.Entity.ID; // 2, Create the account createContext.AccountInfo.ExtraLoan.RefDocID = origdocid; createContext.AccountInfo.CreatedAt = DateTime.Now; createContext.AccountInfo.Createdby = usrName; var acntEntity = _context.FinanceAccount.Add(createContext.AccountInfo); await _context.SaveChangesAsync(); dpaccountid = acntEntity.Entity.ID; // 3, Update the document var itemid = docEntity.Entity.Items.ElementAt(0).ItemID; // _context.Attach(docEntity); var ndi = new FinanceDocumentItem(); ndi.ItemID = ++itemid; ndi.AccountID = dpaccountid; ndi.ControlCenterID = docEntity.Entity.Items.ElementAt(0).ControlCenterID; ndi.OrderID = docEntity.Entity.Items.ElementAt(0).OrderID; ndi.Desp = docEntity.Entity.Items.ElementAt(0).Desp; ndi.TranAmount = docEntity.Entity.Items.ElementAt(0).TranAmount; ndi.UseCurr2 = docEntity.Entity.Items.ElementAt(0).UseCurr2; if (createContext.DocumentInfo.DocType == FinanceDocumentType.DocType_BorrowFrom) { ndi.TranType = FinanceTransactionType.TranType_OpeningLiability; } else if (createContext.DocumentInfo.DocType == FinanceDocumentType.DocType_LendTo) { ndi.TranType = FinanceTransactionType.TranType_OpeningAsset; } docEntity.Entity.Items.Add(ndi); docEntity.State = EntityState.Modified; await _context.SaveChangesAsync(); transaction.Commit(); } catch (Exception exp) { errorOccur = true; errorString = exp.Message; transaction.Rollback(); } } if (errorOccur) { throw new BadRequestException(errorString); } return(Created(createContext.DocumentInfo)); }
public async Task <IActionResult> Put([FromODataUri] int key, [FromBody] FinanceControlCenter update) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } if (key != update.ID) { throw new BadRequestException("Inputted ID mismatched"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == update.HomeID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } if (!update.IsValid(this._context)) { return(BadRequest()); } update.Updatedby = usrName; update.UpdatedAt = DateTime.Now; _context.Entry(update).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException exp) { if (!_context.FinanceControlCenter.Any(p => p.ID == key)) { return(NotFound()); } else { throw new DBOperationException(exp.Message); } } return(Updated(update)); }
public async Task <IActionResult> Put([FromODataUri] int key, [FromBody] FinanceOrder update) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } if (key != update.ID) { throw new BadRequestException("Inputted ID mismatched"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == update.HomeID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } if (!update.IsValid(this._context)) { return(BadRequest()); } update.Updatedby = usrName; update.UpdatedAt = DateTime.Now; _context.Entry(update).State = EntityState.Modified; // SRules. var rulesInDB = _context.FinanceOrderSRule.Where(p => p.OrderID == update.ID).ToList(); foreach (var rule in update.SRule) { var itemindb = rulesInDB.Find(p => p.OrderID == update.ID && p.RuleID == rule.RuleID); if (itemindb == null) { _context.FinanceOrderSRule.Add(rule); } else { // Update _context.Entry(itemindb).State = EntityState.Modified; } } foreach (var rule in rulesInDB) { var nitem = update.SRule.FirstOrDefault(p => p.OrderID == update.ID && p.RuleID == rule.RuleID); if (nitem == null) { _context.FinanceOrderSRule.Remove(rule); } } try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException exp) { if (!_context.FinanceOrder.Any(p => p.ID == key)) { return(NotFound()); } else { throw new DBOperationException(exp.Message); } } return(Updated(update)); }
public async Task <IActionResult> Put([FromODataUri] int key, [FromBody] HomeDefine update) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } if (key != update.ID) { throw new BadRequestException("Inputted ID mismatched"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == update.ID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } if (!update.IsValid(this._context)) { throw new BadRequestException("Inputted Object IsValid Failed"); } // Find out the home define var existinghd = _context.HomeDefines.Find(key); if (existinghd == null) { throw new NotFoundException("Inputted Object Not Found"); } else { update.Updatedby = usrName; update.UpdatedAt = DateTime.Now; update.CreatedAt = existinghd.CreatedAt; update.Createdby = existinghd.Createdby; _context.Entry(existinghd).CurrentValues.SetValues(update); var dbmems = _context.HomeMembers.Where(p => p.HomeID == key).ToList(); foreach (var mem in update.HomeMembers) { var memindb = dbmems.Find(p => p.HomeID == key && p.User == mem.User); if (memindb == null) { mem.Createdby = usrName; mem.CreatedAt = DateTime.Now; _context.HomeMembers.Add(mem); } else { mem.CreatedAt = memindb.CreatedAt; mem.Createdby = memindb.Createdby; _context.Entry(memindb).CurrentValues.SetValues(mem); } } foreach (var mem in dbmems) { var nmem = update.HomeMembers.FirstOrDefault(p => p.User == mem.User); if (nmem == null) { _context.HomeMembers.Remove(mem); } } } try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException exp) { if (!_context.HomeDefines.Any(p => p.ID == key)) { throw new NotFoundException("Inputted Object Not Found"); } else { throw new DBOperationException(exp.Message); } } return(Updated(update)); }
public async Task <IActionResult> PostAssetValueChangeDocument([FromBody] FinanceAssetRevaluationDocumentCreateContext createContext) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } if (createContext == null) { throw new BadRequestException("No data is inputted"); } if (createContext.HID <= 0) { throw new BadRequestException("Not HID inputted"); } if (createContext.AssetAccountID <= 0) { throw new BadRequestException("Asset Account is invalid"); } if (createContext.Items.Count != 1) { throw new BadRequestException("Items count is not correct"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == createContext.HID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } // Construct the Doc. var vmFIDoc = new FinanceDocument(); vmFIDoc.DocType = FinanceDocumentType.DocType_AssetValChg; vmFIDoc.Desp = createContext.Desp; vmFIDoc.TranDate = createContext.TranDate; vmFIDoc.HomeID = createContext.HID; vmFIDoc.TranCurr = createContext.TranCurr; Decimal totalAmount = 0; Int32? rlTranType = null; foreach (var di in createContext.Items) { if (di.ItemID <= 0 || di.TranAmount == 0 || di.AccountID != createContext.AssetAccountID || (di.TranType != FinanceTransactionType.TranType_AssetValueIncrease && di.TranType != FinanceTransactionType.TranType_AssetValueDecrease) || (di.ControlCenterID <= 0 && di.OrderID <= 0)) { return(BadRequest("Invalid input data in items!")); } if (rlTranType == null) { rlTranType = di.TranType; } else { if (rlTranType.Value != di.TranType) { return(BadRequest("Cannot support different trantype")); } } totalAmount += di.TranAmount; vmFIDoc.Items.Add(di); } // Basic check - TBD //try //{ // FinanceDocumentController.FinanceDocumentBasicCheck(vmFIDoc); //} //catch(Exception exp) //{ //} // Perfrom the doc. validation //await FinanceDocumentsController.FinanceDocumentBasicValidationAsync(vmFIDoc, conn); // Additional check 1.account is a valid asset? var query = (from account in this._context.FinanceAccount join assetaccount in this._context.FinanceAccountExtraAS on account.ID equals assetaccount.AccountID where account.ID == createContext.AssetAccountID select new { Status = account.Status, RefSellDoc = assetaccount.RefenceSoldDocumentID }).FirstOrDefault(); if (query.Status != (Byte)FinanceAccountStatus.Normal) { throw new BadRequestException("Account status is not normal"); } if (query.RefSellDoc != null) { throw new BadRequestException("Asset has soldout doc already"); } // Additional check 2. the inputted date is valid > must be the later than all existing transactions; var query2 = (from docitem in this._context.FinanceDocumentItem join docheader in this._context.FinanceDocument on docitem.DocID equals docheader.ID where docitem.AccountID == createContext.AssetAccountID orderby docheader.TranDate descending select new { TranDate = docheader.TranDate }).FirstOrDefault(); if (createContext.TranDate < query2.TranDate) { throw new BadRequestException("Tran. data is invalid"); } // Additional check 3. Fetch current balance var query3 = (from acntbal in this._context.FinanceReporAccountGroupView where acntbal.AccountID == createContext.AssetAccountID select acntbal.Balance).First(); if (query3 <= 0) { throw new BadRequestException("Balance is less than zero"); } // Additional check 4: the balance with the inputted value var nCmpRst = Decimal.Compare(query3, totalAmount); if (nCmpRst > 0) { if (rlTranType.Value != FinanceTransactionType.TranType_AssetValueDecrease) { throw new BadRequestException("Tran type is wrong"); } } else if (nCmpRst < 0) { if (rlTranType.Value != FinanceTransactionType.TranType_AssetValueIncrease) { throw new BadRequestException("Tran type is wrong"); } } else if (nCmpRst == 0) { throw new BadRequestException("Current balance equals to new value"); } // Update the database var errorString = ""; var errorOccur = false; var origdocid = 0; using (var transaction = _context.Database.BeginTransaction()) { try { // 1. Create the document vmFIDoc.Createdby = usrName; vmFIDoc.CreatedAt = DateTime.Now; var docEntity = _context.FinanceDocument.Add(vmFIDoc); await _context.SaveChangesAsync(); origdocid = docEntity.Entity.ID; vmFIDoc = docEntity.Entity; transaction.Commit(); } catch (Exception exp) { errorOccur = true; errorString = exp.Message; transaction.Rollback(); } } if (errorOccur) { throw new BadRequestException(errorString); } return(Created(vmFIDoc)); }
public async Task <IActionResult> PostAssetBuyDocument([FromBody] FinanceAssetBuyDocumentCreateContext createContext) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } if (createContext == null || createContext.ExtraAsset == null) { throw new BadRequestException("No data is inputted"); } if (createContext.HID <= 0) { throw new BadRequestException("Not HID inputted"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == createContext.HID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } // Do basic checks if (String.IsNullOrEmpty(createContext.TranCurr) || String.IsNullOrEmpty(createContext.ExtraAsset.Name)) { throw new BadRequestException("Invalid input data"); } if (createContext.IsLegacy.HasValue && createContext.IsLegacy.Value) { if (createContext.Items.Count > 0) { throw new BadRequestException("Invalid input data"); } } else { if (createContext.Items.Count <= 0) { throw new BadRequestException("Invalid input data"); } } foreach (var di in createContext.Items) { if (di.TranAmount == 0 || di.AccountID <= 0 || di.TranType <= 0 || (di.ControlCenterID <= 0 && di.OrderID <= 0)) { throw new BadRequestException("Invalid input data in items!"); } } // Construct the Account var vmAccount = new FinanceAccount(); vmAccount.HomeID = createContext.HID; vmAccount.Name = createContext.ExtraAsset.Name; vmAccount.Status = (Byte)FinanceAccountStatus.Normal; vmAccount.CategoryID = FinanceAccountCategory.AccountCategory_Asset; vmAccount.ExtraAsset = new FinanceAccountExtraAS(); vmAccount.Owner = createContext.AccountOwner; vmAccount.Comment = createContext.ExtraAsset.Comment; vmAccount.ExtraAsset.Name = createContext.ExtraAsset.Name; vmAccount.ExtraAsset.Comment = createContext.ExtraAsset.Comment; vmAccount.ExtraAsset.CategoryID = createContext.ExtraAsset.CategoryID; vmAccount.ExtraAsset.AccountHeader = vmAccount; // Construct the Doc. var vmFIDoc = new FinanceDocument(); vmFIDoc.DocType = FinanceDocumentType.DocType_AssetBuyIn; vmFIDoc.Desp = createContext.Desp; vmFIDoc.TranDate = createContext.TranDate; vmFIDoc.HomeID = createContext.HID; vmFIDoc.TranCurr = createContext.TranCurr; var maxItemID = 0; if (createContext.IsLegacy.HasValue && createContext.IsLegacy.Value) { // Legacy account... } else { Decimal totalAmt = 0; foreach (var di in createContext.Items) { if (di.ItemID <= 0 || di.TranAmount == 0 || di.AccountID <= 0 || (di.ControlCenterID <= 0 && di.OrderID <= 0)) { throw new BadRequestException("Invalid input data in items!"); } // Todo: new check the tran. type is an expense! totalAmt += di.TranAmount; vmFIDoc.Items.Add(di); if (maxItemID < di.ItemID) { maxItemID = di.ItemID; } } if (totalAmt != createContext.TranAmount) { throw new BadRequestException("Amount is not even"); } } // Database update var errorString = ""; var errorOccur = false; var origdocid = 0; var assetaccountid = 0; using (var transaction = _context.Database.BeginTransaction()) { try { // 1. Create the document vmFIDoc.Createdby = usrName; vmFIDoc.CreatedAt = DateTime.Now; var docEntity = _context.FinanceDocument.Add(vmFIDoc); await _context.SaveChangesAsync(); origdocid = docEntity.Entity.ID; // 2, Create the account vmAccount.ExtraAsset.RefenceBuyDocumentID = origdocid; vmAccount.CreatedAt = DateTime.Now; vmAccount.Createdby = usrName; var acntEntity = _context.FinanceAccount.Add(vmAccount); await _context.SaveChangesAsync(); assetaccountid = acntEntity.Entity.ID; // 3. Update the document by adding one more item var nitem = new FinanceDocumentItem(); nitem.ItemID = ++maxItemID; nitem.AccountID = assetaccountid; nitem.TranAmount = createContext.TranAmount; nitem.Desp = vmFIDoc.Desp; nitem.TranType = FinanceTransactionType.TranType_OpeningAsset; if (createContext.ControlCenterID.HasValue) { nitem.ControlCenterID = createContext.ControlCenterID.Value; } if (createContext.OrderID.HasValue) { nitem.OrderID = createContext.OrderID.Value; } nitem.DocumentHeader = vmFIDoc; docEntity.Entity.Items.Add(nitem); docEntity.State = EntityState.Modified; await _context.SaveChangesAsync(); vmFIDoc = docEntity.Entity; transaction.Commit(); } catch (Exception exp) { errorOccur = true; errorString = exp.Message; transaction.Rollback(); } } if (errorOccur) { throw new BadRequestException(errorString); } return(Created(vmFIDoc)); }
public async Task <IActionResult> PostAssetSellDocument([FromBody] FinanceAssetSellDocumentCreateContext createContext) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } if (createContext.HID <= 0) { throw new BadRequestException("Not HID inputted"); } if (createContext.AssetAccountID <= 0) { throw new BadRequestException("Asset Account is invalid"); } if (createContext.TranAmount <= 0) { throw new BadRequestException("Amount is less than zero"); } if (createContext.Items.Count <= 0) { throw new BadRequestException("No items inputted"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check whether User assigned with specified Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == createContext.HID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } // Construct the Doc. var vmFIDoc = new FinanceDocument(); vmFIDoc.DocType = FinanceDocumentType.DocType_AssetSoldOut; vmFIDoc.Desp = createContext.Desp; vmFIDoc.TranDate = createContext.TranDate; vmFIDoc.HomeID = createContext.HID; vmFIDoc.TranCurr = createContext.TranCurr; Decimal totalAmt = 0; var maxItemID = 0; foreach (var di in createContext.Items) { if (di.ItemID <= 0 || di.TranAmount == 0 || di.AccountID <= 0 || di.TranType != FinanceTransactionType.TranType_AssetSoldoutIncome || (di.ControlCenterID <= 0 && di.OrderID <= 0)) { throw new BadRequestException("Invalid input data in items!"); } totalAmt += di.TranAmount; vmFIDoc.Items.Add(di); if (maxItemID < di.ItemID) { maxItemID = di.ItemID; } } if (Decimal.Compare(totalAmt, createContext.TranAmount) != 0) { throw new BadRequestException("Amount is not even"); } // Check 1: check account is a valid asset? var query = (from account in this._context.FinanceAccount join assetaccount in this._context.FinanceAccountExtraAS on account.ID equals assetaccount.AccountID where account.ID == createContext.AssetAccountID select new { Status = account.Status, RefSellDoc = assetaccount.RefenceSoldDocumentID }).FirstOrDefault(); if (query.Status != (Byte)FinanceAccountStatus.Normal) { throw new BadRequestException("Account status is not normal"); } if (query.RefSellDoc != null) { throw new BadRequestException("Asset has soldout doc already"); } // Check 2: check the inputted date is valid > must be the later than all existing transactions; var query2 = (from docitem in this._context.FinanceDocumentItem join docheader in this._context.FinanceDocument on docitem.DocID equals docheader.ID where docitem.AccountID == createContext.AssetAccountID orderby docheader.TranDate descending select new { TranDate = docheader.TranDate }).FirstOrDefault(); if (createContext.TranDate < query2.TranDate) { throw new BadRequestException("Tran. data is invalid"); } // Check 3. Fetch current balance var query3 = (from acntbal in this._context.FinanceReporAccountGroupView where acntbal.AccountID == createContext.AssetAccountID select acntbal.Balance).First(); if (query3 <= 0) { throw new BadRequestException("Balance is less than zero"); } var nitem = new FinanceDocumentItem(); nitem.ItemID = ++maxItemID; nitem.AccountID = createContext.AssetAccountID; nitem.TranAmount = createContext.TranAmount; nitem.Desp = vmFIDoc.Desp; nitem.TranType = FinanceTransactionType.TranType_AssetSoldout; if (createContext.ControlCenterID.HasValue) { nitem.ControlCenterID = createContext.ControlCenterID.Value; } if (createContext.OrderID.HasValue) { nitem.OrderID = createContext.OrderID.Value; } nitem.DocumentHeader = vmFIDoc; vmFIDoc.Items.Add(nitem); var ncmprst = Decimal.Compare(query3, createContext.TranAmount); if (ncmprst > 0) { var nitem2 = new FinanceDocumentItem(); nitem2.ItemID = ++maxItemID; nitem2.AccountID = createContext.AssetAccountID; nitem2.TranAmount = Decimal.Subtract(query3, createContext.TranAmount); nitem2.Desp = vmFIDoc.Desp; nitem2.TranType = FinanceTransactionType.TranType_AssetValueDecrease; if (createContext.ControlCenterID.HasValue) { nitem2.ControlCenterID = createContext.ControlCenterID.Value; } if (createContext.OrderID.HasValue) { nitem2.OrderID = createContext.OrderID.Value; } nitem.DocumentHeader = vmFIDoc; vmFIDoc.Items.Add(nitem2); } else if (ncmprst < 0) { var nitem2 = new FinanceDocumentItem(); nitem2.ItemID = ++maxItemID; nitem2.AccountID = createContext.AssetAccountID; nitem2.TranAmount = Decimal.Subtract(createContext.TranAmount, query3); nitem2.Desp = vmFIDoc.Desp; nitem2.TranType = FinanceTransactionType.TranType_AssetValueIncrease; if (createContext.ControlCenterID.HasValue) { nitem2.ControlCenterID = createContext.ControlCenterID.Value; } if (createContext.OrderID.HasValue) { nitem2.OrderID = createContext.OrderID.Value; } nitem.DocumentHeader = vmFIDoc; vmFIDoc.Items.Add(nitem2); } // Database update var errorString = ""; var errorOccur = false; var origdocid = 0; using (var transaction = _context.Database.BeginTransaction()) { try { // 1. Create the document vmFIDoc.CreatedAt = DateTime.Now; vmFIDoc.Createdby = usrName; var docEntity = _context.FinanceDocument.Add(vmFIDoc); await _context.SaveChangesAsync(); origdocid = docEntity.Entity.ID; vmFIDoc = docEntity.Entity; transaction.Commit(); } catch (Exception exp) { errorOccur = true; errorString = exp.Message; transaction.Rollback(); } } if (errorOccur) { throw new BadRequestException(errorString); } return(Created(vmFIDoc)); }
public async Task <IActionResult> PostRepayDocument([FromBody] FinanceLoanRepayDocumentCreateContext createContext) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } // Checks // Check 0: Input data check if (createContext.HomeID <= 0 || createContext.LoanTemplateDocumentID <= 0 || createContext.DocumentInfo == null || createContext.DocumentInfo.DocType != FinanceDocumentType.DocType_Repay) { throw new BadRequestException("Invalid inputted data"); } // Check 1: User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check 1: Home ID var hms = _context.HomeMembers.Where(p => p.HomeID == createContext.HomeID && p.User == usrName).Count(); if (hms <= 0) { throw new UnauthorizedAccessException(); } // Check 2: Template doc var docLoanTmp = _context.FinanceTmpLoanDocument .Where(p => p.DocumentID == createContext.LoanTemplateDocumentID) .FirstOrDefault(); if (docLoanTmp == null || docLoanTmp.ReferenceDocumentID > 0) { throw new BadRequestException("Invalid loan template ID or doc has been posted"); } if (!docLoanTmp.ControlCenterID.HasValue && !docLoanTmp.OrderID.HasValue) { throw new BadRequestException("Tmp doc lack of control center or order"); } if (docLoanTmp.TransactionAmount == 0) { throw new BadRequestException("Tmp doc lack of amount"); } // Check 3: Account var loanAccountHeader = _context.FinanceAccount.Where(p => p.ID == docLoanTmp.AccountID).FirstOrDefault(); if (loanAccountHeader == null || loanAccountHeader.Status != (Byte)FinanceAccountStatus.Normal || !(loanAccountHeader.CategoryID == FinanceAccountCategory.AccountCategory_BorrowFrom || loanAccountHeader.CategoryID == FinanceAccountCategory.AccountCategory_LendTo) ) { throw new BadRequestException("Account not exist or account has wrong status or account has wrong category"); } var loanAccountExtra = _context.FinanceAccountExtraLoan.Where(p => p.AccountID == loanAccountHeader.ID).FirstOrDefault(); if (loanAccountExtra == null) { throw new BadRequestException("Account is not a valid loan account"); } // Check 4: Check amounts int ninvaliditems = 0; Decimal acntBalance = 0M; // Balance var acntBalInfo = _context.FinanceReporAccountGroupAndExpenseView.Where(p => p.AccountID == loanAccountHeader.ID).ToList(); if (acntBalInfo.Count > 0) { acntBalance = 0; acntBalInfo.ForEach(action => { if (action.IsExpense) { acntBalance += action.Balance; } else { acntBalance += action.Balance; } }); } else { throw new BadRequestException("No balance"); } // Only four tran. types are allowed if (loanAccountHeader.CategoryID == FinanceAccountCategory.AccountCategory_BorrowFrom) { ninvaliditems = createContext.DocumentInfo.Items.Where(item => item.TranType != FinanceTransactionType.TranType_InterestOut && item.TranType != FinanceTransactionType.TranType_RepaymentOut && item.TranType != FinanceTransactionType.TranType_RepaymentIn) .Count(); } else if (loanAccountHeader.CategoryID == FinanceAccountCategory.AccountCategory_LendTo) { ninvaliditems = createContext.DocumentInfo.Items.Where(item => item.TranType != FinanceTransactionType.TranType_InterestIn && item.TranType != FinanceTransactionType.TranType_RepaymentOut && item.TranType != FinanceTransactionType.TranType_RepaymentIn) .Count(); } if (ninvaliditems > 0) { throw new BadRequestException("Items with invalid tran type"); } // Check the amount decimal totalOut = createContext.DocumentInfo.Items .Where(item => item.TranType == FinanceTransactionType.TranType_RepaymentOut) .Sum(item2 => item2.TranAmount); decimal totalIn = createContext.DocumentInfo.Items .Where(item => item.TranType == FinanceTransactionType.TranType_RepaymentIn) .Sum(item2 => item2.TranAmount); //decimal totalintOut = repaydoc.Items.Where(item => (item.TranType == FinanceTranTypeViewModel.TranType_InterestOut)).Sum(item2 => item2.TranAmount); // New account balance if (loanAccountHeader.CategoryID == FinanceAccountCategory.AccountCategory_LendTo) { acntBalance -= totalOut; } else if (loanAccountHeader.CategoryID == FinanceAccountCategory.AccountCategory_BorrowFrom) { acntBalance += totalIn; } if (totalOut != totalIn) { throw new BadRequestException("Amount is not equal!"); } // The post here is: // 1. Post a repayment document with the content from this template doc // 2. Update the template doc with REFDOCID // 3. If the account balance is zero, close the account; // Database update var errorString = ""; var errorOccur = false; var origdocid = 0; FinanceDocument findoc = null; using (var transaction = _context.Database.BeginTransaction()) { try { // 1. Create the document createContext.DocumentInfo.Createdby = usrName; createContext.DocumentInfo.CreatedAt = DateTime.Now; var docEntity = _context.FinanceDocument.Add(createContext.DocumentInfo); _context.SaveChanges(); origdocid = docEntity.Entity.ID; // 2. Update the tmp doc docLoanTmp.ReferenceDocumentID = origdocid; docLoanTmp.UpdatedAt = DateTime.Now; docLoanTmp.Updatedby = usrName; _context.FinanceTmpLoanDocument.Update(docLoanTmp); _context.SaveChanges(); // 3. In case balance is zero, update the account status if (Decimal.Compare(acntBalance, 0) == 0) { loanAccountHeader.Status = (Byte)FinanceAccountStatus.Closed; loanAccountHeader.Updatedby = usrName; loanAccountHeader.UpdatedAt = DateTime.Now; _context.FinanceAccount.Update(loanAccountHeader); _context.SaveChanges(); } findoc = docEntity.Entity; await transaction.CommitAsync(); } catch (Exception exp) { errorOccur = true; errorString = exp.Message; transaction.Rollback(); } } if (errorOccur) { throw new DBOperationException(errorString); } return(Created(findoc)); }
public async Task <IActionResult> Put([FromODataUri] int key, [FromBody] BlogPost update) { if (!ModelState.IsValid) { HIHAPIUtility.HandleModalStateError(ModelState); } if (key != update.ID) { throw new BadRequestException("ID mismatched"); } // User String usrName = String.Empty; try { usrName = HIHAPIUtility.GetUserID(this); if (String.IsNullOrEmpty(usrName)) { throw new UnauthorizedAccessException(); } if (String.CompareOrdinal(usrName, update.Owner) != 0) { throw new UnauthorizedAccessException(); } } catch { throw new UnauthorizedAccessException(); } // Check setting var setting = _context.BlogUserSettings.SingleOrDefault(p => p.Owner == usrName); if (setting == null) { throw new BadRequestException(" User has no setting "); } update.UpdatedAt = DateTime.Now; _context.Entry(update).State = EntityState.Modified; // Tags var tagInDBs = _context.BlogPostTags.Where(p => p.PostID == update.ID).ToList(); foreach (var tag in update.BlogPostTags) { var tagindb = tagInDBs.Find(p => p.PostID == update.ID && p.Tag == tag.Tag); if (tagindb == null) { _context.BlogPostTags.Add(tag); } } foreach (var tag in tagInDBs) { var ntag = update.BlogPostTags.FirstOrDefault(p => p.PostID == update.ID && p.Tag == tag.Tag); if (ntag == null) { _context.BlogPostTags.Remove(tag); } } // Collection var collInDBs = _context.BlogPostCollections.Where(p => p.PostID == update.ID).ToList(); foreach (var coll in update.BlogPostCollections) { var collindb = collInDBs.Find(p => p.PostID == update.ID && p.CollectionID == coll.CollectionID); if (collindb == null) { _context.BlogPostCollections.Add(coll); } } foreach (var coll in collInDBs) { var ncoll = update.BlogPostCollections.FirstOrDefault(p => p.PostID == update.ID && p.CollectionID == coll.CollectionID); if (ncoll == null) { _context.BlogPostCollections.Remove(coll); } } try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException exp) { if (!_context.FinanceAccount.Any(p => p.ID == key)) { return(NotFound()); } else { throw new DBOperationException(exp.Message); } } return(Ok(update)); }