Beispiel #1
0
        public IActionResult Update(InvoicePayment model)
        {
            string note = AppGlobal.InitString;

            model.Initialization(InitType.Update, RequestUserID);
            int result = _invoicePaymentResposistory.Update(model.Id, model);

            if (result > 0)
            {
                note = AppGlobal.Success + " - " + AppGlobal.EditSuccess;
            }
            else
            {
                note = AppGlobal.Success + " - " + AppGlobal.EditFail;
            }
            return(Json(note));
        }
        public ActionResult <string> SaveChange(InvoicePayment model)
        {
            Result routeResult;
            int    result = 0;

            if (model.Id > 0)
            {
                model.Initialization(InitType.Update, RequestUserID);
                result = _invoicePaymentResposistory.Update(model.Id, model);

                if (result > 0)
                {
                    routeResult = new Result()
                                  .setResultType(ResultType.Success)
                                  .setMessage(AppGlobal.EditSuccess);
                }
                else
                {
                    routeResult = new Result()
                                  .setResultType(ResultType.Error)
                                  .setErrorType(ErrorType.EditError)
                                  .setMessage(AppGlobal.EditFail);
                }
            }
            else
            {
                model.Initialization(InitType.Insert, RequestUserID);
                result = _invoicePaymentResposistory.Create(model);

                if (result > 0)
                {
                    routeResult = new Result()
                                  .setResultType(ResultType.Success)
                                  .setMessage(AppGlobal.CreateSuccess);
                }
                else
                {
                    routeResult = new Result()
                                  .setResultType(ResultType.Error)
                                  .setErrorType(ErrorType.InsertError)
                                  .setMessage(AppGlobal.CreateFail);
                }
            }

            return(ObjectToJson(routeResult));
        }
Beispiel #3
0
        public static List <InvoicePayment> GetiInvoicePayments(OINV_Sales sale)
        {
            lock (Extensions.Locker)
            {
                var db = ContextFactory.GetDBContext();

                var cashAccount = db.PaymentTypes
                                  .FirstOrDefault(p => p.IdPaymentType == 1); // Cuenta para efectivo

                var creditAccount = db.PaymentTypes
                                    .FirstOrDefault(p => p.IdPaymentType == 2); // Cuenta para tarjeta..


                var TDate = sale.DocDate;


                var pagosaloha = (from inaloha in db.InvoiceALOHAs
                                  where inaloha.Date == TDate
                                  select new
                {
                    alohaid = inaloha.IdInvoiceALOHA,
                    cash = inaloha.Cash,
                    credit = inaloha.Credit,
                }).FirstOrDefault();

                var pagos = new List <InvoicePayment>();

                //pago en efectivo
                var pagoe = new InvoicePayment();
                pagoe.WhsCode     = Config.WhsCode;
                pagoe.Amount      = pagosaloha.cash;
                pagoe.PaymentType = cashAccount;

                pagos.Add(pagoe);

                //pago tarjeta
                var pagot = new InvoicePayment();
                pagot.WhsCode     = Config.WhsCode;
                pagot.Amount      = pagosaloha.credit;
                pagot.PaymentType = creditAccount;

                pagos.Add(pagot);

                return(pagos);
            }
        }
Beispiel #4
0
        public BillingInvoiceViewModel()
        {
            Amount   = "Zero";
            Message  = "";
            Invoice  = new Invoice();
            Payment  = new InvoicePayment();
            Details  = new List <InvoiceDetails>();
            Tendered = new List <InvoicePaymentDetails>();
            Payments = new List <InvoicePaymentDetails>();

            //Initialize Items
            for (int i = 0; i < 20; i++)
            {
                Payments.Add(new InvoicePaymentDetails());
            }

            Modes = new List <SelectListItem>();
        }
Beispiel #5
0
        public static InvoicePayment Create(InvoicePaymentAddModel model, string depositFrom, decimal amount, string userId)
        {
            var invoicePayment = new InvoicePayment()
            {
                InvoiceId     = model.InvoiceId,
                PaymentMode   = model.PaymentMode,
                BankAccountId = model.BankAccountId,
                ChequeNumber  = model.ChequeNumber,
                DepositFrom   = depositFrom,
                Amount        = amount,
                PaymentDate   = model.PaymentDate,
                Description   = model.Description,
                Status        = Constants.RecordStatus.Active,
                CreatedBy     = userId ?? "0",
                CreatedOn     = Utility.GetDateTime()
            };

            return(invoicePayment);
        }
Beispiel #6
0
        public async Task Create_WithInvalidApiKey_ShouldThrowNotAuthorizedException()
        {
            //arrange
            var http = A.Fake <IHttpClient>();
            var sut  = GetSystemUnderTest(http);

            var expectedRequestUri = new Uri("/api/invoice-payments", UriKind.Relative);

            A.CallTo(() => http.PostAsync(expectedRequestUri, A <string> .Ignored, A <CancellationToken> .Ignored))
            .ThrowsAsync(ExceptionFactory.CreateNotAuthorizedException);

            var model = new InvoicePayment {
                InvoiceId = 1, Amount = 17f
            };

            await Assert.ThrowsAsync <NotAuthorizedException>(() => sut.CreatePaymentAsync(model));

            A.CallTo(() => http.PostAsync(expectedRequestUri, A <string> .Ignored, A <CancellationToken> .Ignored))
            .MustHaveHappenedOnceExactly();
        }
        public static void OnTransactionConfirmed(JToken jsonParams)
        {
            TransactionConfirmedModel model = jsonParams.ToObject <TransactionConfirmedModel>();

            using (DBEntities dbe = new DBEntities())
            {
                InvoicePayment payment = dbe.InvoicePayment.Include("Invoice").Include("Invoice.CreatedBy").SingleOrDefault(p => p.Address == model.Address && p.CurrencyCode == model.CurrencyCode);
                if (payment != null)
                {
                    double amountRequired = GetAmountRequired(payment.Invoice.FiatAmount, (double)payment.ExchangeRate, model.CurrencyCode);

                    if (model.Amount >= amountRequired)
                    {
                        payment.Invoice.State         = (int)InvoiceState.TRANSACTION_CONFIRMED;
                        payment.Invoice.TransactionId = model.TXID;
                        payment.Invoice.DateReceived  = DateTime.Now;
                        dbe.SaveChanges();

                        // send mail
                        EmailManager.SendMailToPaymentReciever(payment.Invoice, model);
                        EmailManager.SendMailToPaymentSender(payment.Invoice, model);
                    }
                    else
                    {
                        var transactionTime = DateTimeOffset.FromUnixTimeSeconds(model.Timestamp).UtcDateTime;

                        // Special case: if the transaction is less that 3 minutes late, previous exchange rate is still alowed
                        if (payment.Invoice.ExchangeRateSetTime != null && transactionTime.Subtract(payment.Invoice.ExchangeRateSetTime.Value).TotalMinutes < 3)
                        {
                            double previousAmountRequired = GetAmountRequired(payment.Invoice.FiatAmount, (double)payment.PreviousExchangeRate, model.CurrencyCode);
                            if (model.Amount >= previousAmountRequired)
                            {
                                payment.Invoice.State         = (int)InvoiceState.TRANSACTION_SEEN;
                                payment.Invoice.TransactionId = model.TXID;
                                dbe.SaveChanges();
                            }
                        }
                    }
                }
            }
        }
        public static void OnTransactionSeen(JToken jsonParams)
        {
            TransactionSeenModel model = jsonParams.ToObject <TransactionSeenModel>();

            //check if theres invoice with the same address and currencycode + amount in invoice is >= amount received
            using (DBEntities dbe = new DBEntities())
            {
                InvoicePayment payment = dbe.InvoicePayment.Include("Invoice").SingleOrDefault(p => p.Address == model.Address && p.CurrencyCode == model.CurrencyCode);
                if (payment != null)
                {
                    double amountRequired = GetAmountRequired(payment.Invoice.FiatAmount, (double)payment.ExchangeRate, model.CurrencyCode);
                    if (payment.Invoice.State == (int)InvoiceState.NOT_PAID)
                    {
                        if (model.Amount >= amountRequired)
                        {
                            payment.Invoice.State         = (int)InvoiceState.TRANSACTION_SEEN;
                            payment.Invoice.TransactionId = model.TXID;
                            dbe.SaveChanges();
                        }
                        else
                        {
                            var transactionTime = DateTimeOffset.FromUnixTimeSeconds(model.Timestamp).UtcDateTime;

                            // Special case: if the transaction is less that 3 minutes late, previous exchange rate is still alowed
                            if (payment.Invoice.ExchangeRateSetTime != null && transactionTime.Subtract(payment.Invoice.ExchangeRateSetTime.Value).TotalMinutes < 3)
                            {
                                double previousAmountRequired = GetAmountRequired(payment.Invoice.FiatAmount, (double)payment.PreviousExchangeRate, model.CurrencyCode);
                                if (model.Amount >= previousAmountRequired)
                                {
                                    payment.Invoice.State         = (int)InvoiceState.TRANSACTION_SEEN;
                                    payment.Invoice.TransactionId = model.TXID;
                                    dbe.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #9
0
        private void AddPaymentClick(object sender, EventArgs eventArgs)
        {
            PaymentDialog d = new PaymentDialog(invoice);

            if (d.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            InvoicePayment      ip   = d.Payment;
            NameValueCollection data = new NameValueCollection();

            data.Add("invoiceID", invoice.ID);
            data.Add("amount", ip.Amount);
            data.Add("date", ip.Date.ToString("yyyy-MM-dd"));
            data.Add("comment", ip.Comment);
            data.Add("houseID", house.ID);
            Invoice i = Caller.Post <Invoice>("AddInvoicePayment", data);

            if (i != null)
            {
                gui.ShowCurrent();
            }
        }
        public static bool SetInvoicePaymentSerial(InvoicePayment invoicePayment)
        {
            if (invoicePayment == null)
            {
                return(false);
            }

            if (IsInvoicePaymentHasSerial(invoicePayment))
            {
                return(true);
            }

            string nextSerial = FinancialBusinessLogicLibrary.GetNextMedicalInvoiceSerial();

            if (string.IsNullOrEmpty(nextSerial) || string.IsNullOrWhiteSpace(nextSerial))
            {
                return(false);
            }

            invoicePayment.PaymentSerial = nextSerial;

            return(true);
        }
Beispiel #11
0
        public async Task GetById_WithValidInputValue_ShouldReturnCorrectValue()
        {
            //arrange
            const int    id = 872254;
            var          expectedRequestUri = new Uri($"/api/invoice-payments/{id}", UriKind.Relative);
            const string responseBody       = "{\"invoice-payment\":{\"id\":\"872254\",\"created\":\"2015-06-04T09:51:54+02:00\",\"invoice_id\":\"1220304\",\"user_id\":\"52821\",\"date\":\"2015-05-04\",\"amount\":\"-17\",\"comment\":\"\",\"transaction_purpose\":\"\",\"currency_code\":\"\",\"quote\":\"1\",\"type\":\"\",\"customfield\":\"\"}}";
            var          expectedResult     = new InvoicePayment
            {
                Id                 = 872254,
                Created            = DateTime.Parse("2015-06-04T09:51:54+02:00", CultureInfo.InvariantCulture),
                InvoiceId          = 1220304,
                UserId             = 52821,
                Date               = DateTime.Parse("2015-05-04", CultureInfo.InvariantCulture),
                Amount             = -17f,
                Comment            = "",
                TransactionPurpose = "",
                CurrencyCode       = "",
                Quote              = 1,
                MarkInvoiceAsPaid  = true
            };

            var http = A.Fake <IHttpClient>();

            A.CallTo(() => http.GetAsync(expectedRequestUri, A <CancellationToken> .Ignored))
            .Returns(Task.FromResult(responseBody));

            var sut = GetSystemUnderTest(http);

            //act
            var result = await sut.GetPaymentByIdAsync(id);

            //assert
            A.CallTo(() => http.GetAsync(expectedRequestUri, A <CancellationToken> .Ignored))
            .MustHaveHappenedOnceExactly();

            result.Should().BeEquivalentTo(expectedResult);
        }
    public static void AddInvoicePayment(InvoicePayment payment)
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        SqlCommand command;
        connection.Open();
        try
        {
            command = connection.CreateCommand();

            command.CommandText = "INSERT INTO UnileverInvoiceTrackingSystem.dbo.invoicepayment (invoiceno, paymentstatus, amountreceived, balance, paymentremarks, paiddate) VALUES (@IN,@PS,@AR,@B,@PR,@PD);";

            command.Parameters.AddWithValue("@IN", Convert.ToInt64(payment.InvoiceNo));

            command.Parameters.AddWithValue("@PS", Convert.ToString(payment.PaymentStatus));

            command.Parameters.AddWithValue("@AR", Convert.ToDecimal(payment.AmountReceived));

            command.Parameters.AddWithValue("@B", Convert.ToDecimal(payment.Balance));

            command.Parameters.AddWithValue("@PR", Convert.ToString(payment.PaymentRemarks));

            command.Parameters.AddWithValue("@PD", DBNull.Value);

            command.ExecuteNonQuery();
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }
    }
Beispiel #13
0
        public JsonResult GetInvoicesByPatientId(long id, long statusid, string DateStart, string DateEnd, long?invoiceId = null)
        {
            List <PatientInvoice> onlypatientInvoices = new List <PatientInvoice>();
            List <PatientInvoice> patientInvoices;

            DateTime invoiceDateStart = DateTime.Parse("1/1/1980");
            DateTime invoiceDateEnd   = DateTime.Today;

            if (IsDate(DateEnd) && IsDate(DateStart))
            {
                invoiceDateStart = DateTime.Parse(DateStart);
                invoiceDateEnd   = DateTime.Parse(DateEnd);
            }


            using (PatientInvoiceRepository repository = new PatientInvoiceRepository())
            {
                /* ParameterExpression argParam = Expression.Parameter(typeof(PatientInvoice), "s");
                 * Expression patientProperty = Expression.Property(argParam, "PatientID");
                 * Expression statusProperty = Expression.Property(argParam, "InvoiceStatusId");
                 *
                 * var val1 = Expression.Constant(id);
                 * var val2 = Expression.Constant(statusid);
                 *
                 * Expression e1 = Expression.Equal(patientProperty, val1);
                 * Expression e2 = Expression.Equal(statusProperty, val2);
                 *
                 * BinaryExpression andExp;*/


                // var andExp = e1;

                //var lambda = Expression.Lambda<Func<PatientInvoice, bool>>(andExp, argParam);
                Expression <Func <PatientInvoice, bool> > lambda;


                if (id == 0)
                {
                    if (statusid == 0)
                    {
                        lambda = (x => x.Active == true && x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && (invoiceId == null ? x.Id > 0 : x.Id == invoiceId));
                    }
                    else
                    {
                        lambda = (x => x.InvoiceStatusId == statusid && x.Active == true && x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && (invoiceId == null ? x.Id > 0 : x.Id == invoiceId));
                    }
                }
                else
                {
                    if (statusid == 0)
                    {
                        lambda = (x => x.PatientID == id && x.Active == true && x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && (invoiceId == null ? x.Id > 0 : x.Id == invoiceId));
                    }
                    else
                    {
                        lambda = (x => x.PatientID == id && x.Active == true && x.InvoiceStatusId == statusid && x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && (invoiceId == null ? x.Id > 0 : x.Id == invoiceId));
                    }
                }


                patientInvoices = repository.GetByQuery(lambda).ToList();
                patientInvoices = patientInvoices.OrderByDescending(x => x.InvoiceDate).ToList();



                foreach (PatientInvoice pinvoice in patientInvoices)
                {
                    PatientInvoice onlyPatientInvoice = new PatientInvoice();
                    Patient        patient            = new Patient();
                    onlyPatientInvoice.Patient = patient;

                    onlyPatientInvoice.Id                = pinvoice.Id;
                    onlyPatientInvoice.InvoiceDate       = pinvoice.InvoiceDate;
                    onlyPatientInvoice.DueDate           = pinvoice.DueDate;
                    onlyPatientInvoice.PatientID         = pinvoice.PatientID;
                    onlyPatientInvoice.TotalAmount       = pinvoice.TotalAmount;
                    onlyPatientInvoice.TotalDiscount     = pinvoice.TotalDiscount;
                    onlyPatientInvoice.InvoiceStatusId   = pinvoice.InvoiceStatusId;
                    onlyPatientInvoice.ItemDiscount      = pinvoice.ItemDiscount;
                    onlyPatientInvoice.UserId            = pinvoice.UserId;
                    onlyPatientInvoice.LabStatusId       = pinvoice.LabStatusId;
                    onlyPatientInvoice.IsRefunded        = pinvoice.IsRefunded;
                    onlyPatientInvoice.Patient.FirstName = pinvoice.Patient.FirstName;
                    onlyPatientInvoice.Patient.LastName  = pinvoice.Patient.LastName;
                    onlyPatientInvoice.UserId            = GetLoggedinUserInfo().UserId;

                    foreach (InvoicePayment invoicepayment in pinvoice.InvoicePayments)
                    {
                        InvoicePayment invoicePayment = new InvoicePayment();

                        invoicePayment.Id = invoicepayment.Id;
                        invoicePayment.PatientInvoiceId = invoicepayment.PatientInvoiceId;
                        invoicePayment.Amount           = invoicepayment.Amount;
                        invoicePayment.PaymentID        = invoicepayment.PaymentID;
                        invoicePayment.UserId           = invoicepayment.UserId;
                        onlyPatientInvoice.InvoicePayments.Add(invoicePayment);
                    }

                    foreach (PatientService c in pinvoice.PatientServices)
                    {
                        PatientService patientstitem = new PatientService();
                        Item           item          = new Item();
                        ItemCategory   Category      = new ItemCategory();
                        patientstitem.Item = item;
                        patientstitem.Item.ItemCategory = Category;


                        patientstitem.Id                   = c.Id;
                        patientstitem.PatientID            = c.PatientID;
                        patientstitem.ItemId               = c.ItemId;
                        patientstitem.InvoiceID            = c.InvoiceID;
                        patientstitem.ReceiptId            = c.ReceiptId;
                        patientstitem.PatientAdmissionId   = c.PatientAdmissionId;
                        patientstitem.ServiceListPrice     = c.ServiceListPrice;
                        patientstitem.ServiceActualPrice   = c.ServiceActualPrice;
                        patientstitem.ServiceQuantity      = c.ServiceQuantity;
                        patientstitem.ServiceDate          = c.ServiceDate;
                        patientstitem.UserId               = c.UserId;
                        patientstitem.Discount             = c.Discount;
                        patientstitem.DiscountAfterInvoice = c.DiscountAfterInvoice;
                        patientstitem.Refund               = c.Refund;
                        patientstitem.RefundNote           = c.RefundNote;

                        patientstitem.Billed       = c.Billed;
                        patientstitem.LabStatusId  = c.LabStatusId;
                        patientstitem.ReferralFee  = c.ReferralFee;
                        patientstitem.DeliveryDate = c.DeliveryDate;
                        patientstitem.DeliveryTime = c.DeliveryTime;


                        patientstitem.Item.Name        = c.Item.Name;
                        patientstitem.Item.GenericName = c.Item.GenericName;

                        if (c.Item.ItemCategory != null)
                        {
                            patientstitem.Item.ItemCategory.Name = c.Item.ItemCategory.Name;
                        }

                        patientstitem.Item.ReferralAllowed = c.Item.ReferralAllowed;

                        patientstitem.ReferralFeePaid   = c.ReferralFeePaid;
                        patientstitem.ServiceProviderId = c.ServiceProviderId;
                        patientstitem.UserId            = GetLoggedinUserInfo().UserId;

                        onlyPatientInvoice.PatientServices.Add(patientstitem);
                    }

                    onlypatientInvoices.Add(onlyPatientInvoice);
                }

                if (onlypatientInvoices == null)
                {
                    return(Json(HttpNotFound(), JsonRequestBehavior.AllowGet));
                }

                return(Json(onlypatientInvoices, JsonRequestBehavior.AllowGet));
            }
        }
Beispiel #14
0
 /// <summary>
 /// Updates an invoice payment
 /// </summary>
 /// <param name="invoicePayment">The invoice payment to update</param>
 /// <returns>The updated invoice payment</returns>
 public InvoicePayment Update(InvoicePayment invoicePayment)
 {
     return(BaseUpdate(invoicePayment, invoicePayment.Number));
 }
 public static bool IsInvoicePaymentHasSerial(InvoicePayment invoicePayment)
 {
     return(invoicePayment != null && invoicePayment.PaymentSerial != null);
 }
    public async Task Test_InvoicePayment_CRUD()
    {
        #region Arrange

        var tmpCustomer = await FortnoxClient.CustomerConnector.CreateAsync(new Customer()
        {
            Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis"
        });

        var tmpArticle = await FortnoxClient.ArticleConnector.CreateAsync(new Article()
        {
            Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 10
        });

        var invoiceConnector = FortnoxClient.InvoiceConnector;
        var tmpInvoice       = await invoiceConnector.CreateAsync(new Invoice()
        {
            CustomerNumber = tmpCustomer.CustomerNumber,
            InvoiceDate    = new DateTime(2020, 1, 20),
            DueDate        = new DateTime(2020, 6, 20),
            InvoiceRows    = new List <InvoiceRow>()
            {
                new InvoiceRow()
                {
                    ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 2, Price = 10
                },
            }
        });

        await invoiceConnector.BookkeepAsync(tmpInvoice.DocumentNumber);

        #endregion Arrange

        var connector = FortnoxClient.InvoicePaymentConnector;

        #region CREATE

        var newInvoicePayment = new InvoicePayment()
        {
            InvoiceNumber  = tmpInvoice.DocumentNumber,
            Amount         = 10.5m,
            AmountCurrency = 10.5m,
            PaymentDate    = new DateTime(2020, 2, 1)
        };

        var createdInvoicePayment = await connector.CreateAsync(newInvoicePayment);

        Assert.AreEqual("2020-02-01", createdInvoicePayment.PaymentDate?.ToString(ApiConstants.DateFormat));

        #endregion CREATE

        #region UPDATE

        createdInvoicePayment.PaymentDate = new DateTime(2020, 3, 1);

        var updatedInvoicePayment = await connector.UpdateAsync(createdInvoicePayment);

        Assert.AreEqual("2020-03-01", updatedInvoicePayment.PaymentDate?.ToString(ApiConstants.DateFormat));

        #endregion UPDATE

        #region READ / GET

        var retrievedInvoicePayment = await connector.GetAsync(createdInvoicePayment.Number);

        Assert.AreEqual("2020-03-01", retrievedInvoicePayment.PaymentDate?.ToString(ApiConstants.DateFormat));

        #endregion READ / GET

        #region DELETE

        await connector.DeleteAsync(createdInvoicePayment.Number);

        await Assert.ThrowsExceptionAsync <FortnoxApiException>(
            async() => await connector.GetAsync(createdInvoicePayment.Number),
            "Entity still exists after Delete!");

        #endregion DELETE

        #region Delete arranged resources
        //Can't cancel invoice after it is booked
        //FortnoxClient.InvoiceConnector.Cancel(tmpInvoice.DocumentNumber);
        //FortnoxClient.CustomerConnector.Delete(tmpCustomer.CustomerNumber);
        //FortnoxClient.ArticleConnector.Delete(tmpArticle.ArticleNumber);

        #endregion Delete arranged resources
    }
Beispiel #17
0
 /// <summary>
 /// Creates a new invoicePayment
 /// </summary>
 /// <param name="invoicePayment">The invoicePayment to create</param>
 /// <returns>The created invoicePayment</returns>
 public InvoicePayment Create(InvoicePayment invoicePayment)
 {
     return(CreateAsync(invoicePayment).Result);
 }
Beispiel #18
0
 public async Task <InvoicePayment> CreateAsync(InvoicePayment invoicePayment)
 {
     return(await BaseCreate(invoicePayment));
 }
        protected void InvoiceRecordButton_Click(object sender, EventArgs e)
        {
            DateTime duedate;
            duedate = Convert.ToDateTime(InvoiceDateTextBox.Text);
            duedate = duedate.AddDays(40);

            InvoiceDetail invoiceentry = new InvoiceDetail();

            InvoicePayment invoicepayment = new InvoicePayment();

            ShortageDetails shortagedetail = new ShortageDetails();

            invoiceentry.InvoiceNo = Convert.ToInt64(InvoiceNoTextBox.Text);
            invoiceentry.InvoiceTerritory = getterritory();
            invoiceentry.InvoiceRegion = InvoiceRegionDropDownList.SelectedValue;
            invoiceentry.InvoiceDate = Convert.ToDateTime(InvoiceDateTextBox.Text).Date;
            invoiceentry.InvoiceDueDate = duedate.Date;
            invoiceentry.InvoiceAging = Convert.ToInt32((DateTime.Now.Date - Convert.ToDateTime(InvoiceDateTextBox.Text).Date).TotalDays);
            invoiceentry.NPA = Convert.ToDecimal(NetAmountTextBox.Text);
            invoiceentry.SC = ShortageCommentsDropDownList.SelectedValue;

            InvoiceDetailHandler.AddInvoiceDetail(invoiceentry);

            invoicepayment.InvoiceNo = Convert.ToInt64(InvoiceNoTextBox.Text);
            invoicepayment.PaymentStatus = "Non-Paid";
            invoicepayment.AmountReceived = Convert.ToDecimal("0.00");
            invoicepayment.Balance = Convert.ToDecimal("0.00");
            invoicepayment.PaymentRemarks = "Under Progress";

            InvoicePaymentHandler.AddInvoicePayment(invoicepayment);

            shortagedetail.InvoiceNo = Convert.ToInt64(InvoiceNoTextBox.Text);
            shortagedetail.SD = ShortageDetailsTextBox.Text;

            ShortageDetailHandler.AddShortageDetail(shortagedetail);

            cleardata();
        }
 public async Task Create(InvoicePayment payment)
 {
     db.Add(payment);
     await context.SaveChangesAsync();
 }
 public async Task Delete(InvoicePayment payment)
 {
     payment.DeletedAt = DateTime.Now;
     db.Update(payment);
     await context.SaveChangesAsync();
 }
Beispiel #22
0
 /// <summary>
 /// Create a new invoice payment
 /// </summary>
 /// <param name="invoicePayment">The invoice payment to be created</param>
 /// <returns>The created invoice payment</returns>
 public InvoicePayment Create(InvoicePayment invoicePayment)
 {
     return(BaseCreate(invoicePayment));
 }
Beispiel #23
0
 private void CreateInvoice()
 {
     if (!Page.IsPostBack && Request.QueryString["i"] != null)
      {
     var oInvoicePayment = new InvoicePayment();
     oInvoicePayment.Number = Request.QueryString["i"];
     _invoicePayments.Add(oInvoicePayment);
      }
      else
      {
     _invoicePayments.Add(new InvoicePayment());
      }
 }
 public InvoicePayment Delete(InvoicePayment domain)
 {
     Delete(domain.Id);
     return(domain);
 }
Beispiel #25
0
 public void AddInvoicePayment(InvoicePayment invoicePayment)
 {
     UnitOfWork.InvoicePaymentRepository.Add(invoicePayment);
 }
        public static async Task <InvoicePayment> UpdateInvoicePaymentAsync(FortnoxApiRequest request, string invoicePaymentNumber, InvoicePayment invoicePayment)
        {
            var apiRequest =
                new FortnoxApiClientRequest <SingleResource <InvoicePayment> >(HttpMethod.Put, request.AccessToken, request.ClientSecret,
                                                                               $"{ApiEndpoints.InvoicePayments}/{invoicePaymentNumber}")
            {
                Data = new SingleResource <InvoicePayment> {
                    Data = invoicePayment
                }
            };

            return((await FortnoxAPIClient.CallAsync <SingleResource <InvoicePayment>, SingleResource <InvoicePayment> >(apiRequest)).Data);
        }
Beispiel #27
0
        public void Test_InvoicePayment_CRUD()
        {
            #region Arrange

            var tmpCustomer = new CustomerConnector().Create(new Customer()
            {
                Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis"
            });
            var tmpArticle = new ArticleConnector().Create(new Article()
            {
                Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 10
            });
            var invoiceConnector = new InvoiceConnector();
            var tmpInvoice       = invoiceConnector.Create(new Invoice()
            {
                CustomerNumber = tmpCustomer.CustomerNumber,
                InvoiceDate    = new DateTime(2020, 1, 20),
                DueDate        = new DateTime(2020, 6, 20),
                InvoiceRows    = new List <InvoiceRow>()
                {
                    new InvoiceRow()
                    {
                        ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 2, Price = 10
                    },
                }
            });
            invoiceConnector.Bookkeep(tmpInvoice.DocumentNumber);
            MyAssert.HasNoError(invoiceConnector);
            #endregion Arrange

            IInvoicePaymentConnector connector = new InvoicePaymentConnector();

            #region CREATE

            var newInvoicePayment = new InvoicePayment()
            {
                InvoiceNumber  = tmpInvoice.DocumentNumber,
                Amount         = 10.5m,
                AmountCurrency = 10.5m,
                PaymentDate    = new DateTime(2020, 2, 1)
            };

            var createdInvoicePayment = connector.Create(newInvoicePayment);
            MyAssert.HasNoError(connector);
            Assert.AreEqual("2020-02-01", createdInvoicePayment.PaymentDate?.ToString(APIConstants.DateFormat));

            #endregion CREATE

            #region UPDATE

            createdInvoicePayment.PaymentDate = new DateTime(2020, 3, 1);

            var updatedInvoicePayment = connector.Update(createdInvoicePayment);
            MyAssert.HasNoError(connector);
            Assert.AreEqual("2020-03-01", updatedInvoicePayment.PaymentDate?.ToString(APIConstants.DateFormat));

            #endregion UPDATE

            #region READ / GET

            var retrievedInvoicePayment = connector.Get(createdInvoicePayment.Number);
            MyAssert.HasNoError(connector);
            Assert.AreEqual("2020-03-01", retrievedInvoicePayment.PaymentDate?.ToString(APIConstants.DateFormat));

            #endregion READ / GET

            #region DELETE

            connector.Delete(createdInvoicePayment.Number);
            MyAssert.HasNoError(connector);

            retrievedInvoicePayment = connector.Get(createdInvoicePayment.Number);
            Assert.AreEqual(null, retrievedInvoicePayment, "Entity still exists after Delete!");

            #endregion DELETE

            #region Delete arranged resources

            new CustomerConnector().Delete(tmpCustomer.CustomerNumber);
            new ArticleConnector().Delete(tmpArticle.ArticleNumber);

            #endregion Delete arranged resources
        }
Beispiel #28
0
 public async Task <InvoicePayment> CreateAsync(InvoicePayment invoicePayment)
 {
     return(await BaseCreate(invoicePayment).ConfigureAwait(false));
 }
Beispiel #29
0
        public int Payment(CustomerInvoicePaymentModel customerInvoicePaymentModel)
        {
            int Id = 0;

            _serverContext.Database.BeginTransaction();
            var Invoice = (from a in _serverContext.LedgerMasters
                           where a.SubsidiaryLedgerAccountId == customerInvoicePaymentModel.CustomerId
                           select new { a.SubsidiaryLedgerAccountId });

            try
            {
                InvoicePayment invoice = new InvoicePayment();
                //invoice.LedgerMasterId = customerInvoicePaymentModel.LedgerMasterId;
                invoice.SubsidiaryLedgerAccountId = customerInvoicePaymentModel.CustomerId;
                invoice.InvoicePaymentAmount      = customerInvoicePaymentModel.InvoiceAmount;
                invoice.ChartOfAccountId          = customerInvoicePaymentModel.ChartOfAccountId;
                invoice.InvoicePaymentReferenceNo = customerInvoicePaymentModel.ReferenceNo;
                invoice.InvoicePaymentDate        = customerInvoicePaymentModel.PaymentDate;
                invoice.InvoicePaymentCreatedDate = DateTime.Now;
                _serverContext.InvoicePayments.Add(invoice);
                invoice.InvoicePaymentModifiedDate = DateTime.Now;
                _serverContext.SaveChanges();
                Id = invoice.Id;
                foreach (CustomerInvoicePostPaymentItemModel item in customerInvoicePaymentModel.Items)
                {
                    InvoicePaymentDetail invoicePaymentDetail = new InvoicePaymentDetail();
                    invoicePaymentDetail.InvoicePaymentId           = Id;
                    invoicePaymentDetail.LedgerMasterId             = item.Id;
                    invoicePaymentDetail.InvoicePaymentDetailAmount = item.Amount;
                    _serverContext.InvoicePaymentDetails.Add(invoicePaymentDetail);
                    _serverContext.SaveChanges();
                }

                foreach (var item in customerInvoicePaymentModel.Items)
                {
                    GeneralLedger generalLedger = new GeneralLedger
                    {
                        SubsidiaryLedgerAccountId = customerInvoicePaymentModel.CustomerId,
                        GeneralLedgerInvoiceNo    = string.Empty,
                        GeneralLedgerDate         = customerInvoicePaymentModel.PaymentDate,
                        GeneralLedgerReferenceNo  = customerInvoicePaymentModel.ReferenceNo,
                        GeneralLedgerType         = "PI",
                        LedgerMasterId            = item.Id
                    };
                    _serverContext.GeneralLedgers.Add(generalLedger);
                    _serverContext.SaveChanges();
                    GeneralLedgerDetail generalLedgerDetailDebit = new GeneralLedgerDetail();
                    generalLedgerDetailDebit.ChartOfAccountId               = customerInvoicePaymentModel.ChartOfAccountId;
                    generalLedgerDetailDebit.GeneralLedgerDetailMode        = "D";
                    generalLedgerDetailDebit.GeneralLedgerId                = generalLedger.Id;
                    generalLedgerDetailDebit.GeneralLedgerDetailAmount      = item.Amount;
                    generalLedgerDetailDebit.GeneralLedgerDetailDescription = string.Empty;
                    _serverContext.GeneralLedgerDetails.Add(generalLedgerDetailDebit);
                    _serverContext.SaveChanges();
                    GeneralLedgerDetail generalLedgerDetailCredit = new GeneralLedgerDetail();
                    generalLedgerDetailCredit.ChartOfAccountId               = ARTradeKey;
                    generalLedgerDetailCredit.GeneralLedgerDetailMode        = "C";
                    generalLedgerDetailCredit.GeneralLedgerId                = generalLedger.Id;
                    generalLedgerDetailCredit.GeneralLedgerDetailAmount      = item.Amount;
                    generalLedgerDetailCredit.GeneralLedgerDetailDescription = string.Empty;
                    _serverContext.GeneralLedgerDetails.Add(generalLedgerDetailCredit);
                    _serverContext.SaveChanges();
                }
                _serverContext.Database.CommitTransaction();
            }
            catch (Exception ex)
            {
                _serverContext.Database.RollbackTransaction();
            }
            return(Id);
        }
Beispiel #30
0
 public async Task <InvoicePayment> UpdateAsync(InvoicePayment invoicePayment)
 {
     return(await BaseUpdate(invoicePayment, invoicePayment.Number.ToString()).ConfigureAwait(false));
 }
Beispiel #31
0
        public ActionResult ChequeRealize(ChequeRealizeViewModel model)
        {
            if (ModelState.IsValid)
            {
                int           GeneralLedgerHeadId = (int)db.BankAccountLedgerHeads.Find(1).GeneralLedgerHeadId;
                GeneralLedger glObj = new GeneralLedger {
                    Amount = model.Amount, ApplicationUserId = User.Identity.GetUserId(), GeneralLedgerHeadId = GeneralLedgerHeadId, Notes = model.RealizationRemarks + " - " + model.Remarks + " - " + "Cheque Realization", PaymentMethods = PaymentMethod.Cheque, StatementTypes = TransactionType.Income, SysDateTime = DateTime.Now, GeneralLedgerType = LedgerType.Credit
                };
                db.GeneralLedgers.Add(glObj);
                db.SaveChanges();

                Agent agent = db.Agents.Find(model.Agents.Id);
                agent.Balance         = (agent.Balance - model.Amount);
                db.Entry(agent).State = EntityState.Modified;
                db.SaveChanges();

                AgentLedger alObj = new AgentLedger {
                    AgentId = model.Agents.Id, AgentLedgerHeadId = 3, Amount = model.Amount, ApplicationUserId = glObj.ApplicationUserId, Balance = agent.Balance, Remarks = glObj.Notes, SystemDate = glObj.SysDateTime
                };
                db.AgentLedgers.Add(alObj);
                db.SaveChanges();

                BankAccount baObj = db.BankAccounts.Find(model.BankAccountId);
                baObj.Balance         = (baObj.Balance + model.Amount);
                db.Entry(baObj).State = EntityState.Modified;
                db.SaveChanges();

                BankAccountLedger bclObj = new BankAccountLedger {
                    Amount = model.Amount, ApplicationUserId = glObj.ApplicationUserId, Balance = baObj.Balance, BankAccountId = model.BankAccountId, BankAccountLedgerHeadId = 1, LedgerTypes = LedgerType.Credit, Notes = glObj.Notes, PaymentMethods = PaymentMethod.Cheque, RelationId = null, SysDateTime = glObj.SysDateTime
                };
                db.BankAccountLedgers.Add(bclObj);
                db.SaveChanges();

                InvoicePayment ipObj = new InvoicePayment {
                    Amount = model.Amount, ApplicationUserId = glObj.ApplicationUserId, GeneralLedgerId = glObj.Id, InvoiceId = model.InvoiceId, PaymentMethods = PaymentMethod.Cheque, Remarks = model.RealizationRemarks + " - " + model.Remarks + " - " + "Cheque Realization", SysDateTime = glObj.SysDateTime, AgentLedgerId = alObj.Id, BankAccountLedgerId = bclObj.Id
                };
                db.InvoicePayments.Add(ipObj);
                db.SaveChanges();

                InvoiceLog ilObj = new InvoiceLog {
                    ApplicationUserId = glObj.ApplicationUserId, InvoiceId = model.InvoiceId, Remarks = "Payment Received by Cheque Transaction - Realization", SysDateTime = glObj.SysDateTime
                };
                db.InvoiceLogs.Add(ilObj);
                db.SaveChanges();

                IPChequeDetail ipchObj = db.IPChequeDetails.Find(model.IPChequeDetailId);
                ipchObj.GeneralLedgerId  = glObj.Id;
                ipchObj.InvoicePaymentId = ipObj.Id;
                ipchObj.BulkPayment      = false;
                ipchObj.Status           = ChequeStatus.Passed;
                db.Entry(ipchObj).State  = EntityState.Modified;
                db.SaveChanges();

                bclObj.RelationId       = ipchObj.Id;
                db.Entry(ipchObj).State = EntityState.Modified;
                db.SaveChanges();
                FlashMessage.Confirmation("Floating Cheque Realized");
                return(RedirectToAction("FloatingCheque", "Accounting"));
            }
            else
            {
                return(RedirectToAction("FloatingCheque", "Accounting"));
            }
        }
Beispiel #32
0
 /// <summary>
 /// Updates a invoicePayment
 /// </summary>
 /// <param name="invoicePayment">The invoicePayment to update</param>
 /// <returns>The updated invoicePayment</returns>
 public InvoicePayment Update(InvoicePayment invoicePayment)
 {
     return(UpdateAsync(invoicePayment).Result);
 }
 public async Task AddAsync(InvoicePayment entity)
 {
     await _dataContext.InvoicePayments.AddAsync(entity);
 }
        /// <summary>
        /// Applies a single payment to multiple invoices
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="invoiceIds"></param>
        /// <param name="paymentMethodId"></param>
        /// <param name="amount"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ResponseHolder ApplyPaymentToMultipleInvoices(String accountId, String[] invoiceIds, String paymentMethodId, Decimal amount, String type)
        {
            //create payment in draft
            Payment payment = new Payment();
            payment.Amount = amount;
            payment.AmountSpecified = true;
            payment.EffectiveDate = DateTime.Now;
            payment.EffectiveDateSpecified = true;
            payment.AccountId = accountId;
            payment.PaymentMethodId = paymentMethodId;
            payment.Type = type;
            payment.Status = "Draft";

            List<ResponseHolder> payCreateRes =  zs.Create(new List<zObject> { payment }, false);
            foreach (ResponseHolder rh in payCreateRes)
            {
                if (!rh.Success)
                {
                    return rh;
                }
            }
            List<zObject> ipList = new List<zObject>();
            //create invoice payment objects for the invoice amount
            foreach(String invId in invoiceIds)
            {
                ResponseHolder qRes = zs.Query("SELECT id, Amount FROM Invoice WHERE id = '" + invId + "'");
                Invoice inv = (Invoice)qRes.Objects[0];
                InvoicePayment ip = new InvoicePayment();
                ip.AmountSpecified = true;
                ip.Amount = inv.Amount;
                ip.InvoiceId = inv.Id;
                ip.PaymentId = payCreateRes[0].Id;

                ipList.Add(ip);
            }
            List<ResponseHolder> ipCreateRes = zs.Create(ipList, false);
            foreach (ResponseHolder rh in ipCreateRes)
            {
                if (!rh.Success)
                {
                    return rh;
                }
            }
            //update the original payment to be Proccessed
            Payment updatePayment = new Payment();
            updatePayment.Id = payCreateRes[0].Id;
            updatePayment.Status = "Processed";
            List<ResponseHolder> updateRes = zs.Update(new List<zObject>{ updatePayment });

            return updateRes[0];
        }