Example #1
0
        public CustomerLedger UpdateCustomerLedger(CustomerLedger customerLedger)
        {
            _context.CustomerLedgers.Update(customerLedger);
            _context.SaveChanges();

            return(_context.CustomerLedgers.FirstOrDefault(c => c.Id == customerLedger.Id));
        }
Example #2
0
        private CustomerLedger MapToEntity(CustomerLedgerView inputObject)
        {
            Mapper         mapper    = new Mapper();
            CustomerLedger outObject = mapper.Map <CustomerLedger>(inputObject);

            return(outObject);
        }
        private void CustomerLedgerCreate(CustomerLedger aCustomerLedger)
        {
            var aCustomer = db.Customer.SingleOrDefault(p => p.CustomerID == aCustomerLedger.CustomerID);

            if (aCustomer.CustomerName != "CASH")
            {
                aCustomer.PreviousDue = GetPriviousDue(aCustomerLedger);
                if (aCustomer.PreviousDue != 0)
                {
                    aCustomerLedger.IsPreviousDue = 1;
                }
                else
                {
                    aCustomerLedger.IsPreviousDue = 0;
                }

                db.CustomerLedger.Add(aCustomerLedger);
                db.SaveChanges();
            }
            else
            {
                db.CustomerLedger.Add(aCustomerLedger);
                db.SaveChanges();
            }
        }
Example #4
0
        public async Task <IFluentCustomerLedger> CreateCustomerLedgerByInvoiceView(InvoiceView invoiceView)
        {
            Task <AccountReceivable> acctRecLookupTask = unitOfWork.accountReceivableRepository.GetEntityByPurchaseOrderId(invoiceView.PurchaseOrderId);
            Task <Customer>          customerTask      = unitOfWork.customerRepository.GetEntityById(invoiceView.CustomerId);

            Task.WaitAll(acctRecLookupTask, customerTask);

            Task <GeneralLedger> generalLedgerTask = unitOfWork.generalLedgerRepository.GetEntityByDocNumber(acctRecLookupTask.Result?.DocNumber, "OV");

            Task.WaitAll(generalLedgerTask);

            CustomerLedger customerLedger = new CustomerLedger {
                CustomerId          = invoiceView.CustomerId ?? 0,
                GeneralLedgerId     = generalLedgerTask.Result?.GeneralLedgerId ?? 0,
                InvoiceId           = invoiceView.InvoiceId ?? 0,
                AccountReceivableId = acctRecLookupTask.Result?.AccountReceivableId ?? 0,
                DocNumber           = generalLedgerTask.Result?.DocNumber ?? 0,
                DocType             = generalLedgerTask.Result?.DocType,
                Amount               = invoiceView.Amount,
                Gldate               = generalLedgerTask.Result?.Gldate,
                AccountId            = generalLedgerTask.Result?.AccountId ?? 0,
                CreatedDate          = DateTime.Now,
                AddressId            = customerTask.Result.AddressId,
                Comment              = generalLedgerTask.Result?.Comment,
                DebitAmount          = generalLedgerTask.Result?.DebitAmount,
                CreditAmount         = generalLedgerTask.Result?.CreditAmount,
                FiscalPeriod         = generalLedgerTask.Result?.FiscalPeriod ?? 0,
                FiscalYear           = generalLedgerTask.Result?.FiscalYear ?? 0,
                CheckNumber          = generalLedgerTask.Result?.CheckNumber,
                CustomerLedgerNumber = (await unitOfWork.nextNumberRepository.GetNextNumber(TypeOfCustomerLedger.CustomerLedgerNumber.ToString())).NextNumberValue
            };

            AddCustomerLedger(customerLedger);
            return(this as IFluentCustomerLedger);
        }
Example #5
0
        public void UpdateSaleDiscount(PharmaBusinessObjects.Common.Enums.SaleEntryChangeType changeType, decimal discount, decimal specialDiscount, decimal volumeDiscount, string itemCode, string customerCode)
        {
            using (PharmaDBEntities context = new PharmaDBEntities())
            {
                CustomerLedger ledger = context.CustomerLedger.FirstOrDefault(p => p.CustomerLedgerCode == customerCode);
                ItemMaster     master = context.ItemMaster.FirstOrDefault(p => p.ItemCode == itemCode);

                if (changeType == PharmaBusinessObjects.Common.Enums.SaleEntryChangeType.CompanyWiseChange)
                {
                    var compItem = context.CustomerCompanyDiscountRef.Where(p => p.CustomerLedgerID == ledger.CustomerLedgerId && p.CompanyID == master.CompanyID && p.ItemID == null).FirstOrDefault();
                    if (compItem != null)
                    {
                        compItem.Normal = discount;
                    }
                }
                else
                {
                    var disItem = context.CustomerCompanyDiscountRef.Where(p => p.CustomerLedgerID == ledger.CustomerLedgerId && p.CompanyID == master.CompanyID && p.ItemID == master.ItemID).FirstOrDefault();
                    if (disItem != null)
                    {
                        disItem.Normal = discount;
                    }
                    master.SpecialDiscount = specialDiscount;
                }

                context.SaveChanges();
            }
        }
Example #6
0
 private void AddSubtotal(List <decimal> subtotal, CustomerLedger ledger)
 {
     subtotal[(int)SubtotalField.BillingAmount]     += ledger.BillingAmount ?? 0M;
     subtotal[(int)SubtotalField.BillingSlipAmount] += ledger.SlipTotal ?? 0M;
     subtotal[(int)SubtotalField.ReceiptAmount]     += ledger.ReceiptAmount ?? 0M;
     subtotal[(int)SubtotalField.MatchingAmount]    += ledger.MatchingAmount ?? 0M;
 }
Example #7
0
 private void SetSubtotal(List <decimal> subtotal, CustomerLedger ledger)
 {
     ledger.BillingAmount  = subtotal[(int)SubtotalField.BillingAmount];
     ledger.SlipTotal      = subtotal[(int)SubtotalField.BillingSlipAmount];
     ledger.ReceiptAmount  = subtotal[(int)SubtotalField.ReceiptAmount];
     ledger.MatchingAmount = subtotal[(int)SubtotalField.MatchingAmount];
 }
Example #8
0
 private bool IsSameYearMonth(DateTime yearMonth, CustomerLedger next, int closingDay, out DateTime nextYM)
 {
     nextYM = new DateTime(0);
     if (next == null)
     {
         return(false);
     }
     ParseYearMonth(next, closingDay, out nextYM);
     return(yearMonth.Equals(nextYM));
 }
Example #9
0
 public ActionResult CustomerLedger_Init()
 {
     using (FATContainer dataContainer = new FATContainer())
     {
         CustomerLedger clInfo = dataContainer.CustomerLedger.Create();
         clInfo.TchNodeID = Convert.ToInt32(RouteData.Values["id"]);
         TeachingNode tchNode = dataContainer.TeachingNode.FirstOrDefault(node => node.Row_ID == clInfo.TchNodeID);
         clInfo.TchRoutineID = tchNode.RoutineID;
         return(View(clInfo));
     }
 }
        private double?GetPriviousDue(CustomerLedger aCustomerLedger)
        {
            var totalDebit = db.CustomerLedger.Where(c => c.CustomerID == aCustomerLedger.CustomerID)
                             .GroupBy(c => c.CustomerID).Select(g => new { debit = g.Sum(c => c.Debit) }).First();

            var totalCredit = db.CustomerLedger.Where(c => c.CustomerID == aCustomerLedger.CustomerID)
                              .GroupBy(c => c.CustomerID).Select(g => new { credit = g.Sum(c => c.Credit) }).First();

            double?previousDue = (totalDebit.debit + aCustomerLedger.Debit) - (totalCredit.credit + aCustomerLedger.Credit);

            return(previousDue);
        }
Example #11
0
 public ActionResult CustomerLedger_GetTemplate()
 {
     using (FATContainer dataContainer = new FATContainer())
     {
         JsonResult     result = new JsonResult();
         CustomerLedger clInfo = dataContainer.CustomerLedger.Create();
         clInfo.TimeMark    = DateTime.Now;
         clInfo.BalanceTime = DateTime.Now;
         result.Data        = clInfo;
         return(result);
     }
 }
Example #12
0
        public ActionResult CustomerLedger_Insert(CustomerLedger info)
        {
            using (FATContainer dataContainer = new FATContainer())
            {
                dataContainer.CustomerLedger.Add(info);
                dataContainer.SaveChanges();

                JsonResult result = new JsonResult();
                result.Data = info;
                return(result);
            }
        }
Example #13
0
        private void ParseYearMonth(CustomerLedger ledger, int closingDay, out DateTime yearMonth)
        {
            var ymd = ledger.RecordedAt.Value;

            if (closingDay <= 27 && closingDay < ymd.Day &&
                !(ymd.Year == 9999 && ymd.Month == 12))
            {
                ymd = ymd.AddMonths(1);
            }
            yearMonth = new DateTime(ymd.Year, ymd.Month,
                                     closingDay != 99 ? closingDay : DateTime.DaysInMonth(ymd.Year, ymd.Month));
        }
Example #14
0
        public async Task <CustomerLedger> CreateCustomerLedger(CustomerLedger customerLedger)
        {
            try{
                await _context.CustomerLedgers.AddAsync(customerLedger);

                await _context.SaveChangesAsync();

                return(customerLedger);
            }
            catch (Exception) {}

            return(null);
        }
Example #15
0
        public ActionResult CustomerLedger_Update(CustomerLedger info)
        {
            using (FATContainer dataContainer = new FATContainer())
            {
                CustomerLedger existedInfo = dataContainer.CustomerLedger.FirstOrDefault(item => item.Row_ID == info.Row_ID);
                dataContainer.Entry <CustomerLedger>(existedInfo).CurrentValues.SetValues(info);
                dataContainer.SaveChanges();

                JsonResult result = new JsonResult();
                result.Data = info;
                return(result);
            }
        }
Example #16
0
        public ActionResult CustomerLedger_Delete(int glRowID)
        {
            using (FATContainer dataContainer = new FATContainer())
            {
                CustomerLedger clInfo = dataContainer.CustomerLedger.FirstOrDefault(item => item.Row_ID == glRowID);
                dataContainer.CustomerLedger.Remove(clInfo);
                dataContainer.SaveChanges();

                JsonResult result = new JsonResult();
                result.Data = string.Empty;
                return(result);
            }
        }
Example #17
0
        public async Task <IActionResult> CreateCustomerLedger([FromBody] CustomerLedger customerLedger)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var customer = await _repository.CreateCustomerLedger(customerLedger);

            if (customer == null)
            {
                return(BadRequest("Failed to save the customer ledger"));
            }
            return(Ok(customerLedger));
        }
Example #18
0
        public IActionResult UpdateCustomer([FromBody] CustomerLedger customerLedger)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var customer = _repository.UpdateCustomerLedger(customerLedger);

            if (customer == null)
            {
                return(BadRequest("Failed to save the customer"));
            }
            return(Created("Successfully Updated the customer", customer));
        }
Example #19
0
        public ActionResult EditCustomerLedger(string CustomerId)
        {
            int id     = Convert.ToInt32(CustomerId);
            var select = db.CustomerLedger.Where(a => a.ID == id).First();

            var            due             = db.Customer.Where(a => a.CustomerID == select.CustomerID).First();
            CustomerLedger aCustomerLedger = new CustomerLedger()
            {
                ID          = select.ID,
                CustomerID  = select.CustomerID,
                ReceiveDate = select.ReceiveDate,
                PreviouaDue = due.PreviousDue,
                Credit      = select.Credit,
                Remarks     = select.Remarks
            };

            return(Json(aCustomerLedger, JsonRequestBehavior.AllowGet));
        }
Example #20
0
 public CustomerLedgerView(CustomerLedger CustomerLedger)
 {
     this.CustomerLedgerId = CustomerLedger.CustomerLedgerId;
     this.CustomerId       = CustomerLedger.CustomerId;
     this.CustomerName     = CustomerLedger.Customer.AddressBook.Name;
     this.InvoiceId        = CustomerLedger.InvoiceId;
     this.AcctRecId        = CustomerLedger.AcctRecId;
     this.DocNumber        = CustomerLedger.DocNumber;
     this.DocType          = CustomerLedger.DocType;
     this.Amount           = CustomerLedger.Amount ?? 0;
     this.GLDate           = CustomerLedger.GLDate ?? DateTime.Now.Date;
     this.CreatedDate      = CustomerLedger.CreatedDate ?? DateTime.Now.Date;
     this.AccountId        = CustomerLedger.AccountId;
     this.AddressId        = CustomerLedger.AddressId;
     this.Comment          = CustomerLedger.Comment;
     this.DebitAmount      = CustomerLedger.DebitAmount;
     this.CreditAmount     = CustomerLedger.CreditAmount;
     this.FiscalPeriod     = CustomerLedger.FiscalPeriod;
     this.FiscalYear       = CustomerLedger.FiscalYear;
     this.GeneralLedgerId  = CustomerLedger.GeneralLedgerId;
 }
Example #21
0
        public IFluentCustomerLedger CreateEntityByView(CustomerLedgerView view)
        {
            try
            {
                Task <CustomerLedger> queryTask = Task.Run(async() => await unitOfWork.customerLedgerRepository.FindEntityByGeneralLedgerId(view.GeneralLedgerId));
                Task.WaitAll(queryTask);


                if (queryTask.Result == null)
                {
                    CustomerLedger customerLedger = MapToEntity(view);
                    //applicationViewFactory.MapCustomerLedgerEntity(ref customerLedger, view);


                    AddCustomerLedger(customerLedger);

                    return(this as IFluentCustomerLedger);
                }
                processStatus = CreateProcessStatus.AlreadyExists;
                return(this as IFluentCustomerLedger);
            }
            catch (Exception ex)
            { throw new Exception("CreateEntityFromView", ex); }
        }
Example #22
0
 public IFluentCustomerLedger AddCustomerLedger(CustomerLedger newObject)
 {
     unitOfWork.customerLedgerRepository.AddObject(newObject);
     this.processStatus = CreateProcessStatus.Insert;
     return(this as IFluentCustomerLedger);
 }
Example #23
0
 public IFluentCustomerLedger DeleteCustomerLedger(CustomerLedger deleteObject)
 {
     unitOfWork.customerLedgerRepository.DeleteObject(deleteObject);
     this.processStatus = CreateProcessStatus.Delete;
     return(this as IFluentCustomerLedger);
 }
Example #24
0
        public ActionResult AppendCase(TeachingRoutine routine)
        {
            using (FATContainer dataContainer = new FATContainer())
            {
                dataContainer.TeachingRoutine.Add(routine);
                dataContainer.SaveChanges();

                var tempateNodeList = from node in dataContainer.TemplateNode
                                      where node.RoutineID == routine.TmpRoutineID
                                      orderby node.NodeIndex
                                      select node;
                List <TeachingNode> tchNodeList = new List <TeachingNode>();
                foreach (TemplateNode tmpNode in tempateNodeList)
                {
                    TeachingNode newNode = new TeachingNode()
                    {
                        CurrStatus = 0, RelTmpNode = tmpNode, RoutineID = routine.Row_ID, TmpNodeID = tmpNode.Row_ID
                    };
                    tchNodeList.Add(newNode);
                    dataContainer.TeachingNode.Add(newNode);
                }
                dataContainer.SaveChanges();

                string currPhaseName = string.Empty;
                foreach (TeachingNode tchNode in tchNodeList)
                {
                    switch (tchNode.NodeTag)
                    {
                    case "Guide":
                    {
                        currPhaseName = tchNode.NodeName;
                        RoutineGroup group = dataContainer.RoutineGroup.Create();
                        group.GroupText    = string.Empty;
                        group.GroupIdx     = tchNode.GroupIdx;
                        group.TchRoutineID = routine.Row_ID;
                        group.RoutineDesc  = tchNode.GroupIdx + "." + currPhaseName;
                        group.RoutineIntro = string.Empty;
                        dataContainer.RoutineGroup.Add(group);
                        break;
                    }

                        #region common node
                    case "DetailedLedger":
                    {
                        for (int i = 0; i <= tchNode.RelTmpNode.RequireRecord - 1; i++)
                        {
                            DetailedLedger info = dataContainer.DetailedLedger.Create();
                            info.TchNodeID    = tchNode.Row_ID;
                            info.TchRoutineID = routine.Row_ID;
                            info.RoutineDesc  = tchNode.GroupIdx + "." + currPhaseName;
                            info.TimeMark     = DateTime.Now;
                            dataContainer.DetailedLedger.Add(info);
                        }
                        break;
                    }

                    case "CashJournal":
                    {
                        for (int i = 0; i <= tchNode.RelTmpNode.RequireRecord - 1; i++)
                        {
                            CashJournal info = dataContainer.CashJournal.Create();
                            info.TchNodeID    = tchNode.Row_ID;
                            info.TchRoutineID = routine.Row_ID;
                            info.RoutineDesc  = tchNode.GroupIdx + "." + currPhaseName;
                            info.TimeMark     = DateTime.Now;
                            dataContainer.CashJournal.Add(info);
                        }
                        break;
                    }

                    case "OuterSubject":
                    {
                        for (int i = 0; i <= tchNode.RelTmpNode.RequireRecord - 1; i++)
                        {
                            OuterSubject info = dataContainer.OuterSubject.Create();
                            info.TchNodeID    = tchNode.Row_ID;
                            info.TchRoutineID = routine.Row_ID;
                            info.RoutineDesc  = tchNode.GroupIdx + "." + currPhaseName;
                            info.TimeMark     = DateTime.Now;
                            dataContainer.OuterSubject.Add(info);
                        }
                        break;
                    }

                    case "CustomerLedger":
                    {
                        for (int i = 0; i <= tchNode.RelTmpNode.RequireRecord - 1; i++)
                        {
                            CustomerLedger info = dataContainer.CustomerLedger.Create();
                            info.TchNodeID    = tchNode.Row_ID;
                            info.TchRoutineID = routine.Row_ID;
                            info.RoutineDesc  = tchNode.GroupIdx + "." + currPhaseName;
                            info.TimeMark     = DateTime.Now;
                            info.BalanceTime  = DateTime.Now;
                            dataContainer.CustomerLedger.Add(info);
                        }
                        break;
                    }

                    case "GeneralLedger":
                    {
                        for (int i = 0; i <= tchNode.RelTmpNode.RequireRecord - 1; i++)
                        {
                            GeneralLedger info = dataContainer.GeneralLedger.Create();
                            info.TchNodeID    = tchNode.Row_ID;
                            info.TchRoutineID = routine.Row_ID;
                            info.RoutineDesc  = tchNode.GroupIdx + "." + currPhaseName;
                            info.TimeMark     = DateTime.Now;
                            dataContainer.GeneralLedger.Add(info);
                        }
                        break;
                    }

                    default:
                    {
                        if (tchNode.RelTmpNode.NodeType == "SpecialNode")
                        {
                            for (int i = 0; i <= tchNode.RelTmpNode.RequireRecord - 1; i++)
                            {
                                SubjectItem info = dataContainer.SubjectItem.Create();
                                info.TchNodeID    = tchNode.Row_ID;
                                info.TchRoutineID = routine.Row_ID;
                                info.RoutineDesc  = tchNode.GroupIdx + "." + currPhaseName;
                                dataContainer.SubjectItem.Add(info);
                            }
                        }
                        break;
                    }
                        #endregion
                        #region special node


                        #endregion
                    }
                }

                dataContainer.SaveChanges();
            }
            JsonResult result = new JsonResult();
            result.Data = routine;
            return(result);
        }
Example #25
0
        public async Task <IEnumerable <CustomerLedger> > GetAsync(CustomerLedgerSearch searchOption, CancellationToken token, IProgressNotifier notifier)
        {
            var ledgers  = (await ledgerQueryProcessor.GetAsync(searchOption, token, notifier)).ToArray();
            var balances = (await ledgerQueryProcessor.GetBalancesAsync(searchOption, token, notifier))
                           .ToDictionary(x => x.Key, x => x.Value);

            SortedList <int, long[]> keys = null;

            if (searchOption.DisplayMatchingSymbol)
            {
                var items = await ledgerQueryProcessor.GetKeysAsync(searchOption, token, notifier);

                keys = new SortedList <int, long[]>(
                    items.GroupBy(x => x.Key)
                    .ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToArray()));
            }
            var         dicKeys        = new Dictionary <long, int>();
            List <long> balanceKeys    = null;
            List <long> currentKeys    = null;
            var         monthlyKeys    = new List <long>();
            var         carryOverKeys  = new List <long>();
            var         symbol         = string.Empty;
            var         carryOverIndex = 0;

            var     balance    = 0M;
            decimal?slipTotal  = null;
            var     closingDay = searchOption.YearMonthTo.Day;

            if (closingDay > 27)
            {
                closingDay = 99;
            }
            DateTime yearMonth;
            var      nextYM    = new DateTime(0);
            var      monthSub  = GetSubtotalList();
            var      parentSub = GetSubtotalList();

            var result = new List <CustomerLedger>();

            var parentCustomerId = 0;

            for (var i = 0; i < ledgers.Length; i++)
            {
                var ledger     = ledgers[i];
                var nextLedger = (i + 1 < ledgers.Length) ? ledgers[i + 1] : null;
                var newParent  = ledger.ParentCustomerId != parentCustomerId;

                ParseYearMonth(ledger, closingDay, out yearMonth);
                ledger.YearMonth = yearMonth;
                if (newParent)
                {
                    if (searchOption.DisplayMatchingSymbol)
                    {
                        balanceKeys = keys.ContainsKey(ledger.ParentCustomerId)
                            ? keys[ledger.ParentCustomerId].ToList() : new List <long>();
                        monthlyKeys.Clear();
                        carryOverKeys.Clear();
                    }
                    balance = balances.ContainsKey(ledger.ParentCustomerId)
                        ? balances[ledger.ParentCustomerId] : 0M;
                    var carryOver = new CustomerLedger();
                    carryOver.ParentCustomerId   = ledger.ParentCustomerId;
                    carryOver.ParentCustomerCode = ledger.ParentCustomerCode;
                    carryOver.ParentCustomerName = ledger.ParentCustomerName;
                    carryOver.CurrencyCode       = ledger.CurrencyCode;
                    carryOver.RecordType         = CustomerLedger.RecordTypeAlias.CarryOverRecord;
                    carryOver.YearMonth          = yearMonth;
                    carryOver.RemainAmount       = balance;
                    result.Add(carryOver);
                    if (searchOption.DisplayMatchingSymbol)
                    {
                        carryOverIndex = result.IndexOf(carryOver);
                    }
                }

                parentCustomerId = ledger.ParentCustomerId;

                if (searchOption.DisplaySlipTotal &&
                    ledger.DataType == 1 &&
                    ledger.BillingAmount.HasValue)
                {
                    slipTotal = (slipTotal ?? 0M) + ledger.BillingAmount.Value;
                }
                var setSlipTotal = searchOption.DisplaySlipTotal && ledger.DataType == 1 &&
                                   (nextLedger == null ||
                                    ledger.DataType != nextLedger.DataType ||
                                    ledger.BillingInputId != nextLedger.BillingInputId ||
                                    ledger.RecordedAt != nextLedger.RecordedAt);

                if (searchOption.DisplayMatchingSymbol && ledger.DataType != 2)
                {
                    currentKeys = ledger.GetKeys();
                    ConvertKeysToSymbols(dicKeys, currentKeys, ref symbol);
                }
                if (ledger.DataType == 1 && ledger.BillingAmount.HasValue)
                {
                    balance += ledger.BillingAmount.Value;
                }
                if (ledger.DataType == 2 && ledger.ReceiptAmount.HasValue && searchOption.UseReceipt)
                {
                    balance -= ledger.ReceiptAmount.Value;
                }
                if (ledger.DataType == 3 && ledger.MatchingAmount.HasValue && !searchOption.UseReceipt)
                {
                    balance -= ledger.MatchingAmount.Value;
                }

                if (setSlipTotal)
                {
                    ledger.SlipTotal = slipTotal;
                    slipTotal        = null;
                }
                AddSubtotal(monthSub, ledger);
                AddSubtotal(parentSub, ledger);

                if (ledger.DataType == 1 && (!searchOption.DisplaySlipTotal || setSlipTotal) ||
                    ledger.DataType == 2 && searchOption.UseReceipt ||
                    ledger.DataType == 3 && !searchOption.UseReceipt)
                {
                    ledger.RemainAmount = balance;
                }

                if (searchOption.DisplayMatchingSymbol)
                {
                    if (ledger.DataType == 1)
                    {
                        ledger.MatchingSymbolBilling = symbol;
                        foreach (var key in currentKeys)
                        {
                            if (!balanceKeys.Contains(key) &&
                                !monthlyKeys.Contains(key))
                            {
                                monthlyKeys.Add(key);
                            }
                        }
                    }
                    if (ledger.DataType == 3)
                    {
                        ledger.MatchingSymbolReceipt = symbol;
                        foreach (var key in currentKeys)
                        {
                            if (balanceKeys.Contains(key) &&
                                !carryOverKeys.Contains(key))
                            {
                                carryOverKeys.Add(key);
                            }
                        }
                    }
                }
                ledger.RecordType = CustomerLedger.RecordTypeAlias.DataRecord;
                ledger.Truncate(searchOption.UnitPrice);
                result.Add(ledger);

                var sameYM     = IsSameYearMonth(yearMonth, nextLedger, closingDay, out nextYM);
                var sameParent = nextLedger?.ParentCustomerId == ledger.ParentCustomerId;


                if (!sameYM)
                {
                    var sub = new CustomerLedger();
                    sub.ParentCustomerId   = ledger.ParentCustomerId;
                    sub.ParentCustomerCode = ledger.ParentCustomerCode;
                    sub.ParentCustomerName = ledger.ParentCustomerName;
                    sub.CurrencyCode       = ledger.CurrencyCode;
                    sub.YearMonth          = yearMonth;
                    sub.RecordType         = CustomerLedger.RecordTypeAlias.MonthlySubtotalRecord;
                    sub.RemainAmount       = balance;
                    //sub.Caption = $"{yearMont:MM}月合計";
                    SetSubtotal(monthSub, sub);
                    ClearSubtotal(monthSub);
                    sub.Truncate(searchOption.UnitPrice);
                    result.Add(sub);
                }

                if (!sameYM && sameParent &&
                    searchOption.IsPrint && searchOption.RequireMonthlyBreak)
                {
                    var carryOver = new CustomerLedger();
                    carryOver.ParentCustomerId   = ledger.ParentCustomerId;
                    carryOver.ParentCustomerCode = ledger.ParentCustomerCode;
                    carryOver.ParentCustomerName = ledger.ParentCustomerName;
                    carryOver.CurrencyCode       = ledger.CurrencyCode;
                    carryOver.YearMonth          = nextYM;
                    carryOver.RecordType         = CustomerLedger.RecordTypeAlias.CarryOverRecord;
                    carryOver.RemainAmount       = balance;
                    //carryOver.Caption = "繰越";
                    carryOver.Truncate(searchOption.UnitPrice);
                    result.Add(carryOver);
                    if (searchOption.DisplayMatchingSymbol)
                    {
                        ConvertKeysToSymbols(dicKeys, carryOverKeys, ref symbol);
                        result[carryOverIndex].MatchingSymbolBilling = symbol;

                        foreach (var key in monthlyKeys)
                        {
                            if (!balanceKeys.Contains(key))
                            {
                                balanceKeys.Add(key);
                            }
                        }
                        monthlyKeys.Clear();
                        carryOverKeys.Clear();
                        carryOverIndex = result.IndexOf(carryOver);
                    }
                }

                if (!sameParent)
                {
                    var sub = new CustomerLedger();
                    sub.ParentCustomerId   = ledger.ParentCustomerId;
                    sub.ParentCustomerCode = ledger.ParentCustomerCode;
                    sub.ParentCustomerName = ledger.ParentCustomerName;
                    sub.CurrencyCode       = ledger.CurrencyCode;
                    sub.YearMonth          = yearMonth;
                    sub.RecordType         = CustomerLedger.RecordTypeAlias.TotalRecord;
                    sub.RemainAmount       = balance;
                    //sub.Caption = "総合計";
                    SetSubtotal(parentSub, sub);
                    ClearSubtotal(parentSub);
                    sub.Truncate(searchOption.UnitPrice);
                    result.Add(sub);
                    if (searchOption.DisplayMatchingSymbol)
                    {
                        ConvertKeysToSymbols(dicKeys, carryOverKeys, ref symbol);
                        result[carryOverIndex].MatchingSymbolBilling = symbol;
                    }
                }
            }
            notifier?.UpdateState();
            return(result);
        }
        public JsonResult Save(List <Sale> List)
        {
            var            flag            = 0;
            CustomerLedger aCustomerLedger = new CustomerLedger();

            aCustomerLedger.Debit = 0;

            foreach (var item in List)
            {
                Sale aSale = new Sale();

                aSale.CompanyID          = item.CompanyID = GetCompanyID(item.CompanyName, item.SalesCustomerName);
                aSale.PaymentType        = item.PaymentType = 1;
                aSale.SalesCustomerID    = item.SalesCustomerID = GetCustomerID(item.CompanyName, item.SalesCustomerName);
                aSale.SalesPurchasePrice = item.SalesPurchasePrice = GetPurchasePrice(item.SalesProductID);
                aSale.SalesVatRate       = item.SalesVatRate = 5;
                aSale.SalesSoldBy        = item.SalesSoldBy = "admin";


                aSale.Reference              = item.Reference;
                aSale.SalesCustomerName      = item.SalesCustomerName;
                aSale.SalesDate              = item.SalesDate;
                aSale.SalesNo                = item.SalesNo;
                aSale.SalesPuechaseBy        = item.SalesPuechaseBy;
                aSale.SalesPurchaseByContact = item.SalesPurchaseByContact;
                aSale.SalesReceivedAmount    = item.SalesReceivedAmount;
                if (aSale.SalesReceivedAmount == null)
                {
                    aSale.SalesReceivedAmount = 0;
                }
                aSale.SalesRemarks = item.SalesRemarks;

                aSale.SalesProductDiscount = item.SalesProductDiscount;
                aSale.SalesProductID       = item.SalesProductID;
                aSale.SalesQuantity        = item.SalesQuantity;
                aSale.SalesSalePrice       = item.SalesSalePrice;
                aSale.SalesTime            = item.SalesTime;
                aSale.SalesTotal           = item.Total;


                double?vatTotal = (((item.Total * 5) / 100) + item.Total);


                aSale.SalesVatTotal = vatTotal;

                if (item.SalesChangeAmount != null)
                {
                    aSale.SalesChangeAmount = item.SalesChangeAmount;
                }
                else
                {
                    aSale.SalesChangeAmount = -(item.DueAmount);
                }

                StokeDecrement(item.SalesProductID, item.SalesQuantity);

                //For Customer Ledger

                aCustomerLedger.InvoiceNo = item.SalesNo;

                aCustomerLedger.Debit += vatTotal;

                if (item.SalesReceivedAmount != null)
                {
                    if (item.SalesReceivedAmount < vatTotal)
                    {
                        aCustomerLedger.Credit = item.SalesReceivedAmount;
                    }
                    else
                    {
                        aCustomerLedger.Credit = vatTotal;
                    }
                }
                else
                {
                    aCustomerLedger.Credit = 0;
                }
                aCustomerLedger.CustomerID  = Convert.ToInt32(aSale.SalesCustomerID);
                aCustomerLedger.ReceiveDate = item.SalesDate;

                db.Sale.Add(aSale);
                int i = db.SaveChanges();
                if (i > 0)
                {
                    flag = 1;
                }
            }

            CustomerLedgerCreate(aCustomerLedger);
            //ExportSaleInvoice(List);
            return(Json(flag, JsonRequestBehavior.AllowGet));
        }
Example #27
0
        public ActionResult AddCustomer(Customer customer)
        {
            CustomerLedger  aCustomerLedger = new CustomerLedger();
            List <Customer> customers       = new List <Customer>();

            if (customer.CustomerID <= 0 && customer.CustomerName != null && customer.Phone != null)
            {
                var PhoneExist = db.Customer.Where(c => c.Phone == customer.Phone).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.Customer.Max(x => (int?)x.CustomerID);

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

                    if (customer.PreviousDue == null || customer.PreviousDue == 0)
                    {
                        customer.PreviousDue          = 0;
                        aCustomerLedger.IsPreviousDue = 0;
                    }
                    else
                    {
                        aCustomerLedger.IsPreviousDue = 1;
                    }
                    var nowDate = DateTime.Now.ToString("M/d/yyyy");
                    var date    = Convert.ToDateTime(nowDate);
                    aCustomerLedger.ReceiveDate = date;
                    aCustomerLedger.InvoiceNo   = "Previous Due";
                    aCustomerLedger.Remarks     = "Previous Due";
                    aCustomerLedger.Debit       = customer.PreviousDue;
                    aCustomerLedger.Credit      = 0;
                    aCustomerLedger.CustomerID  = Convert.ToInt32(id);

                    customer.GroupName   = groupName.Name;
                    customer.CompanyName = companyName.Name;

                    db.Customer.Add(customer);
                    db.CustomerLedger.Add(aCustomerLedger);
                    db.SaveChanges();
                    customers       = db.Customer.ToList();
                    ViewBag.Message = 1;
                }
                else
                {
                    customers       = db.Customer.ToList();
                    ViewBag.Message = 0;
                }
            }
            else
            {
                customers       = db.Customer.ToList();
                ViewBag.Message = 2;
            }
            ViewBag.group = db.Group.ToList();
            return(View(customers));
        }
Example #28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="customer"></param>
        public void Update(Customer customer)
        {
            var flag = false;

            try
            {
                Check(customer);
                _unitOfWork.BeginTransaction();
                flag = true;
                #region Customer
                var identity   = (LoginIdentity)Thread.CurrentPrincipal.Identity;
                var customerDb = _customerRepository.GetOne(customer.Id);
                if (string.IsNullOrEmpty(customer.CompanyId))
                {
                    customer.CompanyId = identity.CompanyId;
                }
                if (string.IsNullOrEmpty(customer.BranchId))
                {
                    customer.BranchId = identity.BranchId;
                }
                customer.SynchronizationType = customerDb.SynchronizationType;
                customer.AddedBy             = customerDb.AddedBy;
                customer.AddedDate           = customerDb.AddedDate;
                customer.AddedFromIp         = customerDb.AddedFromIp;
                customer.UpdatedBy           = identity.Name;
                customer.UpdatedDate         = DateTime.Now;
                customer.UpdatedFromIp       = identity.IpAddress;
                _customerRepository.Update(customer);
                #endregion

                #region Customer Ledger


                if (customer.AccountsPayable > 0 || customer.AccountsReceivable > 0)
                {
                    CustomerLedger customerLedgerDb = _customerLedgerRepository.GetOne(x => x.CustomerId == customerDb.Id && x.TransactionType == TransactionType.OpeningBalance.ToString());
                    if (customerLedgerDb != null)
                    {
                        if (!string.IsNullOrEmpty(customerLedgerDb.CompanyId))
                        {
                            customerLedgerDb.CompanyId = identity.CompanyId;
                        }
                        if (!string.IsNullOrEmpty(customerLedgerDb.BranchId))
                        {
                            customerLedgerDb.BranchId = identity.BranchId;
                        }
                        customerLedgerDb.TransactionType = TransactionType.OpeningBalance.ToString();
                        if (customer.AccountsPayable > 0)
                        {
                            customerLedgerDb.Particulars  = "Accounts Payable";
                            customerLedgerDb.DebitAmount  = customer.AccountsPayable;
                            customerLedgerDb.CreditAmount = 0;
                        }
                        else if (customer.AccountsReceivable > 0)
                        {
                            customerLedgerDb.Particulars  = "Accounts Receivable";
                            customerLedgerDb.DebitAmount  = 0;
                            customerLedgerDb.CreditAmount = customer.AccountsReceivable;
                        }
                        customerLedgerDb.UpdatedBy     = identity.Name;
                        customerLedgerDb.UpdatedDate   = DateTime.Now;
                        customerLedgerDb.UpdatedFromIp = identity.IpAddress;
                        _customerLedgerRepository.Update(customerLedgerDb);
                    }
                    else
                    {
                        if (customer.AccountsPayable > 0 || customer.AccountsReceivable > 0)
                        {
                            CustomerLedger customerLedger = new CustomerLedger
                            {
                                Id                   = GenerateAutoId(customer.CompanyId, customer.BranchId, "CustomerLedger"),
                                Sequence             = GetAutoSequence("CustomerLedger"),
                                TrackingNo           = GenerateTrackingNo(customer.CompanyId, customer.BranchId, "CustomerLedger"),
                                MoneyReceiveNo       = GenerateMoneyReceiveNo(customer.CompanyId, customer.BranchId, "CustomerLedger"),
                                TransactionDate      = DateTime.Now,
                                CustomerId           = customer.Id,
                                CustomerMobileNumber = customer.Phone1
                            };
                            customerLedger.TransactionType = TransactionType.OpeningBalance.ToString();
                            customerLedger.TransactionDate = DateTime.Now;
                            if (customer.AccountsPayable > 0)
                            {
                                customerLedger.Particulars  = "Accounts Payable";
                                customerLedger.DebitAmount  = customer.AccountsPayable;
                                customerLedger.CreditAmount = 0;
                            }
                            else if (customer.AccountsReceivable > 0)
                            {
                                customerLedger.Particulars  = "Accounts Receivable";
                                customerLedger.DebitAmount  = 0;
                                customerLedger.CreditAmount = customer.AccountsReceivable;
                            }
                            customerLedger.Active = true;
                            customerLedger.SynchronizationType = SynchronizationType.Server.ToString();
                            customerLedger.AddedBy             = identity.Name;
                            customerLedger.AddedDate           = DateTime.Now;
                            customerLedger.AddedFromIp         = identity.IpAddress;
                            _customerLedgerRepository.Add(customerLedger);
                        }
                    }
                }
                #endregion

                _unitOfWork.SaveChanges();
                flag = false;
                _unitOfWork.Commit();
                _rawSqlService.UpdateCustomerLedgerRunningBalance(customer?.Id);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (flag)
                {
                    _unitOfWork.Rollback();
                }
            }
        }
 public ActionResult CustomerPaymentOrReceive(CustomerLedger model)
 {
     return(View());
 }
        public int InsertCustomerLedgerMasterData()
        {
            try
            {
                string query = "select * from ACM where slcd = 'CL'";

                DataTable dtCustomerLedgerMaster = dbConnection.GetData(query);

                List <CustomerLedger> listCustomerLedgerMaster = new List <CustomerLedger>();

                int _result = 0;

                using (PharmaDBEntities context = new PharmaDBEntities())
                {
                    var maxCustomerLedgerID = context.CustomerLedger.Count();

                    if (dtCustomerLedgerMaster != null && dtCustomerLedgerMaster.Rows.Count > 0)
                    {
                        var personRouteList = context.PersonRouteMaster.Select(r => r).ToList();
                        var areaList        = personRouteList.Where(q => q.RecordType.SystemName == PharmaBusinessObjects.Common.Constants.RecordType.AREA).Select(r => r).ToList();
                        var salesmanList    = personRouteList.Where(q => q.RecordType.SystemName == PharmaBusinessObjects.Common.Constants.RecordType.SALESMAN).Select(r => r).ToList();
                        var routeList       = personRouteList.Where(q => q.RecordType.SystemName == PharmaBusinessObjects.Common.Constants.RecordType.ROUTE).Select(r => r).ToList();
                        var asmList         = personRouteList.Where(q => q.RecordType.SystemName == PharmaBusinessObjects.Common.Constants.RecordType.ASM).Select(r => r).ToList();
                        var rsmList         = personRouteList.Where(q => q.RecordType.SystemName == PharmaBusinessObjects.Common.Constants.RecordType.RSM).Select(r => r).ToList();
                        var zsmList         = personRouteList.Where(q => q.RecordType.SystemName == PharmaBusinessObjects.Common.Constants.RecordType.ZSM).Select(r => r).ToList();

                        var customerTypeList = context.CustomerType.Select(p => p);

                        foreach (DataRow dr in dtCustomerLedgerMaster.Rows)
                        {
                            try
                            {
                                maxCustomerLedgerID++;

                                string customerLedgerCode         = "C" + maxCustomerLedgerID.ToString().PadLeft(6, '0');
                                string originalCustomerLedgerCode = Convert.ToString(dr["ACNO"]).Trim();
                                Common.customerLedgerCodeMap.Add(new CustomerLedgerCodeMap()
                                {
                                    OriginalCustomerLedgerCode = originalCustomerLedgerCode
                                    , MappedCustomerLedgerCode = customerLedgerCode
                                    , CustomerLedgerName       = Convert.ToString(dr["ACNAME"]).Trim()
                                });

                                string areaCode = string.IsNullOrEmpty(Convert.ToString(dr["Parea"]).Trim()) ? null : Common.areaCodeMap.Where(p => p.OriginalAreaCode == Convert.ToString(dr["Parea"]).Trim()).FirstOrDefault().MappedAreaCode;
                                int?   areaID   = areaCode == null ? (int?)null : areaList.Where(q => q.PersonRouteCode == areaCode).FirstOrDefault().PersonRouteID;

                                string salesmanCode = string.IsNullOrEmpty(Convert.ToString(dr["Sman"]).Trim()) ||
                                                      Convert.ToString(dr["Sman"]).Trim() == "020"      //this value is not present in MASTERS as Salesman Code
                                                        ? null : Common.salesmanCodeMap.Where(p => p.OriginalSalesManCode == Convert.ToString(dr["Sman"]).Trim()).FirstOrDefault().MappedSalesManCode;
                                int?salesmanID = salesmanCode == null ? (int?)null : salesmanList.Where(q => q.PersonRouteCode == salesmanCode).FirstOrDefault().PersonRouteID;

                                string routeCode = string.IsNullOrEmpty(Convert.ToString(dr["Route"]).Trim()) ? null : Common.routeCodeMap.Where(p => p.OriginalRouteCode == Convert.ToString(dr["Route"]).Trim()).FirstOrDefault().MappedRouteCode;
                                int?   routeID   = routeCode == null ? (int?)null : routeList.Where(q => q.PersonRouteCode == routeCode).FirstOrDefault().PersonRouteID;

                                string asmCode = string.IsNullOrEmpty(Convert.ToString(dr["Asm"]).Trim()) ? null : Common.asmCodeMap.Where(p => p.OriginalASMCode == Convert.ToString(dr["Asm"]).Trim()).FirstOrDefault().MappedASMCode;
                                int?   asmID   = asmCode == null ? (int?)null : asmList.Where(q => q.PersonRouteCode == asmCode).FirstOrDefault().PersonRouteID;

                                string rsmCode = string.IsNullOrEmpty(Convert.ToString(dr["Rsm"]).Trim()) ? null : Common.rsmCodeMap.Where(p => p.OriginalRSMCode == Convert.ToString(dr["Rsm"]).Trim()).FirstOrDefault().MappedRSMCode;
                                int?   rsmID   = rsmCode == null ? (int?)null : rsmList.Where(q => q.PersonRouteCode == rsmCode).FirstOrDefault().PersonRouteID;

                                string zsmCode = string.IsNullOrEmpty(Convert.ToString(dr["Zsm"]).Trim()) ? null : Common.zsmCodeMap.Where(p => p.OriginalZSMCode == Convert.ToString(dr["Zsm"]).Trim()).FirstOrDefault().MappedZSMCode;
                                int?   zsmID   = zsmCode == null ? (int?)null : zsmList.Where(q => q.PersonRouteCode == zsmCode).FirstOrDefault().PersonRouteID;

                                string customerType   = Convert.ToString(dr["Wr"]).Trim();
                                int    customerTypeID = customerTypeList.Where(p => p.CustomerTypeShortName == customerType).FirstOrDefault().CustomerTypeId;

                                CustomerLedger newCustomerLedgerMaster = new CustomerLedger()
                                {
                                    CustomerLedgerCode      = customerLedgerCode,
                                    CustomerLedgerName      = Convert.ToString(dr["ACNAME"]).Trim(),
                                    CustomerLedgerShortName = Convert.ToString(dr["Alt_Name_1"]).Trim(),
                                    CustomerLedgerShortDesc = Convert.ToString(dr["Alt_Name_2"]).Trim(),
                                    Address                   = string.Concat(Convert.ToString(dr["ACAD1"]).Trim(), " ", Convert.ToString(dr["ACAD2"]).Trim(), " ", Convert.ToString(dr["ACAD3"]).Trim()),
                                    ContactPerson             = Convert.ToString(dr["ACAD4"]).Trim(),
                                    Mobile                    = Convert.ToString(dr["Mobile"]).Trim(),
                                    OfficePhone               = Convert.ToString(dr["Telo"]).Trim(),
                                    ResidentPhone             = Convert.ToString(dr["Telr"]).Trim(),
                                    EmailAddress              = Convert.ToString(dr["Email"]).Trim(),
                                    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["DRNO"]).Trim(), //confirm -> increase size more than 20
                                    GSTNo                     = "test",                             //Convert.ToString(dr["Stnoc"]).Trim() -> confirm
                                    CINNo                     = "test",                             //Convert.ToString(dr["Stnoc"]).Trim() -> confirm
                                    LINNo                     = "test",                             //Convert.ToString(dr["Stnol"]).Trim(), //confirm
                                    ServiceTaxNo              = "test",                             //Convert.ToString(dr["Stnol"]).Trim() -> //confirm
                                    PANNo                     = "test",                             //Convert.ToString(dr["Stnol"]).Trim() -> confirm
                                    OpeningBal                = Convert.ToDecimal(dr["Abop"]),
                                    TaxRetail                 = Convert.ToString(dr["Vat"]).Trim(), // Remove
                                    Status                    = Convert.ToChar(dr["ACSTS"]) == '*' ? false : true,
                                    ASMId                     = asmID,
                                    CreditLimit               = Convert.ToInt32(dr["Cr_limit"]),
                                    CustomerTypeID            = customerTypeID,
                                    InterestTypeID            = 1, //Convert.ToString(dr["ACNO"]).Trim(), confirm  SBType
                                    IsLessExcise              = Convert.ToChar(dr["Less_ex"]) == 'Y' ? true : false,
                                    RateTypeID                = 1, //Convert.ToString(dr["ACNO"]).Trim(), confirm
                                    RouteId                   = routeID,
                                    RSMId                     = rsmID,
                                    SalesManId                = salesmanID,
                                    ZSMId                     = zsmID,
                                    SaleBillFormat            = Convert.ToString(dr["Sb_format"]).Trim(),
                                    MaxOSAmount               = Convert.ToInt32(dr["Max_os_a"]),
                                    MaxNumOfOSBill            = Convert.ToInt32(dr["Max_os_n"]),
                                    MaxBillAmount             = Convert.ToInt32(dr["Max_bill_a"]),
                                    MaxGracePeriod            = Convert.ToInt32(dr["Grace_days"]),
                                    IsFollowConditionStrictly = Convert.ToChar(dr["Validate"]) == 'Y' ? true : false,
                                    Discount                  = 0,   //Convert.ToString(dr["ACNO"]).Trim(),
                                    CentralLocal              = "C", //Convert.ToString(dr["ACNO"]).Trim(), //LC
                                    CreatedBy                 = "admin",
                                    CreatedOn                 = DateTime.Now
                                };

                                listCustomerLedgerMaster.Add(newCustomerLedgerMaster);
                            }
                            catch (Exception)
                            {
                                log.Info("CUSTOMER LEDGER : Error in ACName --> " + Convert.ToString(dr["ACName"]).Trim());
                            }
                        }
                    }

                    context.CustomerLedger.AddRange(listCustomerLedgerMaster);
                    _result = context.SaveChanges();

                    return(_result);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }