Exemple #1
0
        /// <summary>ArchiveChildrens a Issuer record.</summary>
        /// <param name="transaction">Commits or rejects a set of commands as a unit</param>
        /// <param name="rowVersion">the version number of this row.</param>
        /// <param name="issuerId">The value for the IssuerId column.</param>
        /// <param name="archive">true to archive the object, false to unarchive it.</param>
        internal static void ArchiveChildren(AdoTransaction adoTransaction, SqlTransaction sqlTransaction, long rowVersion, int issuerId)
        {
            // Accessor for the Issuer Table.
            ServerMarketData.IssuerDataTable issuerTable = ServerMarketData.Issuer;
            // This record can be used to iterate through all the children.
            ServerMarketData.IssuerRow issuerRow = issuerTable.FindByIssuerId(issuerId);
            // Archive the child records.
            for (int index = 0; (index < issuerRow.GetDebtRows().Length); index = (index + 1))
            {
                ServerMarketData.DebtRow childDebtRow = issuerRow.GetDebtRows()[index];
                Debt.ArchiveChildren(adoTransaction, sqlTransaction, childDebtRow.RowVersion, childDebtRow.DebtId);
            }
            // Increment the row version
            rowVersion = ServerMarketData.RowVersion.Increment();
            // Delete the record in the ADO database.
            issuerRow[issuerTable.RowVersionColumn] = rowVersion;
            adoTransaction.DataRows.Add(issuerRow);
            issuerRow.Delete();
            // Archive the record in the SQL database.
            SqlCommand sqlCommand = new SqlCommand("update \"Issuer\" set \"IsArchived\" = 1 where \"IssuerId\"=@issuerId");

            sqlCommand.Connection  = sqlTransaction.Connection;
            sqlCommand.Transaction = sqlTransaction;
            sqlCommand.Parameters.Add(new SqlParameter("@issuerId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, issuerId));
            sqlCommand.ExecuteNonQuery();
        }
Exemple #2
0
        private async void ButtonClicked(object sender, EventArgs e)
        {
            decimal amount;

            if (decimal.TryParse(AmountEntry.Text, out amount))
            {
                amount *= sender == PlusButton ? 1 : -1;
            }
            else
            {
                return;
            }
            UserDialogs.Instance.ShowLoading();
            var updated = new Debt
            {
                Id      = Debt.Id,
                Reason  = null,
                Balance = amount
            };

            Debt = await _serviceClient.AddMovementToDebt(updated);

            DebtUpdated?.Invoke(sender, Debt);
            Movements.Insert(0, new Movement {
                Amount = amount, Date = Debt.UpdatedAt.Value, Reason = Debt.Reason
            });
            AmountEntry.Text = null;
            UpdateAmounts();

            UserDialogs.Instance.HideLoading();
        }
        private void BtnAddDebt_OnClick(object sender, RoutedEventArgs e)
        {
            var dateFrom = DpDateFrom.SelectedDate;
            var dateTo   = DpDateTo.SelectedDate;

            var debt = new Debt()
            {
                Amout      = decimal.Parse(TxtAmout.Text),
                DateStart  = (DateTime)dateFrom,
                DebtStatus = (bool)ChbDebtStatus.IsChecked,
                DueDate    = (DateTime)dateTo,
                PaidAmout  = decimal.Parse(TxtPaidAmout.Text)
            };

            var result = database.AddDebtToPerson(SelectedPerson, debt);

            if (result)
            {
                MessageBox.Show("The debt was added!", "Success", MessageBoxButton.OK);
                UpdateControler.Update();
            }
            else
            {
                MessageBox.Show("The debt was not added!", "Success", MessageBoxButton.OK);
            }
        }
        public void AutoAdd()
        {
            int curYear = DateTime.Now.Year;

            using (DistributorEntities ent = new DistributorEntities())
            {
                var lstSel = ent.Sellers.ToList();
                foreach (var sel in lstSel)
                {
                    if (!sel.Debts.Where(c => c.Year == curYear).Any())
                    {
                        Debt debt = new Debt
                        {
                            SellerId = sel.Id,
                            Year     = curYear
                        };

                        ent.Debts.Add(debt);
                    }
                    else
                    {
                    }
                }

                ent.SaveChanges();
            }
        }
 public ActionResult CreateDebt(Debt debt)
 {
     debt.UserName = User.Identity.Name;
     db.Debts.Add(debt);
     db.SaveChanges();
     return(RedirectToAction("CreateDebt"));
 }
        // flips debt type of given debt
        private static Debt FlipDebtType(Debt debt)
        {
            var type = (debt.Type == DebtType.Repayment) ? DebtType.Loan : DebtType.Repayment;

            return(new Debt(debt.ID, debt.Date, type,
                            debt.Debtor, debt.Creditor, -debt.Amount));
        }
        public void Add(DebtModel debtModel)
        {
            string  Name    = debtModel.Name;
            decimal Amount  = 0;
            decimal APR     = 0;
            decimal Payment = 0;

            decimal.TryParse(debtModel.Amount.ToString(), out Amount);
            decimal.TryParse(debtModel.APR.ToString(), out APR);
            decimal.TryParse(debtModel.Payment.ToString(), out Payment);

            APR /= 100;

            // Save code goes here
            Data data      = new Data();
            Debt debtToAdd = new Debt()
            {
                Name       = Name,
                Amount     = Amount,
                DueDay     = 1,
                Interest   = APR,
                MinPayment = Payment,
            };

            data.Insert(debtToAdd);


            Response.Redirect("/Debt/List");
        }
        public void Should_Create()
        {
            Debt myDebt = new Debt
            {
                Sum     = 15,
                GiverId = currentUser.Id,
                TakerId = 2
            };

            var mockContext = new Mock <DatabaseContext>();

            mockContext.Setup(c => c.Debts.Add(myDebt));

            var service = new DebtsService(mockContext.Object, iMapper, mockAccessor.Object, new DebtDtoMapper(iMapper));

            service.CreateDebt(
                new DebtInboxDto()
            {
                GiverId = (int)myDebt.GiverId,
                TakerId = (int)myDebt.TakerId,
                Sum     = myDebt.Sum
            }
                );

            mockContext.Verify(m => m.SaveChanges());
            mockContext.Verify(m => m.Debts.Add(It.Is <Debt>(t =>
                                                             t.Sum == myDebt.Sum &&
                                                             t.TakerId == myDebt.TakerId &&
                                                             t.GiverId == myDebt.GiverId &&
                                                             t.IsActive == true &&
                                                             t.Date.Date == DateTime.Now.Date &&
                                                             t.Deadline == t.Deadline &&
                                                             t.Description == t.Description
                                                             )));
        }
Exemple #9
0
        public long Add(Debt entity)
        {
            using (var connection = new SqlConnection(_connection))
            {
                connection.Open();
                string sql = @"INSERT INTO Debt(dec_original_value,
								dtt_final_date,
								FK_interest_type,
								int_installments,
								dtt_final_date,
								int_comission,
								dec_final_value) 
								VALUES (@originalValue,
									@originalDate,
									@FKInterestType,
									@installments,
									@finalDate,
									@comission,
									@finalValue)
								SELECT SCOPE_IDENTITY()"                                ;
                connection.Execute(sql, new
                {
                    originalValue  = entity.OriginalValue,
                    originalDate   = entity.OriginalDate,
                    FKInterestType = entity.InterestTypeId,
                    installments   = entity.Installments,
                    finalDate      = entity.FinalDate,
                    comission      = entity.Comission,
                    finalValue     = entity.FinalValue
                });
                connection.Close();
            }
            return(entity.Id);
        }
Exemple #10
0
        public HttpResponseMessage CreatePayment([FromUri] int debtId)
        {
            MessageViewModel messageAttribute = new MessageViewModel();
            Debt             debt             = new Debt();

            if (paymentRepository == null)
            {
                DebtRepository debtRepository = new DebtRepository();
                debt = debtRepository.GetDebtById(debtId);

                if (debt != null)
                {
                    PaymentRepository paymentRepository = new PaymentRepository();
                    Boolean           sucess            = paymentRepository.Insert(debt);

                    if (sucess)
                    {
                        return(Request.CreateResponse(HttpStatusCode.Created, messageAttribute.Create()));
                    }
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not create payment."));
                }
            }
            else
            {
                paymentRepository.Insert(debt);
            }
            return(Request.CreateResponse(HttpStatusCode.Created, messageAttribute.Create()));
        }
        private async void Delete_Click(Object sender, RoutedEventArgs e)
        {
            FrameworkElement fe = sender as FrameworkElement;

            if (fe != null)
            {
                Category cd = fe.DataContext as Category;
                if (cd != null)
                {
                    if (Transaction.RetrieveByCategory(cd.id).Count() != 0 || Debt.RetrieveByCategory(cd.id).Count() != 0)
                    {
                        MessageDialog md = new MessageDialog("Category can't be deleted because there are transactions or debts associated!");
                        await md.ShowAsync();
                    }
                    else if (CategoryViewModel.Categories.Count() == 1)
                    {
                        MessageDialog md = new MessageDialog("Invalid operation. There must be at least one category!");
                        await md.ShowAsync();
                    }
                    else
                    {
                        CategoryViewModel.category = cd;
                        CategoryViewModel.delete();
                    }
                }
            }
        }
Exemple #12
0
        public bool IncreaseDebt(Debt debt, decimal increaseValue)
        {
            bool result = false;

            if (increaseValue <= 0)
            {
                throw new Exception("Increase value must be higher than 0");
            }
            try
            {
                _connection.Open();
                using (var command = new SqlCommand(IncreaseDebtCommand, _connection))
                {
                    command.Parameters.AddWithValue("@DebtId", debt.DebtId);
                    command.Parameters.AddWithValue("@Amount", debt.Amout + increaseValue);
                    var resultCount = command.ExecuteNonQuery();
                    result = resultCount > 0;
                }
                _connection.Close();
            }
            catch (Exception ex)
            {
            }
            return(result);
        }
Exemple #13
0
        public bool AddDebtToPerson(Person person, Debt debt)
        {
            if (debt.Amout < 0)
            {
                throw new Exception("Debt about must be heigher than 0");
            }
            var affectedRows = 0;

            try
            {
                _connection.Open();
                using (var command = new SqlCommand(AddDebtToPersonCommand, _connection))
                {
                    command.Parameters.AddWithValue("@PersonId", person.PersonId);
                    command.Parameters.AddWithValue("@Amount", debt.Amout);
                    command.Parameters.AddWithValue("@DateStart", debt.DateStart);
                    command.Parameters.AddWithValue("@DueDate", debt.DueDate);
                    command.Parameters.AddWithValue("@DebtStatus", debt.DebtStatus);
                    command.Parameters.AddWithValue("@PaidAmount", debt.PaidAmout);

                    affectedRows = command.ExecuteNonQuery();
                }
                _connection.Close();
            }
            catch (Exception ex)
            {
            }

            return(affectedRows > 0);
        }
Exemple #14
0
        /// <summary>Archives a DebtType record.</summary>
        /// <param name="transaction">Commits or rejects a set of commands as a unit</param>
        /// <param name="RowVersion">The version number of this row.</param>
        /// <param name="debtTypeCode">The value for the DebtTypeCode column.</param>
        /// <param name="archive">true to archive the object, false to unarchive it.</param>
        public static void Archive(AdoTransaction adoTransaction, SqlTransaction sqlTransaction, long rowVersion, int debtTypeCode)
        {
            // Accessor for the DebtType Table.
            ServerDataModel.DebtTypeDataTable debtTypeTable = ServerDataModel.DebtType;
            // Rule #1: Make sure the record exists before updating it.
            ServerDataModel.DebtTypeRow debtTypeRow = debtTypeTable.FindByDebtTypeCode(debtTypeCode);
            if ((debtTypeRow == null))
            {
                throw new Exception(string.Format("The DebtType table does not have an element identified by {0}", debtTypeCode));
            }
            // Rule #2: Optimistic Concurrency Check
            if ((debtTypeRow.RowVersion != rowVersion))
            {
                throw new System.Exception("This record is busy.  Please try again later.");
            }
            // Archive the child records.
            for (int index = 0; (index < debtTypeRow.GetDebtRows().Length); index = (index + 1))
            {
                ServerDataModel.DebtRow childDebtRow = debtTypeRow.GetDebtRows()[index];
                Debt.ArchiveChildren(adoTransaction, sqlTransaction, childDebtRow.RowVersion, childDebtRow.DebtId);
            }
            // Increment the row version
            rowVersion = ServerDataModel.RowVersion.Increment();
            // Delete the record in the ADO database.
            debtTypeRow[debtTypeTable.RowVersionColumn] = rowVersion;
            adoTransaction.DataRows.Add(debtTypeRow);
            debtTypeRow.Delete();
            // Archive the record in the SQL database.
            SqlCommand sqlCommand = new SqlCommand("update \"DebtType\" set \"IsArchived\" = 1 where \"DebtTypeCode\"=@debtTypeCode");

            sqlCommand.Connection  = sqlTransaction.Connection;
            sqlCommand.Transaction = sqlTransaction;
            sqlCommand.Parameters.Add(new SqlParameter("@debtTypeCode", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, debtTypeCode));
            sqlCommand.ExecuteNonQuery();
        }
Exemple #15
0
        /// <summary>
        /// Search for an specific debt
        /// </summary>
        /// <param name="MyDebt"> The debt we want to search</param>
        /// <returns></returns>
        public static bool SearchInDebts(Debt MyDebt)
        {
            using (var con = new SQLiteConnection("Data Source =" + SQLDirectory))
            {
                con.Open();
                string Command = $"SELECT ID, DeadLine, Description, Amount " +
                                 $"FROM Debts WHERE ID =" + MyDebt.ID;

                SQLiteCommand Search = new SQLiteCommand(Command, con);

                using (SQLiteDataReader Reader = Search.ExecuteReader())
                {
                    if (Reader.HasRows)
                    {
                        Reader.Close();
                        con.Close();

                        return(true);
                    }

                    Reader.Close();
                    con.Close();

                    return(false);
                }
            }
        }
Exemple #16
0
        public async Task <OperationDetails> UpdateDebtAsync(DebtDto debtDto)
        {
            if (debtDto == null)
            {
                Logger.Error("Debt is null");
                return(new OperationDetails(false, "Something went wrong", "Debt"));
            }

            Debt debt = mapper.Map <DebtDto, Debt>(debtDto);

            try
            {
                await unitOfWork.DebtRepository.UpdateAsync(debt);

                await unitOfWork.SaveAsync();

                Logger.Info("Successfully updated");
                return(new OperationDetails(true));
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return(new OperationDetails(false, ex.Message));
            }
        }
Exemple #17
0
        public async Task <IActionResult> PutDebt(int id, Debt debt)
        {
            User user = await GetCurrentUserAsync();

            if (id != debt.Id || user == null || debt.User != user)
            {
                return(BadRequest());
            }

            _context.Entry(debt).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DebtExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        private void DG_Debt_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (DG_Debt.SelectedCells.Count > 0 && DG_Debt.SelectedCells[0].IsValid)
                {
                    InfoDebt t = DG_Debt.SelectedItem as InfoDebt;
                    using (ApplicationDBContext context = new ApplicationDBContext())
                    {
                        Debt v = (from a in context.Debts
                                  .Include(p => p.DebtInfo)
                                  where a.Id == t.Id
                                  select a).FirstOrDefault();

                        if (v != null)
                        {
                            DebtWindow window = new DebtWindow(v.Id);
                            window.ShowDialog();
                            Refresh();
                        }
                        else
                        {
                            MessageBox.Show("Этот должник не найден в базе");
                        }
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
        // Cadastra um pagamento na tabela
        public Boolean Insert(Debt debt)
        {
            try
            {
                Connection connection = Connection.Instance;

                Payment payment = new Payment();
                payment.Date        = DateTime.Now;
                payment.Value       = debt.Value;
                payment.FriendIdIn  = debt.FriendIdIn;
                payment.FriendIdOut = debt.FriendIdOut;

                connection.dateBase.Payments.Add(payment);

                // Ao pagar a dívida excluir ela do banco
                DebtRepository debtRepository = new DebtRepository();
                debtRepository.DeleteObject(debt);

                connection.dateBase.SaveChanges();

                return(true);
            }
            catch (DbEntityValidationException e)
            {
                return(false);

                throw e;
            }
        }
Exemple #20
0
        //public List<Debt> GetDebts()
        //{
        //    return db.Debts.Where(item => item.IsDebt == true).Include(acc => acc.User).ToList();
        //}

        //public List<Debt> GetPurposes()
        //{
        //    return db.Debts.Where(item => item.IsDebt == false).Include(acc => acc.User).ToList();
        //}
        #endregion

        #region Async Methods
        public async Task <int?> AddItemAsync(Debt debt)
        {
            Debt newDebt = new Debt
            {
                Id              = 0,
                Id2             = debt.Id,
                Title           = debt.Title,
                Date            = debt.Date,
                Term            = debt.Term,
                Type            = debt.Type,
                Sum             = debt.Sum,
                Rate            = debt.Rate,
                MounthlyPayment = debt.MounthlyPayment,
                TotalSum        = debt.TotalSum,
                IsClosed        = debt.IsClosed,
                UpdateTime      = DateTime.Now
            };

            newDebt.User = (debt.User != null) ? db.Users.SingleOrDefault(v => v.Id == debt.User.Id) : null;

            var a = db.Debts.Add(newDebt);

            db.SaveChanges();
            int?id = a.Entity.Id;

            return(await Task.FromResult(id));
        }
Exemple #21
0
        public override bool Approve()
        {
            if (m_PoOrigin == null)
            {
                return(false);
            }
            if (m_PoOrigin.ApproveStatusId == (int)ApproveStatus.Approved)
            {
                return(true);
            }
            ApproveLog log = new ApproveLog();

            log.ApproveCode     = m_PoOrigin.PoCode;
            log.ApproveStatusId = (int)ApproveStatus.Approved;
            try
            {
                using (IUnitOfWork uow = new UnitOfWork())
                {
                    uow.ObjectCoverRepositroy.Approve(m_PoOrigin, ColPrimaryKeyName, (int)ApproveStatus.Approved);
                    Debt.CreateDebt(m_PoOrigin, uow);
                    LogUtility.WriteLog(log, uow);
                    uow.Commit();
                }
                m_PoOrigin.ApproveStatusId = (int)ApproveStatus.Approved;
                UpdateRow <Po>(m_Selectedrow, m_PoOrigin);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public void SecurityPricingSimpleContructionTest()
        {
            Debt s;
            SecuritiesPricing price;

            try
            {
                using (var db = new FGABusinessComponent.BusinessComponent.FGAContext("TEST", compiledModel))
                {
                    s = new Debt(ISIN: "PR0000000001", FinancialInstrumentName: "Pricing Security 1", MaturityDate: new DateTime(2013, 1, 1), interestCoupon: new InterestCalculation(new PercentageRate(2.365), new FrequencyCode(1)));
                    db.Debts.Add(s);
                    CurrencyAndAmount p = new CurrencyAndAmount(1.25, (CurrencyCode)"EUR");
                    price = new SecuritiesPricing(p, DateTime.Parse("31/07/2012"), (TypeOfPriceCode)"MARKET");
                    price.Set(s);
                    db.SecuritiesPricings.Add(price);

                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
                throw e;
            }
        }
        public void AssetClassificationContructionTest()
        {
            Debt s;
            AssetClassification ac;

            try
            {
                using (var db = new FGABusinessComponent.BusinessComponent.FGAContext("PREPROD", compiledModel))
                {
                    s = new Debt(ISIN: "AC0000000001", FinancialInstrumentName: "ClassificationSecurity 1", MaturityDate: new DateTime(2013, 1, 1), interestCoupon: new InterestCalculation(new PercentageRate(2.365), new FrequencyCode(1)));
                    db.Debts.Add(s);
                    db.SaveChanges();


                    ac = new AssetClassification("EXEMPLE");
                    ac.Classification1 = "CLASSIF1";
                    ac.Classification2 = "CLASSIF2";
                    ac.Classification3 = "CLASSIF3";
                    ac.Classification4 = "CLASSIF4";

                    s.Add(ac);

                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
                throw e;
            }
        }
Exemple #24
0
        public async Task <OperationDetails> CloseDebt(int id)
        {
            DebtDto debtDto = await GetDebtByIdAsync(id);

            if (debtDto == null)
            {
                Logger.Error("Debt is null");
                return(new OperationDetails(false, "Something went wrong", "Debt"));
            }

            debtDto.Status = StatusDebt.Closed;

            Debt debt = mapper.Map <DebtDto, Debt>(debtDto);

            try
            {
                await unitOfWork.DebtRepository.UpdateAsync(debt);

                await unitOfWork.SaveAsync();

                Logger.Info("Successfully updated");
                return(new OperationDetails(true));
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return(new OperationDetails(false, ex.Message));
            }
        }
Exemple #25
0
        public ActionResult Add(string key, Guid userid)
        {
            var msg   = new JsonMessage(false, "Thêm mới dữ liệu thành công.");
            var model = new Debt();

            try
            {
                if (key != Keyapi)
                {
                    return(Json(0, JsonRequestBehavior.AllowGet));
                }
                UpdateModel(model);
                model.Note        = HttpUtility.UrlDecode(model.Note);
                model.DateCreated = DateTime.Now.TotalSeconds();
                if (model.Type == 2)
                {
                    model.Price = model.Price * (-1);
                }
                model.IsDeleted   = false;
                model.UserCreated = userid;
                _da.Add(model);
                _da.Save();
            }
            catch (Exception ex)
            {
                msg.Erros   = true;
                msg.Message = "Dữ liệu chưa được thêm mới.";
                Log2File.LogExceptionToFile(ex);
            }
            return(Json(msg, JsonRequestBehavior.AllowGet));
        }
Exemple #26
0
        public async Task <ServiceResponse <int> > Update(Debt updatedDebt)
        {
            var debt = _context.Debts.FirstOrDefault(d => d.Id == updatedDebt.Id);

            if (debt == null)
            {
                return(new ServiceResponse <int>("The debt was not found."));
            }

            debt.TitleNumber            = updatedDebt.TitleNumber;
            debt.DebtorName             = updatedDebt.DebtorName;
            debt.DebtorCPF              = updatedDebt.DebtorCPF;
            debt.InterestPercentageRate = updatedDebt.InterestPercentageRate;
            debt.PenaltyPercentageRate  = updatedDebt.PenaltyPercentageRate;

            _context.Debts.Update(debt);

            if (await _context.SaveChangesAsync() > 0)
            {
                return(new ServiceResponse <int>(debt.Id));
            }
            else
            {
                return(new ServiceResponse <int>("Error when trying to update a debt."));
            }
        }
Exemple #27
0
        public void insertDebt(Debt _debt)
        {
            try
            {
                if (!ExistDebt(_debt.Id))
                {
                    Query = "INSERT INTO deuda(IDClient, IDBanda, nameClient, codeFact, amount, date, active) " +
                            "VALUES('" + _debt.IDClient + "','" + _debt.IDBanda + "','" + _debt.NameClient + "','"
                            + _debt.CodFact + "','" + _debt.Amount + "','" + _debt.Date + "',"
                            + _debt.Active + ");";
                }
                else
                {
                    Query = "UPDATE deuda SET amount='" + _debt.Amount + "' WHERE id='" + _debt.Id + "';";
                }

                MySqlCommand Cmm = new MySqlCommand(Query, ConectDB.getConection());
                Cmm.ExecuteNonQuery();

                Cmm.Connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\ninsertDebt", "Error del Sistema", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public ActionResult Create(CreateDebtViewModel model)
        {
            ViewBag.Parent = "Quản lý giao hàng";
            ViewBag.Child  = "Thanh Toán Công nợ";
            isAdminLogged();
            var   user  = Session["admin"] as Account;
            Staff staff = _staffService.GetByAccount(user.UserName);
            var   debt  = new Debt
            {
                CreatedDate   = DateTime.Now,
                Purchase      = model.moneyDebt,
                idDistributor = model.idDistributor,
                idStaff       = staff.idStaff,
            };
            var result = _debtService.CreateDebt(debt);

            if (result == "thanh cong")
            {
                var dis = _distributorService.GetDistributor(model.idDistributor);
                dis.debt -= model.moneyDebt;
                _distributorService.UpdateDebt(dis.idDistributor, dis.debt.Value);
                model.debt    = dis.debt.Value;
                model.idDebt  = debt.idDebt;
                ViewBag.types = 2;
                ViewBag.msg   = "Lập phiếu công nợ thành công";
                return(RedirectToAction("Create", new { idDistributor = model.idDistributor }));
            }
            else
            {
                ViewBag.types = 1;
                ViewBag.msg   = "Lập phiếu công nợ thất bại";
                return(View(model));
            }
        }
        public async Task <ActionResult> Add(WebUser user, DebtAddModel model)
        {
            if (ModelState.IsValid)
            {
                var debt = new Debt()
                {
                    DateBegin    = DateTime.Now,
                    Person       = model.Person,
                    TypeOfFlowId = model.TypeOfFlowId,
                    AccountId    = model.AccountId,
                    Summ         = model.Summ,
                    UserId       = user.Id
                };
                try
                {
                    await _createCloseDebtService.CreateAsync(debt);
                }
                catch (ServiceException e)
                {
                    throw new WebUiException($"Ошибка в контроллере {nameof(DebtController)} в методе {nameof(Add)}", e);
                }

                return(RedirectToAction("DebtList"));
            }
            model.Accounts = (await AccountList(user.Id)).ToList();
            return(PartialView("_Add", model));
        }
        public async Task <ActionResult> ClosePartially(DebtEditModel model)
        {
            Debt debt = null;

            if (ModelState.IsValid)
            {
                try
                {
                    await _createCloseDebtService.PartialCloseAsync(model.DebtId, model.Sum, model.AccountId);
                }
                catch (ServiceException e)
                {
                    throw new WebUiException(
                              $"Ошибка в контроллере {nameof(DebtController)} в методе {nameof(ClosePartially)}", e);
                }
                catch (ArgumentOutOfRangeException)
                {
                    ModelState.AddModelError("", "Введенная сумма больше суммы долга");
                    debt = await _debtService.GetItemAsync(model.DebtId);
                    await FillDebtViewModel(debt, model);

                    return(PartialView("_ClosePartially", model));
                }

                return(RedirectToAction("DebtList"));
            }
            debt = await _debtService.GetItemAsync(model.DebtId);
            await FillDebtViewModel(debt, model);

            return(PartialView("_ClosePartially", model));
        }
Exemple #31
0
 public CreditorRepayment(Debt debt, decimal monthlyRepayment)
 {
     Debt = debt;
     MonthlyRepayment = monthlyRepayment;
 }
Exemple #32
0
 public static Debt CreateDebt(long ID, decimal amount)
 {
     Debt debt = new Debt();
     debt.Id = ID;
     debt.Amount = amount;
     return debt;
 }
Exemple #33
0
 public void AddToDebts(Debt debt)
 {
     base.AddObject("Debts", debt);
 }