Ejemplo n.º 1
0
        private async Task HandleAsync(LeaseFinalizedEvent @event)
        {
            // Handle lease finalize event - update property status
            //
            var rentalProperty = _context.Property.FirstOrDefault(p => p.Id == @event.RentalPropertyId);

            if (rentalProperty != null)
            {
                RentalStatus status = (RentalStatus)Enum.Parse(typeof(RentalStatus), "rented", true);

                rentalProperty.StatusUpdate(status);

                try
                {
                    await _context.SaveChangesAsync();

                    Log.Information("Message  {MessageType} with Id {MessageId} has been handled successfully", @event.MessageType, @event.MessageId);
                }
                catch (Exception ex)
                {
                    //throw ex;
                    Log.Error(ex, "Error while handling {MessageType} message with id {MessageId}.", @event.MessageType, @event.MessageId);
                }
            }



            //throw new NotImplementedException();
        }
        public async Task <ActionResult <object> > PostDeliveryMethod(DeliveryMethodObjectModel deliveryMethodAjax)
        {
            deliveryMethodAjax.Name = deliveryMethodAjax.Name.Trim();
            _context.DeliveryMethods.Add(deliveryMethodAjax);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetDeliveryMethodModel", new { id = deliveryMethodAjax.Id }, deliveryMethodAjax));
        }
        public async Task <ActionResult <object> > PostWarehouse([FromBody] WarehouseObjectModel ajaxWarehouse)
        {
            _logger.LogInformation("Создание склада. Инициатор: " + _user.FullInfo);
            string msg;

            ajaxWarehouse.Name        = ajaxWarehouse.Name.Trim();
            ajaxWarehouse.Information = ajaxWarehouse.Information.Trim();

            if (!ModelState.IsValid || string.IsNullOrEmpty(ajaxWarehouse.Name))
            {
                msg = "Ошибка контроля валидности модели";
                _logger.LogError(msg);
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = msg,
                    Status = StylesMessageEnum.danger.ToString(),
                    Tag = ModelState
                }));
            }

            if (_context.Warehouses.Any(x => x.Name.ToLower() == ajaxWarehouse.Name.ToLower()))
            {
                msg = "Склад с таким именем уже существует в бд. Придумайте уникальное";
                _logger.LogError(msg);
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = msg,
                    Status = StylesMessageEnum.danger.ToString()
                }));
            }

            if (_user.Role != AccessLevelUserRolesEnum.ROOT)
            {
                ajaxWarehouse.isDisabled       = false;
                ajaxWarehouse.isGlobalFavorite = false;
                ajaxWarehouse.isReadonly       = false;
            }

            _context.Warehouses.Add(ajaxWarehouse);
            await _context.SaveChangesAsync();

            HttpContext.Response.Cookies.Append("rowsCount", (await _context.Warehouses.CountAsync()).ToString());

            msg = $"Склад создан [#{ajaxWarehouse.Id}]";
            _logger.LogInformation(msg);
            return(new ObjectResult(new ServerActionResult()
            {
                Success = true,
                Info = msg,
                Status = StylesMessageEnum.success.ToString(),
                Tag = ajaxWarehouse.Id
            }));
        }
Ejemplo n.º 4
0
        public async Task <ActionResult <object> > PostGood([FromRoute] int id, [FromBody] GoodObjectModel ajaxGood)
        {
            _logger.LogInformation("Создание номенклатуры. Инициатор: " + _user.FullInfo);

            ajaxGood.Name        = ajaxGood.Name.Trim();
            ajaxGood.Information = ajaxGood.Information.Trim();

            if (!ModelState.IsValid ||
                string.IsNullOrEmpty(ajaxGood.Name) ||
                ajaxGood.GroupId <= 0 ||
                ajaxGood.GroupId != id ||
                ajaxGood.UnitId <= 0 ||
                !await _context.GroupsGoods.AnyAsync(group => group.Id == ajaxGood.GroupId) ||
                !await _context.Units.AnyAsync(unit => unit.Id == ajaxGood.UnitId))
            {
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = "Ошибка контроля валидности модели",
                    Status = StylesMessageEnum.danger.ToString(),
                    Tag = ModelState
                }));
            }

            if (await _context.Goods.AnyAsync(good => good.Name.ToLower() == ajaxGood.Name.ToLower()))
            {
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = "Номенклатура с таким именем уже существует в бд. Придумайте уникальное",
                    Status = StylesMessageEnum.danger.ToString()
                }));
            }

            if (_user.Role != AccessLevelUserRolesEnum.ROOT)
            {
                ajaxGood.isDisabled       = false;
                ajaxGood.isGlobalFavorite = false;
                ajaxGood.isReadonly       = false;
            }

            await _context.Goods.AddAsync(ajaxGood);

            await _context.SaveChangesAsync();

            HttpContext.Response.Cookies.Append("rowsCount", (await _context.Goods.CountAsync()).ToString());
            return(new ObjectResult(new ServerActionResult()
            {
                Success = true,
                Info = "Номенклатура создана",
                Status = StylesMessageEnum.success.ToString(),
                Tag = ajaxGood.Id
            }));
        }
Ejemplo n.º 5
0
        public async Task <ActionResult <GroupGoodsObjectModel> > PostGroupGoods(GroupGoodsObjectModel ajaxGroup)
        {
            _logger.LogInformation("Создание номенклатурной группы. Инициатор: " + _user.FullInfo);
            string msg;

            ajaxGroup.Name        = ajaxGroup.Name.Trim();
            ajaxGroup.Information = ajaxGroup.Information.Trim();

            if (!ModelState.IsValid || string.IsNullOrEmpty(ajaxGroup.Name))
            {
                msg = "Ошибка в запросе";
                _logger.LogError(msg);
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = msg,
                    Status = StylesMessageEnum.danger.ToString(),
                    Tag = ModelState
                }));
            }

            if (_context.GroupsGoods.Any(x => x.Name.ToLower() == ajaxGroup.Name.ToLower()))
            {
                msg = "Номенклатурная группа с таким именем уже существует. Придумайте уникальное имя.";
                _logger.LogError(msg);
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = msg,
                    Status = StylesMessageEnum.danger.ToString()
                }));
            }

            if (_user.Role != AccessLevelUserRolesEnum.ROOT)
            {
                ajaxGroup.isDisabled       = false;
                ajaxGroup.isGlobalFavorite = false;
                ajaxGroup.isReadonly       = false;
            }

            _context.GroupsGoods.Add(ajaxGroup);
            await _context.SaveChangesAsync();

            HttpContext.Response.Cookies.Append("rowsCount", (await _context.GroupsGoods.CountAsync()).ToString());
            msg = "Номенклатурная группа создана";
            _logger.LogInformation(msg);
            return(new ObjectResult(new ServerActionResult()
            {
                Success = true,
                Info = msg,
                Status = StylesMessageEnum.success.ToString(),
                Tag = ajaxGroup.Id
            }));
        }
Ejemplo n.º 6
0
        public async Task <ActionResult <object> > PostDepartment(DepartmentObjectModel ajaxDepartment)
        {
            _logger.LogInformation("Добавление департамента. Инициатор: " + _user.FullInfo);
            string msg;

            ajaxDepartment.Name        = ajaxDepartment.Name.Trim();
            ajaxDepartment.Information = ajaxDepartment.Information.Trim();

            if (!ModelState.IsValid || string.IsNullOrEmpty(ajaxDepartment.Name))
            {
                msg = "Ошибка запроса. Департамент не создан";
                _logger.LogError(msg);
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = msg,
                    Status = StylesMessageEnum.danger.ToString(),
                    Tag = ModelState
                }));
            }

            if (await _context.Departments.AnyAsync(dprt => dprt.Name.ToLower() == ajaxDepartment.Name.ToLower()))
            {
                msg = "Имя не уникальное. Придумайте другое";
                _logger.LogError(msg);
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = msg,
                    Status = StylesMessageEnum.danger.ToString()
                }));
            }

            if (_user.Role != AccessLevelUserRolesEnum.ROOT)
            {
                ajaxDepartment.isDisabled       = false;
                ajaxDepartment.isGlobalFavorite = false;
                ajaxDepartment.isReadonly       = false;
            }

            _context.Departments.Add(ajaxDepartment);
            await _context.SaveChangesAsync();

            msg = $"Департамент создан: id={ajaxDepartment.Id}";
            _logger.LogInformation(msg);
            return(new ObjectResult(new ServerActionResult()
            {
                Success = true,
                Info = msg,
                Status = StylesMessageEnum.success.ToString(),
                Tag = ajaxDepartment.Id
            }));
        }
Ejemplo n.º 7
0
        public ActionResult DeleteStorage(string id)
        {
            //string id = ControllerContext.RouteData.Values["id"].ToString();
            myFileMetadata md = FileVerification(id, StoragePath, true);

            if (md.FileInfo is null)
            {
                if (!(md.Object is null))
                {
                    DbContext.FilesStorage.Remove(md.Object);
                    DbContext.SaveChangesAsync();
                }
                _logger.LogError("Не удалось прочитать файл: {0}", Path.Combine(StoragePath, id));
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = "Ошибка чтения файла: " + id,
                    Status = StylesMessageEnum.warning.ToString()
                }));
            }

            DbContext.FilesStorage.Remove(md.Object);
            DbContext.SaveChangesAsync();

            try
            {
                md.FileInfo.Delete();
                if (!(md.ThumbFileInfo is null))
                {
                    md.ThumbFileInfo.Delete();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Не удалось удалить файл(ы): {0}", Path.Combine(StoragePath, id));
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = "Во время удаления файла произошла ошибка: " + ex.Message,
                    Status = StylesMessageEnum.warning.ToString()
                }));
            }
            _logger.LogWarning("Файл удалён: {0}", md.FileInfo.FullName);
            return(new ObjectResult(new ServerActionResult()
            {
                Success = true,
                Info = "Файл удалён",
                Status = StylesMessageEnum.success.ToString(),
                Tag = md.FileInfo.Name
            }));
        }
        public async Task <ActionResult <object> > PostUnitGood(UnitGoodObjectModel ajaxUnit)
        {
            _logger.LogInformation("Создание единицы измерения. Инициатор: " + _user.FullInfo);
            string msg;

            ajaxUnit.Name        = ajaxUnit.Name.Trim();
            ajaxUnit.Information = ajaxUnit.Information.Trim();

            if (!ModelState.IsValid || string.IsNullOrEmpty(ajaxUnit.Name))
            {
                msg = "Ошибка контроля валидности модели";
                _logger.LogError(msg);
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = msg,
                    Status = StylesMessageEnum.danger.ToString(),
                    Tag = ModelState
                }));
            }

            if (await _context.Units.AnyAsync(x => x.Name.ToLower() == ajaxUnit.Name.ToLower()))
            {
                msg = "Такое имя уже существует. Придумайте уникальное имя";
                _logger.LogError(msg);
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = msg,
                    Status = StylesMessageEnum.danger.ToString()
                }));
            }

            await _context.Units.AddAsync(ajaxUnit);

            await _context.SaveChangesAsync();

            HttpContext.Response.Cookies.Append("rowsCount", (await _context.Units.CountAsync()).ToString());
            msg = $"Номенклатурная группа создана [#{ajaxUnit.Id}]";
            _logger.LogInformation(msg);
            return(new ObjectResult(new ServerActionResult()
            {
                Success = true,
                Info = msg,
                Status = StylesMessageEnum.success.ToString(),
                Tag = ajaxUnit.Id
            }));
        }
Ejemplo n.º 9
0
        public async Task <Unit> Handle(AddFeePaymentCommand request, CancellationToken cancellationToken)
        {
            var fee = new FeePayment(request.ManagementContractId, request.ScheduledPaymentAmt, request.ActualPaymentAmt,
                                     request.PayMethod, request.MangementFeeType, request.PaymentDueDate, request.PaymentReceivedDate, request.IsOnTime,
                                     request.InChargeOwnerId, request.Note, request.FeeForMonth, request.FeeForYear, DateTime.Now, DateTime.Now);

            _context.FeePayment.Add(fee);

            try
            {
                await _context.SaveChangesAsync();

                // logging
                Log.Information("Fee payment on contract {ContractId} has been added successfully", fee.ManagementContractId);

                // Send messages if necessary
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error occured while adding fee payment on contract {ContractId}.", fee.ManagementContractId);
            }

            return(await Unit.Task);

            //throw new NotImplementedException();
        }
        // POST api/values
        public async Task PostAsync([FromBody] Student student)
        {
            DB.Student.Add(student);
            await DB.SaveChangesAsync();

            return(Ok());
        }
Ejemplo n.º 11
0
        public async Task <bool> Handle(DeleteImageFromPropertyCommand request, CancellationToken cancellationToken)
        {
            string filePath = _hostingEnvironment.WebRootPath + "\\images";

            var image = _context.PropertyImg.FirstOrDefault(i => i.Id == request.Id);

            int start = image.PropertyImgUrl.LastIndexOf("/");

            string fileName = image.PropertyImgUrl.Substring(start + 1);

            _context.PropertyImg.Remove(image);

            try
            {
                await _context.SaveChangesAsync();

                // logging
                Log.Information("The image for the property {PorpertyName} has been deleted/ successfully", image.Property.PropertyName);

                // Send messages if necessary
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error occured while deleting the image for the property {PropertyName}.", image.Property.PropertyName);
            }

            string fileToBeDeleted = filePath + "\\" + fileName;

            System.IO.File.Delete(fileToBeDeleted);

            return(true);
        }
Ejemplo n.º 12
0
        public async Task <DeletePropertyCommandResult> Handle(DeletePropertyCommand request, CancellationToken cancellationToken)
        {
            var property = _context.Property.FirstOrDefault(p => p.Id == request.PropertyId);

            var deleted = new DeletePropertyCommandResult();

            deleted.PropertyId = request.PropertyId;
            deleted.IsActive   = request.IsActive;

            property.Delete(property);

            try
            {
                await _context.SaveChangesAsync();

                // logging
                Log.Information("A management contract for the property {PorpertyName} has been added successfully", property.PropertyName);

                // Send messages if necessary
            }
            catch (Exception ex)
            {
                throw ex;
            }

            //return request.PropertyId;
            return(deleted);
        }
Ejemplo n.º 13
0
        public async Task <ActionResult <object> > DeleteTelegramBotUpdate(int id)
        {
            TelegramBotUpdateObjectModel telegramBotUpdate = await _context.TelegramBotUpdates.FindAsync(id);

            if (telegramBotUpdate == null)
            {
                _logger.LogError("Удаление TelegramBot Update невозможно. Объект не найден");
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = "TelegramBot Update не найден",
                    Status = StylesMessageEnum.danger.ToString()
                }));
            }

            _context.TelegramBotUpdates.Remove(telegramBotUpdate);
            await _context.SaveChangesAsync();

            _logger.LogInformation("TelegramBot Update удалён: id={0}", id);
            return(new ObjectResult(new ServerActionResult()
            {
                Success = true,
                Info = "TelegramBot Update удалён",
                Status = StylesMessageEnum.success.ToString()
            }));
        }
Ejemplo n.º 14
0
        public async Task <bool> Handle(UploadSignedContractCommand request, CancellationToken cancellationToken)
        {
            var file = request.ContractFile;

            string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\files\\");
            string url  = "files/" + file.FileName;

            if (file.Length > 0)
            {
                using (var fileStream = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
                {
                    try
                    {
                        await file.CopyToAsync(fileStream);
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
            }

            var contract = _context.ManagementContract.FirstOrDefault(c => c.Id == request.ContractId);

            contract.AddSignedContractFile(url, contract);

            _context.Update(contract);

            //var property = _context.Property.FirstOrDefault(p => p.Id == request.PropertyId);


            //var image = property.AddImages(request.Caption, url, request.PropertyId);


            //_context.Add(image);

            try
            {
                await _context.SaveChangesAsync();

                // logging
                Log.Information("Signed contract for the property {ContractTitle} has been added successfully", contract.ManagementContractTitle);

                // Send messages if necessary
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error occured while adding contract file to the property {ContractTitle}.", contract.ManagementContractTitle);
            }

            return(true);


            //throw new NotImplementedException();
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> PutProfile(int id, СonversationDocumentModel ajaxConversation)
        {
            if (id != ajaxConversation.Id)
            {
                return(null); // BadRequest();
            }

            _context.Entry(ajaxConversation).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw;
            }

            return(null); // NoContent();
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> PutNotification(int id, NotificationObjectModel ajaxNotification)
        {
            if (id != ajaxNotification.Id)
            {
                return(BadRequest());
            }

            _context.Entry(ajaxNotification).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw;
            }

            return(NoContent());
        }
Ejemplo n.º 17
0
        public async Task <RemovePropertyOwnerCommandResult> Handle(RemoveOwnerFromPropertyCommand request, CancellationToken cancellationToken)
        {
            var numOfgOwners = _context.OwnerProperty.Where(p => p.PropertyId == request.PropertyId).Count();
            var property     = _context.Property.FirstOrDefault(i => i.Id == request.PropertyId);

            var ownerToRemove = await _context.OwnerProperty.FirstAsync(o => o.PropertyOwnerId == request.PropertyOwnerId);

            if (numOfgOwners >= 2)
            {
                //var ownerToRemove = await _context.OwnerProperty.FirstAsync(o => o.PropertyOwnerId == request.PropertyOwnerId);

                _context.OwnerProperty.Remove(ownerToRemove);

                var removed = new RemovePropertyOwnerCommandResult();

                try
                {
                    await _context.SaveChangesAsync();

                    removed.PropertyId      = property.Id;
                    removed.PropertyOwnerId = request.PropertyOwnerId;

                    //return "Onwer has been removed from the property";

                    // logging
                    Log.Information("The owner {OwnerName} has been removed from the property {PorpertyName} has been added successfully",
                                    ownerToRemove.PropertyOwner.FirstName + " " + ownerToRemove.PropertyOwner.LastName, property.PropertyName);

                    // Send messages if necessary
                }
                catch (Exception ex)
                {
                    //throw ex;
                    Log.Error(ex, "Error occured while deleting the owner for the property {PropertyName}.", property.PropertyName);
                }

                //return "Owner has been removed from the proeprty specified!";
                return(removed);
            }


            Log.Information("The owner {OwnerName} cannot removed from the property {PorpertyName} because this is the only owner",
                            ownerToRemove.PropertyOwner.FirstName + " " + ownerToRemove.PropertyOwner.LastName, property.PropertyName);

            //return "Onwer cannot be removed from the property!";
            return(new RemovePropertyOwnerCommandResult()
            {
            });
        }
Ejemplo n.º 18
0
        public async Task <bool> Handle(AddImageToPropertyCommand request, CancellationToken cancellationToken)
        {
            var file = request.PropertyImage;

            string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images\\");
            string url  = "images/" + file.FileName;

            if (file.Length > 0)
            {
                using (var fileStream = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
                {
                    try
                    {
                        await file.CopyToAsync(fileStream);
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
            }

            var property = _context.Property.FirstOrDefault(p => p.Id == request.PropertyId);

            var image = property.AddImages(request.PropertyImgTitle, url, request.PropertyId);


            _context.Add(image);

            try
            {
                await _context.SaveChangesAsync();

                // logging
                Log.Information("An image for the property {PorpertyName} has been added successfully", property.PropertyName);

                // Send messages if necessary
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error occured while adding image to the property {PropertyName}.", property.PropertyName);
            }

            return(true);
        }
Ejemplo n.º 19
0
        public async Task <UpdatePropertyStatusCommandResult> Handle(UpdatePropertyStatusCommand request, CancellationToken cancellationToken)
        {
            var property = _context.Property.FirstOrDefault(p => p.Id == request.Id);

            var updatedStatus = new UpdatePropertyStatusCommandResult();

            updatedStatus.Id                  = request.Id;
            updatedStatus.Status              = request.Status;
            updatedStatus.PropertyName        = property.PropertyName;
            updatedStatus.PropertyLogoImgUrl  = property.PropertyLogoImgUrl;
            updatedStatus.IsActive            = property.IsActive;
            updatedStatus.IsBasementSuite     = property.IsBasementSuite;
            updatedStatus.CreatedDate         = property.Created;
            updatedStatus.UpdateDate          = DateTime.Now;
            updatedStatus.PropertyType1       = property.Type.ToString();
            updatedStatus.PropertySuiteNumber = property.Address.PropertySuiteNumber;
            updatedStatus.PropertyNumber      = property.Address.PropertyNumber;
            updatedStatus.PropertyStreet      = property.Address.PropertyStreet;
            updatedStatus.PropertyCity        = property.Address.PropertyCity;
            updatedStatus.PropertyZipPostCode = property.Address.PropertyZipPostCode;
            updatedStatus.PropertyCountry     = property.Address.PropertyCountry;

            //property.StatusUpdate(property, request.Status);
            property.StatusUpdate(request.Status);

            try
            {
                await _context.SaveChangesAsync();

                // logging
                Log.Information("The status of the property {PorpertyName} has been updated to {Status} successfully", property.PropertyName, request.Status);

                // Send messages if necessary
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(updatedStatus);
        }
Ejemplo n.º 20
0
        public async Task <string> Handle(AssignPMtoPropertyCommand request, CancellationToken cancellationToken)
        {
            var property = _context.Property.FirstOrDefault(p => p.Id == request.PropertyId);

            property.AsssignPropertyManager(property, request.PmUserName);

            try
            {
                await _context.SaveChangesAsync();


                // logging
                Log.Information("The property manager {ManagerName} has been added to the property {PorpertyName} as been added successfully", request.PmUserName, property.PropertyName);

                // Send messages if necessary
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error occured while adding property manager to the property {PropertyName}.", property.PropertyName);
            }

            return("Property manager assigned!");
        }
Ejemplo n.º 21
0
        public async Task <UpdatePropertyOwnerCommandResult> Handle(UpdatePropertyOwnerCommand request, CancellationToken cancellationToken)
        {
            var owner = _context.PropertyOwner.Include(op => op.OwnerProperty).ThenInclude(p => p.Property)
                        .FirstOrDefault(o => o.Id == request.Id);

            var property = owner.OwnerProperty.FirstOrDefault().Property;

            var updated = property.UpdateOwner(owner, request.FirstName, request.LastName, request.ContactEmail, request.ContactTelephone1,
                                               request.ContactTelephone2, request.UserAvartaImgUrl, request.IsActive, request.Notes, request.StreetNumber, request.City, request.StateProvince,
                                               request.ZipPostCode, request.Country);

            //var updated = owner.Update(owner, request.FirstName, request.LastName, request.ContactEmail, request.ContactTelephone1,
            //    request.ContactTelephone2, request.UserAvartaImgUrl, request.IsActive, request.Notes);

            var updatedOwner = new UpdatePropertyOwnerCommandResult();

            var address = new UpdatedOwnerAddress();

            address.City          = request.City;
            address.StreetNumber  = request.StreetNumber;
            address.StateProvince = request.StateProvince;
            address.ZipPostCode   = request.ZipPostCode;
            address.Country       = request.Country;

            // Query list of property owned by this owner
            //getOwnerPropertyList(request.Id);

            /*
             *
             */

            //var propertyList = _context.Property
            //    .Include(a => a.Address)
            //    .Include(op => op.OwnerProperty)
            //    .ThenInclude(o => o.PropertyOwner)
            //    //.ThenInclude(p => p.Id == request.Id)
            //    .Where(o => o.Id == request.Id)
            //    .ToList();

            //var propertyList = (from p in _context.Property.Include(a => a.Address)
            //                    join op in _context.OwnerProperty on p.Id equals op.PropertyId
            //                    join o in _context.PropertyOwner on op.PropertyOwnerId equals o.Id
            //                    where o.Id == request.Id
            //                    select new PropertyListViewModel
            //                    {
            //                        PropertyName = p.PropertyName.

            //var powner = _context.PropertyOwner
            //     .Include(op => op.OwnerProperty)
            //     .ThenInclude(p => p.Property).ToList()
            //     .Where(o => o.Id == request.Id);

            var propertyList = owner.OwnerProperty.ToList();

            //                    }).ToList();



            //populate the updated owner
            updatedOwner.Id                = request.Id;
            updatedOwner.FirstName         = request.FirstName;
            updatedOwner.LastName          = request.LastName;
            updatedOwner.ContactEmail      = request.ContactEmail;
            updatedOwner.ContactTelephone1 = request.ContactTelephone1;
            updatedOwner.ContactTelephone2 = request.ContactTelephone2;
            updatedOwner.UserAvartaImgUrl  = request.UserAvartaImgUrl;
            updatedOwner.IsActive          = request.IsActive;
            updatedOwner.Notes             = request.Notes;
            updatedOwner.UpdateDate        = DateTime.Now;
            updatedOwner.City              = request.City;
            updatedOwner.StreetNumber      = request.StreetNumber;
            updatedOwner.StateProvince     = request.StateProvince;
            updatedOwner.ZipPostCode       = request.ZipPostCode;
            updatedOwner.Country           = request.Country;
            updatedOwner.Created           = owner.Created.ToString("MMMM dd, yyyy");
            updatedOwner.Modified          = owner.Modified.ToString("MMMM dd, yyyy");
            updatedOwner.Updated           = owner.Modified.ToString("MMMM dd, yyyy");

            updatedOwner.Address = address;

            updatedOwner.OwnerProperty = propertyList;

            _context.Update(updated);

            try
            {
                await _context.SaveChangesAsync();

                // logging
                Log.Information("The owner {OwnerName} for the property {PorpertyName} has been updated successfully", owner.FirstName + " " + owner.LastName, property.PropertyName);

                // Send messages

                UpdateOwnerEvent e = new UpdateOwnerEvent(new Guid(), request.Id, request.FirstName, request.LastName, request.ContactEmail, request.ContactTelephone1,
                                                          request.ContactTelephone2, owner.OnlineAccess, request.IsActive, 2, request.Notes,
                                                          request.StreetNumber, request.City, request.StateProvince, request.ZipPostCode, request.Country);

                try
                {
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "asset_created"); // publishing the message

                    Log.Information("Message  {MessageType} with Id {MessageId} has been published successfully", e.MessageType, e.MessageId);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error while publishing {MessageType} message with id {MessageId}.", e.MessageType, e.MessageId);
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error occured while updating the owner for the property {PropertyName}.", property.PropertyName);
            }

            return(updatedOwner);

            //throw new NotImplementedException();
        }
Ejemplo n.º 22
0
        public async Task <UpdatePropertyCommandResult> Handle(UpdatePropertyCommand request, CancellationToken cancellationToken)
        {
            var ppt = _context.Property.Include(op => op.OwnerProperty).ThenInclude(o => o.PropertyOwner).FirstOrDefault(p => p.Id == request.PropertyId);

//
            var address = new PropertyAddress(request.PropertySuiteNumber,
                                              request.PropertyNumber, request.PropertyStreet,
                                              request.PropertyCity, request.PropertyStateProvince, request.PropertyZipPostCode,
                                              request.PropertyCountry);

            var feature = new PropertyFeature(request.NumberOfBedrooms,
                                              request.NumberOfBathrooms, request.NumberOfLayers,
                                              request.NumberOfParking, request.BasementAvailable,
                                              request.TotalLivingArea, request.IsShared, request.FeatureNotes);


            var facility = new PropertyFacility(request.Stove, request.Refrigerator, request.Dishwasher,
                                                request.AirConditioner, request.Laundry, request.BlindsCurtain, request.Furniture,
                                                request.Tvinternet, request.CommonFacility, request.SecuritySystem, request.UtilityIncluded,
                                                request.FireAlarmSystem, request.Others, request.FacilityNotes);



            var updated = ppt.Update(ppt, request.PropertyName, request.PropertyDesc, request.PropertyType1, request.PropertyBuildYear,
                                     request.IsActive, request.IsShared, request.Status, request.BasementAvailable, DateTime.Now,
                                     address, facility, feature);

            _context.Property.Update(updated);

            var owners = ppt.OwnerProperty.Select(o => o.PropertyOwner).ToList();



            //var owners = _context.PropertyOwner
            //    .Include(op => op.OwnerProperty)
            //    .ThenInclude(p => p.FirstOrDefault().PropertyId == request.PropertyId).ToList();



            var contracts = _context.ManagementContract
                            //.Include(p => p.Property)
                            .Where(p => p.PropertyId == request.PropertyId).ToList();


            var updatedProperty = new UpdatePropertyCommandResult();

            // need to populate it either manual or automapper***************************
            updatedProperty.PropertyId        = request.PropertyId;
            updatedProperty.Id                = request.PropertyId;
            updatedProperty.AirConditioner    = request.AirConditioner;
            updatedProperty.BasementAvailable = request.BasementAvailable;
            updatedProperty.CommonFacility    = request.CommonFacility;
            updatedProperty.Dishwasher        = request.Dishwasher;
            updatedProperty.FacilityNotes     = request.FacilityNotes;
            updatedProperty.FireAlarmSystem   = request.FireAlarmSystem;
            //updatedProperty.FurnishingId = request.FurnishingId;
            updatedProperty.Furniture         = request.Furniture;
            updatedProperty.IsActive          = request.IsActive;
            updatedProperty.IsShared          = request.IsShared;
            updatedProperty.Laundry           = request.Laundry;
            updatedProperty.NumberOfBathrooms = request.NumberOfBathrooms;
            updatedProperty.NumberOfBedrooms  = request.NumberOfBedrooms;
            updatedProperty.NumberOfLayers    = request.NumberOfLayers;
            updatedProperty.NumberOfParking   = request.NumberOfParking;
            updatedProperty.Others            = request.Others;
            updatedProperty.PropertyBuildYear = request.PropertyBuildYear;
            updatedProperty.PropertyCity      = request.PropertyCity;
            updatedProperty.PropertyCountry   = request.PropertyCountry;
            updatedProperty.PropertyDesc      = request.PropertyDesc;
            //updatedProperty.PropertyLogoImgUrl = request.PropertyLogoImgUrl;
            //updatedProperty.PropertyManagerId = request.PropertyManagerId;
            updatedProperty.PropertyName          = request.PropertyName;
            updatedProperty.PropertyNumber        = request.PropertyNumber;
            updatedProperty.PropertyStateProvince = request.PropertyStateProvince;
            updatedProperty.PropertyStreet        = request.PropertyStreet;
            updatedProperty.PropertySuiteNumber   = request.PropertySuiteNumber;
            //updatedProperty.PropertyVideoUrl = request.PropertyVideoUrl;
            updatedProperty.PropertyZipPostCode = request.PropertyZipPostCode;
            updatedProperty.Refrigerator        = request.Refrigerator;
            updatedProperty.SecuritySystem      = request.SecuritySystem;
            updatedProperty.FeatureNotes        = request.FeatureNotes;

            updatedProperty.Status = request.Status.ToString(); //***************************************************************

            updatedProperty.Stove           = request.Stove;
            updatedProperty.TotalLivingArea = request.TotalLivingArea;
            updatedProperty.Tvinternet      = request.Tvinternet;

            updatedProperty.PropertyType1 = request.PropertyType1.ToString(); //***************************************************************
            updatedProperty.Type          = request.PropertyType1.ToString(); // new for client side rendering

            updatedProperty.UtilityIncluded = request.UtilityIncluded;
            updatedProperty.CreationDate    = ppt.Created.ToString("MMMM dd, yyyy");
            updatedProperty.CreatedDate     = ppt.Created.ToString("MMMM dd, yyyy"); //new for client side rendering

            updatedProperty.UpdateDate = updated.Modified.ToString("MMMM dd, yyyy");

            updatedProperty.OwnerList    = owners;
            updatedProperty.ContractList = contracts;

            try
            {
                await _context.SaveChangesAsync();

                // logging
                Log.Information("The property {PorpertyName} has been updated successfully", ppt.PropertyName);

                // Send messages if necessary

                PropertyUpdateEvent e = new PropertyUpdateEvent(Guid.NewGuid(), request.PropertyId, request.PropertyName,
                                                                request.PropertyBuildYear, request.PropertyType1.ToString(), request.BasementAvailable, request.IsShared, request.NumberOfBedrooms,
                                                                request.NumberOfBathrooms, request.NumberOfLayers, request.NumberOfParking, request.TotalLivingArea,
                                                                request.PropertyNumber + " " + request.PropertyStreet, request.PropertyCity, request.PropertyStateProvince, request.PropertyCountry,
                                                                request.PropertyZipPostCode);

                try
                {
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "asset_created"); // publishing the message
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error while publishing {MessageType} message with id {MessageId}.", e.MessageType, e.MessageId);
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error occured while deleting the image for the property {PropertyName}.", ppt.PropertyName);
            }

            return(updatedProperty);  //.true;
        }
Ejemplo n.º 23
0
        public async Task <CreatePropertyCommandResult> Handle(CreatePropertyCommand request, CancellationToken cancellationToken)
        {
            #region Create property aggregate root

            var createdProperty = new CreatePropertyCommandResult();

            var address = new PropertyAddress(request.PropertySuiteNumber,
                                              request.PropertyNumber, request.PropertyStreet,
                                              request.PropertyCity, request.PropertyStateProvince, request.PropertyZipPostCode,
                                              request.PropertyCountry);

            var feature = new PropertyFeature(request.NumberOfBathrooms,
                                              request.NumberOfBathrooms, request.NumberOfLayers,
                                              request.NumberOfParking, request.BasementAvailable,
                                              request.TotalLivingArea, request.IsShared, request.FeatureNotes);


            var facility = new PropertyFacility(request.Stove, request.Refrigerator, request.Dishwasher,
                                                request.AirConditioner, request.Laundry, request.BlindsCurtain, request.Furniture,
                                                request.Tvinternet, request.CommonFacility, request.SecuritySystem, request.UtilityIncluded,
                                                request.FireAlarmSystem, request.FacilityNotes, request.Others);



            var property = new Property(request.PropertyName, request.PropertyDesc, request.Type, request.PropertyManagerUserName,
                                        request.PropertyBuildYear, true, request.IsShared, request.Status,
                                        request.BasementAvailable, DateTime.Now, DateTime.Now, address, facility, feature);


            await _context.AddAsync(property);

            #endregion


            PropertyOwner owner = null;

            if (request.PropertyOwnerId == 0)
            {
                object ownerAddress = null;

                if (!request.IsSameAddress)
                {
                    ownerAddress = new OwnerAddress(request.OwnerStreetNumber, request.OwnerCity, request.OwnerStateProv,
                                                    request.OwnerCountry, request.OwnerZipPostCode);
                }
                else
                {
                    ownerAddress = new OwnerAddress(request.PropertySuiteNumber + " " + request.PropertyNumber + " " + request.PropertyStreet, request.PropertyCity, request.PropertyStateProvince,
                                                    request.PropertyCountry, request.PropertyZipPostCode);
                }

                owner = property.AddOwner("NotSet", request.FirstName, request.LastName, request.ContactEmail,
                                          request.ContactTelephone1, request.ContactTelephone2, request.OnlineAccessEnbaled, request.UserAvartaImgUrl,
                                          request.IsActive, request.RoleId, request.Notes, (OwnerAddress)ownerAddress);


                await _context.AddAsync(owner);
            }
            else
            {
                owner = _context.PropertyOwner.FirstOrDefault(o => o.Id == request.PropertyOwnerId);

                var ownerProperty = property.AddExsitingOwner(owner);

                owner.OwnerProperty.Add(ownerProperty);
            }

            try
            {
                await _context.SaveChangesAsync(); // comment out for testing message sending ONLY

                int PropertyId = property.Id;

                int NewOwnerId = owner.Id;

                request.PropertyId  = property.Id;
                request.CreatedDate = property.Created;
                request.UpdateDate  = property.Modified;

                //Populate return resultEnum.GetName(typeof())
                //
                createdProperty.Id                    = PropertyId;
                createdProperty.PropertyName          = request.PropertyName;
                createdProperty.Type                  = request.Type.ToString();
                createdProperty.Status                = request.Status.ToString();
                createdProperty.PropertyLogoImgUrl    = request.PropertyLogoImgUrl;
                createdProperty.IsShared              = request.IsShared;
                createdProperty.IsActive              = request.IsActive;
                createdProperty.IsBasementSuite       = request.IsBasementSuite;
                createdProperty.CreatedDate           = DateTime.Now.ToString("MMMM dd, yyyy");
                createdProperty.UpdateDate            = DateTime.Now.ToString("MMMM dd, yyyy");
                createdProperty.PropertySuiteNumber   = request.PropertySuiteNumber;
                createdProperty.PropertyStreet        = request.PropertyStreet;
                createdProperty.PropertyCity          = request.PropertyCity;
                createdProperty.PropertyStateProvince = request.PropertyStateProvince;
                createdProperty.PropertyZipPostCode   = request.PropertyZipPostCode;
                createdProperty.PropertyCountry       = request.PropertyCountry;


                Log.Information("Property with id {PropertyName} has been successfully created.", property.PropertyName);



                // Publish Domain Event (MediatR pattern)

                AssetCore.Events.PropertyCreatedEvent domainEvent = new AssetCore.Events.PropertyCreatedEvent(property);

                await _mediator.Publish(domainEvent);



                // Publish Integration Event (RabbitMQ)

                var streetNum = request.PropertySuiteNumber + " " + request.PropertyNumber + " " + request.PropertyStreet;

                //var streetNum = address.PropertySuiteNumber + " " + address.PropertyNumber + " " + address.PropertyStreet;
                // Send message to MQ
                //
                PropertyCreatedEvent e = new PropertyCreatedEvent(Guid.NewGuid(), request.PropertyId, request.PropertyName, request.PropertyManagerUserName,
                                                                  request.PropertyBuildYear, request.Type.ToString(), request.BasementAvailable, request.IsShared, request.NumberOfBedrooms,
                                                                  request.NumberOfBathrooms, request.NumberOfLayers, request.NumberOfParking, request.TotalLivingArea,
                                                                  streetNum, request.PropertyCity, request.PropertyStateProvince, request.PropertyCountry,
                                                                  request.PropertyZipPostCode, NewOwnerId, request.FirstName, request.LastName, request.ContactEmail, request.ContactTelephone1, request.ContactTelephone2,
                                                                  request.OwnerStreetNumber, request.OwnerCity, request.OwnerStateProv, request.OwnerZipPostCode, request.OwnerCountry);

                try
                {
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "asset_created"); // publishing the message

                    Log.Information("Message  {MessageType} with Id {MessageId} has been published successfully", e.MessageType, e.MessageId);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error while publishing {MessageType} message with id {MessageId}.", e.MessageType, e.MessageId);
                }


                // Log message for reconciliation purpose         ******** This part can be replaced by Serilog ***************
                //
                var msgDetails = new MessageDetails();

                msgDetails.PrincicipalId     = e.PropertyId;
                msgDetails.PrincipalType     = "Property";
                msgDetails.PrincipalNameDesc = e.PropertyName;
                msgDetails.OperationType     = "Create";

                var details = msgDetails.ToBsonDocument();

                var msg = new Message(e.MessageId, "Asset Management", details, "asset_created", "asset_created.*", "Publish", DateTime.Now);

                await _loggingService.LogMessage(msg);
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error while creating property, {PropertyName} has not been created.", request.PropertyName);
            }

            return(createdProperty);
            //return new CreatePropertyCommandResult() { };
        }
Ejemplo n.º 24
0
        public async Task <AddOwnerToExistingPropertyCommandResult> Handle(AddOwnerToExistingPropertyCommand request, CancellationToken cancellationToken)
        {
            var property = _context.Property.FirstOrDefault(p => p.Id == request.PropertyId);

            PropertyOwner owner = null;

            var addedOwner = new AddOwnerToExistingPropertyCommandResult();

            // Check if the email already exist if adding new owner instead of existing owner
            //

            //var user = _context.PropertyOwner.FirstOrDefault(e => e.ContactEmail == request.ContactEmail);

            //if (user != null)
            //{
            //    return new AddOwnerToExistingPropertyCommandResult() { Notes = "The email already exists!"};
            //}

            // populate the addedOnwer
            addedOwner.UserAvartaImgUrl    = request.UserAvartaImgUrl;
            addedOwner.FirstName           = request.FirstName;
            addedOwner.LastName            = request.LastName;
            addedOwner.UserName            = request.UserName;
            addedOwner.ContactEmail        = request.ContactEmail;
            addedOwner.ContactTelephone1   = request.ContactTelephone1;
            addedOwner.ContactTelephone2   = request.ContactTelephone2;
            addedOwner.OnlineAccessEnbaled = request.OnlineAccessEnbaled;
            addedOwner.IsActive            = request.IsActive;
            addedOwner.RoleId       = request.RoleId;
            addedOwner.Notes        = request.Notes;
            addedOwner.StreetNumber = request.StreetNumber;
            addedOwner.City         = request.City;
            addedOwner.StateProv    = request.StateProv;
            addedOwner.ZipPostCode  = request.ZipPostCode;
            addedOwner.Country      = request.Country;
            addedOwner.Created      = DateTime.Now.ToString("MMMM dd, yyyy");
            addedOwner.Updated      = DateTime.Now.ToString("MMMM dd, yyyy");


            if (request.PropertyOwnerId == 0)
            {
                // Check if the email already exist if adding new owner instead of existing owner
                //

                var user = _context.PropertyOwner.FirstOrDefault(e => e.ContactEmail == request.ContactEmail);

                if (user != null)
                {
                    return(new AddOwnerToExistingPropertyCommandResult()
                    {
                        Notes = "The email already exists!"
                    });
                }

                var ownerAddress = new OwnerAddress(request.StreetNumber, request.City, request.StateProv, request.Country, request.ZipPostCode);

                owner = property.AddNewOwnerToProperty(request.PropertyId, request.UserName, request.FirstName, request.LastName, request.ContactEmail,
                                                       request.ContactTelephone1, request.ContactTelephone2, false, request.UserAvartaImgUrl, request.IsActive, 2, request.Notes, ownerAddress);

                _context.Add(owner);
            }
            else
            {
                owner = _context.PropertyOwner.Include(a => a.Address).FirstOrDefault(o => o.Id == request.PropertyOwnerId);

                var ownerProperty = property.AddExistingOwnerToProperty(owner, request.PropertyId);

                _context.Add(ownerProperty);
            }


            try
            {
                await _context.SaveChangesAsync();

                addedOwner.Id = owner.Id;


                // logging
                Log.Information("The new owner {OwnerName} has been added to the property {PorpertyName} successfully", request.FirstName + " " + request.LastName, property.PropertyName);

                // Send messages if necessary
                // Publish message to MQ for other service to consume

                AddOwnerEvent e = new AddOwnerEvent(new Guid(), owner.Id, request.PropertyId, owner.UserName, owner.FirstName, owner.LastName,
                                                    owner.ContactEmail, owner.ContactTelephone1, owner.ContactTelephone2, owner.OnlineAccess,
                                                    owner.UserAvartaImgUrl, owner.IsActive, owner.RoleId, owner.Notes, owner.Address.StreetNumber,
                                                    owner.Address.City, owner.Address.StateProvince, owner.Address.ZipPostCode, owner.Address.Country);


                try
                {
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "asset_created"); // publishing the message

                    Log.Information("Message  {MessageType} with Id {MessageId} has been published successfully", e.MessageType, e.MessageId);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error while publishing {MessageType} message with id {MessageId}.", e.MessageType, e.MessageId);
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error occured while adding the new owner {OwnerName} to the property {PropertyName}.", request.FirstName + " " + request.LastName, property.PropertyName);
            }

            return(addedOwner);
        }
Ejemplo n.º 25
0
        public async Task <ManagementContractDetailsViewModel> Handle(UpdateManagementContractCommand request, CancellationToken cancellationToken)
        {
            var contract = _context.ManagementContract.Include(p => p.Property).FirstOrDefault(c => c.Id == request.Id);

            var updatedContract = contract.Property.UpdateContract(contract, request.ManagementContractTitle, request.StartDate, request.EndDate,
                                                                   request.ContractSignDate, request.PlacementFeeScale, request.ManagementFeeScale, request.SolicitingOnly, request.Notes);


            _context.Update(updatedContract);

            var updatedView = new ManagementContractDetailsViewModel();

            try
            {
                await _context.SaveChangesAsync();

                //Need to modify returned model to match the client end
                var rentedProperty = _context.Property
                                     .Include(a => a.Address)
                                     .Include(op => op.OwnerProperty)
                                     .ThenInclude(o => o.PropertyOwner).Where(p => p.Id == contract.PropertyId);



                updatedView.Id = request.Id;
                updatedView.ManagementContractTitle = request.ManagementContractTitle;
                updatedView.StartDate          = request.StartDate.ToString("MMMM dd, yyyy");
                updatedView.EndDate            = request.EndDate.ToString("MMMM dd, yyyy");
                updatedView.ContractSignDate   = request.ContractSignDate.ToString("MMMM dd, yyyy");
                updatedView.ManagementFeeScale = request.ManagementFeeScale;
                updatedView.PlacementFeeScale  = request.PlacementFeeScale;
                updatedView.ManagementFeeScale = request.ManagementFeeScale;
                updatedView.Notes          = request.Notes;
                updatedView.SolicitingOnly = request.SolicitingOnly;
                updatedView.PropertyName   = contract.Property.PropertyName;
                updatedView.Type           = contract.Type;
                //updatedView.PropertyStreet = contract.Property.Address.PropertyStreet;

                // for update return data form for client
                //updatedView.CreatedOn = contract.Created.ToString("MMMM dd, yyyy");
                //updatedView.UpdatedOn = DateTime.Now.ToString("MMMM dd, yyyy");


                updatedView.Created  = contract.Created.ToString("MMMM dd, yyyy");
                updatedView.Modified = DateTime.Now.ToString("MMMM dd, yyyy");

                updatedView.Property = rentedProperty.FirstOrDefault(p => p.Id == contract.PropertyId);



                // logging
                Log.Information("The management contract for the property {PorpertyName} has been updated successfully", contract.Property.PropertyName);

                // Send messages if necessary
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error occured while updating the management contract for the property {PropertyName}.", contract.Property.PropertyName);
            }

            return(updatedView);
        }
Ejemplo n.º 26
0
        public async Task <bool> Handle(EnableOnlineAccessCommand request, CancellationToken cancellationToken)
        {
            var roleId = request.UserRole;

            //var user = _context.PropertyOwner.FirstOrDefault(e => e.ContactEmail == request.Email);

            //PropertyOwner user = null;

            switch (roleId)
            {
            case "owner":
                var user = _context.PropertyOwner.FirstOrDefault(i => i.Id == request.Id);

                try
                {
                    //var user = _context.PropertyOwner.FirstOrDefault(e => e.ContactEmail == request.Email);

                    if (!user.OnlineAccess)
                    {
                        user.ConfigOnlineAccess(request.Enable, "Notset");
                    }

                    string subject = "Online Access Enabled";
                    string body    = "Dear " + user.FirstName + ": \n Your online access privilage has been enabled, please go to this link to register your account! \n Thanks.";

                    //Construct notification event to Notificaiton message queue
                    Events.EmailNotificationEvent e = new Events.EmailNotificationEvent(new Guid(), user.ContactEmail, subject, body);

                    try
                    {
                        await _context.SaveChangesAsync();

                        await _messagePublisher.PublishMessageAsync(e.MessageType, e, "notification");

                        Log.Information("Message  {MessageType} with Id {MessageId} has been published successfully", e.MessageType, e.MessageId);
                    }
                    catch (Exception ex)
                    {
                        //throw ex;
                        Log.Error(ex, "Error while publishing {MessageType} message with id {MessageId}.", e.MessageType, e.MessageId);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                break;

            case "tenant":

                break;

            default:
                break;
            }



            /*
             *          try
             *          {
             *              // Persist data
             *              //
             *              //await _context.SaveChangesAsync(); // comment out for testing ONLY
             *
             *              // Call auth API to create user account
             *              //
             *
             *
             *              var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
             *
             *              //var client = _httpClientFactory.CreateClient();
             *              HttpClient client = new HttpClient();
             *              client.BaseAddress = new Uri("http://localhost:58088/api/Account/register");
             *              var result = await client.PostAsync("http://localhost:58088/api/Account/register", content);
             *
             *
             *              // Send message to MQ
             *              //
             *              //Events.EnableOnlineAccessEvent e = new Events.EnableOnlineAccessEvent(Guid.NewGuid(), request.Email, request.Password,
             *              //    request.FirstName, request.LastName, request.UserName, request.UserRole, request.Enable);
             *
             *
             *              //await _messagePublisher.PublishMessageAsync(e.MessageType, e, "real");
             *
             *
             *
             *
             *          }
             *          catch (Exception ex)
             *          {
             *              throw ex;
             *          }
             *
             *          //var returnedUser =
             */
            return(true);

            //throw new NotImplementedException();
        }
Ejemplo n.º 27
0
        public async Task <ManagementContractDetailsViewModel> Handle(AddManagementContractCommand request, CancellationToken cancellationToken)
        {
            var property = _context.Property
                           .Include(p => p.ManagementContract)
                           .FirstOrDefault(p => p.Id == request.PropertyId);

            // Get existing contract
            //
            var existingContract = property.ManagementContract.FirstOrDefault(c => c.IsActive == true);

            if (existingContract != null)
            {
                // Deactivate the existing active contract
                //
                var updatedContract = property.UpdateManagementContractStatus(existingContract, false);

                _context.Update(updatedContract);



                //if (request.ManagementContractType.ToString() == "Renewal")
                //{
                //    // Deactivate the existing active contract
                //    //
                //    var updatedContract = property.UpdateManagementContractStatus(existingContract, false);

                //    _context.Update(updatedContract);

                //    // save to db aLL tegether at the end
                //    //

                //    //try
                //    //{
                //    //    await _context.SaveChangesAsync();
                //    //}
                //    //catch(Exception ex)
                //    //{
                //    //    //throw ex;
                //    //    Log.Error(ex, "Error occured while renewing management contract to the property {PropertyName}.", property.PropertyName);
                //    //}

                //    //return new ManagementContractDetailsViewModel() { };

                //}
                //else
                //{

                //}
            }



            var contract = property.AddManabgementContract(request.PropertyId, request.ManagementContractTitle, request.ManagementContractType,
                                                           request.StartDate, request.EndDate, request.PlacementFeeScale, request.ManagementFeeScale, request.SolicitingOnly,
                                                           request.ContractSignDate, true, request.Notes);

            _context.Add(contract);

            var newContract = new ManagementContractDetailsViewModel();



            try
            {
                await _context.SaveChangesAsync();

                //property.UpdateManagementContractStatus(existingContract, false); // disable the previous contract, use case: ownership change

                // map the return view model
                newContract.Id = contract.Id;
                newContract.ManagementContractTitle = request.ManagementContractTitle;
                newContract.StartDate          = request.StartDate.ToString("MMMM dd, yyyy");
                newContract.EndDate            = request.EndDate.ToString("MMMM dd, yyyy");
                newContract.ContractSignDate   = request.StartDate.ToString("MMMM dd, yyyy");
                newContract.ManagementFeeScale = request.ManagementFeeScale;
                newContract.PlacementFeeScale  = request.PlacementFeeScale;
                newContract.ManagemetnFeeNotes = request.Notes;
                newContract.PropertyName       = contract.Property.PropertyName;
                //newContract.PropertyStreet =
                newContract.Created  = DateTime.Now.ToString("MMMM dd, yyyy");
                newContract.Modified = DateTime.Now.ToString("MMMM dd, yyyy");

                // logging
                Log.Information("A management contract for the property {PorpertyName} has been added successfully", property.PropertyName);

                // Send messages if necessary, e.g send notificaiton to the contract signers, including owners and pms
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error occured while adding management contract to the property {PropertyName}.", property.PropertyName);
            }

            return(newContract);
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> PutWarehouseDocument([FromBody] WarehouseDocumentsModel ajaxWarehouseDocument, [FromRoute] string id)
        {
            ajaxWarehouseDocument.Name        = ajaxWarehouseDocument.Name.Trim();
            ajaxWarehouseDocument.Information = ajaxWarehouseDocument.Information.Trim();

            id = id.Trim();

            if (string.IsNullOrEmpty(id) || !await _context.Warehouses.AnyAsync(x => x.Id == ajaxWarehouseDocument.WarehouseReceiptId))
            {
                _logger.LogInformation($"Запрос инициализации временного документа [type: '{id}']. Инициатор: " + _user.FullInfo);
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = "Ошибка в запросе",
                    Status = StylesMessageEnum.danger.ToString()
                }));
            }

            WarehouseDocumentsModel warehouseDocumentDb = await _context.WarehouseDocuments.Include(x => x.WarehouseReceipt).FirstOrDefaultAsync(x => x.Discriminator == nameof(WarehouseDocumentsModel) && x.Name.ToLower() == id.ToLower() && x.AuthorId == _user.Id);

            if (warehouseDocumentDb == null)
            {
                _logger.LogInformation($"Запрос инициализации временного документа [type: '{id}']. Инициатор: " + _user.FullInfo);
                warehouseDocumentDb = new WarehouseDocumentsModel()
                {
                    Name               = id,
                    Information        = ajaxWarehouseDocument.Information,
                    WarehouseReceiptId = ajaxWarehouseDocument.WarehouseReceiptId,
                    AuthorId           = _user.Id
                };
                _context.WarehouseDocuments.Add(warehouseDocumentDb);
                _logger.LogInformation("создание <нового> документа");
            }
            else
            {
                warehouseDocumentDb.Information        = ajaxWarehouseDocument.Information;
                warehouseDocumentDb.WarehouseReceiptId = ajaxWarehouseDocument.WarehouseReceiptId;
                _context.WarehouseDocuments.Update(warehouseDocumentDb);
                //_logger.LogInformation($"обновлёние <существующего> документа [#{warehouseDocumentDb.Id}]");
            }
            try
            {
                await _context.SaveChangesAsync();

                return(new ObjectResult(new ServerActionResult()
                {
                    Success = true,
                    Info = "Временный документ (регистры номенклатуры) сохранён",
                    Status = StylesMessageEnum.secondary.ToString()
                }));
            }
            catch (Exception ex)
            {
                string msg = $"Во время инициализации/сохранения временного документа произошла ошибка: {ex.Message}{(ex.InnerException is null ? "" : ". InnerException: " + ex.InnerException.Message)}";
                _logger.LogInformation(msg);
                return(new ObjectResult(new ServerActionResult()
                {
                    Success = false,
                    Info = msg,
                    Status = StylesMessageEnum.secondary.ToString()
                }));
            }
        }