-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSessionStore.cs
More file actions
690 lines (644 loc) · 40.4 KB
/
SessionStore.cs
File metadata and controls
690 lines (644 loc) · 40.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
using OpenActive.NET;
using System;
using System.Collections.Generic;
using System.Linq;
using OpenActive.DatasetSite.NET;
using OpenActive.Server.NET.StoreBooking;
using OpenActive.Server.NET.OpenBookingHelper;
using OpenActive.FakeDatabase.NET;
using RequiredStatusType = OpenActive.FakeDatabase.NET.RequiredStatusType;
using System.Threading.Tasks;
using BookingSystem.AspNetCore.Helpers;
namespace BookingSystem
{
class SessionStore : OpportunityStore<SessionOpportunity, OrderTransaction, OrderStateContext>
{
private readonly AppSettings _appSettings;
private readonly FakeBookingSystem _fakeBookingSystem;
// Example constructor that can set state from EngineConfig. This is not required for an actual implementation.
public SessionStore(AppSettings appSettings, FakeBookingSystem fakeBookingSystem)
{
_appSettings = appSettings;
_fakeBookingSystem = fakeBookingSystem;
}
Random rnd = new Random();
protected override async Task<SessionOpportunity> CreateOpportunityWithinTestDataset(
string testDatasetIdentifier,
OpportunityType opportunityType,
TestOpportunityCriteriaEnumeration criteria,
TestOpenBookingFlowEnumeration openBookingFlow,
SimpleIdComponents seller)
{
if (!_appSettings.FeatureFlags.SingleSeller && !seller.IdLong.HasValue)
throw new OpenBookingException(new OpenBookingError(), "Seller must have an ID in Multiple Seller Mode");
long? sellerId = _appSettings.FeatureFlags.SingleSeller ? null : seller.IdLong;
var requiresApproval = openBookingFlow == TestOpenBookingFlowEnumeration.OpenBookingApprovalFlow;
switch (opportunityType)
{
case OpportunityType.ScheduledSession:
int classId, occurrenceId;
switch (criteria)
{
case TestOpportunityCriteriaEnumeration.TestOpportunityBookable:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Event",
rnd.Next(2) == 0 ? 0M : 14.99M,
10,
requiresApproval);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableCancellable:
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableNonFree:
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableUsingPayment:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event",
14.99M,
10,
requiresApproval);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableWithinValidFromBeforeStartDate:
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableOutsideValidFromBeforeStartDate:
{
var isValid = criteria == TestOpportunityCriteriaEnumeration.TestOpportunityBookableWithinValidFromBeforeStartDate;
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
$"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event {(isValid ? "Within" : "Outside")} Window",
14.99M,
10,
requiresApproval,
validFromStartDate: isValid);
}
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableCancellableWithinWindow:
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableCancellableOutsideWindow:
{
var isValid = criteria == TestOpportunityCriteriaEnumeration.TestOpportunityBookableCancellableWithinWindow;
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
$"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event {(isValid ? "Within" : "Outside")} Cancellation Window",
14.99M,
10,
requiresApproval,
latestCancellationBeforeStartDate: isValid);
}
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableNonFreePrepaymentOptional:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event Prepayment Optional",
10M,
10,
requiresApproval,
prepayment: RequiredStatusType.Optional);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableNonFreePrepaymentUnavailable:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event Prepayment Unavailable",
10M,
10,
requiresApproval,
prepayment: RequiredStatusType.Unavailable);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableNonFreePrepaymentRequired:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event Prepayment Required",
10M,
10,
requiresApproval,
prepayment: RequiredStatusType.Required);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableFree:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Free Event",
0M,
10,
requiresApproval);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableNoSpaces:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Free Event No Spaces",
14.99M,
0,
requiresApproval);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableFiveSpaces:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Free Event Five Spaces",
14.99M,
5,
requiresApproval);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableOneSpace:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Free Event One Space",
14.99M,
1,
requiresApproval);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableNonFreeTaxNet:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
2,
"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event Tax Net",
14.99M,
10,
requiresApproval);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableNonFreeTaxGross:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
1,
"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event Tax Gross",
14.99M,
10,
requiresApproval);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableSellerTermsOfService:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
1,
"[OPEN BOOKING API TEST INTERFACE] Bookable Event With Seller Terms Of Service",
14.99M,
10,
requiresApproval);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableAttendeeDetails:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event That Requires Attendee Details",
10M,
10,
requiresApproval,
requiresAttendeeValidation: true);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableAdditionalDetails:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event That Requires Additional Details",
10M,
10,
requiresApproval,
requiresAdditionalDetails: true);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityOnlineBookable:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Virtual Event",
10M,
10,
requiresApproval,
isOnlineOrMixedAttendanceMode: true);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityOfflineBookable:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Offline Event",
10M,
10,
requiresApproval,
isOnlineOrMixedAttendanceMode: false);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableWithNegotiation:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Paid Event That Allows Proposal Amendment",
10M,
10,
requiresApproval,
allowProposalAmendment: true);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableNotCancellable:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Paid That Does Not Allow Full Refund",
10M,
10,
requiresApproval,
allowCustomerCancellationFullRefund: false);
break;
case TestOpportunityCriteriaEnumeration.TestOpportunityBookableInPast:
(classId, occurrenceId) = await _fakeBookingSystem.Database.AddClass(
testDatasetIdentifier,
sellerId,
"[OPEN BOOKING API TEST INTERFACE] Bookable Sesssion in the Past",
10M,
10,
requiresApproval,
inPast: true);
break;
default:
throw new OpenBookingException(new OpenBookingError(), "testOpportunityCriteria value not supported");
}
return new SessionOpportunity
{
OpportunityType = opportunityType,
SessionSeriesId = classId,
ScheduledSessionId = occurrenceId
};
default:
throw new OpenBookingException(new OpenBookingError(), "Opportunity Type not supported");
}
}
protected override async Task DeleteTestDataset(string testDatasetIdentifier)
{
await _fakeBookingSystem.Database.DeleteTestClassesFromDataset(testDatasetIdentifier);
}
protected override async Task TriggerTestAction(OpenBookingSimulateAction simulateAction, SessionOpportunity idComponents)
{
switch (simulateAction)
{
case ChangeOfLogisticsTimeSimulateAction _:
if (!await _fakeBookingSystem.Database.UpdateScheduledSessionStartAndEndTimeByPeriodInMins(idComponents.ScheduledSessionId.Value, 60))
{
throw new OpenBookingException(new UnknownOpportunityError());
}
return;
case ChangeOfLogisticsNameSimulateAction _:
if (!await _fakeBookingSystem.Database.UpdateClassTitle(idComponents.ScheduledSessionId.Value, "Updated Class Title"))
{
throw new OpenBookingException(new UnknownOpportunityError());
}
return;
case ChangeOfLogisticsLocationSimulateAction _:
if (!await _fakeBookingSystem.Database.UpdateSessionSeriesLocationPlaceId(idComponents.ScheduledSessionId.Value))
{
throw new OpenBookingException(new UnknownOpportunityError());
}
return;
default:
throw new NotImplementedException();
}
}
// Similar to the RPDE logic, this needs to render and return an new hypothetical OrderItem from the database based on the supplied opportunity IDs
protected override async Task GetOrderItems(List<OrderItemContext<SessionOpportunity>> orderItemContexts, StoreBookingFlowContext flowContext, OrderStateContext stateContext)
{
// Note the implementation of this method must also check that this OrderItem is from the Seller specified by context.SellerId (this is not required if using a Single Seller)
// Additionally this method must check that there are enough spaces in each entry
// Response OrderItems must be updated into supplied orderItemContexts (including duplicates for multi-party booking)
var query = await Task.WhenAll(orderItemContexts.Select(async orderItemContext =>
{
var getOccurrenceResultAndRows = await _fakeBookingSystem.Database.GetOccurrenceAndBookedOrderItemInfoByOccurrenceId(flowContext.OrderId.uuid, orderItemContext.RequestBookableOpportunityOfferId.ScheduledSessionId);
var (hasFoundOccurrence, @class, occurrence, bookedOrderItemInfo) = getOccurrenceResultAndRows;
if (hasFoundOccurrence == false)
{
return null;
}
var remainingUsesIncludingOtherLeases = await _fakeBookingSystem.Database.GetNumberOfOtherLeaseForOccurrence(flowContext.OrderId.uuid, orderItemContext.RequestBookableOpportunityOfferId.ScheduledSessionId);
return new
{
OrderItem = new OrderItem
{
// TODO: The static example below should come from the database (which doesn't currently support tax)
// This is because it can be different for each Seller and needs to calculated at the time of booking
UnitTaxSpecification = GetUnitTaxSpecification(flowContext, @class),
AcceptedOffer = new Offer
{
// Note this should always use RenderOfferId with the supplied SessionOpportunity, to take into account inheritance and OfferType
Id = RenderOfferId(orderItemContext.RequestBookableOpportunityOfferId),
Price = @class.Price,
PriceCurrency = "GBP",
LatestCancellationBeforeStartDate = @class.LatestCancellationBeforeStartDate,
OpenBookingPrepayment = _appSettings.FeatureFlags.PrepaymentAlwaysRequired ? null : @class.Prepayment.Convert(),
ValidFromBeforeStartDate = @class.ValidFromBeforeStartDate,
AllowCustomerCancellationFullRefund = @class.AllowCustomerCancellationFullRefund,
},
OrderedItem = new ScheduledSession
{
// Note this should always be driven from the database, with new SessionOpportunity's instantiated
Id = RenderOpportunityId(new SessionOpportunity
{
OpportunityType = OpportunityType.ScheduledSession,
SessionSeriesId = occurrence.ClassId,
ScheduledSessionId = occurrence.Id
}),
SuperEvent = new SessionSeries
{
Id = RenderOpportunityId(new SessionOpportunity
{
OpportunityType = OpportunityType.SessionSeries,
SessionSeriesId = occurrence.ClassId
}),
Name = @class.Title,
Url = new Uri("https://example.com/events/" + occurrence.ClassId),
Location = FeedGenerationHelper.GetPlaceById(@class.PlaceId),
Activity = new List<Concept>
{
new Concept
{
Id = new Uri("https://openactive.io/activity-list#6bdea630-ad22-4e58-98a3-bca26ee3f1da"),
PrefLabel = "Rave Fitness",
InScheme = new Uri("https://openactive.io/activity-list")
}
}
},
StartDate = (DateTimeOffset)occurrence.Start,
EndDate = (DateTimeOffset)occurrence.End,
MaximumAttendeeCapacity = occurrence.TotalSpaces,
// Exclude current Order from the returned lease count
RemainingAttendeeCapacity = occurrence.RemainingSpaces - remainingUsesIncludingOtherLeases
},
Attendee = orderItemContext.RequestOrderItem.Attendee,
AttendeeDetailsRequired = @class.RequiresAttendeeValidation
? new List<PropertyEnumeration>
{
PropertyEnumeration.GivenName,
PropertyEnumeration.FamilyName,
PropertyEnumeration.Email,
PropertyEnumeration.Telephone,
}
: null,
OrderItemIntakeForm = @class.RequiresAdditionalDetails
? PropertyValueSpecificationHelper.HydrateAdditionalDetailsIntoPropertyValueSpecifications(@class.RequiredAdditionalDetails)
: null,
OrderItemIntakeFormResponse = orderItemContext.RequestOrderItem.OrderItemIntakeFormResponse,
},
SellerId = _appSettings.FeatureFlags.SingleSeller ? new SimpleIdComponents() : new SimpleIdComponents { IdLong = @class.SellerId },
@class.RequiresApproval,
BookedOrderItemInfo = bookedOrderItemInfo,
occurrence.RemainingSpaces
};
}));
// Add the response OrderItems to the relevant contexts (note that the context must be updated within this method)
foreach (var (item, ctx) in query.Zip(orderItemContexts, (item, ctx) => (item, ctx)))
{
if (item == null)
{
ctx.SetResponseOrderItemAsSkeleton();
ctx.AddError(new UnknownOpportunityError());
}
else
{
ctx.SetResponseOrderItem(item.OrderItem, item.SellerId, flowContext);
if (item.BookedOrderItemInfo != null)
{
BookedOrderItemHelper.AddPropertiesToBookedOrderItem(ctx, item.BookedOrderItemInfo);
}
if (item.RequiresApproval)
ctx.SetRequiresApproval();
if (item.RemainingSpaces == 0)
ctx.AddError(new OpportunityIsFullError());
// Add validation errors to the OrderItem if either attendee details or additional details are required but not provided
var validationErrors = ctx.ValidateDetails(flowContext.Stage);
if (validationErrors.Count > 0)
ctx.AddErrors(validationErrors);
}
}
}
protected override async ValueTask LeaseOrderItems(
Lease lease, List<OrderItemContext<SessionOpportunity>> orderItemContexts, StoreBookingFlowContext flowContext, OrderStateContext stateContext, OrderTransaction databaseTransaction)
{
// Check that there are no conflicts between the supplied opportunities
// Also take into account spaces requested across OrderItems against total spaces in each opportunity
foreach (var ctxGroup in orderItemContexts.Where(ctx => !ctx.HasErrors).GroupBy(x => x.RequestBookableOpportunityOfferId))
{
// TODO: ENSURE THAT THIS IS CALLED EVERY TIME BY THE STOREBOOKINGENGINE, EVEN WITH ZERO ITEMS
// This will ensure that items can be removed from the Order before the booking is confirmed if all items of that type have been removed from the lease
// Step 1: Get existing lease from database
// Step 2: Compare items in the existing lease to items in the request
// Step 3: Add/remove lease items to match the request
//Dictionary<long, int> existingLease = new Dictionary<long, int>();
// Check that the Opportunity ID and type are as expected for the store
if (ctxGroup.Key.OpportunityType != OpportunityType.ScheduledSession || !ctxGroup.Key.ScheduledSessionId.HasValue)
{
foreach (var ctx in ctxGroup)
{
ctx.AddError(new OpportunityIntractableError(), "Opportunity ID and type are as not expected for the store. Likely a configuration issue with the Booking System.");
}
}
else
{
//var existingOpportunities = existingLease[ctxGroup.Key.ScheduledSessionId.Value];
// Attempt to lease for those with the same IDs, which is atomic
var (result, capacityErrors, capacityLeaseErrors) = await FakeDatabase.LeaseOrderItemsForClassOccurrence(
databaseTransaction.FakeDatabaseTransaction,
flowContext.OrderId.ClientId,
flowContext.SellerId.IdLong ?? null /* Hack to allow this to work in Single Seller mode too */,
flowContext.OrderId.uuid,
ctxGroup.Key.ScheduledSessionId.Value,
ctxGroup.Count());
switch (result)
{
case ReserveOrderItemsResult.Success:
// Do nothing, no errors to add
break;
case ReserveOrderItemsResult.SellerIdMismatch:
foreach (var ctx in ctxGroup)
{
ctx.AddError(new SellerMismatchError(), "An OrderItem SellerID did not match");
}
break;
case ReserveOrderItemsResult.OpportunityNotFound:
foreach (var ctx in ctxGroup)
{
ctx.AddError(new UnableToProcessOrderItemError(), "Opportunity not found");
}
break;
case ReserveOrderItemsResult.OpportunityOfferPairNotBookable:
foreach (var ctx in ctxGroup)
{
ctx.AddError(new OpportunityOfferPairNotBookableError(), "Opportunity not bookable");
}
break;
case ReserveOrderItemsResult.NotEnoughCapacity:
var contexts = ctxGroup.ToArray();
for (var i = contexts.Length - 1; i >= 0; i--)
{
var ctx = contexts[i];
if (capacityErrors > 0)
{
ctx.AddError(new OpportunityHasInsufficientCapacityError());
capacityErrors--;
}
else if (capacityLeaseErrors > 0)
{
ctx.AddError(new OpportunityCapacityIsReservedByLeaseError());
capacityLeaseErrors--;
}
}
break;
default:
foreach (var ctx in ctxGroup)
{
ctx.AddError(new OpportunityIntractableError(), "OrderItem could not be leased for unexpected reasons.");
}
break;
}
}
}
}
// TODO: This should reuse code of LeaseOrderItem to be DRY. Similar logic is also used in ProposeOrderItems as well as
// in LeaseOrderItems, BookOrderItems, and ProposeOrderItems in the SessionStore. The issue for this is: https://github.com/openactive/OpenActive.Server.NET/issues/226
protected override async ValueTask BookOrderItems(List<OrderItemContext<SessionOpportunity>> orderItemContexts, StoreBookingFlowContext flowContext, OrderStateContext stateContext, OrderTransaction databaseTransaction)
{
// Check that there are no conflicts between the supplied opportunities
// Also take into account spaces requested across OrderItems against total spaces in each opportunity
// TODO: ENSURE THAT THIS IS CALLED EVERY TIME BY THE STOREBOOKINGENGINE, EVEN WITH ZERO ITEMS
// This will ensure that items can be removed from the Order before the booking is confirmed if all items of that type have been removed from the lease
// Step 1: Call lease to ensure items are already leased
// Step 2: Set OrderItems to booked
// Step 3: Write attendee and orderItemIntakeFormResponse to the OrderItem records, for inclusion in P later
foreach (var ctxGroup in orderItemContexts.GroupBy(x => x.RequestBookableOpportunityOfferId))
{
// Check that the Opportunity ID and type are as expected for the store
if (ctxGroup.Key.OpportunityType != OpportunityType.ScheduledSession || !ctxGroup.Key.ScheduledSessionId.HasValue)
{
throw new OpenBookingException(new UnableToProcessOrderItemError(), "Opportunity ID and type are as not expected for the SessionStore, during booking");
}
// Attempt to book for those with the same IDs, which is atomic
var (result, bookedOrderItemInfos) = await FakeDatabase.BookOrderItemsForClassOccurrence(
databaseTransaction.FakeDatabaseTransaction,
flowContext.OrderId.ClientId,
flowContext.SellerId.IdLong ?? null /* Hack to allow this to work in Single Seller mode too */,
flowContext.OrderId.uuid,
ctxGroup.Key.ScheduledSessionId.Value,
RenderOpportunityId(ctxGroup.Key),
RenderOfferId(ctxGroup.Key),
ctxGroup.Count(),
false,
ctxGroup
.Select(x =>
x.RequestOrderItem.Attendee == null
? null
: OpenActiveSerializer.Serialize(x.RequestOrderItem.Attendee))
.ToList(),
ctxGroup
.Select(x =>
x.RequestOrderItem.OrderItemIntakeFormResponse == null
? null
: OpenActiveSerializer.SerializeList(x.RequestOrderItem.OrderItemIntakeFormResponse))
.ToList()
);
switch (result)
{
case ReserveOrderItemsResult.Success:
foreach (var (ctx, bookedOrderItemInfo) in ctxGroup.Zip(bookedOrderItemInfos, (ctx, bookedOrderItemInfo) => (ctx, bookedOrderItemInfo)))
{
// Set OrderItemId and access properties for each orderItemContext
ctx.SetOrderItemId(flowContext, bookedOrderItemInfo.OrderItemId);
BookedOrderItemHelper.AddPropertiesToBookedOrderItem(ctx, bookedOrderItemInfo);
// Remove attendee capacity information from the OrderedItem. For more information see: https://github.com/openactive/open-booking-api/issues/156#issuecomment-926643733
BookedOrderItemHelper.RemovePropertiesFromBookedOrderItem(ctx);
}
break;
case ReserveOrderItemsResult.SellerIdMismatch:
throw new OpenBookingException(new SellerMismatchError(), "An OrderItem SellerID did not match");
case ReserveOrderItemsResult.OpportunityNotFound:
throw new OpenBookingException(new UnableToProcessOrderItemError(), "Opportunity not found");
case ReserveOrderItemsResult.NotEnoughCapacity:
throw new OpenBookingException(new OpportunityHasInsufficientCapacityError());
case ReserveOrderItemsResult.OpportunityOfferPairNotBookable:
throw new OpenBookingException(new UnableToProcessOrderItemError(), "Opportunity and offer pair were not bookable");
default:
throw new OpenBookingException(new OrderCreationFailedError(), "Booking failed for an unexpected reason");
}
}
}
// TODO check logic here, it's just been copied from BookOrderItems. Possibly could remove duplication here. Common logic between this, BookOrderItems, and LeaseOrderItems should be pulled out.
protected override async ValueTask ProposeOrderItems(List<OrderItemContext<SessionOpportunity>> orderItemContexts, StoreBookingFlowContext flowContext, OrderStateContext stateContext, OrderTransaction databaseTransaction)
{
// Check that there are no conflicts between the supplied opportunities
// Also take into account spaces requested across OrderItems against total spaces in each opportunity
foreach (var ctxGroup in orderItemContexts.GroupBy(x => x.RequestBookableOpportunityOfferId))
{
// Check that the Opportunity ID and type are as expected for the store
if (ctxGroup.Key.OpportunityType != OpportunityType.ScheduledSession || !ctxGroup.Key.ScheduledSessionId.HasValue)
{
throw new OpenBookingException(new UnableToProcessOrderItemError(), "Opportunity ID and type are as not expected for the SessionStore, during proposal");
}
// Attempt to book for those with the same IDs, which is atomic
var (result, bookedOrderItemInfos) = await FakeDatabase.BookOrderItemsForClassOccurrence(
databaseTransaction.FakeDatabaseTransaction,
flowContext.OrderId.ClientId,
flowContext.SellerId.IdLong ?? null /* Hack to allow this to work in Single Seller mode too */,
flowContext.OrderId.uuid,
ctxGroup.Key.ScheduledSessionId.Value,
RenderOpportunityId(ctxGroup.Key),
RenderOfferId(ctxGroup.Key),
ctxGroup.Count(),
true,
ctxGroup
.Select(x =>
x.RequestOrderItem.Attendee == null
? null
: OpenActiveSerializer.Serialize(x.RequestOrderItem.Attendee))
.ToList(),
ctxGroup
.Select(x =>
x.RequestOrderItem.OrderItemIntakeFormResponse == null
? null
: OpenActiveSerializer.SerializeList(x.RequestOrderItem.OrderItemIntakeFormResponse))
.ToList()
);
switch (result)
{
case ReserveOrderItemsResult.Success:
// Set OrderItemId for each orderItemContext
foreach (var (ctx, bookedOrderItemInfo) in ctxGroup.Zip(bookedOrderItemInfos, (ctx, bookedOrderItemInfo) => (ctx, bookedOrderItemInfo)))
{
ctx.SetOrderItemId(flowContext, bookedOrderItemInfo.OrderItemId);
// Remove attendee capacity information from the OrderedItem. For more information see: https://github.com/openactive/open-booking-api/issues/156#issuecomment-926643733
BookedOrderItemHelper.RemovePropertiesFromBookedOrderItem(ctx);
}
break;
case ReserveOrderItemsResult.SellerIdMismatch:
throw new OpenBookingException(new SellerMismatchError(), "An OrderItem SellerID did not match");
case ReserveOrderItemsResult.OpportunityNotFound:
throw new OpenBookingException(new UnableToProcessOrderItemError(), "Opportunity not found");
case ReserveOrderItemsResult.NotEnoughCapacity:
throw new OpenBookingException(new OpportunityHasInsufficientCapacityError());
case ReserveOrderItemsResult.OpportunityOfferPairNotBookable:
throw new OpenBookingException(new UnableToProcessOrderItemError(), "Opportunity and offer pair were not bookable");
default:
throw new OpenBookingException(new OrderCreationFailedError(), "Booking failed for an unexpected reason");
}
}
}
private List<TaxChargeSpecification> GetUnitTaxSpecification(BookingFlowContext flowContext, ClassTable classes)
{
switch (flowContext.TaxPayeeRelationship)
{
case TaxPayeeRelationship.BusinessToBusiness when _appSettings.Payment.TaxCalculationB2B:
case TaxPayeeRelationship.BusinessToConsumer when _appSettings.Payment.TaxCalculationB2C:
return new List<TaxChargeSpecification>
{
new TaxChargeSpecification
{
Name = "VAT at 20%",
Price = classes.Price * (decimal?)0.2,
PriceCurrency = "GBP",
Rate = (decimal?)0.2
}
};
case TaxPayeeRelationship.BusinessToBusiness when !_appSettings.Payment.TaxCalculationB2B:
case TaxPayeeRelationship.BusinessToConsumer when !_appSettings.Payment.TaxCalculationB2C:
return null;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}