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
|
using Costasdev.Busurbano.Backend.Configuration;
using Costasdev.Busurbano.Backend.Services.Providers;
using Costasdev.Busurbano.Backend.Types.Planner;
using Microsoft.Extensions.Options;
namespace Costasdev.Busurbano.Backend.Services;
public record FareResult(decimal CashFareEuro, bool CashFareIsTotal, decimal CardFareEuro, bool CardFareIsTotal);
public class FareService
{
private readonly AppConfiguration _config;
private readonly XuntaFareProvider _xuntaFareProvider;
private readonly ILogger<FareService> _logger;
private const decimal VitrasaCashFare = 1.63M;
private const decimal VitrasaCardFare = 0.67M;
private const decimal CorunaCashFare = 1.30M;
private const decimal CorunaCardFare = 0.45M;
private const decimal SantiagoCashFare = 1.00M;
private const decimal SantiagoCardFare = 0.36M;
public FareService(
IOptions<AppConfiguration> config,
XuntaFareProvider xuntaFareProvider,
ILogger<FareService> logger
)
{
_config = config.Value;
_xuntaFareProvider = xuntaFareProvider;
_logger = logger;
}
public FareResult CalculateFare(IEnumerable<Leg> legs)
{
var transitLegs = legs
.Where(l => l.Mode != null && !l.Mode.Equals("WALK", StringComparison.CurrentCultureIgnoreCase))
.ToList();
if (!transitLegs.Any())
{
return new FareResult(0, true, 0, true);
}
var cashResult = CalculateCashTotal(transitLegs);
var cardResult = CalculateCardTotal(transitLegs);
return new FareResult(
cashResult.Item1, cashResult.Item2,
cardResult.Item1, cardResult.Item2
);
}
private (decimal, bool) CalculateCashTotal(IEnumerable<Leg> legs)
{
decimal total = 0L;
bool allLegsProcessed = true;
foreach (var leg in legs)
{
switch (leg.FeedId)
{
case "santiago":
total += SantiagoCashFare;
break;
case "coruna":
total += CorunaCashFare;
break;
case "vitrasa":
total += VitrasaCashFare;
break;
case "xunta":
// TODO: Handle potentiall blow-ups
if (leg.From is not { ZoneId: not null })
{
_logger.LogInformation("Ignored fare calculation for leg without From ZoneId. {FromStop}", leg.From?.StopId);
}
if (leg.To is not { ZoneId: not null })
{
_logger.LogInformation("Ignored fare calculation for leg without To ZoneId. {ToStop}", leg.To?.StopId);
}
total += _xuntaFareProvider.GetPrice(leg.From!.ZoneId!, leg.To!.ZoneId!)!.PriceCash;
break;
default:
allLegsProcessed = false;
_logger.LogWarning("Unknown FeedId: {FeedId}", leg.FeedId);
break;
}
}
return (total, allLegsProcessed);
}
private (decimal, bool) CalculateCardTotal(IEnumerable<Leg> legs)
{
List<TicketPurchased> wallet = [];
decimal totalCost = 0;
bool allLegsProcessed = true;
foreach (var leg in legs)
{
int maxMinutes;
int maxUsages;
string? metroArea = null;
decimal initialFare = 0;
switch (leg.FeedId)
{
case "vitrasa":
maxMinutes = 45;
maxUsages = 3;
initialFare = VitrasaCardFare;
break;
case "coruna":
maxMinutes = 45;
maxUsages = 2;
initialFare = CorunaCardFare;
break;
case "santiago":
maxMinutes = 60;
maxUsages = 2;
initialFare = SantiagoCardFare;
break;
case "xunta":
if (leg.From?.ZoneId == null || leg.To?.ZoneId == null)
{
_logger.LogWarning("Missing ZoneId for Xunta leg. From: {From}, To: {To}", leg.From?.StopId, leg.To?.StopId);
continue;
}
var priceRecord = _xuntaFareProvider.GetPrice(leg.From.ZoneId, leg.To.ZoneId);
if (priceRecord == null)
{
_logger.LogWarning("No price record found for Xunta leg from {From} to {To}", leg.From.ZoneId, leg.To.ZoneId);
continue;
}
metroArea = priceRecord.MetroArea;
initialFare = priceRecord.PriceCard;
maxMinutes = 60;
maxUsages = (metroArea != null && metroArea.StartsWith("ATM", StringComparison.OrdinalIgnoreCase)) ? 3 : 1;
break;
default:
_logger.LogWarning("Unknown FeedId: {FeedId}", leg.FeedId);
allLegsProcessed = false;
continue;
}
var validTicket = wallet.FirstOrDefault(t => t.FeedId == leg.FeedId && t.IsValid(leg.StartTime, maxMinutes, maxUsages));
if (validTicket != null)
{
if (leg.FeedId == "xunta" && maxUsages > 1) // ATM upgrade logic
{
var upgradeRecord = _xuntaFareProvider.GetPrice(validTicket.StartZone, leg.To!.ZoneId!);
if (upgradeRecord != null)
{
decimal upgradeCost = Math.Max(0, upgradeRecord.PriceCard - validTicket.TotalPaid);
totalCost += upgradeCost;
validTicket.TotalPaid += upgradeCost;
validTicket.UsedTimes++;
_logger.LogDebug("Xunta ATM upgrade: added {Cost}€, total paid for ticket: {TotalPaid}€", upgradeCost, validTicket.TotalPaid);
}
else
{
// Fallback: treat as new ticket if upgrade path not found
totalCost += initialFare;
wallet.Add(new TicketPurchased
{
FeedId = leg.FeedId,
PurchasedAt = leg.StartTime,
MetroArea = metroArea,
StartZone = leg.From!.ZoneId!,
TotalPaid = initialFare
});
}
}
else
{
// Free transfer for city systems or non-ATM Xunta (though non-ATM Xunta has maxUsages=1)
validTicket.UsedTimes++;
_logger.LogDebug("Free transfer for {FeedId}", leg.FeedId);
}
}
else
{
// New ticket
totalCost += initialFare;
wallet.Add(new TicketPurchased
{
FeedId = leg.FeedId!,
PurchasedAt = leg.StartTime,
MetroArea = metroArea,
StartZone = leg.FeedId == "xunta" ? leg.From!.ZoneId! : string.Empty,
TotalPaid = initialFare
});
_logger.LogDebug("New ticket for {FeedId}: {Cost}€", leg.FeedId, initialFare);
}
}
return (totalCost, allLegsProcessed);
}
}
public class TicketPurchased
{
public required string FeedId { get; set; }
public DateTime PurchasedAt { get; set; }
public string? MetroArea { get; set; }
public required string StartZone { get; set; }
public int UsedTimes = 1;
public decimal TotalPaid { get; set; }
public bool IsValid(DateTime startTime, int maxMinutes, int maxUsagesIncluded)
{
return (startTime - PurchasedAt).TotalMinutes <= maxMinutes && UsedTimes < maxUsagesIncluded;
}
}
|