-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathShoppingCartWorkflow.workflow.cs
More file actions
64 lines (54 loc) · 1.96 KB
/
ShoppingCartWorkflow.workflow.cs
File metadata and controls
64 lines (54 loc) · 1.96 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
namespace TemporalioSamples.UpdateWithStartLazyInit;
using Temporalio.Exceptions;
using Temporalio.Workflows;
[Workflow]
public class ShoppingCartWorkflow
{
public record FinalizedOrder(
string Id,
IReadOnlyCollection<PricedItem> Items,
decimal Total)
{
public override string ToString()
{
var items = string.Join(",", Items.Select(i =>
$"{{ sku: {i.Item.Sku}, quantity: {i.Item.Quantity}, price: {i.Price} }}"));
return $"order id: {Id}, items: [{items}], total: {Total}";
}
}
public record PricedItem(ShoppingCartItem Item, decimal Price);
private readonly List<PricedItem> items = new();
private bool orderSubmitted;
[WorkflowRun]
public async Task<FinalizedOrder> RunAsync()
{
// Wait for order submission and then return finalized order
await Workflow.WaitConditionAsync(() => Workflow.AllHandlersFinished && orderSubmitted);
return new(Workflow.Info.WorkflowId, items, Total);
}
[WorkflowQuery]
public decimal Total => items.Sum(item => item.Price);
[WorkflowUpdateValidator(nameof(AddItemAsync))]
public void ValidateAddItem(ShoppingCartItem item)
{
if (orderSubmitted)
{
throw new ApplicationFailureException("Order already submitted");
}
}
[WorkflowUpdate]
public async Task<decimal> AddItemAsync(ShoppingCartItem item)
{
// Get price or fail
var maybePrice = await Workflow.ExecuteActivityAsync(
() => Activities.GetPriceAsync(item),
new() { ScheduleToCloseTimeout = TimeSpan.FromMinutes(5) });
var price = maybePrice ??
throw new ApplicationFailureException($"Item unavailable: {item}", "ItemUnavailable");
// Add item and return new total
items.Add(new(item, price));
return Total;
}
[WorkflowSignal]
public async Task CheckoutAsync() => orderSubmitted = true;
}