/// <summary> /// Creates just the rates for a particular variant rate plan /// </summary> /// <param name="ratePlan">Rate plan</param> /// <returns>created rate plan with rates</returns> public VariantRatePlan CreateVariantRatePlanRate(VariantRatePlan ratePlan) { if (ratePlan == null) { return null; } using (var tx = new BusinessTransaction()) { variantRatePlanDao.CreateVariantRatePlanRate(ratePlan); tx.Commit(); } eventTrackingManager.CreateBusinessEventAsync(ratePlan.BusinessId, BusinessEventTypesEnum.VariantRatePlanRateAdded, ratePlan.VariantRatePlanRateId.ToString(CultureInfo.InvariantCulture)); return ratePlan; }
/// <summary> /// Links a business to a user /// </summary> /// <param name="userId">User Id</param> /// <param name="businessId">Business Id</param> /// <returns>True if link was successful</returns> public bool AddBusinessToUser(Guid userId, long businessId) { using (var tx = new BusinessTransaction()) { userBusinessDao.AddBusinessToUser(userId, businessId); // Set primary business id if first UserExtension userExtension = userExtensionDao.GetByKey(userId); if (userExtension.PrimaryBusinessId == null) { userExtension.PrimaryBusinessId = businessId; userExtensionDao.Modify(userExtension); } RecordUserEvent(userId, UserEventTypesEnum.BusinessLinkAdded, null, businessId.ToString(CultureInfo.InvariantCulture)); tx.Commit(); } return true; }
/// <summary> /// Modify User /// </summary> /// <param name="user">User</param> public void Modify(Model.User.User user) { if (!user.IsValid()) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30051, "UserManager.Modify")); } using (var btx = new BusinessTransaction()) { userDao.Modify(user); // Update UserExtension userExtensionDao.Modify(user.Extension); //make sure to update the membership with the new user name used var membershipUser = Membership.GetUser(user.Id); if (membershipUser != null) { membershipUser.Email = user.UserName; Membership.UpdateUser(membershipUser); } RecordUserEvent(user.UserName, UserEventTypesEnum.UserModified); btx.Commit(); } }
/// <summary> /// Create a period /// Assumes that if period id is filled in then it is adding a date range /// Otherwise creates full new period /// </summary> /// <param name="period">Period to create</param> /// <param name="cultureCode">culture for translation</param> /// <returns>Period with id filled in</returns> public Period CreatePeriod(Period period, string cultureCode) { ValidatePeriod(period, cultureCode, true); // check for duplicate name only when creating new period if (period.Id == default(int) && periodDao.DoesPeriodNameAlreadyExist(period.BusinessId, period.Name)) { // set error code period.PricingPeriodError = PricingPeriodError.DuplicateName; return period; } // check for any overlaps if (DoDateRangesOverlap(period)) { return period; } string reference = string.Empty; bool isModify = false; using (var bex = new BusinessTransaction()) { //First check if period has an ID, that determines logic for rest of method if (period.Id <= default(int)) { //get the next colour to use for the create period.PeriodColor = periodColorDao.GetNextPeriodColorForPeriodType(period.BusinessId, period.PeriodType.PeriodTypeEnum, cultureCode); period.PeriodColorId = period.PeriodColor.Id; //create of period using the next colour for the type periodDao.Create(period, cultureCode); } else { // it is modify isModify = true; } if (period.PeriodColor == null || period.PeriodColorId == default(int) || period.PeriodColor.Id == default(int)) { //Fetch the colour for the period that exists period.PeriodColor = periodColorDao.GetByPeriodId(period.Id, cultureCode); period.PeriodColorId = period.PeriodColor.Id; } // add date range to it since period and colour should be good now foreach (PeriodDateRange periodDateRange in period.PeriodDateRanges) { // Only create new date ranges for periods that exist in the db if (periodDateRange.PeriodId == default(int) || periodDateRange.Id == default(int)) { periodDateRange.PeriodId = period.Id; periodDateRangeDao.Create(periodDateRange); // add to reference string reference = reference + periodDateRange.StartDate.ToString(StandardDateTimeFormatProvider.GetShortDBFormat()) + ","; reference = reference + periodDateRange.EndDate.ToString(StandardDateTimeFormatProvider.GetShortDBFormat()) + ","; } } bex.Commit(); } BusinessEventTypesEnum businessEvent = GetBusinessEventForPeriodType(period.PeriodType.PeriodTypeEnum, isCreate: !isModify, isEdit: isModify); // event for creation of period / date range here eventTrackingManager.CreateBusinessEventAsync(period.BusinessId, businessEvent, reference.TrimEnd(',')); return period; }
/// <summary> /// Delete a period date range, if no date ranges after, delete the period /// </summary> /// <param name="businessId">business to delete period from</param> /// <param name="periodType">type of period being deleted</param> /// <param name="periodId">period to potentially delete</param> /// <param name="periodDateRangeId">date range id to delete</param> public void DeletePeriod(long businessId, PeriodTypeEnum periodType, int periodId, int periodDateRangeId) { // Add tracked event for date range removal BusinessEventTypesEnum businessEventType = GetBusinessEventForPeriodType(periodType, isDelete: true); PeriodDateRange pdrDeleted = null; string reference = string.Empty; using (var bex = new BusinessTransaction()) { // Actual delete time List<PeriodDateRange> dateRangesLeft = periodDateRangeDao.GetAllByPeriodId(periodId); if (dateRangesLeft.Any(d => d.Id == periodDateRangeId)) { pdrDeleted = dateRangesLeft.First(d => d.Id == periodDateRangeId); } periodDateRangeDao.Remove(periodDateRangeId); if (dateRangesLeft == null || dateRangesLeft.Count == 1) // last one deleted { // this is where rates are killed since period is actually killed // Delete all rates associated with the period variantRatePlanDao.DeleteRatePlanRatesAssociatedWithPeriod(periodId); // Delete the period when no date ranges left periodDao.Remove(periodId); } bex.Commit(); } if (pdrDeleted != null) { reference = reference + pdrDeleted.StartDate.ToString(StandardDateTimeFormatProvider.GetShortDBFormat()) + ","; reference = reference + pdrDeleted.EndDate.ToString(StandardDateTimeFormatProvider.GetShortDBFormat()) + ","; } // event for modify of period / date range here eventTrackingManager.CreateBusinessEventAsync(businessId, businessEventType, reference.TrimEnd(',')); }
/// <summary> /// Opt in to a channel /// </summary> /// <param name="businessChannelOptIn">The businessChannelOptIn object to create</param> /// <param name="cultureCode">The culture code used for translations</param> public void OptInToChannel(BusinessChannelOptIn businessChannelOptIn, string cultureCode ) { var prePaySettings = new BusinessChannelPrePaySettings(); Channel logicalGroup = null; using (var tx = new BusinessTransaction()) { if (businessChannelOptIn.IsValid()) { businessChannelOptIn.ChannelOptInStatus = new ChannelOptInStatus { Code = ChannelOptInStatusEnum.Live.GetCode() }; businessChannelOptIn.OptInDatetime = DateTime.UtcNow; businessChannelOptInDao.Create(businessChannelOptIn); // Record business event eventTrackingManager.CreateBusinessEventAsync(businessChannelOptIn.BusinessId.Value, BusinessEventTypesEnum.ChannelOptIn, businessChannelOptIn.ChannelId.ToString()); logicalGroup = channelDao.GetFirstLogicalGroupChannelByChannelId(businessChannelOptIn.ChannelId.Value); if (logicalGroup == null) { var channel = channelDao.GetById(businessChannelOptIn.ChannelId.Value); var business = businessDao.GetByKey(businessChannelOptIn.BusinessId.Value); var permittedSettings = prePayDao.GetPermittedChannelSettings(businessChannelOptIn.BusinessId.Value, businessChannelOptIn.ChannelId.Value); channel.FullPrePaySettings = new ChannelPrePaySettings { PermittedSettings = permittedSettings }; // if the channel isnt flexible use the channel defaults otherwise use the business defaults if (!channel.FullPrePaySettings.Flexible) { if (channel.DefaultPrePayType.HasValue && channel.DefaultPrePayValue.HasValue) { prePaySettings.Type = channel.DefaultPrePayType.Value; prePaySettings.Value = channel.DefaultPrePayValue.Value; prePaySettings.IsOverridden = false; } } else { if (business.PrePayRuleValue.HasValue) { prePaySettings.Type = business.PrePayRuleType; prePaySettings.Value = business.PrePayRuleValue.Value; prePaySettings.IsOverridden = false; } } businessChannelOptIn.PrePaySettings = prePaySettings; // Update pre pay settings on Opt In UpdatePrePayForOptedInChannel(businessChannelOptIn, permittedSettings); } tx.Commit(); } } // update logical group channel to opt into if needed if (businessChannelOptIn.IsValid() && logicalGroup != null) { // if not already opted in, opt the logical group channel in if (businessChannelOptInDao.IsChannelOptedInForBusiness(businessChannelOptIn.BusinessId.Value, logicalGroup.Id) == false) { BusinessChannelOptIn bco = new BusinessChannelOptIn { BusinessId = businessChannelOptIn.BusinessId.Value, ChannelId = logicalGroup.Id, ChannelTermsId = logicalGroup.ChannelTermsId ?? businessChannelOptIn.ChannelTermsId.Value, PrePaySettings = prePaySettings }; OptInToChannel(bco, cultureCode); } // in all cases, update this channel with info from logical group // need to update cancel / ppy info here based on logical group settings UpdateGroupChannelsWithCancelPrepaySettings(logicalGroup, businessChannelOptIn, cultureCode); } }
/// <summary> /// Create business channel override /// </summary> /// <param name="modifyVisible">modifyVisible</param> /// <param name="modifyCommissions">modifyCommissions</param> /// <param name="businessChannelOverride">businessChannelOverride to create</param> public void CreateBusinessChannelOverride(BusinessChannelOverride businessChannelOverride, bool modifyVisible, bool modifyCommissions) { using (var tx = new BusinessTransaction()) { //Values needed for the previous BCO var channel = channelDao.GetById(businessChannelOverride.ChannelId); var business = businessDao.GetByKey(businessChannelOverride.BusinessId); var oldBusinessChannelOverride = new BusinessChannelOverride() { DisplayCommission = channel.CommissionDisplay, DistributorCommission = channel.DistributorCommission, EviivoCommission = channel.EviivoCommission, Business = business, Channel = channel }; SetOverrideValues(businessChannelOverride, modifyVisible, modifyCommissions, oldBusinessChannelOverride); //opted out if was opted in and now is not visible if (businessChannelOverride.IsVisible == false) { businessChannelOptInDao.RemoveByChannelAndBusiness(businessChannelOverride.BusinessId, businessChannelOverride.ChannelId); } businessChannelOverrideDao.Create(businessChannelOverride); UpsertCommissionDisplay(businessChannelOverride); // Record business events and sending mail if (!businessChannelOverride.HasSameVisibility(oldBusinessChannelOverride)) { eventTrackingManager.CreateBusinessEventAsync(businessChannelOverride.BusinessId, BusinessEventTypesEnum.ChannelSettingUpdated, businessChannelOverride.ChannelId.ToString(), String.Format("{0}: Set channel to {1}", channel.Name, businessChannelOverride.IsVisible == true ? "visible" : "hidden")); } if (businessChannelOverride.DistributorCommission != null || businessChannelOverride.EviivoCommission != null || businessChannelOverride.DisplayCommission != null) { eventTrackingManager.CreateBusinessEventAsync(businessChannelOverride.BusinessId, BusinessEventTypesEnum.ChannelSettingUpdated, businessChannelOverride.ChannelId.ToString(), String.Format("{0}: Edit Business Commission", channel.Name)); emailManager.SendCommissionUpdateEmail(businessChannelOverride, oldBusinessChannelOverride); } tx.Commit(); } }
/// <summary> /// Delete Room /// </summary> /// <param name="id">Room Id</param> /// <param name="businessId">Business Id</param> public void Delete(int id, long businessId) { if (id == default(int) || businessId == default (long)) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30075, "Room.Delete", arguments: new object[] { this })); } var bookings = bookingManager.GetByRoom(id).AsQueryable().Where(b => b.StartDate >= DateTime.UtcNow || b.EndDate >= DateTime.UtcNow); // If any were found throw validation exception if (bookings.Any()) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30097, "RoomManager.Delete", arguments: new object[] { this })); } using (var businessTransaction = new BusinessTransaction()) { roomDao.Delete(id); businessTransaction.Commit(); } eventTrackingManager.CreateBusinessEventAsync(businessId, BusinessEventTypesEnum.RoomDeleted, id.ToString(CultureInfo.InvariantCulture)); }
/// <summary> /// Create Room with the name, type id and business id /// </summary> /// <param name="roomName">Room Name</param> /// <param name="roomTypeId">Room Type Id</param> /// <param name="businessId">Business Id</param> /// <returns>Room</returns> public int CreateRoom(string roomName, int roomTypeId, long businessId) { if (string.IsNullOrEmpty(roomName)) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30086, "RoomManager.CreateRoom", additionalDescriptionParameters: (new object[] { businessId }))); } Model.Room.Room existingRoom = roomDao.GetByName(roomName, businessId); if (existingRoom != null) { // check status, if in delete status just modify to active state if (existingRoom.RoomStatusCode == RoomStatusCodes.DELETED) { existingRoom.RoomTypeId = roomTypeId; existingRoom.RoomStatusCode = RoomStatusCodes.ACTIVE; Modify(existingRoom); return existingRoom.Id; } // Otherwise throw validation exception throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30085, "RoomManager.CreateRoom", additionalDescriptionParameters: (new object[] { businessId }))); } int displayOrder = roomDao.GetNextDisplayOrder(businessId); int sellingPriority = roomDao.GetNextSellingPriority(businessId); var room = new Model.Room.Room { Name = roomName, BusinessId = businessId, IsAvailableOnline = true, IsCombined = false, RoomStatusCode = RoomStatusCodes.ACTIVE, RoomTypeId = roomTypeId, SellingPriority = sellingPriority, DisplayOrder = displayOrder, }; using (var businessTransaction = new BusinessTransaction()) { roomDao.Create(room); businessTransaction.Commit(); } eventTrackingManager.CreateBusinessEventAsync(businessId, BusinessEventTypesEnum.RoomAdded, room.Id.ToString()); return room.Id; }
/// <summary> /// Delete variant rate plan by id /// </summary> /// <param name="id">Variant Rate Plan Id</param> /// <param name="businessId">Business Id</param> /// <returns>true if delete was successful</returns> public bool DeleteVariantRatePlan(int id, long businessId) { bool deleteResult; using (var tx = new BusinessTransaction()) { deleteResult = variantRatePlanDao.DeleteVariantRatePlan(id); tx.Commit(); } eventTrackingManager.CreateBusinessEventAsync(businessId, BusinessEventTypesEnum.VariantRatePlanDeleted, id.ToString(CultureInfo.InvariantCulture)); // Invalidate the cache so it refreshes Cache.Cache.RatePlanViewCache.Invalidate(businessId); return deleteResult; }
/// <summary> /// Delete the rate plan rates for the given roomtype /// Deletes base, variant, and occupant rates to give clean slate /// </summary> /// <remarks> /// Used with changing from per person to per night pricing /// </remarks> /// <param name="roomTypeId">room type id to affect</param> /// <param name="businessId">business for this action</param> public void DeleteRatePlanRates(long businessId, int roomTypeId) { using (var bt = new BusinessTransaction()) { // delete base, variant, and occupant rates ratePlanRateDao.DeleteBaseRatePlanRates(businessId, roomTypeId); variantRatePlanDao.DeleteVariantRatePlanRates(businessId, roomTypeId); ratePlanRateDao.DeleteBaseRatePlanOccupantRates(businessId, roomTypeId); bt.Commit(); } // one event for all the rate plan rates being cleared eventTrackingManager.CreateBusinessEventAsync(businessId, BusinessEventTypesEnum.RatePlanRatesCleared, roomTypeId.ToString()); }
/// <summary> /// Modify a particular variant rate plan /// </summary> /// <param name="ratePlan">Variant Rate plan</param> /// <returns>Modified rate plan</returns> public virtual VariantRatePlan ModifyVariantRatePlan(VariantRatePlan ratePlan) { if (ratePlan == null) { return null; } if (ratePlan.Id == default(int)) { // can't modify with bad id throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30098, "RoomTypeManager.ModifyVariantRatePlan", arguments: new object[] { ratePlan })); } using (var tx = new BusinessTransaction()) { variantRatePlanDao.Modify(ratePlan); //modify rate plan rates for rate plan here. ratePlan.Rates = ModifyRatePlanRates(ratePlan.Rates, false); tx.Commit(); } // events will need data in future eventTrackingManager.CreateBusinessEventAsync(ratePlan.BusinessId, BusinessEventTypesEnum.VariantRatePlanModified, ratePlan.Id.ToString(CultureInfo.InvariantCulture)); // Invalidate the cache so it refreshes Cache.Cache.RatePlanViewCache.Invalidate(ratePlan.BusinessId); return ratePlan; }
/// <summary> /// Delete VariantRatePlanRate /// </summary> /// <param name="variantRatePlanRateId">VariantRatePlanRate id</param> /// <param name="variantRatePlanId">VariantRatePlan id</param> /// <param name="businessId">business id</param> /// <returns>true if delete was successful</returns> public bool DeleteVariantRatePlanRate(int variantRatePlanRateId, int variantRatePlanId, long businessId) { bool deleteResult; using (var tx = new BusinessTransaction()) { deleteResult = variantRatePlanDao.DeleteVariantRatePlanRate(variantRatePlanRateId); tx.Commit(); } eventTrackingManager.CreateBusinessEventAsync(businessId, BusinessEventTypesEnum.VariantRatePlanRateDeleted, variantRatePlanId.ToString(CultureInfo.InvariantCulture)); return deleteResult; }
/// <summary> /// Creates variant rate plan and rates for a particular variant rate plan /// </summary> /// <param name="ratePlan">Rate plan</param> /// <returns>created rate plan with rates created</returns> public VariantRatePlan CreateVariantRatePlanAndRates(VariantRatePlan ratePlan) { if (ratePlan == null) { return null; } using (var tx = new BusinessTransaction()) { CreateVariantRatePlan(ratePlan); CreateVariantRatePlanRate(ratePlan); tx.Commit(); } return ratePlan; }
/// <summary> /// Modify Channel PrePay Settings /// </summary> /// <param name="channelOptIn">Channel Opt In Record</param> /// <param name="permittedSettings">settings permitted</param> /// <returns>True if created</returns> public bool UpdatePrePayForOptedInChannel(BusinessChannelOptIn channelOptIn, List<ChannelPrePayPermittedSetting> permittedSettings = null) { var success = false; if (channelOptIn.IsValid() && channelOptIn.PrePaySettings != null) { // verify they can edit prepay details var currentChannel = channelDao.GetById(channelOptIn.ChannelId.Value); if (currentChannel == null) { //throw error if we cannot find the channel throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30130, "DistributionManager.UpdatePrePayForOptedInChannel", additionalDescriptionParameters: new object[] { channelOptIn.ChannelId.Value }, arguments: new object[] { channelOptIn })); } // retrieve settings if null (will be not null when validating for a group channel as will be supplied below) if (permittedSettings == null) { permittedSettings = prePayDao.GetPermittedChannelSettings(channelOptIn.BusinessId.Value, channelOptIn.ChannelId.Value); } var suppliedSetting = channelOptIn.PrePaySettings; if (suppliedSetting.Type != PrePayRuleTypeEnum.Unknown) { var permittedSetting = permittedSettings.First(c => c.Type == suppliedSetting.Type); // if supplied values are not valid then throw exception if (suppliedSetting.Value < permittedSetting.Min || suppliedSetting.Value > permittedSetting.Max) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30135, "DistributionManager.UpdatePrePayForOptedInChannel", additionalDescriptionParameters: new object[] { currentChannel.ShortName }, arguments: new object[] { currentChannel.ShortName })); } using (var tx = new BusinessTransaction()) { success = businessChannelOptInDao.UpdatePrePaySettings(channelOptIn); tx.Commit(); } // Record business event eventTrackingManager.CreateBusinessEventAsync(channelOptIn.BusinessId.Value, BusinessEventTypesEnum.OptinChannelModified, channelOptIn.ChannelId.Value.ToString(CultureInfo.InvariantCulture), string.Format("{0} - {1}", suppliedSetting.Type, suppliedSetting.Value)); // if not a channel (so a group) update the related channels if (currentChannel.ChannelType != ChannelTypeEnum.Channel) { // update the opted in related channels with this info as well var channelIds = businessChannelOptInDao.GetOptedInChannelsRelatedToGroup(channelOptIn.BusinessId.Value, currentChannel.Id); if (channelIds != null && channelIds.Any()) { foreach (var channelId in channelIds) { channelOptIn.ChannelId = channelId; UpdatePrePayForOptedInChannel(channelOptIn, permittedSettings); // update the sub-channel validating against permitted settings for the group channel } } } } } return success; }
/// <summary> /// Modify Room /// </summary> /// <param name="room">Room</param> public void Modify(Model.Room.Room room) { if (room == null || room.IsValid() == false) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30068, "RoomManager.Modify", arguments: new object[] { this })); } Model.Room.Room existingRoom = roomDao.GetByName(room.Name, room.BusinessId); if (existingRoom != null && existingRoom.Id != room.Id) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30085, "RoomManager.Modify", additionalDescriptionParameters: (new object[] { room.BusinessId }))); } var bookings = bookingManager.GetByRoom(room.Id).AsQueryable().Where(b => b.StartDate >= DateTime.UtcNow || b.EndDate >= DateTime.UtcNow); // If any were found throw validation exception if trying to change status if (bookings.Any() && room.RoomStatusCode != RoomStatusCodes.ACTIVE) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30097, "RoomManager.Modify", arguments: new object[] { this })); } using (var businessTransaction = new BusinessTransaction()) { roomDao.Modify(room); businessTransaction.Commit(); } eventTrackingManager.CreateBusinessEventAsync(room.BusinessId, BusinessEventTypesEnum.RoomModified, room.Id.ToString(CultureInfo.InvariantCulture)); }
/// <summary> /// update cancellation information for an opted in channel /// </summary> /// <param name="channelTerms">channel cancel terms to use</param> /// <param name="channelUpdateInfo">data to change</param> public bool UpdateCancellationForOptedInChannel(BusinessChannelOptIn channelUpdateInfo, ChannelCancellationTerms channelTerms = null) { var result = false; if (channelUpdateInfo.IsValid() && channelUpdateInfo.CancellationValues != null) { // verify they can edit cancellation details Channel currentChannel = channelDao.GetById(channelUpdateInfo.ChannelId.Value); if (currentChannel == null) { //throw error if we cannot find the channel throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30130, "DistributionManager.UpdateCancellationForOptedInChannel", additionalDescriptionParameters: new object[] { channelUpdateInfo.ChannelId .Value }, arguments: new object[] { channelUpdateInfo })); } if (currentChannel.SupportsCustomCancPolicy == false) { //throw error if we don't support custom cancel throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30131, "DistributionManager.UpdateCancellationForOptedInChannel", additionalDescriptionParameters: new object[] { currentChannel.ShortName }, arguments: new object[] { currentChannel.ShortName })); } // get restrictions for editing here List<ChannelCancellationTerms> ListOfChannelTerms = null; if (channelTerms == null) { ListOfChannelTerms = channelCancellationTermsDao.GetByBusiness(channelUpdateInfo.BusinessId.Value); channelTerms = ListOfChannelTerms.FirstOrDefault(ct => ct.ChannelId == currentChannel.Id); } //channel terms would be null if the business is not subscribed to the channel if (channelTerms != null) { // set the terms to the channels currentChannel.ChannelCancellationTerms = channelTerms; if (channelUpdateInfo.IsCustomCancelValid(currentChannel.ChannelCancellationTerms) == false) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30132, "DistributionManager.UpdateCancellationForOptedInChannel", additionalDescriptionParameters: new object[] { currentChannel.ShortName }, arguments: new object[] { currentChannel.ShortName })); } } using (var tx = new BusinessTransaction()) { result = businessChannelOptInDao.UpdateCancellation(channelUpdateInfo); // Record business event eventTrackingManager.CreateBusinessEventAsync(channelUpdateInfo.BusinessId.Value, BusinessEventTypesEnum.OptinChannelModified, channelUpdateInfo.ChannelId.ToString()); tx.Commit(); } // if not a channel (so a group) update the related channels if (currentChannel.ChannelType != ChannelTypeEnum.Channel) { // update the opted in related channels with this info as well List<int> channelIds = businessChannelOptInDao.GetOptedInChannelsRelatedToGroup(channelUpdateInfo.BusinessId.Value, currentChannel.Id); if (channelIds != null && channelIds.Any()) { foreach (int channelId in channelIds) { channelUpdateInfo.ChannelId = channelId; UpdateCancellationForOptedInChannel(channelUpdateInfo, channelTerms); // update the sub-channel } } } } return result; }
/// <summary> /// Delete Payment /// </summary> /// <param name="payment">Payment to delete</param> /// <returns><c>True</c> if deleted, <c>False</c> if not</returns> public bool DeletePayment(Payment payment) { using (var tx = new BusinessTransaction()) { //Modify payment and mark it as deleted payment.PaymentStatusEnum = PaymentStatusEnum.Deleted; paymentDao.Modify(payment); //record event for the deletion of the payment eventTrackingManager.CreatePaymentEvent(payment.Id, PaymentEventTypeEnum.Deleted, payment.Notes); //create the order event eventTrackingManager.CreateOrderEvent(payment.OrderId, OrderEventTypeEnum.PaymentDeleted, payment.Id.ToString(), payment.Notes); tx.Commit(); } return true; }
/// <summary> /// Opt out of a channel /// </summary> /// <param name="businessChannelOptIn">The businessChannelOptIn record to delete</param> public void OptOutOfChannel(BusinessChannelOptIn businessChannelOptIn) { Channel logicalGroupChannel = channelDao.GetFirstLogicalGroupChannelByChannelId(businessChannelOptIn.ChannelId.Value); if (logicalGroupChannel != null) { List<int> numberOptedIn = businessChannelOptInDao.GetOptedInChannelsRelatedToGroup(businessChannelOptIn.BusinessId.Value, logicalGroupChannel.Id); // if this is the last one being opted out, opt out the logical group as well if (numberOptedIn != null && numberOptedIn.Count == 1) { OptOutOfChannel(new BusinessChannelOptIn { BusinessId = businessChannelOptIn.BusinessId, ChannelId = logicalGroupChannel.Id }); } } using (var tx = new BusinessTransaction()) { businessChannelOptInDao.Remove(businessChannelOptIn.BusinessId.Value, businessChannelOptIn.ChannelId.Value); tx.Commit(); } // Record business event eventTrackingManager.CreateBusinessEventAsync(businessChannelOptIn.BusinessId.Value, BusinessEventTypesEnum.ChannelOptOut, businessChannelOptIn.ChannelId.ToString()); }
/// <summary> /// Centralises the logic to create payments and events /// </summary> /// <param name="payment">Payment</param> /// <param name="orderEventType">Order event type to create</param> /// <param name="paymentEventType">Payment event type to create</param> private void CreatePayment(Payment payment, OrderEventTypeEnum orderEventType, PaymentEventTypeEnum paymentEventType, long businessId) { //input validation if (payment.IsValid()) { SetPaymentConvertedValue(payment, businessId); using (var tx = new BusinessTransaction()) { //enforce that the values are positive and negative according to the type of payment we're trying to create if ((payment.Amount > 0 && payment.PaymentTypeEnum == PaymentTypeEnum.Refund) || (payment.Amount < 0 && payment.PaymentTypeEnum == PaymentTypeEnum.Payment)) { payment.Amount *= -1; } //Set Merchant Type if not already done payment.MerchantType = payment.MerchantType ?? paymentDao.GetMerchantType(payment.OrderId); //create payment paymentDao.Create(payment); //create the payment event eventTrackingManager.CreatePaymentEvent(payment.Id, paymentEventType, payment.Notes); //create the order event eventTrackingManager.CreateOrderEvent(payment.OrderId, orderEventType, payment.Id.ToString(), payment.Notes); tx.Commit(); } } }
/// <summary> /// Modify business channel override /// </summary> /// <param name="businessChannelOverride">BusinessChannelOverride to update</param> /// <param name="modifyVisible">modifyVisible</param> /// <param name="modifyCommissions">modifyCommissions</param> public void ModifyBusinessChannelOverride(BusinessChannelOverride businessChannelOverride, bool modifyVisible, bool modifyCommissions) { using (var tx = new BusinessTransaction()) { //Values needed for the previous Business Channel Override var oldBusinessChannelOverride = businessChannelOverrideDao.GetById(businessChannelOverride.Id); oldBusinessChannelOverride.Channel = channelDao.GetById(businessChannelOverride.ChannelId); oldBusinessChannelOverride.Business = businessDao.GetByKey(businessChannelOverride.BusinessId); SetOverrideValues(businessChannelOverride, modifyVisible, modifyCommissions, oldBusinessChannelOverride); //opted out if was opted in and now is not visible if (businessChannelOverride.IsVisible == false) { businessChannelOptInDao.RemoveByChannelAndBusiness(businessChannelOverride.BusinessId, businessChannelOverride.ChannelId); } businessChannelOverrideDao.Modify(businessChannelOverride); UpsertCommissionDisplay(businessChannelOverride); var channelName = oldBusinessChannelOverride.Channel.Name; // Record business event if (!businessChannelOverride.HasSameVisibility(oldBusinessChannelOverride)) { eventTrackingManager.CreateBusinessEventAsync(businessChannelOverride.BusinessId, BusinessEventTypesEnum.ChannelSettingUpdated, businessChannelOverride.ChannelId.ToString(), String.Format("{0}: Set channel to {1}", channelName, businessChannelOverride.IsVisible == true ? "visible" : "hidden")); } //Send CRM email message //if both overrides are the same, we don't bother if (!businessChannelOverride.HasSameCommissions(oldBusinessChannelOverride)) { eventTrackingManager.CreateBusinessEventAsync(businessChannelOverride.BusinessId, BusinessEventTypesEnum.ChannelSettingUpdated, businessChannelOverride.ChannelId.ToString(), String.Format("{0}: Edit Business Commission", channelName)); emailManager.SendCommissionUpdateEmail(businessChannelOverride, oldBusinessChannelOverride); } tx.Commit(); } }
/// <summary> /// Override a set of rates /// </summary> /// <param name="productType">The rate plan to override rates for</param> public void OverrideRates(ProductType productType) { string notes = string.Empty; bool eventNeeded = false; string reference = productType.RatePlanId.ToString(); BusinessEventTypesEnum eventType = BusinessEventTypesEnum.RatePlanOverrideAdded; var validRateList = productType.Rates.Where(x => x.Override && x.IsValid()).ToList(); // if we have any that are overrides if (validRateList.Any()) { using (var tx = new BusinessTransaction()) { // Override rates foreach (var rate in validRateList) { int? dateRateId = rateCacheDao.GetDateRateId(rate); notes += rate.Date.ToString(StandardDateTimeFormatProvider.GetShortDBFormat()) + ","; if (!dateRateId.HasValue) { // Create date rate record rateCacheDao.CreateDateRate(rate); } else { // Modify the existing date rate record rateCacheDao.ModifyDateRate(dateRateId.Value, rate); eventType = BusinessEventTypesEnum.RatePlanOverrideModified; } } eventTrackingManager.CreateBusinessEvent(productType.BusinessId, eventType, reference, notes.TrimEnd(',')); tx.Commit(); } } }
/// <summary> /// Modify a period by changing the date range specified /// </summary> /// <remarks> /// Assumes only date range changes are possible at the moment /// </remarks> /// <param name="period">Period to modify</param> /// <param name="cultureCode">culture for translation</param> /// <returns>Period with date changed</returns> public Period ModifyPeriod(Period period, string cultureCode) { ValidatePeriod(period, cultureCode, false); // Make sure period date range id is set if (period.PeriodDateRanges == null || period.PeriodDateRanges.Any() == false || period.PeriodDateRanges.Any(pdr => pdr.Id == default(int))) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30084, "PricingManager.ModifyPeriod", arguments: new object[] { period, cultureCode })); } // only one date range modify per call if (period.PeriodDateRanges.Count > 1) { // only one period can be modified at a time throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30143, "PricingManager.ModifyPeriod", arguments: new object[] { period, cultureCode })); } // check for any overlaps if (DoDateRangesOverlap(period)) { return period; } BusinessEventTypesEnum businessEvent = BusinessEventTypesEnum.Unknown; string reference = string.Empty; List<PeriodDateRange> existingDateRanges = periodDateRangeDao.GetAllByPeriodId(period.Id); // All ok, so modify the date ranges using (var bex = new BusinessTransaction()) { if (period.PeriodColor == null || period.PeriodColorId == default(int) || period.PeriodColor.Id == default(int)) { //Fetch the colour for the period that exists period.PeriodColor = periodColorDao.GetByPeriodId(period.Id, cultureCode); period.PeriodColorId = period.PeriodColor.Id; } PeriodDateRange pdr = period.PeriodDateRanges.First(); periodDateRangeDao.Modify(pdr); if (period.PeriodDateRanges.Count == 1) { // get the one being modified: if (existingDateRanges.Any(p => p.Id == pdr.Id)) { PeriodDateRange modifyPdr = existingDateRanges.FirstOrDefault(e => e.Id == pdr.Id); reference = reference + modifyPdr.StartDate.ToString(StandardDateTimeFormatProvider.GetShortDBFormat()) + ","; reference = reference + modifyPdr.EndDate.ToString(StandardDateTimeFormatProvider.GetShortDBFormat()) + ","; } // get the new dates as well reference = reference + pdr.StartDate.ToString(StandardDateTimeFormatProvider.GetShortDBFormat()) + ","; reference = reference + pdr.EndDate.ToString(StandardDateTimeFormatProvider.GetShortDBFormat()) + ","; } businessEvent = GetBusinessEventForPeriodType(period.PeriodType.PeriodTypeEnum, isEdit: true); bex.Commit(); } // event for modify of period / date range here eventTrackingManager.CreateBusinessEventAsync(period.BusinessId, businessEvent, reference.TrimEnd(',')); return period; }
/// <summary> /// Delete all override rates for a given roomtype / date /// </summary> /// <param name="businessId">business id</param> /// <param name="roomTypeId">room type to manipulate</param> /// <param name="date">day to delete data for</param> public void DeleteRateOverrides(long businessId, int roomTypeId, DateTime date) { using (var tx = new BusinessTransaction()) { // delete date rates for the date and room type rateCacheDao.DeleteDateRatesForRoomTypeAndDate(roomTypeId, date); // reference is room type id, note is date for the delete // Doing synchronous since we need the results reflected immediately eventTrackingManager.CreateBusinessEvent(businessId, BusinessEventTypesEnum.RatePlanOverrideDeleted, // s format is == reflects a defined standard (ISO 8601) roomTypeId.ToString(), date.Date.ToString("s")); tx.Commit(); } }
/// <summary> /// Delete or Add roles to the user /// </summary> /// <param name="user">User name</param> /// <param name="roles">Roles name</param> public void ReplaceRolesToUser(string user, string[] roles) { if (string.IsNullOrEmpty(user)) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30054, "UserManager.ReplaceRolesToUser", additionalDescriptionParameters: (new object[] { user }), arguments: new object[] { user, roles })); } using(var tx = new BusinessTransaction()) { string[] currentUserRoles = roleDao.GetAssociatedRoles(user); var rolesToDelete = roles != null ? currentUserRoles.Where(r => roles.Contains(r) == false).ToArray() : currentUserRoles; var rolesToAdd = roles != null ? roles.Where(r => currentUserRoles.Contains(r) == false).ToArray() : new string[0]; string notes = ""; if (rolesToDelete != null && rolesToDelete.Length > 0) { notes = "Roles deleted : " + rolesToDelete.Serialize(','); roleDao.RemoveRolesFromUser(user, rolesToDelete); } if (rolesToAdd.Length > 0) { notes += "Roles added : " + rolesToAdd.Serialize(','); roleDao.AssociateRolesToUser(user, rolesToAdd); } if (notes != string.Empty) { RecordUserEvent(user, UserEventTypesEnum.RoleUpdated, notes); } tx.Commit(); } }
/// <summary> /// Cancel the order /// </summary> /// <param name="cancelOrderRequest">Cancel Order Request Dto</param> /// <returns>True id the order has been cancelled</returns> /// <remarks> /// Cancel all the bookings attached to an order /// -The order could be a tentative or not /// </remarks> public bool CancelOrder(CancelOrderRequestDto cancelOrderRequest) { // Log request Log.LogInfo("CancelBooking request: {0}", null, cancelOrderRequest); Log.LogInfoAsXml(cancelOrderRequest); var bookings = new List<Booking>(); var orderCancelSuccess = true; Order order = null; if (!string.IsNullOrEmpty(cancelOrderRequest.ChannelReference)) { order = orderManager.GetOrderWithBookingsByKey(channelReference: cancelOrderRequest.ChannelReference, type: GetOrderWithBookingsByEnum.ChannelReference); if (order == null) { return false; } bookings = order.Bookings; } else { // If the ReferenceNumber begins with a number its a BookingReference otherwise its a OrderReference if (cancelOrderRequest.ReferenceNumber.StartsWithNumber()) { var booking = bookingManager.GetByReference(cancelOrderRequest.ReferenceNumber); bookings.Add(booking); order = booking.Order; order.Bookings = bookings; } else { order = orderManager.GetOrderWithBookingsByKey(orderReference: cancelOrderRequest.ReferenceNumber, type: GetOrderWithBookingsByEnum.OrderReference); if (order == null) { return false; } bookings = order.Bookings; } } if (bookings == null || !bookings.Any()) { return false; } using (var tx = new BusinessTransaction()) { foreach (var booking in bookings) { var cancellationReasonEnum = (CancellationReasonEnum) cancelOrderRequest.CancellationReason; var cancellationDetail = new CancellationDetail { CancellationReason = new CancellationReason {Reason = cancellationReasonEnum}, SendCancellationEmail = false }; booking.CancellationDetails = cancellationDetail; int? refundId; bool? isRefundSuccessful; bool? isRefundAttempted; bookingManager.CancelBooking(booking, out refundId, out isRefundSuccessful, out isRefundAttempted); var response = bookingManager.GetByReference(booking.BookingReferenceNumber).IsCancelled(); if (!response) { orderCancelSuccess = false; } // Log response Log.LogInfo("CancelBooking {0} response: {1}", null, booking.BookingReferenceNumber, response); } emailManager.SendCancellationEmails(order); tx.Commit(); } return orderCancelSuccess; }
/// <summary> /// Remove business from user /// </summary> /// <param name="userId">User Id</param> /// <param name="businessId">Business Id</param> public void RemoveBusinessFromUser(Guid userId, long businessId) { using (var tx = new BusinessTransaction()) { userBusinessDao.RemoveBusinessFromUser(userId, businessId); // Set primary business id to next business if removing the current primary business UserExtension userExtension = userExtensionDao.GetByKey(userId); if (userExtension.PrimaryBusinessId == businessId) { long? firstBusinessId = userBusinessDao.GetFirstBusiness(userId); userExtension.PrimaryBusinessId = firstBusinessId; userExtensionDao.Modify(userExtension); } RecordUserEvent(userId, UserEventTypesEnum.BusinessLinkRemoved, null, businessId.ToString(CultureInfo.InvariantCulture)); tx.Commit(); } }
/// <summary> /// Confirm and change the state of the bookings as well as collecting the payment information /// </summary> /// <param name="confirmBooking">Confirm Order Request Dto</param> /// <returns>ConfirmOrderResponseDto</returns> /// <remarks> /// Confirm all the bookings attached to an order /// </remarks> public ConfirmOrderResponseDto ConfirmOrder(ConfirmOrderRequestDto confirmBooking) { // Log request Log.LogInfo("ConfirmOrder request: {0}", null, confirmBooking); Log.LogInfoAsXml(confirmBooking); #region Preconditions if (confirmBooking == null || string.IsNullOrEmpty(confirmBooking.OrderReferenceNumber)) { return null; } var order = orderManager.GetOrderWithBookingsByKey(orderReference: confirmBooking.OrderReferenceNumber, type: GetOrderWithBookingsByEnum.OrderReference); if (order == null || order.Bookings == null || !order.Bookings.Any()) { return null; } var firstBooking = order.Bookings.FirstOrDefault(); var business = businessManager.GetBusiness(firstBooking.BusinessId); if (business == null) { return null; } #endregion var isCommitSucceeded = false; using (var tx = new BusinessTransaction()) { Payment payment = null; //At this point we just handle credit card and Paypal switch (confirmBooking.PaymentMethod) { case PaymentMethodEnumDto.CreditCard: payment = DataTransferObjectsConverter.ConvertConfirmBookingOnlineRequestDtoToPayment( confirmBooking); break; case PaymentMethodEnumDto.PayPal: payment = DataTransferObjectsConverter.ConvertConfirmBookingOnlineRequestDtoToPaymentFromPaypal( confirmBooking); break; case PaymentMethodEnumDto.AccountTransfer: // This means possibly it is expedia already paid for payment = paymentManager.SetupOtaPayment(order, business, confirmBooking.ReceivedDate); break; } if (payment != null && payment.IsValid()) { payment.OrderId = order.Id.Value; //For the moment we use the business working currency //Because ABS does not supply the currency in the availability offers if (payment.Currency == null) { payment.Currency = new Currency(business.WorkingCurrencyCode); } paymentManager.CreatePaymentForOrder(payment, order.Bookings.Count > 0 ? order.Bookings.FirstOrDefault().BusinessId : 0); } bool areFeesCreated = false; foreach (var booking in order.Bookings) { if (confirmBooking.Guest != null) { Guest guest = Mapper.Map<Guest>(confirmBooking.Guest); if (guest.TryIsValid()) { // Modify or Create the Guest if (booking.Guest != null) { if (!booking.Guest.Id.HasValue) { guestManager.Create(guest); } else { guest.Id = booking.Guest.Id; guest.BusinessId = booking.BusinessId; guestManager.Modify(guest); } } } } if (areFeesCreated == false) { bookingItemManager.CreateBookingFees(booking); areFeesCreated = true; } bookingManager.ConfirmTentativeBooking( booking.Id.Value, booking.BusinessId, confirmBooking.ChannelReference, confirmBooking.CCToken, confirmBooking.CCTokenSource); if (booking.IsOverBooking) { int emailId = emailManager.SendOverbookingEmail(business, order, booking, confirmBooking.ChannelReference); Log.LogInfo( "Over Booking. Split product/inventory availability found for Hotel Shortname={0}, room type id={1}, check-in date={2}, check-out date={3}, email Id = {4}", null, booking.BusinessShortName, booking.RoomTypeId, booking.StartDate.ToString("ddd d MMM, yyyy"), booking.EndDate.ToString("ddd d MMM, yyyy"), emailId); } } tx.Commit(); isCommitSucceeded = true; } if (isCommitSucceeded) { orderManager.SendConfirmationEmails(order); } var confirmBookingResponseDto = new ConfirmOrderResponseDto { OrderReferenceNumber = confirmBooking.OrderReferenceNumber }; // Log response Log.LogInfo("ConfirmOrder response: {0}", null, confirmBookingResponseDto); Log.LogInfoAsXml(confirmBookingResponseDto); return confirmBookingResponseDto; }
/// <summary> /// Modify User Status /// </summary> /// <param name="userId">id of user to modify</param> /// <param name="userStatus">new status for the user</param> /// <param name="notes">notes about the status change</param> public bool ModifyUserSatus(Guid userId, UserStatusEnum userStatus, string notes) { if (string.IsNullOrEmpty(notes)) { throw new ValidationException(ErrorFactory.CreateAndLogError(Errors.SRVEX30051, "Membership.ModifyUserSatus")); } using (var btx = new BusinessTransaction()) { UserEventTypesEnum eventType = userStatus == UserStatusEnum.Disabled ? UserEventTypesEnum.UserDisabled : UserEventTypesEnum.UserEnabled; userExtensionDao.ModifyUserSatus(userId, userStatus); RecordUserEvent(userId, eventType, notes); btx.Commit(); } return true; }
/// <summary> /// Creates just the variant rate plan /// </summary> /// <param name="ratePlan">Rate plan</param> /// <returns>created rate plan with id</returns> public VariantRatePlan CreateVariantRatePlan(VariantRatePlan ratePlan) { if (ratePlan == null) { return null; } using (var tx = new BusinessTransaction()) { variantRatePlanDao.Create(ratePlan); tx.Commit(); } eventTrackingManager.CreateBusinessEventAsync(ratePlan.BusinessId, BusinessEventTypesEnum.VariantRatePlanAdded, ratePlan.Id.ToString(CultureInfo.InvariantCulture)); // Invalidate the cache so it refreshes Cache.Cache.RatePlanViewCache.Invalidate(ratePlan.BusinessId); return ratePlan; }