-
-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathTrainCheckinController.php
More file actions
311 lines (277 loc) · 12.7 KB
/
Copy pathTrainCheckinController.php
File metadata and controls
311 lines (277 loc) · 12.7 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
<?php
namespace App\Http\Controllers\Backend\Transport;
use App\Dto\Internal\CheckInRequestDto;
use App\Dto\Internal\CheckinSuccessDto;
use App\Enum\PointReason;
use App\Events\StatusUpdateEvent;
use App\Events\UserCheckedIn;
use App\Exceptions\Checkin\AlreadyCheckedInException;
use App\Exceptions\CheckInCollisionException;
use App\Exceptions\CheckinException;
use App\Exceptions\DistanceDeviationException;
use App\Exceptions\StationNotOnTripException;
use App\Http\Controllers\Backend\Support\LocationController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\StatusController as StatusBackend;
use App\Http\Controllers\TransportController;
use App\Models\Checkin;
use App\Models\Station;
use App\Models\Status;
use App\Models\Stopover;
use App\Models\Trip;
use App\Models\User;
use App\Notifications\UserJoinedConnection;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;
use PDOException;
abstract class TrainCheckinController extends Controller
{
/**
* @throws StationNotOnTripException
* @throws CheckInCollisionException
* @throws AlreadyCheckedInException
* @throws CheckinException
*/
public static function checkin(CheckInRequestDto $dto, ?User $checkedInBy = null): CheckinSuccessDto {
if ($dto->departure->isAfter($dto->arrival)) {
throw new CheckinException('Departure time must be before arrival time');
}
try {
DB::beginTransaction();
$status = StatusBackend::createStatus(
user: $dto->user,
business: $dto->travelReason,
visibility: $dto->statusVisibility,
body: $dto->body,
event: $dto->event
);
// Add hidden users if specified
if (!empty($dto->hiddenUserIds)) {
foreach ($dto->hiddenUserIds as $userId) {
\App\Models\StatusHiddenUser::create([
'status_id' => $status->id,
'user_id' => $userId,
]);
}
}
$checkinResponse = self::createCheckin(
status: $status,
trip: $dto->trip,
origin: $dto->origin,
destination: $dto->destination,
departure: $dto->departure,
arrival: $dto->arrival,
force: $dto->forceFlag,
checkedInBy: $checkedInBy
);
UserCheckedIn::dispatch(
$status,
$dto->postOnMastodonFlag && $dto->user->socialProfile?->mastodon_id !== null,
$dto->chainFlag
);
DB::commit();
return $checkinResponse;
} catch (PDOException $exception) {
DB::rollBack();
if ((int) $exception->getCode() === 23000) { // Integrity constraint violation: Duplicate entry
throw new AlreadyCheckedInException();
}
throw $exception; // Other scenarios are not handled
} catch (Exception $exception) {
DB::rollBack();
throw $exception;
}
}
/**
* @throws StationNotOnTripException
* @throws CheckInCollisionException
* @throws ModelNotFoundException
* @throws AlreadyCheckedInException
*/
private static function createCheckin(
Status $status,
Trip $trip,
Station $origin,
Station $destination,
Carbon $departure,
Carbon $arrival,
bool $force = false,
?User $checkedInBy = null
): CheckinSuccessDto {
$trip->load('stopovers');
//Note: Compare with ->format because of timezone differences!
$firstStop = $trip->stopovers->where('train_station_id', $origin->id)
->where('departure_planned', $departure)
->first();
$lastStop = $trip->stopovers->where('train_station_id', $destination->id)
->where('arrival_planned', $arrival)
->first();
// In some rare occasions, the departure time of the origin station has a different timezone
// than the first stopover. In this case, we need to find it by comparing the departure time
// in a localtime string format.
if (empty($firstStop)) {
$firstStops = $trip->stopovers->where('train_station_id', $origin->id);
if ($firstStops->count() > 1) {
$firstStop = $firstStops->filter(function(Stopover $stopover) use ($departure) {
return $stopover->departure_planned->format('H:i') === $departure->format('H:i');
})->first();
} else {
$firstStop = $firstStops->first();
}
}
if (empty($firstStop) || empty($lastStop)) {
throw new StationNotOnTripException(
origin: $origin,
destination: $destination,
departure: $departure,
arrival: $arrival,
trip: $trip
);
}
$overlapping = TransportController::getOverlappingCheckIns(
user: $status->user,
start: $firstStop->departure,
end: $lastStop->arrival
);
if (!$force && $overlapping->count() > 0) {
throw new CheckInCollisionException($overlapping->first());
}
$distance = (new LocationController($trip, $firstStop, $lastStop))->calculateDistance();
$pointCalculation = PointsCalculationController::calculatePoints(
distanceInMeter: $distance,
hafasTravelType: $trip->category,
departure: $firstStop->departure,
arrival: $lastStop->arrival,
tripSource: $trip->source,
forceCheckin: $force,
);
try {
/** @var Checkin $checkin */
$checkin = Checkin::create([
'status_id' => $status->id,
'user_id' => $status->user_id,
'trip_id' => $trip->trip_id,
'origin_stopover_id' => $firstStop->id,
'destination_stopover_id' => $lastStop->id,
'distance' => $distance,
'points' => $pointCalculation->points,
'departure' => $firstStop->departure_planned, //@todo: deprecated - use origin_stopover_id instead
'arrival' => $lastStop->arrival_planned //@todo: deprecated - use destination_stopover_id instead
]);
$alsoOnThisConnection = $checkin->alsoOnThisConnection;
foreach ($alsoOnThisConnection as $otherStatus) {
if ($otherStatus?->user && $otherStatus->user->can('view', $status)) {
if ($checkedInBy?->id === $otherStatus->user->id || $otherStatus->user->id === $status->user_id) {
// don't notify the user about their own checkin
continue;
}
$otherStatus->user->notify(new UserJoinedConnection($status));
}
}
return new CheckinSuccessDto($status, $pointCalculation, $alsoOnThisConnection);
} catch (PDOException $exception) {
if ($exception->getCode() === 23000) { // Integrity constraint violation: Duplicate entry
throw new AlreadyCheckedInException();
}
throw $exception; // Other scenarios are not handled, so rethrow the exception
}
}
public static function changeDestination(
Checkin $checkin,
Stopover $newDestinationStopover
): PointReason {
if ($newDestinationStopover->arrival_planned->isBefore($checkin->originStopover->arrival_planned)
|| $newDestinationStopover->is($checkin->originStopover)
|| !$checkin->trip->stopovers->contains('id', $newDestinationStopover->id)
) {
throw new InvalidArgumentException();
}
$newDistance = (new LocationController($checkin->trip, $checkin->originStopover, $newDestinationStopover))
->calculateDistance();
$pointsResource = PointsCalculationController::calculatePoints(
distanceInMeter: $newDistance,
hafasTravelType: $checkin->trip->category,
departure: $checkin->originStopover->departure,
arrival: $newDestinationStopover->arrival,
tripSource: $checkin->trip->source
);
$checkin->update([
'arrival' => $newDestinationStopover->arrival_planned,
'destination_stopover_id' => $newDestinationStopover->id,
'distance' => $newDistance,
'points' => $pointsResource->points,
]);
$checkin->refresh();
StatusUpdateEvent::dispatch($checkin->status);
return $pointsResource->reason;
}
/**
* @throws DistanceDeviationException
*/
public static function refreshDistanceAndPoints(Status $status, bool $resetPolyline = false): void {
$checkin = $status->checkin;
if ($resetPolyline) {
$checkin->trip->update(['polyline_id' => null]);
}
$firstStop = $checkin->originStopover;
$lastStop = $checkin->destinationStopover;
$distance = (new LocationController(
trip: $checkin->trip,
origin: $firstStop,
destination: $lastStop
))->calculateDistance();
$oldPoints = $checkin->points;
$oldDistance = $checkin->distance;
$percentage = config('trwl.distance_deviation_threshold_percent', 15) / 100;
$upperLimit = $oldDistance * (1 + $percentage);
$lowerLimit = $oldDistance * (1 - $percentage);
if ($distance === 0 || ($oldDistance !== 0 && ($distance > $upperLimit || $distance < $lowerLimit))) {
Log::debug(sprintf(
'Distance deviation for status #%d is greater than %d percent. Original: %d, new: %d',
$status->id,
$percentage * 100,
$oldDistance,
$distance
));
throw new DistanceDeviationException();
}
$pointsResource = PointsCalculationController::calculatePoints(
distanceInMeter: $distance,
hafasTravelType: $checkin->trip->category,
departure: $firstStop->departure,
arrival: $lastStop->arrival,
tripSource: $checkin->trip->source,
timestampOfView: $status->created_at
);
$payload = [
'distance' => $distance,
'points' => $pointsResource->points,
];
$checkin->update($payload);
Log::debug(sprintf('Updated distance and points of status #%d: Old: %dm %dp New: %dm %dp',
$status->id,
$oldDistance,
$oldPoints,
$distance,
$pointsResource->points,
));
}
public static function calculateCheckinDuration(Checkin $checkin, bool $update = true): int {
$departure = $checkin->manual_departure ?? $checkin->originStopover->departure ?? $checkin->departure;
$arrival = $checkin->manual_arrival ?? $checkin->destinationStopover->arrival ?? $checkin->arrival;
$duration = $departure->diffInMinutes($arrival);
if ($duration < 0) {
// diffInMinutes() returns negative minutes, if the arrival is before the departure.
$duration = 0;
}
//don't use eloquent here, because it would trigger the observer (and this function) again
if ($update) {
DB::table('train_checkins')->where('id', $checkin->id)->update(['duration' => $duration]);
}
return $duration;
}
}