private Receiving getEntityByModel(ReceivingModel model)
        {
            if (model == null) return null;

            Receiving entity = new Receiving();

            if (model.Id == 0)
            {
                entity.CreateBy = AuthenticationHelper.UserId;
                entity.CreateDate = DateTime.Now;
                entity.CompanyId = AuthenticationHelper.CompanyId.Value;
            }
            else
            {
                entity.CreateBy = model.CreateBy;
                entity.CreateDate = model.CreateDate;
                entity.CompanyId = model.CompanyId;
            }

            entity.Date = model.Date;
            entity.DCNo = model.DCNo;
            entity.Id = model.Id;
            entity.POId = model.POId;
            entity.ReceiptNo = model.ReceiptNo;
            entity.SOBId = model.SOBId;
            entity.UpdateBy = model.UpdateBy;
            entity.UpdateDate = model.UpdateDate;

            return entity;
        }
        private string generateReceiptNum(ReceivingModel model)
        {
            var currentDocument = service.GetAll(AuthenticationHelper.CompanyId.Value, SessionHelper.SOBId).OrderByDescending(rec => rec.Id).FirstOrDefault();
            string newDocNo = "";
            if (currentDocument != null)
            {
                int outVal;
                bool isNumeric = int.TryParse(currentDocument.ReceiptNo, out outVal);
                if (isNumeric && currentDocument.ReceiptNo.Length == 8)
                {
                    newDocNo = (int.Parse(currentDocument.ReceiptNo) + 1).ToString();
                    return newDocNo;
                }
            }

            //Create New DocNum..
            string yearDigit = model.Date.ToString("yy");
            string monthDigit = model.Date.ToString("MM");
            string docNo = int.Parse("1").ToString().PadLeft(4, '0');

            return yearDigit + monthDigit + docNo;
        }
        public ActionResult Edit(string id)
        {
            ReceivingModel receiving = new ReceivingModel(service.GetSingle(id, AuthenticationHelper.CompanyId.Value));
            receiving.ReceivingDetail = service.GetAllReceivingDetail(receiving.Id).Select(x => new ReceivingDetailModel(x, true)).ToList();

            if (receiving.ReceivingDetail != null && receiving.ReceivingDetail.Count() > 0)
            {
                foreach (var detail in receiving.ReceivingDetail)
                {
                    PurchaseOrderDetail currentPODetail = poService.GetSinglePODetail(detail.PODetailId);
                    List<ReceivingDetail> totalReceived = service.GetAllByPODetailId(detail.PODetailId).Where(rec => rec.ReceiptId < Convert.ToInt64(id)).ToList();

                    detail.BalanceQty = currentPODetail.Quantity - (totalReceived.Count() > 0 ? (totalReceived.Sum(rec => rec.Quantity) + detail.ThisPurchaseQty) : detail.ThisPurchaseQty);
                    detail.OrderQty = currentPODetail.Quantity;
                    detail.PurchaseQty = totalReceived.Count() > 0 ? totalReceived.Sum(rec => rec.Quantity) : 0;
                    detail.ThisPurchaseQty = detail.ThisPurchaseQty;
                }
            }

            SessionHelper.Receiving = receiving;

            receiving.POs = poService.GetAllPO(AuthenticationHelper.CompanyId.Value, SessionHelper.SOBId).
                Select(x => new SelectListItem
                {
                    Text = x.PONo,
                    Value = x.Id.ToString()
                }).ToList();

            ViewBag.PO = poService.GetSingle(receiving.POId.ToString(), AuthenticationHelper.CompanyId.Value);

            return View("Edit", receiving);
        }
        public ActionResult Create()
        {
            ReceivingModel receiving = SessionHelper.Receiving;
            if (receiving == null)
            {
                receiving = new ReceivingModel
                {
                    CompanyId = AuthenticationHelper.CompanyId.Value,
                    Date = DateTime.Now,
                    ReceiptNo = "New",
                    SOBId = SessionHelper.SOBId
                };
            }

            receiving.POs = poService.GetAllPO(AuthenticationHelper.CompanyId.Value, SessionHelper.SOBId).
                Select(x => new SelectListItem
                {
                    Text = x.PONo,
                    Value = x.Id.ToString()
                }).ToList();

            if (receiving.POs != null && receiving.POs.Count() > 0)
                receiving.POId = receiving.POId > 0 ? receiving.POId : Convert.ToInt64(receiving.POs.FirstOrDefault().Value);

            SessionHelper.Receiving = receiving;
            if (receiving.POId > 0)
                SessionHelper.Receiving.ReceivingDetail = getPendingReceivingDetail(receiving.POId);

            return View("Edit", receiving);
        }
        private string save(ReceivingModel model)
        {
            Receiving entity = getEntityByModel(model);

            if (model.Id > 0)
            {
                List<ReceivingDetailModel> receivingDetail = service.GetAllReceivingDetail(model.Id).Select(rec => new ReceivingDetailModel(rec, true)).ToList();
                if (receivingDetail != null && receivingDetail.Count() > 0)
                {
                    foreach (var item in receivingDetail)
                    {
                        if (!model.ReceivingDetail.Any(rec => rec.PODetailId == item.PODetailId))
                        {
                            string serialResult = deleteSerials(item);
                            if (string.IsNullOrEmpty(serialResult))
                            {
                                service.DeleteReceivingDetail(item.Id);
                                deleteLot(item);
                            }
                            else
                                return serialResult;
                        }
                    }
                }
            }

            List<ReceivingDetailModel> tobeUpdatedDetail = model.ReceivingDetail.Where(rec => rec.LocatorId > 0 && rec.WarehouseId > 0).ToList();

            string result = string.Empty;
            if (entity.IsValid())
            {
                bool goodToSave = false;
                foreach (var item in tobeUpdatedDetail)
                {
                    ReceivingDetailModel updatedModel = item;
                    string lotResult = updateLot(updatedModel);
                    int outVal;
                    bool isNumeric = int.TryParse(lotResult, out outVal);
                    if (isNumeric || string.IsNullOrEmpty(lotResult))
                    {
                        item.LotNoId = isNumeric ? (long?)Convert.ToInt64(lotResult) : null;
                        string serialResult = updateSerials(updatedModel);
                        if (string.IsNullOrEmpty(serialResult))
                            goodToSave = true;
                        else
                        {
                            if (item.LotNoId != null)
                            {
                                LotNumber lot = lotService.GetSingle(item.LotNoId.Value.ToString(), AuthenticationHelper.CompanyId.Value);
                                lot.Qty = lot.Qty - item.ThisPurchaseQty;
                                lotService.Update(lot);
                            }
                            return serialResult;
                        }
                    }
                    else
                        return lotResult;
                }
                if (goodToSave)
                {
                    if (model.Id > 0)
                        result = service.Update(entity);
                    else
                        result = service.Insert(entity);

                    if (!string.IsNullOrEmpty(result))
                    {
                        var savedLines = getReceivingDetail(result);
                        if (savedLines.Count() > tobeUpdatedDetail.Count())
                        {
                            var tobeDeleted = savedLines.Take(savedLines.Count() - tobeUpdatedDetail.Count());
                            foreach (var item in tobeDeleted)
                            {
                                string serialResult = deleteSerials(item);
                                if (string.IsNullOrEmpty(serialResult))
                                {
                                    string lotResult = deleteLot(item);
                                    if (string.IsNullOrEmpty(lotResult))
                                        service.DeleteReceivingDetail(item.Id);
                                    else
                                        return "Record can not be deleted";
                                }
                                else
                                    return "Record can not be deleted";
                            }
                            savedLines = getReceivingDetail(result);
                        }

                        foreach (var detail in tobeUpdatedDetail)
                        {
                            ReceivingDetail detailEntity = getEntityByModel(detail);
                            if (detailEntity.IsValid())
                            {
                                detailEntity.ReceiptId = Convert.ToInt64(result);
                                if (savedLines.Count() > 0)
                                {
                                    detailEntity.Id = savedLines.FirstOrDefault().Id;
                                    savedLines.Remove(savedLines.FirstOrDefault(rec => rec.Id == detailEntity.Id));

                                    string receivingDetailId = service.Update(detailEntity);

                                    if (detailEntity.LotNoId != null)
                                    {
                                        LotNumber lottobeUpdated = lotService.GetSingle(detailEntity.LotNoId.ToString(), AuthenticationHelper.CompanyId.Value);
                                        lottobeUpdated.SourceId = Convert.ToInt64(receivingDetailId);
                                        lotService.Update(lottobeUpdated);
                                    }
                                }
                                else
                                {
                                    string receivingDetailId = service.Insert(detailEntity);

                                    if (detailEntity.LotNoId != null)
                                    {
                                        LotNumber lottobeUpdated = lotService.GetSingle(detailEntity.LotNoId.ToString(), AuthenticationHelper.CompanyId.Value);
                                        lottobeUpdated.SourceId = Convert.ToInt64(receivingDetailId);
                                        lotService.Update(lottobeUpdated);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return "";
        }