Advertisement
Guest User

Untitled

a guest
Jul 24th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 30.95 KB | None | 0 0
  1. if (connection == null)
  2. {
  3. using (connection = new Konekcija())
  4. {
  5. connection.BeginTransaction();
  6. var res = GetReservationFromRequest(request, connection: connection);
  7. connection.EndTransaction();
  8. return res;
  9. }
  10. }
  11. var reservation = new VelikaRezervacija();
  12.  
  13. // Get user
  14. if (request.CreatedByUserID.HasValue)
  15. {
  16. var user = Korisnik.DohvatiKorisnika(request.CreatedByUserID.Value, connection);
  17. if (user == null || user.Id == 0)
  18. {
  19. throw new Exception("The created by user could not be found!");
  20. }
  21. reservation.CreatedByUser = user;
  22. }
  23.  
  24. // Get currency.
  25. var currency = Valuta.DohvatiValutu(request.CurrencyID, connection);
  26. if (currency == null || currency.StatusValuta != StatusValuta.Aktivna)
  27. throw new Exception(string.Format("Currency with ID={0} doesn't exist or is inactive in system", request.CurrencyID));
  28. reservation.ValutaRezervacija = currency;
  29.  
  30. var epochID = Postavke.SifraRazdobljeDefault;
  31. reservation.RazdobljeRezervacije = new Razdoblje { SifraRazdoblje = epochID };
  32.  
  33. // Get branch office.
  34. var branchOffice = _branchOfficesService.GetBranchOfficeByGUID(request.BranchOfficeGUID, connection: connection);
  35. reservation.PoslovnicaVelikaRezervacija = branchOffice;
  36.  
  37. // Get and log in customer.
  38. var customer = GetCustomerFromRequest(request.Customer, connection: connection);
  39. if (customer == null)
  40. {
  41. if (request.ExecuteInsert)
  42. throw new Exception("Customer couldn't be registered or logged in!");
  43. }
  44. else
  45. {
  46. var customerSaveDTO = _customerSaveService.MapTvrtkaToSaveDTO(customer);
  47. if (branchOffice != null)
  48. customerSaveDTO.BranchOfficeID = (int)branchOffice.SifraPoslovnica;
  49. _customerSaveService.LogOrRegisterCustomer(customerSaveDTO, connection: connection);
  50. }
  51.  
  52. reservation.Kupac = customer;
  53.  
  54. var languageID = !string.IsNullOrEmpty(request.LanguageID) ? Jezik.DohvatiJezik(request.LanguageID, connection: connection).SifraJezik : Postavke.DefaultSifraJezik;
  55.  
  56. // If the creation date isn't set, the value can remain null because the system already has a fallback mechanism (it set's the creation date to the current date)
  57. if (request.CreationDate.HasValue)
  58. {
  59. reservation.Datum = request.CreationDate.Value;
  60. }
  61.  
  62. reservation.Opis = request.BookingDescription;
  63. reservation.ImportSifraVelikeRezervacije = request.ReservationImportID;
  64.  
  65. reservation.UneseneVrijednostiDodatnihPolja = new List<DodatnaPolja>();
  66. var reservationCustomFields = DodatnaPolja.Dohvati(VrstaDodatnogPoljaEnum.ReservationCustomFields, languageID);
  67. ///for each custom field of the partners we check which ones were chosen aqnd then update their values
  68. foreach (var reservationFieldOfCompany in reservationCustomFields)
  69. {
  70. reservationFieldOfCompany.DodatnaPoljaVrijednostSelektirana = new DodatnaPoljaVrijednost();
  71. var listCustomFields = request.ReservationCustomFields;
  72. if (listCustomFields.IsNullOrEmpty())
  73. continue;
  74.  
  75. var customFieldValue = listCustomFields.Where(x => x.ID == reservationFieldOfCompany.SifraDodatnogPolja).Select(x => x.Value).FirstOrDefault();
  76. if (!string.IsNullOrWhiteSpace(customFieldValue))
  77. {
  78. switch (reservationFieldOfCompany.TipDodatnogPolja)
  79. {
  80. case TipDodatnogPoljaEnum.dropDownLista:
  81. var additionalFieldsValueId = 0;
  82. if (!int.TryParse(customFieldValue, out additionalFieldsValueId))
  83. continue;
  84. reservationFieldOfCompany.DodatnaPoljaVrijednostSelektirana.SifraDodatnaPoljaVrijednost = additionalFieldsValueId;
  85. /// We need to set the selected value ID in the values dictionary because the BatchUpdateCustomFieldValues does not work correctly only with the CF value ID.
  86. reservationFieldOfCompany.DodatnaPoljaVrijednostSelektirana.VrijednostDodatnogPoljaDictionary = new Dictionary<byte, string> { { languageID, customFieldValue } };
  87. break;
  88. case TipDodatnogPoljaEnum.textBox:
  89. case TipDodatnogPoljaEnum.textArea:
  90. case TipDodatnogPoljaEnum.radEditor:
  91. reservationFieldOfCompany.DodatnaPoljaVrijednostSelektirana.VrijednostDodatnogPoljaDictionary = new Dictionary<byte, string> { { languageID, customFieldValue } };
  92. break;
  93. case TipDodatnogPoljaEnum.checkBox:
  94. reservationFieldOfCompany.DodatnaPoljaVrijednostSelektirana.VrijednostDodatnogPoljaDictionary = new Dictionary<byte, string> { { languageID, customFieldValue } };
  95. break;
  96. default:
  97. throw new NotImplementedException("Unknown custom field type: " + reservationFieldOfCompany.TipDodatnogPolja);
  98. }
  99. reservationFieldOfCompany.DodatnaPoljaVrijednostSelektirana.DodatnoPolje = reservationFieldOfCompany;
  100.  
  101. if (reservationFieldOfCompany.DodatnaPoljaVrijednostSelektirana != null && reservationFieldOfCompany.DodatnaPoljaVrijednostSelektirana.DodatnoPolje != null)
  102. reservation.UneseneVrijednostiDodatnihPolja.Add(reservationFieldOfCompany);
  103. }
  104. }
  105.  
  106. // Get payment method.
  107. var paymentMethod = NacinPlacanja.DohvatiNacinPlacanja(request.PaymentMethodID, languageID, connection);
  108. var paymentMethodPercentage = Postavke.CreditCardFeeAsItemEnabled ? 0 : paymentMethod.PostotakNadoplata;
  109.  
  110. reservation.NacinPlacanjaVelikaRezervacija = paymentMethod;
  111.  
  112. var dictReservationItemStatuses = new Dictionary<int, InsertReservationPriceCalculationStatus>();
  113. var reservationCalculationDTO = new ReservationCalculationDTO();
  114.  
  115. // Create reservation items.
  116. if (request.ReservationItems.IsNotNullOrEmpty())
  117. {
  118. var selectedMarketsDto = Trziste.SelectMarketsForCalculation(request.MarketID, 0, customer.SifraTvrtka, connection: connection);
  119.  
  120. /// Initial status we're hoping to get for reservation
  121. /// For each non-3ps item status is checked and updated accordingly
  122. var reservationStatus = Postavke.JeLiPartnerimaOnemogucenoRaditiOpcijeRezervacije
  123. ? StatusVelikaRezervacijaEnum.Potvrdjena
  124. : MapToAllowedReservationStatus(request.ReservationStatusID);
  125.  
  126. var waitingList = false;
  127. var dictCapacityUnits = new Dictionary<long, List<Rezervacija>>();
  128.  
  129. var preloadData = new PricingPolicyPreloadData();
  130.  
  131. if (Postavke.EnablePricingPolicy && !request.ReservationItems.IsNullOrEmpty())
  132. {
  133. var unitIDs = request.ReservationItems.Select(x => x.UnitID).ToHashSetLemax();
  134. var productIDs = JedinicaDR.GetParentUnitIDs(unitIDs, connection: connection);
  135.  
  136. preloadData = _reservationItemService.GetPricingPolicyPreloadData(customer.SifraTvrtka, productIDs, unitIDs, languageID, connection: connection);
  137. }
  138.  
  139. reservationCalculationDTO.PricingPolicyPreloadData = preloadData;
  140.  
  141. var exchangeRate = new Tecaj();
  142. var exchangeRatesDictionary = new Dictionary<DateTime, Tecaj>();
  143. if (!Postavke.Enable2ExchangeRates)
  144. {
  145. exchangeRate = Tecaj.DohvatiNajbliziTecaj(DateTimeService.GetSystemTime(), true, connection);
  146. }
  147. else
  148. {
  149. var dates = request.ReservationItems
  150. .Select(x => x.StartDate.Date)
  151. .Distinct()
  152. .ToList();
  153.  
  154. exchangeRatesDictionary = _exchangeRateService.GetClosestExchangeRatesForDates(dates, true, ExchangeRateTypeEnum.Commercial, connection);
  155. }
  156.  
  157. foreach (var item in request.ReservationItems)
  158. {
  159. if (Postavke.Enable2ExchangeRates)
  160. {
  161. exchangeRate = exchangeRatesDictionary.GetValueOrDefault(item.StartDate.Date);
  162. }
  163.  
  164. var itemOrder = item.ReservationItemOrder;
  165. /// common reservation item properties
  166. var reservationItem = new Rezervacija
  167. {
  168. Poredak = itemOrder,
  169. BranchOffice = branchOffice,
  170. VelikaRezervacijaRezervacije = reservation,
  171. ClientComment = item.ClientComment
  172. };
  173.  
  174. var passengersMappedToGuest = new List<PassengerRQGuestMapping>();
  175.  
  176. if (item.Passengers.IsNotNullOrEmpty())
  177. {
  178. passengersMappedToGuest = item.Passengers
  179. .Select(x => new PassengerRQGuestMapping(x))
  180. .ToList();
  181.  
  182.  
  183. reservationItem.ListaGostiju = passengersMappedToGuest
  184. .Select(x => x.Guest)
  185. .ToList();
  186. }
  187.  
  188. var priceCalculationItemStatus = new InsertReservationPriceCalculationStatus { Code = StatusCode.OK };
  189. if (!dictReservationItemStatuses.ContainsKey(itemOrder))
  190. dictReservationItemStatuses[itemOrder] = priceCalculationItemStatus;
  191.  
  192. /// decrypt provider data
  193. var providerData = string.Empty;
  194. if (!string.IsNullOrWhiteSpace(item.UnitCode))
  195. providerData = ITravelKriptiranje.Dekriptiraj(item.UnitCode);
  196.  
  197. if (item.SelectedFlightOptions.IsNotNullOrEmpty())
  198. {
  199. if (string.IsNullOrWhiteSpace(providerData))
  200. throw new ArgumentException("Unit code is empty");
  201.  
  202. /// We need to modify the provider data with the selected flight options because the provider data sent contains all the flight options that are displayed and the selection is done on the search form,
  203. /// but the search form on the web does not have the logic to update the encoded provider data with the selected flight options, so we need to do it here.
  204. /// We do this on the back office search form because it's a part of the iTravel system, unlike the search results code on the websites.
  205. /// We explicitly get the flights interface because this functionality is related on to flights.
  206. var gdsInstanceFlights = _gdsFactory.GetInstanceForFlights(providerData);
  207. providerData = gdsInstanceFlights.ConvertProviderDataAndSelectFlightOptions(providerData, item.SelectedFlightOptions.ToHashSetLemax());
  208. }
  209.  
  210. /// this code is taken from calculation (which stands for best code for booking 3ps at this moment)
  211. /// these two places could potentially be unified but there was no resources for such a big change in this change.
  212. if (!string.IsNullOrWhiteSpace(providerData))
  213. {
  214. var parsedProviderData = HttpUtility.ParseQueryString(providerData);
  215. /// TODO-FLIGHTS (low): Replace with IGdsBookService and remove custom provider data parsing.
  216. var gdsInstance = _gdsFactory.GetInstanceForBooking(providerData);
  217.  
  218. /// Prepare data to create a reservation
  219. var reservationStart = DateTime.Parse(parsedProviderData["startDate"]);
  220. var languageISO = Jezik.DohvatiJezik(languageID).KraticaISO;
  221. /// Get the reservation item
  222. var reservationGDS = gdsInstance.GetCalculatedReservationForUnit(providerData, reservation.ValutaRezervacija.SifraValuta, null, null, reservationStart, languageISO);
  223. /// Save data from the reservation item
  224. var tmpReservationItem = reservationItem;
  225.  
  226. reservationItem = reservationGDS.ListaMalihRezervacija[0];
  227.  
  228. /// Copy the saved data back
  229. reservationItem.Poredak = tmpReservationItem.Poredak;
  230. reservationItem.BranchOffice = tmpReservationItem.BranchOffice;
  231. reservationItem.VelikaRezervacijaRezervacije = tmpReservationItem.VelikaRezervacijaRezervacije;
  232. reservationItem.ListaGostiju = tmpReservationItem.ListaGostiju;
  233.  
  234. /// Number of passengers must match
  235. var maxKapacitet = Convert.ToInt32(parsedProviderData["noOfPersons"]);
  236. var childrenAges = parsedProviderData["childrenAges"];
  237. if (!String.IsNullOrEmpty(childrenAges))
  238. {
  239. string[] separator = { "," };
  240. var splitAges = childrenAges.Split(separator, StringSplitOptions.RemoveEmptyEntries);
  241. foreach (var age in splitAges)
  242. maxKapacitet++;
  243. }
  244.  
  245. if (maxKapacitet > reservationItem.ListaGostiju.Count)
  246. {
  247. int brojOsoba = reservationItem.ListaGostiju.Count;
  248. for (int i = brojOsoba; i < maxKapacitet; i++)
  249. reservationItem.ListaGostiju.Add(new Gost("", "", new DateTime(1900, 1, 1)));
  250. }
  251.  
  252. ///Setting unit
  253. ///Ad hoc unit is never available on the web
  254. var market = item.UnitID == Postavke.AdHocTuzemnaJedinicaDR ? NaTrzistu.AktivnaAgencija : NaTrzistu.AktivnaAgencijaIInternet;
  255. var unit = JedinicaDR.DohvatiJedinicuINadJedinicu(item.UnitID, languageID, market, connection);
  256. if (unit != null)
  257. {
  258. reservationItem.JedinicaDR = unit;
  259. if (unit.NadJedinica != null)
  260. {
  261. reservationItem.JedinicaPR = (JedinicaPR)unit.NadJedinica;
  262. }
  263. }
  264.  
  265. reservation.ListaMalihRezervacija.Add(reservationItem);
  266. }
  267. else
  268. {
  269. reservation.ListaMalihRezervacija.Add(reservationItem);
  270.  
  271. var unit = JedinicaDR.DohvatiJedinicuINadJedinicu(item.UnitID, languageID, NaTrzistu.AktivnaAgencijaIInternet, connection);
  272.  
  273. if (unit == null)
  274. {
  275. string failureMessage = string.Format("Unit with ID {0} doesn't exist.", item.UnitID);
  276. if (!request.SkipUnavailableItems)
  277. {
  278. throw new Exception(failureMessage);
  279. }
  280.  
  281. var unavailbleReservationItemDTO = new UnavailableReservationItemDTO
  282. {
  283. ReservationItem = reservationItem,
  284. Status = new Status
  285. {
  286. Description = failureMessage,
  287. Code = StatusCode.Error
  288. }
  289. };
  290.  
  291. reservationCalculationDTO.UnavailableReservationItems.Add(unavailbleReservationItemDTO);
  292. reservation.ListaMalihRezervacija.Remove(reservationItem);
  293. continue;
  294. }
  295.  
  296. var listMarketIDs = new List<int>();
  297. if (request.MarketID > 0)
  298. listMarketIDs.Add(request.MarketID);
  299. unit.NapuniSveUslugeIPopuste(languageID, null, listMarketIDs, null, selectedMarketsDto.CustomerID, item.StartDate, true, false, selectedMarketsDto.MarketType, connection);
  300.  
  301. reservationItem.PocetakRezervacija = item.StartDate;
  302. reservationItem.KrajRezervacija = item.EndDate;
  303. reservationItem.JedinicaDR = unit;
  304. if (unit.NadJedinica != null)
  305. {
  306. reservationItem.JedinicaPR = (JedinicaPR)unit.NadJedinica;
  307. }
  308.  
  309. if (unit.SifraTipJedinica == (int)TipJediniceEnum.AranzmanDR)
  310. {
  311. reservationItem.RoomSharingCode = Guid.NewGuid().ToString();
  312. }
  313.  
  314. SetReservationItemUnitFitID(item, reservationItem, unit);
  315.  
  316. FixReservationItemDates(item, reservationItem, unit);
  317.  
  318. // Create dictionaries by passengers.
  319. var dictServicesPerPassenger = CreateDictNumberOfPassengersByService(item.SelectedServices, item.Passengers);
  320. var dictSelectedServices = CreateDictPassengersByService(passengersMappedToGuest);
  321.  
  322. var selectedServices = MergeItemAndPassengerServices(item.SelectedServices, item.Passengers);
  323. var calculationSelectedServices = selectedServices
  324. .Select(x => MapServiceToUsluga(x, unit.ListaUsluga))
  325. .ToList();
  326. var passengerList = passengersMappedToGuest.Select(x => x.Guest).ToList();
  327. var servicesForFirstPriceCalculation = calculationSelectedServices
  328. .Select(svc => svc.Clone() as Usluga)
  329. .ToList();
  330.  
  331. if (Postavke.EnablePricingPolicy)
  332. {
  333. if (reservationItem.FitID > 0 && !preloadData.FITs.ContainsKey((int)reservationItem.FitID))
  334. {
  335. var fitFilter = new FilterDetaljiJedinice
  336. {
  337. sifraJedinica = reservationItem.FitID
  338. };
  339. var fit = JedinicaPR.DohvatiJedinicuISveNjezinePodatke(fitFilter, connection: connection);
  340.  
  341. preloadData.FITs.Add((int)reservationItem.FitID, fit);
  342. }
  343.  
  344. var pricingPolicyParameters = new ReservationItemPricingPolicyParameter(reservationItem, connection: connection);
  345. pricingPolicyParameters.ExchangeList = exchangeRate;
  346. pricingPolicyParameters.Currency = currency;
  347. pricingPolicyParameters.Services = servicesForFirstPriceCalculation;
  348.  
  349. pricingPolicyParameters.PreloadData = preloadData;
  350.  
  351. _reservationItemService.ApplyPricingPolicyParameters(pricingPolicyParameters);
  352. }
  353.  
  354. Sezone priceListSchedule = null;
  355. var originalPeriodStartDate = new DateTime();
  356. var originalPeriodEndDate = new DateTime();
  357.  
  358. if (unit.NadJedinica.IsSimpleTour())
  359. {
  360. // todo-commission: retrieve outside this method
  361. var listPriceListSchedules = Sezone.DohvatiSezone(unit.NadJedinica.SifraJedinica, -1, false, true, Postavke.DefaultSifraJezik, connection: connection);
  362.  
  363. if (listPriceListSchedules.IsNotNullOrEmpty())
  364. {
  365. priceListSchedule = listPriceListSchedules[0];
  366. }
  367. }
  368.  
  369. var isDailyDepartures = priceListSchedule != null && priceListSchedule.SvakodnevniPolasci;
  370.  
  371. // Everywhere where you need accurate view of the service availability for simple tours daily departure type of units.
  372. if (isDailyDepartures)
  373. {
  374. IzracunCijene.PricelistAdjustmentForCertainCalculations(servicesForFirstPriceCalculation, ref originalPeriodStartDate, ref originalPeriodEndDate, reservationItem.PocetakRezervacija, reservationItem.KrajRezervacija, true);
  375. }
  376.  
  377. // Get reservation details from price calculation.
  378. var priceCalculation = _priceCalculationService.CalculatePrice((TipJediniceEnum)unit.SifraTipJedinica, servicesForFirstPriceCalculation, passengerList, reservationItem.PocetakRezervacija, reservationItem.KrajRezervacija
  379. , dictServicesPerPassenger, exchangeRate, currency, true, paymentMethodPercentage, unit.Kapacitet
  380. , guestsForServices: dictSelectedServices, specialOfferServices: unit.RjecnikUslugaPoPosebnimPonudama, today: DateTimeService.GetSystemTime());
  381. if (priceCalculation.StatusIzracunCijene == StatusIzracunCijeneEnum.Pogreska)
  382. {
  383. priceCalculationItemStatus.Code = StatusCode.Error;
  384. priceCalculationItemStatus.Description = priceCalculation.PorukaPogreska;
  385. }
  386.  
  387. if (isDailyDepartures)
  388. {
  389. IzracunCijene.PricelistAdjustmentForCertainCalculations(servicesForFirstPriceCalculation, ref originalPeriodStartDate, ref originalPeriodEndDate, reservationItem.PocetakRezervacija, reservationItem.KrajRezervacija, false);
  390. }
  391.  
  392. reservationItem.ListaRezervacijaDetalji = priceCalculation.ListaRezervacijaDetalji;
  393. reservationItem.NacinObracunaKolicine = Postavke.NacinObracunaKolicineNaRezervaciji;
  394.  
  395. #region todo-commission - extract and unify with ReservationItemsGroupActionService - Used for calculating commission when reservation insert is NOT executed
  396. var affiliateID = reservation.AffiliateTvrtka != null ? reservation.AffiliateTvrtka.SifraTvrtka : 0;
  397.  
  398. /*************** SELECTION FOR COMMISSION PRICE MARKET ******************/
  399. /*************** CREATE COMMISSION PRICE SERVICES/DETAILS (listCommissionServices -> listSelectedServicesAffiliate) ******************/
  400. var listCommissionServices = _commissionService.CreateCommisionServices(reservationItem, unit, languageID, epochID, customer.SifraTvrtka, customer.SellingMode
  401. , affiliateID: affiliateID, connection: connection);
  402.  
  403. var listSelectedServicesAffiliate = Rezervacija.GetAffiliateServices(listCommissionServices, calculationSelectedServices);
  404.  
  405. // Get all additional services, supplements and reductions which type of payment is per person.
  406. var listAdditionalServicesSupplementsAndReductions = unit.ListaUsluga
  407. .Where(x => x.IsMultiplierPerPerson()
  408. && (x.VrstaUsluga == (int)VrsteUslugaEnum.DodatneUsluge
  409. || x.VrstaUsluga == (int)VrsteUslugaEnum.NadoplateIOdbici))
  410. .ToList();
  411.  
  412. /*************** CREATE SELLING PRICE SERVICES/DETAILS (listaOdabranihUsluga) ******************/
  413. var listSelectedServices = new List<Usluga>();
  414.  
  415. /// key = serviceID, value = number of persons that use the service under serviceID
  416. var dictNumberOfPassengersOnService = new Dictionary<int, int>();
  417. var reservationItemServicesIDs = new HashSet<int>();
  418. if (reservationItem.ListaRezervacijaDetalji.IsNotNullOrEmpty())
  419. {
  420. reservationItemServicesIDs.AddRange(reservationItem.ListaRezervacijaDetalji
  421. .Where(x => x.RezervacijaUsluga != null && x.RezervacijaUsluga.SifraUsluga > 0)
  422. .Select(x => x.RezervacijaUsluga.SifraUsluga));
  423. }
  424.  
  425. foreach (var usluga in unit.ListaUsluga)
  426. {
  427. switch ((VrsteUslugaEnum)usluga.VrstaUsluga)
  428. {
  429. case VrsteUslugaEnum.OsnovneUsluge:
  430. listSelectedServices.Add(usluga);
  431. int personsUseServiceCount = dictServicesPerPassenger.TryGetValue(usluga.SifraUsluga, out personsUseServiceCount) ? personsUseServiceCount : 1;
  432. dictNumberOfPassengersOnService[usluga.SifraUsluga] = personsUseServiceCount;
  433. break;
  434. case VrsteUslugaEnum.NadoplateIOdbici:
  435. case VrsteUslugaEnum.DodatneUsluge:
  436. if (reservationItemServicesIDs.Contains(usluga.SifraUsluga))
  437. {
  438. listSelectedServices.Add(usluga);
  439. dictNumberOfPassengersOnService[usluga.SifraUsluga] = 1;
  440. }
  441. break;
  442. case VrsteUslugaEnum.ObavezneUsluge:
  443. case VrsteUslugaEnum.Akcije:
  444. case VrsteUslugaEnum.PosebnePonude:
  445. case VrsteUslugaEnum.Popusti:
  446. if (usluga.OptionalSpecialOffer && reservationItemServicesIDs.Contains(usluga.SifraUsluga))
  447. dictNumberOfPassengersOnService[usluga.SifraUsluga] = reservationItem.ListaGostiju.IsNotNullOrEmpty() ? reservationItem.ListaGostiju.Count : 1;
  448. listSelectedServices.Add(usluga);
  449. break;
  450. }
  451. }
  452.  
  453. /*************** CREATE SELLING PRICE SERVICES/DETAILS FOR ADDITIONAL SERVICES PER PASSENGER (listaOdabranihUsluga) ******************/
  454. foreach (var passengerPerService in dictSelectedServices)
  455. {
  456. foreach (var serviceFromList in listAdditionalServicesSupplementsAndReductions)
  457. {
  458. if (serviceFromList.SifraUsluga != passengerPerService.Key)
  459. continue;
  460.  
  461. // Skip adding service that is already in list.
  462. var isServiceInList = listSelectedServices.Any(x => x.SifraUsluga == serviceFromList.SifraUsluga);
  463. if (!isServiceInList)
  464. listSelectedServices.Add(serviceFromList);
  465.  
  466. // Add number of passengers on each service to dictionary.
  467. dictNumberOfPassengersOnService[serviceFromList.SifraUsluga] = passengerPerService.Value.Count;
  468. }
  469. }
  470.  
  471. // Get new percentage only if payment method exist on reservation.
  472. var newPercentageSupplement = reservation.NacinPlacanjaVelikaRezervacija != null ? reservation.NacinPlacanjaVelikaRezervacija.PostotakNadoplata : 0.0;
  473.  
  474. reservationItem.NacinObracunaKolicine = Postavke.NacinObracunaKolicineNaRezervaciji;
  475.  
  476. var reservationItemCalculationRQ = new ReservationItemCalculationRQ
  477. {
  478. ReservationItem = reservationItem,
  479. LanguageID = languageID,
  480. ListSelectedServices = calculationSelectedServices.Select(svc => svc.Clone() as Usluga).ToList(),
  481. ListSelectedServicesAffiliate = listSelectedServicesAffiliate.Select(svc => svc.Clone() as Usluga).ToList(),
  482. DictNumberOfPassengersOnService = dictServicesPerPassenger,
  483. ExchangeRate = exchangeRate,
  484. NewPercentageSupplement = newPercentageSupplement,
  485. Capacity = unit.Kapacitet,
  486. DictPassengersOnServices = dictSelectedServices,
  487. PricingPolicyPreloadData = preloadData,
  488. Connection = connection
  489. };
  490.  
  491. var response = _reservationItemService.CalculateReservationItemPrice(reservationItemCalculationRQ);
  492.  
  493. if (response.Status.StatusCode != ReservationItemCalculationStatusEnum.OK
  494. && request.SkipUnavailableItems)
  495. {
  496. var unavailableReservationItemDTO = new UnavailableReservationItemDTO
  497. {
  498. ReservationItem = reservationItem,
  499. Status = new Status
  500. {
  501. Description = response.Status.ErrorMessage,
  502. Code = StatusCode.Error
  503. }
  504. };
  505.  
  506. reservationCalculationDTO.UnavailableReservationItems.Add(unavailableReservationItemDTO);
  507. reservation.ListaMalihRezervacija.Remove(reservationItem);
  508. continue;
  509. }
  510.  
  511. #endregion
  512.  
  513. var infantAge = _reservationItemService.CalculateInfantAge(reservationItem);
  514.  
  515. reservationItem.ListaGostiju.Modify(x => x.SetAgeRelatedProperties(reservationItem.PocetakRezervacija, reservationItem.KrajRezervacija, infantAge));
  516.  
  517. /// Status update
  518. var errorMessage = string.Empty;
  519. var isCongress = false;
  520.  
  521. /// This method is called to check unit availability and possibly downgrade reservation status (if unit is not available)
  522. /// This way, after running it for all items we get best possible reservation status
  523. /// Calling this method is possibly a overkill but after long discussion we agreed this is the be choice atm.
  524. /// We're interested only in availability and status changes so other functionality of this method is ignored.
  525. var isAvailable = VelikaRezervacija.CheckAvailabilityAndCalculatePrices(
  526. reservation,
  527. ref errorMessage,
  528. false,
  529. NaTrzistu.NijeBitno,
  530. ref isCongress,
  531. languageID,
  532. paymentMethod,
  533. exchangeRate,
  534. ref reservationStatus,
  535. reservationStatus,
  536. dictCapacityUnits,
  537. ref waitingList,
  538. reservationItem,
  539. true,
  540. connection,
  541. pricingPolicyPreloadData: preloadData);
  542.  
  543. if (!isAvailable && request.SkipUnavailableItems)
  544. {
  545. var unavailableReservationItemDTO = new UnavailableReservationItemDTO
  546. {
  547. ReservationItem = reservationItem,
  548. Status = new Status
  549. {
  550. Description = OnlineBooking.porukaSmjestajZauzet,
  551. Code = StatusCode.Error
  552. }
  553. };
  554.  
  555. reservationCalculationDTO.UnavailableReservationItems.Add(unavailableReservationItemDTO);
  556. reservation.ListaMalihRezervacija.Remove(reservationItem);
  557. continue;
  558. }
  559.  
  560. if (!string.IsNullOrWhiteSpace(errorMessage))
  561. {
  562. if (!request.SkipUnavailableItems)
  563. {
  564. priceCalculationItemStatus.Code = StatusCode.Error;
  565. priceCalculationItemStatus.Description = string.Format("{0}{1}", priceCalculationItemStatus.Description, errorMessage);
  566. }
  567. else
  568. {
  569. var unavailableReservationItemDTO = new UnavailableReservationItemDTO
  570. {
  571. ReservationItem = reservationItem,
  572. Status = new Status
  573. {
  574. Description = errorMessage,
  575. Code = StatusCode.Error
  576. }
  577. };
  578.  
  579. reservationCalculationDTO.UnavailableReservationItems.Add(unavailableReservationItemDTO);
  580. reservation.ListaMalihRezervacija.Remove(reservationItem);
  581. continue;
  582. }
  583. }
  584.  
  585. try
  586. {
  587. // Check if daily capacities are available
  588. Rezervacija.GetDailyCapacityOccupancies(reservationItem, throwWhenUnavaiLable: true, connection: connection);
  589. }
  590. catch (CapacityException cex)
  591. {
  592. if (request.SkipUnavailableItems)
  593. {
  594. var unavailableReservationItemDTO = new UnavailableReservationItemDTO
  595. {
  596. ReservationItem = reservationItem,
  597. Status = new Status
  598. {
  599. Description = cex.Message,
  600. Code = StatusCode.Error
  601. }
  602. };
  603.  
  604. reservationCalculationDTO.UnavailableReservationItems.Add(unavailableReservationItemDTO);
  605. reservation.ListaMalihRezervacija.Remove(reservationItem);
  606. continue;
  607. }
  608.  
  609. throw;
  610. }
  611.  
  612. ValidatePassengerList(reservationItem, reservationCalculationDTO, priceCalculationItemStatus, infantAge, connection);
  613.  
  614. if (priceCalculationItemStatus.Code == StatusCode.Error)
  615. {
  616. if (!request.SkipUnavailableItems)
  617. {
  618. priceCalculationItemStatus.Code = StatusCode.Error;
  619. priceCalculationItemStatus.Description = string.Format("{0}{1}", priceCalculationItemStatus.Description, errorMessage);
  620.  
  621. reservationCalculationDTO.ErrorMessage = string.Format("{0}{1}", reservationCalculationDTO.ErrorMessage, errorMessage);
  622. }
  623. else
  624. {
  625. var unavailableReservationItemDTO = new UnavailableReservationItemDTO
  626. {
  627. ReservationItem = reservationItem,
  628. Status = new Status
  629. {
  630. Description = errorMessage,
  631. Code = StatusCode.Error
  632. }
  633. };
  634.  
  635. reservationCalculationDTO.UnavailableReservationItems.Add(unavailableReservationItemDTO);
  636. reservation.ListaMalihRezervacija.Remove(reservationItem);
  637. continue;
  638. }
  639. }
  640. }
  641.  
  642. reservationItem.CancellationData = _cancellationPolicyService.CalculateCancellationPolicyForReservationItem(reservationItem,
  643. reservation.ValutaRezervacija.SifraValuta,
  644. customer.SifraTvrtka);
  645. }
  646.  
  647. reservation.Status = waitingList ? StatusVelikaRezervacijaEnum.NaCekanju : reservationStatus;
  648. }
  649.  
  650. // Create ad-hoc reservation items.
  651. if (request.AdHocReservationItems.IsNotNullOrEmpty())
  652. {
  653. // If there is at least one ad-hoc item, the status of whole reservation is set to Inquiry.
  654. reservation.Status = StatusVelikaRezervacijaEnum.Upit;
  655.  
  656. foreach (var adHocItem in request.AdHocReservationItems)
  657. {
  658. var passengers = adHocItem.Passengers.IsNotNullOrEmpty() ? adHocItem.Passengers.Select(x => MapPassengerToDTO(x)).ToList() : new List<PassengerSaveDTO>();
  659. var services = adHocItem.SelectedServices.IsNotNullOrEmpty() ? adHocItem.SelectedServices.Select(x => MapServiceToDTO(x)).ToList() : new List<AdHocServiceSaveDTO>();
  660. var adHocItemDTO = new AdHocReservationItemSaveDTO
  661. {
  662. ReservationStartDate = adHocItem.StartDate,
  663. ReservationEndDate = adHocItem.EndDate,
  664. ReservationItemOrder = adHocItem.ReservationItemOrder,
  665. Passengers = passengers,
  666. LanguageID = languageID,
  667. AdHocServices = services,
  668. AdHocName = adHocItem.AdHocItemName,
  669. AdditionalComment = adHocItem.AdditionalComment,
  670. VoucherReferenceNumber = adHocItem.VoucherReferenceNumber
  671. };
  672.  
  673. var adHocReservationItem = _reservationItemService.CreateAdHocReservationItem(adHocItemDTO, connection: connection);
  674.  
  675. if (adHocItem.DestinationID > 0)
  676. {
  677. adHocReservationItem.Destinacija = new Destinacija { SifraDestinacija = adHocItem.DestinationID.Value };
  678. }
  679. adHocReservationItem.BranchOffice = branchOffice;
  680.  
  681. reservation.ListaMalihRezervacija.Add(adHocReservationItem);
  682. }
  683. }
  684.  
  685. // No need for fallback because if the reservation department isn't explicitly set, the system will set it to default department
  686. if (request.DepartmentID > 0)
  687. {
  688. var department = Odjeljenje.GetDepartmentByID(request.DepartmentID.Value, connection: connection);
  689.  
  690. if (department != null)
  691. {
  692. reservation.DepartmentID = request.DepartmentID.Value;
  693. reservation.ListaMalihRezervacija.Modify(x => x.Odjeljenje = department);
  694. }
  695. }
  696.  
  697. foreach (var reservationItem in reservation.ListaMalihRezervacija)
  698. {
  699. if (reservationItem.JedinicaDR == null || !reservationItem.JedinicaDR.IsTransferOrFlight)
  700. {
  701. continue;
  702. }
  703.  
  704. reservationItem.JedinicaDR.PopuniListuDestinacija(languageID, connection: connection);
  705. }
  706.  
  707. _dynamicPackageService.RewriteSellingPricesWithDynamicPackagePrices(reservation.ListaMalihRezervacija);
  708.  
  709. reservationCalculationDTO.Reservation = reservation;
  710. reservationCalculationDTO.DictionaryReservationItemStatuses = dictReservationItemStatuses;
  711.  
  712. return reservationCalculationDTO;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement