Gán điểm kết thúc của chặng trước làm điểm khởi hành của chặng sau
This commit is contained in:
Vendored
+39
-3
@@ -449,14 +449,47 @@ let RoutingController = class RoutingController {
|
||||
this.prisma = prisma;
|
||||
}
|
||||
async optimize(legId) {
|
||||
const currentLeg = await this.prisma.leg.findUnique({
|
||||
where: { id: legId },
|
||||
});
|
||||
if (!currentLeg)
|
||||
throw new NotFoundException('Không tìm thấy chặng');
|
||||
const locations = await this.prisma.location.findMany({
|
||||
where: { legId },
|
||||
});
|
||||
if (locations.length <= 2)
|
||||
return locations;
|
||||
if (locations.length === 0)
|
||||
return { locations: [], totalDistance: 0 };
|
||||
let startAnchor = null;
|
||||
const prevLeg = await this.prisma.leg.findFirst({
|
||||
where: {
|
||||
tourId: currentLeg.tourId,
|
||||
sequence: currentLeg.sequence - 1
|
||||
},
|
||||
include: { locations: { orderBy: { plannedStart: 'asc' } } }
|
||||
});
|
||||
if (prevLeg?.locations?.length) {
|
||||
startAnchor = prevLeg.locations[prevLeg.locations.length - 1];
|
||||
}
|
||||
if (locations.length <= 2 && !startAnchor)
|
||||
return { locations, totalDistance: 0 };
|
||||
const optimized = [];
|
||||
const unvisited = [...locations];
|
||||
let current = unvisited.sort((a, b) => (a.plannedStart?.getTime() || 0) - (b.plannedStart?.getTime() || 0)).shift();
|
||||
let current;
|
||||
if (startAnchor) {
|
||||
let nearestIdx = 0;
|
||||
let minDist = Infinity;
|
||||
for (let i = 0; i < unvisited.length; i++) {
|
||||
const d = calculateDistance(startAnchor.latitude, startAnchor.longitude, unvisited[i].latitude, unvisited[i].longitude);
|
||||
if (d < minDist) {
|
||||
minDist = d;
|
||||
nearestIdx = i;
|
||||
}
|
||||
}
|
||||
current = unvisited.splice(nearestIdx, 1)[0];
|
||||
}
|
||||
else {
|
||||
current = unvisited.sort((a, b) => (a.plannedStart?.getTime() || 0) - (b.plannedStart?.getTime() || 0)).shift();
|
||||
}
|
||||
optimized.push(current);
|
||||
while (unvisited.length > 0) {
|
||||
let nearestIdx = 0;
|
||||
@@ -472,6 +505,9 @@ let RoutingController = class RoutingController {
|
||||
optimized.push(current);
|
||||
}
|
||||
let totalDistance = 0;
|
||||
if (startAnchor) {
|
||||
totalDistance += calculateDistance(startAnchor.latitude, startAnchor.longitude, optimized[0].latitude, optimized[0].longitude);
|
||||
}
|
||||
for (let i = 0; i < optimized.length - 1; i++) {
|
||||
totalDistance += calculateDistance(optimized[i].latitude, optimized[i].longitude, optimized[i + 1].latitude, optimized[i + 1].longitude);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user