public InvoiceViewModel CreateContractInvoice(InvoiceViewModel invoice, int contractId)
        {
            var newInvoice = new Invoice
            {
                Id = invoice.Id,
                From = invoice.From,
                To = invoice.To,
                MgSubs = invoice.MgSubs,
                Cps = invoice.Cps,
                CreatedOn = DateTime.Now,
                CorrespondencePayment = invoice.CorrespondencePayment,
                AdditionalInformation = invoice.AdditionalInformation,
                FixedMonthlyFee = invoice.FixedMonthlyFee,
                Vat = invoice.Vat,
                ClientContractId = contractId,
                Comments = invoice.Comments,
                IsPaid = false,
                IsVisible = invoice.IsVisible
            };

            this.Data.Invoices.Add(newInvoice);
            this.Data.SaveChanges();

            invoice.Id = newInvoice.Id;
            return invoice;
        }
        public InvoiceViewModel DestroyClientInvoice(InvoiceViewModel invoice)
        {
            this.Data.Invoices.Delete(invoice.Id);
            this.Data.SaveChanges();

            return invoice;
        }
 public InvoiceViewModel GetSelectedInvoiceByTransaction(int InvoiceID)
 {
     Invoice Invoice = _invoiceRepository
         .GetById(InvoiceID);
     InvoiceViewModel mappedResult = new InvoiceViewModel();
     return Map(Invoice, mappedResult);
 }
        public JsonResult CreateContractInvoice([DataSourceRequest]  DataSourceRequest request, InvoiceViewModel invoice, int contractId)
        {
            if (invoice.From != null)
            {
                invoice.From = DateTime.Parse(invoice.From.ToString());
            }
            if (invoice.To != null)
            {
                invoice.To = DateTime.Parse(invoice.To.ToString());
            }
            if (invoice.CorrespondencePayment != null)
            {
                invoice.CorrespondencePayment = DateTime.Parse(invoice.CorrespondencePayment.ToString());
            }

            if (invoice == null)
            {
                return Json(new[] { invoice }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
            }

            var createdInvoice = this.invoices.CreateContractInvoice(invoice, contractId);

            var loggedUserId = this.User.Identity.GetUserId();
            Base.CreateActivity(ActivityType.Create, createdInvoice.Id.ToString(), ActivityTargetType.Invoice, loggedUserId);

            invoice.Id = createdInvoice.Id;

            return Json(new[] { invoice }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
        }
 public InvoiceViewModel GetLatestInvoiceInfo(int InvoiceID)
 {
     Invoice Invoice = _invoiceRepository
         .GetById(InvoiceID);
     InvoiceViewModel mappedResult = new InvoiceViewModel();
     return Map(Invoice, mappedResult);
 }
        public InvoiceViewModel GetInvoiceBySPKId(int spkId)
        {
            Invoice result = _invoiceRepository.GetMany(i => i.SPKId == spkId).FirstOrDefault();

            InvoiceViewModel mappedResult = new InvoiceViewModel();

            return Map(result, mappedResult);
        }
Exemplo n.º 7
0
        public InvoiceViewModel GetExistingOrder(int orderNumber)
        {
            var invoiceDt = DrSodaProxy.GetTable(string.Format(SqlQueries.GetOrder, orderNumber));

            var invoice = new InvoiceViewModel();
            if (invoiceDt != null && invoiceDt.Rows.Count > 0)
            {
                invoice.OrderNumber = (int) invoiceDt.Rows[0]["InvoiceMainID"];

                if (invoiceDt.Rows[0]["CustPONo"] != DBNull.Value)
                {
                    invoice.CustPONo = (string) invoiceDt.Rows[0]["CustPONo"];
                }
                invoice.OrderDate = (DateTime?)invoiceDt.Rows[0]["OrderDate"];

                if (invoiceDt.Rows[0]["InvoiceDate"] != DBNull.Value)
                {
                    invoice.InvoiceDate = (DateTime?) invoiceDt.Rows[0]["InvoiceDate"];
                }
                invoice.Total = (decimal)invoiceDt.Rows[0]["ArTotal"];
                invoice.Payment = (decimal)invoiceDt.Rows[0]["ARPayments"];
                invoice.OpenAmount = (decimal)invoiceDt.Rows[0]["OpenAmt"];

                invoice.Order = new OrderViewModel();
                invoice.Order.ShippingInfo = new ShippingViewModel()
                {
                    Name = invoiceDt.Rows[0]["CustomerName"].ToString(),
                    Address = invoiceDt.Rows[0]["SAddr1"].ToString(),
                    Address2 = invoiceDt.Rows[0]["SAddr2"].ToString(),
                    City = invoiceDt.Rows[0]["SCity"].ToString(),
                    State = invoiceDt.Rows[0]["SState"].ToString(),
                    Zip = invoiceDt.Rows[0]["SZip"].ToString(),
                    Phone = invoiceDt.Rows[0]["SPhoneNo"].ToString(),
                    Email = invoiceDt.Rows[0]["EmailAddressST"].ToString(),
                };

                invoice.Order.Items = new List<ProductViewModel>();

                for (int i = 0; i < invoiceDt.Rows.Count; i++)
                {
                    ProductViewModel product = new ProductViewModel();
                    product.ProductID = (int)invoiceDt.Rows[i]["ProductId"];
                    product.ProductDesc = (string)invoiceDt.Rows[i]["ProductDesc"];
                    product.Price = (decimal)invoiceDt.Rows[i]["Price"];
                    product.OrderQty = (int)invoiceDt.Rows[i]["ShipQty"];
                    product.Taxable = (int) invoiceDt.Rows[i]["Taxable"];
                    product.TaxRate = (decimal)invoiceDt.Rows[i]["Rate"];
                    product.CRVperUnit = (decimal)invoiceDt.Rows[i]["CRVperUnit"];
                    //product.Cost = (decimal)invoiceDt.Rows[i]["Cost"];
                    product.CustTaxable = (int) invoiceDt.Rows[i]["CustomerTaxable"];
                    product.ExtAmt = (decimal)invoiceDt.Rows[i]["ExtAmt"];
                    invoice.Order.Items.Add(product);
                }
            }

            return invoice;
        }
        public JsonResult DestroyClientInvoice([DataSourceRequest] DataSourceRequest request, InvoiceViewModel invoice)
        {
            var deletedInvoice = this.invoices.DestroyClientInvoice(invoice);

            var loggedUserId = this.User.Identity.GetUserId();
            Base.CreateActivity(ActivityType.Delete, deletedInvoice.Id.ToString(), ActivityTargetType.Invoice, loggedUserId);

            invoice.Id = deletedInvoice.Id;

            return Json(new[] { invoice }, JsonRequestBehavior.AllowGet);
        }
 public async Task <IActionResult> Put([FromBody] InvoiceViewModel invoice)
 {
     return(await Post(invoice));
 }
Exemplo n.º 10
0
 public ActionResult New(InvoiceViewModel model)
 {
     SetTempData(model.Type);
     Manager.Insert(model.ToInvoice());
     return(RedirectToAction("Details", new { @id = model.Id }));
 }
        public async Task <IActionResult> Filter(DateTime?date, int clientid, int projectid)
        {
            FilterViewModel viewModel = new FilterViewModel();

            if (date == DateTime.MinValue)
            {
                date = null;
                viewModel.DateTime = null;
            }
            else
            {
                viewModel.DateTime = date;
            }

            var client = await _context.Clients.FindAsync(clientid);

            if (client != null)
            {
                viewModel.ClientName = client.Name;
            }
            var project = await _context.Projects.FindAsync(projectid);

            if (project != null)
            {
                viewModel.ProjectName = project.Name;
            }


            var invoice = await _context.Invoices.Where(c => (viewModel.ClientName != null && viewModel.ProjectName == null && viewModel.DateTime == null)?(c.Client.Name == viewModel.ClientName) : true &&
                                                        (viewModel.ClientName == null && viewModel.ProjectName != null && viewModel.DateTime == null)?(c.Project.Name == viewModel.ProjectName) : true &&
                                                        (viewModel.DateTime != null && viewModel.ClientName == null && viewModel.ProjectName == null)?(c.DateTime == date) : true &&
                                                        (viewModel.ClientName != null && viewModel.ProjectName != null && viewModel.DateTime == null)?(c.Client.Name == viewModel.ClientName && c.Project.Name == viewModel.ProjectName) : true &&
                                                        (viewModel.ClientName != null && viewModel.ProjectName == null && viewModel.DateTime != null)?(c.Client.Name == viewModel.ClientName && c.DateTime == date) : true &&
                                                        (viewModel.ClientName == null && viewModel.ProjectName != null && viewModel.DateTime != null)?(c.Project.Name == viewModel.ProjectName && c.DateTime == date) : true &&
                                                        (viewModel.ClientName != null && viewModel.ProjectName != null && viewModel.DateTime != null)?(c.Client.Name == viewModel.ClientName && c.Project.Name == viewModel.ProjectName && c.DateTime == date) : true

                                                        ).ToListAsync();


            List <InvoiceViewModel> vm = new List <InvoiceViewModel>();

            foreach (var item in invoice)
            {
                InvoiceViewModel vm2 = new InvoiceViewModel();
                var invoiceProject   = _context.Projects.Find(item.ProjectId);

                var invoiceClient = _context.Clients.Find(item.ClientId);

                vm2.Id          = item.Id;
                vm2.TaxAmount   = item.TaxAmount;
                vm2.Note        = item.Note;
                vm2.NetAmount   = item.NetAmount;
                vm2.ProjectId   = item.ProjectId;
                vm2.TotalAmount = item.TotalAmount;
                vm2.DateTime    = item.DateTime;
                vm2.Status      = item.Status;
                vm2.ClientId    = item.ClientId;
                vm2.Project     = await _context.Projects.FindAsync(item.ProjectId);

                vm2.Client = await _context.Clients.FindAsync(item.ClientId);

                vm.Add(vm2);
            }

            if (invoice != null)
            {
                return(Json(new
                {
                    status = 200,
                    data = vm
                }));
            }

            return(Json(new
            {
                status = 400
            }));
        }
Exemplo n.º 12
0
 public void Delete(InvoiceViewModel invoice)
 {
     invoice.Deleted = true;
     _invoiceLogic.Update(invoice);
 }
Exemplo n.º 13
0
 public InvoiceView(InvoiceViewModel view_model)
 {
     InitializeComponent();
     DataContext = view_model;
 }
Exemplo n.º 14
0
        public IHttpActionResult Get()
        {
            var invoice = new InvoiceViewModel {
                Master = new Master {
                    Id            = 12345,
                    Created       = DateTime.Now,
                    DueDate       = DateTime.Now,
                    Amount        = "1000.00",
                    PaymentMethod = "Wire Transfer",
                    Company       = new Company
                    {
                        Address = "Av Evergreen 123456",
                        Name    = "My Nice Company",
                        State   = "Carabobo"
                    },
                    Client = new Client
                    {
                        CompanyName = "Rakatakataka LLC",
                        Email       = "*****@*****.**",
                        Name        = "John Doe"
                    }
                },

                Details = new List <Detail> {
                    new Detail {
                        Item = "Web Page", Amount = 500
                    },
                    new Detail {
                        Item = "Domain", Amount = 250
                    },
                    new Detail {
                        Item = "Support Contract", Amount = 250
                    }
                },

                Total = 1000
            };

            string template = System.Text.Encoding.UTF8.GetString(File.ReadAllBytes(AppContext.BaseDirectory + @"Templates\Invoice.cshtml"));

            string html = Engine.Razor.RunCompile(template, "report", typeof(InvoiceViewModel), invoice);

            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize   = PaperKind.A4,
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        PagesCount     = true,
                        HtmlContent    = html,
                        WebSettings    = { DefaultEncoding = "utf-8"                   },
                        FooterSettings ={ FontSize                             =9, Right = "Page [page] of [toPage]" }
                    }
                }
            };

            byte[] pdf = converter.Convert(doc);

            MemoryStream stream = new MemoryStream(pdf);

            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream)
            };

            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "report-employee.pdf"
            };

            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

            ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);

            return(responseMessageResult);
        }
Exemplo n.º 15
0
 public InvoicePage()
 {
     InitializeComponent();
     BindingContext = new InvoiceViewModel();
 }
Exemplo n.º 16
0
        public IActionResult Create()
        {
            InvoiceViewModel model = new InvoiceViewModel();

            return(View(model));
        }
 public int Save([FromBody] InvoiceViewModel invoice)
 {
     return(_service.SaveInvoice(invoice));
 }
        private SqliteCommand AddCreateParameters(SqliteCommand insertCommand, InvoiceViewModel Invoice)
        {
            insertCommand.Parameters.AddWithValue("@ServerId", Invoice.Id);
            insertCommand.Parameters.AddWithValue("@Identifier", Invoice.Identifier);
            insertCommand.Parameters.AddWithValue("@Code", ((object)Invoice.Code) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@InvoiceNumber", ((object)Invoice.InvoiceNumber) ?? DBNull.Value);

            insertCommand.Parameters.AddWithValue("@BuyerId", ((object)Invoice.Buyer?.Id) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@BuyerIdentifier", ((object)Invoice.Buyer?.Identifier) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@BuyerCode", ((object)Invoice.Buyer?.Code) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@BuyerName", ((object)Invoice.Buyer?.Name) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@BuyerInternalCode", ((object)Invoice.Buyer?.InternalCode) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@BuyerNameGer", ((object)Invoice.Buyer?.NameGer) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@EnteredBuyerName", ((object)Invoice.BuyerName) ?? DBNull.Value);

            insertCommand.Parameters.AddWithValue("@Address", ((object)Invoice.Address) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@InvoiceDate", ((object)Invoice.InvoiceDate) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@DueDate", ((object)Invoice.DueDate) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@DateOfPayment", ((object)Invoice.DateOfPayment) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@Status", ((object)Invoice.Status) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@StatusDate", ((object)Invoice.StatusDate) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@Description", ((object)Invoice.Description) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@CurrencyCode", ((object)Invoice.CurrencyCode) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@CurrencyExchangeRate", ((object)Invoice.CurrencyExchangeRate) ?? DBNull.Value);

            insertCommand.Parameters.AddWithValue("@CityId", ((object)Invoice.City?.Id) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@CityIdentifier", ((object)Invoice.City?.Identifier) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@CityCode", ((object)Invoice.City?.ZipCode) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@CityName", ((object)Invoice.City?.Name) ?? DBNull.Value);

            insertCommand.Parameters.AddWithValue("@MunicipalityId", ((object)Invoice.Municipality?.Id) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@MunicipalityIdentifier", ((object)Invoice.Municipality?.Identifier) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@MunicipalityCode", ((object)Invoice.Municipality?.Code) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@MunicipalityName", ((object)Invoice.Municipality?.Name) ?? DBNull.Value);

            insertCommand.Parameters.AddWithValue("@DiscountId", ((object)Invoice.Discount?.Id) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@DiscountIdentifier", ((object)Invoice.Discount?.Identifier) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@DiscountCode", ((object)Invoice.Discount?.Code) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@DiscountName", ((object)Invoice.Discount?.Name) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@DiscountAmount", ((object)Invoice.Discount?.Amount) ?? DBNull.Value);

            insertCommand.Parameters.AddWithValue("@VatId", ((object)Invoice.Vat?.Id) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@VatIdentifier", ((object)Invoice.Vat?.Identifier) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@VatCode", ((object)Invoice.Vat?.Code) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@VatDescription", ((object)Invoice.Vat?.Description) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@VatAmount", ((object)Invoice.Vat?.Amount) ?? DBNull.Value);

            insertCommand.Parameters.AddWithValue("@PdvType", ((object)Invoice.PdvType) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@TotalPrice", ((object)Invoice.TotalPrice) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@TotalPDV", ((object)Invoice.TotalPDV) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@TotalRebate", ((object)Invoice.TotalRebate) ?? DBNull.Value);

            insertCommand.Parameters.AddWithValue("@IsSynced", Invoice.IsSynced);
            insertCommand.Parameters.AddWithValue("@UpdatedAt", ((object)Invoice.UpdatedAt) ?? DBNull.Value);
            insertCommand.Parameters.AddWithValue("@CreatedById", MainWindow.CurrentUser.Id);
            insertCommand.Parameters.AddWithValue("@CreatedByName", MainWindow.CurrentUser.FirstName + " " + MainWindow.CurrentUser.LastName);
            insertCommand.Parameters.AddWithValue("@CompanyId", MainWindow.CurrentCompany.Id);
            insertCommand.Parameters.AddWithValue("@CompanyName", MainWindow.CurrentCompany.CompanyName);

            return(insertCommand);
        }
        public InvoiceListResponse GetInvoicesByPage(int companyId, InvoiceViewModel InvoiceSearchObject, int currentPage = 1, int itemsPerPage = 50)
        {
            InvoiceListResponse     response = new InvoiceListResponse();
            List <InvoiceViewModel> Invoices = new List <InvoiceViewModel>();

            using (SqliteConnection db = new SqliteConnection("Filename=SirmiumERPGFC.db"))
            {
                db.Open();
                try
                {
                    SqliteCommand selectCommand = new SqliteCommand(
                        SqlCommandSelectPart +
                        "FROM Invoices " +
                        "WHERE (@BuyerName IS NULL OR @BuyerName = '' OR BuyerName LIKE @BuyerName) " +
                        "AND (@InvoiceNumber IS NULL OR @InvoiceNumber = '' OR InvoiceNumber LIKE @InvoiceNumber) " +
                        "AND (@DateTo IS NULL OR @DateTo = '' OR DATE(InvoiceDate) <= DATE(@DateTo)) " +
                        "AND (@DateFrom IS NULL OR @DateFrom = '' OR DATE(InvoiceDate) >= DATE(@DateFrom)) " +
                        "AND (@DateOfPaymentTo IS NULL OR @DateOfPaymentTo = '' OR DATE(DateOfPayment) <=  DATE(@DateOfPaymentTo)) " +
                        "AND (@DateOfPaymentFrom IS NULL OR @DateOfPaymentFrom = '' OR DATE(DateOfPayment) >= DATE(@DateOfPaymentFrom)) " +
                        "AND CompanyId = @CompanyId " +
                        "ORDER BY IsSynced, Id DESC " +
                        "LIMIT @ItemsPerPage OFFSET @Offset;", db);

                    selectCommand.Parameters.AddWithValue("@BuyerName", ((object)InvoiceSearchObject.SearchBy_BusinessPartner) != null ? "%" + InvoiceSearchObject.SearchBy_BusinessPartner + "%" : "");
                    selectCommand.Parameters.AddWithValue("@InvoiceNumber", ((object)InvoiceSearchObject.SearchBy_InvoiceNumber) != null ? "%" + InvoiceSearchObject.SearchBy_InvoiceNumber + "%" : "");
                    selectCommand.Parameters.AddWithValue("@DateFrom", ((object)InvoiceSearchObject.SearchBy_InvoiceDateFrom) ?? DBNull.Value);
                    selectCommand.Parameters.AddWithValue("@DateTo", ((object)InvoiceSearchObject.SearchBy_InvoiceDateTo) ?? DBNull.Value);
                    selectCommand.Parameters.AddWithValue("@DateOfPaymentFrom", ((object)InvoiceSearchObject.SearchBy_DateOfPaymentFrom) ?? DBNull.Value);
                    selectCommand.Parameters.AddWithValue("@DateOfPaymentTo", ((object)InvoiceSearchObject.SearchBy_DateOfPaymentTo) ?? DBNull.Value);
                    selectCommand.Parameters.AddWithValue("@CompanyId", companyId);
                    selectCommand.Parameters.AddWithValue("@ItemsPerPage", itemsPerPage);
                    selectCommand.Parameters.AddWithValue("@Offset", (currentPage - 1) * itemsPerPage);

                    SqliteDataReader query = selectCommand.ExecuteReader();

                    while (query.Read())
                    {
                        InvoiceViewModel dbEntry = Read(query);
                        Invoices.Add(dbEntry);
                    }


                    selectCommand = new SqliteCommand(
                        "SELECT Count(*) " +
                        "FROM Invoices " +
                        "WHERE(@BuyerName IS NULL OR @BuyerName = '' OR BuyerName LIKE @BuyerName) " +
                        "AND (@InvoiceNumber IS NULL OR @InvoiceNumber = '' OR InvoiceNumber LIKE @InvoiceNumber) " +
                        "AND (@InvoiceNumber IS NULL OR @InvoiceNumber = '' OR InvoiceNumber LIKE @InvoiceNumber) " +
                        "AND (@DateTo IS NULL OR @DateTo = '' OR DATE(InvoiceDate) <= DATE(@DateTo)) " +
                        "AND (@DateFrom IS NULL OR @DateFrom = '' OR DATE(InvoiceDate) >= DATE(@DateFrom)) " +
                        "AND (@DateOfPaymentTo IS NULL OR @DateOfPaymentTo = '' OR DATE(DateOfPayment) <=  DATE(@DateOfPaymentTo)) " +
                        "AND (@DateOfPaymentFrom IS NULL OR @DateOfPaymentFrom = '' OR DATE(DateOfPayment) >= DATE(@DateOfPaymentFrom)) " +
                        "AND CompanyId = @CompanyId;", db);

                    selectCommand.Parameters.AddWithValue("@BuyerName", ((object)InvoiceSearchObject.SearchBy_BusinessPartner) != null ? "%" + InvoiceSearchObject.SearchBy_BusinessPartner + "%" : "");
                    selectCommand.Parameters.AddWithValue("@InvoiceNumber", ((object)InvoiceSearchObject.SearchBy_InvoiceNumber) != null ? "%" + InvoiceSearchObject.SearchBy_InvoiceNumber + "%" : "");
                    selectCommand.Parameters.AddWithValue("@DateFrom", ((object)InvoiceSearchObject.SearchBy_InvoiceDateFrom) ?? "");
                    selectCommand.Parameters.AddWithValue("@DateTo", ((object)InvoiceSearchObject.SearchBy_InvoiceDateTo) ?? "");
                    selectCommand.Parameters.AddWithValue("@DateOfPaymentFrom", ((object)InvoiceSearchObject.SearchBy_DateOfPaymentFrom) ?? "");
                    selectCommand.Parameters.AddWithValue("@DateOfPaymentTo", ((object)InvoiceSearchObject.SearchBy_DateOfPaymentTo) ?? "");
                    selectCommand.Parameters.AddWithValue("@CompanyId", companyId);

                    query = selectCommand.ExecuteReader();

                    if (query.Read())
                    {
                        response.TotalItems = query.GetInt32(0);
                    }
                }
                catch (SqliteException error)
                {
                    MainWindow.ErrorMessage = error.Message;
                    response.Success        = false;
                    response.Message        = error.Message;
                    response.Invoices       = new List <InvoiceViewModel>();
                    return(response);
                }
                db.Close();
            }
            response.Success  = true;
            response.Invoices = Invoices;
            return(response);
        }
Exemplo n.º 20
0
 public Invoice MapDTO(InvoiceViewModel invoiceView)
 {
     return(mapper.Map <Invoice>(invoiceView));
 }
Exemplo n.º 21
0
        public async Task <IActionResult> Create([FromBody] InvoiceViewModel model)
        {
            if (model == null)
            {
                return(StatusCode(400, "Invalid parameter(s)."));
            }

            Invoice invoice = new Invoice
            {
                InvoiceNumber = model.InvoiceNumber,
                CreatedOn     = model.CreatedOn,
                ExpiredOn     = model.ExpiredOn,
                Total         = model.Total,
                Discount      = model.Discount,
                Comment       = model.Comment,
                CustomerId    = model.CustomerId,
                IsPaid        = model.IsPaid,
                Concept       = model.Concept,
                Debtor        = new Debtor
                {
                    Id          = model.Debtor.Id,
                    FirstName   = model.Debtor.FirstName,
                    LastName    = model.Debtor.LastName,
                    Email       = model.Debtor.Email,
                    BankAccount = model.Debtor.BankAccount,
                    Phone       = model.Debtor.Phone,
                    CompanyName = model.Debtor.CompanyName
                }
            };

            //Set invoice number
            if (invoice.InvoiceNumber == "-1")
            {
                var today  = DateTime.Now;
                var prefix = String.IsNullOrEmpty(_settings.InvoicePrefix) ? _settings.InvoicePrefix : "";

                var invoiceCount = await this._repo.GetCount();

                var leadingZeros = "";
                switch (today.Month.ToString().Length)
                {
                case 1:
                    leadingZeros = "000";
                    break;

                case 2:
                    leadingZeros = "00";
                    break;

                case 3:
                    leadingZeros = "0";
                    break;

                case 4:
                    leadingZeros = "";
                    break;
                }

                invoice.InvoiceNumber = prefix + today.Year + '-' + (leadingZeros + invoiceCount);
            }

            //Swap comma with dots
            var totalString = invoice.Total.ToString().Replace(".", ",");

            invoice.Total = Convert.ToDecimal(totalString);

            //Insert invoice
            var data = await _repo.Insert(invoice);

            if (data == null)
            {
                return(StatusCode(500, "A problem occured while saving the record. Please try again!"));
            }

            //Send email
            if (invoice.Concept == false)
            {
                await _email.SendNotification(new Debtor
                {
                    Id          = model.Debtor.Id,
                    FirstName   = model.Debtor.FirstName,
                    LastName    = model.Debtor.LastName,
                    Email       = model.Debtor.Email,
                    BankAccount = model.Debtor.BankAccount,
                    Phone       = model.Debtor.Phone,
                    CompanyName = model.Debtor.CompanyName
                });
            }

            var result = new InvoiceViewModel();

            result.SetProperties(data);

            return(Ok(result));
        }
Exemplo n.º 22
0
        public async Task <IActionResult> Create(InvoiceViewModel model, InvoiceItemsGridViewModel[] items)
        {
            if (model.Id == null && model.AppointmentId != null && model.PatientId != null)
            {
                throw new AwroNoreException("Can not create invoice for appointment & patient");
            }

            if (items == null || !items.Any())
            {
                throw new AwroNoreException("Please enter at least one item");
            }

            if (items.Any(x => (x.ShiftCenterServiceId == null || x.ShiftCenterServiceId <= 0) && string.IsNullOrEmpty(x.CustomServiceName)))
            {
                throw new AwroNoreException("Please select service for all items");
            }

            bool success  = false;
            var  strategy = _dbContext.Database.CreateExecutionStrategy();
            await strategy.ExecuteAsync(async() =>
            {
                using (var transaction = _dbContext.Database.BeginTransaction())
                {
                    try
                    {
                        if (model.Id != null)
                        {
                            var invoice = await _dbContext.Invoices.FindAsync(model.Id);

                            if (invoice == null || invoice.Patient.ServiceSupply.ShiftCenterId != CurrentBeautyCenter.Id)
                            {
                                throw new AwroNoreException("Invoice Not Found");
                            }

                            var invoiceItems = await _dbContext.InvoiceItems.Where(x => x.InvoiceId == invoice.Id).ToListAsync();

                            if (invoiceItems.Any())
                            {
                                _dbContext.InvoiceItems.RemoveRange(invoiceItems);

                                await _dbContext.SaveChangesAsync();
                            }

                            if (items != null && items.Any())
                            {
                                var treats = items.Where(x => !x.IsDeleted && (x.ShiftCenterServiceId != null && x.ShiftCenterServiceId > 0) || !string.IsNullOrEmpty(x.CustomServiceName)).Select(x => new InvoiceItem
                                {
                                    InvoiceId            = invoice.Id,
                                    ShiftCenterCerviceId = x.ShiftCenterServiceId,
                                    CustomServiceName    = x.CustomServiceName,
                                    Price     = x.Price,
                                    Note      = x.Note,
                                    CreatedAt = DateTime.Now,
                                }).ToList();

                                _dbContext.InvoiceItems.AddRange(treats);

                                await _dbContext.SaveChangesAsync();
                            }

                            invoice.VisitDate   = DateTime.Parse(model.VisitDate);
                            invoice.Description = model.Description ?? "";

                            _dbContext.Invoices.Attach(invoice);

                            _dbContext.Entry(invoice).State = EntityState.Modified;

                            await _dbContext.SaveChangesAsync();
                        }
                        else
                        {
                            Appointment appointment = null;
                            Patient patient         = null;
                            if (model.AppointmentId != null)
                            {
                                appointment = await _dbContext.Appointments.FindAsync(model.AppointmentId);

                                if (appointment == null)
                                {
                                    throw new AwroNoreException("Appointment Not Found");
                                }

                                patient = await _dbContext.Patients.FirstOrDefaultAsync(x => x.ServiceSupplyId == appointment.ServiceSupplyId && x.PersonId == appointment.PersonId);

                                if (patient == null)
                                {
                                    patient = new Patient
                                    {
                                        ServiceSupplyId = appointment.ServiceSupplyId,
                                        PersonId        = appointment.PersonId,
                                        CreatedAt       = DateTime.Now
                                    };

                                    await _dbContext.Patients.AddAsync(patient);

                                    await _dbContext.SaveChangesAsync();
                                }
                            }
                            else if (model.PatientId != null)
                            {
                                patient = await _dbContext.Patients.FindAsync(model.PatientId.Value) ?? throw new AwroNoreException("Patient Not Found");
                            }

                            var invoice = new Invoice
                            {
                                PatientId     = patient.Id,
                                AppointmentId = model.AppointmentId,
                                CreatedAt     = DateTime.Now,
                                Description   = model.Description ?? "",
                                VisitDate     = DateTime.Parse(model.VisitDate)
                            };

                            _dbContext.Invoices.Add(invoice);

                            await _dbContext.SaveChangesAsync();

                            if (items != null && items.Any())
                            {
                                var treats = items.Where(x => !x.IsDeleted && (x.ShiftCenterServiceId != null && x.ShiftCenterServiceId > 0) || !string.IsNullOrEmpty(x.CustomServiceName)).Select(x => new InvoiceItem
                                {
                                    InvoiceId            = invoice.Id,
                                    ShiftCenterCerviceId = x.ShiftCenterServiceId,
                                    CustomServiceName    = x.CustomServiceName,
                                    Price     = x.Price,
                                    Note      = x.Note,
                                    CreatedAt = DateTime.Now,
                                }).ToList();

                                var oldItems = await _dbContext.InvoiceItems.Where(x => x.InvoiceId == invoice.Id).ToListAsync();

                                if (oldItems.Any())
                                {
                                    _dbContext.InvoiceItems.RemoveRange(oldItems);
                                }

                                _dbContext.InvoiceItems.AddRange(treats);

                                await _dbContext.SaveChangesAsync();
                            }

                            if (appointment != null)
                            {
                                _dbContext.Entry(appointment).State = EntityState.Modified;
                                appointment.Status = AppointmentStatus.Done;
                                await _dbContext.SaveChangesAsync();
                                await SendDoneAppointmentNotificationAsync(appointment, patient);
                            }
                        }

                        transaction.Commit();

                        success = true;
                    }
                    catch
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            });

            return(Json(new { success, message = success ? Core.Resources.EntitiesResources.Messages.ActionDoneSuccesfully : Core.Resources.EntitiesResources.Messages.ErrorOccuredWhileDoneAction }));
        }
Exemplo n.º 23
0
        public async Task <Tuple <bool, int> > AddInvoice(InvoiceViewModel invoice,
                                                          List <ProductBuyingDetailsViewModel> productDetails)
        {
            try
            {
                //check if product details is valid
                foreach (var details in productDetails)
                {
                    var product = await _context.HangHoa.Where(p => p.Id == details.ProductId).FirstOrDefaultAsync();

                    if (product == null || (details.Count > product.TonKho))
                    {
                        return(new Tuple <bool, int>(false, -1));
                    }
                }

                //add invoice
                var userId = (from user in _context.Staff
                              where user.UserName == invoice.Staff
                              select user).First().Id;

                //hard code id, edit later
                int statusId = 0;

                if (invoice.CustomerPaid >= invoice.TotalValue)
                {
                    statusId = await GetCustomerTransactionStatus("Paid", "KhachHang");
                }
                else if (invoice.CustomerPaid <= 0)
                {
                    statusId = await GetCustomerTransactionStatus("Not-Paid", "KhachHang");
                }
                else
                {
                    statusId = await GetCustomerTransactionStatus("Semi-Paid", "KhachHang");
                }

                var invoice_ = new DonHang
                {
                    KhachHangId = invoice.CustomerId,
                    NhanVienId  = userId,
                    NgayLap     = DateTime.Now,
                    TongTien    = invoice.TotalValue,
                    TrangThaiId = statusId,
                    ChietKhau   = invoice.Discount.GetValueOrDefault()
                };

                await _context.DonHang.AddAsync(invoice_);

                //add related product
                foreach (var product in productDetails)
                {
                    var detail = new ChiTietDonHang
                    {
                        //DonHangId = invoice_.Id,
                        HangHoaId = product.ProductId,
                        SoLuong   = product.Count,
                        GiaBan    = product.Price
                    };

                    invoice_.ChiTietDonHang.Add(detail);

                    //also update product count
                    var boughtProduct = await(from bought in _context.HangHoa
                                              where bought.Id == product.ProductId
                                              select bought).FirstAsync();

                    boughtProduct.TonKho -= product.Count;

                    //update number of products sold
                    boughtProduct.DaBan += product.Count;
                }

                //finally, add receipt voucher
                if (invoice.CustomerPaid > 0)
                {
                    var receiptVoucher = new PhieuThu
                    {
                        NgayLap    = DateTime.Now,
                        NhanVienId = invoice_.NhanVienId,
                        TongTien   = invoice.CustomerPaid >= invoice.TotalValue ?
                                     invoice.TotalValue : invoice.CustomerPaid,
                        LoaiPhieuId = 2, //hard code for tesing, edit later
                        KhachHangId = invoice.CustomerId
                    };
                    invoice_.PhieuThu.Add(receiptVoucher);
                }
                //commit transaction
                _context.SaveChanges();

                return(new Tuple <bool, int>(true, invoice_.Id));
            }
            catch (Exception e)
            {
                var error = e;
                return(new Tuple <bool, int>(false, -1));;
            }
        }
Exemplo n.º 24
0
        public InvoiceViewModel GetInvoiceDetailMain(int masterPNRId)
        {
            var masterPnrDetails = _ent.TBO_MasterPNRs.Where(x => x.MPNRId == masterPNRId).FirstOrDefault();
            var OldPnrDetails    = _ent.PNRs.Where(x => x.PNRId == masterPNRId).FirstOrDefault();

            if (masterPnrDetails == null)
            {
                GetPNRDetail(OldPnrDetails.AgentId, masterPNRId);
            }
            else
            {
                GetMasterPNRDetail(masterPnrDetails.AgentId, masterPNRId);
            }

            var pnrDetails = _ent.TBO_PNRs.Where(x => x.MPNRId == masterPNRId).Select(x => x.PNRId).ToList();

            if (pnrDetails.Count == 0)
            {
                var pnrsDetail             = _ent.PNRs.Where(x => x.PNRId == masterPNRId).Select(x => x.PNRId).ToList();
                InvoiceViewModel viewModel = new InvoiceViewModel();

                viewModel.ServiceProviderId = OldPnrDetails.ServiceProviderId;

                int pnrcount = pnrsDetail.Count;

                foreach (var pnr in pnrsDetail)
                {
                    InvoicePNRDetailModel model = new InvoicePNRDetailModel();

                    var agentdetail = GetBranchDetail(OldPnrDetails.AgentId);

                    var pnrDetail        = GetOldPNRDetailById((int)pnr);
                    var paxDetailByPNRId = GetOldPassengerDetails((int)pnrDetail.PNRId);

                    model.AgencyDetail        = agentdetail;
                    model.BilledBy            = "Travel Planner Pvt.Ltd";
                    model.TicketedToAgent     = agentdetail.AgencyName;
                    model.BilledByAgent       = agentdetail.AgencyName;
                    model.TicketedToPassenger = paxDetailByPNRId.FirstOrDefault().FirstName + paxDetailByPNRId.FirstOrDefault().LastName;
                    model.PNRId        = (int)pnrDetail.PNRId;
                    model.PNR          = pnrDetail.GDSRefrenceNumber;
                    model.InvoiceDate  = createdDate;
                    model.VendorDetail = GetVendorDetail();
                    model.InvoiceNo    = GetVoucherByTransactionRef(masterPNRId).ToString().PadLeft(4, '0');

                    InvoiceItineraryDetailModel itinerary = new InvoiceItineraryDetailModel();

                    var sectorDetail = GetOldPNRSectorDetail((int)pnrDetail.PNRId);
                    model.TravelDate = sectorDetail.DepartDate;
                    List <int> segDepCityIdList = new List <int>();
                    var        segmentdetail    = GetOldSegmentDetail((int)pnrDetail.PNRId);
                    int        departcityid     = 0;
                    int        arrivecityid     = 1;

                    foreach (PNRSegments segment in segmentdetail)
                    {
                        departcityid = segmentdetail[0].DepartCityId;
                        arrivecityid = segment.ArriveCityId;

                        segDepCityIdList.Add(segment.DepartCityId);

                        InvoiceItinerarySegment invoiceSegment = new InvoiceItinerarySegment();
                        var airlineDetail = GetAirlineDetailById(segment.AirlineId);
                        invoiceSegment.Airline       = airlineDetail.AirlineName;
                        invoiceSegment.AirlineCode   = airlineDetail.AirlineCode;
                        invoiceSegment.FlightNo      = segment.FlightNumber;
                        invoiceSegment.Class         = segment.BIC;
                        invoiceSegment.DepartureDate = segment.DepartDate.ToString();
                        itinerary.Segments.Add(invoiceSegment);
                    }

                    if (departcityid != arrivecityid)
                    {
                        model.Journey = "OneWay";
                    }
                    else
                    {
                        model.Journey = "RoundTrip";
                    }
                    string sector = string.Empty;
                    foreach (var cityId in segDepCityIdList)
                    {
                        sector += GetCityDetailsByCityId(cityId).CityCode + " - ";
                    }
                    if (model.Journey == "OneWay")
                    {
                        sector += GetCityDetailsByCityId(sectorDetail.DestinationCityId).CityCode;
                    }

                    if (model.Journey == "RoundTrip")
                    {
                        sector += GetCityDetailsByCityId(sectorDetail.DepartCityId).CityCode;
                    }
                    itinerary.Sector = sector;

                    double grossAmt    = 0;
                    double discountAmt = 0;
                    double serviceTax  = 0;
                    double transFee    = 0;
                    var    paxDetail   = GetOldPassengerDetails((int)pnr);
                    int    paxcounter  = paxDetail.Count;
                    foreach (Passengers pax in paxDetail)
                    {
                        InvoicePassenger invPax = new InvoicePassenger();
                        invPax.PassengerName = pax.FirstName + " " + pax.MiddleName + " " + pax.LastName;
                        invPax.PassengerType = GetPassengerTypeById(pax.PassengerTypeId).PassengerTypeName;
                        var pnrtickets = GetOldPNRTickets((int)pax.PassengerId);
                        if (pnrtickets != null)
                        {
                            model.Currency = pnrtickets.Currency;
                            invPax.FxRate  = pnrtickets.LCY_FX_Rate;
                            if (invPax.FxRate == 0)
                            {
                                invPax.FxRate = 1;
                            }
                            if (model.Currency != "USD")
                            {
                                invPax.Fare              = (pnrtickets.Fare + pnrtickets.MarkupAmount) * invPax.FxRate;
                                invPax.OtherCharge       = pnrtickets.FSC * invPax.FxRate;
                                invPax.FuelSurcharge     = pnrtickets.FSC * invPax.FxRate;
                                invPax.ServiceCharge     = pnrtickets.ServiceCharge * invPax.FxRate;
                                invPax.Tax               = (pnrtickets.TaxAmount + pnrtickets.ServiceCharge + pnrtickets.FSC) * invPax.FxRate; //+ pnrtickets.MarkupAmount;
                                grossAmt                += invPax.Fare + invPax.OtherCharge + invPax.Tax + invPax.FuelSurcharge;               // + invPax.ServiceCharge
                                invPax.MarkupAmount      = pnrtickets.MarkupAmount * invPax.FxRate;
                                model.AgentAirlineMarkUp = pnrtickets.MarkupAmount * invPax.FxRate;
                                discountAmt             += pnrtickets.DiscountAmount * invPax.FxRate;
                            }
                            else
                            {
                                invPax.Fare              = pnrtickets.Fare + pnrtickets.MarkupAmount;
                                invPax.OtherCharge       = pnrtickets.FSC;
                                invPax.FuelSurcharge     = pnrtickets.FSC;
                                invPax.ServiceCharge     = pnrtickets.ServiceCharge;
                                invPax.Tax               = pnrtickets.TaxAmount + pnrtickets.ServiceCharge + pnrtickets.FSC;     //+ pnrtickets.MarkupAmount;
                                grossAmt                += invPax.Fare + invPax.OtherCharge + invPax.Tax + invPax.FuelSurcharge; // + invPax.ServiceCharge
                                invPax.MarkupAmount      = pnrtickets.MarkupAmount;
                                model.AgentAirlineMarkUp = pnrtickets.MarkupAmount;
                                discountAmt             += pnrtickets.DiscountAmount;
                            }

                            itinerary.TicketNo = pnrtickets.TicketNumber;
                            invPax.TicketNo    = pnrtickets.TicketNumber;

                            serviceTax += 0;
                            transFee   += 0;

                            model.TicketStatusId = pnrtickets.TicketStatusId;
                        }
                        itinerary.PassengerDetail.Add(invPax);
                    }
                    model.ItineraryDetails.Add(itinerary);
                    model.GrossAmount = grossAmt;
                    string aaa = discountAmt.ToString();
                    if (!aaa.Contains("-"))
                    {
                        model.CommissionEarned = discountAmt;
                    }
                    if (aaa.Contains("-"))
                    {
                        string bbb = aaa.TrimStart('-');
                        model.TransactionFee = Convert.ToDouble(bbb) + transFee;
                    }
                    else
                    {
                        model.TransactionFee = transFee;
                    }
                    model.ServiceTax           = serviceTax;
                    model.TaxDeductionAtSource = Math.Ceiling(discountAmt * 0.1);
                    model.NetAmount            = model.GrossAmount - model.CommissionEarned + model.ServiceTax + model.TransactionFee;
                    model.NetReceivable        = model.NetAmount;
                    viewModel.PNRDetails.Add(model);
                }
                return(viewModel);
            }
            else
            {
                InvoiceViewModel viewModel = new InvoiceViewModel();

                viewModel.ServiceProviderId = masterPnrDetails.ServiceProviderId;

                int pnrcount = pnrDetails.Count;

                foreach (var pnr in pnrDetails)
                {
                    InvoicePNRDetailModel model = new InvoicePNRDetailModel();

                    var agentdetail = GetBranchDetail(masterPnrDetails.AgentId);

                    var pnrDetail        = GetPNRDetailById((int)pnr);
                    var paxDetailByPNRId = GetPassengerDetails((int)pnrDetail.PNRId);

                    model.AgencyDetail        = agentdetail;
                    model.BilledBy            = "Travel Planner Pvt.Ltd";
                    model.TicketedToAgent     = agentdetail.AgencyName;
                    model.BilledByAgent       = agentdetail.AgencyName;
                    model.TicketedToPassenger = paxDetailByPNRId.FirstOrDefault().FirstName + paxDetailByPNRId.FirstOrDefault().LastName;
                    model.PNRId        = (int)pnrDetail.PNRId;
                    model.PNR          = pnrDetail.RecLoc;
                    model.InvoiceDate  = createdDate;
                    model.VendorDetail = GetVendorDetail();
                    model.InvoiceNo    = GetVoucherByTransactionRef(masterPNRId).ToString().PadLeft(4, '0');

                    InvoiceItineraryDetailModel itinerary = new InvoiceItineraryDetailModel();

                    var sectorDetail = GetPNRSectorDetail((int)pnrDetail.PNRId);
                    model.TravelDate = sectorDetail.DepartDate;
                    List <int> segDepCityIdList = new List <int>();
                    var        segmentdetail    = GetSegmentDetail((int)pnrDetail.PNRId);
                    int        departcityid     = 0;
                    int        arrivecityid     = 1;

                    foreach (TBO_PNRsegments segment in segmentdetail)
                    {
                        departcityid = segmentdetail[0].DepartCityId;
                        arrivecityid = segment.ArrivalCityId;

                        segDepCityIdList.Add(segment.DepartCityId);

                        InvoiceItinerarySegment invoiceSegment = new InvoiceItinerarySegment();
                        var airlineDetail = GetAirlineDetailById(segment.AirlineId);
                        invoiceSegment.Airline       = airlineDetail.AirlineName;
                        invoiceSegment.AirlineCode   = airlineDetail.AirlineCode;
                        invoiceSegment.FlightNo      = segment.FlightNumber;
                        invoiceSegment.Class         = segment.BIC;
                        invoiceSegment.DepartureDate = segment.DepartDate.ToString();
                        itinerary.Segments.Add(invoiceSegment);
                    }

                    if (departcityid != arrivecityid)
                    {
                        model.Journey = "OneWay";
                    }
                    else
                    {
                        model.Journey = "RoundTrip";
                    }
                    string sector = string.Empty;
                    foreach (var cityId in segDepCityIdList)
                    {
                        sector += GetCityDetailsByCityId(cityId).CityCode + " - ";
                    }
                    if (model.Journey == "OneWay")
                    {
                        sector += GetCityDetailsByCityId(sectorDetail.DestinationCityId).CityCode;
                    }

                    if (model.Journey == "RoundTrip")
                    {
                        sector += GetCityDetailsByCityId(sectorDetail.DepartCityId).CityCode;
                    }
                    itinerary.Sector = sector;

                    double grossAmt                = 0;
                    double discountAmt             = 0;
                    double serviceTax              = 0;
                    double transFee                = 0;
                    double totalCalculatedDiscount = 0;
                    double totalSummedDiscount     = 0;
                    double totalTranFee            = 0;
                    var    paxDetail               = GetPassengerDetails((int)pnr);

                    int paxcounter = paxDetail.Count;
                    foreach (TBO_Passengers pax in paxDetail)
                    {
                        InvoicePassenger invPax = new InvoicePassenger();

                        invPax.PassengerName = pax.FirstName + " " + pax.MiddleName + " " + pax.LastName;
                        invPax.PassengerType = GetPassengerTypeById(pax.PassengerTypeId).PassengerTypeName;

                        var pnrtickets = GetPNRTickets((int)pax.PassengerId);
                        if (pnrtickets != null)
                        {
                            model.Currency = pnrtickets.Currency;
                            invPax.FxRate  = pnrtickets.LCY_FX_Rate;
                            if (invPax.FxRate == 0)
                            {
                                invPax.FxRate = 1;
                            }
                            if (model.Currency != "USD")
                            {
                                invPax.Fare          = pnrtickets.SellingBaseFare * invPax.FxRate;
                                invPax.OtherCharge   = pnrtickets.SellingOtherCharges * invPax.FxRate;
                                invPax.FuelSurcharge = pnrtickets.SellingFSC * invPax.FxRate;
                                invPax.ServiceCharge = pnrtickets.ServiceCharge * invPax.FxRate;
                                if (viewModel.ServiceProviderId == 5)                                                          //TBO ALREADY CONTAIN FSC ON TAX
                                {
                                    invPax.Tax = (pnrtickets.SellingTax + pnrtickets.SellingAdditionalTxnFee) * invPax.FxRate; //+ pnrtickets.MarkupAmount;
                                }
                                else
                                {
                                    invPax.Tax = (pnrtickets.SellingTax + pnrtickets.SellingAdditionalTxnFee + pnrtickets.SellingFSC) * invPax.FxRate; //+ pnrtickets.MarkupAmount;
                                }
                                grossAmt           += invPax.Fare + invPax.OtherCharge + invPax.Tax;                                                   // + invPax.ServiceCharge
                                invPax.MarkupAmount = pnrtickets.MarkupAmount * invPax.FxRate;
                                discountAmt        += pnrtickets.DiscountAmount * invPax.FxRate;

                                totalCalculatedDiscount = pnrtickets.DiscountAmount > 0 ? pnrtickets.DiscountAmount : 0;

                                totalTranFee += (pnrtickets.DiscountAmount < 0 ? Math.Abs(pnrtickets.DiscountAmount) : 0);

                                //if (masterPnrDetails.isBranchByPassDeal == false)
                                //{
                                //    totalCalculatedDiscount = pnrtickets.BranchDealAmount < 0 ? Math.Abs(pnrtickets.BranchDealAmount) : 0;
                                //    totalTranFee += (pnrtickets.BranchDealAmount > 0 ? Math.Abs(pnrtickets.BranchDealAmount) : 0);
                                //}
                                //if (masterPnrDetails.isDistributorByPassDeal == false)
                                //{
                                //    totalCalculatedDiscount = pnrtickets.DistrubutorDealAmount < 0 ? Math.Abs(pnrtickets.DistrubutorDealAmount) : 0;
                                //    totalTranFee += (pnrtickets.DistrubutorDealAmount > 0 ? Math.Abs(pnrtickets.DistrubutorDealAmount) : 0);
                                //}

                                //totalCalculatedDiscount += (pnrtickets.DiscountAmount > 0 ? pnrtickets.DiscountAmount : 0 +
                                //          (pnrtickets.BranchDealAmount < 0 ? Math.Abs(pnrtickets.BranchDealAmount) : 0) +
                                //          (pnrtickets.DistrubutorDealAmount < 0 ? Math.Abs(pnrtickets.DistrubutorDealAmount) : 0));
                                //totalTranFee += ((pnrtickets.DiscountAmount < 0 ? Math.Abs(pnrtickets.DiscountAmount) : 0) +
                                //         (pnrtickets.BranchDealAmount > 0 ? Math.Abs(pnrtickets.BranchDealAmount) : 0) +
                                //         (pnrtickets.DistrubutorDealAmount > 0 ? Math.Abs(pnrtickets.DistrubutorDealAmount) : 0));

                                serviceTax += pnrtickets.SellingServiceTax * invPax.FxRate;

                                transFee += pnrtickets.SellingAirlineTransFee * invPax.FxRate;
                                model.AgentAirlineMarkUp = pnrtickets.MarkupAmount * invPax.FxRate;
                            }
                            else
                            {
                                invPax.Fare          = pnrtickets.SellingBaseFare;
                                invPax.OtherCharge   = pnrtickets.SellingOtherCharges;
                                invPax.FuelSurcharge = pnrtickets.SellingFSC;
                                invPax.ServiceCharge = pnrtickets.ServiceCharge;
                                if (viewModel.ServiceProviderId == 5)                                          //TBO ALREADY CONTAIN FSC ON TAX
                                {
                                    invPax.Tax = (pnrtickets.SellingTax + pnrtickets.SellingAdditionalTxnFee); //+ pnrtickets.MarkupAmount;
                                }
                                else
                                {
                                    invPax.Tax = (pnrtickets.SellingTax + pnrtickets.SellingAdditionalTxnFee + pnrtickets.SellingFSC); //+ pnrtickets.MarkupAmount;
                                }
                                grossAmt           += invPax.Fare + invPax.OtherCharge + invPax.Tax;                                   // + invPax.ServiceCharge
                                invPax.MarkupAmount = pnrtickets.MarkupAmount;
                                discountAmt        += pnrtickets.DiscountAmount;

                                totalCalculatedDiscount = pnrtickets.DiscountAmount > 0 ? pnrtickets.DiscountAmount : 0;
                                totalTranFee            = (pnrtickets.DiscountAmount < 0 ? Math.Abs(pnrtickets.DiscountAmount) : 0);
                                //if (masterPnrDetails.isBranchByPassDeal == false)
                                //{
                                //    totalCalculatedDiscount = pnrtickets.BranchDealAmount < 0 ? Math.Abs(pnrtickets.BranchDealAmount) : 0;
                                //    totalTranFee += (pnrtickets.BranchDealAmount > 0 ? Math.Abs(pnrtickets.BranchDealAmount) : 0);
                                //}
                                //if (masterPnrDetails.isDistributorByPassDeal == false)
                                //{
                                //    totalCalculatedDiscount = pnrtickets.DistrubutorDealAmount < 0 ? Math.Abs(pnrtickets.DistrubutorDealAmount) : 0;
                                //    totalTranFee += (pnrtickets.DistrubutorDealAmount > 0 ? Math.Abs(pnrtickets.DistrubutorDealAmount) : 0);
                                //}

                                //totalCalculatedDiscount += (pnrtickets.DiscountAmount > 0 ? pnrtickets.DiscountAmount : 0 +
                                //        (pnrtickets.BranchDealAmount < 0 ? Math.Abs(pnrtickets.BranchDealAmount) : 0) +
                                //        (pnrtickets.DistrubutorDealAmount < 0 ? Math.Abs(pnrtickets.DistrubutorDealAmount) : 0));
                                //totalTranFee += ((pnrtickets.DiscountAmount < 0 ? Math.Abs(pnrtickets.DiscountAmount) : 0) +
                                //         (pnrtickets.BranchDealAmount > 0 ? Math.Abs(pnrtickets.BranchDealAmount) : 0) +
                                //         (pnrtickets.DistrubutorDealAmount > 0 ? Math.Abs(pnrtickets.DistrubutorDealAmount) : 0));


                                serviceTax += pnrtickets.SellingServiceTax;

                                transFee += pnrtickets.SellingAirlineTransFee;
                                model.AgentAirlineMarkUp = pnrtickets.MarkupAmount;
                            }
                            totalSummedDiscount += totalCalculatedDiscount;
                            itinerary.TicketNo   = pnrtickets.TicketNumber;
                            invPax.TicketNo      = pnrtickets.TicketNumber;


                            model.AgentAirlineMarkUp = pnrtickets.MarkupAmount;
                            model.TicketStatusId     = pnrtickets.TicketStatusId;
                        }
                        itinerary.PassengerDetail.Add(invPax);
                    }
                    model.ItineraryDetails.Add(itinerary);
                    model.GrossAmount = grossAmt;

                    model.CommissionEarned = totalSummedDiscount;
                    model.TransactionFee   = totalTranFee + transFee;


                    model.ServiceTax = serviceTax;

                    model.TaxDeductionAtSource = Math.Ceiling(totalSummedDiscount * 0.1);

                    model.NetAmount     = model.GrossAmount - model.CommissionEarned + model.ServiceTax + model.TransactionFee;
                    model.NetReceivable = model.NetAmount;
                    viewModel.PNRDetails.Add(model);
                }
                return(viewModel);
            }
        }
Exemplo n.º 25
0
        public IActionResult Index(int id, string view, int patientId, int invoiceId
                                   , int page, string firstName, string lastName, string invoiceFromDate, string invoiceToDate)
        {
            var userContext = _userHandler.GetUserContext();

            if (view == "InvoiceForm")
            {
                if (id == 0)
                {
                    ViewData["Title"]    = $"New Invoice";
                    ViewData["FormType"] = $"New Invoice";

                    var patient = _patientService.SearchPatientModelAsync(patientId);
                    if (patient != null)
                    {
                        var patients = _patientService.SearchPatientsAsync(patient.FamilyId);

                        ViewBag.ListofPatient = patients.Select(p => new ListItemModel
                        {
                            Id   = p.PatientId,
                            Name = $"{p.FirstName} {p.LastName}"
                        }).ToList();

                        var doctors = _doctorService.SearchDoctorsAsync(userContext.ClinicId);

                        ViewBag.ListofDoctor = doctors.Select(p => new ListItemModel
                        {
                            Id   = p.DoctorId,
                            Name = $"{p.FirstName} {p.LastName}"
                        }).ToList();

                        var data = new InvoiceViewModel
                        {
                            FamilyId    = patient.FamilyId,
                            PatientId   = patient.PatientId,
                            DoctorId    = patient.DoctorId,
                            InvoiceDate = DateTime.Now,
                            PatientName = $"{patient.FirstName} {patient.LastName}",
                            Patients    = patients.Select(p => (PatientViewModel)p).ToList()
                        };
                        return(View(view, data));
                    }
                    else
                    {
                        var result = new BaseResultViewModel();
                        result.Message = "Patient not found. ";

                        return(View("_SharedResult", result));
                    }
                }
                else
                {
                    ViewData["Title"]    = $"Edit Invoice";
                    ViewData["FormType"] = $"Edit Invoice";

                    return(View(view));
                }
            }
            else if (view == "InvoiceDetail")
            {
                ViewData["Title"] = $"Invoice Detail";

                var data = _invoiceService.SearchInvoice(invoiceId);
                if (data != null)
                {
                    var viewData = (InvoiceViewModel)data;

                    return(View(view, viewData));
                }
                else
                {
                    var result = new BaseResultViewModel();
                    result.Message = "Invoice not found. ";

                    return(View("_SharedResult", result));
                }
            }
            else if (view == "Index")
            {
                ViewData["Title"] = $"Search Invoice";

                var invoiceRequestViewModel = new InvoiceRequestViewModel();

                if (page > 0)
                {
                    invoiceRequestViewModel = new InvoiceRequestViewModel()
                    {
                        CurrentPage     = page,
                        FirstName       = firstName,
                        LastName        = lastName,
                        InvoiceFromDate = invoiceFromDate,
                        InvoiceToDate   = invoiceToDate
                    };
                    if (invoiceId > 0)
                    {
                        invoiceRequestViewModel.DisplayId = invoiceId;
                    }

                    invoiceRequestViewModel = GetInvoiceRequestViewModel(invoiceRequestViewModel);
                    SetInvoiceFilter(invoiceRequestViewModel);
                }

                return(View(view, invoiceRequestViewModel));
            }

            return(View(view));
        }
Exemplo n.º 26
0
        public InvoiceViewModel GetInvoiceDetail(int agentId, int masterPNRId)
        {
            StringBuilder builder = new StringBuilder();

            GetMasterPNRDetail(agentId, masterPNRId);

            var masterPnrDetails = _ent.TBO_MasterPNRs.Where(x => x.MPNRId == masterPNRId).FirstOrDefault();


            var pnrDetails             = _ent.TBO_PNRs.ToList().FindAll(id => id.MPNRId == masterPNRId).Select(x => x.PNRId).ToList();
            InvoiceViewModel viewModel = new InvoiceViewModel();

            int pnrcount = pnrDetails.Count;

            foreach (var pnr in pnrDetails)
            {
                InvoicePNRDetailModel model = new InvoicePNRDetailModel();

                var agentdetail = GetAgentDetail(agentId);

                var pnrDetail        = GetPNRDetailById((int)pnr);
                var paxDetailByPNRId = GetPassengerDetails((int)pnrDetail.PNRId);

                model.AgencyDetail    = agentdetail;
                model.BilledBy        = "Travel Planner Pvt.Ltd";
                model.TicketedToAgent = agentdetail.AgencyName;

                model.BilledByAgent       = agentdetail.AgencyName;
                model.TicketedToPassenger = paxDetailByPNRId.FirstOrDefault().FirstName + paxDetailByPNRId.FirstOrDefault().LastName;


                model.PNRId = (int)pnrDetail.PNRId;
                model.PNR   = pnrDetail.RecLoc;

                model.InvoiceDate  = createdDate;
                model.VendorDetail = GetVendorDetail();

                model.InvoiceNo = "ATSI" + GetVoucherByTransactionRef(masterPNRId).ToString().PadLeft(4, '0');

                InvoiceItineraryDetailModel itinerary = new InvoiceItineraryDetailModel();

                var sectorDetail = GetPNRSectorDetail((int)pnr);
                model.TravelDate = sectorDetail.DepartDate;

                List <int> segDepCityIdList = new List <int>();
                ;
                var segmentdetail = GetSegmentDetail((int)sectorDetail.SectorId);

                int departcityid = 0;
                int arrivecityid = 1;

                foreach (TBO_PNRsegments segment in segmentdetail)
                {
                    departcityid = segmentdetail[0].DepartCityId;
                    arrivecityid = segment.ArrivalCityId;

                    segDepCityIdList.Add(segment.DepartCityId);

                    InvoiceItinerarySegment invoiceSegment = new InvoiceItinerarySegment();
                    var airlineDetail = GetAirlineDetailById(segment.AirlineId);
                    invoiceSegment.Airline     = airlineDetail.AirlineName;
                    invoiceSegment.AirlineCode = airlineDetail.AirlineCode;
                    invoiceSegment.FlightNo    = segment.FlightNumber;
                    invoiceSegment.Class       = segment.BIC;
                    itinerary.Segments.Add(invoiceSegment);
                }

                if (departcityid != arrivecityid)
                {
                    model.Journey = "OneWay";
                }

                else
                {
                    model.Journey = "RoundTrip";
                }

                string sector = string.Empty;
                foreach (var cityId in segDepCityIdList)
                {
                    sector += GetCityDetailsByCityId(cityId).CityCode + " - ";
                }
                if (model.Journey == "OneWay")
                {
                    sector += GetCityDetailsByCityId(sectorDetail.DestinationCityId).CityCode;
                }

                if (model.Journey == "RoundTrip")
                {
                    sector += GetCityDetailsByCityId(sectorDetail.DepartCityId).CityCode;
                }

                itinerary.Sector = sector;

                double grossAmt    = 0;
                double discountAmt = 0;
                double serviceTax  = 0;
                double transFee    = 0;
                var    paxDetail   = GetPassengerDetails((int)pnr);
                int    paxcounter  = paxDetail.Count;
                foreach (TBO_Passengers pax in paxDetail)
                {
                    InvoicePassenger invPax = new InvoicePassenger();

                    invPax.PassengerName = pax.FirstName + " " + pax.MiddleName + " " + pax.LastName;
                    invPax.PassengerType = GetPassengerTypeById(pax.PassengerTypeId).PassengerTypeName;

                    var pnrtickets = GetPNRTickets((int)pax.PassengerId);
                    if (pnrtickets != null)
                    {
                        invPax.Fare          = pnrtickets.SellingBaseFare;
                        invPax.OtherCharge   = pnrtickets.SellingOtherCharges;
                        invPax.FuelSurcharge = pnrtickets.SellingFSC;
                        invPax.ServiceCharge = pnrtickets.ServiceCharge;
                        invPax.Tax           = pnrtickets.SellingTax + pnrtickets.SellingAdditionalTxnFee + pnrtickets.MarkupAmount;
                        grossAmt            += invPax.Fare + invPax.OtherCharge + invPax.Tax + invPax.FuelSurcharge;
                        invPax.MarkupAmount  = pnrtickets.MarkupAmount;
                        itinerary.TicketNo   = pnrtickets.TicketNumber;

                        discountAmt = pnrtickets.DiscountAmount;
                        serviceTax  = pnrtickets.SellingServiceTax;
                        transFee   += pnrtickets.SellingAirlineTransFee;
                        model.AgentAirlineMarkUp = pnrtickets.MarkupAmount;
                        model.TicketStatusId     = pnrtickets.TicketStatusId;

                        model.NetAmount = pnrtickets.BaseFare - pnrtickets.DiscountAmount + pnrtickets.FSC + pnrtickets.Tax + pnrtickets.MarkupAmount +
                                          pnrtickets.OtherCharges + pnrtickets.ServiceTax + pnrtickets.ServiceCharge + pnrtickets.AirlineTransFee
                                          + pnrtickets.AdditionalTxnFee;
                    }
                    itinerary.PassengerDetail.Add(invPax);
                }
                model.ItineraryDetails.Add(itinerary);
                model.GrossAmount      = grossAmt;
                model.CommissionEarned = discountAmt;
                model.ServiceTax       = serviceTax;
                model.TransactionFee   = transFee;


                model.NetReceivable = model.NetAmount;
                viewModel.PNRDetails.Add(model);
            }
            return(viewModel);
        }
        public ActionResult AgentInvoiceDetails(int agentId)
        {
            var invoiceDetails = (from c in _context.Customer
                                  join i in _context.Invoice
                                  on c.IdCustomer equals i.IdCustomer

                                  join ag in _context.Agent
                                  on i.IdAgent equals ag.IdAgent

                                  join iap in _context.InvoiceArtPiece
                                  on i.IdInvoice equals iap.IdInvoice

                                  join ap in _context.ArtPiece
                                  on iap.IdArtPiece equals ap.IdArtPiece

                                  join aw in _context.ArtWork
                                  on ap.IdArtWork equals aw.IdArtWork

                                  join ar in _context.Artist
                                  on aw.IdArtist equals ar.IdArtist

                                  where ag.IdAgent == agentId
                                  group new
            {
                i.IdInvoice,
                ag.AgentFirstName,
                ag.AgentLastName,
                c.CustomerFirstName,
                c.CustomerLastName,
                c.CustomerAddress,
                c.CustomerPhoneNumber,
                i.PaymentMethod,
                ap.IdArtPiece,
                aw.ArtWorkTitle,
                ar.ArtistName
            }
                                  by i.IdInvoice into newGroup
                                  select newGroup).ToList();


            // Create a father VM that will cointains a list of tickets
            InvoiceListViewModel Allinvoices = new InvoiceListViewModel();
            // Create a local VM that IS a list of tickets
            List <InvoiceViewModel> _localInvoices = new List <InvoiceViewModel>();
            decimal TotalSales = new decimal();

            foreach (var item in invoiceDetails)
            { //create a new view model
                InvoiceViewModel ivm = new InvoiceViewModel();
                ivm.IdInvoice           = item.First().IdInvoice;
                ivm.agentName           = item.First().AgentFirstName + " " + item.First().AgentLastName;
                ivm.customerName        = item.First().CustomerFirstName + " " + item.First().CustomerLastName;
                ivm.customerAddress     = item.First().CustomerAddress;
                ivm.customerPhoneNumber = item.First().CustomerPhoneNumber;
                ivm.paymentMethod       = item.First().PaymentMethod;
                decimal            invoiceTotalSales = new decimal();
                List <APinInvoice> art = new List <APinInvoice>();
                // Get acces to each painting sold in the invoice
                foreach (var curInvoice in item)
                { //add painting to the view model of each invoice
                    APinInvoice singleAP = new APinInvoice();
                    singleAP.Artist        = curInvoice.ArtistName;
                    singleAP.ArtWorkTitle  = curInvoice.ArtWorkTitle;
                    singleAP.ArtPiecePrice = curInvoice.IdArtPiece;
                    art.Add(singleAP);
                    invoiceTotalSales += singleAP.ArtPiecePrice;
                    //ivm.IdartPiece.Add(curInvoice.IdArtPiece);
                }
                ivm.invoiceTotalSales = invoiceTotalSales;
                TotalSales           += invoiceTotalSales;
                ivm.ArtWork           = art;
                _localInvoices.Add(ivm);
            }
            Allinvoices.TotalSales    = TotalSales;
            Allinvoices.InvoiceModels = _localInvoices;
            return(View(Allinvoices));
        }
Exemplo n.º 28
0
 public static double TotalPrice(this InvoiceViewModel invoice)
 {
     return(invoice.Basket.BasketItems.Sum(i => i.Amount * i.UnitPrice));
 }
Exemplo n.º 29
0
        public IActionResult Invoice()
        {
            InvoiceViewModel vm = new InvoiceViewModel();

            return(View(vm));
        }
        public InvoiceViewModel UpdateContractInvoice(InvoiceViewModel invoice)
        {
            var invoiceFromDb = this.Data.Invoices
                .All()
              .FirstOrDefault(c => c.Id == invoice.Id);

            invoiceFromDb.From = invoice.From;
            invoiceFromDb.To = invoice.To;
            invoiceFromDb.MgSubs = invoice.MgSubs;
            invoiceFromDb.Cps = invoice.Cps;
            invoiceFromDb.Comments = invoice.Comments;
            invoiceFromDb.CorrespondencePayment = invoice.CorrespondencePayment;
            invoiceFromDb.AdditionalInformation = invoice.AdditionalInformation;
            invoiceFromDb.FixedMonthlyFee = invoice.FixedMonthlyFee;
            invoiceFromDb.Vat = invoice.Vat;
            invoiceFromDb.IsVisible = invoice.IsVisible;

            this.Data.SaveChanges();

            return invoice;
        }
Exemplo n.º 31
0
 public Sales_Return_Report()
 {
     InitializeComponent();
     _IVM             = new InvoiceViewModel();
     this.DataContext = _IVM;
 }
Exemplo n.º 32
0
        public IActionResult Detail(int id)
        {
            var invoice = new InvoiceViewModel();

            return(View(invoice));
        }
Exemplo n.º 33
0
 public ListTapCommand(InvoiceViewModel invoiceVM)
 {
     viewModel = invoiceVM;
 }
Exemplo n.º 34
0
        public InvoiceMaster SaveInvoiceForSalesOrder(InvoiceViewModel invoiceData, int tenantId, int userId)
        {
            var     account                  = _currentDbContext.Account.Find(invoiceData.AccountId);
            var     invoiceMaster            = _currentDbContext.InvoiceMasters.FirstOrDefault(u => u.InvoiceMasterId == invoiceData.InvoiceMasterId);
            decimal amount                   = invoiceMaster.InvoiceTotal;
            int     accountTransactionTypeId = (int)AccountTransactionTypeEnum.InvoicedToAccount;

            if (invoiceMaster != null)
            {
                invoiceMaster.OrderProcessId = invoiceData.OrderProcessId < 1 ? (int?)null : invoiceData.OrderProcessId;

                invoiceMaster.InvoiceDate     = invoiceData.InvoiceDate;
                invoiceMaster.AccountId       = invoiceData.AccountId;
                invoiceMaster.CardCharges     = invoiceData.CardCharges;
                invoiceMaster.InvoiceAddress  = account.FullAddress;
                invoiceMaster.InvoiceCurrency = account.GlobalCurrency.CurrencyName;
                invoiceMaster.DateUpdated     = DateTime.UtcNow;
                invoiceMaster.InvoiceTotal    = invoiceData.InvoiceTotal;
                invoiceMaster.NetAmount       = invoiceData.NetAmount - invoiceData.TaxAmount;
                invoiceMaster.PostageCharges  = invoiceData.PostageCharges;
                invoiceMaster.TaxAmount       = invoiceData.TaxAmount;
                invoiceMaster.WarrantyAmount  = invoiceData.WarrantyAmount;
                invoiceMaster.UpdatedBy       = userId;
                invoiceMaster.CurrencyId      = account.CurrencyID;
                invoiceMaster.InvoiceNumber   = invoiceMaster.InvoiceNumber;
                var invoiceProductID = invoiceData.AllInvoiceProducts.Select(u => u.ProductId).ToList();
                var invoiceDelete    = _currentDbContext.InvoiceDetails.Where(u => u.InvoiceMasterId == invoiceMaster.InvoiceMasterId && !invoiceProductID.Contains(u.ProductId) && u.IsDeleted != true).ToList();
                invoiceDelete.ForEach(u => u.IsDeleted = true);
                foreach (var item in invoiceData.AllInvoiceProducts)
                {
                    var invoiceDetail = _currentDbContext.InvoiceDetails.FirstOrDefault(u => u.ProductId == item.ProductId && u.InvoiceMasterId == invoiceMaster.InvoiceMasterId && u.IsDeleted != true);
                    if (invoiceDetail == null)
                    {
                        invoiceDetail = new InvoiceDetail()
                        {
                            ProductId       = item.ProductId,
                            Quantity        = item.QtyProcessed,
                            Price           = item.Price,
                            Total           = item.TotalAmount + (item.TaxAmountsInvoice ?? 0) + item.WarrantyAmount,
                            Tax             = item.TaxAmountsInvoice ?? 0,
                            NetAmount       = item.TotalAmount,
                            WarrantyAmount  = item.WarrantyAmount,
                            CreatedBy       = userId,
                            DateCreated     = DateTime.UtcNow,
                            DateUpdated     = DateTime.UtcNow,
                            UpdatedBy       = userId,
                            InvoiceMasterId = invoiceMaster.InvoiceMasterId,
                        };
                        _currentDbContext.InvoiceDetails.Add(invoiceDetail);
                        _currentDbContext.Entry(invoiceDetail).State = EntityState.Added;
                    }

                    else
                    {
                        invoiceDetail.ProductId       = item.ProductId;
                        invoiceDetail.Quantity        = item.QtyProcessed;
                        invoiceDetail.Price           = item.Price;
                        invoiceDetail.Total           = item.TotalAmount + item.TaxAmount + item.WarrantyAmount;
                        invoiceDetail.Tax             = item.TaxAmountsInvoice ?? 0;
                        invoiceDetail.NetAmount       = item.TotalAmount;
                        invoiceDetail.WarrantyAmount  = item.WarrantyAmount;
                        invoiceDetail.CreatedBy       = userId;
                        invoiceDetail.DateCreated     = DateTime.UtcNow;
                        invoiceDetail.DateUpdated     = DateTime.UtcNow;
                        invoiceDetail.UpdatedBy       = userId;
                        invoiceDetail.TenantId        = tenantId;
                        invoiceDetail.InvoiceMasterId = invoiceMaster.InvoiceMasterId;
                        _currentDbContext.Entry(invoiceDetail).State = EntityState.Modified;
                    }
                }
                var process = _currentDbContext.OrderProcess.Find(invoiceData.OrderProcessId);
                if (process != null)
                {
                    process.InvoiceNo            = invoiceMaster.InvoiceNumber;
                    process.OrderProcessStatusId = (int)OrderProcessStatusEnum.Invoiced;
                    process.DateUpdated          = DateTime.UtcNow;
                    process.UpdatedBy            = userId;

                    process.Order.InvoiceNo = invoiceMaster.InvoiceNumber + string.Join(",", _currentDbContext.OrderProcess.Where(u => u.OrderID == process.OrderID).Select(u => u.InvoiceNo).ToList());
                    _currentDbContext.Entry(process).State = EntityState.Modified;
                }
                if (amount > invoiceData.InvoiceTotal)
                {
                    amount = (amount - invoiceData.InvoiceTotal);
                    accountTransactionTypeId = (int)AccountTransactionTypeEnum.Refund;
                }
                else
                {
                    amount = (invoiceData.InvoiceTotal - amount);
                }
                if (amount > 0)
                {
                    var accountTransaction = new AccountTransaction()
                    {
                        AccountId = account.AccountID,
                        AccountTransactionTypeId = accountTransactionTypeId,
                        CreatedBy   = userId,
                        Notes       = ("Invoiced : " + (process != null ? process.Order.OrderNumber : "")).Trim(),
                        DateCreated = DateTime.UtcNow,
                        Amount      = amount,
                        TenantId    = tenantId
                    };
                    _currentDbContext.Entry(invoiceMaster).State = EntityState.Modified;

                    if (process != null)
                    {
                        var orderPorcessCount = _currentDbContext.OrderProcess.Count(u => u.OrderID == process.OrderID && u.OrderProcessStatusId != (int)OrderProcessStatusEnum.Invoiced);
                        if (orderPorcessCount <= 0)
                        {
                            process.Order.OrderStatusID = (int)OrderStatusEnum.Invoiced;
                            _currentDbContext.SaveChanges();
                        }
                    }

                    SaveAccountTransaction(accountTransaction, tenantId, userId);
                }
                _currentDbContext.SaveChanges();
                return(invoiceMaster);
            }

            return(null);
        }
 public override void RefreshDataView()
 {
     if (!bgwMain.IsBusy)
     {
         MethodBase.GetCurrentMethod().Info("Fecthing SalesReturn data...");
         _selectedInvoice = null;
         FormHelpers.CurrentMainForm.UpdateStatusInformation("Memuat data penjualan...", false);
         bgwMain.RunWorkerAsync();
     }
 }
Exemplo n.º 36
0
        public InvoiceViewModel LoadInvoiceProductValuesByOrderProcessId(int orderProcessId, int?inventoryTransctionType = null)
        {
            InvoiceViewModel model = new InvoiceViewModel();
            var orderProcess       = _currentDbContext.OrderProcess.FirstOrDefault(u => u.OrderProcessID == orderProcessId && u.IsDeleted != true);

            if (orderProcess != null)
            {
                model.OrderNumber     = orderProcess.Order.OrderNumber;
                model.OrderProcessId  = orderProcess.OrderProcessID;
                model.InvoiceCurrency = orderProcess.Order.Account.GlobalCurrency.CurrencyName;
                model.InvoiceAddress  = orderProcess.Order.Account.FullAddressWithNameHtml;
                model.AccountId       = orderProcess.Order.AccountID ?? 0;
                model.InvoiceDate     = orderProcess.InvoiceDate ?? DateTime.UtcNow;
                //model.TenantName = CurrentTenant.TenantName;
            }

            var orderProcesses = _currentDbContext.OrderProcessDetail
                                 .Where(o => o.OrderProcessId == orderProcessId && o.IsDeleted != true)
                                 .Include(o => o.ProductMaster)
                                 .ToList();

            foreach (var x in orderProcesses)
            {
                var pd = model.AllInvoiceProducts.FirstOrDefault(m => m.ProductId == x.ProductId);
                if (pd == null)
                {
                    pd = new OrderProcessDetailsViewModel()
                    {
                        QtyProcessed   = x.QtyProcessed,
                        ProductName    = x.ProductMaster.Name,
                        ProductCode    = x.ProductMaster.SKUCode,
                        ProductId      = x.ProductId,
                        OrderProcessId = x.OrderProcessId,
                        //Remove methods from here
                        Price = x?.OrderDetail?.Price ?? 0,
                        OrderProcessDetailId = x.OrderProcessDetailID,
                        TaxAmountsInvoice    = ((x?.OrderDetail?.Price ?? 0 * x.QtyProcessed) / 100) * (x.OrderDetail.TaxName?.PercentageOfAmount ?? 0)
                    };
                    if (x?.OrderDetail?.Warranty != null)
                    {
                        pd.WarrantyAmount = x.OrderDetail.Warranty.IsPercent ? Math.Round(x.OrderDetail.Warranty.PercentageOfPrice * ((pd.Price * x.QtyProcessed) / 100), 2) : Math.Round(x.OrderDetail.Warranty.FixedPrice * x.QtyProcessed, 2);
                    }
                    if (x?.OrderDetail?.TaxName != null)
                    {
                        pd.TaxPercent = x.OrderDetail.TaxName.PercentageOfAmount;
                    }

                    model.AllInvoiceProducts.Add(pd);
                }
                else
                {
                    var index = model.AllInvoiceProducts.IndexOf(pd);
                    model.AllInvoiceProducts[index].QtyProcessed += x.QtyProcessed;
                }
            }
            model.TaxAmount = model.AllInvoiceProducts.Select(I => I.TaxAmount).DefaultIfEmpty(0).Sum();
            var amount = model.AllInvoiceProducts.Select(u => u.NetAmount).DefaultIfEmpty(0).Sum();

            model.NetAmount       = amount - model.TaxAmount;
            model.WarrantyAmount += model.AllInvoiceProducts.Select(u => u.WarrantyAmount).DefaultIfEmpty(0).Sum();
            model.InvoiceTotal    = Math.Round(model.NetAmount + model.TaxAmount + model.WarrantyAmount, 2);

            return(model);
        }
        public JsonResult UpdateContractInvoice([DataSourceRequest] DataSourceRequest request, InvoiceViewModel invoice)
        {
            if (invoice == null || !ModelState.IsValid)
            {
                return Json(new[] { invoice }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
            }

            var updatedInvoice = this.invoices.UpdateContractInvoice(invoice);

            var loggedUserId = this.User.Identity.GetUserId();
            Base.CreateActivity(ActivityType.Edit, updatedInvoice.Id.ToString(), ActivityTargetType.Invoice, loggedUserId);

            invoice.Id = updatedInvoice.Id;

            return Json((new[] { invoice }.ToDataSourceResult(request, ModelState)), JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 38
0
        public InvoiceMaster CreateInvoiceForSalesOrder(InvoiceViewModel invoiceData, int tenantId, int userId)
        {
            var account = _currentDbContext.Account.Find(invoiceData.AccountId);

            var invoice = new InvoiceMaster
            {
                OrderProcessId  = invoiceData.OrderProcessId < 1 ? (int?)null : invoiceData.OrderProcessId,
                TenantId        = tenantId,
                DateCreated     = DateTime.UtcNow,
                CreatedBy       = userId,
                InvoiceDate     = invoiceData.InvoiceDate,
                AccountId       = invoiceData.AccountId,
                CardCharges     = invoiceData.CardCharges,
                InvoiceAddress  = account.FullAddress,
                InvoiceCurrency = account.GlobalCurrency.CurrencyName,
                DateUpdated     = DateTime.UtcNow,
                InvoiceTotal    = invoiceData.InvoiceTotal,
                NetAmount       = invoiceData.InvoiceTotal - invoiceData.TaxAmount,
                PostageCharges  = invoiceData.PostageCharges,
                TaxAmount       = invoiceData.TaxAmount,
                WarrantyAmount  = invoiceData.WarrantyAmount,
                UpdatedBy       = userId,
                CurrencyId      = account.CurrencyID
            };

            invoice.InvoiceNumber = GenerateNextInvoiceNumber(tenantId);


            invoice.InvoiceDetails = invoiceData.AllInvoiceProducts.Select(m => new InvoiceDetail()
            {
                ProductId      = m.ProductId,
                Quantity       = m.QtyProcessed,
                Price          = m.Price,
                Total          = m.TotalAmount + (m.TaxAmountsInvoice ?? 0) + m.WarrantyAmount,
                Tax            = m.TaxAmountsInvoice ?? 0,
                NetAmount      = m.TotalAmount,
                WarrantyAmount = m.WarrantyAmount,
                CreatedBy      = userId,
                DateCreated    = DateTime.UtcNow,
                DateUpdated    = DateTime.UtcNow,
                UpdatedBy      = userId,
                TenantId       = tenantId
            }).ToList();
            _currentDbContext.Entry(invoice).State = EntityState.Added;

            var process = _currentDbContext.OrderProcess.Find(invoiceData.OrderProcessId);

            if (process != null)
            {
                process.InvoiceNo            = invoice.InvoiceNumber;
                process.OrderProcessStatusId = (int)OrderProcessStatusEnum.Invoiced;
                process.DateUpdated          = DateTime.UtcNow;
                process.UpdatedBy            = userId;

                process.Order.InvoiceNo = invoice.InvoiceNumber + string.Join(",", _currentDbContext.OrderProcess.Where(u => u.OrderID == process.OrderID).Select(u => u.InvoiceNo).ToList());
                _currentDbContext.Entry(process).State = EntityState.Modified;
            }


            var accountTransaction = new AccountTransaction()
            {
                AccountId = account.AccountID,
                AccountTransactionTypeId = (int)AccountTransactionTypeEnum.InvoicedToAccount,
                CreatedBy   = userId,
                Notes       = ("Invoiced : " + (process != null ? process.Order.OrderNumber : "")).Trim(),
                DateCreated = DateTime.UtcNow,
                Amount      = invoice.InvoiceTotal,
                TenantId    = tenantId
            };

            _currentDbContext.Entry(account).State = EntityState.Modified;
            _currentDbContext.SaveChanges();
            if (process != null)
            {
                var orderPorcessCount = _currentDbContext.OrderProcess.Count(u => u.OrderID == process.OrderID && u.OrderProcessStatusId != (int)OrderProcessStatusEnum.Invoiced);
                if (orderPorcessCount <= 0)
                {
                    process.Order.OrderStatusID = (int)OrderStatusEnum.Invoiced;
                    _currentDbContext.SaveChanges();
                }
            }

            SaveAccountTransaction(accountTransaction, tenantId, userId);
            return(invoice);
        }
Exemplo n.º 39
0
        public IActionResult Invoice()


        {
            var InvoiceType     = _context.InvoiceType.ToList();
            var InvoiceTypeList = new List <SelectListItem>();

            foreach (var item in InvoiceType)
            {
                InvoiceTypeList.Add(new SelectListItem {
                    Value = item.Id.ToString(), Text = item.Type.ToString()
                });
            }
            ViewBag.InvoiceType = InvoiceTypeList;

            var model   = new InvoiceViewModel();
            var joblist = _context.Jobs.Where(x => x.Status == "Done").ToList();

            foreach (var p in joblist)
            {
                model.jobs.Add(new iJobs {
                    Job = p.Job, Id = p.Id, JobRate = p.JobRate
                });
            }

            var tasklist = _context.Tasks.Where(x => x.Status == "Done").ToList();

            foreach (var t in tasklist)
            {
                model.tasks.Add(new iTasks {
                    Task = t.Task, Id = t.Id, TasksRate = t.TasksRate
                });
            }

            var BusVallist = _context.BusinessValues.ToList();

            foreach (var b in BusVallist)
            {
                model.businessValues.Add(new iBusinessValues {
                    Business = b.Business, Id = b.Id, Rate = b.Rate
                });
            }

            var userlist = _context.Users.ToList();

            foreach (var u in userlist)
            {
                model.user.Add(new iUser {
                    Id = u.Id, UserName = u.UserName, Rate = u.Rate
                });
            }


            List <InvoiceType> invoices = new List <InvoiceType>();

            invoices = (from Type in _context.InvoiceType
                        select Type).ToList();
            invoices.Insert(0, new InvoiceType {
                Id = 0, Type = "Select"
            });
            ViewBag.InvoiceType = invoices;


            return(View(model));
        }
Exemplo n.º 40
0
        // GET: Invoice/Delete/5
        public async Task <ActionResult> Delete(int id)
        {
            InvoiceViewModel invoice = await ApiService <InvoiceViewModel> .GetApi($"/api/invoice/get/{id}", User.Identity.Name);

            return(View(invoice));
        }
Exemplo n.º 41
0
 public Window_InvoiceList()
 {
     InitializeComponent();
     _InvoiceViewModel = new InvoiceViewModel();
     this.DataContext  = _InvoiceViewModel;
 }
        public void UpdateInvoice(InvoiceViewModel invoice, List<InvoiceDetailViewModel> invoiceDetails, int userId)
        {
            using(var trans = _unitOfWork.BeginTransaction())
            {
                try
                {
                    DateTime serverTime = DateTime.Now;

                    Invoice entity = _invoiceRepository.GetById<int>(invoice.Id);
                    entity.PaymentMethodId = invoice.PaymentMethodId;
                    entity.TotalHasPaid = invoice.TotalHasPaid;
                    entity.TotalPrice = invoice.TotalPrice;

                    entity.TotalService = invoice.TotalService;
                    entity.TotalFeeService = invoice.TotalFeeService;
                    entity.TotalServicePlusFee = invoice.TotalServicePlusFee;
                    entity.TotalSparepart = invoice.TotalSparepart;
                    entity.TotalFeeSparepart = invoice.TotalFeeSparepart;
                    entity.TotalSparepartPlusFee = invoice.TotalSparepartPlusFee;
                    entity.TotalSparepartAndService = invoice.TotalSparepartAndService;
                    entity.TotalValueAdded = invoice.TotalValueAdded;

                    //Map(invoice, entity);
                    entity.ModifyDate = serverTime;
                    entity.ModifyUserId = userId;
                    entity.Status = (int)DbConstant.InvoiceStatus.NotPrinted;

                    if (entity.TotalHasPaid == entity.TotalPrice)
                    {
                        entity.PaymentStatus = (int)DbConstant.PaymentStatus.Settled;
                    }
                    else
                    {
                        entity.PaymentStatus = (int)DbConstant.PaymentStatus.NotSettled;
                    }

                    _invoiceRepository.AttachNavigation(entity.CreateUser); // yang inherit ke base modifier harus ada ini, klo gak user e dobel2
                    _invoiceRepository.AttachNavigation(entity.ModifyUser); // yang inherit ke base modifier harus ada ini, klo gak user e dobel2
                    _invoiceRepository.AttachNavigation(entity.SPK);
                    _invoiceRepository.AttachNavigation(entity.PaymentMethod);

                    _invoiceRepository.Update(entity);
                    _unitOfWork.SaveChanges();

                    foreach (var invoiceDetail in invoiceDetails)
                    {
                        InvoiceDetail entityDetail = _invoiceDetailRepository.GetById<int>(invoiceDetail.Id);
                        entityDetail.FeePctg = invoiceDetail.FeePctg;
                        entityDetail.SubTotalPrice = invoiceDetail.SubTotalPrice;
                        //Map(invoiceDetail, entityDetail);

                        entityDetail.ModifyDate = serverTime;
                        entityDetail.ModifyUserId = userId;

                        _invoiceDetailRepository.AttachNavigation(entityDetail.CreateUser);
                        _invoiceDetailRepository.AttachNavigation(entityDetail.ModifyUser);
                        _invoiceDetailRepository.AttachNavigation(entityDetail.Invoice);
                        _invoiceDetailRepository.AttachNavigation(entityDetail.SPKDetailSparepartDetail);
                        _invoiceDetailRepository.Update(entityDetail);
                    }
                    _unitOfWork.SaveChanges();

                    Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_INVOICE).FirstOrDefault();
                    Transaction transaction = _transactionRepository.GetMany(x =>x.ReferenceTableId == transactionReferenceTable.Id &&
                        x.PrimaryKeyValue == invoice.Id).OrderBy(x => x.CreateDate).FirstOrDefault();
                    Reference paymentMethod = _referenceRepository.GetById(invoice.PaymentMethodId);

                    if (transaction != null)
                    {
                        transaction.ModifyDate = serverTime;
                        transaction.ModifyUserId = userId;
                        transaction.TotalTransaction = invoice.TotalPrice.AsDouble();
                        transaction.TotalPayment = invoice.TotalHasPaid.AsDouble();
                        transaction.PaymentMethodId = invoice.PaymentMethodId;
                        _transactionRepository.AttachNavigation(transaction.CreateUser);
                        _transactionRepository.AttachNavigation(transaction.ModifyUser);
                        _transactionRepository.AttachNavigation(transaction.ReferenceTable);
                        _transactionRepository.AttachNavigation(transaction.PaymentMethod);
                        _transactionRepository.Update(transaction);
                        _unitOfWork.SaveChanges();

                        List<TransactionDetail> transactionDetails = _transactionDetailRepository.GetMany(x => x.ParentId == transaction.Id).ToList();
                        foreach (TransactionDetail transactionDetail in transactionDetails)
                        {
                            _transactionDetailRepository.Delete(transactionDetail);
                        }
                        _unitOfWork.SaveChanges();
                    }
                    else
                    {
                        transaction = new Transaction();
                        transaction.CreateDate = serverTime;
                        transaction.CreateUserId = userId;
                        transaction.ModifyDate = serverTime;
                        transaction.ModifyUserId = userId;
                        transaction.Description = "pembayaran invoice";
                        transaction.TotalTransaction = invoice.TotalPrice.AsDouble();
                        transaction.TotalPayment = invoice.TotalHasPaid.AsDouble();
                        transaction.ReferenceTableId = transactionReferenceTable.Id;
                        transaction.PrimaryKeyValue = invoice.Id;
                        transaction.TransactionDate = serverTime;
                        transaction.PaymentMethodId = invoice.PaymentMethodId;
                        transaction.Status = (int)DbConstant.DefaultDataStatus.Active;

                        _transactionRepository.AttachNavigation(transaction.CreateUser);
                        _transactionRepository.AttachNavigation(transaction.ModifyUser);
                        _transactionRepository.AttachNavigation(transaction.ReferenceTable);
                        _transactionRepository.AttachNavigation(transaction.PaymentMethod);
                        transaction = _transactionRepository.Add(transaction);
                        _unitOfWork.SaveChanges();
                    }

                    switch (paymentMethod.Code)
                    {
                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_EKONOMI:
                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_BCA1:
                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_BCA2:
                            {
                                // Bank Debet --> Karena bertmbah
                                TransactionDetail detailBank = new TransactionDetail();
                                detailBank.Debit = invoice.TotalHasPaid;
                                if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_EKONOMI)
                                {
                                    detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.01").FirstOrDefault().Id;
                                }
                                else if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_BCA1)
                                {
                                    detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.02").FirstOrDefault().Id;
                                }
                                else if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_BCA2)
                                {
                                    detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.03").FirstOrDefault().Id;
                                }
                                detailBank.ParentId = transaction.Id;

                                _transactionDetailRepository.AttachNavigation(detailBank.Journal);
                                _transactionDetailRepository.AttachNavigation(detailBank.Parent);
                                _transactionDetailRepository.Add(detailBank);
                                break;
                            }

                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_KAS:
                            // Kas Debit --> Karena bertambah
                            TransactionDetail detailKas = new TransactionDetail();
                            detailKas.Debit = invoice.TotalHasPaid;
                            detailKas.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.01.01").FirstOrDefault().Id;
                            detailKas.ParentId = transaction.Id;

                            _transactionDetailRepository.AttachNavigation(detailKas.Journal);
                            _transactionDetailRepository.AttachNavigation(detailKas.Parent);
                            _transactionDetailRepository.Add(detailKas);
                            break;

                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_KAS:
                            // Kas Debit --> Karena bertambah
                            TransactionDetail detailKasKarenaUangMuka = new TransactionDetail();
                            detailKasKarenaUangMuka.Debit = invoice.TotalHasPaid;
                            detailKasKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.01.01").FirstOrDefault().Id;
                            detailKasKarenaUangMuka.ParentId = transaction.Id;

                            _transactionDetailRepository.AttachNavigation(detailKasKarenaUangMuka.Journal);
                            _transactionDetailRepository.AttachNavigation(detailKasKarenaUangMuka.Parent);
                            _transactionDetailRepository.Add(detailKasKarenaUangMuka);

                            // Uang Muka Debit --> Karena bertambah
                            TransactionDetail detailUangMukaBertambahKarenaKas = new TransactionDetail();
                            detailUangMukaBertambahKarenaKas.Debit = invoice.TotalHasPaid;
                            detailUangMukaBertambahKarenaKas.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.05.01.01").FirstOrDefault().Id;
                            detailUangMukaBertambahKarenaKas.ParentId = transaction.Id;

                            _transactionDetailRepository.AttachNavigation(detailUangMukaBertambahKarenaKas.Journal);
                            _transactionDetailRepository.AttachNavigation(detailUangMukaBertambahKarenaKas.Parent);
                            _transactionDetailRepository.Add(detailUangMukaBertambahKarenaKas);

                            // Uang Muka Kredit --> Karena berkurang
                            TransactionDetail detailUangMukaBerkurangKarenaKas = new TransactionDetail();
                            detailUangMukaBerkurangKarenaKas.Credit = invoice.TotalHasPaid;
                            detailUangMukaBerkurangKarenaKas.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.05.01.01").FirstOrDefault().Id;
                            detailUangMukaBerkurangKarenaKas.ParentId = transaction.Id;

                            _transactionDetailRepository.AttachNavigation(detailUangMukaBerkurangKarenaKas.Journal);
                            _transactionDetailRepository.AttachNavigation(detailUangMukaBerkurangKarenaKas.Parent);
                            _transactionDetailRepository.Add(detailUangMukaBerkurangKarenaKas);
                            break;

                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_EKONOMI:
                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA1:
                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA2:
                            {
                                // Bank Debit --> Karena bertambah
                                TransactionDetail detailBankKarenaUangMuka = new TransactionDetail();
                                detailBankKarenaUangMuka.Debit = invoice.TotalHasPaid;
                                if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_EKONOMI)
                                {
                                    detailBankKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.01").FirstOrDefault().Id;
                                }
                                else if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA1)
                                {
                                    detailBankKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.02").FirstOrDefault().Id;
                                }
                                else if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA2)
                                {
                                    detailBankKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.03").FirstOrDefault().Id;
                                }
                                detailBankKarenaUangMuka.ParentId = transaction.Id;

                                _transactionDetailRepository.AttachNavigation(detailBankKarenaUangMuka.Journal);
                                _transactionDetailRepository.AttachNavigation(detailBankKarenaUangMuka.Parent);
                                _transactionDetailRepository.Add(detailBankKarenaUangMuka);

                                // Uang Muka Debit --> Karena bertambah
                                TransactionDetail detailUangMukaBertambahKarenaBank = new TransactionDetail();
                                detailUangMukaBertambahKarenaBank.Debit = invoice.TotalHasPaid;
                                detailUangMukaBertambahKarenaBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.05.01.01").FirstOrDefault().Id;
                                detailUangMukaBertambahKarenaBank.ParentId = transaction.Id;

                                _transactionDetailRepository.AttachNavigation(detailUangMukaBertambahKarenaBank.Journal);
                                _transactionDetailRepository.AttachNavigation(detailUangMukaBertambahKarenaBank.Parent);
                                _transactionDetailRepository.Add(detailUangMukaBertambahKarenaBank);

                                // Uang Muka Kredit --> Karena berkurang
                                TransactionDetail detailUangMukaBerkurangKarenaBank = new TransactionDetail();
                                detailUangMukaBerkurangKarenaBank.Credit = invoice.TotalHasPaid;
                                detailUangMukaBerkurangKarenaBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.05.01.01").FirstOrDefault().Id;
                                detailUangMukaBerkurangKarenaBank.ParentId = transaction.Id;

                                _transactionDetailRepository.AttachNavigation(detailUangMukaBerkurangKarenaBank.Journal);
                                _transactionDetailRepository.AttachNavigation(detailUangMukaBerkurangKarenaBank.Parent);
                                _transactionDetailRepository.Add(detailUangMukaBerkurangKarenaBank);
                                break;
                            }

                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_PIUTANG:
                            TransactionDetail piutang = new TransactionDetail();
                            piutang.Debit = invoice.TotalPrice - invoice.TotalHasPaid;
                            piutang.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.03.01.01").FirstOrDefault().Id;
                            piutang.ParentId = transaction.Id;

                            _transactionDetailRepository.AttachNavigation(piutang.Journal);
                            _transactionDetailRepository.AttachNavigation(piutang.Parent);
                            _transactionDetailRepository.Add(piutang);
                            break;
                    }

                    if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_EKONOMI ||
                        paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA1 ||
                        paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA2 ||
                       paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_KAS)
                    {
                        if (invoice.TotalPrice > invoice.TotalHasPaid)
                        {
                            // Piutang Debit --> Karena bertambah
                            TransactionDetail piutang = new TransactionDetail();
                            piutang.Debit = invoice.TotalPrice - invoice.TotalHasPaid;
                            piutang.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.03.01.01").FirstOrDefault().Id;
                            piutang.Parent = transaction;

                            _transactionDetailRepository.AttachNavigation(piutang.Journal);
                            _transactionDetailRepository.AttachNavigation(piutang.Parent);
                            _transactionDetailRepository.Add(piutang);
                        }
                    }

                    // Sales Kredit --> Karena berkurang
                    TransactionDetail sales = new TransactionDetail();
                    sales.Credit = invoice.TotalSparepartAndService;
                    sales.JournalId = _journalMasterRepository.GetMany(j => j.Code == "3.01.01").FirstOrDefault().Id;
                    sales.ParentId = transaction.Id;

                    _transactionDetailRepository.AttachNavigation(sales.Journal);
                    _transactionDetailRepository.AttachNavigation(sales.Parent);
                    _transactionDetailRepository.Add(sales);

                    // Service Income Kredit --> Karena berkurang
                    TransactionDetail serviceIncome = new TransactionDetail();
                    serviceIncome.Credit = invoice.TotalValueAdded + invoice.TotalFeeSparepart;
                    serviceIncome.JournalId = _journalMasterRepository.GetMany(j => j.Code == "3.01.04").FirstOrDefault().Id;
                    serviceIncome.ParentId = transaction.Id;

                    _transactionDetailRepository.AttachNavigation(serviceIncome.Journal);
                    _transactionDetailRepository.AttachNavigation(serviceIncome.Parent);
                    _transactionDetailRepository.Add(serviceIncome);

                    // HPP Sparepart Debit --> Karena bertambah
                    TransactionDetail hppSparepart = new TransactionDetail();
                    hppSparepart.Debit = invoice.TotalSparepartPlusFee;
                    hppSparepart.JournalId = _journalMasterRepository.GetMany(j => j.Code == "3.04.01").FirstOrDefault().Id;
                    hppSparepart.ParentId = transaction.Id;

                    _transactionDetailRepository.AttachNavigation(hppSparepart.Journal);
                    _transactionDetailRepository.AttachNavigation(hppSparepart.Parent);
                    _transactionDetailRepository.Add(hppSparepart);

                    if(invoice.TotalServicePlusFee > 0)
                    {
                        if (entity.SPK.isContractWork)
                        {
                            // HPP Tukang Harian Debit --> Karena bertambah
                            TransactionDetail hppTukang = new TransactionDetail();
                            hppTukang.Debit = invoice.TotalServicePlusFee;
                            hppTukang.JournalId = _journalMasterRepository.GetMany(j => j.Code == "3.04.05").FirstOrDefault().Id;
                            hppTukang.ParentId = transaction.Id;

                            _transactionDetailRepository.AttachNavigation(hppTukang.Journal);
                            _transactionDetailRepository.AttachNavigation(hppTukang.Parent);
                            _transactionDetailRepository.Add(hppTukang);
                        }
                        else
                        {
                            // HPP Tukang Borongan Debit --> Karena bertambah
                            TransactionDetail hppTukang = new TransactionDetail();
                            hppTukang.Debit = invoice.TotalServicePlusFee;
                            hppTukang.JournalId = _journalMasterRepository.GetMany(j => j.Code == "3.04.04").FirstOrDefault().Id;
                            hppTukang.ParentId = transaction.Id;

                            _transactionDetailRepository.AttachNavigation(hppTukang.Journal);
                            _transactionDetailRepository.AttachNavigation(hppTukang.Parent);
                            _transactionDetailRepository.Add(hppTukang);
                        }
                    }

                    // Sparepart Kredit --> Karena berkurang
                    TransactionDetail detailSparepart = new TransactionDetail();
                    detailSparepart.Credit = invoice.TotalSparepart;
                    detailSparepart.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.04.01").FirstOrDefault().Id;
                    detailSparepart.ParentId = transaction.Id;

                    _transactionDetailRepository.AttachNavigation(detailSparepart.Journal);
                    _transactionDetailRepository.AttachNavigation(detailSparepart.Parent);
                    _transactionDetailRepository.Add(detailSparepart);

                    if (invoice.TotalServicePlusFee > 0)
                    {
                        // SDM Kredit --> Karena berkurang
                        TransactionDetail detailSDM = new TransactionDetail();
                        detailSDM.Credit = invoice.TotalServicePlusFee;
                        detailSDM.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.04.04").FirstOrDefault().Id;
                        detailSDM.ParentId = transaction.Id;

                        _transactionDetailRepository.AttachNavigation(detailSDM.Journal);
                        _transactionDetailRepository.AttachNavigation(detailSDM.Parent);
                        _transactionDetailRepository.Add(detailSDM);
                    }

                    _unitOfWork.SaveChanges();

                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }