Ejemplo n.º 1
0
        /// <summary>
        /// Metodo que dada una entidad devuelve su DTO
        /// </summary>
        /// <param name="entity">Entidad de la cual se requiere el DTO</param>
        /// <returns>DTO para la entidad pasada por parametro</returns>
        private InvoiceDTO GetDTO(Invoice entity)
        {
            InvoiceDTO dto = new InvoiceDTO();

            dto.InvoiceId = entity.InvoiceId;
            this.SetDTOExtras(entity, ref dto);

            return(dto);
        }
Ejemplo n.º 2
0
        protected void btnLuu_Click(object sender, EventArgs e)
        {
            InvoiceDTO invdto = new InvoiceDTO();

            invdto.MaClaim    = txtId_claim.Text;
            invdto.NoInvoice  = txtInvoice.Text;
            invdto.GrandTotal = float.Parse(txtTongTien.Text);
            invdto.DateIssue  = DateTime.Parse(txtIssueDate.Text);
            bool kq = inv.Insert(invdto);

            if (kq == true)
            {
                IncomeDTO idto = new IncomeDTO();
                //int idgdv = int.Parse(drDSGDV.SelectedItem.Value.ToString());
                int idgdv = 0;

                //idto.MaGDV = 0;
                string thamchieu = txtId_claim.Text;
                //bool kttrung = idao.KiemTraTrung(thamchieu, idgdv);
                DataTable     dt     = ts.ListIDGDV(thamchieu);
                List <string> ListID = new List <string>();
                if (dt.Rows.Count > 0)
                {
                    //foreach (DataRow dr in dt.Rows)
                    for (int t = 0; t < dt.Rows.Count; t++)
                    {
                        ListID.Add(dt.Rows[t][0].ToString());
                    }
                }
                //int maLA = int.Parse(ListID[0].ToString());

                //foreach (DataRow ID_GDV in ListID)
                for (int i = 0; i < ListID.Count; i++)
                {
                    //Response.Write("<script>alert('" + ListID[i].ToString()+ "');</script>");
                    idgdv      = int.Parse(ListID[i].ToString());
                    idto.MaGDV = idgdv;
                    int maInvoice = inv.SelectMaMax();
                    idto.MaInvoice = maInvoice;
                    idto.MaClaim   = thamchieu;
                    float feeissue = float.Parse(txtIssueFee.Text);
                    idto.IssueFee = feeissue;
                    float feereal = float.Parse(txtRealfee.Text);
                    idto.RealFee = feereal;
                    float percentage = feereal / feeissue;
                    idto.Percentage = percentage;
                    float magicincome = ts.CyberIncomeGDV(thamchieu, idgdv);
                    idto.CyberIncome = magicincome;
                    float realincome = percentage * magicincome / 4;
                    idto.RealIncome = realincome;
                    bool them = ic.Insert(idto);
                }
                Session["ThamChieu"] = thamchieu;
                Response.Redirect("~/Pages/detailincome.aspx");
            }
        }
        public void UpdateInvoice(InvoiceDTO invoiceDTO)
        {
            Invoice invoice = _mapper.Mapper().Map <Invoice>(invoiceDTO);

            invoice.CustomerId = invoiceDTO.CustomerDTOId;
            invoice.Customer   = _customerRepository.GetById(invoice.CustomerId);

            _invoiceRepository.UpdateEntity(invoice);
            _invoiceRepository.Save();
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Servicio que permite insertar una nueva entidad: Invoice (Invoice)
 /// </summary>
 /// <param name="entity">DTO de la entidad a insertar</param>
 /// <param name="user">Usuario que ejecuta la inserción</param>
 /// <returns>Se devulve el DTO de la entidad creada con el id asignado</returns>
 public InvoiceDTO Insert(InvoiceDTO dto, string user)
 {
     using (var dbContextScope = new TiendaDbContext())
     {
         Invoice entity = GetEntity(dto);
         entity = _repository.Insert(entity, user);
         dbContextScope.SaveChanges();
         return(GetDTO(entity));
     }
 }
Ejemplo n.º 5
0
        public async Task NewInvoice_IfCartExists()
        {
            //проверяем создание нового счета
            InvoiceDTO invoiceDTO = await _invoicesService.ByUserID(1);

            Assert.IsTrue(invoiceDTO.InvoiceID > 0);
            Assert.AreNotEqual(DateTime.MinValue, invoiceDTO.CreatedAt);
            Assert.IsTrue(invoiceDTO.CountOfCommodities > 0);
            Assert.IsTrue(invoiceDTO.Total > 0);
        }
Ejemplo n.º 6
0
        public IHttpActionResult CreateInvoice(InvoiceDTO invoiceDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            _invoiceLogic.Create(invoiceDto);
            return(Created(new Uri(Request.RequestUri + "/" + invoiceDto.Id), invoiceDto));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Check exist before manipulate data. If found record will update data. Otherwise insert new data.
        /// </summary>
        /// <param name="database"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public int AddNewOrUpdate(Database database, InvoiceDTO data)
        {
            Database db = UseDatabase(database);

            if (Exist(database, data.TRANS_ID))
            {
                return(UpdateWithoutPK(db, data));
            }

            return(AddNew(db, data));
        }
Ejemplo n.º 8
0
        public async Task <ServiceResponse> CreateInvoice(InvoiceDTO bill)
        {
            //Get customer by Customer Id
            var customer = await _customerRepository.GetById(bill.CustomerId);

            if (customer == null)
            {
                return new ServiceResponse {
                           Successful = false, Message = "Customer ID is invalid"
                }
            }
            ;
            //Get total amount of bill
            var totalAmount = CalculateInvoiceTotal(bill.Items);
            //exclude any item price with itemType of Groceries
            var totaAmountWithoutGroceries = CalculateInvoiceTotal(bill.Items.Where(s => s.ItemType.ToLower() != "groceries").ToList());
            //Caculate discount
            var discountAmount = await _invoiceDomainService.CalculateDiscount(totalAmount, totaAmountWithoutGroceries, customer.Role, customer.DateRegistered);

            //Save invoice to db
            var invoiceItems = new List <InvoiceItem>();

            foreach (var item in bill.Items)
            {
                invoiceItems.Add(new InvoiceItem
                {
                    Category    = item.ItemType,
                    Description = item.ItemDescription,
                    UnitPrice   = item.UnitPrice,
                    Units       = item.Quantity,
                });
            }
            var invoice = new Invoice
            {
                InvoiceDate    = DateTime.Now,
                TotalAmount    = totalAmount,
                DiscountAmount = discountAmount,
                CustomerId     = bill.CustomerId,
                InvoiceItems   = invoiceItems
            };
            await _unitOfWork.InvoiceRepository.Insert(invoice);

            _unitOfWork.Commit();
            bill.InvoiceDate     = invoice.InvoiceDate;
            bill.InvoiceId       = invoice.Id;
            bill.TotalAmount     = invoice.TotalAmount;
            bill.DiscountAmount  = invoice.DiscountAmount;
            bill.Customer        = customer.Name;
            bill.ShippingAddress = customer.Address;

            return(new ServiceResponse {
                Successful = true, Id = invoice.Id, Message = bill
            });
        }
        public decimal GetTotalPrice(InvoiceDTO invoiceDTO)
        {
            decimal totalPrice = 0;
            List <DetailLineDTO> detailLineDTOs = _detailLineService.GetAllDetailLines().Where(d => d.InvoiceDTOId == invoiceDTO.InvoiceId).ToList();

            foreach (var item in detailLineDTOs)
            {
                totalPrice += item.TotalPriceWithDiscountAndVat;
            }
            return(totalPrice);
        }
Ejemplo n.º 10
0
        public async Task <InvoiceDTO> Get(string invoiceId)
        {
            InvoiceDTO invoiceDTO = null;
            Invoice    invoice    = await _invoiceData.Get(invoiceId);

            if (invoice != null)
            {
                invoiceDTO = _mapper.Map <Invoice, InvoiceDTO>(invoice);
            }
            return(invoiceDTO);
        }
Ejemplo n.º 11
0
        //public InvoiceService()//Just for messing about with SpecFlow
        //{
        //}

        public void PostInvoiceDTO(InvoiceDTO dto, int customerId, int productId)
        {
            CustomerDTO customerDTO = _customerService.ReturnCustomerByIdOld(customerId);
            ProductDTO  productDTO  = _productService.ReturnProductById(productId);

            //So would the tax calculation go here??
            dto = EFCorePoC.Helpers.TaxService.calculateTotalNet(dto);
            dto = EFCorePoC.Helpers.TaxService.calculateTax(dto);
            dto = EFCorePoC.Helpers.TaxService.calculateTotalGross(dto);

            _repository.PostInvoice(dto.ConvertDTOToInvoice(dto, customerDTO, productDTO));
        }
Ejemplo n.º 12
0
        void ReplaceStrings()
        {
            ContractDTO contract = MainForm.DB.Contracts.Get(MainForm.DB.Invoices.Get((lBDeliveryNotes.SelectedItem as DeliveryNoteDTO).InvoiceId).ContractId);
            InvoiceDTO  invoice  = MainForm.DB.Invoices.Get((lBDeliveryNotes.SelectedItem as DeliveryNoteDTO).InvoiceId);

            WordWorker.FindReplace("{dateNakl}", dTPData.Value.ToShortDateString());
            WordWorker.FindReplace("{contractName}", contract.ToString());
            WordWorker.FindReplace("{invoiceName}", invoice.ToString());
            WordWorker.FindReplace("{numberNakl}", tBNumber.Text.ToString());
            WordWorker.FindReplace("{nameCompanySeller}", MainForm.DB.Sellers.Get(contract.SellerId).NameCompany);
            WordWorker.FindReplace("{nameCompanyCustomer}", MainForm.DB.Customers.Get(contract.CustomerId).NameCompany);
            WordWorker.FindReplace("{fullNameCompanySeller}", MainForm.DB.Sellers.Get(contract.SellerId).FullNameCompany);
            WordWorker.FindReplace("{fullNameCompanyCustomer}", MainForm.DB.Customers.Get(contract.CustomerId).FullNameCompany);
            WordWorker.FindReplace("{nameSeller}", MainForm.DB.Sellers.Get(contract.SellerId).NameSeller);
            WordWorker.FindReplace("{addressCustomer}", MainForm.DB.Customers.Get(contract.CustomerId).AddressCompany);
            WordWorker.FindReplace("{addressSeller}", MainForm.DB.Sellers.Get(contract.SellerId).AddressCompany);
            WordWorker.FindReplace("{innCustomer}", MainForm.DB.Customers.Get(contract.CustomerId).INN.ToString());
            WordWorker.FindReplace("{innSeller}", MainForm.DB.Sellers.Get(contract.SellerId).INN.ToString());
            WordWorker.FindReplace("{kppCustomer}", MainForm.DB.Customers.Get(contract.CustomerId).KPP.ToString());
            WordWorker.FindReplace("{kppSeller}", MainForm.DB.Sellers.Get(contract.SellerId).KPP.ToString());
            WordWorker.FindReplace("{personalAccountCustomer}", MainForm.DB.Customers.Get(contract.CustomerId).PersonalAccount);
            WordWorker.FindReplace("{corespAccountSeller}", MainForm.DB.Sellers.Get(contract.SellerId).CorrespondentAccount);
            WordWorker.FindReplace("{bikCustomer}", MainForm.DB.Customers.Get(contract.CustomerId).BIK.ToString());
            WordWorker.FindReplace("{bikSeller}", MainForm.DB.Sellers.Get(contract.SellerId).BIK.ToString());
            WordWorker.FindReplace("{bikCustomer}", MainForm.DB.Customers.Get(contract.CustomerId).BIK.ToString());
            WordWorker.FindReplace("{bankCustomer}", MainForm.DB.Customers.Get(contract.CustomerId).Bank);
            WordWorker.FindReplace("{bankSeller}", MainForm.DB.Sellers.Get(contract.SellerId).Bank);
            WordWorker.FindReplace("{bankAccountCustomer}", MainForm.DB.Customers.Get(contract.CustomerId).BankAccount);
            WordWorker.FindReplace("{bankAccountSeller}", MainForm.DB.Sellers.Get(contract.SellerId).BankAccount);
            WordWorker.FindReplace("{priemName}", tBPriemName.Text);
            WordWorker.FindReplace("{gruzName}", tBGruzName.Text);

            string replacedOfWord = WordWorker.ReplaceOfWord(float.Parse(lSumm.Text));

            if (lSumm.Text.Contains(','))
            {
                if (lSumm.Text.Substring(lSumm.Text.IndexOf(',')).Length - 1 == 2)
                {
                    WordWorker.FindReplace("{total}", replacedOfWord.Remove(replacedOfWord.Length - 1));
                    WordWorker.FindReplace("{kopeiki}", lSumm.Text.Substring(lSumm.Text.IndexOf(',') + 1));
                }
                else
                {
                    WordWorker.FindReplace("{total}", replacedOfWord.Remove(replacedOfWord.Length - 1));
                    WordWorker.FindReplace("{kopeiki}", lSumm.Text.Substring(lSumm.Text.IndexOf(',') + 1) + "0");
                }
            }
            else
            {
                WordWorker.FindReplace("{total}", replacedOfWord.Remove(replacedOfWord.Length - 1));
                WordWorker.FindReplace("{kopeiki}", "00");
            }
        }
        public byte[] CreateInvoice(int?invoiceId)
        {
            InvoiceDTO invoiceDTO = GetInvoiceById(invoiceId);

            HtmlToPdf   converter = new HtmlToPdf();
            PdfDocument document  = converter.ConvertHtmlString(GetInvoiceTemplate(invoiceDTO));

            byte[] doc = document.Save();
            document.Close();

            return(doc);
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Edit(int id, InvoiceDTO invoiceDto)
        {
            if (id != invoiceDto.InvoiceId)
            {
                return(NotFound());
            }

            var invoice = await _context.Invoices.FindAsync(invoiceDto.InvoiceId);

            if (invoice == null)
            {
                return(NotFound());
            }

            var client = await _context.Clients.FindAsync(invoiceDto.ClientId);

            if (client == null)
            {
                return(NotFound());
            }

            var stock = await _context.Stocks.FindAsync(invoiceDto.StockId);

            if (stock == null)
            {
                return(NotFound());
            }
            invoice.Client = client;
            invoice.Stock  = stock;
            invoice.Count  = invoiceDto.Count;

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(invoice);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!InvoiceExists(invoice.InvoiceId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(invoice));
        }
Ejemplo n.º 15
0
        public static Invoice DtoToInvoice(InvoiceDTO dto)
        {
            var invoice = new Invoice
            {
                Id            = 0,
                GeneratedDate = DateTime.Today,
                FileArray     = Array.Empty <byte>(),
                TimesheetId   = dto.TimesheetId
            };

            return(invoice);
        }
Ejemplo n.º 16
0
        public ActionResult <InvoiceDTO> GetInvoice(int invoiceId)
        {
            string userId = User?.Identity?.Name;

            if (string.IsNullOrEmpty(userId))
            {
                return(Forbid());
            }

            InvoiceDTO invoice = new InvoiceDTO(InvoiceService.GetInvoice(invoiceId));

            return(Ok(invoice));
        }
Ejemplo n.º 17
0
        public async Task <ActionResult <InvoiceDTO> > PostInvoice(InvoiceDTO invoiceDTO)
        {
            invoiceDTO.AppUserId = User.UserGuidId();

            var bllEntity = _mapper.Map(invoiceDTO);

            _bll.Invoices.Add(bllEntity);
            await _bll.SaveChangesAsync();

            invoiceDTO.Id = bllEntity.Id;

            return(CreatedAtAction("GetInvoice", new { id = invoiceDTO.Id, version = HttpContext.GetRequestedApiVersion()?.ToString() ?? "0" }, invoiceDTO));
        }
        public void AddInvoice(InvoiceDTO invoiceDTO)
        {
            Invoice invoice = _mapper.Mapper().Map <Invoice>(invoiceDTO);

            invoice.IsDeleted  = false;
            invoice.IsFinished = false;

            invoice.CustomerId = invoiceDTO.CustomerDTOId;
            invoice.Customer   = _customerRepository.GetById(invoice.CustomerId);

            _invoiceRepository.InsertEntity(invoice);
            _invoiceRepository.Save();
        }
Ejemplo n.º 19
0
 public Invoice Transform(InvoiceDTO dto)
 {
     if (dto == null)
     {
         return(null);
     }
     return(new Invoice
     {
         InvoiceNr = dto.InvoiceNr,
         InvoiceDate = dto.InvoiceDate,
         InvoiceSum = dto.InvoiceSum,
         InvoiceTax = dto.InvoiceTax
     });
 }
Ejemplo n.º 20
0
        private InvoiceDTO CreateMockInvoiceDTO()
        {
            var invoiceDto = new InvoiceDTO()
            {
                GeneratedDate   = _sampleDate,
                Id              = 1,
                TimesheetId     = 1,
                InvoiceForMonth = "2",
                InvoiceForYear  = "2020",
                InvoiceNumber   = "20/01/2020"
            };

            return(invoiceDto);
        }
Ejemplo n.º 21
0
        public async Task <ActionResult> Post([FromBody] InvoiceDTO bill)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var result = await _invoiceService.CreateInvoice(bill);

            if (!result.Successful)
            {
                return(BadRequest(result.Message));
            }
            return(CreatedAtAction(nameof(GetById), new { id = result.Id }, result.Message));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Generate the mail containing invoice information
        /// send the mail to the user
        /// </summary>
        /// <param name="invoice"></param>
        private void MailSender(InvoiceDTO invoice)
        {
            string email = this.Session["Email"].ToString();

            if (email != null)
            {
                //Mail sending procedure
                //Body creation
                AccountBL  accountBL = new AccountBL();
                AccountDTO customer  = accountBL.GetCustomer(email);
                List <ProductSelectionDTO> products = (List <ProductSelectionDTO>)(this.Session["Cart"]);

                //Introduction
                string body = "Hi, " + customer.GetFirstName() + " " + customer.GetLastName() + ",\n\nHere your order of " + invoice.GetOrderDate().ToString("dd/MM/yyyy") + " :\n\n";

                //List of product
                foreach (ProductSelectionDTO p in products)
                {
                    body += p.GetQuantity() + " " + p.GetProduct().GetName() + " " + p.GetOrigSize() + " at " + p.GetOrigPrice() + "/Unit\n";
                }
                //Invoice costs
                body += "\nShipping cost :" + invoice.GetShippingCost() + "AUS$\nTax : " + invoice.GetTax() + "%\nTotal Amount : " + invoice.GetTotal() + " AUS$\nEstimate arrival date : " + invoice.GetArrivalDate().ToString("dd/MM/yyyy");
                body += "\n\nThank you for your confidence.\nHope to see you soon on LaitBrasseur.com !";

                //Message creation (To / From/ link to verification)
                MailMessage mm = new MailMessage();
                mm.To.Add(new MailAddress(email));
                mm.From = new MailAddress("*****@*****.**");
                mm.Body = body;

                mm.IsBodyHtml = false;
                mm.Subject    = "Your order " + invoice.GetOrderDate().ToString("dd/MM/yyyy");

                //SMTP client initialization (gmail with projet address)
                SmtpClient smcl = new SmtpClient();
                smcl.Host        = "smtp.gmail.com";
                smcl.Port        = 587;
                smcl.Credentials = new NetworkCredential("*****@*****.**", "clementjanina");
                smcl.EnableSsl   = true;
                smcl.Send(mm);

                //Feedback
                lblResult.CssClass = "text-success";
                lblResult.Text    += "A confirmation email has been sent.";
            }
            else
            {
                lblResult.Text = "There is a problem with your email.";
            }
        }
Ejemplo n.º 23
0
 public ActionResult Edit(InvoiceDTO invoice)
 {
     try
     {
         if (!invoice.InvoiceStatus.Equals(StatusDTO.Completed))
         {
             mgr.ChangeInvoice(invoice);
         }
         return(RedirectToAction("Index"));
     }
     catch
     {
         return(View());
     }
 }
Ejemplo n.º 24
0
        public static InvoiceDTO calculateTax(InvoiceDTO dto)
        {
            if (dto.Quantity != 0)
            {
                decimal quantity = dto.Quantity;
                decimal taxCalc  = dto.ItemNet * (dto.TaxRate / 100);
                dto.TotalTax = quantity * taxCalc;
            }
            else
            {
                dto.TotalTax = dto.TotalNet * (dto.TaxRate / 100);
            }

            return(dto);
        }
Ejemplo n.º 25
0
        public IList <InvoiceDTO> GetClientInvoices(string pCardCode, string pDocStatus = "%")
        {
            SAPbobsCOM.Recordset lObjResults     = (SAPbobsCOM.Recordset)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            IList <InvoiceDTO>   lLstObjInvoices = new List <InvoiceDTO>();

            try
            {
                string lStrQuery = this.GetSQL("GetClientInvoices").InjectSingleValue("CardCode", pCardCode).InjectSingleValue("DocStatus", pDocStatus);
                lObjResults.DoQuery(lStrQuery);
                if (lObjResults.RecordCount > 0)
                {
                    for (int i = 0; i < lObjResults.RecordCount; i++)
                    {
                        //lObjResults.GetColumnValue<int>("CheckKey");
                        InvoiceDTO lObjInvoiceDTO = new InvoiceDTO();
                        lObjInvoiceDTO.DocStatus    = lObjResults.GetColumnValue <string>("DocStatus");
                        lObjInvoiceDTO.DocNum       = lObjResults.GetColumnValue <int>("DocNum");
                        lObjInvoiceDTO.Series       = lObjResults.GetColumnValue <int>("Series");
                        lObjInvoiceDTO.SeriesName   = lObjResults.GetColumnValue <string>("SeriesName");
                        lObjInvoiceDTO.DocNum       = lObjResults.GetColumnValue <int>("DocNum");
                        lObjInvoiceDTO.DocEntry     = lObjResults.GetColumnValue <int>("DocEntry");
                        lObjInvoiceDTO.TransId      = lObjResults.GetColumnValue <int>("TransId");
                        lObjInvoiceDTO.DocDate      = lObjResults.GetColumnValue <DateTime>("DocDate");
                        lObjInvoiceDTO.DocDueDate   = lObjResults.GetColumnValue <DateTime>("DocDueDate");
                        lObjInvoiceDTO.DocCur       = lObjResults.GetColumnValue <string>("DocCur");
                        lObjInvoiceDTO.DocTotal     = lObjResults.GetColumnValue <double>("DocTotal");
                        lObjInvoiceDTO.DocTotalFC   = lObjResults.GetColumnValue <double>("DocTotalFC");
                        lObjInvoiceDTO.PaidToDate   = lObjResults.GetColumnValue <double>("PaidToDate");
                        lObjInvoiceDTO.DocRemaining = lObjResults.GetColumnValue <double>("DocRemaining");
                        lObjInvoiceDTO.CardCode     = lObjResults.GetColumnValue <string>("CardCode");
                        lObjInvoiceDTO.OcrCode      = lObjResults.GetColumnValue <string>("OcrCode");
                        lObjInvoiceDTO.ObjType      = lObjResults.GetColumnValue <string>("ObjType");
                        lLstObjInvoices.Add(lObjInvoiceDTO);
                        lObjResults.MoveNext();
                    }
                }
                return(lLstObjInvoices);
            }
            catch (Exception e)
            {
                LogUtility.WriteError(string.Format("[DocumentDAO - GetClientInvoices] Error al obtener las facturas del cliente {0}: {1}", pCardCode, e.Message));
                throw new Exception(string.Format("Error al obtener las facturas del cliente {0}: {1}", pCardCode, e.Message));
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjResults);
            }
        }
Ejemplo n.º 26
0
        public IHttpActionResult UpdateInvoice(InvoiceDTO invoiceDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var invoiceInDb = _invoiceLogic.FindByID(invoiceDto.Id);

            if (invoiceInDb == null)
            {
                return(NotFound());
            }

            return(Ok(_invoiceLogic.Update(invoiceDto)));
        }
Ejemplo n.º 27
0
        protected void btnInsert_Click(object sender, EventArgs e)
        {
            InvoiceDTO invdto = new InvoiceDTO();

            invdto.MaClaim    = txtClaimNo.Text;
            invdto.NoInvoice  = txtInvoiceNo.Text;
            invdto.GrandTotal = float.Parse(txtTotal.Text);
            invdto.DateIssue  = DateTime.Parse(txtDateIssue.Text);
            bool kq = inv.Insert(invdto);

            if (kq == true)
            {
                LoadGR();
                ClearInputs(Page.Controls);
            }
        }
Ejemplo n.º 28
0
        public void UpdateInvoice(InvoiceDTO editedInvoice)
        {
            var invoice = _mapper.Map <Invoice>(editedInvoice);
            // Aktualizacja usług na fakturze
            var editedIRSIds = editedInvoice.Services.Select(s => s.InvoiceRowServiceID);
            var services     = GetAllServices(invoice.InvoiceID);
            var irs2remove   = services.Where(s => !editedIRSIds.Contains(s.InvoiceRowServiceID)).Select(x => _mapper.Map <InvoiceRowService>(x));

            _context.Entry(invoice).State = EntityState.Modified;
            _context.SaveChanges();

            foreach (var irs in irs2remove)
            {
                DeleteInvoiceRowService(irs);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Получение информации о накладной
        /// </summary>
        /// <param name="invoiceId">Id накладной</param>
        /// <returns></returns>
        public InvoiceDTO Get(int invoiceId)
        {
            var model   = new InvoiceDTO();
            var url     = new Uri($"{this.url}/invoice/{invoiceId}");
            var request = WebRequest.Create(url);

            request.Method = "Get";
            var response = request.GetResponse();

            using (var stream = new StreamReader(response.GetResponseStream()))
            {
                var json = stream.ReadToEnd();
                model = JsonConvert.DeserializeObject <InvoiceDTO>(json);
            }
            return(model);
        }
Ejemplo n.º 30
0
        public IHttpActionResult Post([FromBody] InvoiceDTO value)
        {
            try
            {
                if (value == null)
                {
                    return(BadRequest());
                }

                string userName = null;
                if (HttpContext.Current != null && HttpContext.Current.User != null &&
                    HttpContext.Current.User.Identity.Name != null)
                {
                    userName = HttpContext.Current.User.Identity.Name;
                }

                if (value.Amount != value.InvoiceItems.Sum(it => it.Amount))
                {
                    return(BadRequest("Invocie Amount Miss Match with total Invoice Item Amount"));
                }

                if (value.GST != value.InvoiceItems.Sum(it => it.GST))
                {
                    return(BadRequest("Invocie GST Miss Match with total Invoice Item GST"));
                }

                var invoice = value.ToDomain();
                invoice.CreateUser  = userName;
                invoice.ChangeUser  = userName;
                invoice.Concurrency = Guid.NewGuid();

                _InvoiceRepo.Add(invoice);

                _uow.SaveChanges();

                if (invoice.ID > 0)
                {
                    return(Created <InvoiceDTO>(Request.RequestUri + "/" + invoice.ID, invoice.ToDTO()));
                }

                return(BadRequest());
            }
            catch (Exception ex)
            {
                return(InternalServerError());
            }
        }
Ejemplo n.º 31
0
    public InvoiceDTO getInvoiceById(string id)
    {
        Invoice i = db.Invoices.Where(p => p.InvoiceID == id).FirstOrDefault();

        // use a serialize safe object
        InvoiceDTO ix = new InvoiceDTO();
        ix.InvoiceID = i.InvoiceID;
        ix.DateCreated = i.dateCreated.ToString();
        ix.DateModified = i.dateModified.ToString();
        ix.JobStatus = i.jobStatus;
        ix.PaymentStatus = i.paymentStatus;
        ix.QuoteCode = i.Quote.quoteCode;

        // you'll need to get the person connected to the Customer
        Person pr = db.People.Where(x => x.Customer_Id == i.Customer_Id).FirstOrDefault();

        ix.CustomerName = pr.fname + " " + pr.lname;

        return ix;
    }