public int SetDepartmentRep([FromBody] BriefDepartment e)//username
        {
            //Retrieve department head
            //string depHeadId;
            // var user = database.AspNetUsers.Where(x => x.Id == depHeadId).FirstOrDefault();
            //Retrieve department
            var dept = _context.Department.Where(x => x.DepartmentId == e.DepartmentId).FirstOrDefault();

            //Change department rep
            string oldEmpRepId = dept.DepartmentRepId;

            //string userId = model.UserId;
            dept.DepartmentRepId = e.DepartmentRepId;

            //Change previous Department Rep to employee
            ApplicationUserManager manager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();

            manager.RemoveFromRole(oldEmpRepId, RoleName.DepartmentRepresentative);
            manager.AddToRole(oldEmpRepId, RoleName.Employee);
            //Assign new employee to Department Rep
            manager.RemoveFromRole(e.DepartmentRepId, RoleName.Employee);
            manager.AddToRole(e.DepartmentRepId, RoleName.DepartmentRepresentative);

            _context.SaveChanges();

            return(1);
        }
예제 #2
0
        public bool UpdatePurchaseOrder(string userId, string poNo, bool isApproved)
        {
            var query  = context.AspNetUsers.FirstOrDefault(x => x.Id == userId);
            var thisPo = context.PurchaseOrder.FirstOrDefault(x => x.PONo == poNo);

            if (query == null || thisPo == null)
            {
                return(false);
            }

            if (isApproved)
            {
                thisPo.Status     = "Pending Delivery";
                thisPo.ApprovedBy = query.Id;

                try
                {
                    context.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    Console.WriteLine(e);
                }

                #region Send Email
                string recipientEmail, subject, content;
                recipientEmail = thisPo.AspNetUsers1.Email;
                subject        = " PO approved!";
                content        = "I am very happy to inform you, your PO has been approved ";
                Email.Send(recipientEmail, subject, content);
                #endregion

                return(true);
            }
            else
            {
                thisPo.Status     = "Rejected";
                thisPo.ApprovedBy = query.Id;
                try
                {
                    context.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    Console.WriteLine(e);
                }

                #region SendEmail
                string recipientEmail, subject, content;
                recipientEmail = thisPo.AspNetUsers1.Email;
                //recipientEmail = "*****@*****.**";
                subject = " PO rejected!";
                content = "Unfortunately, your PO was rejected";
                Email.Send(recipientEmail, subject, content);
                #endregion

                return(true);
            }
        }
        public ActionResult Edit(StationeryRequest requests)
        {
            string result = null;

            if (requests != null)
            {
                result = "data include";

                string userId = User.Identity.GetUserId();

                var stationery = _context.StationeryRequest.Find(requests.RequestId);



                var stationerytran = _context.TransactionDetail.Where(x => x.TransactionRef == requests.RequestId).ToList();
                if (stationery == null)
                {
                    return(HttpNotFound());
                }

                else
                {
                    //for collection date check
                    {
                        var dep = _context.Department.FirstOrDefault(x => x.DepartmentId == stationery.DepartmentId);
                        if (dep.NextAvailableDate > DateTime.Now)
                        {
                            _context.Entry(stationery).Property("CollectionDate").CurrentValue = dep.NextAvailableDate;
                        }
                        else
                        {
                            DateTime nextMon = Next(DateTime.Today, DayOfWeek.Monday);
                            _context.Entry(stationery).Property("CollectionDate").CurrentValue = nextMon;
                        }
                    }
                    _context.Entry(stationery).Property("Status").CurrentValue     = requests.Status;
                    _context.Entry(stationery).Property("ApprovedBy").CurrentValue = userId;
                    _context.Entry(stationery).Property("Comment").CurrentValue    = requests.Comment;
                    _context.SaveChanges();
                }
                if (stationerytran == null)
                {
                    return(HttpNotFound());
                }

                else
                {
                    foreach (TransactionDetail detail in stationerytran)
                    {
                        _context.Entry(detail).Property("Remarks").CurrentValue = requests.Status;
                    }

                    _context.SaveChanges();
                }
            }

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
예제 #4
0
        public int UpdateDisb([FromBody] AckListViewModel ackListViewModel)
        {
            using (var dbContextTransaction = _context.Database.BeginTransaction())
            {
                try
                {
                    foreach (var i in ackListViewModel.AckList)
                    {
                        var query = _context.Disbursement.Where(x => x.DisbursementNo == i.DisbursementNo).ToList();
                        foreach (var disb in query)
                        {
                            var dept = _context.Department.FirstOrDefault(x => x.DepartmentId == i.DepartmentId);
                            disb.AcknowledgedBy = dept.DepartmentRepId;
                            disb.DisbursedBy    = i.AcknowledgedBy;
                            disb.Status         = "Acknowledged";
                            disb.DisbursedBy    = ackListViewModel.DisbursedBy;
                            _context.SaveChanges();
                        }
                    }

                    dbContextTransaction.Commit();
                    return(1);
                }
                catch (Exception)
                {
                    dbContextTransaction.Rollback();
                    return(0);
                }
            }
        }
        public void AssignDelegateHead(string userId, string selectedUser, string deptId, DateTime startDate, DateTime endDate)
        {
            DelegationOfAuthority doaInDb = new DelegationOfAuthority
            {
                DelegatedBy  = userId,    //"b36a58f3-51f9-47eb-8601-bcc757a8cadb";//selected Employee ID;
                DelegatedTo  = selectedUser,
                StartDate    = startDate, //new DateTime(2017,3,5);
                EndDate      = endDate,   //new DateTime(2017, 5, 5);
                DepartmentId = deptId
            };

            context.DelegationOfAuthority.Add(doaInDb);
            context.SaveChanges();
        }
예제 #6
0
        public ActionResult AddOrEdit(ManagePointViewModel collectionPoint)
        {
            try
            {
                if (collectionPoint.ImageUpload == null && collectionPoint.CollectionPointId == 0)
                {
                    throw new Exception("Please select an image.");
                }
                CollectionPoint cp = new CollectionPoint();
                if (collectionPoint.ImageUpload != null)
                {
                    string fileName  = Path.GetFileNameWithoutExtension(collectionPoint.ImageUpload.FileName);
                    string extension = Path.GetExtension(collectionPoint.ImageUpload.FileName);
                    fileName       = fileName + DateTime.Now.ToString("yymmssfff") + extension;
                    cp.CPImagePath = "/Content/images/CollPoint/" + fileName;
                    collectionPoint.ImageUpload.SaveAs(Path.Combine(Server.MapPath("~/Content/images/CollPoint/"), fileName));
                }

                string date = DateTime.Now.ToString("yyyy/M/dd ");
                cp.CollectionDescription = collectionPoint.CollectionDescription;
                cp.Time = DateTime.ParseExact(date + collectionPoint.Time, "yyyy/M/dd h:mm tt", null);


                if (collectionPoint.CollectionPointId == 0)
                {
                    db.CollectionPoint.Add(cp);
                    db.SaveChanges();
                }
                else
                {
                    var oldCP = db.CollectionPoint.FirstOrDefault(x => x.CollectionPointId == collectionPoint.CollectionPointId);
                    oldCP.CollectionDescription = cp.CollectionDescription;
                    if (collectionPoint.ImageUpload != null)
                    {
                        oldCP.CPImagePath = cp.CPImagePath;
                    }
                    oldCP.Time = cp.Time;

                    db.SaveChanges();
                }

                return(Json(new { success = true, html = GlobalClass.RenderRazorViewToString(this, "ViewAll", db.CollectionPoint.ToList()), message = "Submitted Successfully" }, JsonRequestBehavior.AllowGet));
            }

            catch (Exception ex)
            {
                return(Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
        public string Delegate(DelegateHeadViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return("fail");
            }

            else
            {
                string userId                 = User.Identity.GetUserId();
                var    selectedEmployee       = model.SelectedUser;
                DelegationOfAuthority doaInDb = new DelegationOfAuthority
                {
                    DelegatedBy  = userId,          //"b36a58f3-51f9-47eb-8601-bcc757a8cadb";//selected Employee ID;
                    DelegatedTo  = selectedEmployee,
                    StartDate    = model.StartDate, //new DateTime(2017,3,5);
                    EndDate      = model.EndDate,   //new DateTime(2017, 5, 5);
                    DepartmentId = model.DepartmentID
                };

                //model.CurrentUser = userId;

                ApplicationUserManager userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();

                userManager.RemoveFromRole(doaInDb.DelegatedTo, RoleName.Employee);
                userManager.AddToRole(doaInDb.DelegatedTo, RoleName.ActingDepartmentHead);
                _context.DelegationOfAuthority.Add(doaInDb);
                _context.SaveChanges();
                return("success");
            }
        }
        public ActionResult Save(AdjustmentViewModel[] requests, string remark)
        {
            string result = "You Haven't Add Any Adjustment Item!";


            string currentUserId = User.Identity.GetUserId();
            //AspNetUsers currentUser = context.AspNetUsers.First(m => m.Id == currentUserId);

            decimal?amount = 0;

            if (requests != null)
            {
                StockAdjustment adjustment = new StockAdjustment
                {
                    StockAdjId = newAdjustId(),
                    PreparedBy = currentUserId,
                    ApprovedBy = null,
                    Remarks    = remark,
                    Date       = DateTime.Today
                };

                foreach (var item in requests)
                {
                    TransactionDetail transactionDetail = new TransactionDetail
                    {
                        TransactionId   = GenerateTransactionDetailId(),
                        ItemId          = item.ItemId,
                        Quantity        = item.Quantity,
                        Remarks         = "Pending Approval",
                        TransactionRef  = adjustment.StockAdjId,
                        TransactionDate = DateTime.Today,
                        UnitPrice       = context.Stationery.Single(x => x.ItemId == item.ItemId).FirstSuppPrice
                    };
                    amount += item.Quantity * transactionDetail.UnitPrice;
                    adjustment.TransactionDetail.Add(transactionDetail);
                    context.TransactionDetail.Add(transactionDetail);
                    context.SaveChanges();
                }

                context.StockAdjustment.Add(adjustment);
                context.SaveChanges();
                result = "Success! Request is complete!";

                SendEmail(currentUserId, amount);
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
예제 #9
0
        public IHttpActionResult ReturnItem(ReturnToWarehouseSetApiModel apiModel)
        {
            string            status = "fail";
            StationeryRequest stationeryRequestInDb =
                _context.StationeryRequest.FirstOrDefault(m => m.RequestId == apiModel.RequestId);

            TransactionDetail transactionDetailInDb =
                stationeryRequestInDb.TransactionDetail.FirstOrDefault(m =>
                                                                       m.ItemId == apiModel.ItemId && m.Quantity == apiModel.Quantity);

            //moving from quantity in transit to quantity in warehouse
            Stationery stationeryInDb =
                _context.Stationery.FirstOrDefault(m => m.ItemId == transactionDetailInDb.ItemId);

            stationeryInDb.QuantityTransit   -= apiModel.Quantity;
            stationeryInDb.QuantityWarehouse += apiModel.Quantity;

            transactionDetailInDb.Remarks = "Returned";


            _context.SaveChanges();
            status = "Successfully returned";
            stationeryRequestInDb = _context.StationeryRequest.FirstOrDefault(m => m.RequestId == apiModel.RequestId);

            //Checking if all items are returned
            bool allReturned = true;

            foreach (TransactionDetail current in stationeryRequestInDb.TransactionDetail)
            {
                if (current.Remarks == "Void")
                {
                    allReturned = false;
                    break;
                }
            }

            if (allReturned)
            {
                stationeryRequestInDb.Status = "Returned";

                Disbursement disbursementInDb =
                    _context.Disbursement.FirstOrDefault(m => m.RequestId == apiModel.RequestId);
                disbursementInDb.Status = "Returned";
                _context.SaveChanges();
            }
            return(Ok(status));
        }
예제 #10
0
        public ActionResult Postpone(string id = null)
        {
            try
            {
                if (id == "ALL")
                {
                    var deptList = _context.Department.ToList();
                    foreach (var dept in deptList)
                    {
                        DateTime nextMonday   = GlobalClass.GetNextWeekDay((DateTime)dept.NextAvailableDate, DayOfWeek.Monday);
                        DateTime comingMonday = GlobalClass.GetNextWeekDay(DateTime.Now, DayOfWeek.Monday);
                        if (nextMonday > comingMonday)
                        {
                            dept.NextAvailableDate = nextMonday.AddDays(7);
                        }
                        else
                        {
                            dept.NextAvailableDate = comingMonday.AddDays(7);
                        }
                    }
                    _context.SaveChanges();
                    return(Json(new { success = true, html = GlobalClass.RenderRazorViewToString(this, "Index", disbService.GetBriefDept()), message = "Updated Successfully" }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    Department dept         = _context.Department.FirstOrDefault(x => x.DepartmentId == id);
                    DateTime   nextMonday   = GlobalClass.GetNextWeekDay((DateTime)dept.NextAvailableDate, DayOfWeek.Monday);
                    DateTime   comingMonday = GlobalClass.GetNextWeekDay(DateTime.Now, DayOfWeek.Monday);
                    if (nextMonday > comingMonday)
                    {
                        dept.NextAvailableDate = nextMonday.AddDays(7);
                    }
                    else
                    {
                        dept.NextAvailableDate = comingMonday.AddDays(7);
                    }

                    _context.SaveChanges();
                    return(Json(new { success = true, html = GlobalClass.RenderRazorViewToString(this, "Index", disbService.GetBriefDept()), message = "Updated Successfully" }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
        public bool VoidDisbursement(string disbno)
        {
            var disb = context.Disbursement.Where(x => x.DisbursementNo == disbno).ToList();

            if (disb != null)
            {
                var               onedisb = disb.First();
                string            reqid   = onedisb.RequestId;
                StationeryRequest req     = context.StationeryRequest.Find(reqid);
                if (req != null)
                {
                    req.Status = "Void";
                }
                foreach (Disbursement dd in disb)
                {
                    dd.Status = "Void";
                    context.SaveChanges();
                    var transactionDetail = context.TransactionDetail.Where(x => x.TransactionRef == dd.RequestId).ToList();
                    if (transactionDetail != null)
                    {
                        foreach (TransactionDetail detail in transactionDetail)
                        {
                            detail.Remarks = "Void";
                        }
                    }
                    var transactionDetaildisb = context.TransactionDetail.Where(x => x.TransactionRef == dd.DisbursementId).ToList();
                    if (transactionDetaildisb != null)
                    {
                        foreach (TransactionDetail detail in transactionDetaildisb)
                        {
                            detail.Remarks = "Void";
                        }
                    }
                }

                context.SaveChanges();
                return(true);
            }

            return(false);



            throw new NotImplementedException();
        }
        public ActionResult Create([Bind(Include = "SupplierId,SupplierName,ContactName,ContactNo,FaxNo,Address,GSTRegNo,Status,Email")] Supplier supplier)
        {
            if (ModelState.IsValid)
            {
                if (!(CheckSupplier(supplier.SupplierId)))
                {
                    _context.Supplier.Add(supplier);
                    _context.SaveChanges();
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ViewBag.Error1 = "The Supplier ID Already Exists!";
                    return(View());
                }
            }

            return(View(supplier));
        }
        public ActionResult Save(Stationery stationery)
        {
            string a = stationery.ItemId;

            if (!ModelState.IsValid)
            {
                var viewModel = new StationeryFormViewModel(stationery)
                {
                    Suppliers  = _context.Supplier.ToList(),
                    Categories = _context.Stationery.Select(m => m.Category).Distinct().ToList(),
                    Units      = _context.Stationery.Select(m => m.UnitOfMeasure).Distinct().ToList()
                };
                return(View("StationeryForm", viewModel));
            }

            //for Create New Stationery operation
            if (stationery.ItemId == null)
            {
                stationery.ItemId      = GenerateItemId(stationery.Description);
                stationery.ActiveState = true;
                _context.Stationery.Add(stationery);
            }


            //for Update Stationery operation
            else
            {
                var stationeryInDb = _context.Stationery.Single(m => m.ItemId == stationery.ItemId);
                stationeryInDb.Category          = stationery.Category;
                stationeryInDb.Description       = stationery.Description;
                stationeryInDb.ReorderLevel      = stationery.ReorderLevel;
                stationeryInDb.ReorderQuantity   = stationery.ReorderQuantity;
                stationeryInDb.UnitOfMeasure     = stationery.UnitOfMeasure;
                stationeryInDb.QuantityWarehouse = stationery.QuantityWarehouse;
                stationeryInDb.Location          = stationery.Location;
                stationeryInDb.FirstSupplierId   = stationery.FirstSupplierId;
                stationeryInDb.FirstSuppPrice    = stationery.FirstSuppPrice;
                stationeryInDb.SecondSupplierId  = stationery.SecondSupplierId;
                stationeryInDb.SecondSuppPrice   = stationery.SecondSuppPrice;
                stationeryInDb.ThirdSupplierId   = stationery.ThirdSupplierId;
                stationeryInDb.ThirdSuppPrice    = stationery.ThirdSuppPrice;
            }

            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                Console.WriteLine(e);
            }
            return(RedirectToAction("Index", "ManageStationery"));
        }
예제 #14
0
        public IHttpActionResult save(List <AdjustmentInfo> request)
        {
            decimal?amount = 0;

            if (request != null)
            {
                StockAdjustment adjustment = new StockAdjustment
                {
                    StockAdjId = newAdjustId(),
                    PreparedBy = User.Identity.GetUserId(),
                    ApprovedBy = null,
                    Remarks    = request[0].remark,
                    Date       = DateTime.Today
                };

                foreach (var item in request)
                {
                    TransactionDetail transactionDetail = new TransactionDetail
                    {
                        TransactionId   = GenerateTransactionDetailId(),
                        ItemId          = item.itemId,
                        Quantity        = item.quantity,
                        Remarks         = "Pending Approval",
                        TransactionRef  = adjustment.StockAdjId,
                        TransactionDate = DateTime.Today,
                        UnitPrice       = context.Stationery.Single(x => x.ItemId == item.itemId).FirstSuppPrice
                    };
                    amount += item.quantity * transactionDetail.UnitPrice;
                    adjustment.TransactionDetail.Add(transactionDetail);
                    context.TransactionDetail.Add(transactionDetail);
                    context.SaveChanges();
                }

                context.StockAdjustment.Add(adjustment);
                context.SaveChanges();
            }
            return(Ok());
        }
        public IHttpActionResult PutStationery(string id)
        {
            Stationery stationery = _context.Stationery.Find(id);

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

            stationery.ActiveState = false;
            _context.SaveChanges();

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #16
0
        public void UpdateAdjustment(string stockAdjId, string userId, string status)
        {
            var thisAdj = context.StockAdjustment.FirstOrDefault(x => x.StockAdjId == stockAdjId);
            var remarks = context.TransactionDetail.Where(x => x.TransactionRef == stockAdjId).ToList();

            thisAdj.ApprovedBy = userId;
            foreach (var item in remarks)
            {
                var items = context.Stationery.Where(x => x.ItemId == item.ItemId).FirstOrDefault();
                item.Remarks = status;
                if (status == "Approved")
                {
                    items.QuantityWarehouse += item.Quantity;
                }
            }
            context.SaveChanges();
        }
예제 #17
0
        public bool UpdateCollectionPoint(string userId, int cpId)
        {
            var query     = context.AspNetUsers.FirstOrDefault(x => x.Id == userId);
            var dept      = query.Department;
            var collPoint = context.CollectionPoint.FirstOrDefault(x => x.CollectionPointId == cpId);

            dept.CollectionPoint = collPoint;
            try
            {
                context.SaveChanges();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #18
0
        public ActionResult Save(string requestId, string itemId, int oldItemQuantity, int newItemQuantity)
        {
            string result = "Error! Saving Error!";

            if (String.IsNullOrWhiteSpace(requestId) || String.IsNullOrWhiteSpace(itemId) || oldItemQuantity <= 0 || newItemQuantity <= 0)
            {
                result = "Invalid input! Kindly amend your input.";
            }

            else
            {
                TransactionDetail transactionDetail = _context.TransactionDetail.First(m =>
                                                                                       m.TransactionRef == requestId && m.ItemId == itemId && m.Quantity == oldItemQuantity);
                transactionDetail.Quantity = newItemQuantity;
                _context.SaveChanges();
                result = "Entry successfully updated!";
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
예제 #19
0
 public ActionResult Postpone()
 {
     try
     {
         string   userId       = User.Identity.GetUserId();
         var      dept         = _context.AspNetUsers.FirstOrDefault(x => x.Id == userId).Department;
         DateTime nextMonday   = GlobalClass.GetNextWeekDay((DateTime)dept.NextAvailableDate, DayOfWeek.Monday);
         DateTime comingMonday = GlobalClass.GetNextWeekDay(DateTime.Now, DayOfWeek.Monday);
         if (nextMonday > comingMonday)
         {
             dept.NextAvailableDate = nextMonday.AddDays(7);
         }
         else
         {
             dept.NextAvailableDate = comingMonday.AddDays(7);
         }
         _context.SaveChanges();
         return(Json(new { success = true, html = GlobalClass.RenderRazorViewToString(this, "Index", disbService.GetBriefDept(dept.DepartmentId)), message = "Updated Successfully" }, JsonRequestBehavior.AllowGet));
     }
     catch (Exception ex)
     {
         return(Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet));
     }
 }
        public ActionResult Save(RaisePOViewModel[] poModel)
        {
            //Validation
            string result = "Error!";

            if (poModel == null)
            {
                result = "The List is Empty!Please check the list again!";
            }

            //Add New Items
            else
            {
                // to get the user ID of the current user
                string userId = User.Identity.GetUserId();
                var    query  = _context.AspNetUsers.FirstOrDefault(x => x.Id == userId);

                // to get the list of suppliers
                List <String> uniqueSupplier = poModel.Select(m => m.SupplierId).Distinct().ToList();

                foreach (String current in uniqueSupplier)
                {
                    string newPOnum = "PO" + DateTime.Now.Date.ToString("yy") + "/" + DateTime.Now.Date.ToString("MM") + "/" + GetSerialNumber();

                    decimal?amount = 0;
                    foreach (var po in poModel)
                    {
                        if (po.SupplierId == current)
                        {
                            decimal?total = (po.Quantity * po.UnitPrice);
                            amount = amount + total;
                            TransactionDetail newTD = new TransactionDetail
                            {
                                ItemId          = po.Description,
                                Quantity        = po.Quantity,
                                Remarks         = "Pending Approval",
                                TransactionRef  = newPOnum,
                                TransactionDate = DateTime.Today,
                                UnitPrice       = po.UnitPrice
                            };
                            _context.TransactionDetail.Add(newTD);
                            _context.SaveChanges();
                        }
                    }
                    PurchaseOrder newPO = new PurchaseOrder()
                    {
                        PONo       = newPOnum,
                        SupplierId = current,
                        OrderedBy  = query.Id,
                        ApprovedBy = null,
                        Amount     = Convert.ToDecimal(amount),
                        Date       = DateTime.Today,
                        Status     = "Pending Approval"
                    };
                    _context.PurchaseOrder.Add(newPO);
                    _context.SaveChanges();
                }
                SendEmail();
                result = "A PO has been raised successfully!";
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
예제 #21
0
        public ActionResult Save(RaiseRequestViewModel[] requests)
        {
            string result        = "Error! Request is incomplete!";
            bool   validQuantity = false;

            if (requests != null)
            {
                for (int i = 0; i < requests.Length; i++)
                {
                    validQuantity = requests[i].Quantity > 0;
                    if (validQuantity != true)
                    {
                        break;
                    }
                }
                if (!validQuantity)
                {
                    result = "Invalid input! Kindly raise a valid request.";
                }

                else
                {
                    string      currentUserId = User.Identity.GetUserId();
                    AspNetUsers currentUser   = _context.AspNetUsers.First(m => m.Id == currentUserId);


                    string newStationeryRequestId = GenerateRequestId();
                    if (requests != null)
                    {
                        StationeryRequest stationeryRequestInDb = new StationeryRequest
                        {
                            RequestId      = newStationeryRequestId,
                            RequestedBy    = currentUserId,
                            ApprovedBy     = null,
                            DepartmentId   = currentUser.DepartmentId,
                            Status         = "Pending Approval",
                            Comment        = null,
                            RequestDate    = DateTime.Today,
                            CollectionDate = null
                        };

                        _context.StationeryRequest.Add(stationeryRequestInDb);
                        _context.SaveChanges();

                        foreach (var item in requests)
                        {
                            decimal           itemPrice             = _context.Stationery.Single(m => m.ItemId == item.Description).FirstSuppPrice;
                            TransactionDetail transactionDetailInDb = new TransactionDetail
                            {
                                TransactionId   = GenerateTransactionDetailId(),
                                ItemId          = item.Description,
                                Quantity        = item.Quantity,
                                Remarks         = "Pending Approval",
                                TransactionRef  = newStationeryRequestId,
                                TransactionDate = DateTime.Today,
                                UnitPrice       = itemPrice
                            };
                            _context.TransactionDetail.Add(transactionDetailInDb);
                        }
                        _context.SaveChanges();

                        //Sending email to department head to approve the request
                        //string depRepEmail = _context.Department.FirstOrDefault(m => m.DepartmentId == pair.Key).AspNetUsers1.Email;
                        string recipient = "*****@*****.**"; //dummy email used
                        string title     = "A request by " + currentUser.EmployeeName + " is raised";
                        string body      = "Kindly check the details for the request.";
                        Email.Send(recipient, title, body);

                        result = "Success! Request is complete!";
                    }
                }
            }
            else
            {
                result = "List is empty.";
            }

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
        public bool SaveAndDisburse(List <RequestByItemViewModel> model, string userId)
        {
            LogicDB context = new LogicDB();

            using (var dbContextTransaction = context.Database.BeginTransaction())
            {
                try
                {
                    StationeryRetrieval retrieval = new StationeryRetrieval();
                    string rid = GetNewRetrievalId();
                    retrieval.RetrievalId = rid;
                    retrieval.RetrievedBy = userId;
                    retrieval.Date        = DateTime.Now;

                    foreach (var sr in model)
                    {
                        int retQty = sr.requestList.Sum(x => x.RetrievedQty);
                        if (retQty > 0)
                        {
                            TransactionDetail detail = new TransactionDetail();
                            detail.ItemId          = sr.ItemId;
                            detail.Quantity        = retQty;
                            detail.TransactionDate = DateTime.Now;
                            detail.Remarks         = "Retrieved";
                            detail.TransactionRef  = rid;
                            retrieval.TransactionDetail.Add(detail);

                            //Less off from stationery

                            var item = context.Stationery.FirstOrDefault(x => x.ItemId == sr.ItemId);
                            if (item != null)
                            {
                                item.QuantityWarehouse -= retQty;
                                item.QuantityTransit   += retQty;
                            }
                        }
                    }
                    context.StationeryRetrieval.Add(retrieval);
                    context.SaveChanges();

                    List <RequestByIdViewModel> requests = CreateDisbHelpers.GetRequestQuery(context).OrderBy(x => x.RequestId).ToList();

                    List <DisbursementByDeptViewModel> disbList = GenerateDisbursement(model);

                    foreach (var dept in disbList)
                    {
                        string currentDeptId = dept.DepartmentId;
                        string disbNo        = CreateDisbHelpers.GetNewDisbNo(context, currentDeptId);
                        string OTP;
                        do
                        {
                            Random rand = new Random();
                            OTP = rand.Next(10000).ToString("0000");
                        } while (context.Disbursement.Where(x => x.OTP == OTP).FirstOrDefault() != null);

                        Dictionary <string, int> tempDict = new Dictionary <string, int>();
                        foreach (var retItem in dept.requestList)
                        {
                            tempDict.Add(retItem.Description, retItem.RetrievedQty);
                        }

                        var deptReqList = requests.Where(x => x.DepartmentId == dept.DepartmentId).ToList();

                        foreach (var req in deptReqList)
                        {
                            bool isComplete = true;
                            foreach (var item in req.ItemList)
                            {
                                var disbItem = dept.requestList.FirstOrDefault(x => x.ItemId == item.ItemId);
                                if (disbItem != null)
                                {
                                    if (disbItem.RetrievedQty >= item.Quantity)
                                    {
                                        disbItem.RetrievedQty -= item.Quantity;
                                    }
                                    else
                                    {
                                        item.Quantity         = disbItem.RetrievedQty;
                                        disbItem.RetrievedQty = 0; //0
                                        isComplete            = false;
                                    }
                                }
                                else
                                {
                                    item.Quantity = 0;
                                    isComplete    = false;
                                }
                            }

                            foreach (var item in req.ItemList)
                            {
                                if (item.Quantity > 0)
                                {
                                    Disbursement      newDisb   = new Disbursement();
                                    TransactionDetail newDetail = new TransactionDetail();
                                    newDisb.DisbursementId    = CreateDisbHelpers.GetNewDisbId(context);
                                    newDisb.DisbursementNo    = disbNo;
                                    newDisb.DepartmentId      = currentDeptId;
                                    newDisb.DisbursedBy       = userId;
                                    newDisb.Date              = DateTime.Now;
                                    newDisb.RequestId         = req.RequestId;
                                    newDisb.Status            = "In Transit";
                                    newDisb.OTP               = OTP;
                                    newDetail.ItemId          = item.ItemId;
                                    newDetail.Quantity        = item.Quantity;
                                    newDetail.TransactionRef  = newDisb.DisbursementId;
                                    newDetail.TransactionDate = DateTime.Now;
                                    newDetail.UnitPrice       = item.UnitPrice;
                                    newDetail.Remarks         = "In Transit";
                                    newDisb.TransactionDetail.Add(newDetail);
                                    context.Disbursement.Add(newDisb);
                                    context.SaveChanges();
                                }
                            }

                            var currentReq = context.StationeryRequest.FirstOrDefault(x => x.RequestId == req.RequestId);
                            if (isComplete)
                            {
                                currentReq.Status = "Completed";
                            }
                            else
                            {
                                currentReq.Status = "Partially Fulfilled";
                            }
                        }
                        //Send email to dept rep
                        string email   = context.Department.FirstOrDefault(x => x.DepartmentId == dept.DepartmentId).AspNetUsers1.Email;
                        string subject = string.Format("Stationeries ready for collection (Disbursement No: {0})", disbNo);

                        string content = string.Format("Disbursement No: {0}{1}Please quote the OTP below when collecting your stationeries.{2}OTP: {3}{4}Collection Point: {5}{6}Time: {7}{8}Item\t\t\t\t\t\t\tQuantity{9}",
                                                       disbNo, Environment.NewLine, Environment.NewLine, OTP, Environment.NewLine, dept.CollectionDescription, Environment.NewLine, dept.CollectionTime, Environment.NewLine, Environment.NewLine);
                        foreach (KeyValuePair <string, int> entry in tempDict)
                        {
                            content += string.Format("{0}\t\t\t\t\t\t{1}{2}", entry.Key, entry.Value, Environment.NewLine);
                        }
                        Email.Send(email, subject, content);
                    }

                    dbContextTransaction.Commit();
                    return(true);
                }
                catch (Exception)
                {
                    dbContextTransaction.Rollback();
                    return(false);
                }
            }
        }