Example #1
0
        public void PutPartner_Negative_TestCases_TestResults_Invalid_UserStatus()
        {
            //Assign
            var _mockAdminMethod = new Mock <AdminManager>();

            UserModified PartnerData = new UserModified()
            {
                UserId          = 1,
                UserName        = "******",
                UserEmail       = "*****@*****.**",
                UserPhoneNumber = "98236466",
                UserAddress     = "scf",
                UserType        = "Partn",
                UserStatus      = "on"
            };
            var InalidUserStatus_Response = PutPartner_Mock_Negative_Invalid_UserStatus();

            _mockAdminMethod.Setup(p => p.UpdatePartner(PartnerData, 1)).Returns(InalidUserStatus_Response);
            AdminController _AdminController = new AdminController(_mockAdminMethod.Object);
            //Act
            var _returnedPartnersResp = _AdminController.Getpartnerdata();
            // var _returnedUsersAck = _returnedUsersResp as OkObjectResult;
            var _originalPartnersAck = PutPartner_Mock_Negative_Invalid_UserStatus();

            //Assert
            //Assert.IsNotNull(_returnedPartnersResp);
            Assert.ReferenceEquals(_returnedPartnersResp, _originalPartnersAck);
        }
Example #2
0
        private Acknowledgement <UserModified> Getpartnerdata_Mock_Positive()
        {
            UserModified PartnerData = new UserModified()
            {
                UserId          = 1,
                UserName        = "******",
                UserEmail       = "*****@*****.**",
                UserPhoneNumber = "9823623466",
                UserAddress     = "Nagpur",
                UserType        = "Partner",
                UserStatus      = "valid"
            };

            List <UserModified> partnerList = new List <UserModified>();

            partnerList.Add(PartnerData);

            var partner_ack = new Acknowledgement <UserModified>
            {
                code    = 0,
                Set     = partnerList,
                Message = "Partnerdata loading failed"
            };

            return(partner_ack);
        }
        public IActionResult PutPartner([FromRoute] int PartnerId, [FromBody] UserModified user)
        {
            Acknowledgement <UserModified> aknowledgement = new Acknowledgement <UserModified>();

            try
            {
                if (!(PartnerId == user.UserId))
                {
                    aknowledgement.code    = 2;
                    aknowledgement.Set     = null;
                    aknowledgement.Message = "PartnerId and UserId does not match";
                    return(Ok(aknowledgement));
                }
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                return(Ok(adminManager.UpdatePartner(user, PartnerId)));
            }
            catch (Exception)
            {
                aknowledgement.code    = 2;
                aknowledgement.Set     = null;
                aknowledgement.Message = "Something went wrong. Please try again later";
                return(Ok(aknowledgement));
            }
        }
Example #4
0
        private Acknowledgement <UserModified> GetUsersDetails_Mock_Positive()
        {
            UserModified userData = new UserModified()
            {
                UserId          = 1,
                UserName        = "******",
                UserEmail       = "*****@*****.**",
                UserPhoneNumber = "9823625981",
                UserAddress     = "Nagpur",
                UserType        = "Partner",
                UserStatus      = "valid"
            };

            List <UserModified> userList = new List <UserModified>();

            userList.Add(userData);

            var users_ack = new Acknowledgement <UserModified>
            {
                code    = 0,
                Set     = userList,
                Message = "Success"
            };

            return(users_ack);
        }
Example #5
0
        //This method will get the partner data from database

        public List <UserModified> Getpartnerdata()
        {
            try
            {
                IList <User>        lstUsers    = roomDb.FMRUsers.ToList();
                List <UserModified> PartnerData = new List <UserModified>();
                foreach (var item in lstUsers)
                {
                    if (item.UserType == "Partner")
                    {
                        UserModified user = new UserModified();
                        user.UserId          = item.UserId;
                        user.UserName        = item.UserName;
                        user.UserEmail       = item.UserEmail;
                        user.UserPhoneNumber = item.UserPhoneNumber;
                        user.UserStatus      = item.UserStatus;
                        user.UserType        = item.UserType;
                        user.UserAddress     = item.UserAddress;
                        PartnerData.Add(user);
                    }
                }


                return(PartnerData);
            }
            catch (Exception ex)
            {
                throw new RetrievingDataException(ex.Message);
            }
        }
Example #6
0
        //This method will update partner data
        public List <UserModified> GetUserDetails()
        {
            IList <User>        lstUsers = roomDb.FMRUsers.ToList();
            List <UserModified> UserData = new List <UserModified>();

            try
            {
                using (var context = new FindMyRoomDb())
                {
                    foreach (var item in lstUsers)
                    {
                        if (item.UserType == "Partner")
                        {
                            UserModified user = new UserModified();
                            user.UserId          = item.UserId;
                            user.UserName        = item.UserName;
                            user.UserEmail       = item.UserEmail;
                            user.UserPhoneNumber = item.UserPhoneNumber;
                            user.UserAddress     = item.UserAddress;
                            user.UserStatus      = item.UserStatus;
                            user.UserAddress     = item.UserAddress;
                            user.UserType        = item.UserType;
                            UserData.Add(user);
                        }
                    }
                }
                return(UserData);
            }
            catch (Exception ex)
            {
                throw new InsertingDataException(ex.Message);
            }
        }
Example #7
0
        // UserService signup = new UserService();
        public static string validations(UserModified user)
        {
            AdminService update1 = new AdminService();

            // Regex UserId = new Regex(@"^$");
            Regex Name = new Regex(@"^[a-zA-Z\s]*$");
            //Regex Email = new Regex(@"^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$");
            Regex MobileNumber = new Regex(@"[6/7/8/9]{1}[0-9]{9}$");
            //Regex Password = new Regex(@"(?=^.{6,20}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&amp;*()_+}{&quot;:;'?/&gt;.&lt;,])(?!.*\s).*$");
            int    Count1 = 0;
            string type   = "";

            foreach (var item in update1.GetUserDetails())
            {
                if ((item.UserId == user.UserId))
                {
                    Count1++;
                    type = item.UserType;
                }
            }
            if (Count1 == 1 && !(type.Equals("partner", StringComparison.OrdinalIgnoreCase)))
            {
                return("User is not a partner");
            }
            if (Count1 == 0)
            {
                return("UserID does not exist");
            }
            if (!Name.IsMatch(user.UserName))
            {
                return("Username is invalid");
            }
            else if (!MobileNumber.IsMatch(user.UserPhoneNumber))
            {
                return("Mobile number should start with 6/7/8/9 and should have 10 digits");
            }
            else if (!user.UserType.Equals("Partner", StringComparison.OrdinalIgnoreCase))
            {
                return("user type should be Partner");
            }
            else if (!(user.UserStatus.Equals("valid", StringComparison.OrdinalIgnoreCase) || user.UserStatus.Equals("invalid", StringComparison.OrdinalIgnoreCase)))
            {
                return("user status should be valid or invalid");
            }
            else
            {
                return("success");
            }
        }
Example #8
0
        public async Task UpdateAllInventories(int orderId, UserModified userModified)
        {
            var orderItems = await _unitOfWork.OrderItemRepository
                             .FindByCondition(oi => oi.OrderId == orderId)
                             .AsNoTracking()
                             .ToListAsync();

            var inventories = await _unitOfWork.InventoryRepository
                              .FindAll()
                              .AsNoTracking()
                              .OrderByDescending(t => t.CreatedDate)
                              .ToListAsync();

            var iventoryModels        = new List <Inventory>();
            var listProductIdsUpdated = inventories.Select(i => i.ProductId).ToList();

            if (inventories.Any())
            {
                inventories = inventories.GroupBy(i => i.ProductId)
                              .Select(grp => grp.FirstOrDefault())
                              .ToList();
                foreach (var inventory in inventories)
                {
                    var orderItemsFound = orderItems.Where(o => o.ProductId == inventory.ProductId).ToList();
                    iventoryModels.Add(CreateInventoryModel(inventory.ProductId,
                                                            inventory.AmountOfImport,
                                                            orderItemsFound.Sum(o => o.Amount),
                                                            userModified));
                }
            }
            if (orderItems.Any())
            {
                var orderItemsGroupByProductId = orderItems.Where(o => !listProductIdsUpdated.Contains(o.ProductId))
                                                 .GroupBy(i => i.ProductId)
                                                 .Select(grp => grp.FirstOrDefault())
                                                 .ToList();
                foreach (var inventory in orderItemsGroupByProductId)
                {
                    var orderItemsFound = orderItems.Where(o => o.ProductId == inventory.ProductId).ToList();
                    iventoryModels.Add(CreateInventoryModel(inventory.ProductId,
                                                            0,
                                                            orderItemsFound.Sum(o => o.Amount),
                                                            userModified));
                }
            }

            _unitOfWork.InventoryRepository.AddRange(iventoryModels);
            await _unitOfWork.Commit();
        }
Example #9
0
        public async Task <ApiJsonResult> Delete(int?tenantId, long userId, int id)
        {
            var result = new ApiJsonResult();
            var order  = await GetById(id).AsNoTracking().FirstOrDefaultAsync();

            if (order == null)
            {
                result.Code    = CodeModel.Fail;
                result.Message = "Order is not found";
                return(result);
            }
            var orderNoteModel = await _unitOfWork.OrderNoteRepository
                                 .FindByCondition(on => on.OrderId == order.Id)
                                 .FirstOrDefaultAsync();

            if (orderNoteModel != null)
            {
                _unitOfWork.OrderNoteRepository.Delete(orderNoteModel);
            }
            var orderItemModels = await _unitOfWork.OrderItemRepository
                                  .FindByCondition(oi => oi.OrderId == order.Id)
                                  .AsNoTracking()
                                  .ToListAsync();

            if (orderItemModels.Any())
            {
                _unitOfWork.OrderItemRepository.RemoveRange(orderItemModels);
            }

            var shipmentModel = await _unitOfWork.ShipmentRepository
                                .FindByCondition(s => s.OrderId == order.Id)
                                .AsNoTracking()
                                .FirstOrDefaultAsync();

            if (shipmentModel != null)
            {
                _unitOfWork.ShipmentRepository.Delete(shipmentModel);
            }
            _unitOfWork.OrderRepository.Delete(order);
            await _unitOfWork.Commit();

            var userModified = new UserModified
            {
                TenantId = tenantId,
                UserId   = userId
            };

            return(result);
        }
Example #10
0
        private Inventory CreateInventoryModel(
            int productId,
            int currentAmountOfImport,
            int currentAmountOfExport,
            UserModified userModified)
        {
            var inventoryModel = new Inventory
            {
                ProductId      = productId,
                Amount         = currentAmountOfImport - currentAmountOfExport,
                AmountOfImport = currentAmountOfImport,
                AmountOfExport = currentAmountOfExport,
                TenantId       = userModified.TenantId.Value,
                CreatedDate    = DateTime.Now,
                UserModifiedId = userModified.UserId,
            };

            return(inventoryModel);
        }
Example #11
0
        private Acknowledgement <UserModified> PutPartner_Mock_Negative_Invalid_UserStatus()
        {
            Acknowledgement <UserModified> aknowledgement = new Acknowledgement <UserModified>();
            List <UserModified>            partnerList    = new List <UserModified>();
            UserModified PartnerData = new UserModified()
            {
                UserId          = 1,
                UserName        = "******",
                UserEmail       = "*****@*****.**",
                UserPhoneNumber = "9823625674",
                UserAddress     = "Nagpur",
                UserType        = "Partner",
                UserStatus      = "sts"
            };

            partnerList.Add(PartnerData);
            aknowledgement.code    = 2;
            aknowledgement.Set     = partnerList;
            aknowledgement.Message = "UserType is invalid";
            return(aknowledgement);
        }
Example #12
0
        private Acknowledgement <UserModified> PutPartner_Mock_Negative_Invalid_phonenumber()
        {
            Acknowledgement <UserModified> aknowledgement = new Acknowledgement <UserModified>();
            UserModified PartnerData = new UserModified()
            {
                UserId          = 1,
                UserName        = "******",
                UserEmail       = "*****@*****.**",
                UserPhoneNumber = "982362",
                UserAddress     = "Nagpur",
                UserType        = "Partner",
                UserStatus      = "valid"
            };

            List <UserModified> partnerList = new List <UserModified>();

            partnerList.Add(PartnerData);
            aknowledgement.code    = 2;
            aknowledgement.Set     = partnerList;
            aknowledgement.Message = "Mobile number should start with 6/7/8/9 and should have 10 digits";
            return(aknowledgement);
        }
Example #13
0
        }//end EditUser

        public async Task <IActionResult> EditUserConfirm(SignupViewModel model, List <IFormFile> img, string Id)
        {
            string nvm;
            var    user = await _userManager.FindByIdAsync(Id);

            var userModifier = await _userManager.FindByNameAsync(User.Identity.Name);

            try
            {
                if (user == null)
                {
                    nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Record_Not_Exist, contentRootPath);
                    return(RedirectToAction("UserList", new { notification = nvm }));
                }


                //check if other users want to change 'Admin' deny their access to do that
                var userModifierRoleId   = _db.UserRoles.Where(x => x.UserId == userModifier.Id).FirstOrDefault().RoleId;
                var userModifierRoleName = _db.Roles.Where(x => x.Id == userModifierRoleId).FirstOrDefault().Name;

                var userRoleId   = _db.UserRoles.Where(x => x.UserId == Id).FirstOrDefault().RoleId;
                var userRoleName = _db.Roles.Where(x => x.Id == userRoleId).FirstOrDefault().Name;
                if (userModifierRoleName != "Admin" && userRoleName == "Admin")
                {
                    nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Access_denied, contentRootPath);
                    return(RedirectToAction("UserList", new { notification = nvm }));
                }

                if (model.CurrentPassword != null && model.NewPassword != null && model.ConfirmNewPassword != null)
                {
                    if (userModifier == user || userModifierRoleName == "Admin")
                    {
                        var statusPasswordChange = await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword);
                    }
                }

                //Get Backup From The User Into 'UserModified' Table
                var userJSONForBackup = JsonConvert.SerializeObject(user);

                using (var transaction = _db.Database.BeginTransaction())
                {
                    UserModified UM = new UserModified()
                    {
                        LastUserBackupJson = userJSONForBackup,
                        ModifedByUserId    = userModifier.Id,
                        UserId             = user.Id,
                        Comment            = "Edited by " + userModifier.UserName
                    };
                    _dbUserModified.Insert(UM);

                    var greDate = CustomizeCalendar.PersianToGregorian(model.Dateofbirth ?? DateTime.Now);
                    user.FirstName   = model.Firstname;
                    user.LastName    = model.Lastname;
                    user.Email       = model.Email;
                    user.PhoneNumber = model.Phonenumber;
                    user.SpecialUser = model.Specialuser;
                    //user.Status = model.Status;
                    user.DateOfBirth = greDate;
                    if (model.Gender == true)
                    {
                        user.Gendre = 1; //male
                    }
                    else if (model.Gender == false)
                    {
                        user.Gendre = 2; //female
                    }
                    else
                    {
                        user.Gendre = null; //not specified
                    }

                    if (userRoleName != model.RoleName)
                    {
                        if (userModifierRoleName != "Admin")
                        {
                            nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Access_denied, contentRootPath);
                            return(RedirectToAction("UserList", new { notification = nvm }));
                        }
                    }
                    //only admin can disable other users
                    if (userModifierRoleName == "Admin")
                    {
                        //"*****@*****.**" will never be disable
                        if (user.UserName == MainAdmin)
                        {
                            user.Status = model.Status;
                            //change user role
                            IdentityResult rol_status_1 = new IdentityResult(), rol_status_2 = new IdentityResult();
                            if (userRoleName != model.RoleName)
                            {
                                rol_status_1 = await _userManager.RemoveFromRoleAsync(user, userRoleName);

                                rol_status_2 = await _userManager.AddToRoleAsync(user, model.RoleName);
                            }
                        }
                        else
                        {
                            nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Access_denied, contentRootPath);
                            return(RedirectToAction("UserList", new { notification = nvm }));
                        }
                    }


                    //--------------------------------
                    if (img.Count > 0)
                    {
                        //disable the last images of the user
                        var doesUserHaveImage = _db.UserImage.Where(x => x.UserId == Id).ToList();
                        if (doesUserHaveImage.Count > 0)
                        {
                            foreach (var item in doesUserHaveImage)
                            {
                                var lastImagesOfUser = _dbUserImage.FindById(item.Id);
                                lastImagesOfUser.Status  = false;
                                lastImagesOfUser.Comment = $"Edited by {userModifier.UserName}";
                                _db.UserImage.Update(lastImagesOfUser);
                            }
                        }
                        //--------------------------------
                        //add new image of the user
                        UserImage userImage = new UserImage()
                        {
                            UserId  = Id,
                            Caption = model.Lastname + "_" + DateTime.Now
                        };
                        img.ForEach(x =>
                        {
                            if (x != null)
                            {
                                byte[] b = new byte[x.Length];
                                x.OpenReadStream().Read(b, 0, b.Length);
                                userImage.Image = b;

                                //Make Thumbnail
                                MemoryStream mem1 = new MemoryStream(b);
                                Image img2        = Image.FromStream(mem1);
                                Bitmap bmp        = new Bitmap(img2, 120, 120);
                                MemoryStream mem2 = new MemoryStream();
                                bmp.Save(mem2, System.Drawing.Imaging.ImageFormat.Jpeg);
                                userImage.ImageThumbnail = mem2.ToArray();
                            }
                        });
                        _dbUserImage.Insert(userImage);
                    }



                    //--------------------------------
                    var status = await _userManager.UpdateAsync(user);

                    if (status.Succeeded)
                    {
                        transaction.Commit(); //Save the new records in 'User' table and 'UserImage' table

                        nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Success_Update, contentRootPath);
                        return(RedirectToAction("UserList", new { notification = nvm }));
                    }
                }
                nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Failed_Update, contentRootPath);
                return(RedirectToAction("UserList", new { notification = nvm }));
            }
            catch (Exception)
            {
                nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Failed_Update, contentRootPath);
                return(RedirectToAction("UserList", new { notification = nvm }));
            }
        }//end EditUserConfirm
Example #14
0
        public async Task <ApiJsonResult> Create(int?tenantId, long userId, OrderItemDto data)
        {
            var result          = new ApiJsonResult();
            var orderItemModels = new List <OrderItem>();

            foreach (var product in data.Products)
            {
                var orderItem = new OrderItem
                {
                    TenantId       = tenantId.Value,
                    ProductId      = product.Id,
                    Amount         = product.Amount,
                    Price          = product.Price,
                    CreatedDate    = DateTime.Now,
                    UserModifiedId = userId
                };
                orderItemModels.Add(orderItem);
            }
            var orderModel = new Order
            {
                CustomerId = data.CustomerId,
                SellerId   = data.SellerId,
                TenantId   = tenantId.Value,
                OrderNote  = new OrderNote
                {
                    TenantId       = tenantId.Value,
                    Note           = data.OrderNote,
                    CreatedDate    = DateTime.Now,
                    UserModifiedId = userId
                },
                OrderCode      = Constants.GenerateCode(),
                OrderItems     = orderItemModels,
                SaleDate       = data.SaleDateUtc,
                CreatedDate    = DateTime.Now,
                UserModifiedId = userId,
                OrderType      = data.OrderType,
                OrderTotal     = data.OrderTotal,
                OrderDiscount  = data.OrderDiscount,
                OrderPaid      = data.OrderPaid,
                OrderDebt      = data.OrderDebt,
                StoreId        = data.StoreId,
                OrderStatusId  = OrderStatus.Ordered
            };

            switch (data.OrderType)
            {
            case OrderType.Order:
                if (data.CarrierId.HasValue)
                {
                    var shipment = new Shipment
                    {
                        TenantId        = tenantId.Value,
                        DeliveryDateUtc = data.DeliveryDate,
                        Note            = data.ShipmentNote,
                        Shipper         = data.Shipper,
                        CarrierId       = data.CarrierId,
                        CreatedDate     = DateTime.Now,
                        UserModifiedId  = userId
                    };
                    orderModel.Shipment = shipment;
                }
                break;

            case OrderType.Sale:
            case OrderType.ReturnSupplier:
                orderModel.PaymentMethodId = data.PaymentMethodId;
                break;

            default:
                break;
            }
            _salesDbContext.Add(orderModel);
            await _unitOfWork.Commit();

            var userModified = new UserModified
            {
                TenantId = tenantId,
                UserId   = userId
            };
            await _inventoryService.UpdateAllInventories(orderModel.Id, userModified);

            return(result);
        }
Example #15
0
        private Acknowledgement <UserModified> PutPartner_Mock_Positive_TestCases_TestResults(UserModified user, int partnerId)
        {
            Acknowledgement <UserModified> aknowledgement = new Acknowledgement <UserModified>();
            List <UserModified>            partnerList    = new List <UserModified>();

            partnerList.Add(user);
            aknowledgement.code    = 0;
            aknowledgement.Set     = partnerList;
            aknowledgement.Message = "Success";
            return(aknowledgement);
        }
Example #16
0
        private Acknowledgement <UserModified> PutPartner_Mock_NegativeTestMismatchedId(UserModified user, int partnerId)
        {
            Acknowledgement <UserModified> aknowledgement = new Acknowledgement <UserModified>();

            if (user.UserId != partnerId)
            {
                aknowledgement.code    = 2;
                aknowledgement.Set     = null;
                aknowledgement.Message = "PartnerId and UserId does not match";
                return(aknowledgement);
            }
            else
            {
                List <UserModified> partnerList = new List <UserModified>();
                partnerList.Add(user);
                aknowledgement.code    = 0;
                aknowledgement.Set     = partnerList;
                aknowledgement.Message = "Success";
                return(aknowledgement);
            }
        }
Example #17
0
        //This method will do validations for existance of email and type of partner and if not exists it inserts data.

        public virtual Acknowledgement <UserModified> UpdatePartner(UserModified user, int id)
        {
            Acknowledgement <UserModified> acknowledgement = new Acknowledgement <UserModified>();

            try
            {
                List <UserModified> partners = new List <UserModified>();
                partners.Add(user);
                User getuser = update.GetPartner(id);

                string validator = validations(user);
                if (!validator.Equals("success"))
                {
                    acknowledgement.code    = 2;
                    acknowledgement.Set     = partners;
                    acknowledgement.Message = validator;
                    return(acknowledgement);
                }
                else
                {
                    string name    = user.UserName.Trim();
                    string address = user.UserAddress.Trim();
                    if (name.Equals(""))
                    {
                        acknowledgement.code    = 2;
                        acknowledgement.Set     = partners;
                        acknowledgement.Message = "Full Name field should not empty";
                        return(acknowledgement);
                    }
                    else if ((address.Equals("")))
                    {
                        acknowledgement.code    = 2;
                        acknowledgement.Set     = partners;
                        acknowledgement.Message = "Address field should not be empty";
                        return(acknowledgement);
                    }
                    else if (!(user.UserEmail.Equals(getuser.UserEmail)))
                    {
                        acknowledgement.code    = 2;
                        acknowledgement.Set     = partners;
                        acknowledgement.Message = "Email id cannot be updated";
                        return(acknowledgement);
                    }
                    else
                    {
                        acknowledgement.code    = 0;
                        acknowledgement.Set     = partners;
                        acknowledgement.Message = "Successfully updated.";
                        update.UpdatePartner(user, id);
                        return(acknowledgement);
                    }
                }

                //return acknowledgement;

                //List<User> partners = new List<User>();
                //partners.Add(user);

                //if (partners == null)
                //{
                //    acknowledgement.code = 2;
                //    acknowledgement.Set = partners;
                //    acknowledgement.Message = "Partnerdata loading failed";
                //    return acknowledgement;
                //}
                //acknowledgement.code = 0;
                //acknowledgement.Set = partners;
                //acknowledgement.Message = "Partnerdata loaded successfully";
                //update.UpdatePartner(user, id);
                //return acknowledgement;
            }
            catch (Exception ex)
            {
                throw new InsertingDataException(ex.Message);
            }
        }
Example #18
0
        public void UpdatePartner(UserModified user, int id)
        {
            try
            {
                //var toUpdate = (from users in roomDb.FMRUsers where user.UserId == id select users).FirstOrDefault();
                //toUpdate = user;

                //   (from p in roomDb.FMRUsers
                //where p.UserId == id
                //select p).ToList().ForEach(x => {
                //    x.UserStatus = user.UserStatus;
                //    x.UserPhoneNumber = user.UserPhoneNumber;
                //    });

                //roomDb.FMRUsers.Update(user);
                User updatePartner = (User)roomDb.FMRUsers.Find(id);
                if (updatePartner == null)
                {
                    return;
                }

                updatePartner.UserName = user.UserName;

                updatePartner.UserAddress     = user.UserAddress;
                updatePartner.UserPhoneNumber = user.UserPhoneNumber;
                updatePartner.UserStatus      = user.UserStatus;

                roomDb.SaveChanges();
                if (user.UserStatus.Equals("invalid"))
                {
                    List <int> list = new List <int>();
                    foreach (Owner own in roomDb.FMROwners)
                    {
                        if (own.PartnerId == user.UserId)
                        {
                            list.Add(own.RoomId);
                        }
                    }
                    foreach (Room room in roomDb.FMRRooms)
                    {
                        if (list.Contains(room.RoomId))
                        {
                            room.Status = "unavailable";
                        }
                    }
                    //roomDb.SaveChanges();
                }
                else if (user.UserStatus.Equals("valid"))
                {
                    List <int> listtomakeavailable = new List <int>();
                    foreach (Owner own in roomDb.FMROwners)
                    {
                        if (own.PartnerId == user.UserId)
                        {
                            listtomakeavailable.Add(own.RoomId);
                        }
                    }
                    List <int> listofbookedrooms = new List <int>();
                    foreach (Book book in roomDb.FMRBookings)
                    {
                        if (listtomakeavailable.Contains(book.RoomId))
                        {
                            listofbookedrooms.Add(book.RoomId);
                        }
                    }
                    foreach (Room room in roomDb.FMRRooms)
                    {
                        if (listtomakeavailable.Contains(room.RoomId) && !listofbookedrooms.Contains(room.RoomId))
                        {
                            room.Status = "Available";
                        }
                    }
                    //roomDb.SaveChanges();
                }
                roomDb.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new InsertingDataException(ex.Message);
            }
        }
Example #19
0
        public async Task <ApiJsonResult> Update(int?tenantId, long userId, int orderId, OrderItemDto data)
        {
            var result     = new ApiJsonResult();
            var orderModel = await GetById(orderId).AsNoTracking().FirstOrDefaultAsync();

            var orderItems = await GetAllOrderItems();

            if (orderModel == null)
            {
                result.Code    = CodeModel.Fail;
                result.Message = $"Order not found with orderId {orderId}";
                return(result);
            }
            var orderItemModels = await _unitOfWork.OrderItemRepository
                                  .FindByCondition(oi => oi.OrderId == orderId)
                                  .AsNoTracking()
                                  .ToListAsync();

            var orderItemProductIds = orderItemModels.Select(o => o.ProductId);
            var productIds          = data.Products.Select(p => p.Id);

            // delete order items
            var deleteOrderItems = orderItemModels
                                   .Where(o => !productIds.Contains(o.ProductId)).ToList();

            if (deleteOrderItems.Any())
            {
                _unitOfWork.OrderItemRepository.RemoveRange(deleteOrderItems);
            }

            // update order items
            var updateOrderItems = orderItemModels
                                   .Where(o => productIds.Contains(o.ProductId)).ToList();

            foreach (var orderItem in updateOrderItems)
            {
                var productFound = data.Products.Where(p => p.Id == orderItem.ProductId).FirstOrDefault();
                if (productFound == null)
                {
                    continue;
                }
                var orderItemsFound = orderItems
                                      .Where(o => o.ProductId == orderItem.ProductId && o.Id != orderItem.Id)
                                      .ToList();
                orderItem.Amount       = productFound.Amount;
                orderItem.ModifiedDate = DateTime.Now;
            }

            // add new order items
            var newOrderItems = data.Products
                                .Where(p => !orderItemProductIds.Contains(p.Id))
                                .ToList();

            foreach (var newOrderItem in newOrderItems)
            {
                var orderItemsFound = orderItems
                                      .Where(o => o.ProductId == newOrderItem.Id)
                                      .ToList();
                var orderItem = new OrderItem
                {
                    TenantId       = tenantId.Value,
                    ProductId      = newOrderItem.Id,
                    Amount         = newOrderItem.Amount + orderItemsFound.Sum(o => o.Amount),
                    Price          = newOrderItem.Price,
                    CreatedDate    = DateTime.Now,
                    UserModifiedId = userId
                };
                updateOrderItems.Add(orderItem);
            }

            var orderNoteModel = await _unitOfWork.OrderNoteRepository
                                 .FindByCondition(on => on.OrderId == orderId)
                                 .AsNoTracking()
                                 .FirstOrDefaultAsync();

            if (orderNoteModel != null)
            {
                orderNoteModel.Note           = data.OrderNote;
                orderNoteModel.ModifiedDate   = DateTime.Now;
                orderNoteModel.UserModifiedId = userId;
                orderModel.OrderNote          = orderNoteModel;
            }
            orderModel.CustomerId     = data.CustomerId;
            orderModel.SellerId       = data.SellerId;
            orderModel.OrderItems     = updateOrderItems;
            orderModel.SaleDate       = data.SaleDateUtc;
            orderModel.ModifiedDate   = DateTime.Now;
            orderModel.OrderTotal     = data.OrderTotal;
            orderModel.OrderDiscount  = data.OrderDiscount;
            orderModel.OrderPaid      = data.OrderPaid;
            orderModel.OrderDebt      = data.OrderDebt;
            orderModel.StoreId        = data.StoreId;
            orderModel.UserModifiedId = userId;

            switch (orderModel.OrderType)
            {
            case OrderType.Order:
                var shipmentModel = await _unitOfWork.ShipmentRepository
                                    .FindByCondition(s => s.OrderId == orderId)
                                    .AsNoTracking()
                                    .FirstOrDefaultAsync();

                if (shipmentModel == null)
                {
                    shipmentModel             = new Shipment();
                    shipmentModel.CreatedDate = DateTime.Now;
                }
                else
                {
                    shipmentModel.ModifiedDate = DateTime.Now;
                }
                shipmentModel.UserModifiedId  = userId;
                shipmentModel.DeliveryDateUtc = data.DeliveryDate;
                shipmentModel.CarrierId       = data.CarrierId;
                shipmentModel.Note            = data.ShipmentNote;
                shipmentModel.Shipper         = data.Shipper;
                orderModel.Shipment           = shipmentModel;
                break;

            case OrderType.Sale:
                orderModel.PaymentMethodId = data.PaymentMethodId;
                break;

            default:
                break;
            }
            _unitOfWork.OrderRepository.Update(orderModel);
            await _unitOfWork.Commit();

            var userModified = new UserModified
            {
                TenantId = tenantId,
                UserId   = userId
            };

            return(result);
        }