public void Mutation_ConfirmCleanedAndServices_InvalidStatus() { Database.WriteAsync(realm => realm.Add(new HouseKeeping { Id = 33, Status = (int)HouseKeeping.StatusEnum.Pending, Type = (int)HouseKeeping.TypeEnum.ExpectedDeparture, Employee = EmployeeBusiness.Get("admin"), Booking = BookingBusiness.Get(1) })).Wait(); SchemaHelper.ExecuteAndExpectError( "Không thể xác nhận dọn phòng", @"/_GraphQL/HouseKeeping/mutation.confirmCleanedAndServices.gql", new { servicesDetails = new[] { new { number = 1, service = new { id = 1 } }, new { number = 2, service = new { id = 1 } } }, houseKeepingId = 33 }, p => p.PermissionCleaning = true ); }
public void Mutation_ConfirmCleaned_InvalidEmployee() { Database.WriteAsync(realm => { realm.Add(new Employee { Id = "nhanvien_60", Address = "Địa chỉ", IsActive = true, Birthdate = DateTimeOffset.Now, Email = "*****@*****.**", Gender = true, Name = "Quản trị viên", IdentityCard = "123456789", Password = CryptoHelper.Encrypt("12345678"), PhoneNumber = "+84 0123456789", Position = PositionBusiness.Get(1), StartingDate = DateTimeOffset.Now }); realm.Add(new HouseKeeping { Id = 22, Status = (int)HouseKeeping.StatusEnum.Cleaning, Employee = EmployeeBusiness.Get("nhanvien_60"), Booking = BookingBusiness.Get(1) }); }).Wait(); SchemaHelper.ExecuteAndExpectError( "Nhân viên không được phép xác nhận dọn", @"/_GraphQL/HouseKeeping/mutation.confirmCleaned.gql", new { id = 22 }, p => p.PermissionCleaning = true ); }
public void Mutation_DeleteServicesDetail_InvalidBooking_Status() { Database.WriteAsync(realm => { realm.Add(new Booking { Id = 200, Status = (int)Booking.StatusEnum.CheckedOut, EmployeeBooking = EmployeeDataAccess.Get("admin"), EmployeeCheckIn = EmployeeDataAccess.Get("admin"), EmployeeCheckOut = EmployeeDataAccess.Get("admin"), Bill = BillDataAccess.Get(1), Room = RoomDataAccess.Get(1) }); realm.Add(new ServicesDetail { Id = 11, Booking = BookingBusiness.Get(1), Service = ServiceBusiness.Get(200), Number = 10 }); }).Wait(); SchemaHelper.ExecuteAndExpectError( "Phòng đã check-out. Không thể cập nhật/xóa chi tiết dịch vụ", @"/_GraphQL/ServicesDetail/mutation.deleteServicesDetail.gql", new { id = 11 }, p => p.PermissionCleaning = true ); }
public void Mutation_UpdateServicesDetail_InvalidService() { Database.WriteAsync(realm => realm.Add(new ServicesDetail { Id = 20, Booking = BookingBusiness.Get(1), Service = ServiceBusiness.Get(1), Number = 10 })).Wait(); SchemaHelper.ExecuteAndExpectError( "Mã dịch vụ không tồn tại", @"/_GraphQL/ServicesDetail/mutation.updateServicesDetail.gql", new { input = new { id = 20, number = 2, service = new { id = 100 } } }, p => p.PermissionCleaning = true ); }
public void Mutation_ConfirmCleanedAndServices_InvalidType() { Database.WriteAsync(realm => realm.Add(new HouseKeeping { Id = 34, Status = (int)HouseKeeping.StatusEnum.Cleaning, Type = (int)HouseKeeping.TypeEnum.ExpectedArrival, Employee = EmployeeBusiness.Get("admin"), Booking = BookingBusiness.Get(1) })).Wait(); SchemaHelper.ExecuteAndExpectError( "Chỉ được sử dụng kiểu xác nhận này đối với phòng check-out", @"/_GraphQL/HouseKeeping/mutation.confirmCleanedAndServices.gql", new { servicesDetails = new[] { new { number = 1, service = new { id = 1 } }, new { number = 2, service = new { id = 1 } } }, houseKeepingId = 34 }, p => p.PermissionCleaning = true ); }
/// <summary> /// Consultar assentos disponíveis. (O objetivo final é permitir que o cliente compre um assento especial) /// Neste caso estamos usando uma reserva nacional, com apenas um passageiro. /// O motivo disto é facilitar o manuseio da reserva, já que em reservas nacionais eu /// tenho grupo de assento específicos para determinados tipos de tarifas. /// Exemplo a tarifa Business que tem direito a um assento de luxo.Outro ponto que determinou fazermos desta forma, /// foi o fato que em voos internacionais temos o skysofa. Assento personalizado da Azul, que possui uma série de regras, /// que dificulta o desenvolvimento. /// /// No novo serviço da navitaire, não está sendo disponibilizado informações referentes ao as características do assento, /// no caso não são informados as seguintes características do assento: /// * O Assento é na janela; /// * O Assento é na saida de emergencia; /// * O Assento é reclinável; /// * O assento é parcialmente reclinável; /// </summary> static async Task ConsultarAssentosDisponiveisEmUmVoo() { ///Obtendo o token necessário para consumir o serviço da Navitaire. string token = await(new LoginBusiness()).LogonAndGetTokenNavitaire(); BookingBusiness bookingBusiness = new BookingBusiness(token); SeatBusiness seatBusiness = new SeatBusiness(token); ///Para que possamos fazer qualquer alteração de uma reserva, se faz necessário estamos com ela em sessão. ///por esse motivo realizamos usamos a função ReatriveBooking. Desta forma inserindo em sessão o booking que iremos trabalhar. BookingResponse booking = await bookingBusiness.ReatriveBooking("G7VIVI"); ///Para facilitar o desenvolvimento, estamos sempre usando a chave do primeiro seguinto, da primeira jornada. List <SeatMapResponse> seatMapResponseList = await seatBusiness.GetSeatMapAvailabilityBySegmentKey(booking.Journeys[0].Segments[0].SegmentKey); ///Função retorna os assentos disponíveis, usando como base os atributos Type e Assignable, do objeto unit. ///O objeto unit representa uma unidade de espaço dentro a aeronave, ou seja posso ter unit, que representam ///espaços em brancos ou por exemplo o banheiro de uma determinada aeronave. ///Para trazermos apenas unidades que representam assento, estamos verificando sei o campo Type, ///está sendo preenchido com o valor “NormalSeat”. Alem de verificar se o valor do objeto Assignable está como true, ///indicando que o assento está disponível para marcação. ///Outro filtro que tive que incluir, pois a Navitaire estava me levantando erro é quando o assento está disponível para marcação, ///porém ele está em espera, por esse motivo, colocamos um filtro no campo Availability, trazendo apenas assentos com o valor ///deste campo igual a open (disponível). List <Unit> units = seatBusiness.GetAvailabilitySeat(seatMapResponseList); }
public ActionResult Save(FormCollection actionValues) { var scheduler = new DHXScheduler(this); var action = new DataAction(actionValues); // scheduler.InitialValues.Add("text"); try { var changedEvent = (Schedule)DHXEventsHelper.Bind(typeof(Schedule), actionValues); int d = Convert.ToInt32(System.Web.HttpContext.Current.Session["ide"]); var dat = new BookingBusiness(); // changedEvent.text = dat.GetSaveBooking(d).FullName + "<br/>" + dat.GetSaveBooking(d).Physician; string name = dat.GetSaveBooking(d).FullName; switch (action.Type) { case DataActionTypes.Insert: dat.InsertSaveBooking(changedEvent, d); break; case DataActionTypes.Delete: int num; try { num = Convert.ToInt32(action.SourceId); } catch (Exception) { return(RedirectToAction("Index", "Calendar")); } dat.DeleteSavedBooking(num); break; default: // "update" var evt = b.displaySchedule().SingleOrDefault(ez => ez.id == action.SourceId); DHXEventsHelper.Update(evt, changedEvent, new List <string>() { "id" }); //do update b.UpdateSavedBooking(evt, changedEvent); break; } action.TargetId = changedEvent.id; } catch { action.Type = DataActionTypes.Error; } return((ContentResult) new AjaxSaveResponse(action)); }
public Booking GetManaged() { var booking = BookingBusiness.Get(Id); if (booking == null) { throw new Exception("Mã booking không tồn tại"); } return(booking); }
protected View() { ClientRepository = new Repository <ClientEntity>(); RoomRepository = new Repository <RoomEntity>(); BookingRepository = new Repository <BookingEntity>(); ClientBusiness = new ClientBusiness(ClientRepository); RoomBusiness = new RoomBusiness(RoomRepository); HotelBusiness = new HotelBusiness(RoomRepository); BookingBusiness = new BookingBusiness(RoomRepository, BookingRepository); BookingServices = new BookingServices(BookingBusiness, ClientBusiness, RoomBusiness); RoomServices = new RoomServices(RoomBusiness); ClientServices = new ClientServices(ClientBusiness); HotelServices = new HotelServices(HotelBusiness); }
public void Mutation_DeleteServicesDetail() { Database.WriteAsync(realm => realm.Add(new ServicesDetail { Id = 10, Booking = BookingBusiness.Get(1) })).Wait(); SchemaHelper.Execute( @"/_GraphQL/ServicesDetail/mutation.deleteServicesDetail.gql", @"/_GraphQL/ServicesDetail/mutation.deleteServicesDetail.schema.json", new { id = 10 }, p => p.PermissionCleaning = true ); }
public void Query_HouseKeeping() { Database.WriteAsync(realm => realm.Add(new HouseKeeping { Id = 40, Status = (int)HouseKeeping.StatusEnum.Cleaning, Type = (int)HouseKeeping.TypeEnum.ExpectedDeparture, Employee = EmployeeBusiness.Get("admin"), Booking = BookingBusiness.Get(1) })).Wait(); SchemaHelper.Execute( @"/_GraphQL/HouseKeeping/query.houseKeeping.gql", @"/_GraphQL/HouseKeeping/query.houseKeeping.schema.json", new { id = 40 } ); }
public void Mutation_ConfirmCleaned_InvalidStatus() { Database.WriteAsync(realm => realm.Add(new HouseKeeping { Id = 21, Status = (int)HouseKeeping.StatusEnum.Pending, Employee = EmployeeBusiness.Get("admin"), Booking = BookingBusiness.Get(1) })).Wait(); SchemaHelper.ExecuteAndExpectError( "Không thể xác nhận dọn phòng", @"/_GraphQL/HouseKeeping/mutation.confirmCleaned.gql", new { id = 21 }, p => p.PermissionCleaning = true ); }
public void Mutation_AssignCleaningService_InvalidStaus() { Database.WriteAsync(realm => realm.Add(new HouseKeeping { Id = 11, Status = (int)HouseKeeping.StatusEnum.Cleaned, Employee = EmployeeBusiness.Get("admin"), Booking = BookingBusiness.Get(1) })).Wait(); SchemaHelper.ExecuteAndExpectError( "Không thể nhận phòng này. Phòng đã hoặc đang được dọn", @"/_GraphQL/HouseKeeping/mutation.assignCleaningService.gql", new { id = 11 }, p => p.PermissionCleaning = true ); }
public void Mutation_ConfirmCleaned() { Database.WriteAsync(realm => realm.Add(new HouseKeeping { Id = 20, Status = (int)HouseKeeping.StatusEnum.Cleaning, Employee = EmployeeBusiness.Get("admin"), Booking = BookingBusiness.Get(1) })).Wait(); SchemaHelper.Execute( @"/_GraphQL/HouseKeeping/mutation.confirmCleaned.gql", @"/_GraphQL/HouseKeeping/mutation.confirmCleaned.schema.json", new { id = 20 }, p => p.PermissionCleaning = true ); }
public void Mutation_ConfirmCleaned_InvalidType() { Database.WriteAsync(realm => realm.Add(new HouseKeeping { Id = 23, Type = (int)HouseKeeping.TypeEnum.ExpectedDeparture, Status = (int)HouseKeeping.StatusEnum.Cleaning, Employee = EmployeeBusiness.Get("admin"), Booking = BookingBusiness.Get(1) })).Wait(); SchemaHelper.ExecuteAndExpectError( "Không thể sử dụng kiểu xác nhận này đối với phòng check-out", @"/_GraphQL/HouseKeeping/mutation.confirmCleaned.gql", new { id = 23 }, p => p.PermissionCleaning = true ); }
public void Mutation_ConfirmCleanedAndServices_InvalidService() { Database.WriteAsync(realm => { realm.Add(new Service { Id = 40, IsActive = false, Name = "Tên dịch vụ", Unit = "Đơn vị" }); realm.Add(new HouseKeeping { Id = 32, Status = (int)HouseKeeping.StatusEnum.Cleaning, Type = (int)HouseKeeping.TypeEnum.ExpectedDeparture, Employee = EmployeeBusiness.Get("admin"), Booking = BookingBusiness.Get(1) }); }).Wait(); SchemaHelper.ExecuteAndExpectError( "Dịch vụ Tên dịch vụ đã ngừng cung cấp", @"/_GraphQL/HouseKeeping/mutation.confirmCleanedAndServices.gql", new { servicesDetails = new[] { new { number = 1, service = new { id = 1 } }, new { number = 2, service = new { id = 40 } } }, houseKeepingId = 32 }, p => p.PermissionCleaning = true ); }
/// <summary> /// Update the navigation property bookingBusinesses in solutions /// <param name="body"></param> /// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param> /// </summary> public RequestInformation CreatePatchRequestInformation(BookingBusiness body, Action <BookingBusinessItemRequestBuilderPatchRequestConfiguration> requestConfiguration = default) { _ = body ?? throw new ArgumentNullException(nameof(body)); var requestInfo = new RequestInformation { HttpMethod = Method.PATCH, UrlTemplate = UrlTemplate, PathParameters = PathParameters, }; requestInfo.SetContentFromParsable(RequestAdapter, "application/json", body); if (requestConfiguration != null) { var requestConfig = new BookingBusinessItemRequestBuilderPatchRequestConfiguration(); requestConfiguration.Invoke(requestConfig); requestInfo.AddRequestOptions(requestConfig.Options); requestInfo.AddHeaders(requestConfig.Headers); } return(requestInfo); }
/// <summary> /// Reservar assento para um cliente em um voo e indicar um link do site onde ele possa pagar o assento /// depois de deixar o booking negativo /// Nesta função, irei repetir algumas chamadas do método ConsultarAssentosDisponiveisEmUmVoo, /// pois a marcação de assento segue o mesmo princípio da exibição do mapa de assento. /// Outro ponto é que para que eu possa marcar um assento, se faz necessário o unityKey, /// que é retornado justamente na função que traz o mapa de assento. Com relação a marcação de assentos, /// estamos usando apenas um fluxo feliz, ou seja o passageiro que iremos utilizar não possui assento, /// caso contrário teríamos que remover o assento, para após marcar um novo. /// Outro ponto é que o usuário não pode realizar mudança de assento, para um assento de valor inferior ao já registrado na reserva. /// Pois hoje a Azul não trabalha com reembolso do valor do assento. /// </summary> static async Task ComprarAssentoParaClienteEmUmVoo() { ///Obtendo o token necessário para consumir o serviço da Navitaire. string token = await(new LoginBusiness()).LogonAndGetTokenNavitaire(); BookingBusiness bookingBusiness = new BookingBusiness(token); SeatBusiness seatBusiness = new SeatBusiness(token); ///Para que possamos fazer qualquer alteração de uma reserva, se faz necessário estamos com ela em sessão. ///por esse motivo realizamos usamos a função ReatriveBooking. Desta forma inserindo em sessão o booking que iremos trabalhar. BookingResponse booking = await bookingBusiness.ReatriveBooking("G7VIVI"); ///Para facilitar o desenvolvimento, estamos sempre usando a chave do primeiro seguinto, da primeira jornada. List <SeatMapResponse> seatMapResponseList = await seatBusiness.GetSeatMapAvailabilityBySegmentKey(booking.Journeys[0].Segments[0].SegmentKey); ///Caso o tenhamos assento para o primeiro segmento, realizamos a remoção, assim prosseguindo com o fluxo de marcação. if (seatBusiness.ThereIsSeatReservedFirstPassenger(booking)) { Seat seat = booking.Journeys[0]?.Segments[0]?.PassengersSegment[0].Value?.Seats[0]; await seatBusiness.UnassignPassengerSegmentSeat(seat.PassengerKey, seat.UnitKey); } ///Função retorna os assentos disponíveis, usando como base os atributos Type e Assignable, do objeto unit. ///O objeto unit representa uma unidade de espaço dentro a aeronave, ou seja posso ter unit, que representam ///espaços em brancos ou por exemplo o banheiro de uma determinada aeronave. ///Para trazermos apenas unidades que representam assento, estamos verificando sei o campo Type, ///está sendo preenchido com o valor “NormalSeat”. Alem de verificar se o valor do objeto Assignable está como true, ///indicando que o assento está disponível para marcação. ///Outro filtro que tive que incluir, pois a Navitaire estava me levantando erro é quando o assento está disponível para marcação, ///porém ele está em espera, por esse motivo, colocamos um filtro no campo Availability, trazendo apenas assentos com o valor ///deste campo igual a open (disponível). List <Unit> units = seatBusiness.GetAvailabilitySeat(seatMapResponseList); ///Está função realiza a marcação de assento, usando como base o booking em sessão, a key do passageiro informado e a ///key do assento que será atrelado ao usuário.Caso o assento tenha valor a pagar será incluído uma fee(taxa) referente ///ao valor do assento. await seatBusiness.AssingnmentSeat(booking.Passengers[0].Key, units[0].UnitKey); ///Está função é responsavel por salvar as alterações feitas no booking em sessão. ///Ela tem como o booking, porém estou apenas retornando informações referente ao valor pago, valor a pagar. BookingCommitResponse bookingCommitResult = await bookingBusiness.CommitBooking(); }
private static string RenderSMSTemplate(BookingBusiness _business, BookingAppointment appointment, string _appointmentDateString, SMSTemplate sMSTemplate) { string smsTemplateBody = ConfigurationManager.AppSettings[sMSTemplate.ToString()]; // String.Format(, appointment.ServiceName, _appointmentDateString); string messageFooter = ConfigurationManager.AppSettings["SMSFooter"]; string message = (smsTemplateBody + messageFooter); message = message.Replace("%BookingAppointment.CustomerName%", appointment.CustomerName); message = message.Replace("%BookingAppointment.CustomerEmailAddress%", appointment.CustomerEmailAddress); message = message.Replace("%BookingAppointment.CustomerPhone%", appointment.CustomerPhone); message = message.Replace("%BookingAppointment.ServiceName%", appointment.ServiceName.ToLower()); message = message.Replace("%BookingAppointment.Start%", System.DateTime.Parse(appointment.Start.DateTime).ToLocalTime().ToString("dd.MM.yyyy HH:mm")); message = message.Replace("%BookingAppointment.End%", System.DateTime.Parse(appointment.End.DateTime).ToLocalTime().ToString("dd.MM.yyyy HH:mm")); message = message.Replace("%BookingAppointment.Duration%", appointment.Duration.Minutes.ToString()); message = message.Replace("%BookingAppointment.ServiceLocation.DisplayName%", appointment.ServiceLocation.DisplayName); message = message.Replace("%BookingAppointment.ServiceLocation.LocationEmailAddress%", appointment.ServiceLocation.LocationEmailAddress); message = message.Replace("%BookingAppointment.ServiceLocation.Address.Street%", appointment.ServiceLocation.Address.Street ?? ""); message = message.Replace("%BookingAppointment.ServiceLocation.Address.City%", appointment.ServiceLocation.Address.City ?? ""); message = message.Replace("%BookingAppointment.ServiceLocation.Address.State%", appointment.ServiceLocation.Address.State ?? ""); message = message.Replace("%BookingAppointment.ServiceLocation.Address.CountryOrRegion%", appointment.ServiceLocation.Address.CountryOrRegion ?? ""); message = message.Replace("%BookingAppointment.ServiceLocation.Address.PostalCode%", appointment.ServiceLocation.Address.PostalCode ?? ""); message = message.Replace("%BookingAppointment.ServiceLocation.Coordinates.Altitude%", appointment.ServiceLocation.Coordinates.Altitude.ToString() ?? ""); message = message.Replace("%BookingAppointment.ServiceLocation.Coordinates.Latitude%", appointment.ServiceLocation.Coordinates.Latitude.ToString() ?? ""); message = message.Replace("%BookingAppointment.ServiceLocation.Coordinates.Longitude%", appointment.ServiceLocation.Coordinates.Longitude.ToString() ?? ""); message = message.Replace("%BookingAppointment.ServiceLocation.Coordinates.Accuracy%", appointment.ServiceLocation.Coordinates.Accuracy.ToString() ?? ""); message = message.Replace("%BookingAppointment.ServiceLocation.Coordinates.AltitudeAccuracy%", appointment.ServiceLocation.Coordinates.AltitudeAccuracy.ToString() ?? ""); message = message.Replace("%BookingBusiness.Address.City%", _business.Address.City); message = message.Replace("%BookingBusiness.Address.Street%", _business.Address.Street); message = message.Replace("%BookingBusiness.Address.PostalCode%", _business.Address.PostalCode); message = message.Replace("%BookingBusiness.Address.State%", _business.Address.State); message = message.Replace("%BookingBusiness.Address.CountryOrRegion%", _business.Address.CountryOrRegion); message = message.Replace("%BookingBusiness.DisplayName%", _business.DisplayName); message = message.Replace("%BookingBusiness.Email%", _business.Email); message = message.Replace("%BookingBusiness.Phone%", _business.Phone); message = message.Replace("%BookingBusiness.PublicUrl%", _business.PublicUrl); message = message.Replace("%BookingBusiness.WebSiteUrl%", _business.WebSiteUrl); message = message.Replace("\\n", Environment.NewLine); return(message); }
public BookingQuery() { Field <NonNullGraphType <ListGraphType <NonNullGraphType <BookingType> > > >( _List, "Trả về một danh sách các đơn đặt phòng", resolve: _CheckPermission_List( p => p.PermissionManageRentingRoom, context => BookingBusiness.Get() ) ); Field <NonNullGraphType <BookingType> >( _Item, "Trả về thông tin một đơn đặt phòng", _IdArgument(), _CheckPermission_Object( p => p.PermissionManageRentingRoom, context => BookingBusiness.Get(_GetId <int>(context)) ) ); }
public void Mutation_UpdateServicesDetail_InvalidService_InActive() { Database.WriteAsync(realm => { realm.Add(new Service { Id = 202, IsActive = false, Name = "Tên dịch vụ", Unit = "Đơn vị" }); realm.Add(new ServicesDetail { Id = 21, Booking = BookingBusiness.Get(1), Service = ServiceBusiness.Get(1), Number = 10 }); }).Wait(); SchemaHelper.ExecuteAndExpectError( "Dịch vụ 202 đã ngừng cung cấp", @"/_GraphQL/ServicesDetail/mutation.updateServicesDetail.gql", new { input = new { id = 21, number = 2, service = new { id = 202 } } }, p => p.PermissionCleaning = true ); }
public static void Main() { callGraphServiceTimer.Start(); callGraphServiceTimer.Elapsed += (sender, e) => HandleTimer(sender, e); ViaNettSMS viaNettSMS = new ViaNettSMS(_SMSServiceUserName, _SMSServicePassword); try { // ADAL: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-authentication-libraries authenticationContext = new AuthenticationContext(GraphService.DefaultAadInstance, TokenCache.DefaultShared); authenticationResult = authenticationContext.AcquireTokenAsync( GraphService.ResourceId, _ApplicationAppId, _ApplicationRedirectUri, new PlatformParameters(PromptBehavior.RefreshSession)).Result; } catch (Exception e) { Console.WriteLine(e); } // This BookingsContainer is generated by the ODATA v4 Client Code Generator // See https://odata.github.io and https://github.com/odata/odata.net for usage. // Note that the code generator customizes the entity and property names to PascalCase // so they match C# guidelines, while the EDM uses lower case camelCase, as per Graph guidelies. // Since the application is short lived, the delegate is simply returning the authorization // header obtained above; a long lived application would likely need to refresh the token // when it expires, so it would have a slightly more complex delegate. var graphService = new GraphService( GraphService.DefaultV1ServiceRoot, () => { // Hvis Token timedout // Forny Token if (authenticationResult.ExpiresOn.ToLocalTime() >= DateTime.Now) { //refresh // Har mulighet til å refreshe i 5 minutter etter token har utgått authenticationResult = authenticationContext.AcquireTokenSilentAsync(GraphService.ResourceId, _ApplicationAppId).Result; string _header = authenticationResult.CreateAuthorizationHeader(); return(_header); } else { string _header = authenticationResult.CreateAuthorizationHeader(); return(_header); } }); // Fiddler makes it easy to look at the request/response payloads. Use it automatically if it is running. // https://www.telerik.com/download/fiddler if (System.Diagnostics.Process.GetProcessesByName("fiddler").Any()) { graphService.WebProxy = new WebProxy(new Uri("http://*****:*****@"[^\d+]", ""), customerNotes = oDataAppointment.CustomerNotes, Id = oDataAppointment.Id, staffMemberIds = oDataAppointment.StaffMemberIds.FirstOrDefault(), Start = System.DateTime.Parse(oDataAppointment.Start.DateTime).ToLocalTime(), End = System.DateTime.Parse(oDataAppointment.End.DateTime).ToLocalTime(), serviceId = oDataAppointment.ServiceId, serviceName = oDataAppointment.ServiceName.ToLower(), json = JsonConvert.SerializeObject(oDataAppointment), md5 = Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(oDataAppointment.Id + oDataAppointment.Start.DateTime.ToString() + oDataAppointment.End.DateTime.ToString()))), md5hash = md5.ComputeHash(Encoding.Unicode.GetBytes(oDataAppointment.Id)) }; Debug.WriteLine(appointment.json); List <BookingAppointment> _list = new List <BookingAppointment> { oDataAppointment }; switch (InsertOrUpdate(appointment, db)) { case EntityState.Detached: break; case EntityState.Unchanged: break; case EntityState.Added: // Ny Avtale SendSMS(viaNettSMS, _business, _list, SMSTemplate.SMSConfirmation); break; case EntityState.Deleted: break; case EntityState.Modified: // Avtalen er endret SendSMS(viaNettSMS, _business, _list, SMSTemplate.SMSUpdate); break; default: break; } } //Create a list of Cancelled Appointments (Appointments in database not occuring from the graphservice.business.appointments ) List <byte[]> odataIDs; try { odataIDs = bookingAppointments.Select(x => md5.ComputeHash(Encoding.Unicode.GetBytes(x.Id))).ToList <byte[]>(); } catch (Exception e) { Console.WriteLine($"ExceptionCount: {exceptionCount} , exception: {e.InnerException.ToString()}"); exceptionCount++; continue; } /* * */ var deleteAppointments = from a in db.Appointment where !odataIDs.Contains(a.md5hash) && a.Start > DateTime.Now && a.appointmentIsActive == true select a; var bookingAppointmentList = new List <BookingAppointment>(); //Update database for every Cancelled appointment and create a list of those Appointments foreach (var appoint in deleteAppointments) { appoint.appointmentIsActive = false; appoint.appointmentChangedDate = DateTime.Now; var bappoint = JsonConvert.DeserializeObject <BookingAppointment>(appoint.json); bookingAppointmentList.Add(bappoint); } try { db.SaveChanges(); } catch (Exception e) { Console.WriteLine($"ExceptionCount: {exceptionCount} , exception: {e.InnerException.ToString()}"); exceptionCount++; continue; } /* Send SMS for every Cancelled Appointments in the AppointmentList*/ SendSMS(viaNettSMS, _business, bookingAppointmentList, SMSTemplate.SMSCancellation); // Send Reminder SMS DateTime rm1DateTimeMax = DateTime.Now.Add(SMSReminder1TimeSpanBefore); DateTime rm2DateTimeMax = DateTime.Now.Add(SMSReminder2TimeSpanBefore); //DateTime rm3DateTimeMax = DateTime.Now.Add(SMSReminder3TimeSpanBefore); DateTime rm1DateTimeMin = rm1DateTimeMax.AddHours(-2); DateTime rm2DateTimeMin = rm2DateTimeMax.AddHours(-2); //DateTime rm3DateTimeMin = rm3DateTimeMax.AddHours(-2); DateTime surveyDateTimeMin = DateTime.Now.Add(SMSSurveyTimeSpanBefore); // 7 Dager var reminder1Appointments = from a in db.Appointment where a.SMSLog.Where(s => s.smsTemplate == SMSTemplate.SMSReminder1.ToString() && s.smsIsSent == true).Count() < 1 && a.Start <rm1DateTimeMax && a.Start> rm1DateTimeMin && !(a.appointmentCreatedDate <rm1DateTimeMax && a.appointmentCreatedDate> rm1DateTimeMin) && !string.IsNullOrEmpty(a.customerId) && !string.IsNullOrEmpty(a.customerPhone) && a.appointmentIsActive == true select a; // 2 Dager var reminder2Appointments = from a in db.Appointment where a.SMSLog.Where(s => s.smsTemplate == SMSTemplate.SMSReminder2.ToString() && s.smsIsSent == true).Count() < 1 && a.Start <rm2DateTimeMax && a.Start> rm2DateTimeMin && !(a.appointmentCreatedDate <rm2DateTimeMax && a.appointmentCreatedDate> rm2DateTimeMin) && !string.IsNullOrEmpty(a.customerId) && !string.IsNullOrEmpty(a.customerPhone) && a.appointmentIsActive == true select a; //// 1 Dag //var reminder3Appointments = from a in db.Appointment // where a.SMSLog.Where(s => s.smsTemplate == SMSTemplate.SMSReminder3.ToString() && s.smsIsSent == true).Count() < 1 // && a.Start < rm3DateTimeMax // && a.Start > rm3DateTimeMin // && !(a.appointmentCreatedDate < rm3DateTimeMax && a.appointmentCreatedDate > rm3DateTimeMin) // select a; var surveyAppointments = from a in db.Appointment where a.SMSLog.Where(s => s.smsTemplate == SMSTemplate.SMSSurvey.ToString() && s.smsIsSent == true).Count() < 1 && a.Start < surveyDateTimeMin && !string.IsNullOrEmpty(a.customerId) && !string.IsNullOrEmpty(a.customerPhone) && a.appointmentIsActive == true select a; List <BookingAppointment> reminder1List = new List <BookingAppointment>(); List <BookingAppointment> reminder2List = new List <BookingAppointment>(); List <BookingAppointment> surveyList = new List <BookingAppointment>(); //List<BookingAppointment> reminder3List = new List<BookingAppointment>(); foreach (var item in reminder1Appointments) { reminder1List.Add( new BookingAppointment { Id = item.Id , CustomerName = item.customerName , CustomerPhone = item.customerPhone , ServiceName = item.serviceName , Start = new DateTimeTimeZone { DateTime = DateTime.Parse(item.Start.ToString()).ToUniversalTime().ToString("o"), TimeZone = "UTC" } , CustomerEmailAddress = item.customerEmailAddress , End = new DateTimeTimeZone { DateTime = DateTime.Parse(item.End.ToString()).ToUniversalTime().ToString("o"), TimeZone = "UTC" } , Duration = new TimeSpan(1, 0, 0) , ServiceLocation = new Location { Address = new PhysicalAddress() , Coordinates = new OutlookGeoCoordinates() } } ); } foreach (var item in reminder2Appointments) { reminder2List.Add( new BookingAppointment { Id = item.Id , CustomerName = item.customerName , CustomerPhone = item.customerPhone , ServiceName = item.serviceName , Start = new DateTimeTimeZone { DateTime = DateTime.Parse(item.Start.ToString()).ToUniversalTime().ToString("o"), TimeZone = "UTC" } , CustomerEmailAddress = item.customerEmailAddress , End = new DateTimeTimeZone { DateTime = DateTime.Parse(item.End.ToString()).ToUniversalTime().ToString("o"), TimeZone = "UTC" } , Duration = new TimeSpan(1, 0, 0) , ServiceLocation = new Location { Address = new PhysicalAddress() , Coordinates = new OutlookGeoCoordinates() } } ); } foreach (var item in surveyAppointments) { surveyList.Add( new BookingAppointment { Id = item.Id , CustomerName = item.customerName , CustomerPhone = item.customerPhone , ServiceName = item.serviceName , Start = new DateTimeTimeZone { DateTime = DateTime.Parse(item.Start.ToString()).ToUniversalTime().ToString("o"), TimeZone = "UTC" } , CustomerEmailAddress = item.customerEmailAddress , End = new DateTimeTimeZone { DateTime = DateTime.Parse(item.End.ToString()).ToUniversalTime().ToString("o"), TimeZone = "UTC" } , Duration = new TimeSpan(1, 0, 0) , ServiceLocation = new Location { Address = new PhysicalAddress() , Coordinates = new OutlookGeoCoordinates() } } ); } //foreach (var item in reminder3Appointments) //{ // reminder3List.Add( // new BookingAppointment { // Id = item.Id // ,CustomerName = item.customerName // ,CustomerPhone = item.customerPhone // ,ServiceName = item.serviceName // ,Start = new DateTimeTimeZone { DateTime = DateTime.Parse(item.Start.ToString()).ToUniversalTime().ToString("o"), TimeZone = "UTC" } // ,CustomerEmailAddress = item.customerEmailAddress // ,End = new DateTimeTimeZone { DateTime = DateTime.Parse(item.End.ToString()).ToUniversalTime().ToString("o"), TimeZone = "UTC" } // ,Duration = new TimeSpan(1,0,0) // ,ServiceLocation = new Location { // Address = new PhysicalAddress() // ,Coordinates = new OutlookGeoCoordinates() // } // } // ); //} SendSMS(viaNettSMS, _business, reminder1List, SMSTemplate.SMSReminder1); SendSMS(viaNettSMS, _business, reminder2List, SMSTemplate.SMSReminder2); SendSMS(viaNettSMS, _business, surveyList, SMSTemplate.SMSSurvey); //SendSMS(viaNettSMS, _business, reminder3List, SMSTemplate.SMSReminder3); } System.Threading.Thread.Sleep(60000); } // End While }
private static void SendSMS(ViaNettSMS viaNettSMS, BookingBusiness _business, IEnumerable <BookingAppointment> _appointments, SMSTemplate sMSTemplate) { MD5 md5 = MD5.Create(); foreach (BookingAppointment appointment in _appointments) { // Send SMS to Customer Console.WriteLine("Sending SMS to CustomerName: {0}, CustomerPhone: {1}", appointment.CustomerName, appointment.CustomerPhone); ViaNettSMS.Result result; string _appointmentDateString = DateTime.Parse(appointment.Start.DateTime).ToString("dd.MM.yyyy HH:mm"); string message = RenderSMSTemplate(_business, appointment, _appointmentDateString, sMSTemplate); try { // Send SMS through HTTP API Console.WriteLine("{0} SendingSMS: {1} {2} {3}", Date.Now.ToString(), _SMSSenderFrom, appointment.CustomerPhone, message); result = viaNettSMS.SendSMS(_SMSSenderFrom, appointment.CustomerPhone, message); //result = viaNettSMS.SendSMS(_SMSSenderFrom, "40453626", message); // Show Send SMS response if (result.Success) { Debug.WriteLine("Message successfully sent"); using (BookingEntities context = new BookingEntities()) { context.SMSLog.Add(new SMSLog { appointmentId = appointment.Id , message = message , recipientPhone = appointment.CustomerPhone , sentDate = DateTime.Now , smsIsSent = true , sentResult = "OK" , smsTemplate = sMSTemplate.ToString() , md5hash = md5.ComputeHash(Encoding.Unicode.GetBytes(appointment.Id)) }); context.SaveChanges(); } } else { using (BookingEntities context = new BookingEntities()) { context.SMSLog.Add(new SMSLog { appointmentId = appointment.Id , message = message , recipientPhone = appointment.CustomerPhone , sentDate = DateTime.Now , smsIsSent = false , sentResult = $"Received error: {result.ErrorCode} {result.ErrorMessage}" , smsTemplate = sMSTemplate.ToString() , md5hash = md5.ComputeHash(Encoding.Unicode.GetBytes(appointment.Id)) }); context.SaveChanges(); } Debug.WriteLine($"Received error: {result.ErrorCode} {result.ErrorMessage}"); } } catch (System.Net.WebException ex) { //Catch error occurred while connecting to server. Debug.WriteLine(ex.Message); } } md5.Dispose(); }
protected void btnBookingSpot_Click(object sender, EventArgs e) { Booking newBooking = new Booking(); BookingBusiness bookingBusiness = new BookingBusiness(); ParkingBusiness parkingBusiness = new ParkingBusiness(); User currentUser = (User)Session["USER"]; Vehicle bookingVehicle = new Vehicle(); ParkingSpot bookingSpot = new ParkingSpot(); ParkingLot bookingParking = new ParkingLot(); bookingSpot.IdParking = Int32.Parse(DropDownListParking.SelectedValue); bookingSpot = parkingBusiness.GetSpotForReserve(bookingSpot, (int)Session["Position"]); newBooking.IdVehicle = bookingVehicle; bookingParking.Name = DropDownListParking.SelectedItem.Text; newBooking.IdUser = currentUser; newBooking.IdParkingSpot = bookingSpot; newBooking.IdParkingLot = bookingParking; newBooking.EntryTime = DateTime.Parse(DropDownListInitialHour.SelectedValue); newBooking.ExitTime = DateTime.Parse(DropDownListFinalHour.SelectedValue); newBooking.IdVehicle.Id = DropDownListVehicleFormUser.SelectedValue.Trim(); newBooking.Date = DateTime.Today; newBooking.IdParkingSpot.Id = bookingSpot.Id; newBooking.IdParkingLot.Id = Int32.Parse(DropDownListParking.SelectedValue); if (bookingSpot.Id == 0) { } else { bookingBusiness.InsertBooking(newBooking); Session["BOOKING"] = newBooking; bookingParking = parkingBusiness.GetDimensions(bookingParking); selectedPosition = -1; bookingParking = removeSelected(Int32.Parse(DropDownListParking.SelectedValue)); Session["BOOKINGALERT"] = SendMail(newBooking); TableDesignOfNewParking = bookingBusiness.VerifySpots(bookingParking, TableDesignOfNewParking, DateTime.Parse(DropDownListInitialHour.SelectedValue), DateTime.Parse(DropDownListFinalHour.SelectedValue)); Response.Redirect("bookingdone.aspx"); } }
public BookingServices(IRepository <Booking> boockingrepository, BookingBusiness boockingstore) { _bookingrepository = boockingrepository; _bookingstore = boockingstore; }
public BookingMutation() { Field <NonNullGraphType <BookingType> >( "CheckIn", "Cập nhật thời gian checkin của phòng", _IdArgument(), _CheckPermission_TaskObject( p => p.PermissionManageRentingRoom, context => { var employee = AuthenticationHelper.GetEmployee(context); return(BookingBusiness.CheckIn(employee, _GetId <int>(context))); } ) ); Field <NonNullGraphType <BookingType> >( "RequestCheckOut", "Yêu cầu kiểm tra khi trả phòng", _IdArgument(), _CheckPermission_TaskObject( p => p.PermissionManageRentingRoom, context => { var employee = AuthenticationHelper.GetEmployee(context); return(BookingBusiness.RequestCheckOut(employee, _GetId <int>(context))); } ) ); Field <NonNullGraphType <BookingType> >( "CheckOut", "Thực hiện xác nhận trả phòng", _IdArgument(), _CheckPermission_TaskObject( p => p.PermissionManageRentingRoom, context => { var employee = AuthenticationHelper.GetEmployee(context); return(BookingBusiness.CheckOut(employee, _GetId <int>(context))); } ) ); Field <NonNullGraphType <StringGraphType> >( "Cancel", "Hủy đặt phòng", _IdArgument(), _CheckPermission_String( p => p.PermissionManageRentingRoom, context => { BookingBusiness.Cancel(_GetId <int>(context)); return("Hủy thành công"); } ) ); Field <NonNullGraphType <BookingType> >( "AddBookingToBill", "Thêm phòng khách đoàn", new QueryArguments( new QueryArgument <NonNullGraphType <BillIdInput> > { Name = "bill" }, new QueryArgument <NonNullGraphType <BookingCreateInput> > { Name = "booking" } ), _CheckPermission_TaskObject( p => p.PermissionManageRentingRoom, context => { var employee = AuthenticationHelper.GetEmployee(context); var bill = context.GetArgument <Bill>("bill"); var booking = context.GetArgument <Booking>("booking"); return(BookingBusiness.Add(employee, bill, booking)); } ) ); }
protected void btnDeleteReserve_Click(object sender, EventArgs e) { Booking newBooking = new Booking(); BookingBusiness bookingBusiness = new BookingBusiness(); ParkingBusiness parkingBusiness = new ParkingBusiness(); User currentUser = (User)Session["USER"]; Vehicle bookingVehicle = new Vehicle(); ParkingSpot bookingSpot = new ParkingSpot(); ParkingLot bookingParking = new ParkingLot(); bookingSpot.IdParking = Int32.Parse(DropDownListParking.SelectedValue); bookingSpot = parkingBusiness.GetSpotForReserve(bookingSpot, (int)Session["Position"]); newBooking.IdVehicle = bookingVehicle; newBooking.IdUser = currentUser; newBooking.IdParkingSpot = bookingSpot; newBooking.IdParkingLot = bookingParking; newBooking.EntryTime = DateTime.Parse(DropDownListInitialHour.SelectedValue); newBooking.ExitTime = DateTime.Parse(DropDownListFinalHour.SelectedValue); newBooking.IdVehicle.Id = DropDownListVehicleFormUser.SelectedValue.Trim(); newBooking.Date = DateTime.Today; newBooking.IdParkingSpot.Id = bookingSpot.Id; newBooking.IdParkingLot.Id = Int32.Parse(DropDownListParking.SelectedValue); if (bookingSpot.Id == 0) { //Return error here } else { bookingBusiness.DenyBooking(newBooking, newBooking.EntryTime, newBooking.ExitTime); bookingParking = parkingBusiness.GetDimensions(bookingParking); selectedPosition = -1; bookingParking = removeSelected(Int32.Parse(DropDownListParking.SelectedValue)); FillTableDesignOfNewParking(newBooking.IdParkingLot.Id); } }
public void FillTableDesignOfNewParking(int parkingName) { TableDesignOfNewParking.Rows.Clear(); ParkingBusiness parkingBusiness = new ParkingBusiness(); BookingBusiness bookingBusiness = new BookingBusiness(); ParkingLot parkingspotTable = new ParkingLot(); ParkingSpot parking = new ParkingSpot(); int counter = 0; parkingspotTable.Id = parkingName; parkingspotTable = parkingBusiness.GetDimensions(parkingspotTable); TableDesignOfNewParking = parkingBusiness.GetSpotData(parkingspotTable, TableDesignOfNewParking); for (int counterRow = 0; counterRow < parkingspotTable.DimensionX; counterRow++) { for (int counterColumn = 0; counterColumn < parkingspotTable.DimensionY; counterColumn++) { TableDesignOfNewParking.Rows[counterRow].Cells[counterColumn].Controls.Add(addButton(counter)); counter++; } } TableDesignOfNewParking = bookingBusiness.VerifySpots(parkingspotTable, TableDesignOfNewParking, DateTime.Parse(DropDownListInitialHour.SelectedValue), DateTime.Parse(DropDownListFinalHour.SelectedValue)); for (int counterRow = 0; counterRow < parkingspotTable.DimensionX; counterRow++) { for (int counterColumn = 0; counterColumn < parkingspotTable.DimensionY; counterColumn++) { if (TableDesignOfNewParking.Rows[counterRow].Cells[counterColumn].BackColor == Color.Red) { TableDesignOfNewParking.Rows[counterRow].Cells[counterColumn].Enabled = true; } else { TableDesignOfNewParking.Rows[counterRow].Cells[counterColumn].Enabled = false; } } } }