public bool UpdatePurchaseInvoiceHeader(PurchaseInvoiceHeader PIH)
        {
            IDBManager dbm = new DBManager();

            try
            {
                dbm.CreateParameters(12);
                dbm.AddParameters(0, "@InvoiceID", PIH.InvoiceID);
                dbm.AddParameters(1, "@InvoiceNumber", PIH.InvoiceNumber);
                dbm.AddParameters(2, "@Status", PIH.Status);
                dbm.AddParameters(3, "@EmployeeID", PIH.EmployeeID);
                dbm.AddParameters(4, "@VendorID", PIH.VendorID);
                dbm.AddParameters(5, "@InvoiceDate", PIH.InvoiceDate);
                dbm.AddParameters(6, "@SubTotal", PIH.SubTotal);
                dbm.AddParameters(7, "@TaxAmt", PIH.TaxAmt);
                dbm.AddParameters(8, "@Freight", PIH.Freight);
                dbm.AddParameters(9, "@TotalDue", PIH.TotalDue);
                dbm.AddParameters(10, "@ModifiedDate", DateTime.Now);
                dbm.AddParameters(11, "@PurchaseOrderID", PIH.PurchaseOrderID);

                dbm.ExecuteNonQuery(CommandType.StoredProcedure, "UpdatePurchaseInvoiceHeader");
            }
            catch (Exception ex)
            {
                log.Write(ex.Message, "UpdatePurchaseInvoiceHeader");
                throw (ex);
            }
            finally
            {
                dbm.Dispose();
            }
            return(true);
        }
Exemple #2
0
        private void UpdatePurchaseOrderStatus(PurchaseInvoiceHeader purchaseInvoice, PurchaseOrderHeader purchaseOrder)
        {
            // update the purchase order status
            if (purchaseOrder == null)
            {
                // get the first order line
                purchaseOrder =
                    GetPurchaseOrderLineById(
                        purchaseInvoice.PurchaseInvoiceLines.FirstOrDefault().PurchaseOrderLineId.GetValueOrDefault())
                    .PurhcaseOrderHeader;
            }
            // if all orderline has no remaining qty to invoice, set the status to fullyinvoice
            bool hasRemainingQtyToInvoice = false;

            foreach (var line in purchaseOrder.PurchaseOrderLines)
            {
                if (line.GetRemainingQtyToInvoice() > 0)
                {
                    hasRemainingQtyToInvoice = true;
                    break;
                }
            }
            if (!hasRemainingQtyToInvoice)
            {
                purchaseOrder.Status = PurchaseOrderStatus.FullReceived;
                _purchaseOrderRepo.Update(purchaseOrder);
            }
        }
 public ActionResult SaveInvoice(Models.ViewModels.Purchases.PurchaseHeaderViewModel model)
 {
     if (model.Id == 0)
     {
         var invoice = new PurchaseInvoiceHeader();
         invoice.Date            = model.Date;
         invoice.Description     = string.Empty;
         invoice.VendorId        = model.VendorId;
         invoice.VendorInvoiceNo = model.ReferenceNo;
     }
     else
     {
     }
     return(RedirectToAction("PurchaseInvoices"));
 }
        public ActionResult AddPurchaseInvoice(Models.ViewModels.Purchases.AddPurchaseInvoice model)
        {
            if (string.IsNullOrEmpty(model.VendorInvoiceNo))
            {
                return(RedirectToAction("PurchaseOrders"));
            }

            var existingPO = _purchasingService.GetPurchaseOrderById(model.Id);
            var vendor     = _purchasingService.GetVendorById(existingPO.VendorId);

            var purchInvoice = new PurchaseInvoiceHeader()
            {
                Date            = model.Date,
                VendorInvoiceNo = model.VendorInvoiceNo,
                Vendor          = vendor,
                VendorId        = vendor.Id,
                CreatedBy       = User.Identity.Name,
                CreatedOn       = DateTime.Now,
                ModifiedBy      = User.Identity.Name,
                ModifiedOn      = DateTime.Now
            };

            foreach (var line in model.PurchaseInvoiceLines)
            {
                var item        = _inventoryService.GetItemById(line.ItemId);
                var measurement = _inventoryService.GetMeasurementById(line.UnitOfMeasurementId);
                purchInvoice.PurchaseInvoiceLines.Add(new PurchaseInvoiceLine()
                {
                    ItemId           = item.Id,
                    MeasurementId    = measurement.Id,
                    Quantity         = line.Quantity,
                    ReceivedQuantity = line.ReceivedQuantity,
                    Cost             = item.Cost.Value,
                    Discount         = 0,
                    Amount           = item.Cost.Value * line.ReceivedQuantity,
                    CreatedBy        = User.Identity.Name,
                    CreatedOn        = DateTime.Now,
                    ModifiedBy       = User.Identity.Name,
                    ModifiedOn       = DateTime.Now
                });
            }
            _purchasingService.AddPurchaseInvoice(purchInvoice, existingPO.Id);
            return(RedirectToAction("PurchaseOrders"));
        }
        public PurchaseInvoiceHeaderCollection GetAllPurchaseInvoiceHeaderDynamicCollection(string whereExpression, string orderBy)
        {
            IDBManager dbm = new DBManager();
            PurchaseInvoiceHeaderCollection cols = new PurchaseInvoiceHeaderCollection();

            try
            {
                dbm.CreateParameters(2);
                dbm.AddParameters(0, "@WhereCondition", whereExpression);
                dbm.AddParameters(1, "@OrderByExpression", orderBy);
                IDataReader reader = dbm.ExecuteReader(CommandType.StoredProcedure, "SelectPurchaseInvoiceHeadersDynamic");
                while (reader.Read())
                {
                    PurchaseInvoiceHeader PIH = new PurchaseInvoiceHeader();

                    PIH.InvoiceID       = Int32.Parse(reader["InvoiceID"].ToString());
                    PIH.InvoiceNumber   = reader["InvoiceNumber"].ToString();
                    PIH.EmployeeID      = Int32.Parse(reader["EmployeeID"].ToString());
                    PIH.Status          = Byte.Parse(reader["status"].ToString());
                    PIH.VendorID        = Int32.Parse(reader["VendorID"].ToString());
                    PIH.InvoiceDate     = DateTime.Parse(reader["InvoiceDate"].ToString());
                    PIH.SubTotal        = Decimal.Parse(reader["SubTotal"].ToString());
                    PIH.TaxAmt          = Decimal.Parse(reader["TaxAmt"].ToString());
                    PIH.Freight         = Decimal.Parse(reader["Freight"].ToString());
                    PIH.TotalDue        = Decimal.Parse(reader["TotalDue"].ToString());
                    PIH.ModifiedDate    = DateTime.Parse(reader["ModifiedDate"].ToString());
                    PIH.PurchaseOrderID = Int32.Parse(reader["PurchaseOrderID"].ToString());
                    cols.Add(PIH);
                }
            }

            catch (Exception ex)
            {
                log.Write(ex.Message, "GetAllPurchaseInvoiceHeaderDynamicCollection");
                throw (ex);
            }
            finally
            {
                dbm.Dispose();
            }
            return(cols);
        }
        public PurchaseInvoiceHeader GetPurchaseInvoiceHeader(int purchaseOrderID)
        {
            IDBManager            dbm = new DBManager();
            PurchaseInvoiceHeader PIH = new PurchaseInvoiceHeader();

            try
            {
                dbm.CreateParameters(1);
                dbm.AddParameters(0, "@InvoiceID", purchaseOrderID);
                IDataReader reader = dbm.ExecuteReader(CommandType.StoredProcedure, "SelectPurchaseInvoiceHeader");
                while (reader.Read())
                {
                    PIH.InvoiceID       = Int32.Parse(reader["InvoiceID"].ToString());
                    PIH.InvoiceNumber   = reader["InvoiceNumber"].ToString();
                    PIH.EmployeeID      = Int32.Parse(reader["EmployeeID"].ToString());
                    PIH.Status          = Byte.Parse(reader["status"].ToString());
                    PIH.VendorID        = Int32.Parse(reader["VendorID"].ToString());
                    PIH.InvoiceDate     = DateTime.Parse(reader["InvoiceDate"].ToString());
                    PIH.SubTotal        = Decimal.Parse(reader["SubTotal"].ToString());
                    PIH.TaxAmt          = Decimal.Parse(reader["TaxAmt"].ToString());
                    PIH.Freight         = Decimal.Parse(reader["Freight"].ToString());
                    PIH.TotalDue        = Decimal.Parse(reader["TotalDue"].ToString());
                    PIH.ModifiedDate    = DateTime.Parse(reader["ModifiedDate"].ToString());
                    PIH.PurchaseOrderID = Int32.Parse(reader["PurchaseOrderID"].ToString());
                }
            }
            catch (Exception ex)
            {
                log.Write(ex.Message, "GetPurchaseInvoiceHeader");
                throw (ex);
            }
            finally
            {
                dbm.Dispose();
            }
            return(PIH);
        }
        public void SavePurchaseInvoice(PurchaseInvoiceHeader purchaseInvoice, PurchaseOrderHeader purchaseOrder)
        {
            // This method should be in a single transaction. when one fails, roll back all changes.
            try
            {
                // is there any new order line item? save it first. otherwise, saving invoice will fail.
                if (purchaseOrder != null && purchaseOrder.PurchaseOrderLines.Where(id => id.Id == 0).Count() > 0)
                {
                    if (purchaseOrder.Id == 0)
                    {
                        purchaseOrder.No     = GetNextNumber(SequenceNumberTypes.SalesOrder).ToString();
                        purchaseOrder.Status = (int)PurchaseOrderStatus.Draft;
                        _purchaseOrderRepo.Insert(purchaseOrder);
                    }
                    else
                    {
                        _purchaseOrderRepo.Update(purchaseOrder);
                    }
                }

                if (purchaseInvoice.Id == 0)
                {
                    purchaseInvoice.No = GetNextNumber(SequenceNumberTypes.SalesInvoice).ToString();
                    _purchaseInvoiceRepo.Insert(purchaseInvoice);
                }
                else
                {
                    _purchaseInvoiceRepo.Update(purchaseInvoice);
                }

                UpdatePurchaseOrderStatus(purchaseInvoice, purchaseOrder);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 public PurchaseInvoiceHeader Add(PurchaseInvoiceHeader pt)
 {
     _unitOfWork.Repository <PurchaseInvoiceHeader>().Insert(pt);
     return(pt);
 }
 public PurchaseInvoiceHeader Create(PurchaseInvoiceHeader pt)
 {
     pt.ObjectState = ObjectState.Added;
     _unitOfWork.Repository <PurchaseInvoiceHeader>().Insert(pt);
     return(pt);
 }
Exemple #10
0
        public ActionResult DeletePost(PurchaseInvoiceLineViewModel vm)
        {
            bool BeforeSave = true;

            try
            {
                BeforeSave = PurchaseInvoiceDocEvents.beforeLineDeleteEvent(this, new PurchaseEventArgs(vm.PurchaseInvoiceHeaderId, vm.PurchaseInvoiceLineId), ref db);
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXC"] += message;
                EventException     = true;
            }

            if (!BeforeSave)
            {
                TempData["CSEXC"] += "Validation failed before delete.";
            }

            if (BeforeSave && !EventException)
            {
                List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();

                PurchaseInvoiceLine PurchaseInvoiceLine = db.PurchaseInvoiceLine.Find(vm.PurchaseInvoiceLineId);

                try
                {
                    PurchaseInvoiceDocEvents.onLineDeleteEvent(this, new PurchaseEventArgs(PurchaseInvoiceLine.PurchaseInvoiceHeaderId, PurchaseInvoiceLine.PurchaseInvoiceLineId), ref db);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXCL"] += message;
                    EventException      = true;
                }

                LogList.Add(new LogTypeViewModel
                {
                    ExObj = Mapper.Map <PurchaseInvoiceLine>(PurchaseInvoiceLine),
                });

                PurchaseInvoiceHeader header = db.PurchaseInvoiceHeader.Find(PurchaseInvoiceLine.PurchaseInvoiceHeaderId);

                new PurchaseOrderLineStatusService(_unitOfWork).UpdatePurchaseQtyOnInvoice(PurchaseInvoiceLine.PurchaseGoodsReceiptLineId, PurchaseInvoiceLine.PurchaseInvoiceLineId, header.DocDate, 0, ref db, true);

                var chargeslist = (from p in db.PurchaseInvoiceLineCharge
                                   where p.LineTableId == PurchaseInvoiceLine.PurchaseInvoiceLineId
                                   select p).ToList();

                if (chargeslist != null)
                {
                    foreach (var item in chargeslist)
                    {
                        item.ObjectState = Model.ObjectState.Deleted;
                        db.PurchaseInvoiceLineCharge.Remove(item);
                        //new PurchaseInvoiceLineChargeService(_unitOfWork).Delete(item.Id);
                    }
                }

                PurchaseInvoiceLine.ObjectState = Model.ObjectState.Deleted;
                db.PurchaseInvoiceLine.Remove(PurchaseInvoiceLine);


                if (header.Status != (int)StatusConstants.Drafted && header.Status != (int)StatusConstants.Import)
                {
                    header.Status       = (int)StatusConstants.Modified;
                    header.ModifiedDate = DateTime.Now;
                    header.ModifiedBy   = User.Identity.Name;
                    //new PurchaseInvoiceHeaderService(_unitOfWork).Update(header);
                }
                header.ObjectState = Model.ObjectState.Modified;
                db.PurchaseInvoiceHeader.Add(header);



                if (vm.footercharges != null)
                {
                    foreach (var item in vm.footercharges)
                    {
                        var footer = db.PurchaseInvoiceHeaderCharge.Find(item.Id);
                        footer.Rate        = item.Rate;
                        footer.Amount      = item.Amount;
                        footer.ObjectState = Model.ObjectState.Modified;
                        db.PurchaseInvoiceHeaderCharge.Add(footer);
                        //new PurchaseInvoiceHeaderChargeService(_unitOfWork).Update(footer);
                    }
                }

                XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                try
                {
                    if (EventException)
                    {
                        throw new Exception();
                    }

                    db.SaveChanges();
                    //_unitOfWork.Save();
                }

                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXCL"] += message;
                    PrepareViewBag(null);
                    return(PartialView("_Create", vm));
                }

                try
                {
                    PurchaseInvoiceDocEvents.afterLineDeleteEvent(this, new PurchaseEventArgs(PurchaseInvoiceLine.PurchaseInvoiceHeaderId, PurchaseInvoiceLine.PurchaseInvoiceLineId), ref db);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                }

                LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                {
                    DocTypeId       = header.DocTypeId,
                    DocId           = header.PurchaseInvoiceHeaderId,
                    DocLineId       = PurchaseInvoiceLine.PurchaseInvoiceLineId,
                    ActivityType    = (int)ActivityTypeContants.Deleted,
                    DocNo           = header.DocNo,
                    xEModifications = Modifications,
                    DocDate         = header.DocDate,
                    DocStatus       = header.Status,
                }));
            }

            return(Json(new { success = true }));
        }
Exemple #11
0
        public void AddPurchaseInvoice(PurchaseInvoiceHeader purchaseIvoice, int?purchaseOrderId)
        {
            #region Auto create purchase order
            if (!purchaseOrderId.HasValue)
            {
                var po = new PurchaseOrderHeader()
                {
                    Date        = purchaseIvoice.Date,
                    No          = GetNextNumber(SequenceNumberTypes.PurchaseOrder).ToString(),
                    Vendor      = purchaseIvoice.Vendor,
                    VendorId    = purchaseIvoice.VendorId.Value,
                    Description = purchaseIvoice.Description,
                };
                foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
                {
                    var item = _inventoryService.GetItemById(line.ItemId);

                    po.PurchaseOrderLines.Add(new PurchaseOrderLine()
                    {
                        ItemId        = item.Id,
                        MeasurementId = line.MeasurementId,
                        Quantity      = line.Quantity,
                        Cost          = item.Cost.Value,
                        Discount      = line.Discount.HasValue ? line.Discount.Value : 0,
                        Amount        = line.Amount * line.Quantity,
                    });
                }
                purchaseIvoice.PurchaseOrders.Add(po);
                //var poReceipt = new PurchaseReceiptHeader()
                //{
                //    Date = DateTime.Now,
                //    VendorId = po.VendorId.Value,
                //    PurchaseOrderHeaderId = po.Id,
                //};

                //foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
                //{
                //    poReceipt.PurchaseReceiptLines.Add(new PurchaseReceiptLine()
                //    {
                //        ItemId = line.ItemId,
                //        MeasurementId = line.MeasurementId,
                //        Quantity = line.Quantity,
                //        ReceivedQuantity = (line.ReceivedQuantity.HasValue ? line.ReceivedQuantity.Value : 0),
                //        Cost = line.Cost.Value,
                //        Amount = line.Cost.Value * (line.ReceivedQuantity.HasValue ? line.ReceivedQuantity.Value : 0),
                //    });
                //}

                //po.PurchaseReceipts.Add(poReceipt);

                //AddPurchaseOrderReceipt(poReceipt);
            }
            #endregion

            var glHeader = _financialService.CreateGeneralLedgerHeader(DocumentTypes.PurchaseInvoice, purchaseIvoice.Date, purchaseIvoice.Description);

            decimal totalTaxAmount = 0, totalAmount = 0, totalDiscount = 0;
            var     taxes = new List <KeyValuePair <int, decimal> >();

            foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
            {
                var lineTaxes = _financialService.ComputeInputTax(purchaseIvoice.VendorId.GetValueOrDefault(), line.ItemId, line.Quantity, line.Amount, line.Discount.GetValueOrDefault());

                var lineAmount = line.Quantity * line.Amount;

                var totalLineAmount = lineAmount + lineTaxes.Sum(t => t.Value);

                totalAmount += (decimal)totalLineAmount;

                foreach (var t in lineTaxes)
                {
                    taxes.Add(t);
                }

                var     item = _inventoryService.GetItemById(line.ItemId);
                decimal lineItemTotalAmountAfterTax = line.Amount - lineTaxes.Sum(t => t.Value);

                GeneralLedgerLine debitInventory = _financialService.CreateGeneralLedgerLine(DrOrCrSide.Dr, item.InventoryAccount.Id, lineItemTotalAmountAfterTax);
                glHeader.GeneralLedgerLines.Add(debitInventory);

                GeneralLedgerLine creditGRNClearingAccount = _financialService.CreateGeneralLedgerLine(DrOrCrSide.Cr, GetGeneralLedgerSetting().GoodsReceiptNoteClearingAccountId.Value, lineItemTotalAmountAfterTax);
                glHeader.GeneralLedgerLines.Add(creditGRNClearingAccount);

                line.InventoryControlJournal = _inventoryService.CreateInventoryControlJournal(line.ItemId,
                                                                                               line.MeasurementId,
                                                                                               DocumentTypes.PurchaseReceipt,
                                                                                               line.Quantity,
                                                                                               null,
                                                                                               line.Quantity * item.Cost,
                                                                                               null);
            }

            if (taxes != null && taxes.Count > 0)
            {
                var groupedTaxes = from t in taxes
                                   group t by t.Key into grouped
                                   select new
                {
                    Key   = grouped.Key,
                    Value = grouped.Sum(t => t.Value)
                };

                totalTaxAmount = taxes.Sum(t => t.Value);

                foreach (var tax in groupedTaxes)
                {
                    var tx = _financialService.GetTaxes().Where(t => t.Id == tax.Key).FirstOrDefault();
                    var debitPurchaseTaxAccount = _financialService.CreateGeneralLedgerLine(DrOrCrSide.Dr, tx.PurchasingAccountId.Value, tax.Value);
                    glHeader.GeneralLedgerLines.Add(debitPurchaseTaxAccount);
                }
            }

            if (totalDiscount > 0)
            {
            }

            Vendor vendor = GetVendorById(purchaseIvoice.VendorId.Value);
            var    creditVendorAccount = _financialService.CreateGeneralLedgerLine(DrOrCrSide.Cr, vendor.AccountsPayableAccountId.Value, totalAmount);
            glHeader.GeneralLedgerLines.Add(creditVendorAccount);

            var debitGRNClearingAccount = _financialService.CreateGeneralLedgerLine(DrOrCrSide.Dr, GetGeneralLedgerSetting().GoodsReceiptNoteClearingAccountId.Value, totalAmount - totalTaxAmount);
            glHeader.GeneralLedgerLines.Add(debitGRNClearingAccount);

            if (_financialService.ValidateGeneralLedgerEntry(glHeader))
            {
                purchaseIvoice.GeneralLedgerHeader = glHeader;

                purchaseIvoice.No = GetNextNumber(SequenceNumberTypes.PurchaseInvoice).ToString();
                _purchaseInvoiceRepo.Insert(purchaseIvoice);

                if (purchaseOrderId.HasValue)
                {
                    // TODO: Look for other way to update the purchase order's invoice header id field so that it shall be in a single transaction along with purchase invoice saving
                    var purchOrder = GetPurchaseOrderById(purchaseOrderId.GetValueOrDefault());
                    //purchOrder.PurchaseInvoiceHeaderId = purchaseIvoice.Id;
                    _purchaseOrderRepo.Update(purchOrder);
                }
            }
        }
Exemple #12
0
        public dynamic GenerateGLHeader(ICollection <PurchaseInvoiceLine> InvoiceLines, PurchaseInvoiceHeader purchaseIvoice)
        {
            var glHeader = _financialService.CreateGeneralLedgerHeader(DocumentTypes.PurchaseInvoice, purchaseIvoice.Date, purchaseIvoice.Description);

            decimal totalTaxAmount = 0, totalAmount = 0, totalDiscount = 0;
            var     taxes = new List <KeyValuePair <int, decimal> >();

            foreach (var line in InvoiceLines)
            {
                var lineTaxes = _financialService.ComputeInputTax(purchaseIvoice.VendorId.Value, line.ItemId, line.Quantity, line.Cost.Value, decimal.Zero);

                var lineAmount = line.Quantity * line.Cost;

                var totalLineAmount = lineAmount + lineTaxes.Sum(t => t.Value);

                totalAmount += (decimal)totalLineAmount;

                foreach (var t in lineTaxes)
                {
                    taxes.Add(t);
                }
            }

            if (taxes != null && taxes.Count > 0)
            {
                var groupedTaxes = from t in taxes
                                   group t by t.Key into grouped
                                   select new
                {
                    Key   = grouped.Key,
                    Value = grouped.Sum(t => t.Value)
                };

                totalTaxAmount = taxes.Sum(t => t.Value);

                foreach (var tax in groupedTaxes)
                {
                    var tx = _financialService.GetTaxes().Where(t => t.Id == tax.Key).FirstOrDefault();
                    var debitPurchaseTaxAccount = _financialService.CreateGeneralLedgerLine(DrOrCrSide.Dr, tx.PurchasingAccountId.Value, tax.Value);
                    glHeader.GeneralLedgerLines.Add(debitPurchaseTaxAccount);
                }
            }

            if (totalDiscount > 0)
            {
            }

            Vendor vendor = _vendorRepo.GetById(purchaseIvoice.VendorId.Value);
            var    creditVendorAccount = _financialService.CreateGeneralLedgerLine(DrOrCrSide.Cr, vendor.AccountsPayableAccountId.Value, totalAmount);

            glHeader.GeneralLedgerLines.Add(creditVendorAccount);

            var debitGRNClearingAccount = _financialService.CreateGeneralLedgerLine(DrOrCrSide.Dr, GetGeneralLedgerSetting().GoodsReceiptNoteClearingAccountId.Value, totalAmount - totalTaxAmount);

            glHeader.GeneralLedgerLines.Add(debitGRNClearingAccount);

            return(glHeader);
        }
Exemple #13
0
        public void SavePurchaseInvoice(PurchaseInvoiceHeader purchaseIvoice)
        {
            var invoice = GetPurchaseInvoiceById(purchaseIvoice.Id);

            if (invoice != null)
            {
                invoice.Date        = purchaseIvoice.Date;
                invoice.No          = purchaseIvoice.No;
                invoice.VendorId    = purchaseIvoice.VendorId;
                invoice.Description = purchaseIvoice.Description;
                // update invoice lines from old invoice
                foreach (var line in invoice.PurchaseInvoiceLines)
                {
                    var singleLine = purchaseIvoice.PurchaseInvoiceLines.Where(x => x.Id == line.Id).FirstOrDefault();
                    if (singleLine != null)
                    {
                        line.ItemId        = singleLine.ItemId;
                        line.MeasurementId = singleLine.MeasurementId;
                        line.Quantity      = singleLine.Quantity;
                        line.Cost          = singleLine.Cost;
                        line.Discount      = singleLine.Discount;
                        line.Amount        = singleLine.Amount;
                        // TODO: tax is not mapped coming from front end with amount
                    }
                    else
                    {
                        line.Deleted = true;
                    }
                }
                foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
                {
                    var singleLine = invoice.PurchaseInvoiceLines.Where(x => x.Id == line.Id).FirstOrDefault();
                    if (singleLine == null)
                    {
                        line.Id = 0;
                        invoice.PurchaseInvoiceLines.Add(line);
                    }
                }
                // end updatesdaw
                var glHeader = GenerateGLHeader(invoice.PurchaseInvoiceLines, invoice);
                if (_financialService.ValidateGeneralLedgerEntry(glHeader))
                {
                    purchaseIvoice.GeneralLedgerHeader = glHeader;

                    purchaseIvoice.No = GetNextNumber(SequenceNumberTypes.PurchaseInvoice).ToString();
                    _purchaseInvoiceRepo.Update(purchaseIvoice);
                }
            }
            else
            {
                var glHeader = GenerateGLHeader(purchaseIvoice.PurchaseInvoiceLines, purchaseIvoice);
                if (_financialService.ValidateGeneralLedgerEntry(glHeader))
                {
                    purchaseIvoice.GeneralLedgerHeader = glHeader;

                    purchaseIvoice.No = GetNextNumber(SequenceNumberTypes.PurchaseInvoice).ToString();
                    _purchaseInvoiceRepo.Insert(purchaseIvoice);

                    // TODO: Look for other way to update the purchase order's invoice header id field so that it shall be in a single transaction along with purchase invoice saving
                    //var purchOrder = _purchaseOrderRepo.GetById(purchaseOrderId.Value);
                    // purchOrder.PurchaseInvoiceHeaderId = purchaseIvoice.Id;
                    //_purchaseOrderRepo.Update(purchOrder);
                }
            }
        }
        public void AddPurchaseInvoice(PurchaseInvoiceHeader purchaseIvoice, int?purchaseOrderId)
        {
            #region Auto create purchase order
            if (!purchaseOrderId.HasValue)
            {
                var po = new PurchaseOrderHeader()
                {
                    Date = purchaseIvoice.Date,
                    //No = GetNextNumber(SequenceNumberTypes.PurchaseOrder).ToString(),
                    Vendor      = purchaseIvoice.Vendor,
                    VendorId    = purchaseIvoice.VendorId.Value,
                    Description = purchaseIvoice.Description,
                };
                foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
                {
                    var item = _itemRepo.GetById(line.ItemId);

                    po.PurchaseOrderLines.Add(new PurchaseOrderLine()
                    {
                        ItemId        = item.Id,
                        MeasurementId = line.MeasurementId,
                        Quantity      = line.Quantity,
                        Cost          = item.Cost.Value,
                        Discount      = line.Discount.HasValue ? line.Discount.Value : 0,
                        Amount        = item.Cost.Value * line.Quantity,
                    });
                }
                purchaseIvoice.PurchaseOrders.Add(po);

                var poReceipt = new PurchaseReceiptHeader()
                {
                    Date     = DateTime.Now,
                    Vendor   = po.Vendor,
                    VendorId = po.VendorId.Value,
                    PurchaseOrderHeaderId = po.Id,
                };

                foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
                {
                    poReceipt.PurchaseReceiptLines.Add(new PurchaseReceiptLine()
                    {
                        ItemId           = line.ItemId,
                        MeasurementId    = line.MeasurementId,
                        Quantity         = line.Quantity,
                        ReceivedQuantity = (line.ReceivedQuantity.HasValue ? line.ReceivedQuantity.Value : 0),
                        Cost             = line.Cost.Value,
                        Amount           = line.Cost.Value * (line.ReceivedQuantity.HasValue ? line.ReceivedQuantity.Value : 0),
                    });
                }

                po.PurchaseReceipts.Add(poReceipt);

                AddPurchaseOrderReceipt(poReceipt);
            }
            #endregion


            decimal totalTaxAmount = 0, totalAmount = 0, totalDiscount = 0;
            var     taxes = new List <KeyValuePair <int, decimal> >();

            foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
            {
                var lineTaxes = _financialService.ComputeInputTax(purchaseIvoice.VendorId.Value, line.ItemId, line.Quantity, line.Cost.Value, decimal.Zero);

                var lineAmount = line.Quantity * line.Cost;

                var totalLineAmount = lineAmount + lineTaxes.Sum(t => t.Value);

                totalAmount += (decimal)totalLineAmount;

                foreach (var t in lineTaxes)
                {
                    taxes.Add(t);
                }
            }

            if (taxes != null && taxes.Count > 0)
            {
                var groupedTaxes = from t in taxes
                                   group t by t.Key into grouped
                                   select new
                {
                    Key   = grouped.Key,
                    Value = grouped.Sum(t => t.Value)
                };

                totalTaxAmount = taxes.Sum(t => t.Value);

                //foreach (var tax in groupedTaxes)
                //{
                //    var tx = _financialService.GetTaxes().Where(t => t.Id == tax.Key).FirstOrDefault();

                //}
            }

            if (totalDiscount > 0)
            {
            }

            Vendor vendor = _vendorRepo.GetById(purchaseIvoice.VendorId.Value);
        }
Exemple #15
0
 public static PurchaseInvoiceHeader ToEntity(this InvoiceModel model, PurchaseInvoiceHeader destination)
 {
     return(model.MapTo(destination));
 }
 public void Delete(PurchaseInvoiceHeader pt)
 {
     _unitOfWork.Repository <PurchaseInvoiceHeader>().Delete(pt);
 }
Exemple #17
0
        public void AddPurchaseInvoice(PurchaseInvoiceHeader purchaseIvoice, int?purchaseOrderId)
        {
            #region Auto create purchase order
            if (!purchaseOrderId.HasValue)
            {
                var po = new PurchaseOrderHeader()
                {
                    Date        = purchaseIvoice.Date,
                    No          = GetNextNumber(SequenceNumberTypes.PurchaseOrder).ToString(),
                    Vendor      = purchaseIvoice.Vendor,
                    VendorId    = purchaseIvoice.VendorId.Value,
                    Description = purchaseIvoice.Description,
                    CreatedBy   = purchaseIvoice.CreatedBy,
                    CreatedOn   = purchaseIvoice.CreatedOn,
                    ModifiedBy  = purchaseIvoice.ModifiedBy,
                    ModifiedOn  = purchaseIvoice.ModifiedOn
                };
                foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
                {
                    var item = _itemRepo.GetById(line.ItemId);

                    po.PurchaseOrderLines.Add(new PurchaseOrderLine()
                    {
                        ItemId        = item.Id,
                        MeasurementId = line.MeasurementId,
                        Quantity      = line.Quantity,
                        Cost          = item.Cost.Value,
                        Discount      = line.Discount.HasValue ? line.Discount.Value : 0,
                        Amount        = item.Cost.Value * line.Quantity,
                        CreatedBy     = line.CreatedBy,
                        CreatedOn     = line.CreatedOn,
                        ModifiedBy    = line.ModifiedBy,
                        ModifiedOn    = line.ModifiedOn
                    });
                }
                purchaseIvoice.PurchaseOrders.Add(po);

                var poReceipt = new PurchaseReceiptHeader()
                {
                    Date     = DateTime.Now,
                    Vendor   = po.Vendor,
                    VendorId = po.VendorId,
                    PurchaseOrderHeaderId = po.Id,
                    CreatedBy             = po.CreatedBy,
                    CreatedOn             = DateTime.Now,
                    ModifiedBy            = po.ModifiedBy,
                    ModifiedOn            = DateTime.Now
                };

                foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
                {
                    poReceipt.PurchaseReceiptLines.Add(new PurchaseReceiptLine()
                    {
                        ItemId           = line.ItemId,
                        MeasurementId    = line.MeasurementId,
                        Quantity         = line.Quantity,
                        ReceivedQuantity = (line.ReceivedQuantity.HasValue ? line.ReceivedQuantity.Value : 0),
                        Cost             = line.Cost.Value,
                        Amount           = line.Cost.Value * (line.ReceivedQuantity.HasValue ? line.ReceivedQuantity.Value : 0),
                        CreatedBy        = po.CreatedBy,
                        CreatedOn        = DateTime.Now,
                        ModifiedBy       = po.ModifiedBy,
                        ModifiedOn       = DateTime.Now
                    });
                }

                po.PurchaseReceipts.Add(poReceipt);

                AddPurchaseOrderReceipt(poReceipt);
            }
            #endregion

            var glHeader = _financialService.CreateGeneralLedgerHeader(DocumentTypes.PurchaseInvoice, purchaseIvoice.Date, purchaseIvoice.Description);

            decimal taxAmount = 0;
            var     taxes     = new List <KeyValuePair <int, decimal> >();
            foreach (var line in purchaseIvoice.PurchaseInvoiceLines)
            {
                var lineAmount = line.Quantity * line.Cost;
                //var item = _inventoryService.GetItemById(line.ItemId);
                //foreach (var tax in item.ItemTaxGroup.ItemTaxGroupTax)
                //{
                //    if(!tax.IsExempt)
                //    {
                //        var lineTaxAmount = (tax.Tax.Rate / 100) * lineAmount;
                //        taxAmount += lineTaxAmount.Value;
                //        taxes.Add(new KeyValuePair<int, decimal>(tax.Tax.PurchasingAccountId.Value, lineTaxAmount.Value));
                //    }
                //}
                var lineTaxes = _financialService.ComputeInputTax(line.ItemId, line.Quantity, line.Cost.Value);
                foreach (var t in lineTaxes)
                {
                    taxes.Add(t);
                }
            }

            decimal totalAmount   = purchaseIvoice.PurchaseInvoiceLines.Sum(d => d.Amount);
            decimal totalDiscount = 0;

            Vendor vendor = _vendorRepo.GetById(purchaseIvoice.VendorId.Value);
            var    creditVendorAccount = _financialService.CreateGeneralLedgerLine(TransactionTypes.Cr, vendor.AccountsPayableAccountId.Value, totalAmount + taxAmount);
            glHeader.GeneralLedgerLines.Add(creditVendorAccount);

            var creditGRNClearingAccount = _financialService.CreateGeneralLedgerLine(TransactionTypes.Dr, GetGeneralLedgerSetting().GoodsReceiptNoteClearingAccountId.Value, totalAmount);
            glHeader.GeneralLedgerLines.Add(creditGRNClearingAccount);

            if (taxAmount > 0)
            {
                var groupedTaxes = from t in taxes
                                   group t by t.Key into grouped
                                   select new
                {
                    Key   = grouped.Key,
                    Value = grouped.Sum(t => t.Value)
                };

                foreach (var tax in groupedTaxes)
                {
                    var tx = _financialService.GetTaxes().Where(t => t.Id == tax.Key).FirstOrDefault();
                    var debitPurchaseTaxAccount = _financialService.CreateGeneralLedgerLine(TransactionTypes.Dr, tx.SalesAccountId.Value, tax.Value);
                    glHeader.GeneralLedgerLines.Add(debitPurchaseTaxAccount);
                }
            }

            if (totalDiscount > 0)
            {
            }

            if (_financialService.ValidateGeneralLedgerEntry(glHeader))
            {
                purchaseIvoice.GeneralLedgerHeader = glHeader;

                purchaseIvoice.No = GetNextNumber(SequenceNumberTypes.PurchaseInvoice).ToString();
                _purchaseInvoiceRepo.Insert(purchaseIvoice);

                // TODO: Look for another way to update the purchase order's invoice header id field so that it shall be in a single transaction along with purchase invoice saving
                var purchOrder = _purchaseOrderRepo.GetById(purchaseOrderId.Value);
                purchOrder.PurchaseInvoiceHeaderId = purchaseIvoice.Id;
                purchOrder.ModifiedBy = purchaseIvoice.ModifiedBy;
                purchOrder.ModifiedOn = purchaseIvoice.ModifiedOn;
                _purchaseOrderRepo.Update(purchOrder);
            }
        }
 public bool DeletePurchaseInvoiceHeader(PurchaseInvoiceHeader PIH)
 {
     return(DeletePurchaseInvoiceHeader(PIH.InvoiceID));
 }
 public void Update(PurchaseInvoiceHeader pt)
 {
     pt.ObjectState = ObjectState.Modified;
     _unitOfWork.Repository <PurchaseInvoiceHeader>().Update(pt);
 }
Exemple #20
0
 public static InvoiceModel ToModel(this PurchaseInvoiceHeader entity)
 {
     return(entity.MapTo <PurchaseInvoiceHeader, InvoiceModel>());
 }