feat: implement route assignment management and sequencing module with interactive data visualization and editing capabilities

This commit is contained in:
2026-08-31 17:56:33 -04:00
parent cd5c57c5ee
commit 9f42175afc
29 changed files with 458 additions and 218 deletions
@@ -5,11 +5,11 @@ import { Router, ActivatedRoute } from '@angular/router';
import { Subscription, Subject } from 'rxjs';
import * as L from 'leaflet';
import 'leaflet.heat';
import { RouteState } from '../../../core/route-state/route';
import { RouteState, UnassignedAssignment } from '../../../core/route-state/route';
import { OrsService } from '../../../core/services/ors.service';
import { RouteAssignedResponse, RouteNoAssignedResponse } from '../../../core/models/route.model';
import { colorForUsuario } from '../../../shared/utils/palette.utils';
import { haversineKm, sequenceRoutes } from '../../../shared/utils/route-sequencing.utils';
import { DailyRouteSummary, haversineKm, sequenceRoutes, summarizeDailyRoutes } from '../../../shared/utils/route-sequencing.utils';
interface MapRoute {
data: RouteAssignedResponse;
@@ -71,7 +71,7 @@ export class RouteOverviewMapComponent implements OnInit, OnDestroy, AfterViewIn
editUnassignedLng = 0;
editUnassignedReason = '';
assignmentUser: Record<string, string> = {};
assignmentDay: Record<string, string> = {};
assignmentDays: Record<string, string[]> = {};
assigningUnassignedId: number | null = null;
unassignedActionError: string | null = null;
reassigningRoute = false;
@@ -94,6 +94,10 @@ export class RouteOverviewMapComponent implements OnInit, OnDestroy, AfterViewIn
return sum.toFixed(0);
}
get dailySummaries(): DailyRouteSummary[] {
return summarizeDailyRoutes(this.filteredRoutes);
}
constructor(
private routeState: RouteState,
private orsService: OrsService,
@@ -517,6 +521,16 @@ export class RouteOverviewMapComponent implements OnInit, OnDestroy, AfterViewIn
this.reassignError = null;
}
moveSelectedVisit(direction: -1 | 1): void {
if (!this.selectedRouteDetail) return;
this.routeState.moveRouteVisit(this.selectedRouteDetail, direction);
}
resetSelectedDayOrder(): void {
if (!this.selectedRouteDetail) return;
this.routeState.resetRouteVisitOrder(this.selectedRouteDetail.json.usuario_id, this.selectedRouteDetail.json.dia);
}
async reassignRoute(): Promise<void> {
const route = this.selectedRouteDetail;
if (!route || !this.reassignUserId || !this.reassignDay || this.reassigningRoute) return;
@@ -540,6 +554,17 @@ export class RouteOverviewMapComponent implements OnInit, OnDestroy, AfterViewIn
const response = results[0] as { geojson?: { features?: { properties?: { summary?: { distance: number; duration: number } } }[] }; error?: string } | undefined;
const summary = response?.geojson?.features?.[0]?.properties?.summary;
if (response?.error || !summary) throw new Error('ORS no devolvió una ruta vial');
const capacity = this.routeState.canAssignToDay(
this.reassignUserId,
this.reassignDay,
Number(route.json.horas_trabajo || route.json.hora_minima_semanal_pdv || 0),
route,
summary.duration / 3600
);
if (!capacity.allowed) {
this.reassignError = `La reasignación excede la capacidad diaria (${capacity.totalHours.toFixed(1)} h de ${capacity.capacityHours.toFixed(1)} h).`;
return;
}
this.routeState.updateAssignedRoute(route, this.reassignUserId, this.reassignDay, {
distance: summary.distance / 1000,
duration: summary.duration / 3600
@@ -586,6 +611,15 @@ export class RouteOverviewMapComponent implements OnInit, OnDestroy, AfterViewIn
return segment ? `${segment.visitOrder} de ${segment.totalStops}` : '-';
}
get canMoveSelectedVisitUp(): boolean {
return (this.selectedMapSegment?.visitOrder ?? 0) > 1;
}
get canMoveSelectedVisitDown(): boolean {
const segment = this.selectedMapSegment;
return !!segment && segment.visitOrder < segment.totalStops;
}
get selectedSegmentOrigin(): string {
const segment = this.selectedMapSegment;
if (!segment) return '-';
@@ -621,6 +655,13 @@ export class RouteOverviewMapComponent implements OnInit, OnDestroy, AfterViewIn
return this.routeState.getDiasUnicos();
}
toggleUnassignedDay(pdvId: number, day: string, checked: boolean): void {
const key = String(pdvId);
const days = new Set(this.assignmentDays[key] ?? []);
checked ? days.add(day) : days.delete(day);
this.assignmentDays[key] = Array.from(days);
}
selectUnassigned(route: RouteNoAssignedResponse): void {
this.selectedUnassigned = route;
this.selectedRouteDetail = null;
@@ -670,9 +711,9 @@ export class RouteOverviewMapComponent implements OnInit, OnDestroy, AfterViewIn
async assignUnassigned(route: RouteNoAssignedResponse): Promise<void> {
const userId = this.assignmentUser[String(route.pdv_id)];
const day = this.assignmentDay[String(route.pdv_id)];
if (!userId || !day) {
this.unassignedActionError = 'Selecciona usuario y día antes de asignar.';
const days = this.assignmentDays[String(route.pdv_id)] ?? [];
if (!userId || !days.length) {
this.unassignedActionError = 'Selecciona usuario y al menos un día antes de asignar.';
return;
}
const user = this.routeState.getAssignedSnapshot().find(item => String(item.json.usuario_id) === userId);
@@ -682,14 +723,23 @@ export class RouteOverviewMapComponent implements OnInit, OnDestroy, AfterViewIn
try {
const origin = [Number(user.json.longitud_usuario), Number(user.json.latitud_usuario)];
const destination = [Number(route.longitud), Number(route.latitud)];
const results = await this.orsService.processPairs([{ pdv_id: route.pdv_id, origin, destination }], 1, true);
const geo = (results[0] as { geojson?: { features?: { properties?: { summary?: { distance: number; duration: number } } }[] }; error?: string });
const summary = geo?.geojson?.features?.[0]?.properties?.summary;
if (geo?.error || !summary) throw new Error('No se obtuvo una ruta vial');
this.routeState.addAssignedFromUnassigned(route, userId, day, summary.distance / 1000, summary.duration / 3600);
const assignments: UnassignedAssignment[] = [];
for (const day of days) {
const results = await this.orsService.processPairs([{ pdv_id: route.pdv_id, origin, destination }], 1, true);
const geo = (results[0] as { geojson?: { features?: { properties?: { summary?: { distance: number; duration: number } } }[] }; error?: string });
const summary = geo?.geojson?.features?.[0]?.properties?.summary;
if (geo?.error || !summary) throw new Error('No se obtuvo una ruta vial');
const capacity = this.routeState.canAssignToDay(userId, day, route.minimo_horas_semana, undefined, summary.duration / 3600);
if (!capacity.allowed) {
this.unassignedActionError = `${day}: excede la capacidad diaria (${capacity.totalHours.toFixed(1)} h de ${capacity.capacityHours.toFixed(1)} h).`;
return;
}
assignments.push({ userId, day, distance: summary.distance / 1000, duration: summary.duration / 3600 });
}
this.routeState.addAssignedFromUnassignedMany(route, assignments);
this.selectedUnassigned = null;
delete this.assignmentUser[String(route.pdv_id)];
delete this.assignmentDay[String(route.pdv_id)];
delete this.assignmentDays[String(route.pdv_id)];
} catch {
this.unassignedActionError = `No se pudo calcular la ruta vial para ${route.pdv_nombre}.`;
} finally {