Example #1
0
        public IFluentSupplierLedger CreateEntityByView(SupplierLedgerView view)
        {
            try
            {
                //SupplierLedger supplierLedger = new SupplierLedger();

                Task <SupplierLedger> supplierLedgerQueryTask = Task.Run(async() => await unitOfWork.supplierLedgerRepository.GetEntityByView(view));
                Task.WaitAll(supplierLedgerQueryTask);


                if (supplierLedgerQueryTask.Result == null)
                {
                    SupplierLedger supplierLedger = MapToEntity(view);


                    AddSupplierLedger(supplierLedger);

                    processStatus = CreateProcessStatus.Insert;

                    return(this as IFluentSupplierLedger);
                }
                processStatus = CreateProcessStatus.AlreadyExists;
                return(this as IFluentSupplierLedger);
            }
            catch (Exception ex)
            { throw new Exception("CreateEntityByView", ex); }
        }
Example #2
0
        private SupplierLedger MapToEntity(SupplierLedgerView inputObject)
        {
            Mapper         mapper    = new Mapper();
            SupplierLedger outObject = mapper.Map <SupplierLedger>(inputObject);

            return(outObject);
        }
Example #3
0
        public IFluentSupplierLedger UpdateEntityByView(SupplierLedgerView supplierLedgerView)

        {
            try
            {
                Task <SupplierLedger> supplierLedgerBaseTask = Task.Run(async() => await unitOfWork.supplierLedgerRepository.GetEntityById(supplierLedgerView.SupplierLedgerId));
                Task.WaitAll(supplierLedgerBaseTask);
                SupplierLedger supplierLedgerBase = supplierLedgerBaseTask.Result;


                if (supplierLedgerBase != null)

                {
                    applicationViewFactory.MapSupplierLedgerEntity(ref supplierLedgerBase, supplierLedgerView);
                    UpdateSupplierLedger(supplierLedgerBase);

                    processStatus = CreateProcessStatus.Update;
                    return(this as IFluentSupplierLedger);
                }

                processStatus = CreateProcessStatus.Failed;
                return(this as IFluentSupplierLedger);
            }
            catch (Exception ex)
            {
                throw new Exception("UpdateEntityByView", ex);
            }
        }
        public ActionResult AddSupplier(Supplier supplier)
        {
            SupplierLedger  aSupplierLedger = new SupplierLedger();
            List <Supplier> supplierList    = new List <Supplier>();

            if (supplier.SupplierID <= 0 && supplier.SupplierName != null && supplier.SupplierPhone != null)
            {
                var PhoneExist = db.Supplier.Where(c => c.SupplierPhone == supplier.SupplierPhone).FirstOrDefault();

                if (PhoneExist == null)
                {
                    //var companyName = db.Company.Where(c => c.CompanyID == customer.CompanyID).Select(g => new { Name = g.CompanyName }).First();
                    //var groupName = db.Group.Where(c => c.GroupID == customer.GroupID).Select(g => new { Name = g.GroupName }).First();
                    int?MaxId = db.Supplier.Max(x => (int?)x.SupplierID);

                    if (MaxId == null)
                    {
                        MaxId = 0;
                    }
                    var id = MaxId + 1;

                    if (supplier.SupplierPreviousDue == null || supplier.SupplierPreviousDue == 0)
                    {
                        supplier.SupplierPreviousDue  = 0;
                        aSupplierLedger.IsPreviousDue = 0;
                    }
                    else
                    {
                        aSupplierLedger.IsPreviousDue = 1;
                    }
                    string date    = DateTime.Now.ToString("M/d/yyyy");
                    var    NowDate = Convert.ToDateTime(date);
                    aSupplierLedger.ReceiveDate = NowDate;
                    aSupplierLedger.InvoiceNo   = "Previous Due";
                    aSupplierLedger.Remarks     = "Previous Due";
                    aSupplierLedger.Debit       = 0;
                    aSupplierLedger.Credit      = supplier.SupplierPreviousDue;
                    aSupplierLedger.SupplierID  = Convert.ToInt32(id);
                    db.Supplier.Add(supplier);
                    db.SupplierLedger.Add(aSupplierLedger);
                    db.SaveChanges();
                    supplierList    = db.Supplier.ToList();
                    ViewBag.Message = 1;
                }
                else
                {
                    supplierList    = db.Supplier.ToList();
                    ViewBag.Message = 0;
                }
            }
            else
            {
                supplierList    = db.Supplier.ToList();
                ViewBag.Message = 2;
            }
            ViewBag.Suppliergroup = db.SupplierGroup.ToList();
            return(View(supplierList));
        }
        public async Task <IActionResult> DeleteSupplierLedger([FromBody] SupplierLedgerView view)
        {
            SupplierLedgerModule invMod         = new SupplierLedgerModule();
            SupplierLedger       supplierLedger = await invMod.SupplierLedger.Query().MapToEntity(view);

            invMod.SupplierLedger.DeleteSupplierLedger(supplierLedger).Apply();

            return(Ok(view));
        }
Example #6
0
        public async Task TestAddUpdatDelete()
        {
            SupplierLedgerModule SupplierLedgerMod = new SupplierLedgerModule();
            Supplier             supplier          = await SupplierLedgerMod.Supplier.Query().GetEntityById(3);

            Invoice invoice = await SupplierLedgerMod.Invoice.Query().GetEntityById(2);

            AccountPayable accountPayable = await SupplierLedgerMod.AccountPayable.Query().GetEntityById(2);

            GeneralLedger generalLedger = await SupplierLedgerMod.GeneralLedger.Query().GetEntityById(17);

            AddressBook addressBook = await SupplierLedgerMod.AddressBook.Query().GetEntityById(17);


            SupplierLedgerView view = new SupplierLedgerView()
            {
                SupplierId      = supplier.SupplierId,
                InvoiceId       = invoice.InvoiceId,
                AcctPayId       = accountPayable.AccountPayableId,
                Amount          = 300M,
                Gldate          = DateTime.Parse("11/11/2019"),
                AccountId       = generalLedger.AccountId,
                GeneralLedgerId = generalLedger.GeneralLedgerId,
                DocNumber       = 17,
                Comment         = "back to school",
                AddressId       = addressBook.AddressId,
                CreatedDate     = DateTime.Parse("11/11/2019"),
                DocType         = "PV",
                DebitAmount     = null,
                CreditAmount    = null,
                FiscalYear      = 2019,
                FiscalPeriod    = 11
            };
            NextNumber nnNextNumber = await SupplierLedgerMod.SupplierLedger.Query().GetNextNumber();

            view.SupplierLedgerNumber = nnNextNumber.NextNumberValue;

            SupplierLedger supplierLedger = await SupplierLedgerMod.SupplierLedger.Query().MapToEntity(view);

            SupplierLedgerMod.SupplierLedger.AddSupplierLedger(supplierLedger).Apply();

            SupplierLedger newSupplierLedger = await SupplierLedgerMod.SupplierLedger.Query().GetEntityByNumber(view.SupplierLedgerNumber);

            Assert.NotNull(newSupplierLedger);

            newSupplierLedger.Comment = "back to school update";

            SupplierLedgerMod.SupplierLedger.UpdateSupplierLedger(newSupplierLedger).Apply();

            SupplierLedgerView updateView = await SupplierLedgerMod.SupplierLedger.Query().GetViewById(newSupplierLedger.SupplierLedgerId);

            Assert.Same(updateView.Comment, "back to school update");
            SupplierLedgerMod.SupplierLedger.DeleteSupplierLedger(newSupplierLedger).Apply();
            SupplierLedger lookupSupplierLedger = await SupplierLedgerMod.SupplierLedger.Query().GetEntityById(view.SupplierLedgerId);

            Assert.Null(lookupSupplierLedger);
        }
Example #7
0
        private void ShowSupplierForm()
        {
            SupplierLedger Itm = new SupplierLedger();

            Itm.TopLevel = false;
            this.Controls.Add(Itm);
            Itm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            Itm.Dock            = DockStyle.Fill;
            Itm.BringToFront();
            Itm.Show();
        }
        public async Task <IActionResult> UpdateSupplierLedger([FromBody] SupplierLedgerView view)
        {
            SupplierLedgerModule invMod = new SupplierLedgerModule();

            SupplierLedger supplierLedger = await invMod.SupplierLedger.Query().MapToEntity(view);


            invMod.SupplierLedger.UpdateSupplierLedger(supplierLedger).Apply();

            SupplierLedgerView retView = await invMod.SupplierLedger.Query().GetViewById(supplierLedger.SupplierLedgerId);


            return(Ok(retView));
        }
        public ActionResult EditSupplierLedger(int Id)
        {
            var select = db.SupplierLedger.Where(a => a.ID == Id).First();

            var            due             = db.Supplier.Where(a => a.SupplierID == select.SupplierID).First();
            SupplierLedger aSupplierLedger = new SupplierLedger()
            {
                ID          = select.ID,
                SupplierID  = select.SupplierID,
                ReceiveDate = select.ReceiveDate,
                PreviouaDue = due.SupplierPreviousDue,
                Debit       = select.Debit,
                Remarks     = select.Remarks
            };

            return(Json(aSupplierLedger, JsonRequestBehavior.AllowGet));
        }
        public async Task <IActionResult> AddSupplierLedger([FromBody] SupplierLedgerView view)
        {
            SupplierLedgerModule invMod = new SupplierLedgerModule();

            NextNumber nnSupplierLedger = await invMod.SupplierLedger.Query().GetNextNumber();

            view.SupplierLedgerNumber = nnSupplierLedger.NextNumberValue;

            SupplierLedger supplierLedger = await invMod.SupplierLedger.Query().MapToEntity(view);

            invMod.SupplierLedger.AddSupplierLedger(supplierLedger).Apply();

            SupplierLedgerView newView = await invMod.SupplierLedger.Query().GetViewByNumber(view.SupplierLedgerNumber);


            return(Ok(newView));
        }
Example #11
0
        public override void MapSupplierLedgerEntity(ref SupplierLedger supplierLedger, SupplierLedgerView view)

        {
            supplierLedger.SupplierLedgerId = view.SupplierLedgerId;
            supplierLedger.SupplierId       = view.SupplierId;
            supplierLedger.InvoiceId        = view.InvoiceId;
            supplierLedger.AcctPayId        = view.AcctPayId;
            supplierLedger.Amount           = view.Amount;
            supplierLedger.Gldate           = view.Gldate;
            supplierLedger.AccountId        = view.AccountId;
            supplierLedger.GeneralLedgerId  = view.GeneralLedgerId;
            supplierLedger.DocNumber        = view.DocNumber;
            supplierLedger.DocType          = view.DocType;
            supplierLedger.Comment          = view.Comment;
            supplierLedger.AddressId        = view.AddressId;
            supplierLedger.CreatedDate      = view.CreatedDate;
            supplierLedger.FiscalPeriod     = view.FiscalPeriod;
            supplierLedger.FiscalYear       = view.FiscalYear;
        }
Example #12
0
        public static List <SupplierLedger> GetSupplierLedger(int supplierid)
        {
            var dbUtil          = new DatabaseManager();
            var supplierledgers = new List <SupplierLedger>();

            using (var conn = new SqlConnection(dbUtil.getSQLConnectionString("MainDB")))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandType    = CommandType.StoredProcedure;
                    cmd.CommandText    = "spCommonGetSuppEntryLedger";
                    cmd.CommandTimeout = 180;
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@intIDMasSupplier", supplierid);

                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        int counter = 0;

                        while (reader.Read())
                        {
                            var supplierledger = new SupplierLedger
                            {
                                SupplierLedgerID = counter + 1,
                                BookTypeCode     = ReferenceEquals(reader["strMasBookTypeCode"], DBNull.Value) ? String.Empty : (string)reader["strMasBookTypeCode"],
                                ReferenceNo      = ReferenceEquals(reader["intRefDocNo"], DBNull.Value) ? 0 : (int)reader["intRefDocNo"],
                                Credit           = ReferenceEquals(reader["curCredit"], DBNull.Value) ? 0 : (decimal)reader["curCredit"],
                                Debit            = ReferenceEquals(reader["curDebit"], DBNull.Value) ? 0 : (decimal)reader["curDebit"],
                                Balance          = ReferenceEquals(reader["curRunningBalance"], DBNull.Value) ? 0 : (decimal)reader["curRunningBalance"]
                            };

                            supplierledgers.Add(supplierledger);

                            counter += 1;
                        }

                        return(supplierledgers);
                    }
                }
            }
        }
 public SupplierLedgerView(SupplierLedger SupplierLedger)
 {
     this.SupplierLedgerId = SupplierLedger.SupplierLedgerId;
     this.SupplierId       = SupplierLedger.SupplierId;
     this.SupplierName     = SupplierLedger.Supplier.AddressBook.Name;
     this.InvoiceId        = SupplierLedger.InvoiceId;
     this.AcctPayId        = SupplierLedger.AcctPayId;
     this.DocNumber        = SupplierLedger.DocNumber;
     this.DocType          = SupplierLedger.DocType;
     this.Amount           = SupplierLedger.Amount ?? 0;
     this.GLDate           = SupplierLedger.GLDate ?? DateTime.Now.Date;
     this.CreatedDate      = SupplierLedger.CreatedDate ?? DateTime.Now.Date;
     this.AccountId        = SupplierLedger.AccountId;
     this.AddressId        = SupplierLedger.AddressId;
     this.Comment          = SupplierLedger.Comment;
     this.DebitAmount      = SupplierLedger.DebitAmount;
     this.CreditAmount     = SupplierLedger.CreditAmount;
     this.FiscalPeriod     = SupplierLedger.FiscalPeriod;
     this.FiscalYear       = SupplierLedger.FiscalYear;
     this.GeneralLedgerId  = SupplierLedger.GeneralLedgerId;
 }
Example #14
0
        private void SupplierLedgerCreate(string invoiceNO, double?totalAmount, int?supplierID, DateTime date)
        {
            SupplierLedger aSupplierLedger = new SupplierLedger();
            var            aSupplier       = db.Supplier.SingleOrDefault(p => p.SupplierID == supplierID);

            aSupplierLedger.ReceiveDate   = date;
            aSupplierLedger.SupplierID    = Convert.ToInt32(supplierID);
            aSupplierLedger.InvoiceNo     = invoiceNO;
            aSupplierLedger.Debit         = 0;
            aSupplierLedger.Credit        = totalAmount;
            aSupplier.SupplierPreviousDue = GetPreviousDue(totalAmount, supplierID);
            if (aSupplier.SupplierPreviousDue != 0)
            {
                aSupplierLedger.IsPreviousDue = 1;
            }
            else
            {
                aSupplierLedger.IsPreviousDue = 0;
            }

            db.SupplierLedger.Add(aSupplierLedger);
            db.SaveChanges();
        }
Example #15
0
 public abstract void MapSupplierLedgerEntity(ref SupplierLedger supplierLedger, SupplierLedgerView view);
Example #16
0
 public IFluentSupplierLedger DeleteSupplierLedger(SupplierLedger deleteObject)
 {
     unitOfWork.supplierLedgerRepository.DeleteObject(deleteObject);
     this.processStatus = CreateProcessStatus.Delete;
     return(this as IFluentSupplierLedger);
 }
Example #17
0
 public IFluentSupplierLedger AddSupplierLedger(SupplierLedger newObject)
 {
     unitOfWork.supplierLedgerRepository.AddObject(newObject);
     this.processStatus = CreateProcessStatus.Insert;
     return(this as IFluentSupplierLedger);
 }
Example #18
0
        public int InsertSupplierLedgerMasterData()
        {
            try
            {
                string query = "select * from ACM where slcd = 'SL'";

                DataTable dtSupplierLedgerMaster = dbConnection.GetData(query);

                List <SupplierLedger> listSupplierLedgerMaster = new List <SupplierLedger>();

                int _result = 0;

                using (PharmaDBEntities context = new PharmaDBEntities())
                {
                    var maxSupplierLedgerID = context.SupplierLedger.Count();

                    if (dtSupplierLedgerMaster != null && dtSupplierLedgerMaster.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dtSupplierLedgerMaster.Rows)
                        {
                            try
                            {
                                maxSupplierLedgerID++;

                                string supplierLedgerCode         = "S" + maxSupplierLedgerID.ToString().PadLeft(6, '0');
                                string originalSupplierLedgerCode = Convert.ToString(dr["ACNO"]).TrimEnd();
                                Common.supplierLedgerCodeMap.Add(new SupplierLedgerCodeMap()
                                {
                                    OriginalSupplierLedgerCode = originalSupplierLedgerCode, MappedSupplierLedgerCode = supplierLedgerCode
                                });

                                string areaCode           = Common.areaCodeMap.Where(p => p.OriginalAreaCode == Convert.ToString(dr["PAREA"]).TrimEnd()).FirstOrDefault().MappedAreaCode;
                                int    areaID             = context.PersonRouteMaster.Where(q => q.PersonRouteCode == areaCode).FirstOrDefault().PersonRouteID;
                                string purchaseLedgerCode = Common.accountLedgerCodeMap.Where(q => q.OriginalAccountLedgerCode == Convert.ToString(dr["PCODE"]).TrimEnd()).FirstOrDefault().MappedAccountLedgerCode;
                                int    purchaseTypeID     = context.AccountLedgerMaster.Where(p => p.AccountLedgerCode == purchaseLedgerCode).FirstOrDefault().AccountLedgerID;

                                SupplierLedger newSupplierLedgerMaster = new SupplierLedger()
                                {
                                    SupplierLedgerCode      = supplierLedgerCode,
                                    SupplierLedgerName      = Convert.ToString(dr["ACName"]).TrimEnd(),
                                    SupplierLedgerShortName = Convert.ToString(dr["Alt_name_1"]).TrimEnd(),
                                    SupplierLedgerShortDesc = Convert.ToString(dr["Alt_name_2"]).TrimEnd(),
                                    Address       = string.Concat(Convert.ToString(dr["ACAD1"]).TrimEnd(), " ", Convert.ToString(dr["ACAD2"]).TrimEnd(), " ", Convert.ToString(dr["ACAD3"]).TrimEnd()),
                                    ContactPerson = Convert.ToString(dr["ACAD4"]).TrimEnd(),
                                    Mobile        = Convert.ToString(dr["Mobile"]).TrimEnd(),
                                    //Pager = Convert.ToString(dr["Pager"]).TrimEnd(),
                                    //Fax = Convert.ToString(dr["Fax"]).TrimEnd(),
                                    OfficePhone    = Convert.ToString(dr["Telo"]).TrimEnd(),
                                    ResidentPhone  = Convert.ToString(dr["Telr"]).TrimEnd(),
                                    EmailAddress   = Convert.ToString(dr["Email"]).TrimEnd(),
                                    AreaId         = areaID,
                                    CreditDebit    = Convert.ToDecimal(dr["Abop"]) > 0 ? Convert.ToString(PharmaBusinessObjects.Common.Enums.TransType.D) : Convert.ToString(PharmaBusinessObjects.Common.Enums.TransType.C),
                                    DLNo           = "test", // Convert.ToString(dr["Stnol"]).TrimEnd(),
                                    OpeningBal     = Convert.ToDecimal(dr["Abop"]),
                                    TaxRetail      = Convert.ToString(dr["Vat"]).TrimEnd(),
                                    Status         = Convert.ToChar(dr["ACSTS"]) == '*' ? false : true,
                                    PurchaseTypeID = purchaseTypeID,
                                    CreatedBy      = "admin",
                                    CreatedOn      = DateTime.Now
                                };

                                listSupplierLedgerMaster.Add(newSupplierLedgerMaster);
                            }
                            catch (Exception)
                            {
                                log.Info("SuPPLIER LEDGER : Error in ACName --> " + Convert.ToString(dr["ACName"]).TrimEnd());
                            }
                        }
                    }

                    context.SupplierLedger.AddRange(listSupplierLedgerMaster);
                    _result = context.SaveChanges();

                    return(_result);
                }
            }
            catch (DbEntityValidationException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="purchaseReturn"></param>
        public void Add(PurchaseReturn purchaseReturn)
        {
            var flag = false;

            try
            {
                _unitOfWork.BeginTransaction();
                flag = true;
                var identity = (LoginIdentity)Thread.CurrentPrincipal.Identity;
                #region PurchaseReturn
                purchaseReturn.Id                  = GenerateAutoId(identity.CompanyId, identity.BranchId, "PurchaseReturn");
                purchaseReturn.Sequence            = GetAutoSequence();
                purchaseReturn.PurchaseReturnDate  = DateTime.Now;
                purchaseReturn.Active              = true;
                purchaseReturn.SynchronizationType = SynchronizationType.Server.ToString();
                purchaseReturn.CompanyId           = identity.CompanyId;
                purchaseReturn.BranchId            = identity.BranchId;
                purchaseReturn.AddedBy             = identity.Name;
                purchaseReturn.AddedDate           = DateTime.Now;
                purchaseReturn.AddedFromIp         = identity.IpAddress;
                _purchaseReturnRepository.Add(purchaseReturn);
                #endregion

                #region PurchaseReturn Products
                if (purchaseReturn.PurchaseReturnDetails != null)
                {
                    var sqnc     = GetAutoSequence("PurchaseReturnDetail");
                    int detailId = Convert.ToInt32(GenerateAutoId(purchaseReturn.CompanyId, purchaseReturn.BranchId, "PurchaseReturnDetail"));
                    foreach (var purchaseReturnDetail in purchaseReturn.PurchaseReturnDetails)
                    {
                        var productDb      = _productRepository.GetOne(x => x.Id == purchaseReturnDetail.ProductId);
                        var purchaseDetail = _purchaseDetailRepository.GetOne(r => r.Id == purchaseReturnDetail.PurchaseDetailId);
                        #region Purchase return detail
                        purchaseReturnDetail.Id               = detailId.ToString();
                        purchaseReturnDetail.Sequence         = sqnc;
                        purchaseReturnDetail.PurchaseReturnId = purchaseReturn.Id;
                        decimal alreadyReturnQty = GetAlreadyReturnQty(purchaseReturnDetail.PurchaseId, purchaseReturnDetail.ProductId);
                        purchaseReturnDetail.RemainingQuantity = purchaseReturnDetail.PurchaseQuantity - (alreadyReturnQty + purchaseReturnDetail.ReturnQuantity);
                        purchaseDetail.Returned = purchaseDetail.Quantity == alreadyReturnQty + purchaseReturnDetail.ReturnQuantity;
                        purchaseReturnDetail.ProductCategoryId           = productDb.ProductCategoryId;
                        purchaseReturnDetail.ProductSubCategoryId        = productDb.ProductSubCategoryId;
                        purchaseReturnDetail.ProductSubsidiaryCategoryId = productDb.ProductSubsidiaryCategoryId;
                        purchaseReturnDetail.UOMId   = productDb.UOMId;
                        purchaseReturnDetail.BrandId = productDb.BrandId;
                        purchaseReturnDetail.GradeId = productDb.GradeId;
                        purchaseReturnDetail.PurchaseReturnDetailDate = DateTime.Now;
                        purchaseReturnDetail.CompanyId           = identity.CompanyId;
                        purchaseReturnDetail.BranchId            = identity.BranchId;
                        purchaseReturnDetail.Active              = true;
                        purchaseReturnDetail.SynchronizationType = SynchronizationType.Server.ToString();
                        purchaseReturnDetail.AddedBy             = identity.Name;
                        purchaseReturnDetail.AddedDate           = DateTime.Now;
                        purchaseReturnDetail.AddedFromIp         = identity.IpAddress;
                        _purchaseReturnDetailRepository.Add(purchaseReturnDetail);
                        detailId++;
                        sqnc++;
                        #endregion
                    }
                }
                #endregion
                #region Supplier Ledger
                var supplier = _supplierRepository.GetOne(x => x.Id == purchaseReturn.SupplierId);
                if (!string.IsNullOrEmpty(supplier?.Id))
                {
                    var supplierLedger = new SupplierLedger
                    {
                        Id                  = GenerateAutoId(identity.CompanyId, identity.BranchId, "SupplierLedger"),
                        Sequence            = GetAutoSequence("SupplierLedger"),
                        CompanyId           = identity.CompanyId,
                        BranchId            = identity.BranchId,
                        PurchaseId          = purchaseReturn.Id,
                        TrackingNo          = GenerateTrackingNo(identity.CompanyId, identity.BranchId, "SupplierLedger"),
                        SupplierId          = supplier.Id,
                        SupplierPhone       = supplier.Phone1,
                        Particulars         = TransactionType.PurchaseReturn.ToString(),
                        TransactionType     = TransactionType.PurchaseReturn.ToString(),
                        TransactionDate     = DateTime.Now,
                        DebitAmount         = purchaseReturn.TotalAmount,
                        CreditAmount        = 0,
                        RunningBalance      = 0,
                        Active              = true,
                        SynchronizationType = SynchronizationType.Server.ToString(),
                        AddedBy             = identity.Name,
                        AddedDate           = DateTime.Now,
                        AddedFromIp         = identity.IpAddress
                    };
                    _supplierLedgerRepository.Add(supplierLedger);
                }
                #endregion
                _unitOfWork.SaveChanges();
                ChangePurchaseStatus(purchaseReturn.PurchaseId);
                ChangePurchaseReturnStatus(purchaseReturn.Id);
                flag = false;
                _unitOfWork.Commit();
                _rawSqlService.UpdateSupplierLedgerRunningBalance(supplier?.Id);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (flag)
                {
                    _unitOfWork.Rollback();
                }
            }
        }
        public ActionResult AddSupplierLedger(SupplierLedger model)
        {
            List <SupplierLedger> supplierLedger = new List <SupplierLedger>();

            if (model.SupplierID != 0)
            {
                if (model.ID <= 0)
                {
                    var aSupplier = db.Supplier.SingleOrDefault(x => x.SupplierID == model.SupplierID);

                    var totalDebit = db.SupplierLedger.Where(c => c.SupplierID == model.SupplierID)
                                     .GroupBy(c => c.SupplierID).Select(g => new { dabit = g.Sum(c => c.Debit) }).First();

                    var totalCredit = db.SupplierLedger.Where(c => c.SupplierID == model.SupplierID)
                                      .GroupBy(c => c.SupplierID).Select(g => new { credit = g.Sum(c => c.Credit) }).First();


                    double?previousDue = totalCredit.credit - (totalDebit.dabit + model.Debit);

                    aSupplier.SupplierPreviousDue = previousDue;

                    if (previousDue == 0)
                    {
                        model.IsPreviousDue = 0;
                    }
                    else
                    {
                        model.IsPreviousDue = 1;
                    }

                    model.Credit = 0;
                    db.SupplierLedger.Add(model);
                    db.SaveChanges();
                    ViewBag.Message = 1;
                    supplierLedger  = db.SupplierLedger.ToList();
                }
                else
                {
                    var aSupplier       = db.Supplier.SingleOrDefault(x => x.SupplierID == model.SupplierID);
                    var aSupplierLedger = db.SupplierLedger.SingleOrDefault(x => x.ID == model.ID);
                    aSupplierLedger.Debit = model.Debit;
                    db.SaveChanges();

                    var totalDebit = db.SupplierLedger.Where(c => c.SupplierID == model.SupplierID)
                                     .GroupBy(c => c.SupplierID).Select(g => new { dabit = g.Sum(c => c.Debit) }).First();

                    var totalCredit = db.SupplierLedger.Where(c => c.SupplierID == model.SupplierID)
                                      .GroupBy(c => c.SupplierID).Select(g => new { credit = g.Sum(c => c.Credit) }).First();

                    double?previousDue = totalCredit.credit - totalDebit.dabit;

                    aSupplier.SupplierPreviousDue = previousDue;

                    if (previousDue == 0)
                    {
                        aSupplierLedger.IsPreviousDue = 0;
                    }
                    else
                    {
                        aSupplierLedger.IsPreviousDue = 1;
                    }


                    aSupplierLedger.SupplierID = model.SupplierID;

                    aSupplierLedger.ReceiveDate = model.ReceiveDate;

                    aSupplierLedger.Debit = model.Debit;

                    aSupplierLedger.Remarks = model.Remarks;


                    db.SaveChanges();

                    ViewBag.Message = 1;

                    supplierLedger = db.SupplierLedger.ToList();
                }
            }
            else
            {
                ViewBag.Message = 0;
                supplierLedger  = db.SupplierLedger.ToList();
            }

            ViewBag.supplierList = db.Supplier.ToList();

            return(View(supplierLedger));
        }