Beispiel #1
0
        public static void CreateTestData(IPosDbContext context, ApplicationIdentityUser user)
        {
            //old db
            var connetionString = ConfigurationManager.ConnectionStrings["OldIPosDbContext"];

            var categories = ImportExistingData <Category>(connetionString.ConnectionString).Result;

            categories.ToList().ForEach((e) =>
            {
                e.CreatedBy_Id = user.Id;
            });
            context.Set <Category>().AddOrUpdate(p => p.CategoryUId, categories.ToArray());
            context.SaveChanges();

            var adminUser = IposMembershipService.GetUserId("*****@*****.**");
            var products  = ImportExistingData <Product>(connetionString.ConnectionString).Result;

            products.ToList().ForEach((e) =>
            {
                e.CreatedBy_Id = user.Id;
                e.Category_UId = Rand.Next(1, categories.Count());
                e.Insert_UId   = adminUser;
            });
            context.Set <Product>().AddOrUpdate(p => p.ProductUId, products.ToArray());
            context.SaveChanges();
        }
Beispiel #2
0
        public HttpResponseMessage EditUserAccount(AppUserViewModel accountModel)
        {
            var response = new ApiResultViewModel <AppUserViewModel>();

            if (accountModel.Id != 0)
            {
                var account = _appUserMgr.FindById(accountModel.Id);

                if (account == null)
                {
                    response.errorMessage = "Account does not exist.";
                    return(Request.CreateResponse(response));
                }

                try
                {
                    account.FirstName      = accountModel.FirstName;
                    account.LastName       = accountModel.LastName;
                    account.Email          = accountModel.Email;
                    account.PhoneNumber    = accountModel.PhoneNumber;
                    account.LockoutEnabled = !accountModel.Status;

                    var result = _appUserMgr.Update(account);

                    if (result.Succeeded)
                    {
                        RemovePreviousRoles(account);
                        AddToMutipleRoles(accountModel, account.Id);
                        _appUserMgr.Update(account);

                        var eventDescription = String.Format("{0} account was edited.", account.UserName);

                        var membershipUserId = IposConfig.UseMembership ? (Guid?)IposMembershipService.GetUserId(User.Identity.Name) : null;

                        _auditSvc.LogEvent(eventDescription, AuditType.NEW_ACCOUNT, membershipUserId, User.Identity.GetUserId <int>());

                        response.message = "Account details has been updated.";
                    }
                    else
                    {
                        response.errorMessage = result.Errors.FirstOrDefault();
                    }
                }
                catch (Exception e)
                {
                    _logger.Log(e);
#if DEBUG
                    response.errorMessage = e.Message;
                    response.errorStatus  = true;
#else
                    response.errorMessage = "Error occured, please contact admin.";
                    response.errorStatus  = true;
#endif
                }
            }
            return(Request.CreateResponse(response));
        }
Beispiel #3
0
        public HttpResponseMessage EditProduct(ProductViewModel prodVM)
        {
            var response = new ApiResultViewModel <ProductViewModel>();

            try
            {
                var product = _prodSvc.GetProductById(prodVM.Id);

                if (product == null || product.IsDeleted)
                {
                    response.errorStatus  = true;
                    response.errorMessage = ("Sorry this product can not be found, Please contact your administrator");
                    Request.CreateResponse(response);
                }
                var fmrQty         = product.Quantity;
                var fmrName        = product.Name;
                var membershipId   = IposConfig.UseMembership ? (Guid?)IposMembershipService.GetUserId(User.Identity.Name) : null;
                var identityUserId = User.Identity.GetUserId <int>();

                product.ModifiedOnUtc  = DateTime.Now;
                product.ModifiedBy_Id  = identityUserId;
                product.Name           = prodVM.Name ?? product.Name;
                product.Description    = String.IsNullOrEmpty(prodVM.Description) ? product.Description : prodVM.Description;
                product.CostPrice      = prodVM.CostPrice;
                product.Price          = prodVM.SellPrice;
                product.Quantity       = prodVM.Quantity;
                product.Category_UId   = prodVM.Category;
                product.ReorderLevel   = prodVM.ReorderLevel;
                product.Notes          = String.IsNullOrEmpty(prodVM.Notes) ? product.Notes : prodVM.Notes;
                product.Barcode        = prodVM.Barcode;
                product.IsDiscountable = prodVM.IsDiscountable;

                SetExpiryDate(prodVM, product);

                _prodSvc.Update(product);

                response.message = "Item was successfully edited.";

                var eventDescription = String.Format("{0} Item with {1} quantity was edited to {2} with {3} quantity.", fmrName, fmrQty, product.Name, product.Quantity);
                _auditSvc.LogEvent(eventDescription, AuditType.EDIT_PRODUCT, membershipId, identityUserId);
            }
            catch (Exception ex)
            {
                _logger.Log(ex);
#if DEBUG
                response.errorMessage = ex.Message;
                response.errorStatus  = true;
#else
                response.errorMessage = "Error occured, please contact admin.";
                response.errorStatus  = true;
#endif
                return(Request.CreateResponse(response));
            }
            return(Request.CreateResponse(response));
        }
Beispiel #4
0
        public HttpResponseMessage CreateNewCategory(CategoryViewModel catVm)
        {
            var response = new ApiResultViewModel <CategoryViewModel>();

            try
            {
                var identityUserId = User.Identity.GetUserId <int>();

                var newCategoryItem = new Category()
                {
                    Name         = catVm.Name.Trim(),
                    Description  = catVm.Description,
                    CreatedBy_Id = identityUserId,
                    ParentCatId  = catVm.ParentCatId
                };

                _catSvc.NewCategory(newCategoryItem);

                if (newCategoryItem.HasErrors)
                {
                    response.errorStatus  = newCategoryItem.HasErrors;
                    response.errorMessage = newCategoryItem.ValidationErrors.FirstOrDefault() != null?
                                            newCategoryItem.ValidationErrors.FirstOrDefault().ErrorMessage : string.Empty;
                }
                else
                {
                    var membershipUserId = IposConfig.UseMembership ? (Guid?)IposMembershipService.GetUserId(User.Identity.Name) : null;

                    response.message = "Category was saved successfully";
                    var eventDescription = String.Format("{0} Category was created.", newCategoryItem.Name);
                    _cacheManager.Remove(Key);
                    _auditSvc.LogEvent(eventDescription, AuditType.NEW_CATEGORY, membershipUserId, identityUserId);
                }
            }
            catch (Exception ex)
            {
                _logger.Log(ex);
#if DEBUG
                response.errorMessage = ex.Message;
                response.errorStatus  = true;
#else
                response.errorMessage = "Error occured, please contact admin.";
                response.errorStatus  = true;
#endif
            }
            return(Request.CreateResponse(response));
        }
Beispiel #5
0
        public HttpResponseMessage EditCategory(CategoryViewModel catVm)
        {
            var response = new ApiResultViewModel <CategoryViewModel>();

            try
            {
                var identityUserId   = User.Identity.GetUserId <int>();
                var membershipUserId = IposConfig.UseMembership ? (Guid?)IposMembershipService.GetUserId(User.Identity.Name) : null;

                var category = _catSvc.GetCategoryById(catVm.CategoryUId);

                if (category == null || category.IsDeleted)
                {
                    response.errorStatus  = true;
                    response.errorMessage = "Sorry please this category could not be found or permanently deleted. Please contact administrator";
                }
                else
                {
                    var previousName = category.Name;
                    category.ModifiedOnUtc = DateTime.Now;
                    category.ModifiedBy_Id = identityUserId;
                    category.Name          = catVm.Name ?? category.Name;
                    category.Description   = String.IsNullOrEmpty(catVm.Description) ? category.Description : catVm.Description;
                    _catSvc.Update(category);

                    var eventDescription = String.Format("{0} Category was edited to {1}.", previousName, category.Name);
                    _auditSvc.LogEvent(eventDescription, AuditType.EDIT_PRODUCT, membershipUserId, identityUserId);
                    _cacheManager.Remove(Key);

                    response.message = "Category edit was successful.";
                }
            }
            catch (Exception ex)
            {
                _logger.Log(ex);
#if DEBUG
                response.errorMessage = ex.Message;
                response.errorStatus  = true;
#else
                response.errorMessage = "Error occured, please contact admin.";
                response.errorStatus  = true;
#endif
            }
            return(Request.CreateResponse(response));
        }
Beispiel #6
0
        public static ApplicationIdentityUser CreateAdminUser(IPosDbContext context)
        {
            var applicationUserManager = IdentityFactory.CreateUserManager(context);

            string username = "******";
            string password = "******";

            ApplicationIdentityUser user = applicationUserManager.FindByNameAsync(username).Result;

            if (user != null)
            {
                return(user);
            }

            user = new ApplicationIdentityUser
            {
                UserName = username,
                Email    = username
            };


            if (IposConfig.UseMembership)
            {
                IposMembershipService.CreateUserAccount(new AppUserViewModel {
                    UserName = username, Password = password
                });
            }


            applicationUserManager.CreateAsync(user, password).Wait();
            applicationUserManager.SetLockoutEnabled(user.Id, false);
            applicationUserManager.Update(user);

            var isInRole = applicationUserManager.IsInRoleAsync(user.Id, IposRoleHelper.ADMIN);

            if (user != null && !isInRole.Result)
            {
                applicationUserManager.AddToRoleAsync(user.Id, IposRoleHelper.ADMIN).Wait();
            }
            return(user);
        }
Beispiel #7
0
        public async Task <HttpResponseMessage> ChangingUserPassword(AppUserViewModel accountModel)
        {
            var response = new ApiResultViewModel <bool>();

            var changePwdResult = IposMembershipService.ChangeUserAccountPassword(accountModel.UserName, String.Empty, accountModel.NewPassword);

            if (!changePwdResult)
            {
                response.errorStatus  = true;
                response.errorMessage = string.Format("Password change was unsuccessful ");

                return(Request.CreateResponse(response));
            }

            if (ModelState.IsValid && accountModel.Id != 0)
            {
                var token = await _appUserMgr.GeneratePasswordResetTokenAsync(accountModel.Id);

                var result = await _appUserMgr.ResetPasswordAsync(accountModel.Id, token, accountModel.NewPassword);

                if (result.Succeeded)
                {
                    response.message = "Password change was successful.";
                    response.result  = true;
                }
                else
                {
                    response.errorStatus  = true;
                    response.errorMessage = string.Format("Password change was unsuccessful : {0}.", result.Errors.FirstOrDefault());
                }
            }
            else
            {
                response.errorStatus  = true;
                response.errorMessage = "Invalid request. Please confirm and try again.";
            }

            return(Request.CreateResponse(response));
        }
        public HttpResponseMessage TenderOrders(PostRequestViewModel request)
        {
            DateTime entrytDate;
            var      pendingPost = _cacheManager.Get <List <PostedProduct> >(PostKey);

            var response = new ApiResultViewModel <string>();

            if (!pendingPost.Any())
            {
                response.errorMessage = "Transaction could not be completed!. Please refresh your page and try again.";
                response.errorStatus  = true;
                return(Request.CreateResponse(response));
            }

            if (
                !DateTime.TryParseExact(request.entryDate, "dd/MM/yyyy", DateTimeFormatInfo.InvariantInfo,
                                        DateTimeStyles.None, out entrytDate))
            {
                response.errorMessage = "Transaction date is invalid.";
                response.errorStatus  = true;
                return(Request.CreateResponse(response));
            }

            AddCurrentTime(ref entrytDate);

            if (entrytDate > DateTime.Now)
            {
                response.errorMessage = "Transaction date cannot be in the future.";
                response.errorStatus  = true;
                return(Request.CreateResponse(response));
            }

            try
            {
                using (var uow = _orderSvc.UnitOfWork)
                {
                    uow.BeginTransaction();
                    var currentUserId = User.Identity.GetUserId <int>();
                    var order         = new Order
                    {
                        EntryDate    = entrytDate,
                        Remark       = request.remarks,
                        OrderUId     = Guid.NewGuid(),
                        Total        = 0,
                        OrderStatus  = (int)OrderStatus.POST,
                        CreatedBy_Id = currentUserId
                    };
                    if (IposConfig.UseMembership)
                    {
                        order.User_Id = IposMembershipService.GetUserId(User.Identity.Name);
                    }

                    _orderSvc.Add(order);

                    foreach (var pt in pendingPost)
                    {
                        AddMilliSecconds(ref entrytDate);
                        if (pt.Quantity <= 0)
                        {
                            continue;
                        }

                        var product = _productSvc.GetProductById(pt.Id);

                        if (product == null)
                        {
                            continue;
                        }

                        //entrytDate = entrytDate.AddMilliseconds(DateTime.Now.Millisecond);

                        var ordDt = new OrderDetail
                        {
                            EntryDate      = entrytDate,
                            OrderDetailUId = Guid.NewGuid(),
                            Remarks        = pt.Remarks ?? product.Description,
                            Quantiy        = pt.Quantity,
                            Price          = (product.Price ?? 0) * pt.Quantity,
                            Order_UId      = order.OrderUId,
                            Product_Id     = product.ProductId,
                            CostPrice      = product.CostPrice ?? (product.Price ?? 0),
                            CreatedBy_Id   = currentUserId,
                            Discount       = 0
                        };

                        order.Total      += ordDt.Price;
                        product.Quantity -= pt.Quantity;
                        _orderDetailSvc.Add(ordDt);
                        _productSvc.Update(product);
                    }
                    _orderSvc.Update(order);

                    uow.Commit();

                    _cacheManager.Remove(PostKey);
                    response.message = "Pending transactions was commited successfully.";
                }
            }
            catch (Exception ex)
            {
                _logger.Log(ex);
#if DEBUG
                response.errorMessage = ex.Message;
                response.errorStatus  = true;
#else
                response.errorMessage = "Error occured, please contact admin.";
                response.errorStatus  = true;
#endif
            }
            return(Request.CreateResponse(response));
        }
        public HttpResponseMessage RecallOrder(RecallRequestViewModel request)
        {
            var response = new ApiResultViewModel <OrderDetailViewModel>();

            try
            {
                if (request == null || Guid.Empty.Equals(request.itemId))
                {
                    response.errorStatus  = true;
                    response.errorMessage = "Invalid request. Please confirm and try again.";
                    return(Request.CreateResponse(response));
                }

                if (request.quantity <= 0 & request.price <= 0)
                {
                    response.errorStatus  = true;
                    response.errorMessage = "Please enter a valid quantity and price to complete recall action.";
                    return(Request.CreateResponse(response));
                }

                var orderDetail = _orderDetailSvc.GetOrderDetailByUId(request.itemId);

                if (orderDetail == null)
                {
                    response.errorStatus  = true;
                    response.errorMessage = "Transaction record not found.";
                    return(Request.CreateResponse(response));
                }

                if (request.quantity > orderDetail.Quantiy)
                {
                    response.errorStatus  = true;
                    response.errorMessage = String.Format("Stock quantity supplied cannot exceed {0}.", orderDetail.Quantiy);
                    return(Request.CreateResponse(response));
                }

                if (request.price > orderDetail.Price)
                {
                    response.errorStatus  = true;
                    response.errorMessage = String.Format("Stock price supplied cannot exceed N {0}.", orderDetail.Price);
                    return(Request.CreateResponse(response));
                }

                //var order = _orderSvc.GetOrderByUId(orderDetail.Order_UId);

                //if ((orderDetail == null || orderDetail.IsDeleted) || (order == null || order.IsDeleted))
                //{
                //    response.errorStatus = true;
                //    response.errorMessage = "Order not found.";
                //    return Request.CreateResponse(response);
                //}

                //if (orderDetail.Quantiy < request.quantity)
                //{
                //    response.errorStatus = true;
                //    response.errorMessage = "Quantity exceeds Order item quantity.";
                //    return Request.CreateResponse(response);
                //}

                //RecallOrderItem(request, orderDetail, order);

                var stockRecalled = _productSvc.GetProductById(orderDetail.Product_Id.Value);

                OrderDetail newOrderDt = new OrderDetail();
                newOrderDt.OrderDetailUId = Guid.NewGuid();

                Order newOrder = new Order();
                newOrder.OrderUId      = Guid.NewGuid();
                newOrder.EntryDate     = DateTime.Now;
                newOrder.OrderStatus   = (Int32)OrderStatus.RECALL;
                newOrder.Total         = (request.quantity * -request.price);
                newOrder.User_Id       = IposMembershipService.GetUserId(User.Identity.Name);
                newOrder.IsDiscounted  = request.price < orderDetail.Price ? true : false;
                newOrder.CreatedBy_Id  = User.Identity.GetUserId <Int32>();
                newOrder.PaymentMethod = (Int32)PaymentMethod.CASH;

                newOrderDt.EntryDate    = newOrder.EntryDate;
                newOrderDt.Order_UId    = newOrder.OrderUId;
                newOrderDt.Price        = -request.price;
                newOrderDt.Product_Id   = orderDetail.Product_Id;
                newOrderDt.CostPrice    = orderDetail.CostPrice;
                newOrderDt.CreatedBy_Id = User.Identity.GetUserId <int>();
                newOrderDt.Discount     = 0; //(Double?)(orderDetail.Price - request.price);
                newOrderDt.Quantiy      = orderDetail.Quantiy;

                stockRecalled.Quantity += request.quantity;

                newOrder.Remark = String.Format("Recall of {0} price was update to {1} and quantity to {2} reason being {0}"
                                                , stockRecalled.Name + " " + stockRecalled.Description, request.price, stockRecalled.Quantity, request.comment);

                using (var uow = _orderDetailSvc.UnitOfWork)
                {
                    _productSvc.Update(stockRecalled);
                    _orderSvc.Add(newOrder);
                    _orderDetailSvc.Add(newOrderDt);
                    uow.SaveChanges();
                }

                //response.result = Mapper.Map<OrderDetailViewModel>(orderDetail);
                response.message = "Recall action on stock item was successful.";
            }
            catch (Exception e)
            {
                _logger.Log(e);
#if DEBUG
                response.errorMessage = e.Message;
                response.errorStatus  = true;
#else
                response.errorMessage = "Error occured, please contact admin.";
                response.errorStatus  = true;
#endif
            }
            return(Request.CreateResponse(response));
        }
Beispiel #10
0
        public HttpResponseMessage DeleteUserAccount(int[] acctToDeleteIds)
        {
            var response = new ApiResultViewModel <List <int> >();

            if (acctToDeleteIds == null)
            {
                response.errorStatus  = true;
                response.errorMessage = "Incomplete delete request.";
                return(Request.CreateResponse(response));
            }

            try
            {
                var deletedacctId = new List <int>();

                foreach (var iterator in acctToDeleteIds)
                {
                    var account = _appUserMgr.FindById(iterator);

                    if (account == null)
                    {
                        response.errorStatus  = true;
                        response.errorMessage = "One or more selected user account does not exist.";
                        return(Request.CreateResponse(response));
                    }

                    if (IposConfig.UseMembership)
                    {
                        var deleteMember = IposMembershipService.DeleteAccount(account.UserName);

                        if (!deleteMember)
                        {
                            response.errorStatus  = true;
                            response.errorMessage = "One or more user account could not be deleted.";
                            continue;
                        }
                    }

                    if (account.Roles.Count > 0)
                    {
                        RemoveUserFromRole(account);
                    }

                    var result = _appUserMgr.DeleteAsync(account.Id).Result;

                    if (result.Succeeded)
                    {
                        deletedacctId.Add(iterator);
                    }
                }

                if (deletedacctId.Count == acctToDeleteIds.Length)
                {
                    response.message = "Selected user accounts has been deleted.";
                }

                else
                {
                    response.errorMessage = "Sorry! An error orccured while working.";
                    response.errorStatus  = true;
                }

                response.result = deletedacctId;
            }

            catch (Exception e)
            {
                _logger.Log(e);
#if DEBUG
                response.errorMessage = e.Message;
                response.errorStatus  = true;
#else
                response.errorMessage = "Error occured, please contact admin.";
                response.errorStatus  = true;
#endif
            }
            return(Request.CreateResponse(response));
        }
Beispiel #11
0
        public HttpResponseMessage CreateUserAccount(AppUserViewModel accountModel)
        {
            var response = new ApiResultViewModel <AppUserViewModel>();

            if (ModelState.IsValid)
            {
                var user = new AppUser
                {
                    Email          = accountModel.Email,
                    UserName       = accountModel.UserName,
                    PhoneNumber    = accountModel.PhoneNumber,
                    FirstName      = accountModel.FirstName,
                    LastName       = accountModel.LastName,
                    LockoutEnabled = !accountModel.Status
                };

                try
                {
                    if (IposConfig.UseMembership)
                    {
                        var membershipUser = IposMembershipService.CreateUserAccount(accountModel);

                        if (membershipUser.HasError)
                        {
                            response.errorMessage = membershipUser.ErrorMessage;
                            response.errorStatus  = true;
                            return(Request.CreateResponse(response));
                        }
                    }

                    var userRegisterResponse = _appUserMgr.Create(user, accountModel.Password);

                    if (userRegisterResponse.Succeeded)
                    {
                        AddToMutipleRoles(accountModel, user.Id);

                        var eventDescription = String.Format("{0} account was created.", accountModel.UserName);

                        var membershipUserId = IposConfig.UseMembership ? (Guid?)IposMembershipService.GetUserId(User.Identity.Name) : null;

                        _auditSvc.LogEvent(eventDescription, AuditType.NEW_ACCOUNT, membershipUserId, User.Identity.GetUserId <int>());

                        response.message = "New User account has been created.";
                        return(Request.CreateResponse(response));
                    }
                    else
                    {
                        response.errorMessage = userRegisterResponse.Errors.FirstOrDefault();
                    }
                }
                catch (Exception e)
                {
                    _logger.Log(e);

#if DEBUG
                    response.errorMessage = e.Message;
                    response.errorStatus  = true;
#else
                    response.errorMessage = "Error occured, please contact admin.";
                    response.errorStatus  = true;
#endif
                }
            }
            else
            {
                response.errorStatus  = true;
                response.errorMessage = "Cannot create user account with Incomplete fields.";
            }

            return(Request.CreateResponse(response));
        }
Beispiel #12
0
        public HttpResponseMessage EditWasteItem(SpoilViewModel spoilVm)
        {
            var response = new ApiResultViewModel <dynamic>();

            if (spoilVm == null || Guid.Empty == spoilVm.SpoilId || spoilVm.Quantity <= 0)
            {
                response.errorStatus  = true;
                response.errorMessage = "Invalid request. Please confirm and try again.";
            }

            try
            {
                using (var uow = _wasteSvc.UnitOfWork)
                {
                    var spoil = _wasteSvc.GetWastedById(spoilVm.SpoilId);

                    var product = _prodSvc.GetProductById(spoil.Product_Id.Value);
                    if (product == null)
                    {
                        response.errorStatus  = true;
                        response.errorMessage = "Product was not found.";
                        return(Request.CreateResponse(response));
                    }
                    var oldQty = spoil.Quantity;

                    if (product.Quantity < 0 || product.Quantity + (oldQty - spoilVm.Quantity) < 0)
                    {
                        response.errorStatus  = true;
                        response.errorMessage = "Cannot report waste for a negative product.";
                        return(Request.CreateResponse(response));
                    }

                    var membershipId   = IposConfig.UseMembership ? (Guid?)IposMembershipService.GetUserId(User.Identity.Name) : null;
                    var identityUserId = User.Identity.GetUserId <int>();
                    spoil.Quantity    = spoilVm.Quantity;
                    product.Quantity += (oldQty - spoilVm.Quantity);

                    _prodSvc.Update(product);
                    _wasteSvc.Update(spoil);

                    var eventDescription = String.Format("Waste {0} item was edited.", product.Name);

                    _auditSvc.LogEvent(eventDescription, AuditType.EDIT_WASTE, membershipId, identityUserId);
                    uow.SaveChanges();
                    response.message = "Waste item has been updated";
                    response.result  = new { productName = product.Name, spoil.Quantity, spoil.SpoilId, EntryDate = spoil.EntryDate.Value.ToString("dd/MM/yyyy") };
                }
            }
            catch (Exception e)
            {
                _logger.Log(e);
#if DEBUG
                response.errorMessage = e.Message;
                response.errorStatus  = true;
#else
                response.errorMessage = "An error occurred while working, Please try again or contact support.";
                response.errorStatus  = true;
#endif
                return(Request.CreateResponse(response));
            }
            return(Request.CreateResponse(response));
        }
Beispiel #13
0
        public HttpResponseMessage CreateQuantityOfStock(QuantityViewModel quantityVM)
        {
            var response = new ApiResultViewModel <QuantityViewModel>();

            if (quantityVM == null || quantityVM.Id == 0)
            {
                response.errorStatus  = true;
                response.errorMessage = "Invalid request.";
                return(Request.CreateResponse(response));
            }

            try
            {
                using (var uow = _prodSvc.UnitOfWork)
                {
                    uow.BeginTransaction();
                    var product = _prodSvc.GetProductById(quantityVM.Id);
                    if (product == null)
                    {
                        response.errorStatus  = true;
                        response.errorMessage = "Product was not found.";
                        return(Request.CreateResponse(response));
                    }

                    if (quantityVM.Quantity == null)
                    {
                        response.errorStatus  = true;
                        response.errorMessage = "Please enter a value for the quantity";
                        return(Request.CreateResponse(response));
                    }

                    var membershipId = IposConfig.UseMembership ? (Guid?)IposMembershipService.GetUserId(User.Identity.Name) : null;

                    var identityUserId = User.Identity.GetUserId <int>();



                    product.Quantity += quantityVM.Quantity;


                    product.ProductId    = product.ProductId;
                    product.CreatedBy_Id = identityUserId;
                    //newQuantity.ModifiedBy_Id = membershipId(int);

                    // newSpoil.User_Id = membershipId;

                    _prodSvc.Update(product);

                    if (product.HasErrors)
                    {
                        response.errorStatus  = product.HasErrors;
                        response.errorMessage = product.ValidationErrors.FirstOrDefault() != null?
                                                product.ValidationErrors.FirstOrDefault().ErrorMessage : String.Empty;
                    }
                    else
                    {
                        quantityVM.Quantity = product.Quantity;

                        var eventDescription = String.Format("{0} quantity of {1} was updated.", product.Quantity, product.Name);
                        _auditSvc.LogEvent(eventDescription, AuditType.NEW_PRODUCT, membershipId, identityUserId);
                        uow.Commit();
                        response.message = "Quantity has now been updated.";
                        response.result  = quantityVM;
                    }

                    // return Request.CreateResponse(response);
                }
            }
            catch (Exception ex)
            {
                _logger.Log(ex);

#if DEBUG
                response.errorMessage = ex.Message;
                response.errorStatus  = true;
#else
                response.errorMessage = "Error occured, please contact admin.";
                response.errorStatus  = true;
#endif
            }
            return(Request.CreateResponse(response));
        }
Beispiel #14
0
        public HttpResponseMessage CreateWasteStock(SpoilViewModel spoilVM)
        {
            var response = new ApiResultViewModel <dynamic>();

            if (spoilVM == null || spoilVM.Id == 0)
            {
                response.errorStatus  = true;
                response.errorMessage = "Invalid request.";
                return(Request.CreateResponse(response));
            }

            try
            {
                using (var uow = _spoilSvc.UnitOfWork)
                {
                    uow.BeginTransaction();
                    var product = _prodSvc.GetProductById(spoilVM.Id);
                    if (product == null)
                    {
                        response.errorStatus  = true;
                        response.errorMessage = "Product was not found.";
                        return(Request.CreateResponse(response));
                    }

                    if (product.Quantity < 0 || product.Quantity - spoilVM.Quantity < 0)
                    {
                        response.errorStatus  = true;
                        response.errorMessage = "Cannot report waste for a negative product.";
                        return(Request.CreateResponse(response));
                    }
                    var newSpoil     = new Spoil();
                    var membershipId = IposConfig.UseMembership ? (Guid?)IposMembershipService.GetUserId(User.Identity.Name) : null;

                    var identityUserId = User.Identity.GetUserId <int>();
                    newSpoil.Title        = product.Name;
                    newSpoil.Description  = spoilVM.Description;
                    newSpoil.Quantity     = spoilVM.Quantity;
                    newSpoil.Product_Id   = product.ProductId;
                    newSpoil.CreatedBy_Id = identityUserId;
                    newSpoil.User_Id      = membershipId;

                    _spoilSvc.NewWaste(newSpoil);

                    if (newSpoil.HasErrors)
                    {
                        response.errorStatus  = newSpoil.HasErrors;
                        response.errorMessage = newSpoil.ValidationErrors.FirstOrDefault() != null?
                                                newSpoil.ValidationErrors.FirstOrDefault().ErrorMessage : String.Empty;
                    }
                    else
                    {
                        product.Quantity -= newSpoil.Quantity;
                        _prodSvc.Update(product);
                        var eventDescription = String.Format("{0} quantity of {1} was entered as a waste.", newSpoil.Quantity, product.Name);
                        _auditSvc.LogEvent(eventDescription, AuditType.NEW_WASTE, membershipId, identityUserId);
                        uow.Commit();
                        response.result  = new { product.Quantity, Id = product.ProductId };
                        response.message = "Waste has now been reported.";
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Log(ex);

#if DEBUG
                response.errorMessage = ex.Message;
                response.errorStatus  = true;
#else
                response.errorMessage = "Error occured, please contact admin.";
                response.errorStatus  = true;
#endif
            }
            return(Request.CreateResponse(response));
        }
Beispiel #15
0
        public HttpResponseMessage CreateNewProd(ProductViewModel prodVM, bool isDiscountable = false)
        {
            var response = new ApiResultViewModel <ProductViewModel>();

            try
            {
                if (prodVM.CanExpire && string.IsNullOrEmpty(prodVM.ExpiryDate))
                {
                    response.errorStatus  = true;
                    response.errorMessage = "Expiry Date is required.";
                    return(Request.CreateResponse(response));
                }

                var identityUserId = User.Identity.GetUserId <int>();

                var membershipUserId = IposConfig.UseMembership ? (Guid?)IposMembershipService.GetUserId(User.Identity.Name) : null;
                var newProd          = new Product
                {
                    Name           = prodVM.Name.Trim(),
                    Description    = prodVM.Description,
                    CostPrice      = prodVM.CostPrice ?? 0,
                    Price          = prodVM.SellPrice ?? 0,
                    Quantity       = prodVM.Quantity ?? 0,
                    Category_UId   = prodVM.Category,
                    ReorderLevel   = prodVM.ReorderLevel ?? 0,
                    Notes          = prodVM.Notes,
                    IsDiscountable = prodVM.IsDiscountable,
                    Barcode        = prodVM.Barcode,
                    CreatedBy_Id   = identityUserId,
                    Insert_UId     = membershipUserId
                };

                SetExpiryDate(prodVM, newProd);

                if (newProd.CanExpire && DateTime.Today > newProd.ExpiryDate)
                {
                    response.errorStatus  = true;
                    response.errorMessage = "Expiry Date must be a date beyond today.";
                    return(Request.CreateResponse(response));
                }

                if (_prodSvc.ProductBarcodeExists(newProd.Barcode))
                {
                    response.errorStatus  = true;
                    response.errorMessage = "Barcode already exists for another product.";
                    return(Request.CreateResponse(response));
                }

                _prodSvc.NewProduct(newProd);

                if (newProd.HasErrors)
                {
                    response.errorStatus  = newProd.HasErrors;
                    response.errorMessage = newProd.ValidationErrors.FirstOrDefault() != null?
                                            newProd.ValidationErrors.FirstOrDefault().ErrorMessage : String.Empty;
                }
                else
                {
                    response.errorStatus  = false;
                    response.errorMessage = "Product was saved successfully";
                }

                var eventDescription = String.Format("{0} item was created ", newProd.Name);
                _auditSvc.LogEvent(eventDescription, AuditType.NEW_PRODUCT, membershipUserId, identityUserId);
            }
            catch (Exception ex)
            {
                _logger.Log(ex);

#if DEBUG
                response.errorMessage = ex.Message;
                response.errorStatus  = true;
#else
                response.errorMessage = "Error occured, please contact admin.";
                response.errorStatus  = true;
#endif

                return(Request.CreateResponse(HttpStatusCode.InternalServerError, response));
            }
            return(Request.CreateResponse(response));
        }