Beispiel #1
0
        public string EnviarMovimientoMedicamento(CredencialServicio credencial, byte[] archivo, int establecimientoId)
        {
            string respuesta = "";

            if (UtilService.ValidarCredencial(credencial, out respuesta))
            {
                try
                {
                    string rutaDescarga = ConfigurationManager.AppSettings["rutaDescargaEnviosFua"] + "\\" + establecimientoId.ToString();
                    FisalUtil.Util.GuardarArchivo(rutaDescarga, "MovMed.zip", archivo);
                    respuesta = "Enviado con exito...!";
                }
                catch (Exception ex) { respuesta = ex.Message; }
            }
            return(respuesta);
        }
Beispiel #2
0
 public ApiConfigController(
     CourseService courseService, LanguageService languageService, IDbService dbService,
     ProblemDescriptionService problemDescriptionService, AppOptions appOptions,
     CompareService compareService, IHttpContextAccessor httpContextAccessor, UserService userService,
     UtilService utilService
     )
 {
     _courseService             = courseService;
     _languageService           = languageService;
     _dbService                 = dbService;
     _problemDescriptionService = problemDescriptionService;
     _appOptions                = appOptions;
     _compareService            = compareService;
     _userService               = userService;
     _utilService               = utilService;
 }
        /// <summary>
        /// Checks if the users request is authenticated/authorized by proofing users access token:
        /// 1. Check if user exists in the database if not fetch the user from Fracebooks Graph API.
        /// 1.1. If user exists check if it is up to date (if not fetch user)
        /// 2. Check if it equals the users access token in the Database.
        /// 2.1. If not... inspecting access tokens (user and app access token) via Facebooks Graph API.
        /// </summary>
        /// <param name="shortAccessToken">The users access token which has to be validated</param>
        /// <param name="userPassword">The users Facebook-Id</param>
        /// <returns>true if access token is validated, otherwise false</returns>
        public async Task <bool> authorizeRequest(String userFbId, String shortAccessToken)
        {
            FbUser user = await fbUserRepo.GetByFbIdAsync(userFbId);

            //fetch user from FB if not yet in DB
            if (user == null)
            {
                user = await fetchAndStoreUserDetails(shortAccessToken);
            }
            //Update Fb User when last updated time > 60 minutes
            else
            {
                if ((DateTime.Now - user.lastUpdatedTimestamp).TotalHours > 1.00)
                {
                    user = await fetchAndStoreUserDetails(shortAccessToken);
                }
            }

            //When Users short access token is the same as the one in the Database then the user ist validated
            if (user != null && shortAccessToken == user.shortAccessToken)
            {
                return(true);
            }
            else
            {
                String appAccessToken = UtilService.performGetRequest(new Uri("https://graph.facebook.com/oauth/access_token?client_id=" + fbAppId + "&client_secret=" +
                                                                              fbAppSecret + "&grant_type=client_credentials"));

                String jsonResponse = UtilService.performGetRequest(new Uri("https://graph.facebook.com/v2.3/debug_token?input_token=" + shortAccessToken + "&" + appAccessToken));

                FbTokenInspection insp = JsonConvert.DeserializeObject <FbTokenInspection>(jsonResponse);

                if (insp.data.is_valid == true)
                {
                    if (user != null)
                    {
                        user.shortAccessToken = shortAccessToken;
                        fbUserRepo.UpdateAsync(user);
                    }
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Beispiel #4
0
        // [ValidateAntiForgeryToken]
        public async Task <JsonResult> ApplicationAccepted(AcceptAndDeclineRentalApplicationModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new { Success = false }));
            }
            var user   = User.Identity.Name;
            var login  = AccountService.GetLoginByEmail(user);
            var result = PropertyService.AcceptApplication(model, login);


            // send email here
            if (result.IsSuccess)
            {
                var tenantPersonDetails = AccountService.GetPersonById(model.TenantId);
                var tenatLoginDetails   = AccountService.GetLoginById(model.TenantId);


                var property      = db.Property.FirstOrDefault(x => x.Id == model.PropertyId);
                var addressString = "";
                if (property != null)
                {
                    var address = PropertyService.GetAddressById(property.AddressId);
                    if (address != null)
                    {
                        if (address.Street != "" && address.City != "")
                        {
                            addressString = address.Number + " " + address.Street + ", " + address.Suburb + ", " + address.City + ", " + address.PostCode;
                        }
                    }
                }

                string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "Tenants/Home/MyRentals");
                SendGridEmailModel mail = new SendGridEmailModel
                {
                    RecipentName  = tenantPersonDetails.FirstName,
                    ButtonText    = "",
                    ButtonUrl     = url,
                    RecipentEmail = tenatLoginDetails.Email,
                    Address       = addressString,
                };
                await EmailService.SendEmailWithSendGrid(EmailType.AcceptRentalApplication, mail);

                return(Json(new { Success = result.IsSuccess }));
            }
            return(Json(new { Success = result.IsSuccess, Msg = result.ErrorMessage }));
        }
        public async Task MissedRaid(SocketUser user, [Remainder] string reason = "")
        {
            ISocketMessageChannel channel = (ISocketMessageChannel)Context.Guild.GetChannel(514112072326578207);

            if (String.IsNullOrEmpty(reason))
            {
                UserAccounts.AccountUpdate(user, "1", UserAccounts.UpdateType.MissedRaidNoReason);
                await channel.SendMessageAsync("", false, UtilService.Report(Context.User, user, (SocketChannel)Context.Channel, $"**Missed Raid**\n\n**Reason Given**: **__NONE__**"));
                await ReplyAsync($"Account Updated for {user.Username}");
            }
            else
            {
                UserAccounts.AccountUpdate(user, "1", UserAccounts.UpdateType.MissedRaidWithReason);
                await channel.SendMessageAsync("", false, UtilService.Report(Context.User, user, (SocketChannel)Context.Channel, $"**Missed Raid**\n\n**Reason Given**: {reason}"));
                await ReplyAsync($"Account Updated for {user.Username}");
            }
        }
Beispiel #6
0
        public async Task <ActionResult> SendActivationEmailToTenant(PropertyMyOnboardModel model)
        {
            var user = User.Identity.Name;

            if (String.IsNullOrEmpty(user))
            {
                return(Json(new { Success = false, ErrorMsg = "Invalid user!" }));
            }
            var owner = AccountService.GetLoginByEmail(user);

            if (owner == null)
            {
                return(Json(new { Success = false, ErrorMsg = "Can not find current user!" }));
            }
            var ownerPerson = AccountService.GetPersonByLoginId(owner.Id);
            var nvc         = new NameValueCollection();

            nvc.Set("TenantEmail", model.TenantToPropertyModel.TenantEmail);
            string url     = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "Account/RegisterToBeTenant", UtilService.ToQueryString(nvc));
            string subject = "Property Community: Account Activated";
            string body    =
                "Hello !<br />"
                + $"{ownerPerson.FirstName} has added you to be a tenant in his/her property and activated your account on Property Community.<br />";

            MailMessage msg = new MailMessage()
            {
                Subject         = subject,
                SubjectEncoding = System.Text.Encoding.UTF8,
                Body            = body,
                BodyEncoding    = System.Text.Encoding.UTF8,
                IsBodyHtml      = true
            };

            msg.To.Add(model.TenantToPropertyModel.TenantEmail);
            try
            {
                await EmailService.SendAsync(msg);

                return(Json(new { Success = true, Status = "Await response" }));
            }
            catch (Exception ex)
            {
                return(Json(new { Sucess = false, msg = ex.ToString() }));
            }
        }
Beispiel #7
0
        // GET: Inquiry
        public ActionResult Index(string id)
        {
            log.Info("inquiry index : projectid=" + id);
            ViewBag.projectId = id;
            SelectListItem empty = new SelectListItem();

            empty.Value = "";
            empty.Text  = "";
            List <SelectListItem> selectMain = UtilService.getMainSystem(id, service);

            // selectMain.Add(empty);
            ViewBag.SystemMain = selectMain;
            List <SelectListItem> selectSub = UtilService.getSubSystem(id, service);

            //selectSub.Add(empty);
            ViewBag.SystemSub = selectSub;
            return(View());
        }
Beispiel #8
0
        public async Task Ban([Summary("The user you want to ban. (@ them)")] SocketUser bUser, [Summary("The reason you're banning them.")][Remainder] string reason)
        {
            var requestingUser = (SocketGuildUser)Context.User;
            var bannedUser     = (IGuildUser)bUser;
            var reportChannel  = (ISocketMessageChannel)Context.Guild.GetChannel(514112072326578207);

            if (UtilService.IsOfficer(requestingUser.Roles))
            {
                await bannedUser.BanAsync(2, reason);
                await ReplyAsync($"{bannedUser.Username} with ID {bUser.Id} has been banned from {Context.Guild.Name}");

                await reportChannel.SendMessageAsync("", false, UtilService.BanReporter(bUser, Context.User, (SocketChannel)Context.Channel, reason));

                LoggingService.Log("admin", LogSeverity.Info, $"{Context.User.Username} has banned {bannedUser.Username}");
                return;
            }
            else
            {
                await ReplyAsync("You do not have the required role to do that.");

                LoggingService.Log("admin", LogSeverity.Warning, $"{Context.User.Username} Requested a command without permision.");
            }
        }
Beispiel #9
0
        /**
         * fetches a cities details from the google maps api and stores the updated city in the DB.
         */

        private City fetchCityDetailFromGMapsAndStoreInDb(City city)
        {
            var urlEncodedAddress = HttpUtility.UrlEncode(city.formatted_address);
            var requestUrl        = "https://maps.googleapis.com/maps/api/geocode/json?address=" + urlEncodedAddress + "&key=" +
                                    MAPS_KEY;
            var result        = UtilService.performGetRequest(new Uri(requestUrl));
            var fetchedCities = JsonConvert.DeserializeObject <GMapsGeocodingResponse>(result);

            if (fetchedCities.status == "OK")
            {
                var fetchedCity = fetchedCities.results[0];
                fetchedCity.Id = city.Id;
                var citySaveTask = cityRepo.UpdateAsync(fetchedCity);
                citySaveTask.Wait();
                Thread.Sleep(1000 * 2); //otherwise google maps kicks us out :-/
                return(fetchedCity);
            }
            else
            {
                Thread.Sleep(1000 * 10 * 60);
                return(fetchCityDetailFromGMapsAndStoreInDb(city));
            }
        }
Beispiel #10
0
        public async System.Threading.Tasks.Task <JsonResult> SaveJobQuote(QuoteModel jobQuoteViewModel)
        {
            if (ModelState.IsValid)
            {
                var files  = Request.Files;
                var user   = User.Identity.Name;
                var login  = AccountService.GetLoginByEmail(user);
                var result = JobService.AddJobQuote(jobQuoteViewModel, login, Request.Files);
                #region


                if (result.IsSuccess)
                {
                    var propertyOwner      = JobService.GetOwnerDetails(jobQuoteViewModel.JobRequestId);
                    var propertyOwnerLogin = AccountService.GetLoginById(propertyOwner.Id);

                    var property = db.TenantJobRequest.Where(x => x.Id == jobQuoteViewModel.JobRequestId).Select(x => x.Property).FirstOrDefault();
                    var nvc      = new NameValueCollection();
                    nvc.Add("marketJobId", jobQuoteViewModel.JobRequestId.ToString());
                    string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "/Jobs/Home/GetJobQuotes", UtilService.ToQueryString(nvc));
                    SendGridEmailModel mail = new SendGridEmailModel
                    {
                        RecipentName  = propertyOwner.FirstName,
                        ButtonText    = "",
                        ButtonUrl     = url,
                        Address       = property.Address.ToAddressString(),
                        RecipentEmail = propertyOwnerLogin.Email,
                        JobTitle      = jobQuoteViewModel.Title ?? "No Title",
                    };
                    await EmailService.SendEmailWithSendGrid(EmailType.NewQuoteEmail, mail);
                }

                #endregion
                return(Json(new { Success = result.IsSuccess, ErrorMsg = result.ErrorMessage ?? "" }));
            }
            return(Json(new { success = false }));
        }
Beispiel #11
0
        public async Task <ActionResult> AccceptQuote(JobAcceptedModel jobModel)
        {
            var user = User.Identity.Name;

            if (String.IsNullOrEmpty(user))
            {
                return(Json(new { Success = false, Msg = "User not found!" }));
            }
            var login  = AccountService.GetLoginByEmail(user);
            var result = JobService.AcceptQuote(jobModel, login);

            if (result.IsSuccess)
            {
                var serviceProviderPersonDetails = JobService.GetPersonByJobQuoteId(jobModel);
                var serviceProviderLoginDetails  = AccountService.GetLoginById(serviceProviderPersonDetails.Id);
                var jobDetails = JobService.GetMarketJobById(jobModel.JobRequestId);
                var nvc        = new NameValueCollection();
                nvc.Add("userAction", "2");

                string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "/Jobs/Home", UtilService.ToQueryString(nvc));
                SendGridEmailModel mail = new SendGridEmailModel
                {
                    RecipentName  = serviceProviderPersonDetails.FirstName,
                    ButtonText    = "",
                    ButtonUrl     = url,
                    RecipentEmail = serviceProviderLoginDetails.Email,
                    JobTitle      = jobDetails.Title ?? "No Title",
                };
                await EmailService.SendEmailWithSendGrid(EmailType.AcceptQuote, mail);

                return(Json(new { Success = result.IsSuccess, Msg = result.ErrorMessage }));
            }


            return(Json(new { Success = false }));
        }
Beispiel #12
0
        //更新任務分派資料
        public String refreshTaskItem(FormCollection form)
        {
            log.Info("form:" + form.Count);
            string         msg  = "修改任務分派資料成功!!";
            TND_TASKASSIGN item = new TND_TASKASSIGN();

            item.PROJECT_ID = form["prjid"];
            if (null != form["task_id"] && form["task_id"] != "")
            {
                item.TASK_ID = Int64.Parse(form["task_id"]);
            }
            item.USER_ID   = form["userId"];
            item.TASK_TYPE = form["taskType"];
            item.TASK_ITEM = form["taskItem"];
            item.REMARK    = form["taskRemark"];
            if (null != form["finishDate"] && form["finishDate"] != "")
            {
                item.FINISH_DATE = Convert.ToDateTime(form.Get("finishDate"));
            }

            item.CREATE_DATE = DateTime.Now;
            UserService us = new UserService();
            SYS_USER    u  = UtilService.GetUserInfoFromSession(Session);

            item.CREATE_ID   = u.USER_ID;
            item.MODIFY_ID   = u.USER_ID;
            item.MODIFY_DATE = DateTime.Now;
            TnderProjectService service = new TnderProjectService();
            int i = service.updateTask(item);

            if (i == 0)
            {
                msg = service.message;
            }
            return(msg);
        }
        public async Task <ActionResult> Create([FromBody] CreateUserRequest command)
        {
            var user = new ApplicationUser
            {
                UserName           = command.Username,
                Email              = command.Email,
                FirstName          = command.FirstName,
                LastName           = command.LastName,
                PhoneNumber        = command.PhoneNumber,
                IdentificationCard = command.IdentificationCard,
                EstadoRegistro     = command.EstadoRegistro
            };
            await base.Command <CreateUserRequest, ICollection <UserDto> >(command);

            var emailSend = await EmailSender.SendEmailAsync(user.Email, user.FirstName,
                                                             "Bienvenido a VentasApp",
                                                             await UtilService.getHtmlBodyAccount(command.Username, command.Password));

            if (emailSend > 0)
            {
                return(Ok("Se ha enviado un correo de confirmacion"));
            }
            return(BadRequest());
        }
Beispiel #14
0
        public async Task <ActionResult> Delete(int id)
        {
            var user = User.Identity.Name;

            var property = db.Property.First(p => p.Id == id);

            if (property == null)
            {
                return(Json(new
                {
                    Success = false,
                    message = "The selected property can't be found in the database."
                }));
            }
            else
            {
                property.IsActive = false;
                var op = db.OwnerProperty.FirstOrDefault(x => x.PropertyId == id);
                db.OwnerProperty.Remove(op);
                var applicants = property.RentalListing.Where(x => x.IsActive).SelectMany(x => x.RentalApplication)
                                 .Where(x => x.IsActive && x.ApplicationStatusId != 3)
                                 .Select(x => x.Person).Select(x => new Recipient
                {
                    Name  = x.FirstName,
                    Email = x.Login.UserName
                }).ToList();
                var nvc     = new NameValueCollection();
                var url1    = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "/Tenants/Home/MyRentalApplications", UtilService.ToQueryString(nvc));
                var tenants = property.TenantProperty.Where(x => x.IsActive ?? false)
                              .Select(x => x.Tenant.Person)
                              .Select(x => new Recipient
                {
                    Name  = x.FirstName,
                    Email = x.Login.UserName
                }).ToList();
                var url2             = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "/Tenants/Home/MyRentals", UtilService.ToQueryString(nvc));
                var serviceSuppliers = property.Job.Where(x => x.JobStatusId != 5 || x.JobStatusId != 6 && x.ProviderId != null)
                                       .Select(x => x.ServiceProvider.Person)
                                       .Select(x => new Recipient
                {
                    Name  = x.FirstName,
                    Email = x.Login.UserName
                });
                var url3 = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "/Companies/Home/MyJobs", UtilService.ToQueryString(nvc));
                foreach (var item in property.RentalListing)
                {
                    item.IsActive = false;
                    foreach (var app in item.RentalApplication)
                    {
                        app.ApplicationStatusId = 3;
                    }
                }
                foreach (var item in property.TenantProperty)
                {
                    item.IsActive = (item.IsActive ?? false) ? false : item.IsActive;
                }

                foreach (var item in property.Job)
                {
                    item.JobStatusId = (item.JobStatusId != 5 && item.JobStatusId != 6) ? item.JobStatusId = 5 : item.JobStatusId;
                }
                var address = property.Address.ToAddressString();
                await EmailService.SendEmailToGroup(EmailType.DeletePropertyRentApplicationDeclined, applicants, url1, address);

                await EmailService.SendEmailToGroup(EmailType.DeletePropertyRentalCanceled, tenants, url2, address);

                await EmailService.SendEmailToGroup(EmailType.DeletePropertyJobCanceled, serviceSuppliers, url3, address);

                db.SaveChanges();

                return(Json(new
                {
                    Success = true,
                    message = "Property deleted successfully",
                    id = id
                }));
            }
        }
Beispiel #15
0
 public static CcData IncludeDirectories(this CcData item, UtilService utilService)
 {
     return(utilService.IncludeDirectories(item));
 }
        public async Task <ActionResult> SendInvitationEmailToTenant(AddTenantToPropertyModel model)
        {
            var user = User.Identity.Name;

            if (String.IsNullOrEmpty(user))
            {
                return(Json(new { Success = false, ErrorMsg = "Invalid user!" }));
            }
            var owner = AccountService.GetLoginByEmail(user);

            if (owner == null)
            {
                return(Json(new { Success = false, ErrorMsg = "Can not find current user!" }));
            }
            var ownerPerson = AccountService.GetPersonByLoginId(owner.Id);
            var property    = PropertyService.GetPropertyById(model.PropertyId);

            if (property == null)
            {
                return(Json(new { Success = false, ErrorMsg = "Can not find property!" }));
            }
            var nvc = new NameValueCollection();

            nvc.Set("TenantEmail", model.TenantEmail);
            nvc.Set("PropertyId", model.PropertyId.ToString());
            nvc.Set("StartDate", model.StartDate.ToString());
            nvc.Set("EndDate", model.EndDate.ToString());
            nvc.Set("PaymentFrequencyId", model.PaymentFrequencyId.ToString());
            nvc.Set("PaymentAmount", model.PaymentAmount.ToString());
            string url     = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "Account/RegisterToBeTenant", UtilService.ToQueryString(nvc));
            string subject = "Property Community: Invitation to register";
            string body    =
                "Hello !<br />"
                + $"{ownerPerson.FirstName} has added you to be a tenant in his/her property and invited you to register at Property Community.<br />"
                + "Please <a target='_blank' href=" + url + "> Click Here </a> to register<br />";
            MailMessage msg = new MailMessage()
            {
                Subject         = subject,
                SubjectEncoding = System.Text.Encoding.UTF8,
                Body            = body,
                BodyEncoding    = System.Text.Encoding.UTF8,
                IsBodyHtml      = true
            };

            msg.To.Add(model.TenantEmail);
            try
            {
                await EmailService.SendAsync(msg);

                return(Json(new { Success = true, Status = "Await response" }));
            }
            catch (Exception ex)
            {
                return(Json(new { Sucess = false, msg = ex.ToString() }));
            }
        }
        public void Calculate_DuplicatedValues_ReturnDistinct()
        {
            var response = UtilService.GetEnumByName <DayTime>("morning");

            Assert.Equal(DayTime.morning, response);
        }
Beispiel #18
0
 public EmbedBuilder NormalizeEmbed(string title, string description, ColorType colorType = ColorType.Normal,
                                    bool withRequested = false)
 {
     return(UtilService.NormalizeEmbed(title, description, colorType, Random, Server, withRequested, Context));
 }
        public async Task <ActionResult> AddRentalApplication(RentalApplicationModel model)
        {
            if (ModelState.IsValid)
            {
                var files    = Request.Files;
                var userName = User.Identity.Name;

                if (String.IsNullOrEmpty(userName))
                {
                    return(Json(new { Success = false, ErrorMsg = "User not exist!" }));
                }


                var login  = AccountService.GetLoginByEmail(userName);
                var result = RentalService.AddRentallApllication(model, login, Request.Files);
                if (result.IsSuccess)
                {
                    var propertyOwner      = RentalService.GetOwnerDetails(model);
                    var propertyOwnerLogin = AccountService.GetLoginById(propertyOwner.Id);
                    var property           = db.Property.FirstOrDefault(x => x.Id == model.PropertyId);
                    var addressString      = "";
                    if (property != null)
                    {
                        var address = PropertyService.GetAddressById(property.AddressId);
                        if (address != null)
                        {
                            if (address.Street != "" && address.City != "")
                            {
                                addressString = address.Number + " " + address.Street + ", " + address.Suburb + ", " + address.City + ", " + address.PostCode;
                            }
                        }
                    }
                    //  string url = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "PropertyOwners/Property/RentalProperties");
                    var nvc = new NameValueCollection();
                    nvc.Add("PropId", model.PropertyId.ToString());
                    nvc.Add("returnUrl", "/PropertyOwners/Property/RentalProperties");
                    string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "/PropertyOwners/Property/AllRentalApplications", UtilService.ToQueryString(nvc));
                    SendGridEmailModel mail = new SendGridEmailModel
                    {
                        RecipentName  = propertyOwner.FirstName,
                        ButtonText    = "",
                        ButtonUrl     = url,
                        RecipentEmail = propertyOwnerLogin.Email,
                        Address       = addressString,
                    };
                    await EmailService.SendEmailWithSendGrid(EmailType.NewApplicationEmail, mail);
                }
                return(result.IsSuccess ? Json(new { Success = true }) : Json(new { Success = false, ErrorMsg = result.ErrorMessage }));
            }
            return(Json(new { Success = false }));
        }
        public void test2()
        {
            var response = UtilService.GetEnumName <MorningMeals>("2");

            Assert.Equal(MorningMeals.toast.ToString(), response);
        }
        public void test8()
        {
            var response = UtilService.IsNumeric("1");

            Assert.True(response);
        }
 public void test4()
 {
     Assert.Throws <ArgumentException>(() => UtilService.GetEnumName <int>("test"));
 }
 public void ReturnExcp()
 {
     Assert.Throws <ArgumentException>(() => UtilService.GetEnumByName <DayTime>("test"));
 }
Beispiel #24
0
        public async Task <JsonResult> AddNewProperty(PropertyMyOnboardModel model)
        {
            var files   = Request.Files;
            var status  = true;
            var message = "Record added successfully";
            var data    = model;
            AddTenantToPropertyModel tenant = new AddTenantToPropertyModel();
            var user         = User.Identity.Name;
            var login        = AccountService.GetLoginByEmail(user);
            var newProp      = PropertyOwnerService.AddOnboardProperty(login, model);
            var newRepayment = new PropertyRepayment();

            if (newProp == null)
            {
                return(Json(new { Success = false, message = "Cannot add the property!" }));
            }
            else
            {
                newRepayment = PropertyOwnerService.AddOnboardRepayment(login, model.Repayments, newProp.Id);
                decimal _totalRepayment = 0;
                int     _nosWeeks       = 0;
                int     _nosFortnights  = 0;
                int     _nosMonthly     = 0;
                if (newRepayment != null)
                {
                    foreach (Service.Models.RepaymentViewModel repayment in model.Repayments)
                    {
                        switch (repayment.FrequencyType)
                        {
                        case 1:     // Weekly
                                    // find the nos of weeks in datediff(StartDate, EndDate)
                            _nosWeeks = ((newRepayment.EndDate - newRepayment.StartDate) ?? TimeSpan.Zero).Days / 7;
                            // _totalAmount = nos weeks * amount
                            _totalRepayment = _nosWeeks * newRepayment.Amount;
                            break;

                        case 2:       // Fortnightly
                                      // find the nos of Fortnights in datediff(StartDate, EndDate)
                            _nosFortnights = ((newRepayment.EndDate - newRepayment.StartDate) ?? TimeSpan.Zero).Days / 14;
                            // _totalAmount = nos weeks * amount
                            _totalRepayment = _nosFortnights * newRepayment.Amount;
                            break;

                        case 3:     //Monthly
                                    // find the nos of Monthls in datediff(StartDate, EndDate)
                            _nosMonthly     = ((newRepayment.EndDate - newRepayment.StartDate) ?? TimeSpan.Zero).Days / 30;
                            _totalRepayment = _nosMonthly * newRepayment.Amount;
                            // _totalAmount = nos Monthls * amount
                            break;
                        }
                        actualTotalRepayment += _totalRepayment;
                    }
                }
                //*****AddExpenses
                var newExpense = new PropertyExpense();
                newExpense = PropertyOwnerService.AddOnboardExpense(login, model.Expenses, newProp.Id);
                //******AddFinancial
                var newFinancial = new PropertyFinance();
                newFinancial = PropertyOwnerService.AddOnboardFinance(login, model, newProp.Id, actualTotalRepayment);
                var ownerPerson = AccountService.GetPersonByLoginId(login.Id);
                if (!model.IsOwnerOccupied)
                {
                    var ten = AccountService.GetExistingLogin(model.TenantToPropertyModel.TenantEmail);
                    if (ten == null)
                    {
                        var sendEmail = false;
                        var temPass   = UtilService.GeneraterRandomKey(8);
                        var createRes = AccountService.CreateTenantAccount(model.TenantToPropertyModel, login, temPass);

                        if (createRes.IsSuccess)
                        {
                            ten       = createRes.NewObject as Login;
                            sendEmail = true;
                        }

                        if (sendEmail)
                        {
                            var emailRes = await EmailService.SendCreateAccountToTenant(model, temPass, ownerPerson);
                        }
                        else
                        {
                            return(Json(new { Success = false, NewPropId = newProp.Id }));
                        }
                        //return Json(new { Success = false, NewPropId = newProp.Id, Todo = "Send email", ErrorMsg = "Cannot find person in login table!" });
                    }
                    else // ten not null
                    {
                        if (!ten.IsActive)
                        {
                            var resultTenantActive = PropertyService.ActivateTenant(login, ten.Id);
                            if (resultTenantActive.IsSuccess)
                            {
                                await EmailService.SendActivationEmailToTenant(model, ownerPerson);
                            }
                        }
                    }
                    var person = AccountService.GetPersonByLoginId(ten.Id);
                    //var result = PropertyService.AddTenantToProperty(login, person.Id, newProp.Id, model.TenantToPropertyModel.StartDate,
                    //    model.TenantToPropertyModel.EndDate, model.TenantToPropertyModel.PaymentFrequencyId, model.TenantToPropertyModel.PaymentAmount);
                    model.TenantToPropertyModel.Liabilities = model.LiabilityValues;
                    model.TenantToPropertyModel.PropertyId  = newProp.Id;
                    var result = PropertyService.AddTenant(login, ten.Id, model.TenantToPropertyModel);
                    if (result.IsSuccess)
                    {
                        return(Json(new { Sucess = true, Msg = "Added!", NewPropId = newProp.Id, result = "Redirect", url = Url.Action("Index", "PropertyOwners") }));
                    }
                    else
                    {
                        return(Json(new { Sucess = false, NewPropId = newProp.Id, Msg = result.ErrorMessage, redirect = "Redirect", url = Url.Action("Index", "PropertyOwners") }));
                    }
                }
            }
            return(Json(new { Success = status, NewPropId = newProp.Id, message = message, data = tenant }));
        }
        public void test3()
        {
            var response = UtilService.GetEnumName <MorningMeals>("5");

            Assert.Equal("error", response);
        }
Beispiel #26
0
 public productController(ILogger <productController> logger, ProductService ProductService, UtilService utilService)
 {
     this.utilService    = utilService;
     this.ProductService = ProductService;
     _logger             = logger;
 }
        public void test7()
        {
            var response = UtilService.IsNumeric("morning");

            Assert.False(response);
        }
 public void SetUp()
 {
     us = new UtilService();
 }
 public async Task Execute(IJobExecutionContext context)
 {
     string builder = string.Format("Fort siege in 2 hours!! Get online!!");
     await UtilService.SendMessage(builder, "clan-announcements");
 }
 public ActionResult <List <string> > GetList(string q = null) =>
 UtilService.ListProperty(_service.Query(), s => s.Nome, q).ToList();