public async Task<IHttpActionResult> Create(Transaction model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (model.isDebit) { if (model.Amount > 0) { model.Amount *= -1; } } else if (model.Amount < 0) { model.Amount *= -1; } var account = db.HouseHoldAccounts.Find(model.HouseHoldAccountId); account.Balance += model.Amount; if (model.Reconcile) { account.ReconciledBalance += model.Amount; } model.Created = DateTimeOffset.Now; model.CategoryId = model.Category.id; model.Category = null; db.Transactions.Add(model); await db.SaveChangesAsync(); return Ok(); }
public async Task<IHttpActionResult> Edit(Transaction model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var oldTrans = db.Transactions.AsNoTracking().FirstOrDefault(t => t.id == model.id); if (model.isDebit) { if (model.Amount > 0) { model.Amount *= -1; } } else if (model.Amount < 0) { model.Amount *= -1; } var account = db.HouseHoldAccounts.FirstOrDefault(a => a.id == model.HouseHoldAccountId); //check if the amount/isDebit has changed if (oldTrans.Amount != model.Amount) { account.Balance -= oldTrans.Amount; account.Balance += model.Amount; } //check if transaction is Reconciled if (oldTrans.Reconcile != model.Reconcile) { account.ReconciledBalance -= oldTrans.Amount; account.ReconciledBalance += model.Amount; } model.CategoryId = model.Category.id; model.Category = null; var arr = new List<string>(){"Amount", "Reconcile", "CategoryId", "Description", "isDebit"}; db.Update<Transaction>(model, arr.ToArray()); model.Updated = DateTimeOffset.Now; await db.SaveChangesAsync(); return Ok(); }