Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0736db2b5c | |||
| 0c652a0bd7 | |||
| c45182012c | |||
| bb6757b492 | |||
| 8f34462876 | |||
| 540bc46fc2 | |||
| 7d696e6f16 | |||
| 65fe788281 | |||
| 9f42175afc | |||
| cd5c57c5ee | |||
| a0ea3fea48 |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,15 @@
|
||||
# OpenRouteService por país
|
||||
|
||||
- República Dominicana: `http://localhost:18080/ors/v2`
|
||||
- México: `http://localhost:18081/ors/v2`
|
||||
|
||||
Cada país mantiene su propio archivo OSM, configuración y directorio de grafos. Desde contenedores Docker, como n8n, usa `host.docker.internal` en lugar de `localhost`.
|
||||
|
||||
El workflow selecciona el servicio según la columna `País` del archivo PDV. `MEXICO` usa `18081`; cualquier proyecto anterior sin país se mantiene en República Dominicana y usa `18080`.
|
||||
|
||||
La imagen ORS configura memoria con `XMS`, `XMX` y `ADDITIONAL_JAVA_OPTS`; no se debe sobrescribir `JAVA_OPTS`, porque el entrypoint de la imagen lo reconstruye.
|
||||
|
||||
```powershell
|
||||
docker compose -f ors-app/republica-dominicana/docker-compose.yml up -d
|
||||
docker compose -f ors-app/mexico/docker-compose.yml up -d
|
||||
```
|
||||
@@ -0,0 +1,16 @@
|
||||
services:
|
||||
ors:
|
||||
image: openrouteservice/openrouteservice:latest
|
||||
container_name: ors-mexico
|
||||
ports:
|
||||
- "18081:8082"
|
||||
volumes:
|
||||
- ./ors-docker/mexico-latest.osm.pbf:/home/ors/files/mexico-latest.osm.pbf
|
||||
- ./ors-docker/graphs:/home/ors/graphs
|
||||
- ./ors-docker/elevation_cache:/home/ors/elevation_cache
|
||||
- ./ors-docker/config/ors-config.yml:/home/ors/config/ors-config.yml
|
||||
environment:
|
||||
- XMS=4g
|
||||
- XMX=12g
|
||||
- ADDITIONAL_JAVA_OPTS=-XX:MaxGCPauseMillis=300 -XX:InitiatingHeapOccupancyPercent=75
|
||||
restart: unless-stopped
|
||||
@@ -0,0 +1,17 @@
|
||||
ors:
|
||||
cors:
|
||||
allowed_origins: "*"
|
||||
allowed_headers: Content-Type, X-Requested-With, accept, Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization
|
||||
preflight_max_age: 600
|
||||
engine:
|
||||
profile_default:
|
||||
enabled: false
|
||||
graph_path: graphs
|
||||
build:
|
||||
source_file: /home/ors/files/mexico-latest.osm.pbf
|
||||
elevation: false
|
||||
service:
|
||||
maximum_distance: 500000
|
||||
profiles:
|
||||
driving-car:
|
||||
enabled: true
|
||||
@@ -1,7 +1,7 @@
|
||||
services:
|
||||
ors:
|
||||
image: openrouteservice/openrouteservice:latest
|
||||
container_name: ors-route-planner
|
||||
container_name: ors-republica-dominicana
|
||||
ports:
|
||||
- "18080:8082"
|
||||
volumes:
|
||||
@@ -10,5 +10,7 @@ services:
|
||||
- ./ors-docker/elevation_cache:/home/ors/elevation_cache
|
||||
- ./ors-docker/config/ors-config.yml:/home/ors/config/ors-config.yml
|
||||
environment:
|
||||
- JAVA_OPTS=-Djava.awt.headless=true -server -XX:TargetSurvivorRatio=75 -XX:SurvivorRatio=64 -XX:MaxTenuringThreshold=3 -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=80 -Xms2g -Xmx4g
|
||||
- XMS=1g
|
||||
- XMX=4g
|
||||
- ADDITIONAL_JAVA_OPTS=-XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=80
|
||||
restart: unless-stopped
|
||||
@@ -18,16 +18,27 @@
|
||||
"polyfills": ["zone.js"],
|
||||
"tsConfig": "tsconfig.app.json",
|
||||
"assets": [{ "glob": "**/*", "input": "public" }],
|
||||
"styles": ["src/styles.css"],
|
||||
"styles": [
|
||||
"src/styles.css",
|
||||
"node_modules/leaflet/dist/leaflet.css",
|
||||
"node_modules/leaflet.markercluster/dist/MarkerCluster.css",
|
||||
"node_modules/leaflet.markercluster/dist/MarkerCluster.Default.css"
|
||||
],
|
||||
"scripts": []
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"budgets": [
|
||||
{ "type": "initial", "maximumWarning": "1.5MB", "maximumError": "2MB" },
|
||||
{ "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" }
|
||||
{ "type": "initial", "maximumWarning": "2.1MB", "maximumError": "3MB" },
|
||||
{ "type": "anyComponentStyle", "maximumWarning": "6kB", "maximumError": "12kB" }
|
||||
],
|
||||
"outputHashing": "all"
|
||||
"outputHashing": "all",
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/environments/environment.ts",
|
||||
"with": "src/environments/environment.prod.ts"
|
||||
}
|
||||
]
|
||||
},
|
||||
"development": {
|
||||
"optimization": false,
|
||||
|
||||
Generated
+118
@@ -15,8 +15,11 @@
|
||||
"@angular/platform-browser": "^21.1.0",
|
||||
"@angular/router": "^21.1.0",
|
||||
"@primeng/themes": "^21.0.0",
|
||||
"@supabase/supabase-js": "^2.115.0",
|
||||
"file-saver": "^2.0.5",
|
||||
"leaflet": "^1.9.4",
|
||||
"leaflet.heat": "^0.2.0",
|
||||
"leaflet.markercluster": "^1.5.3",
|
||||
"primeicons": "^7.0.0",
|
||||
"primeng": "^21.0.0",
|
||||
"rxjs": "~7.8.2",
|
||||
@@ -4035,6 +4038,98 @@
|
||||
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@supabase/auth-js": {
|
||||
"version": "2.115.0",
|
||||
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.115.0.tgz",
|
||||
"integrity": "sha512-YNQlQWm1H0gsXHSY8Jd/xepBhjO0Zhwx04iW17A83/joQ5kFiUin6iPj9s9kZZvupnwLjXVP/diTFiLz2jUbwQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@supabase/functions-js": {
|
||||
"version": "2.115.0",
|
||||
"resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.115.0.tgz",
|
||||
"integrity": "sha512-p97V6/YFcdp+zblFDVJaE8f9rGKTNz0PRzyJ2d1w/EYIU5lwidKuc3l/wM+u27ACmAC62albvoGiUGzLPSg7Aw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@supabase/phoenix": {
|
||||
"version": "0.4.5",
|
||||
"resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.5.tgz",
|
||||
"integrity": "sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@supabase/postgrest-js": {
|
||||
"version": "2.115.0",
|
||||
"resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.115.0.tgz",
|
||||
"integrity": "sha512-DdERcurLh5t84pgSywDg2LjLR5le7XAzl52/iQhC7FdboWDqGfDPMfaWJV3MHvhyxSlSNzbpSQG+RiQOBSn/4w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@supabase/realtime-js": {
|
||||
"version": "2.115.0",
|
||||
"resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.115.0.tgz",
|
||||
"integrity": "sha512-5HyBkvlA/IUV2v8jX3uLTdy15jmTPRVXwXKoxvH2SKw5jZMNURxCxt+VpCEukscXQlY7pUpH8Cy4NH6io4iaRw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@supabase/phoenix": "0.4.5",
|
||||
"tslib": "2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@supabase/storage-js": {
|
||||
"version": "2.115.0",
|
||||
"resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.115.0.tgz",
|
||||
"integrity": "sha512-dLyIxzbO+MCcKHhcce8rVUCQX1iyqXqQ8ytgkOVYJ7D+Zp0qKylPtQH3hamgxrGSxtDjaw47Urpzw2iK9PsKdA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"iceberg-js": "^0.8.1",
|
||||
"tslib": "2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@supabase/supabase-js": {
|
||||
"version": "2.115.0",
|
||||
"resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.115.0.tgz",
|
||||
"integrity": "sha512-PYJSxtCo37R7tTZW6pAqsxUeSx/dlhA7zn8RzKEUSCqyTxCUhG+iHrDTb04UyVBYbttaUbhwkNTvb8h5HW+uZA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@supabase/auth-js": "2.115.0",
|
||||
"@supabase/functions-js": "2.115.0",
|
||||
"@supabase/postgrest-js": "2.115.0",
|
||||
"@supabase/realtime-js": "2.115.0",
|
||||
"@supabase/storage-js": "2.115.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@opentelemetry/api": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@tufjs/canonical-json": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@tufjs/canonical-json/-/canonical-json-2.0.0.tgz",
|
||||
@@ -5886,6 +5981,15 @@
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/iceberg-js": {
|
||||
"version": "0.8.1",
|
||||
"resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz",
|
||||
"integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.7.3",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
|
||||
@@ -6226,6 +6330,20 @@
|
||||
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/leaflet.heat": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/leaflet.heat/-/leaflet.heat-0.2.0.tgz",
|
||||
"integrity": "sha512-Cd5PbAA/rX3X3XKxfDoUGi9qp78FyhWYurFg3nsfhntcM/MCNK08pRkf4iEenO1KNqwVPKCmkyktjW3UD+h9bQ=="
|
||||
},
|
||||
"node_modules/leaflet.markercluster": {
|
||||
"version": "1.5.3",
|
||||
"resolved": "https://registry.npmjs.org/leaflet.markercluster/-/leaflet.markercluster-1.5.3.tgz",
|
||||
"integrity": "sha512-vPTw/Bndq7eQHjLBVlWpnGeLa3t+3zGiuM7fJwCkiMFq+nmRuG3RI3f7f4N4TDX7T4NpbAXpR2+NTRSEGfCSeA==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"leaflet": "^1.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/listr2": {
|
||||
"version": "9.0.5",
|
||||
"resolved": "https://registry.npmjs.org/listr2/-/listr2-9.0.5.tgz",
|
||||
|
||||
@@ -17,8 +17,11 @@
|
||||
"@angular/platform-browser": "^21.1.0",
|
||||
"@angular/router": "^21.1.0",
|
||||
"@primeng/themes": "^21.0.0",
|
||||
"@supabase/supabase-js": "^2.115.0",
|
||||
"file-saver": "^2.0.5",
|
||||
"leaflet": "^1.9.4",
|
||||
"leaflet.heat": "^0.2.0",
|
||||
"leaflet.markercluster": "^1.5.3",
|
||||
"primeicons": "^7.0.0",
|
||||
"primeng": "^21.0.0",
|
||||
"rxjs": "~7.8.2",
|
||||
|
||||
@@ -2,11 +2,22 @@ import { Routes } from '@angular/router';
|
||||
import { LoginComponent } from './public/login/login.component';
|
||||
import { HomeComponent } from './private/home/home.component';
|
||||
import { AssignedRouteDetailComponent } from './private/home/assigned-route-detail/assigned-route-detail.component';
|
||||
import { RouteOverviewMapComponent } from './private/home/route-overview-map/route-overview-map.component';
|
||||
import { authGuard } from './core/services/auth.guard';
|
||||
import { EmployeesComponent } from './private/employees/employees.component';
|
||||
import { ProjectListComponent } from './private/projects/project-list.component';
|
||||
import { NewProjectComponent } from './private/projects/new-project.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: '', redirectTo: 'login', pathMatch: 'full' },
|
||||
{ path: 'login', component: LoginComponent },
|
||||
{ path: 'home', component: HomeComponent, pathMatch: 'full' },
|
||||
{ path: 'home/assigned-route', component: AssignedRouteDetailComponent },
|
||||
{ path: 'home', component: ProjectListComponent, pathMatch: 'full', canActivate: [authGuard] },
|
||||
{ path: 'proyectos/nuevo', component: NewProjectComponent, canActivate: [authGuard] },
|
||||
{ path: 'proyectos/:id', component: HomeComponent, pathMatch: 'full', canActivate: [authGuard] },
|
||||
{ path: 'proyectos/:id/mapa', component: RouteOverviewMapComponent, canActivate: [authGuard] },
|
||||
{ path: 'proyectos/:id/ruta', component: AssignedRouteDetailComponent, canActivate: [authGuard] },
|
||||
{ path: 'empleados', component: EmployeesComponent, canActivate: [authGuard] },
|
||||
{ path: 'home/assigned-route', component: AssignedRouteDetailComponent, canActivate: [authGuard] },
|
||||
{ path: 'home/mapa', component: RouteOverviewMapComponent, canActivate: [authGuard] },
|
||||
{ path: '**', redirectTo: 'login' }
|
||||
];
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
export interface Employee {
|
||||
id: string;
|
||||
employee_code: string;
|
||||
nombre: string;
|
||||
usuario: string | null;
|
||||
email: string | null;
|
||||
perfil: string | null;
|
||||
pais: string | null;
|
||||
regional: string | null;
|
||||
latitud: number;
|
||||
longitud: number;
|
||||
horas_por_dia: number;
|
||||
dias_por_semana: number;
|
||||
jornada_codigo: string;
|
||||
horas_descanso_por_dia: number;
|
||||
dias_descanso: string[];
|
||||
visitas_maximas_por_dia: number;
|
||||
activo: boolean;
|
||||
}
|
||||
|
||||
export type EmployeeInput = Omit<Employee, 'id'>;
|
||||
@@ -0,0 +1,17 @@
|
||||
export interface RuteroProyecto {
|
||||
id: string;
|
||||
nombre: string;
|
||||
descripcion: string | null;
|
||||
propietario_id: string;
|
||||
estado: 'borrador' | 'optimizado' | 'archivado';
|
||||
version: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface RuteroProyectoPdv {
|
||||
id: string;
|
||||
proyecto_id: string;
|
||||
pdv_id: string;
|
||||
pdv_data: Record<string, unknown>;
|
||||
}
|
||||
@@ -26,6 +26,24 @@ export interface RouteAssignedJson {
|
||||
nombre_pdv: string;
|
||||
usuario_id: string;
|
||||
pdv_id: number;
|
||||
visit_order?: number;
|
||||
geojson?: unknown;
|
||||
horas_por_dia_usuario?: number;
|
||||
horas_descanso_por_dia?: number;
|
||||
jornada_codigo?: string;
|
||||
pais?: string;
|
||||
ciudad?: string;
|
||||
estado?: string;
|
||||
provincia?: string;
|
||||
region?: string;
|
||||
zona?: string;
|
||||
metro?: string;
|
||||
pais_usuario?: string;
|
||||
ciudad_usuario?: string;
|
||||
estado_usuario?: string;
|
||||
provincia_usuario?: string;
|
||||
region_usuario?: string;
|
||||
zona_usuario?: string;
|
||||
}
|
||||
export interface RouteNoAssignedResponse {
|
||||
pdv_id: number;
|
||||
@@ -34,4 +52,11 @@ export interface RouteAssignedJson {
|
||||
latitud: number,
|
||||
longitud: number,
|
||||
motivo: string;
|
||||
}
|
||||
pais?: string;
|
||||
ciudad?: string;
|
||||
estado?: string;
|
||||
provincia?: string;
|
||||
region?: string;
|
||||
zona?: string;
|
||||
metro?: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
export interface UserProfile {
|
||||
nombre: string;
|
||||
pais: string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export interface WorkSchedule {
|
||||
code: 'LUN_DOM_44' | 'LUN_SAB_40' | 'LUN_SAB_44' | 'LUN_VIE_40';
|
||||
label: string;
|
||||
weeklyHours: number;
|
||||
days: string[];
|
||||
}
|
||||
|
||||
export const WORK_SCHEDULES: WorkSchedule[] = [
|
||||
{ code: 'LUN_DOM_44', label: 'Lun a Dom - 44h', weeklyHours: 44, days: ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo'] },
|
||||
{ code: 'LUN_SAB_40', label: 'Lun a Sáb - 40h', weeklyHours: 40, days: ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado'] },
|
||||
{ code: 'LUN_SAB_44', label: 'Lun a Sáb - 44h', weeklyHours: 44, days: ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado'] },
|
||||
{ code: 'LUN_VIE_40', label: 'Lun a Vie - 40h', weeklyHours: 40, days: ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes'] }
|
||||
];
|
||||
|
||||
export function workSchedule(code: string): WorkSchedule {
|
||||
return WORK_SCHEDULES.find(schedule => schedule.code === code) ?? WORK_SCHEDULES[3];
|
||||
}
|
||||
@@ -4,6 +4,20 @@ import {
|
||||
RouteAssignedResponse,
|
||||
RouteNoAssignedResponse
|
||||
} from '../models/route.model';
|
||||
import { summarizeDailyRoutes } from '../../shared/utils/route-sequencing.utils';
|
||||
|
||||
const STORAGE_ASSIGNED = 'rp_assigned_routes';
|
||||
const STORAGE_ASSIGNED_ORIGINAL = 'rp_assigned_routes_original';
|
||||
const STORAGE_NO_ASSIGNED = 'rp_no_assigned_routes';
|
||||
const STORAGE_NO_ASSIGNED_ORIGINAL = 'rp_no_assigned_routes_original';
|
||||
const STORAGE_SELECTED = 'rp_selected_route';
|
||||
const DAY_ORDER = ['Lunes', 'Martes', 'Miércoles', 'Miercoles', 'Jueves', 'Viernes', 'Sábado', 'Sabado'];
|
||||
export interface UnassignedAssignment {
|
||||
userId: string;
|
||||
day: string;
|
||||
distance: number;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class RouteState {
|
||||
@@ -11,13 +25,13 @@ export class RouteState {
|
||||
private loading = new BehaviorSubject<boolean>(false);
|
||||
loading$ = this.loading.asObservable();
|
||||
|
||||
private assignedRoutes = new BehaviorSubject<RouteAssignedResponse[]>([]);
|
||||
private assignedRoutes = new BehaviorSubject<RouteAssignedResponse[]>(this.loadAssigned());
|
||||
assignedRoutes$ = this.assignedRoutes.asObservable();
|
||||
|
||||
private noAssignedRoutes = new BehaviorSubject<RouteNoAssignedResponse[]>([]);
|
||||
private noAssignedRoutes = new BehaviorSubject<RouteNoAssignedResponse[]>(this.loadNoAssigned());
|
||||
noAssignedRoutes$ = this.noAssignedRoutes.asObservable();
|
||||
|
||||
private selectedRoute = new BehaviorSubject<RouteAssignedResponse | null>(null);
|
||||
private selectedRoute = new BehaviorSubject<RouteAssignedResponse | null>(this.loadSelected());
|
||||
selectedRoute$ = this.selectedRoute.asObservable();
|
||||
|
||||
resetLoading() {
|
||||
@@ -30,13 +44,297 @@ export class RouteState {
|
||||
|
||||
setAssignedRoutes(data: RouteAssignedResponse[]) {
|
||||
this.assignedRoutes.next(data);
|
||||
this.persist(STORAGE_ASSIGNED, data);
|
||||
this.persist(STORAGE_ASSIGNED_ORIGINAL, data);
|
||||
}
|
||||
|
||||
updateAssignedRoute(
|
||||
route: RouteAssignedResponse,
|
||||
userId: string,
|
||||
day: string,
|
||||
metrics?: { distance: number; duration: number }
|
||||
): void {
|
||||
const profile = this.assignedRoutes.getValue().find(item => String(item.json.usuario_id) === String(userId));
|
||||
if (!profile) return;
|
||||
const updated = this.assignedRoutes.getValue().map(item => {
|
||||
if (item !== route) return item;
|
||||
return {
|
||||
json: {
|
||||
...item.json,
|
||||
usuario_id: profile.json.usuario_id,
|
||||
nombre_usuario: profile.json.nombre_usuario,
|
||||
latitud_usuario: profile.json.latitud_usuario,
|
||||
longitud_usuario: profile.json.longitud_usuario,
|
||||
pais_usuario: profile.json.pais_usuario,
|
||||
ciudad_usuario: profile.json.ciudad_usuario,
|
||||
estado_usuario: profile.json.estado_usuario,
|
||||
provincia_usuario: profile.json.provincia_usuario,
|
||||
region_usuario: profile.json.region_usuario,
|
||||
zona_usuario: profile.json.zona_usuario,
|
||||
hora_laboral_semanal_usuario: profile.json.hora_laboral_semanal_usuario,
|
||||
dia: day,
|
||||
distancia: metrics?.distance ?? item.json.distancia,
|
||||
horas_desplazamiento: metrics?.duration ?? item.json.horas_desplazamiento
|
||||
}
|
||||
};
|
||||
});
|
||||
this.setDraftAssignedRoutes(updated);
|
||||
}
|
||||
|
||||
addAssignedFromUnassigned(route: RouteNoAssignedResponse, userId: string, day: string, distance: number, duration: number): void {
|
||||
this.addAssignedFromUnassignedMany(route, [{ userId, day, distance, duration }]);
|
||||
}
|
||||
|
||||
addAssignedFromUnassignedMany(route: RouteNoAssignedResponse, assignments: UnassignedAssignment[]): void {
|
||||
const routes = this.assignedRoutes.getValue();
|
||||
const newRoutes = assignments.map(assignment => {
|
||||
const profile = routes.find(item => String(item.json.usuario_id) === String(assignment.userId));
|
||||
if (!profile) return null;
|
||||
return { json: {
|
||||
dia: assignment.day,
|
||||
distancia: assignment.distance,
|
||||
horas_desplazamiento: assignment.duration,
|
||||
hora_laboral_semanal_usuario: profile.json.hora_laboral_semanal_usuario,
|
||||
hora_minima_semanal_pdv: route.minimo_horas_semana,
|
||||
horas_trabajo: String(route.minimo_horas_semana),
|
||||
latitud_usuario: profile.json.latitud_usuario,
|
||||
longitud_usuario: profile.json.longitud_usuario,
|
||||
latitud_pdv: route.latitud,
|
||||
longitud_pdv: route.longitud,
|
||||
nombre_usuario: profile.json.nombre_usuario,
|
||||
nombre_pdv: route.pdv_nombre,
|
||||
usuario_id: profile.json.usuario_id,
|
||||
pdv_id: route.pdv_id,
|
||||
pais: route.pais,
|
||||
ciudad: route.ciudad,
|
||||
estado: route.estado,
|
||||
provincia: route.provincia,
|
||||
region: route.region,
|
||||
zona: route.zona,
|
||||
metro: route.metro,
|
||||
pais_usuario: profile.json.pais_usuario,
|
||||
ciudad_usuario: profile.json.ciudad_usuario,
|
||||
estado_usuario: profile.json.estado_usuario,
|
||||
provincia_usuario: profile.json.provincia_usuario,
|
||||
region_usuario: profile.json.region_usuario,
|
||||
zona_usuario: profile.json.zona_usuario
|
||||
} } as RouteAssignedResponse;
|
||||
});
|
||||
if (newRoutes.some(item => !item)) return;
|
||||
this.setDraftAssignedRoutes([...routes, ...(newRoutes as RouteAssignedResponse[])]);
|
||||
this.setDraftNoAssignedRoutes(this.noAssignedRoutes.getValue().filter(item => item.pdv_id !== route.pdv_id));
|
||||
}
|
||||
|
||||
updateNoAssignedRoute(route: RouteNoAssignedResponse, changes: Partial<RouteNoAssignedResponse>): void {
|
||||
const updated = this.noAssignedRoutes.getValue().map(item => item.pdv_id === route.pdv_id ? { ...item, ...changes } : item);
|
||||
this.setDraftNoAssignedRoutes(updated);
|
||||
}
|
||||
|
||||
canAssignToDay(
|
||||
userId: string,
|
||||
day: string,
|
||||
requiredHours: number,
|
||||
excluding?: RouteAssignedResponse,
|
||||
additionalTravelHours = 0
|
||||
): { allowed: boolean; totalHours: number; capacityHours: number } {
|
||||
const userRoute = this.assignedRoutes.getValue().find(route => String(route.json.usuario_id) === String(userId));
|
||||
if (!userRoute) return { allowed: false, totalHours: 0, capacityHours: 0 };
|
||||
const weeklyCapacity = Number(userRoute.json.hora_laboral_semanal_usuario || 0);
|
||||
const weeklyLoad = this.assignedRoutes.getValue()
|
||||
.filter(route => String(route.json.usuario_id) === String(userId) && route !== excluding)
|
||||
.reduce((sum, route) => sum + Number(route.json.horas_trabajo || route.json.hora_minima_semanal_pdv || 0), 0) + requiredHours;
|
||||
if (weeklyLoad > weeklyCapacity) {
|
||||
return { allowed: false, totalHours: weeklyLoad, capacityHours: weeklyCapacity };
|
||||
}
|
||||
const existing = this.assignedRoutes.getValue().filter(route =>
|
||||
String(route.json.usuario_id) === String(userId) && route.json.dia === day && route !== excluding
|
||||
);
|
||||
const capacityHours = Number(userRoute.json.hora_laboral_semanal_usuario || 0) / 5;
|
||||
const workHours = existing.reduce((sum, route) => sum + Number(route.json.horas_trabajo || route.json.hora_minima_semanal_pdv || 0), 0) + requiredHours;
|
||||
const existingTravelHours = summarizeDailyRoutes(existing).reduce((sum, item) => sum + item.travelHours, 0);
|
||||
const totalHours = workHours + existingTravelHours + additionalTravelHours;
|
||||
return { allowed: totalHours <= capacityHours, totalHours, capacityHours };
|
||||
}
|
||||
|
||||
moveRouteVisit(route: RouteAssignedResponse, direction: -1 | 1): void {
|
||||
const group = this.assignedRoutes.getValue().filter(item =>
|
||||
String(item.json.usuario_id) === String(route.json.usuario_id) && item.json.dia === route.json.dia
|
||||
);
|
||||
const sequence = summarizeDailyRoutes(group)[0]?.routes ?? [];
|
||||
const index = sequence.findIndex(item => item.route === route);
|
||||
const target = index + direction;
|
||||
if (index < 0 || target < 0 || target >= sequence.length) return;
|
||||
const ordered = [...sequence];
|
||||
[ordered[index], ordered[target]] = [ordered[target], ordered[index]];
|
||||
const orderByRoute = new Map<RouteAssignedResponse, number>(ordered.map((item, position) => [item.route, position + 1]));
|
||||
this.setDraftAssignedRoutes(this.assignedRoutes.getValue().map(item => {
|
||||
const order = orderByRoute.get(item);
|
||||
return order ? { json: { ...item.json, visit_order: order } } : item;
|
||||
}));
|
||||
}
|
||||
|
||||
resetRouteVisitOrder(userId: string, day: string): void {
|
||||
this.setDraftAssignedRoutes(this.assignedRoutes.getValue().map(route =>
|
||||
String(route.json.usuario_id) === String(userId) && route.json.dia === day
|
||||
? { json: { ...route.json, visit_order: undefined } }
|
||||
: route
|
||||
));
|
||||
}
|
||||
|
||||
restoreOriginalAssignedRoutes(): void {
|
||||
const original = this.loadOriginalAssigned();
|
||||
this.setDraftAssignedRoutes(original);
|
||||
}
|
||||
|
||||
reoptimizeAssignedRoutes(): void {
|
||||
const current = this.assignedRoutes.getValue();
|
||||
const profiles = Array.from(new Map(current.map(route => [String(route.json.usuario_id), route])).values());
|
||||
if (profiles.length < 2) return;
|
||||
|
||||
const load = new Map<string, number>(profiles.map(profile => [String(profile.json.usuario_id), 0]));
|
||||
const optimized = [...current]
|
||||
.sort((a, b) => Number(b.json.hora_minima_semanal_pdv) - Number(a.json.hora_minima_semanal_pdv))
|
||||
.map(route => {
|
||||
const routeHours = Number(route.json.horas_trabajo || route.json.hora_minima_semanal_pdv || 0);
|
||||
const user = profiles
|
||||
.slice()
|
||||
.filter(profile => {
|
||||
const userId = String(profile.json.usuario_id);
|
||||
const capacity = Number(profile.json.hora_laboral_semanal_usuario || 0);
|
||||
return (load.get(userId) ?? 0) + routeHours <= capacity;
|
||||
})
|
||||
.sort((a, b) => (load.get(String(a.json.usuario_id)) ?? 0) - (load.get(String(b.json.usuario_id)) ?? 0))[0]
|
||||
?? profiles.slice().sort((a, b) => (load.get(String(a.json.usuario_id)) ?? 0) - (load.get(String(b.json.usuario_id)) ?? 0))[0];
|
||||
const userId = String(user.json.usuario_id);
|
||||
load.set(userId, (load.get(userId) ?? 0) + routeHours);
|
||||
return {
|
||||
json: {
|
||||
...route.json,
|
||||
usuario_id: user.json.usuario_id,
|
||||
nombre_usuario: user.json.nombre_usuario,
|
||||
latitud_usuario: user.json.latitud_usuario,
|
||||
longitud_usuario: user.json.longitud_usuario,
|
||||
pais_usuario: user.json.pais_usuario,
|
||||
ciudad_usuario: user.json.ciudad_usuario,
|
||||
estado_usuario: user.json.estado_usuario,
|
||||
provincia_usuario: user.json.provincia_usuario,
|
||||
region_usuario: user.json.region_usuario,
|
||||
zona_usuario: user.json.zona_usuario,
|
||||
hora_laboral_semanal_usuario: user.json.hora_laboral_semanal_usuario
|
||||
}
|
||||
};
|
||||
});
|
||||
this.setDraftAssignedRoutes(optimized);
|
||||
}
|
||||
|
||||
setNoAssignedRoutes(data: RouteNoAssignedResponse[]) {
|
||||
this.noAssignedRoutes.next(data);
|
||||
this.persist(STORAGE_NO_ASSIGNED, data);
|
||||
this.persist(STORAGE_NO_ASSIGNED_ORIGINAL, data);
|
||||
}
|
||||
|
||||
sendRoute(route: RouteAssignedResponse) {
|
||||
this.selectedRoute.next(route);
|
||||
this.persist(STORAGE_SELECTED, route);
|
||||
}
|
||||
|
||||
getAssignedSnapshot(): RouteAssignedResponse[] {
|
||||
return this.assignedRoutes.getValue();
|
||||
}
|
||||
|
||||
getNoAssignedSnapshot(): RouteNoAssignedResponse[] {
|
||||
return this.noAssignedRoutes.getValue();
|
||||
}
|
||||
|
||||
findRoute(pdvId: string | number, usuarioId?: string): RouteAssignedResponse | null {
|
||||
const pid = String(pdvId);
|
||||
const routes = this.getAssignedSnapshot();
|
||||
const found = routes.find(r => {
|
||||
const jp = r.json;
|
||||
if (String(jp.pdv_id) !== pid) return false;
|
||||
if (usuarioId && String(jp.usuario_id) !== String(usuarioId)) return false;
|
||||
return true;
|
||||
});
|
||||
return found ?? null;
|
||||
}
|
||||
|
||||
getUsuariosUnicos(): { id: string; nombre: string }[] {
|
||||
const map = new Map<string, string>();
|
||||
for (const r of this.getAssignedSnapshot()) {
|
||||
const id = String(r.json.usuario_id);
|
||||
if (!map.has(id)) map.set(id, r.json.nombre_usuario);
|
||||
}
|
||||
return Array.from(map.entries()).map(([id, nombre]) => ({ id, nombre }));
|
||||
}
|
||||
|
||||
getDiasUnicos(): string[] {
|
||||
const set = new Set<string>();
|
||||
for (const r of this.getAssignedSnapshot()) set.add(r.json.dia);
|
||||
return Array.from(set).sort((a, b) => {
|
||||
const indexA = DAY_ORDER.indexOf(a);
|
||||
const indexB = DAY_ORDER.indexOf(b);
|
||||
return (indexA < 0 ? DAY_ORDER.length : indexA) - (indexB < 0 ? DAY_ORDER.length : indexB);
|
||||
});
|
||||
}
|
||||
|
||||
clearAll() {
|
||||
this.assignedRoutes.next([]);
|
||||
this.noAssignedRoutes.next([]);
|
||||
this.selectedRoute.next(null);
|
||||
try {
|
||||
sessionStorage.removeItem(STORAGE_ASSIGNED);
|
||||
sessionStorage.removeItem(STORAGE_ASSIGNED_ORIGINAL);
|
||||
sessionStorage.removeItem(STORAGE_NO_ASSIGNED);
|
||||
sessionStorage.removeItem(STORAGE_NO_ASSIGNED_ORIGINAL);
|
||||
sessionStorage.removeItem(STORAGE_SELECTED);
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
private persist(key: string, data: unknown) {
|
||||
try {
|
||||
sessionStorage.setItem(key, JSON.stringify(data));
|
||||
} catch { /* ignore storage errors */ }
|
||||
}
|
||||
|
||||
private setDraftAssignedRoutes(data: RouteAssignedResponse[]): void {
|
||||
this.assignedRoutes.next(data);
|
||||
this.persist(STORAGE_ASSIGNED, data);
|
||||
}
|
||||
|
||||
private setDraftNoAssignedRoutes(data: RouteNoAssignedResponse[]): void {
|
||||
this.noAssignedRoutes.next(data);
|
||||
this.persist(STORAGE_NO_ASSIGNED, data);
|
||||
}
|
||||
|
||||
private loadAssigned(): RouteAssignedResponse[] {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(STORAGE_ASSIGNED);
|
||||
if (raw) return JSON.parse(raw) as RouteAssignedResponse[];
|
||||
} catch { /* ignore */ }
|
||||
return [];
|
||||
}
|
||||
|
||||
private loadOriginalAssigned(): RouteAssignedResponse[] {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(STORAGE_ASSIGNED_ORIGINAL);
|
||||
if (raw) return JSON.parse(raw) as RouteAssignedResponse[];
|
||||
} catch { /* ignore */ }
|
||||
return this.loadAssigned();
|
||||
}
|
||||
|
||||
private loadNoAssigned(): RouteNoAssignedResponse[] {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(STORAGE_NO_ASSIGNED);
|
||||
if (raw) return JSON.parse(raw) as RouteNoAssignedResponse[];
|
||||
} catch { /* ignore */ }
|
||||
return [];
|
||||
}
|
||||
|
||||
private loadSelected(): RouteAssignedResponse | null {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(STORAGE_SELECTED);
|
||||
if (raw) return JSON.parse(raw) as RouteAssignedResponse;
|
||||
} catch { /* ignore */ }
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
export const authGuard: CanActivateFn = async () => {
|
||||
const auth = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
return await auth.getSession() ? true : router.parseUrl('/login');
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Session } from '@supabase/supabase-js';
|
||||
import { supabaseClient } from './supabase.client';
|
||||
import { UserProfileService } from './user-profile.service';
|
||||
|
||||
const CORPORATE_DOMAIN = '@gomezleemarketing.com';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthService {
|
||||
private readonly client = supabaseClient;
|
||||
constructor(private profile: UserProfileService) {}
|
||||
|
||||
async signIn(email: string, password: string): Promise<string | null> {
|
||||
const normalizedEmail = email.trim().toLowerCase();
|
||||
if (!normalizedEmail.endsWith(CORPORATE_DOMAIN)) {
|
||||
return `Solo se permiten correos ${CORPORATE_DOMAIN}.`;
|
||||
}
|
||||
const { error } = await this.client.auth.signInWithPassword({ email: normalizedEmail, password });
|
||||
return error?.message ?? null;
|
||||
}
|
||||
|
||||
async signInWithGoogle(): Promise<string | null> {
|
||||
const { error } = await this.client.auth.signInWithOAuth({
|
||||
provider: 'google',
|
||||
// Return to login so the OAuth callback can load the profile from n8n
|
||||
// before private routes are opened.
|
||||
options: { redirectTo: `${window.location.origin}/login` }
|
||||
});
|
||||
return error?.message ?? null;
|
||||
}
|
||||
|
||||
async getSession(): Promise<Session | null> {
|
||||
const { data } = await this.client.auth.getSession();
|
||||
const email = data.session?.user.email?.toLowerCase() ?? '';
|
||||
return email.endsWith(CORPORATE_DOMAIN) ? data.session : null;
|
||||
}
|
||||
|
||||
async signOut(): Promise<void> {
|
||||
await this.client.auth.signOut();
|
||||
this.profile.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Employee, EmployeeInput } from '../models/employee.model';
|
||||
import { workSchedule } from '../models/work-schedule.model';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { supabaseClient } from './supabase.client';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class EmployeeService {
|
||||
private readonly client = supabaseClient;
|
||||
private readonly table = 'rutero_empleados';
|
||||
|
||||
async list(): Promise<Employee[]> {
|
||||
const { data: sessionData, error: sessionError } = await this.client.auth.getSession();
|
||||
if (sessionError) throw sessionError;
|
||||
if (!sessionData.session) throw new Error('No hay una sesión Supabase activa. Cierra sesión e inicia sesión nuevamente.');
|
||||
const { data, error } = await this.client.from(this.table).select('*').order('nombre');
|
||||
if (error) throw new Error(`Supabase ${error.code ?? 'error'}: ${error.message}`);
|
||||
return (data ?? []).map(row => ({
|
||||
...row,
|
||||
jornada_codigo: row.jornada_codigo ?? 'LUN_VIE_40',
|
||||
horas_descanso_por_dia: Number(row.horas_descanso_por_dia ?? 1),
|
||||
dias_descanso: Array.isArray(row.dias_descanso) ? row.dias_descanso : []
|
||||
})) as Employee[];
|
||||
}
|
||||
|
||||
async create(employee: EmployeeInput): Promise<void> {
|
||||
const { error } = await this.client.from(this.table).insert(employee);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
async upsert(employees: EmployeeInput[]): Promise<void> {
|
||||
const { error } = await this.client.from(this.table).upsert(employees, { onConflict: 'employee_code' });
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
async update(id: string, employee: EmployeeInput): Promise<void> {
|
||||
const { error } = await this.client.from(this.table).update(employee).eq('id', id);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
const { error } = await this.client.from(this.table).delete().eq('id', id);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
async active(country = ''): Promise<Employee[]> {
|
||||
const expectedCountry = this.normalizeCountry(country);
|
||||
return (await this.list()).filter(employee => employee.activo && (!expectedCountry || this.normalizeCountry(employee.pais ?? '') === expectedCountry));
|
||||
}
|
||||
|
||||
async activeEmployeesFile(country = ''): Promise<File> {
|
||||
const employees = await this.active(country);
|
||||
const rows = employees.map(employee => ({
|
||||
ID: employee.employee_code,
|
||||
'Nombre del empleado': employee.nombre,
|
||||
'País': employee.pais,
|
||||
Regional: employee.regional,
|
||||
Latitud: employee.latitud,
|
||||
Longitud: employee.longitud,
|
||||
'Horas por día usuario': employee.horas_por_dia,
|
||||
'Horas por semana usuario': workSchedule(employee.jornada_codigo).weeklyHours,
|
||||
'Visitas maximas por dia': employee.visitas_maximas_por_dia,
|
||||
Jornada: employee.jornada_codigo,
|
||||
'Horas descanso por día': employee.horas_descanso_por_dia,
|
||||
'Días descanso': (employee.dias_descanso ?? []).join(', '),
|
||||
'Usuario activo': 'Sí'
|
||||
}));
|
||||
const workbook = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(workbook, XLSX.utils.json_to_sheet(rows), 'Usuarios');
|
||||
const data = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
|
||||
return new File([data], 'empleados_activos.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||
}
|
||||
|
||||
private normalizeCountry(country: string): string {
|
||||
const normalized = country.normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim().toUpperCase();
|
||||
if (normalized.includes('MEXICO')) return 'MEXICO';
|
||||
if (normalized.includes('DOMINICANA')) return 'REPUBLICA DOMINICANA';
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,13 @@ import {
|
||||
catchError,
|
||||
map,
|
||||
toArray,
|
||||
timeout
|
||||
timeout,
|
||||
Observable,
|
||||
Subject
|
||||
} from 'rxjs';
|
||||
import { takeUntil } from 'rxjs/operators';
|
||||
import { environment } from '../../../environments/environment';
|
||||
|
||||
const ENDPOINT = 'http://localhost:18080/ors/v2/directions/driving-car';
|
||||
const ENDPOINTJSON = 'http://localhost:18080/ors/v2/directions/driving-car/geojson';
|
||||
const MAX_CONCURRENT_REQUESTS = 2;
|
||||
|
||||
@Injectable({
|
||||
@@ -21,8 +23,14 @@ const MAX_CONCURRENT_REQUESTS = 2;
|
||||
})
|
||||
export class OrsService {
|
||||
|
||||
private geoCache = new Map<string, unknown>();
|
||||
|
||||
constructor(private http: HttpClient) { }
|
||||
|
||||
private cacheKey(origin: number[], dest: number[]): string {
|
||||
return `${origin[0].toFixed(5)},${origin[1].toFixed(5)}->${dest[0].toFixed(5)},${dest[1].toFixed(5)}`;
|
||||
}
|
||||
|
||||
private fetchRoute(
|
||||
origin: number[],
|
||||
destination: number[],
|
||||
@@ -31,8 +39,12 @@ export class OrsService {
|
||||
const body = {
|
||||
coordinates: [origin, destination]
|
||||
};
|
||||
const baseUrl = this.isMexico(origin) || this.isMexico(destination)
|
||||
? environment.orsMexicoBaseUrl
|
||||
: environment.orsBaseUrl;
|
||||
const endpoint = `${baseUrl}/directions/driving-car${isJson ? '/geojson' : ''}`;
|
||||
|
||||
return this.http.post<any>(isJson ? ENDPOINTJSON : ENDPOINT, body).pipe(
|
||||
return this.http.post<unknown>(endpoint, body).pipe(
|
||||
timeout(8000),
|
||||
catchError(error => {
|
||||
throw error;
|
||||
@@ -40,6 +52,11 @@ export class OrsService {
|
||||
);
|
||||
}
|
||||
|
||||
private isMexico(coordinates: number[]): boolean {
|
||||
const [longitude, latitude] = coordinates;
|
||||
return latitude >= 14 && latitude <= 33 && longitude >= -119 && longitude <= -86;
|
||||
}
|
||||
|
||||
async processPairs(
|
||||
pares: {
|
||||
pdv_id: number;
|
||||
@@ -48,37 +65,91 @@ export class OrsService {
|
||||
}[],
|
||||
concurrency = MAX_CONCURRENT_REQUESTS,
|
||||
isJson = false
|
||||
): Promise<any[]> {
|
||||
return lastValueFrom(
|
||||
from(pares).pipe(
|
||||
mergeMap(
|
||||
pair =>
|
||||
this.fetchRoute(pair.origin, pair.destination, isJson).pipe(
|
||||
delay(300),
|
||||
): Promise<unknown[]> {
|
||||
return this.processPairsWithProgress(pares, concurrency, isJson).promise;
|
||||
}
|
||||
|
||||
processPairsWithProgress(
|
||||
pares: {
|
||||
pdv_id: number;
|
||||
origin: number[];
|
||||
destination: number[];
|
||||
}[],
|
||||
concurrency = MAX_CONCURRENT_REQUESTS,
|
||||
isJson = false,
|
||||
abort$?: Observable<void>
|
||||
): { promise: Promise<unknown[]>; progress$: Observable<{ completed: number; total: number; item: unknown }> } {
|
||||
const progressSubject = new Subject<{ completed: number; total: number; item: unknown }>();
|
||||
let completed = 0;
|
||||
|
||||
let source$: Observable<unknown[]>;
|
||||
const base$ = from(pares).pipe(
|
||||
mergeMap(
|
||||
pair => {
|
||||
const key = this.cacheKey(pair.origin, pair.destination);
|
||||
if (isJson && this.geoCache.has(key)) {
|
||||
const cached = this.geoCache.get(key);
|
||||
const wrapped = { pdv_id: pair.pdv_id, geojson: cached };
|
||||
return of(wrapped).pipe(
|
||||
map(data => {
|
||||
if (!isJson) {
|
||||
const summary = data.routes[0].summary;
|
||||
return {
|
||||
pdv_id: pair.pdv_id,
|
||||
distance: summary.distance,
|
||||
duration: summary.duration,
|
||||
raw: data
|
||||
};
|
||||
} else {
|
||||
return data;
|
||||
}
|
||||
}),
|
||||
catchError(error =>
|
||||
of({
|
||||
completed++;
|
||||
progressSubject.next({ completed, total: pares.length, item: data as unknown });
|
||||
if (completed === pares.length) progressSubject.complete();
|
||||
return data as unknown;
|
||||
})
|
||||
);
|
||||
}
|
||||
return this.fetchRoute(pair.origin, pair.destination, isJson).pipe(
|
||||
delay(300),
|
||||
map(data => {
|
||||
if (isJson) this.geoCache.set(key, data);
|
||||
if (!isJson) {
|
||||
const summary = (data as { routes: { summary: { distance: number; duration: number } }[] }).routes[0].summary;
|
||||
const out = {
|
||||
pdv_id: pair.pdv_id,
|
||||
error: error.message || 'Error ORS'
|
||||
})
|
||||
)
|
||||
),
|
||||
concurrency
|
||||
),
|
||||
toArray()
|
||||
)
|
||||
);
|
||||
distance: summary.distance,
|
||||
duration: summary.duration,
|
||||
raw: data
|
||||
};
|
||||
completed++;
|
||||
progressSubject.next({ completed, total: pares.length, item: out });
|
||||
if (completed === pares.length) progressSubject.complete();
|
||||
return out;
|
||||
} else {
|
||||
const wrapped = { pdv_id: pair.pdv_id, geojson: data };
|
||||
completed++;
|
||||
progressSubject.next({ completed, total: pares.length, item: wrapped as unknown });
|
||||
if (completed === pares.length) progressSubject.complete();
|
||||
return wrapped as unknown;
|
||||
}
|
||||
}),
|
||||
catchError(error => {
|
||||
const errOut = {
|
||||
pdv_id: pair.pdv_id,
|
||||
error: (error as Error).message || 'Error ORS'
|
||||
};
|
||||
completed++;
|
||||
progressSubject.next({ completed, total: pares.length, item: errOut });
|
||||
if (completed === pares.length) progressSubject.complete();
|
||||
return of(errOut);
|
||||
})
|
||||
);
|
||||
},
|
||||
concurrency
|
||||
),
|
||||
toArray()
|
||||
) as Observable<unknown[]>;
|
||||
source$ = abort$ ? (base$.pipe(takeUntil(abort$)) as Observable<unknown[]>) : base$;
|
||||
|
||||
const promise = lastValueFrom(source$).catch(() => {
|
||||
progressSubject.complete();
|
||||
return [];
|
||||
});
|
||||
|
||||
return { promise, progress$: progressSubject.asObservable() };
|
||||
}
|
||||
|
||||
clearCache() {
|
||||
this.geoCache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class PlanningInputService {
|
||||
private pdvFile: File | null = null;
|
||||
private usuariosFile: File | null = null;
|
||||
|
||||
setFiles(pdvFile: File, usuariosFile: File): void {
|
||||
this.pdvFile = pdvFile;
|
||||
this.usuariosFile = usuariosFile;
|
||||
}
|
||||
|
||||
getFormData(): FormData | null {
|
||||
if (!this.pdvFile || !this.usuariosFile) return null;
|
||||
const data = new FormData();
|
||||
data.append('pdv_file', this.pdvFile, this.pdvFile.name);
|
||||
data.append('usuarios_file', this.usuariosFile, this.usuariosFile.name);
|
||||
return data;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.pdvFile = null;
|
||||
this.usuariosFile = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { RuteroProyecto, RuteroProyectoPdv } from '../models/project.model';
|
||||
import { supabaseClient } from './supabase.client';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ProjectService {
|
||||
async list(): Promise<RuteroProyecto[]> {
|
||||
const { data, error } = await supabaseClient.from('rutero_proyectos').select('*').order('updated_at', { ascending: false });
|
||||
if (error) throw error;
|
||||
return (data ?? []) as RuteroProyecto[];
|
||||
}
|
||||
|
||||
async get(id: string): Promise<RuteroProyecto> {
|
||||
const { data, error } = await supabaseClient.from('rutero_proyectos').select('*').eq('id', id).single();
|
||||
if (error) throw error;
|
||||
return data as RuteroProyecto;
|
||||
}
|
||||
|
||||
async update(id: string, changes: Partial<Pick<RuteroProyecto, 'nombre' | 'descripcion'>>): Promise<void> {
|
||||
const { error } = await supabaseClient.from('rutero_proyectos').update(changes).eq('id', id);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
const dependentTables = ['rutero_proyecto_rutas', 'rutero_proyecto_pdvs'];
|
||||
for (const table of dependentTables) {
|
||||
const { error } = await supabaseClient.from(table).delete().eq('proyecto_id', id);
|
||||
if (error) throw error;
|
||||
}
|
||||
const { error } = await supabaseClient.from('rutero_proyectos').delete().eq('id', id);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
async create(nombre: string, rows: Record<string, unknown>[]): Promise<RuteroProyecto> {
|
||||
const { data: sessionData, error: sessionError } = await supabaseClient.auth.getSession();
|
||||
if (sessionError) throw sessionError;
|
||||
const ownerId = sessionData.session?.user.id;
|
||||
if (!ownerId) throw new Error('No hay una sesión activa.');
|
||||
const projectId = crypto.randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const project: RuteroProyecto = {
|
||||
id: projectId,
|
||||
nombre: nombre.trim(),
|
||||
descripcion: null,
|
||||
propietario_id: ownerId,
|
||||
estado: 'borrador',
|
||||
version: 1,
|
||||
created_at: now,
|
||||
updated_at: now
|
||||
};
|
||||
const { error } = await supabaseClient
|
||||
.from('rutero_proyectos')
|
||||
.insert({ id: projectId, nombre: project.nombre, propietario_id: ownerId });
|
||||
if (error) throw error;
|
||||
const pdvs = rows.map((pdv, index) => ({
|
||||
proyecto_id: projectId,
|
||||
pdv_id: String(pdv['ID'] ?? pdv['id'] ?? pdv['Id'] ?? index + 1),
|
||||
pdv_data: pdv
|
||||
}));
|
||||
const { error: pdvError } = await supabaseClient.from('rutero_proyecto_pdvs').insert(pdvs);
|
||||
if (pdvError) {
|
||||
await supabaseClient.from('rutero_proyectos').delete().eq('id', projectId);
|
||||
throw pdvError;
|
||||
}
|
||||
return project;
|
||||
}
|
||||
|
||||
async pdvs(id: string): Promise<RuteroProyectoPdv[]> {
|
||||
const { data, error } = await supabaseClient.from('rutero_proyecto_pdvs').select('*').eq('proyecto_id', id).order('created_at');
|
||||
if (error) throw error;
|
||||
return (data ?? []) as RuteroProyectoPdv[];
|
||||
}
|
||||
|
||||
async projectInput(id: string): Promise<{ file: File; country: string }> {
|
||||
const pdvs = await this.pdvs(id);
|
||||
const rows = pdvs.map(pdv => pdv.pdv_data);
|
||||
const workbook = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(workbook, XLSX.utils.json_to_sheet(rows), 'PDVs');
|
||||
const data = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
|
||||
const country = rows.map(row => Object.entries(row).find(([key]) => {
|
||||
const normalized = key.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
|
||||
return normalized === 'pais' || normalized === 'country';
|
||||
})?.[1]).find(value => String(value ?? '').trim());
|
||||
return {
|
||||
file: new File([data], 'pdvs_proyecto.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
|
||||
country: String(country ?? 'Republica Dominicana').trim()
|
||||
};
|
||||
}
|
||||
|
||||
async pdvFile(id: string): Promise<File> {
|
||||
return (await this.projectInput(id)).file;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { ApiResponse } from '../../core/models/route.model';
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
import { ApiResponse } from '../models/route.model';
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { catchError, timeout, throwError } from 'rxjs';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class RutasService {
|
||||
@@ -9,8 +11,20 @@ export class RutasService {
|
||||
|
||||
calcularRutas(data: FormData) {
|
||||
return this.http.post<ApiResponse>(
|
||||
'https://agenteit.digitalcompass.agency/webhook/calcular-camino',
|
||||
environment.n8nWebhookUrl,
|
||||
data
|
||||
).pipe(
|
||||
timeout(environment.requestTimeoutMs),
|
||||
catchError((err: HttpErrorResponse | Error) => {
|
||||
if (err instanceof Error && err.name === 'TimeoutError') {
|
||||
return throwError(() => Object.assign(new Error(`Timeout al calcular rutas (${environment.requestTimeoutMs / 1000}s). Intenta con menos filas o reintenta.`), { name: 'TimeoutError' }));
|
||||
}
|
||||
return throwError(() => err);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
reoptimizarRutas(data: FormData) {
|
||||
return this.calcularRutas(data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createClient } from '@supabase/supabase-js';
|
||||
import { environment } from '../../../environments/environment';
|
||||
|
||||
export const supabaseClient = createClient(environment.supabaseUrl, environment.supabaseAnonKey, {
|
||||
auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: true }
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { UserProfile } from '../models/user-profile.model';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class UserProfileService {
|
||||
private readonly storageKey = 'rp_user_profile';
|
||||
private profile: UserProfile | null = null;
|
||||
avatarUrl = '';
|
||||
constructor() { this.restore(); }
|
||||
get current(): UserProfile | null { return this.profile; }
|
||||
clear(): void {
|
||||
this.profile = null;
|
||||
this.avatarUrl = '';
|
||||
sessionStorage.removeItem(this.storageKey);
|
||||
}
|
||||
|
||||
async load(email: string, avatarUrl = ''): Promise<UserProfile> {
|
||||
const controller = new AbortController();
|
||||
const timeout = window.setTimeout(() => controller.abort(), 15000);
|
||||
try {
|
||||
const response = await fetch(environment.userProfileWebhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }), signal: controller.signal });
|
||||
if (!response.ok) throw new Error(`El webhook respondió con ${response.status}.`);
|
||||
const data = await response.json() as Partial<UserProfile>;
|
||||
if (!data.nombre || !data.pais) throw new Error('El webhook no devolvió nombre y país.');
|
||||
this.profile = { nombre: data.nombre, pais: data.pais };
|
||||
this.avatarUrl = avatarUrl;
|
||||
sessionStorage.setItem(this.storageKey, JSON.stringify({ ...this.profile, avatarUrl }));
|
||||
return this.profile;
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === 'AbortError') throw new Error('La consulta de datos del usuario tardó demasiado.');
|
||||
throw error;
|
||||
} finally { window.clearTimeout(timeout); }
|
||||
}
|
||||
|
||||
private restore(): void {
|
||||
try {
|
||||
const stored = sessionStorage.getItem(this.storageKey);
|
||||
if (!stored) return;
|
||||
const data = JSON.parse(stored) as Partial<UserProfile> & { avatarUrl?: string };
|
||||
if (!data.nombre || !data.pais) return;
|
||||
this.profile = { nombre: data.nombre, pais: data.pais };
|
||||
this.avatarUrl = data.avatarUrl ?? '';
|
||||
} catch {
|
||||
sessionStorage.removeItem(this.storageKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
.employees-topbar { display: flex; align-items: center; gap: 12px; padding: 9px 24px; border-bottom: 3px solid var(--glm-verde); background: #fff; color: var(--glm-azul); font-weight: 700; }
|
||||
.user-profile { display:flex; align-items:center; gap:8px; margin-left:auto; color:var(--glm-azul); font-size:.84rem; font-weight:700; }.user-profile img,.avatar-fallback { width:30px; height:30px; border-radius:50%; }.user-profile img { object-fit:cover; }.avatar-fallback { display:inline-flex; align-items:center; justify-content:center; background:var(--glm-verde); color:#fff; }
|
||||
.employees-topbar img { height: 38px; width: auto; }
|
||||
.topbar-actions { display: flex; gap: 8px; margin-left: auto; }
|
||||
.topbar-actions button, .table-header button, .form-actions button, .row-actions button { border: 1px solid var(--glm-gris-medio); border-radius: 4px; background: #fff; color: var(--glm-azul); cursor: pointer; font: inherit; font-size: .78rem; font-weight: 600; padding: 7px 10px; }
|
||||
.topbar-actions button:hover, .table-header button:hover, .form-actions button:hover, .row-actions button:hover { background: var(--glm-verde-bg); border-color: var(--glm-verde); }
|
||||
.employees-page { max-width: 1200px; margin: 0 auto; padding: 24px; }
|
||||
.employees-page header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 18px; border-bottom: 3px solid var(--glm-verde); padding-bottom: 12px; }
|
||||
.employees-page h1, .employees-page h2 { margin: 0; color: var(--glm-azul); }
|
||||
.employees-page h1 { font-size: 1.45rem; }.employees-page h2 { font-size: 1rem; }
|
||||
.employees-page header p, .weekly-capacity { color: var(--glm-acero); }
|
||||
.import-button { display: inline-flex; align-items: center; gap: 6px; padding: 8px 11px; border: 1px solid var(--glm-verde); border-radius: 4px; background: var(--glm-verde-bg); color: var(--glm-azul); cursor: pointer; font-size: .82rem; font-weight: 700; }.import-button input { display: none; }.import-message { color: var(--glm-verde); font-weight: 600; }
|
||||
.employee-form-card, .employee-table-card { margin-top: 16px; padding: 18px; border: 1px solid var(--glm-gris-medio); border-top: 3px solid var(--glm-azul); border-radius: 4px; background: #fff; }
|
||||
.employee-form-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin-top: 16px; }
|
||||
.employee-form-grid label { display: flex; flex-direction: column; gap: 4px; color: var(--glm-azul); font-size: .75rem; font-weight: 700; text-transform: uppercase; }
|
||||
.employee-form-grid input, .employee-form-grid select { padding: 8px; border: 1px solid #9aaab3; border-radius: 4px; background: #fff; color: #2f3f48; font: inherit; font-weight: 500; text-transform: none; }
|
||||
.employee-form-grid input::placeholder { color: #71808a; opacity: 1; }
|
||||
.employee-form-grid input:focus, .employee-form-grid select:focus { outline: 2px solid rgba(108, 194, 74, .35); border-color: var(--glm-verde); background: #fff; color: #1f2d34; }
|
||||
.form-actions { display: flex; gap: 8px; }.form-actions button:first-child { background: var(--glm-azul); color: #fff; }.form-error { color: #c9252d; font-size: .82rem; }.table-header { display: flex; justify-content: space-between; align-items: center; gap: 12px; }.table-wrap { overflow-x: auto; margin-top: 12px; }table { width: 100%; min-width: 920px; border-collapse: collapse; font-size: .82rem; }th { padding: 9px; background: var(--glm-azul); color: #fff; text-align: left; }td { padding: 9px; border-bottom: 1px solid var(--glm-gris-claro); color: var(--glm-gris-oscuro); }.status { color: var(--glm-verde); font-weight: 700; }.status.inactive { color: #c9252d; }.row-actions { display: flex; gap: 5px; }.row-actions .delete { color: #c9252d; }.loading { color: var(--glm-acero); }.rest-days-button { max-width: 155px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.rest-days-picker { display: grid; gap: 4px; margin-top: 6px; padding: 6px; border: 1px solid var(--glm-gris-medio); background: #fff; }.rest-days-picker label { font-size: .72rem; white-space: nowrap; }
|
||||
.editing-row { background: var(--glm-verde-bg); }.editing-row select, .inline-number { width: 100%; min-width: 92px; box-sizing: border-box; padding: 7px; border: 1px solid var(--glm-verde); border-radius: 4px; font: inherit; }.inline-number { max-width: 100px; }.inline-picker { min-width: 130px; margin: 0; }.editing-row .row-actions { flex-wrap: wrap; }
|
||||
@media (max-width: 760px) { .employees-page { padding: 16px; }.employee-form-grid { grid-template-columns: 1fr; }.employees-topbar { padding: 9px 16px; }.topbar-actions button { font-size: 0; }.topbar-actions button i { font-size: .9rem; } }
|
||||
@@ -0,0 +1,50 @@
|
||||
<div class="employees-topbar">
|
||||
<img src="GLM_completo.png" alt="GomezLee Marketing" />
|
||||
<span>Route Planner</span><div class="user-profile" *ngIf="profile.current"><img *ngIf="profile.avatarUrl" [src]="profile.avatarUrl" alt=""><span *ngIf="!profile.avatarUrl" class="avatar-fallback">{{ profile.current.nombre.charAt(0) }}</span><span>{{ profile.current.nombre }}</span></div>
|
||||
<div class="topbar-actions"><button type="button" (click)="goBack()"><i class="pi pi-arrow-left"></i> Volver</button><button type="button" (click)="goHome()"><i class="pi pi-home"></i> Proyectos</button><button type="button" (click)="signOut()"><i class="pi pi-sign-out"></i> Salir</button></div>
|
||||
</div>
|
||||
|
||||
<main class="employees-page">
|
||||
<header><div><h1>Gestionar empleados</h1><p>{{ activeEmployees }} activos de {{ employees.length }} empleados registrados</p></div><label class="import-button"><i class="pi pi-file-import"></i> {{ importing ? 'Importando...' : 'Importar empleados' }}<input type="file" accept=".xlsx,.xls" (change)="importFile($event)" [disabled]="importing"></label></header>
|
||||
<p class="import-message" *ngIf="importMessage">{{ importMessage }}</p>
|
||||
|
||||
<section class="employee-form-card">
|
||||
<h2>Nuevo empleado</h2>
|
||||
<form (ngSubmit)="save()" #employeeForm="ngForm">
|
||||
<div class="employee-form-grid">
|
||||
<label>ID<input name="employeeCode" [(ngModel)]="form.employee_code" required></label>
|
||||
<label>Nombre<input name="nombre" [(ngModel)]="form.nombre" required></label>
|
||||
<label>Usuario<input name="usuario" [(ngModel)]="form.usuario"></label>
|
||||
<label>Email<input type="email" name="email" [(ngModel)]="form.email"></label>
|
||||
<label>Perfil<input name="perfil" [(ngModel)]="form.perfil"></label>
|
||||
<label>Regional<input name="regional" [(ngModel)]="form.regional"></label>
|
||||
<label>País<input name="pais" [(ngModel)]="form.pais"></label>
|
||||
<label>Estado<select name="activo" [(ngModel)]="form.activo"><option [ngValue]="true">Activo</option><option [ngValue]="false">Inactivo</option></select></label>
|
||||
<label>Latitud<input type="number" name="latitud" [(ngModel)]="form.latitud" step="any" required></label>
|
||||
<label>Longitud<input type="number" name="longitud" [(ngModel)]="form.longitud" step="any" required></label>
|
||||
<label>Horas por día<input type="number" name="hoursDay" [(ngModel)]="form.horas_por_dia" min="0.5" max="24" step="0.5" required></label>
|
||||
<label>Jornada de trabajo<select name="schedule" [(ngModel)]="form.jornada_codigo"><option *ngFor="let schedule of schedules" [value]="schedule.code">{{ schedule.label }}</option></select></label>
|
||||
<label>Horas de descanso/día<input type="number" name="dailyRest" [(ngModel)]="form.horas_descanso_por_dia" min="0" max="3" step="1" required></label>
|
||||
<label>Visitas máximas/día<input type="number" name="visitsDay" [(ngModel)]="form.visitas_maximas_por_dia" min="1" required></label>
|
||||
</div>
|
||||
<p class="weekly-capacity">Capacidad semanal: {{ selectedScheduleHours }} h · Capacidad diaria efectiva: {{ form.horas_por_dia - form.horas_descanso_por_dia | number:'1.0-1' }} h</p>
|
||||
<p class="form-error" *ngIf="error">{{ error }}</p>
|
||||
<div class="form-actions"><button type="submit" [disabled]="saving || employeeForm.invalid"><i class="pi pi-save"></i> {{ saving ? 'Guardando...' : 'Agregar empleado' }}</button></div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="employee-table-card">
|
||||
<div class="table-header"><h2>Empleados registrados</h2><button type="button" (click)="load()" [disabled]="loading"><i class="pi pi-refresh"></i> Actualizar</button></div>
|
||||
<p class="form-error" *ngIf="error && !loading">{{ error }}</p>
|
||||
<p class="loading" *ngIf="loading">Cargando empleados...</p>
|
||||
<div class="table-wrap" *ngIf="!loading">
|
||||
<table>
|
||||
<thead><tr><th>ID</th><th>Nombre</th><th>Regional</th><th>Jornada</th><th>Descanso/día</th><th>Días de descanso</th><th>Visitas/día</th><th>Estado</th><th>Acciones</th></tr></thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let employee of employees" [class.editing-row]="editingId === employee.id"><td>{{ employee.employee_code }}</td><td>{{ employee.nombre }}</td><td>{{ employee.regional || '-' }}</td><td><ng-container *ngIf="editingId === employee.id; else scheduleText"><select [(ngModel)]="employee.jornada_codigo" [name]="'schedule-' + employee.id" (ngModelChange)="onInlineScheduleChange(employee)"><option *ngFor="let schedule of schedules" [value]="schedule.code">{{ schedule.label }}</option></select></ng-container><ng-template #scheduleText>{{ scheduleLabel(employee) }}</ng-template></td><td><ng-container *ngIf="editingId === employee.id; else restText"><input class="inline-number" type="number" [(ngModel)]="employee.horas_descanso_por_dia" [name]="'rest-' + employee.id" min="0" max="3" step="1"></ng-container><ng-template #restText>{{ employee.horas_descanso_por_dia }} h</ng-template></td><td><ng-container *ngIf="editingId === employee.id; else daysText"><div class="rest-days-picker inline-picker"><label *ngFor="let day of availableRestDays(employee)"><input type="checkbox" [checked]="employee.dias_descanso.includes(day)" (change)="toggleRestDay(employee, day, $any($event.target).checked)">{{ day }}</label></div></ng-container><ng-template #daysText>{{ employee.dias_descanso.length ? employee.dias_descanso.join(', ') : 'Ninguno' }}</ng-template></td><td><ng-container *ngIf="editingId === employee.id; else visitsText"><input class="inline-number" type="number" [(ngModel)]="employee.visitas_maximas_por_dia" [name]="'visits-' + employee.id" min="1" step="1"></ng-container><ng-template #visitsText>{{ employee.visitas_maximas_por_dia }}</ng-template></td><td><span class="status" [class.inactive]="!employee.activo">{{ employee.activo ? 'Activo' : 'Inactivo' }}</span></td><td class="row-actions"><ng-container *ngIf="editingId === employee.id; else normalActions"><button type="button" (click)="saveInline(employee)" [disabled]="saving">Guardar</button><button type="button" (click)="cancelEdit()" [disabled]="saving">Cancelar</button></ng-container><ng-template #normalActions><button type="button" (click)="edit(employee)">Editar</button><button type="button" (click)="toggleActive(employee)">{{ employee.activo ? 'Desactivar' : 'Activar' }}</button><button type="button" class="delete" (click)="remove(employee)">Eliminar</button></ng-template></td></tr>
|
||||
<tr *ngIf="!employees.length"><td colspan="9">No hay empleados registrados.</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
@@ -0,0 +1,281 @@
|
||||
import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { Location } from '@angular/common';
|
||||
import { Employee, EmployeeInput } from '../../core/models/employee.model';
|
||||
import { EmployeeService } from '../../core/services/employee.service';
|
||||
import { AuthService } from '../../core/services/auth.service';
|
||||
import { UserProfileService } from '../../core/services/user-profile.service';
|
||||
import { WORK_SCHEDULES, workSchedule } from '../../core/models/work-schedule.model';
|
||||
import { normalizeRow, cleanNum } from '../../shared/utils/header-normalization.utils';
|
||||
import * as XLSX from 'xlsx';
|
||||
|
||||
type EmployeeForm = Omit<EmployeeInput, 'activo'> & { activo: boolean };
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
selector: 'app-employees',
|
||||
imports: [CommonModule, FormsModule],
|
||||
templateUrl: './employees.component.html',
|
||||
styleUrls: ['./employees.component.css']
|
||||
})
|
||||
export class EmployeesComponent implements OnDestroy, OnInit {
|
||||
employees: Employee[] = [];
|
||||
form = this.emptyForm();
|
||||
editingId: string | null = null;
|
||||
loading = true;
|
||||
saving = false;
|
||||
error = '';
|
||||
importMessage = '';
|
||||
importing = false;
|
||||
openRestDaysFor: string | null = null;
|
||||
readonly schedules = WORK_SCHEDULES;
|
||||
private destroyed = false;
|
||||
private loadSequence = 0;
|
||||
|
||||
constructor(
|
||||
private employeesService: EmployeeService,
|
||||
private auth: AuthService,
|
||||
private router: Router,
|
||||
private location: Location,
|
||||
public profile: UserProfileService,
|
||||
private cdr: ChangeDetectorRef
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
void this.load();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroyed = true;
|
||||
this.loadSequence++;
|
||||
}
|
||||
|
||||
get activeEmployees(): number {
|
||||
return this.employees.filter(employee => employee.activo).length;
|
||||
}
|
||||
|
||||
get selectedScheduleHours(): number {
|
||||
return workSchedule(this.form.jornada_codigo).weeklyHours;
|
||||
}
|
||||
|
||||
async load(): Promise<void> {
|
||||
const sequence = ++this.loadSequence;
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
try {
|
||||
const employees = await this.employeesService.list();
|
||||
if (this.destroyed || sequence !== this.loadSequence) return;
|
||||
this.employees = employees;
|
||||
this.cdr.detectChanges();
|
||||
} catch (error: any) {
|
||||
if (!this.destroyed && sequence === this.loadSequence) {
|
||||
this.error = error?.message ?? 'No se pudieron cargar los empleados.';
|
||||
}
|
||||
} finally {
|
||||
this.loading = false;
|
||||
if (!this.destroyed && sequence === this.loadSequence) this.cdr.detectChanges();
|
||||
}
|
||||
}
|
||||
|
||||
edit(employee: Employee): void {
|
||||
this.editingId = employee.id;
|
||||
}
|
||||
|
||||
cancelEdit(): void {
|
||||
this.editingId = null;
|
||||
this.error = '';
|
||||
void this.load();
|
||||
}
|
||||
|
||||
async saveInline(employee: Employee): Promise<void> {
|
||||
const rest = Number(employee.horas_descanso_por_dia);
|
||||
const visits = Number(employee.visitas_maximas_por_dia);
|
||||
if (!Number.isInteger(rest) || rest < 0 || rest > 3 || !Number.isInteger(visits) || visits < 1) {
|
||||
this.error = 'Descanso/día debe ser un entero entre 0 y 3, y Visitas/día debe ser un entero mayor que 0.';
|
||||
return;
|
||||
}
|
||||
this.saving = true;
|
||||
this.error = '';
|
||||
try {
|
||||
await this.employeesService.update(employee.id, {
|
||||
...employee,
|
||||
dias_por_semana: workSchedule(employee.jornada_codigo).days.length,
|
||||
horas_descanso_por_dia: rest,
|
||||
visitas_maximas_por_dia: visits,
|
||||
dias_descanso: (employee.dias_descanso ?? []).filter(day => workSchedule(employee.jornada_codigo).days.includes(day))
|
||||
});
|
||||
this.editingId = null;
|
||||
await this.load();
|
||||
} catch (error: any) {
|
||||
this.error = error?.message ?? 'No se pudo actualizar el empleado.';
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
onInlineScheduleChange(employee: Employee): void {
|
||||
employee.dias_descanso = (employee.dias_descanso ?? []).filter(day => workSchedule(employee.jornada_codigo).days.includes(day));
|
||||
employee.dias_por_semana = workSchedule(employee.jornada_codigo).days.length;
|
||||
}
|
||||
|
||||
async save(): Promise<void> {
|
||||
if (!this.form.employee_code.trim() || !this.form.nombre.trim()) {
|
||||
this.error = 'El ID y el nombre son obligatorios.';
|
||||
return;
|
||||
}
|
||||
if (this.form.horas_descanso_por_dia >= this.form.horas_por_dia) {
|
||||
this.error = 'Las horas de descanso deben ser menores que las horas de trabajo diarias.';
|
||||
return;
|
||||
}
|
||||
this.saving = true;
|
||||
this.error = '';
|
||||
const employee: EmployeeInput = {
|
||||
...this.form,
|
||||
dias_por_semana: workSchedule(this.form.jornada_codigo).days.length,
|
||||
employee_code: this.form.employee_code.trim(),
|
||||
nombre: this.form.nombre.trim(),
|
||||
usuario: this.nullable(this.form.usuario),
|
||||
email: this.nullable(this.form.email),
|
||||
perfil: this.nullable(this.form.perfil),
|
||||
pais: this.nullable(this.form.pais),
|
||||
regional: this.nullable(this.form.regional)
|
||||
};
|
||||
try {
|
||||
if (this.editingId) await this.employeesService.update(this.editingId, employee);
|
||||
else await this.employeesService.create(employee);
|
||||
this.cancelEdit();
|
||||
await this.load();
|
||||
} catch (error: any) {
|
||||
this.error = error?.message ?? 'No se pudo guardar el empleado.';
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async toggleActive(employee: Employee): Promise<void> {
|
||||
try {
|
||||
await this.employeesService.update(employee.id, { ...employee, activo: !employee.activo });
|
||||
await this.load();
|
||||
} catch (error: any) {
|
||||
this.error = error?.message ?? 'No se pudo actualizar el estado.';
|
||||
}
|
||||
}
|
||||
|
||||
scheduleLabel(employee: Employee): string {
|
||||
return workSchedule(employee.jornada_codigo).label;
|
||||
}
|
||||
|
||||
availableRestDays(employee: Employee): string[] {
|
||||
return workSchedule(employee.jornada_codigo).days;
|
||||
}
|
||||
|
||||
toggleRestDayEditor(employee: Employee): void {
|
||||
this.openRestDaysFor = this.openRestDaysFor === employee.id ? null : employee.id;
|
||||
}
|
||||
|
||||
async toggleRestDay(employee: Employee, day: string, checked: boolean): Promise<void> {
|
||||
const days = new Set(employee.dias_descanso ?? []);
|
||||
checked ? days.add(day) : days.delete(day);
|
||||
employee.dias_descanso = Array.from(days);
|
||||
}
|
||||
|
||||
async importFile(event: Event): Promise<void> {
|
||||
const file = (event.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
this.importing = true;
|
||||
this.importMessage = '';
|
||||
this.error = '';
|
||||
try {
|
||||
const workbook = XLSX.read(await file.arrayBuffer(), { type: 'array' });
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const rows = XLSX.utils.sheet_to_json(sheet, { defval: null, raw: true }).map(row => normalizeRow(row as Record<string, unknown>));
|
||||
const employees = rows.map((row, index) => this.fromExcelRow(row, index + 2));
|
||||
const invalid = employees.filter((employee): employee is null => employee === null).length;
|
||||
const valid = employees.filter((employee): employee is EmployeeInput => employee !== null);
|
||||
if (!valid.length) throw new Error('El archivo no contiene empleados válidos.');
|
||||
await this.employeesService.upsert(valid);
|
||||
this.importMessage = `${valid.length} empleados guardados${invalid ? `; ${invalid} filas omitidas por datos inválidos` : ''}.`;
|
||||
await this.load();
|
||||
} catch (error: any) {
|
||||
this.error = error?.message ?? 'No se pudo importar el archivo.';
|
||||
} finally {
|
||||
this.importing = false;
|
||||
(event.target as HTMLInputElement).value = '';
|
||||
}
|
||||
}
|
||||
|
||||
async remove(employee: Employee): Promise<void> {
|
||||
if (!window.confirm(`¿Eliminar a ${employee.nombre}? Esta acción no se puede deshacer.`)) return;
|
||||
try {
|
||||
await this.employeesService.remove(employee.id);
|
||||
await this.load();
|
||||
} catch (error: any) {
|
||||
this.error = error?.message ?? 'No se pudo eliminar el empleado.';
|
||||
}
|
||||
}
|
||||
|
||||
async signOut(): Promise<void> {
|
||||
this.destroyed = true;
|
||||
this.loadSequence++;
|
||||
this.employees = [];
|
||||
this.loading = true;
|
||||
await this.auth.signOut();
|
||||
await this.router.navigate(['/login']);
|
||||
}
|
||||
|
||||
async goHome(): Promise<void> {
|
||||
await this.router.navigate(['/home']);
|
||||
}
|
||||
|
||||
goBack(): void {
|
||||
if (history.length > 1) this.location.back();
|
||||
else void this.router.navigate(['/home']);
|
||||
}
|
||||
|
||||
private nullable(value: string | null): string | null {
|
||||
return value?.trim() || null;
|
||||
}
|
||||
|
||||
private emptyForm(): EmployeeForm {
|
||||
return {
|
||||
employee_code: '', nombre: '', usuario: '', email: '', perfil: 'Promotor', pais: 'Republica Dominicana', regional: '',
|
||||
latitud: 18.4861, longitud: -69.9312, horas_por_dia: 8, dias_por_semana: 5, jornada_codigo: 'LUN_VIE_40', horas_descanso_por_dia: 1, dias_descanso: [], visitas_maximas_por_dia: 3, activo: true
|
||||
};
|
||||
}
|
||||
|
||||
private fromExcelRow(row: Record<string, unknown>, excelRow: number): EmployeeInput | null {
|
||||
const code = String(row['id'] ?? '').trim();
|
||||
const nombre = String(row['nombre_del_empleado'] ?? '').trim();
|
||||
const latitude = cleanNum(row['latitud']);
|
||||
const longitude = cleanNum(row['longitud']);
|
||||
const dailyHours = cleanNum(row['horas_por_dia_usuario']);
|
||||
const weeklyHours = cleanNum(row['horas_por_semana_usuario']);
|
||||
if (!code || !nombre || !Number.isFinite(latitude) || !Number.isFinite(longitude) || !Number.isFinite(dailyHours)) return null;
|
||||
const jornadaTexto = String(row['jornada'] ?? '').trim();
|
||||
const jornadaCodigo = this.schedules.some(schedule => schedule.code === jornadaTexto)
|
||||
? jornadaTexto
|
||||
: weeklyHours === 44 ? 'LUN_SAB_44' : 'LUN_VIE_40';
|
||||
const restDays = String(row['dias_descanso'] ?? '').split(',').map(day => day.trim()).filter(day => workSchedule(jornadaCodigo).days.includes(day));
|
||||
const active = !['no', 'n', '0', 'false'].includes(String(row['usuario_activo'] ?? 'si').trim().toLowerCase());
|
||||
return {
|
||||
employee_code: code,
|
||||
nombre,
|
||||
usuario: this.nullable(String(row['usuario'] ?? '')),
|
||||
email: this.nullable(String(row['email'] ?? '')),
|
||||
perfil: this.nullable(String(row['perfil_de_acceso'] ?? '')),
|
||||
pais: this.nullable(String(row['pais'] ?? '')),
|
||||
regional: this.nullable(String(row['regionales'] ?? row['regional'] ?? '')),
|
||||
latitud: latitude,
|
||||
longitud: longitude,
|
||||
horas_por_dia: dailyHours,
|
||||
dias_por_semana: workSchedule(jornadaCodigo).days.length,
|
||||
jornada_codigo: jornadaCodigo,
|
||||
horas_descanso_por_dia: Math.min(3, Math.max(0, Math.round(cleanNum(row['horas_descanso_por_dia']) || 1))),
|
||||
dias_descanso: restDays,
|
||||
visitas_maximas_por_dia: Math.max(1, cleanNum(row['visitas_maximas_por_dia']) || 3),
|
||||
activo: active
|
||||
};
|
||||
}
|
||||
}
|
||||
+34
@@ -196,3 +196,37 @@
|
||||
background: var(--glm-verde);
|
||||
border: 3px solid #fff;
|
||||
}
|
||||
|
||||
.location-pin {
|
||||
position: relative;
|
||||
width: 30px;
|
||||
height: 38px;
|
||||
background: #c9252d;
|
||||
clip-path: polygon(50% 100%, 8% 43%, 5% 31%, 10% 18%, 22% 7%, 36% 2%, 50% 0, 64% 2%, 78% 7%, 90% 18%, 95% 31%, 92% 43%);
|
||||
filter: drop-shadow(0 2px 2px rgba(0, 0, 0, 0.42));
|
||||
}
|
||||
|
||||
.location-pin:hover {
|
||||
transform: scale(1.12);
|
||||
transform-origin: center bottom;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.location-pin::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 3px 3px 7px;
|
||||
background: #ff424a;
|
||||
clip-path: polygon(50% 100%, 8% 43%, 5% 31%, 10% 18%, 22% 7%, 36% 2%, 50% 0, 64% 2%, 78% 7%, 90% 18%, 95% 31%, 92% 43%);
|
||||
}
|
||||
|
||||
.location-pin::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
background: #620000;
|
||||
}
|
||||
|
||||
+2
@@ -25,6 +25,8 @@
|
||||
<div><dt>Usuario</dt><dd>{{ routeData.json.nombre_usuario }}</dd></div>
|
||||
<div><dt>PDV</dt><dd>{{ routeData.json.nombre_pdv }}</dd></div>
|
||||
<div><dt>Día</dt><dd>{{ routeData.json.dia }}</dd></div>
|
||||
<div><dt>Orden</dt><dd>{{ visitOrder }} de {{ totalStops }}</dd></div>
|
||||
<div><dt>Origen del tramo</dt><dd>{{ segmentOriginName }}</dd></div>
|
||||
<div><dt>Distancia</dt><dd>{{ routeData.json.distancia }} km</dd></div>
|
||||
<div><dt>Duración</dt><dd>{{ (routeData.json.horas_desplazamiento * 60).toFixed(0) }} min</dd></div>
|
||||
<div><dt>Horas trabajo</dt><dd>{{ routeData.json.horas_trabajo }}</dd></div>
|
||||
|
||||
+114
-39
@@ -1,11 +1,12 @@
|
||||
import { Component, OnInit, OnDestroy, AfterViewInit, ChangeDetectorRef } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Router } from '@angular/router';
|
||||
import { Router, ActivatedRoute } from '@angular/router';
|
||||
import { Subscription } from 'rxjs';
|
||||
import * as L from 'leaflet';
|
||||
import { RouteState } from '../../../core/route-state/route';
|
||||
import { OrsService } from '../../../core/services/ors.service';
|
||||
import { RouteAssignedResponse } from '../../../core/models/route.model';
|
||||
import { sequenceRoutes } from '../../../shared/utils/route-sequencing.utils';
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
@@ -26,9 +27,13 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
routeData: RouteAssignedResponse | null = null;
|
||||
isLoading = false;
|
||||
error: string | null = null;
|
||||
segmentOriginName = '';
|
||||
visitOrder = 0;
|
||||
totalStops = 0;
|
||||
|
||||
constructor(
|
||||
private router: Router,
|
||||
private activatedRoute: ActivatedRoute,
|
||||
private routeState: RouteState,
|
||||
private orsService: OrsService,
|
||||
private cdr: ChangeDetectorRef
|
||||
@@ -36,11 +41,30 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
|
||||
ngOnInit() {
|
||||
this.sub = this.routeState.selectedRoute$.subscribe((route: RouteAssignedResponse | null) => {
|
||||
this.routeData = route;
|
||||
if (route && this.map) {
|
||||
this.loadAndShowRoute(route);
|
||||
} else if (!route) {
|
||||
this.error = 'No hay ruta seleccionada';
|
||||
if (route) {
|
||||
this.routeData = route;
|
||||
if (this.map) {
|
||||
this.loadAndShowRoute(route);
|
||||
}
|
||||
this.error = null;
|
||||
} else {
|
||||
// Try to resolve from queryParams + sessionStorage snapshot
|
||||
const qp = this.activatedRoute.snapshot.queryParams;
|
||||
const pdvId = qp['pdv_id'];
|
||||
const usuarioId = qp['usuario_id'];
|
||||
if (pdvId) {
|
||||
const found = this.routeState.findRoute(pdvId, usuarioId);
|
||||
if (found) {
|
||||
this.routeData = found;
|
||||
if (this.map) this.loadAndShowRoute(found);
|
||||
this.error = null;
|
||||
} else {
|
||||
// No data at all (e.g., direct URL after hard refresh with empty storage)
|
||||
this.error = 'No hay ruta seleccionada. Vuelve al listado y selecciona una ruta.';
|
||||
}
|
||||
} else if (!this.routeData) {
|
||||
this.error = 'No hay ruta seleccionada';
|
||||
}
|
||||
}
|
||||
this.cdr.detectChanges();
|
||||
});
|
||||
@@ -50,6 +74,18 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
this.initMap();
|
||||
if (this.routeData) {
|
||||
this.loadAndShowRoute(this.routeData);
|
||||
} else {
|
||||
// Re-attempt resolution after map init (queryParams case)
|
||||
const qp = this.activatedRoute.snapshot.queryParams;
|
||||
if (qp['pdv_id']) {
|
||||
const found = this.routeState.findRoute(qp['pdv_id'], qp['usuario_id']);
|
||||
if (found) {
|
||||
this.routeData = found;
|
||||
this.error = null;
|
||||
this.loadAndShowRoute(found);
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,10 +99,26 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
}
|
||||
|
||||
private initMap() {
|
||||
this.map = L.map('map').setView([18.4861, -69.9312], 13);
|
||||
const territoryBounds = this.routeData ? L.latLngBounds([
|
||||
[Number(this.routeData.json.latitud_usuario), Number(this.routeData.json.longitud_usuario)],
|
||||
[Number(this.routeData.json.latitud_pdv), Number(this.routeData.json.longitud_pdv)]
|
||||
]) : null;
|
||||
this.map = L.map('map', { maxBoundsViscosity: 0.85 });
|
||||
if (territoryBounds?.isValid()) {
|
||||
this.map.fitBounds(territoryBounds.pad(0.3));
|
||||
this.map.setMaxBounds(territoryBounds.pad(0.6));
|
||||
} else {
|
||||
this.map.setView([18.4861, -69.9312], 13);
|
||||
}
|
||||
const pdvPane = this.map.createPane('pdvPane');
|
||||
pdvPane.style.zIndex = '650';
|
||||
|
||||
this.tileLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
attribution: '© OpenStreetMap contributors'
|
||||
attribution: '© OpenStreetMap contributors',
|
||||
bounds: territoryBounds?.isValid() ? territoryBounds.pad(0.6) : undefined,
|
||||
keepBuffer: 1,
|
||||
noWrap: true,
|
||||
updateWhenIdle: true
|
||||
}).addTo(this.map);
|
||||
}
|
||||
|
||||
@@ -77,13 +129,27 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
this.cdr.detectChanges();
|
||||
|
||||
const json = route.json;
|
||||
const origin: [number, number] = [Number(json.longitud_usuario), Number(json.latitud_usuario)];
|
||||
const sequence = sequenceRoutes(this.routeState.getAssignedSnapshot().filter(item =>
|
||||
String(item.json.usuario_id) === String(json.usuario_id) && item.json.dia === json.dia
|
||||
));
|
||||
const segment = sequence.find(item => item.route === route) ?? sequence.find(item => item.route.json.pdv_id === json.pdv_id);
|
||||
const origin: [number, number] = segment?.origin ?? [Number(json.longitud_usuario), Number(json.latitud_usuario)];
|
||||
const destination: [number, number] = [Number(json.longitud_pdv), Number(json.latitud_pdv)];
|
||||
this.segmentOriginName = segment?.previousPdvName ?? `Casa de ${json.nombre_usuario}`;
|
||||
this.visitOrder = segment?.order ?? 1;
|
||||
this.totalStops = segment?.totalStops ?? 1;
|
||||
|
||||
this.centerMapOnPoints(origin, destination);
|
||||
|
||||
if (json.geojson) {
|
||||
this.showRouteOnMap(json.geojson, origin, destination, json, this.segmentOriginName);
|
||||
this.isLoading = false;
|
||||
this.cdr.detectChanges();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const geojson = await this.orsService.processPairs(
|
||||
const results = await this.orsService.processPairs(
|
||||
[{ pdv_id: json.pdv_id, origin, destination }],
|
||||
1,
|
||||
true
|
||||
@@ -91,13 +157,14 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
|
||||
if (this.destroyed) return;
|
||||
|
||||
if (geojson[0] && !geojson[0].error) {
|
||||
this.showRouteOnMap(geojson[0], origin, destination, json);
|
||||
const result = results[0] as { error?: string; geojson?: unknown } | undefined;
|
||||
if (result && !result.error && result.geojson) {
|
||||
this.showRouteOnMap(result.geojson, origin, destination, json, this.segmentOriginName);
|
||||
} else {
|
||||
this.showFallbackRoute(origin, destination, json);
|
||||
this.showFallbackRoute(origin, destination, json, this.segmentOriginName);
|
||||
}
|
||||
} catch {
|
||||
this.showFallbackRoute(origin, destination, json);
|
||||
this.showFallbackRoute(origin, destination, json, this.segmentOriginName);
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
this.cdr.detectChanges();
|
||||
@@ -112,31 +179,38 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
this.map.fitBounds(bounds.pad(0.3));
|
||||
}
|
||||
|
||||
private extractCoords(geojson: any): L.LatLngExpression[] {
|
||||
if (geojson.type === 'FeatureCollection' && geojson.features?.length) {
|
||||
return geojson.features[0].geometry.coordinates.map(
|
||||
private extractCoords(geojson: unknown): L.LatLngExpression[] {
|
||||
const g = geojson as { type: string; features?: { geometry: { coordinates: number[][] } }[]; coordinates?: number[][] };
|
||||
if (g.type === 'FeatureCollection' && g.features?.length) {
|
||||
return g.features[0].geometry.coordinates.map(
|
||||
(c: number[]) => [c[1], c[0]] as L.LatLngExpression
|
||||
);
|
||||
}
|
||||
if (geojson.type === 'LineString') {
|
||||
return geojson.coordinates.map(
|
||||
if (g.type === 'LineString' && g.coordinates) {
|
||||
return g.coordinates.map(
|
||||
(c: number[]) => [c[1], c[0]] as L.LatLngExpression
|
||||
);
|
||||
}
|
||||
// ORS geojson response wrapped
|
||||
const maybeFeature = (geojson as { features?: { geometry: { coordinates: number[][] } }[] })?.features;
|
||||
if (maybeFeature?.length) {
|
||||
return maybeFeature[0].geometry.coordinates.map(c => [c[1], c[0]] as L.LatLngExpression);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private showRouteOnMap(geojson: any, origin: [number, number], destination: [number, number], json: any) {
|
||||
private showRouteOnMap(geojson: unknown, origin: [number, number], destination: [number, number], json: RouteAssignedResponse['json'], originName: string) {
|
||||
const coords = this.extractCoords(geojson);
|
||||
if (!coords.length) {
|
||||
this.showFallbackRoute(origin, destination, json);
|
||||
this.showFallbackRoute(origin, destination, json, originName);
|
||||
return;
|
||||
}
|
||||
|
||||
const distance = geojson.features?.[0]?.properties?.summary?.distance
|
||||
? (geojson.features[0].properties.summary.distance / 1000).toFixed(2) : 'N/A';
|
||||
const duration = geojson.features?.[0]?.properties?.summary?.duration
|
||||
? (geojson.features[0].properties.summary.duration / 60).toFixed(0) : 'N/A';
|
||||
const g = geojson as { features?: { properties?: { summary?: { distance: number; duration: number } } }[] };
|
||||
const distance = g.features?.[0]?.properties?.summary?.distance
|
||||
? (g.features[0].properties.summary.distance / 1000).toFixed(2) : 'N/A';
|
||||
const duration = g.features?.[0]?.properties?.summary?.duration
|
||||
? (g.features[0].properties.summary.duration / 60).toFixed(0) : 'N/A';
|
||||
|
||||
this.routeGlow = L.polyline(coords, {
|
||||
color: '#6CC24A',
|
||||
@@ -163,11 +237,11 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
lineCap: 'round'
|
||||
}).addTo(this.map);
|
||||
|
||||
this.routeLine.bindPopup(
|
||||
`<strong style="color:#4F758B">${json.nombre_usuario} → ${json.nombre_pdv}</strong><br>Distancia: ${distance} km<br>Duración: ${duration} min`
|
||||
(this.routeLine as L.Polyline).bindPopup(
|
||||
`<strong style="color:#4F758B">${originName} → ${json.nombre_pdv}</strong><br>Distancia: ${distance} km<br>Duración: ${duration} min`
|
||||
);
|
||||
|
||||
this.addMarkers(origin, destination, json, distance, duration);
|
||||
this.addMarkers(origin, destination, json, distance, duration, originName);
|
||||
const group = new L.FeatureGroup([
|
||||
...(this.routeGlow ? [this.routeGlow] : []),
|
||||
...(this.routeLine ? [this.routeLine] : []),
|
||||
@@ -176,13 +250,13 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
this.map.fitBounds(group.getBounds().pad(0.1));
|
||||
}
|
||||
|
||||
private showFallbackRoute(origin: [number, number], destination: [number, number], json: any) {
|
||||
private showFallbackRoute(origin: [number, number], destination: [number, number], json: RouteAssignedResponse['json'], originName: string) {
|
||||
this.routeLine = L.polyline(
|
||||
[[origin[1], origin[0]], [destination[1], destination[0]]],
|
||||
{ color: '#FF6A13', weight: 5, dashArray: '12, 10', opacity: 0.9 }
|
||||
).addTo(this.map);
|
||||
|
||||
this.addMarkers(origin, destination, json, 'N/A', 'N/A');
|
||||
this.addMarkers(origin, destination, json, 'N/A', 'N/A', originName);
|
||||
const group = new L.FeatureGroup([this.routeLine, ...this.markers]);
|
||||
this.map.fitBounds(group.getBounds().pad(0.1));
|
||||
}
|
||||
@@ -190,9 +264,10 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
private addMarkers(
|
||||
origin: [number, number],
|
||||
destination: [number, number],
|
||||
json: any,
|
||||
json: RouteAssignedResponse['json'],
|
||||
distance: string,
|
||||
duration: string
|
||||
duration: string,
|
||||
originName: string
|
||||
) {
|
||||
const startIcon = L.divIcon({
|
||||
className: 'custom-marker marker-start',
|
||||
@@ -204,19 +279,19 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
|
||||
const endIcon = L.divIcon({
|
||||
className: 'custom-marker marker-end',
|
||||
html: '<div class="marker-inner">B</div>',
|
||||
iconSize: [30, 30],
|
||||
iconAnchor: [15, 15],
|
||||
html: '<div class="location-pin"><span></span></div>',
|
||||
iconSize: [30, 38],
|
||||
iconAnchor: [15, 38],
|
||||
popupAnchor: [0, -18]
|
||||
});
|
||||
|
||||
this.markers.push(
|
||||
L.marker([origin[1], origin[0]], { icon: startIcon })
|
||||
.addTo(this.map)
|
||||
.bindPopup(`<strong>Origen:</strong> ${json.nombre_usuario}`),
|
||||
L.marker([destination[1], destination[0]], { icon: endIcon })
|
||||
.bindPopup(`<strong>Origen del tramo:</strong> ${originName}`),
|
||||
L.marker([destination[1], destination[0]], { icon: endIcon, pane: 'pdvPane', zIndexOffset: 1000 })
|
||||
.addTo(this.map)
|
||||
.bindPopup(`<strong>Destino:</strong> ${json.nombre_pdv}<br><strong>Distancia:</strong> ${distance} km<br><strong>Duración:</strong> ${duration} min`)
|
||||
.bindPopup(`<strong>Destino:</strong> ${json.nombre_pdv}<br><strong>Usuario:</strong> ${json.nombre_usuario}<br><strong>Distancia:</strong> ${distance} km<br><strong>Duración:</strong> ${duration} min`)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -238,6 +313,6 @@ export class AssignedRouteDetailComponent implements OnInit, OnDestroy, AfterVie
|
||||
}
|
||||
|
||||
goBack() {
|
||||
this.router.navigate(['/home']);
|
||||
this.router.navigate(['/proyectos', this.activatedRoute.snapshot.paramMap.get('id')]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,3 +69,31 @@
|
||||
color: var(--glm-acero);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.link-usuario {
|
||||
color: var(--glm-azul);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: transparent;
|
||||
transition: text-decoration-color 0.15s;
|
||||
}
|
||||
|
||||
.link-usuario:hover {
|
||||
text-decoration-color: var(--glm-verde);
|
||||
color: var(--glm-verde);
|
||||
}
|
||||
.inline-edit {
|
||||
width: 100%;
|
||||
min-width: 100px;
|
||||
padding: 4px 6px;
|
||||
border: 1px solid var(--glm-verde);
|
||||
border-radius: 3px;
|
||||
background: #fff;
|
||||
color: var(--glm-gris-oscuro);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.edit-actions {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@@ -7,9 +7,19 @@
|
||||
(input)="dt.filterGlobal($any($event.target).value, 'contains')"
|
||||
/>
|
||||
<div class="actions-right">
|
||||
<button type="button" class="btn-secondary" (click)="goToOverviewMap()" pTooltip="Ver mapa filtrado por usuario" tooltipPosition="top">
|
||||
<i class="pi pi-map"></i> Ver mapa
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="downloadCSV()">
|
||||
<i class="pi pi-download"></i> Descargar CSV
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="reoptimizeLocally()" [disabled]="!canReoptimize" title="Vuelve a ejecutar el optimizador con los archivos cargados">
|
||||
<span *ngIf="reoptLoading" class="spinner-inline"></span>
|
||||
<i *ngIf="!reoptLoading" class="pi pi-sync"></i> {{ reoptLoading ? 'Reoptimizando...' : 'Reoptimizar rutas' }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" *ngIf="hasLocalChanges" (click)="restoreOriginal()">
|
||||
<i class="pi pi-undo"></i> Deshacer cambios
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
@@ -22,6 +32,8 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-error" *ngIf="reoptError"><i class="pi pi-exclamation-triangle"></i> {{ reoptError }}</div>
|
||||
<div class="table-error" *ngIf="editError"><i class="pi pi-exclamation-triangle"></i> {{ editError }}</div>
|
||||
|
||||
<p-table
|
||||
#dt
|
||||
@@ -60,20 +72,41 @@
|
||||
|
||||
<ng-template pTemplate="body" let-row>
|
||||
<tr>
|
||||
<td>{{ row.json.nombre_usuario }}</td>
|
||||
<td>
|
||||
<ng-container *ngIf="editingRoute === row; else userValue">
|
||||
<select class="inline-edit" [(ngModel)]="editUserId">
|
||||
<option *ngFor="let user of userOptions" [value]="user.id">{{ user.name }}</option>
|
||||
</select>
|
||||
</ng-container>
|
||||
<ng-template #userValue><a class="link-usuario" (click)="goToUserMap(row.json.usuario_id)" pTooltip="Ver todas las rutas de este usuario" tooltipPosition="top">{{ row.json.nombre_usuario }}</a></ng-template>
|
||||
</td>
|
||||
<td>{{ row.json.nombre_pdv }}</td>
|
||||
<td>{{ row.json.hora_laboral_semanal_usuario }}</td>
|
||||
<td>{{ row.json.hora_minima_semanal_pdv }}</td>
|
||||
<td>{{ row.json.horas_trabajo }}</td>
|
||||
<td>{{ row.json.dia }}</td>
|
||||
<td>
|
||||
<ng-container *ngIf="editingRoute === row; else dayValue">
|
||||
<select class="inline-edit" [(ngModel)]="editDay">
|
||||
<option *ngFor="let day of dayOptions" [value]="day">{{ day }}</option>
|
||||
</select>
|
||||
</ng-container>
|
||||
<ng-template #dayValue>{{ row.json.dia }}</ng-template>
|
||||
</td>
|
||||
<td>{{ row.json.distancia }}</td>
|
||||
<td>{{ row.json.horas_desplazamiento }}</td>
|
||||
<td class="text-center">
|
||||
<td>{{ (row.json.horas_desplazamiento * 60).toFixed(0) }} min</td>
|
||||
<td class="text-center edit-actions">
|
||||
<ng-container *ngIf="editingRoute === row; else editButton">
|
||||
<button type="button" class="btn-icon" (click)="saveEdit()" title="Guardar"><i class="pi pi-check"></i></button>
|
||||
<button type="button" class="btn-icon" (click)="cancelEdit()" title="Cancelar"><i class="pi pi-times"></i></button>
|
||||
</ng-container>
|
||||
<ng-template #editButton>
|
||||
<button type="button" class="btn-icon" (click)="startEdit(row)" title="Editar asignación"><i class="pi pi-pencil"></i></button>
|
||||
</ng-template>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-icon"
|
||||
(click)="onShowMap(row)"
|
||||
pTooltip="Ver en mapa"
|
||||
pTooltip="Ver en mapa (1 ruta)"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<i class="pi pi-map-marker"></i>
|
||||
@@ -84,7 +117,7 @@
|
||||
|
||||
<ng-template pTemplate="emptymessage">
|
||||
<tr>
|
||||
<td colspan="9" class="text-center">No hay rutas asignadas</td>
|
||||
<td colspan="9" class="text-center">No hay rutas asignadas</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Component, ChangeDetectorRef, ViewChild } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { RouteAssignedResponse } from '../../../core/models/route.model';
|
||||
import { saveAs } from 'file-saver';
|
||||
import { Table } from 'primeng/table';
|
||||
@@ -9,6 +9,8 @@ import { TableModule } from 'primeng/table';
|
||||
import { InputTextModule } from 'primeng/inputtext';
|
||||
import { TooltipModule } from 'primeng/tooltip';
|
||||
import { RouteState } from '../../../core/route-state/route';
|
||||
import { RutasService } from '../../../core/services/router.service';
|
||||
import { PlanningInputService } from '../../../core/services/planning-input.service';
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
@@ -30,23 +32,39 @@ export class AssignedRouteComponent {
|
||||
assignedRoutes: RouteAssignedResponse[] = [];
|
||||
isLoading = false;
|
||||
cols: any[] = [];
|
||||
editingRoute: RouteAssignedResponse | null = null;
|
||||
editUserId = '';
|
||||
editDay = '';
|
||||
hasLocalChanges = false;
|
||||
editError: string | null = null;
|
||||
reoptLoading = false;
|
||||
reoptError: string | null = null;
|
||||
|
||||
constructor(
|
||||
private routesState: RouteState,
|
||||
private cdr: ChangeDetectorRef,
|
||||
private router: Router
|
||||
private router: Router,
|
||||
private activatedRoute: ActivatedRoute,
|
||||
private rutasService: RutasService,
|
||||
private planningInput: PlanningInputService
|
||||
) { }
|
||||
|
||||
private subs: import('rxjs').Subscription[] = [];
|
||||
|
||||
ngOnInit() {
|
||||
this.routesState.resetLoading();
|
||||
this.routesState.loading$.subscribe(value => {
|
||||
this.isLoading = value;
|
||||
this.cdr.detectChanges();
|
||||
});
|
||||
this.routesState.assignedRoutes$.subscribe(data => {
|
||||
this.assignedRoutes = [...data];
|
||||
this.cdr.detectChanges();
|
||||
});
|
||||
this.subs.push(
|
||||
this.routesState.loading$.subscribe(value => {
|
||||
this.isLoading = value;
|
||||
this.cdr.detectChanges();
|
||||
})
|
||||
);
|
||||
this.subs.push(
|
||||
this.routesState.assignedRoutes$.subscribe(data => {
|
||||
this.assignedRoutes = [...data];
|
||||
this.cdr.detectChanges();
|
||||
})
|
||||
);
|
||||
this.cols = [
|
||||
{ field: 'json.nombre_usuario', header: 'Usuario' },
|
||||
{ field: 'json.nombre_pdv', header: 'PDV' },
|
||||
@@ -60,14 +78,114 @@ export class AssignedRouteComponent {
|
||||
];
|
||||
|
||||
}
|
||||
onShowMap(row: RouteAssignedResponse) {
|
||||
onShowMap(row: RouteAssignedResponse) {
|
||||
this.routesState.sendRoute(row);
|
||||
this.router.navigate(['/home/assigned-route']);
|
||||
this.router.navigate(['/proyectos', this.projectId, 'ruta'], {
|
||||
queryParams: { pdv_id: row.json.pdv_id, usuario_id: row.json.usuario_id, dia: row.json.dia }
|
||||
});
|
||||
}
|
||||
|
||||
goToOverviewMap() {
|
||||
// If table has filtered view, use first visible row's usuario as default; else first assigned
|
||||
const target = (this.table?.filteredValue?.[0] as RouteAssignedResponse | undefined) ?? this.assignedRoutes[0];
|
||||
if (target) {
|
||||
this.router.navigate(['/proyectos', this.projectId, 'mapa'], {
|
||||
queryParams: { usuario_id: target.json.usuario_id, dia: 'Todos' }
|
||||
});
|
||||
} else {
|
||||
this.router.navigate(['/proyectos', this.projectId, 'mapa']);
|
||||
}
|
||||
}
|
||||
|
||||
goToUserMap(usuarioId: string) {
|
||||
this.router.navigate(['/proyectos', this.projectId, 'mapa'], { queryParams: { usuario_id: usuarioId, dia: 'Todos' } });
|
||||
}
|
||||
|
||||
private get projectId(): string { return this.activatedRoute.snapshot.paramMap.get('id') ?? ''; }
|
||||
|
||||
get userOptions(): { id: string; name: string }[] {
|
||||
const users = new Map<string, string>();
|
||||
for (const route of this.assignedRoutes) users.set(String(route.json.usuario_id), route.json.nombre_usuario);
|
||||
return Array.from(users, ([id, name]) => ({ id, name }));
|
||||
}
|
||||
|
||||
get dayOptions(): string[] {
|
||||
return this.routesState.getDiasUnicos();
|
||||
}
|
||||
|
||||
startEdit(route: RouteAssignedResponse): void {
|
||||
this.editingRoute = route;
|
||||
this.editUserId = String(route.json.usuario_id);
|
||||
this.editDay = route.json.dia;
|
||||
this.editError = null;
|
||||
}
|
||||
|
||||
cancelEdit(): void {
|
||||
this.editingRoute = null;
|
||||
}
|
||||
|
||||
saveEdit(): void {
|
||||
if (!this.editingRoute || !this.editUserId || !this.editDay) return;
|
||||
const capacity = this.routesState.canAssignToDay(
|
||||
this.editUserId,
|
||||
this.editDay,
|
||||
Number(this.editingRoute.json.horas_trabajo || this.editingRoute.json.hora_minima_semanal_pdv || 0),
|
||||
this.editingRoute
|
||||
);
|
||||
if (!capacity.allowed) {
|
||||
this.editError = `La asignación excede la capacidad diaria (${capacity.totalHours.toFixed(1)} h de ${capacity.capacityHours.toFixed(1)} h).`;
|
||||
return;
|
||||
}
|
||||
this.routesState.updateAssignedRoute(this.editingRoute, this.editUserId, this.editDay);
|
||||
this.hasLocalChanges = true;
|
||||
this.editingRoute = null;
|
||||
}
|
||||
|
||||
get canReoptimize(): boolean {
|
||||
return this.assignedRoutes.length > 0 && !!this.planningInput.getFormData() && !this.reoptLoading;
|
||||
}
|
||||
|
||||
reoptimizeLocally(): void {
|
||||
const data = this.planningInput.getFormData();
|
||||
if (!data || !this.assignedRoutes.length || this.reoptLoading) return;
|
||||
this.reoptLoading = true;
|
||||
this.reoptError = null;
|
||||
this.routesState.setLoading(true);
|
||||
this.rutasService.reoptimizarRutas(data).subscribe({
|
||||
next: response => {
|
||||
const items = response as unknown as unknown[];
|
||||
const assigned = items.find(item => item && typeof item === 'object' && 'assigned' in item) as { assigned?: unknown } | undefined;
|
||||
const noAssigned = items.find(item => item && typeof item === 'object' && 'noAssigned' in item) as { noAssigned?: unknown } | undefined;
|
||||
if (assigned?.assigned) this.routesState.setAssignedRoutes(assigned.assigned as never);
|
||||
if (noAssigned?.noAssigned) this.routesState.setNoAssignedRoutes(noAssigned.noAssigned as never);
|
||||
this.hasLocalChanges = false;
|
||||
this.reoptLoading = false;
|
||||
this.routesState.setLoading(false);
|
||||
this.cdr.detectChanges();
|
||||
},
|
||||
error: err => {
|
||||
this.reoptError = err?.error?.error || err?.message || 'No se pudo reoptimizar la planificación';
|
||||
this.reoptLoading = false;
|
||||
this.routesState.setLoading(false);
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
});
|
||||
this.editingRoute = null;
|
||||
}
|
||||
|
||||
restoreOriginal(): void {
|
||||
this.routesState.restoreOriginalAssignedRoutes();
|
||||
this.hasLocalChanges = false;
|
||||
this.editingRoute = null;
|
||||
}
|
||||
toggleRutas() {
|
||||
this.rutasExpandido = !this.rutasExpandido;
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
this.subs.forEach(s => s.unsubscribe());
|
||||
}
|
||||
|
||||
downloadCSV() {
|
||||
const headers = [
|
||||
'Usuario ID',
|
||||
@@ -119,4 +237,4 @@ export class AssignedRouteComponent {
|
||||
saveAs(blob, 'rutas_planificadas.csv');
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,10 @@
|
||||
color: var(--glm-verde);
|
||||
}
|
||||
|
||||
.projects-link { margin-left: auto; color: var(--glm-azul); font-size: .82rem; text-decoration: none; }
|
||||
.user-profile { display:flex; align-items:center; gap:8px; margin-left:auto; color:var(--glm-azul); font-size:.84rem; font-weight:700; }.user-profile img,.avatar-fallback { width:30px; height:30px; border-radius:50%; }.user-profile img { object-fit:cover; }.avatar-fallback { display:inline-flex; align-items:center; justify-content:center; background:var(--glm-verde); color:#fff; }
|
||||
.projects-link button,.home-employees-link,.edit-project,.project-edit-actions button { border:1px solid var(--glm-gris-medio); border-radius:4px; background:#fff; color:var(--glm-azul); cursor:pointer; font:inherit; font-weight:700; padding:8px 11px; text-decoration:none; }.home-employees-link { display:inline-block; margin-bottom:12px; }.project-heading { width:100%; }.project-title-line { display:flex; align-items:center; gap:14px; }.project-title-line h1 { margin:0; }.back-projects { color:var(--glm-azul); font-size:.85rem; font-weight:700; text-decoration:none; white-space:nowrap; }.edit-project,.project-edit-actions { margin-left:auto; }.project-title-line input,.project-heading textarea { border:1px solid #9aaab3; border-radius:4px; background:#fff; color:#2f3f48; font:inherit; padding:8px; }.project-heading textarea { display:block; width:100%; margin-top:10px; resize:vertical; }.project-edit-actions { display:flex; gap:6px; }.project-edit-actions button:first-child { background:var(--glm-azul); color:#fff; }
|
||||
|
||||
.home-container {
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
@@ -38,11 +42,18 @@
|
||||
}
|
||||
|
||||
.home-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 24px;
|
||||
border-bottom: 3px solid var(--glm-verde);
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
|
||||
.employees-link { display: inline-flex; align-items: center; gap: 6px; padding: 8px 11px; border: 1px solid var(--glm-verde); border-radius: 4px; background: var(--glm-verde-bg); color: var(--glm-azul); font-size: .82rem; font-weight: 700; text-decoration: none; white-space: nowrap; }
|
||||
.employees-link:hover { background: var(--glm-verde); color: #fff; }
|
||||
|
||||
.home-header h1 {
|
||||
margin: 0;
|
||||
color: var(--glm-azul);
|
||||
@@ -79,6 +90,8 @@
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.employees-summary { display: flex; align-items: center; gap: 7px; margin: -2px 0 16px; color: var(--glm-acero); font-size: .88rem; }.employees-summary i { color: var(--glm-verde); }.employees-summary.empty, .employees-summary.empty i { color: #c9252d; }
|
||||
|
||||
.upload-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
@@ -233,6 +246,161 @@
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.file-label.has-error {
|
||||
border-color: #F5A6A0;
|
||||
background: var(--glm-rojo-ok);
|
||||
}
|
||||
|
||||
.file-label.has-success {
|
||||
border-color: var(--glm-verde);
|
||||
background: var(--glm-verde-bg);
|
||||
}
|
||||
|
||||
.preview-card {
|
||||
padding: 12px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
background: var(--glm-surface);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.preview-success {
|
||||
border-color: var(--glm-verde-claro);
|
||||
background: var(--glm-verde-bg);
|
||||
}
|
||||
|
||||
.preview-success .preview-header {
|
||||
color: var(--glm-verde);
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.preview-error {
|
||||
border-color: #F5A6A0;
|
||||
background: var(--glm-rojo-ok);
|
||||
}
|
||||
|
||||
.preview-error .preview-header {
|
||||
color: #D32F2F;
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.preview-stats {
|
||||
margin-top: 6px;
|
||||
color: var(--glm-acero);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.preview-errors {
|
||||
margin: 8px 0 0;
|
||||
padding: 0 0 0 18px;
|
||||
color: var(--glm-gris-oscuro);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.preview-errors li {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.error-value {
|
||||
color: var(--glm-acero);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.more-errors {
|
||||
color: var(--glm-acero);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.preview-loading {
|
||||
color: var(--glm-acero);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.preview-loading-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--glm-acero);
|
||||
}
|
||||
|
||||
.params-card {
|
||||
margin-top: 16px;
|
||||
padding: 14px;
|
||||
background: var(--glm-surface);
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-radius: 4px;
|
||||
border-left: 3px solid var(--glm-azul);
|
||||
}
|
||||
|
||||
.params-title {
|
||||
margin: 0 0 10px;
|
||||
font-size: 0.9rem;
|
||||
color: var(--glm-azul);
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.params-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
@media (min-width: 600px) {
|
||||
.params-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.param-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.param-label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--glm-azul);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
.param-select {
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-radius: 4px;
|
||||
font-size: 0.9rem;
|
||||
font-family: Arial, sans-serif;
|
||||
background: #fff;
|
||||
color: var(--glm-gris-oscuro);
|
||||
}
|
||||
|
||||
.param-select:focus {
|
||||
outline: none;
|
||||
border-color: var(--glm-verde);
|
||||
box-shadow: 0 0 0 2px rgba(108, 194, 74, 0.15);
|
||||
}
|
||||
|
||||
.param-hint {
|
||||
font-size: 0.75rem;
|
||||
color: var(--glm-acero);
|
||||
}
|
||||
|
||||
.hint-text {
|
||||
color: var(--glm-acero);
|
||||
font-size: 0.82rem;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.spinner-inline {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
|
||||
@@ -1,58 +1,63 @@
|
||||
<div class="glm-topbar">
|
||||
<img src="GLM_completo.png" alt="GomezLee Marketing" class="glm-topbar-logo" />
|
||||
<span class="glm-topbar-sep">|</span>
|
||||
<span class="glm-topbar-context">Route Planner</span>
|
||||
<span class="glm-topbar-context">Route Planner</span><div class="user-profile" *ngIf="profile.current"><img *ngIf="profile.avatarUrl" [src]="profile.avatarUrl" alt=""><span *ngIf="!profile.avatarUrl" class="avatar-fallback">{{ profile.current.nombre.charAt(0) }}</span><span>{{ profile.current.nombre }}</span></div><div class="projects-link"><button type="button" (click)="signOut()"><i class="pi pi-sign-out"></i> Salir</button></div>
|
||||
</div>
|
||||
|
||||
<div class="home-container">
|
||||
<a class="employees-link home-employees-link" routerLink="/empleados"><i class="pi pi-users"></i> Gestionar empleados</a>
|
||||
<header class="home-header">
|
||||
<h1>Route Planner</h1>
|
||||
<p>Gestión de rutas asignadas y puntos de venta pendientes</p>
|
||||
<div class="project-heading"><div class="project-title-line"><a class="back-projects" routerLink="/home"><i class="pi pi-arrow-left"></i> Mis proyectos</a><h1 *ngIf="!editingProject">{{ projectName || 'Proyecto' }}</h1><input *ngIf="editingProject" [(ngModel)]="projectName" maxlength="120"><button *ngIf="!editingProject" type="button" class="edit-project" (click)="startProjectEdit()"><i class="pi pi-pencil"></i> Editar proyecto</button><div *ngIf="editingProject" class="project-edit-actions"><button type="button" (click)="saveProject()" [disabled]="projectSaving">Guardar</button><button type="button" (click)="cancelProjectEdit()" [disabled]="projectSaving">Cancelar</button></div></div><textarea *ngIf="editingProject" [(ngModel)]="projectDescription" maxlength="500" placeholder="Descripción del proyecto"></textarea><p *ngIf="!editingProject">Gestión de rutas asignadas y puntos de venta pendientes</p></div>
|
||||
</header>
|
||||
|
||||
<section class="card upload-card">
|
||||
<h2 class="section-title">Subir archivos para optimización</h2>
|
||||
|
||||
<h2 class="section-title">PDVs del proyecto</h2>
|
||||
<p class="employees-summary" [class.empty]="!employeesLoading && !activeEmployees"><i class="pi pi-users"></i> <span *ngIf="employeesLoading">Cargando empleados activos...</span><span *ngIf="!employeesLoading">{{ activeEmployees }} empleados activos de {{ projectCountry }} se usarán para planificar.</span></p>
|
||||
|
||||
<div class="upload-grid">
|
||||
<div class="file-input-wrapper">
|
||||
<label class="file-label" for="pdvFile">
|
||||
<label class="file-label" for="pdvFile" [class.has-error]="pdvPreview && !pdvPreview.valid" [class.has-success]="pdvPreview?.valid">
|
||||
<i class="pi pi-file-excel"></i>
|
||||
<span>Archivo PDVs (Excel)</span>
|
||||
<span class="file-hint">.xlsx / .xls • máx 10MB</span>
|
||||
<span>Archivo PDVs guardado</span>
|
||||
<span class="file-hint">Los PDVs pertenecen a este proyecto</span>
|
||||
</label>
|
||||
<input
|
||||
id="pdvFile"
|
||||
type="file"
|
||||
accept=".xlsx,.xls"
|
||||
(change)="onPdvFileChange($event)"
|
||||
disabled
|
||||
class="file-input"
|
||||
[class.has-file]="pdvFile"
|
||||
/>
|
||||
<div class="file-name" *ngIf="pdvFile">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
<i class="pi" [class.pi-check-circle]="pdvPreview?.valid" [class.pi-exclamation-circle]="pdvPreview && !pdvPreview.valid" [class.pi-spin]="pdvPreviewLoading"></i>
|
||||
{{ pdvFile.name }}
|
||||
<span *ngIf="pdvPreviewLoading" class="preview-loading">Validando...</span>
|
||||
</div>
|
||||
|
||||
<div class="preview-card" *ngIf="pdvPreviewLoading">
|
||||
<div class="preview-loading-row"><span class="spinner-inline"></span> Analizando archivo PDV...</div>
|
||||
</div>
|
||||
|
||||
<div class="preview-card preview-success" *ngIf="pdvPreview?.valid">
|
||||
<div class="preview-header"><i class="pi pi-check-circle"></i> PDV válido — {{ pdvPreview!.totalRows }} filas</div>
|
||||
<div class="preview-stats">{{ pdvPreview!.validRows }} filas válidas • Columnas: {{ pdvPreview!.headers.join(', ') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="preview-card preview-error" *ngIf="pdvPreview && !pdvPreview.valid">
|
||||
<div class="preview-header"><i class="pi pi-exclamation-triangle"></i> Errores en PDV ({{ pdvPreview.errors.length }})</div>
|
||||
<div class="preview-stats" *ngIf="pdvPreview.missingHeaders.length">Faltan: {{ pdvPreview.missingHeaders.join(', ') }}</div>
|
||||
<div class="preview-stats">{{ pdvPreview.totalRows }} filas leídas • {{ pdvPreview.validRows }} válidas</div>
|
||||
<ul class="preview-errors">
|
||||
<li *ngFor="let e of pdvPreview.errors.slice(0, 8)">
|
||||
<strong>Fila {{ e.row }} — {{ e.field }}:</strong> {{ e.message }}
|
||||
<span *ngIf="e.value !== undefined && e.value !== null" class="error-value">({{ e.value }})</span>
|
||||
</li>
|
||||
<li *ngIf="pdvPreview.errors.length > 8" class="more-errors">+ {{ pdvPreview.errors.length - 8 }} errores más...</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="file-input-wrapper">
|
||||
<label class="file-label" for="usuariosFile">
|
||||
<i class="pi pi-file-excel"></i>
|
||||
<span>Archivo Usuarios (Excel)</span>
|
||||
<span class="file-hint">.xlsx / .xls • máx 10MB</span>
|
||||
</label>
|
||||
<input
|
||||
id="usuariosFile"
|
||||
type="file"
|
||||
accept=".xlsx,.xls"
|
||||
(change)="onUsuariosFileChange($event)"
|
||||
class="file-input"
|
||||
[class.has-file]="usuariosFile"
|
||||
/>
|
||||
<div class="file-name" *ngIf="usuariosFile">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
{{ usuariosFile.name }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="upload-actions">
|
||||
@@ -65,24 +70,38 @@
|
||||
type="button"
|
||||
class="btn-primary"
|
||||
(click)="cargarRutas()"
|
||||
[disabled]="!canSubmit || isLoading"
|
||||
[disabled]="!canSubmit"
|
||||
[title]="submitDisabledReason || ''"
|
||||
>
|
||||
<span *ngIf="isLoading" class="spinner-inline"></span>
|
||||
<i *ngIf="!isLoading" class="pi pi-upload"></i>
|
||||
{{ isLoading ? 'Procesando...' : 'Cargar rutas' }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
*ngIf="isLoading"
|
||||
(click)="cancelarCarga()"
|
||||
>
|
||||
<i class="pi pi-times"></i> Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
(click)="clearFiles()"
|
||||
[disabled]="!pdvFile && !usuariosFile"
|
||||
[disabled]="!pdvFile"
|
||||
>
|
||||
<i class="pi pi-times"></i> Limpiar
|
||||
</button>
|
||||
</div>
|
||||
<small class="hint-text" *ngIf="submitDisabledReason && !isLoading">{{ submitDisabledReason }}</small>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card kpis-card">
|
||||
<app-planning-kpis></app-planning-kpis>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<app-assigned-route></app-assigned-route>
|
||||
</section>
|
||||
@@ -91,4 +110,4 @@
|
||||
<h2 class="section-title">PDVs sin ruta asignada</h2>
|
||||
<app-no-assigned-route></app-no-assigned-route>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { Component, ChangeDetectorRef, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { AssignedRouteComponent } from './assigned-route/assigned-route.component';
|
||||
@@ -6,101 +6,323 @@ import { NoAssignedRouteComponent } from './no-assigned-route/no-assigned-route.
|
||||
import { RutasService } from '../../core/services/router.service';
|
||||
import { RouteState } from '../../core/route-state/route';
|
||||
import { ApiResponse } from '../../core/models/route.model';
|
||||
import { ExcelPreviewService, PreviewResult } from '../../shared/services/excel-preview.service';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { PlanningKpisComponent } from './planning-kpis/planning-kpis.component';
|
||||
import { PlanningInputService } from '../../core/services/planning-input.service';
|
||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||
import { EmployeeService } from '../../core/services/employee.service';
|
||||
import { ProjectService } from '../../core/services/project.service';
|
||||
import { AuthService } from '../../core/services/auth.service';
|
||||
import { UserProfileService } from '../../core/services/user-profile.service';
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
selector: 'app-home',
|
||||
imports: [CommonModule, FormsModule, AssignedRouteComponent, NoAssignedRouteComponent],
|
||||
imports: [CommonModule, FormsModule, RouterLink, AssignedRouteComponent, NoAssignedRouteComponent, PlanningKpisComponent],
|
||||
templateUrl: './home.component.html',
|
||||
styleUrls: ['./home.component.css']
|
||||
})
|
||||
export class HomeComponent {
|
||||
export class HomeComponent implements OnInit {
|
||||
pdvFile: File | null = null;
|
||||
usuariosFile: File | null = null;
|
||||
pdvPreview: PreviewResult | null = null;
|
||||
usuariosPreview: PreviewResult | null = null;
|
||||
pdvPreviewLoading = false;
|
||||
usuariosPreviewLoading = false;
|
||||
activeEmployees = 0;
|
||||
employeesLoading = true;
|
||||
uploadError: string | null = null;
|
||||
isLoading = false;
|
||||
projectName = '';
|
||||
projectId = '';
|
||||
editingProject = false;
|
||||
projectDescription = '';
|
||||
projectCountry = '';
|
||||
projectSaving = false;
|
||||
private calcSub: Subscription | null = null;
|
||||
|
||||
constructor(
|
||||
private rutasService: RutasService,
|
||||
private routeState: RouteState
|
||||
private routeState: RouteState,
|
||||
private previewService: ExcelPreviewService,
|
||||
private planningInput: PlanningInputService,
|
||||
private employeesService: EmployeeService,
|
||||
private projectsService: ProjectService,
|
||||
private activatedRoute: ActivatedRoute,
|
||||
private auth: AuthService,
|
||||
private router: Router,
|
||||
public profile: UserProfileService,
|
||||
private cdr: ChangeDetectorRef
|
||||
) {}
|
||||
|
||||
onPdvFileChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
if (input.files && input.files.length > 0) {
|
||||
this.pdvFile = input.files[0];
|
||||
this.validateFile(this.pdvFile, 'PDV');
|
||||
this.uploadError = null;
|
||||
ngOnInit(): void {
|
||||
void this.initialize();
|
||||
}
|
||||
|
||||
private async initialize(): Promise<void> {
|
||||
await this.loadProject();
|
||||
await this.loadEmployees();
|
||||
}
|
||||
|
||||
private async loadProject(): Promise<void> {
|
||||
this.projectId = this.activatedRoute.snapshot.paramMap.get('id') ?? '';
|
||||
if (!this.projectId) return;
|
||||
try {
|
||||
const [project, input] = await Promise.all([this.projectsService.get(this.projectId), this.projectsService.projectInput(this.projectId)]);
|
||||
this.projectName = project.nombre;
|
||||
this.projectDescription = project.descripcion ?? '';
|
||||
this.projectCountry = input.country;
|
||||
this.pdvFile = input.file;
|
||||
this.pdvPreview = await this.previewService.previewFile(input.file, 'PDV');
|
||||
} catch (error: any) {
|
||||
this.uploadError = error?.message ?? 'No se pudo cargar el proyecto.';
|
||||
} finally {
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
}
|
||||
|
||||
onUsuariosFileChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
if (input.files && input.files.length > 0) {
|
||||
this.usuariosFile = input.files[0];
|
||||
this.validateFile(this.usuariosFile, 'Usuarios');
|
||||
this.uploadError = null;
|
||||
startProjectEdit(): void { this.editingProject = true; }
|
||||
|
||||
cancelProjectEdit(): void { this.editingProject = false; void this.loadProject(); }
|
||||
|
||||
async saveProject(): Promise<void> {
|
||||
if (!this.projectId || !this.projectName.trim()) return;
|
||||
this.projectSaving = true;
|
||||
try {
|
||||
await this.projectsService.update(this.projectId, { nombre: this.projectName.trim(), descripcion: this.projectDescription.trim() || null });
|
||||
this.editingProject = false;
|
||||
} catch (error: any) { this.uploadError = error?.message ?? 'No se pudo actualizar el proyecto.'; }
|
||||
finally { this.projectSaving = false; this.cdr.detectChanges(); }
|
||||
}
|
||||
|
||||
async signOut(): Promise<void> { await this.auth.signOut(); await this.router.navigate(['/login']); }
|
||||
|
||||
private async loadEmployees(): Promise<void> {
|
||||
this.employeesLoading = true;
|
||||
try {
|
||||
this.activeEmployees = (await this.employeesService.active(this.projectCountry)).length;
|
||||
} catch {
|
||||
this.activeEmployees = 0;
|
||||
} finally {
|
||||
this.employeesLoading = false;
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
}
|
||||
|
||||
private validateFile(file: File, type: string) {
|
||||
async onPdvFileChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
if (input.files && input.files.length > 0) {
|
||||
const file = input.files[0];
|
||||
const basicError = this.validateFileBasic(file, 'PDV');
|
||||
if (basicError) {
|
||||
this.pdvFile = null;
|
||||
this.pdvPreview = null;
|
||||
this.uploadError = basicError;
|
||||
return;
|
||||
}
|
||||
this.pdvFile = file;
|
||||
if (this.usuariosFile) this.planningInput.setFiles(file, this.usuariosFile);
|
||||
this.uploadError = null;
|
||||
this.pdvPreviewLoading = true;
|
||||
this.pdvPreview = null;
|
||||
this.cdr.detectChanges();
|
||||
try {
|
||||
this.pdvPreview = await this.previewService.previewFile(file, 'PDV');
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : 'Error al leer el archivo PDV';
|
||||
this.pdvPreview = {
|
||||
fileName: file.name,
|
||||
type: 'PDV',
|
||||
valid: false,
|
||||
totalRows: 0,
|
||||
validRows: 0,
|
||||
headers: [],
|
||||
normalizedHeaders: [],
|
||||
missingHeaders: [],
|
||||
errors: [{ row: 1, field: 'file', message: msg }],
|
||||
duplicateIds: [],
|
||||
sampleValidRows: [],
|
||||
};
|
||||
} finally {
|
||||
this.pdvPreviewLoading = false;
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async onUsuariosFileChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
if (input.files && input.files.length > 0) {
|
||||
const file = input.files[0];
|
||||
const basicError = this.validateFileBasic(file, 'Usuarios');
|
||||
if (basicError) {
|
||||
this.usuariosFile = null;
|
||||
this.usuariosPreview = null;
|
||||
this.uploadError = basicError;
|
||||
return;
|
||||
}
|
||||
this.usuariosFile = file;
|
||||
if (this.pdvFile) this.planningInput.setFiles(this.pdvFile, file);
|
||||
this.uploadError = null;
|
||||
this.usuariosPreviewLoading = true;
|
||||
this.usuariosPreview = null;
|
||||
this.cdr.detectChanges();
|
||||
try {
|
||||
this.usuariosPreview = await this.previewService.previewFile(file, 'Usuarios');
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : 'Error al leer el archivo Usuarios';
|
||||
this.usuariosPreview = {
|
||||
fileName: file.name,
|
||||
type: 'Usuarios',
|
||||
valid: false,
|
||||
totalRows: 0,
|
||||
validRows: 0,
|
||||
headers: [],
|
||||
normalizedHeaders: [],
|
||||
missingHeaders: [],
|
||||
errors: [{ row: 1, field: 'file', message: msg }],
|
||||
duplicateIds: [],
|
||||
sampleValidRows: [],
|
||||
};
|
||||
} finally {
|
||||
this.usuariosPreviewLoading = false;
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private validateFileBasic(file: File, type: string): string | null {
|
||||
const validExtensions = ['.xlsx', '.xls'];
|
||||
const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
|
||||
if (!validExtensions.includes(ext)) {
|
||||
this.uploadError = `El archivo ${type} debe ser .xlsx o .xls`;
|
||||
if (type === 'PDV') this.pdvFile = null;
|
||||
else this.usuariosFile = null;
|
||||
return `El archivo ${type} debe ser .xlsx o .xls`;
|
||||
}
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
this.uploadError = `El archivo ${type} supera 10MB`;
|
||||
if (type === 'PDV') this.pdvFile = null;
|
||||
else this.usuariosFile = null;
|
||||
return `El archivo ${type} supera 10MB`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
get canSubmit(): boolean {
|
||||
return !!this.pdvFile && !!this.usuariosFile && !this.uploadError;
|
||||
if (!this.pdvFile || !this.activeEmployees) return false;
|
||||
if (this.pdvPreviewLoading || this.employeesLoading) return false;
|
||||
if (this.isLoading) return false;
|
||||
if (this.uploadError) return false;
|
||||
// Require valid previews before enabling submit
|
||||
if (this.pdvPreview && !this.pdvPreview.valid) return false;
|
||||
if (!this.pdvPreview) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
cargarRutas() {
|
||||
get submitDisabledReason(): string | null {
|
||||
if (!this.pdvFile) return 'Sube el archivo PDV';
|
||||
if (this.employeesLoading) return 'Cargando empleados...';
|
||||
if (!this.activeEmployees) return 'No hay empleados activos. Regístralos en Gestionar empleados.';
|
||||
if (this.pdvPreviewLoading) return 'Validando archivo PDV...';
|
||||
if (this.pdvPreview && !this.pdvPreview.valid) return 'Corrige los errores del archivo PDV';
|
||||
return null;
|
||||
}
|
||||
|
||||
async cargarRutas() {
|
||||
if (!this.canSubmit) return;
|
||||
|
||||
this.isLoading = true;
|
||||
this.uploadError = null;
|
||||
this.routeState.setLoading(true);
|
||||
let pdvForOptimizer: File;
|
||||
try {
|
||||
pdvForOptimizer = await this.previewService.preparePdvForOptimizer(this.pdvFile!);
|
||||
} catch {
|
||||
this.uploadError = 'No se pudo preparar el archivo PDV para el optimizador.';
|
||||
this.routeState.setLoading(false);
|
||||
this.isLoading = false;
|
||||
this.cdr.detectChanges();
|
||||
return;
|
||||
}
|
||||
let employeesFile: File;
|
||||
try {
|
||||
employeesFile = await this.employeesService.activeEmployeesFile(this.projectCountry);
|
||||
} catch {
|
||||
this.uploadError = 'No se pudieron obtener los empleados activos.';
|
||||
this.routeState.setLoading(false);
|
||||
this.isLoading = false;
|
||||
return;
|
||||
}
|
||||
this.planningInput.setFiles(pdvForOptimizer, employeesFile);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('pdv_file', this.pdvFile!, this.pdvFile!.name);
|
||||
formData.append('usuarios_file', this.usuariosFile!, this.usuariosFile!.name);
|
||||
formData.append('pdv_file', pdvForOptimizer, pdvForOptimizer.name);
|
||||
formData.append('usuarios_file', employeesFile, employeesFile.name);
|
||||
formData.append('pais', this.projectCountry);
|
||||
|
||||
this.rutasService.calcularRutas(formData).subscribe({
|
||||
this.calcSub?.unsubscribe();
|
||||
this.calcSub = this.rutasService.calcularRutas(formData).subscribe({
|
||||
next: (res: ApiResponse) => {
|
||||
const assigned = res.find(r => 'assigned' in r);
|
||||
const noAssigned = res.find(r => 'noAssigned' in r);
|
||||
// ApiResponse is [AssignedResponse, NoAssignedResponse] but backend may return object with error
|
||||
const anyRes = res as unknown as Record<string, unknown>;
|
||||
if (anyRes && 'error' in anyRes) {
|
||||
this.uploadError = String((anyRes as { error: unknown }).error);
|
||||
this.routeState.setLoading(false);
|
||||
this.isLoading = false;
|
||||
this.cdr.detectChanges();
|
||||
return;
|
||||
}
|
||||
const arr = res as unknown as unknown[];
|
||||
const assigned = (arr as ApiResponse).find(r => r && typeof r === 'object' && 'assigned' in r) as unknown as { assigned: unknown } | undefined;
|
||||
const noAssigned = (arr as ApiResponse).find(r => r && typeof r === 'object' && 'noAssigned' in r) as unknown as { noAssigned: unknown } | undefined;
|
||||
if (assigned) {
|
||||
this.routeState.setAssignedRoutes(assigned.assigned);
|
||||
this.routeState.setAssignedRoutes(assigned.assigned as never);
|
||||
}
|
||||
if (noAssigned) {
|
||||
this.routeState.setNoAssignedRoutes(noAssigned.noAssigned);
|
||||
this.routeState.setNoAssignedRoutes(noAssigned.noAssigned as never);
|
||||
}
|
||||
this.routeState.setLoading(false);
|
||||
this.isLoading = false;
|
||||
this.cdr.detectChanges();
|
||||
},
|
||||
error: (err) => {
|
||||
this.uploadError = err.error?.message || 'Error al procesar los archivos';
|
||||
this.uploadError = this.mapBackendError(err);
|
||||
this.routeState.setLoading(false);
|
||||
this.isLoading = false;
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancelarCarga() {
|
||||
this.calcSub?.unsubscribe();
|
||||
this.calcSub = null;
|
||||
this.isLoading = false;
|
||||
this.routeState.setLoading(false);
|
||||
this.uploadError = 'Cálculo cancelado';
|
||||
}
|
||||
|
||||
private mapBackendError(err: unknown): string {
|
||||
const anyErr = err as { error?: { error?: string; message?: string }; message?: string; status?: number; name?: string };
|
||||
if (anyErr?.name === 'TimeoutError') return 'El cálculo tardó demasiado (timeout 180s). Intenta de nuevo con menos filas.';
|
||||
if (anyErr?.error?.error) return anyErr.error.error;
|
||||
if (anyErr?.error?.message) return anyErr.error.message;
|
||||
if (anyErr?.message) return anyErr.message;
|
||||
return 'Error al procesar los archivos';
|
||||
}
|
||||
|
||||
clearFiles() {
|
||||
this.calcSub?.unsubscribe();
|
||||
this.planningInput.clear();
|
||||
this.routeState.clearAll();
|
||||
this.pdvFile = null;
|
||||
this.usuariosFile = null;
|
||||
this.pdvPreview = null;
|
||||
this.usuariosPreview = null;
|
||||
this.pdvPreviewLoading = false;
|
||||
this.usuariosPreviewLoading = false;
|
||||
this.uploadError = null;
|
||||
this.isLoading = false;
|
||||
this.routeState.setLoading(false);
|
||||
const pdvInput = document.getElementById('pdvFile') as HTMLInputElement;
|
||||
const usuariosInput = document.getElementById('usuariosFile') as HTMLInputElement;
|
||||
if (pdvInput) pdvInput.value = '';
|
||||
if (usuariosInput) usuariosInput.value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,3 +11,58 @@
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.3px;
|
||||
}
|
||||
|
||||
.assignment-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
min-width: 230px;
|
||||
}
|
||||
|
||||
.inline-select {
|
||||
max-width: 115px;
|
||||
padding: 5px;
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-radius: 3px;
|
||||
background: #fff;
|
||||
color: var(--glm-gris-oscuro);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.day-checkboxes {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 3px 5px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.day-checkboxes label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
color: var(--glm-acero);
|
||||
font-size: 0.68rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.spinner-inline {
|
||||
display: inline-block;
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
border: 2px solid transparent;
|
||||
border-top-color: currentColor;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
.table-error {
|
||||
margin-top: 10px;
|
||||
padding: 9px 12px;
|
||||
background: var(--glm-rojo-ok);
|
||||
border: 1px solid #F5A6A0;
|
||||
border-radius: 4px;
|
||||
color: var(--glm-gris-oscuro);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
+17
-3
@@ -19,14 +19,28 @@
|
||||
<td class="text-left">{{ row.minimo_horas_semana }}</td>
|
||||
<td class="text-left">{{ row.latitud }}</td>
|
||||
<td class="text-left">{{ row.longitud }}</td>
|
||||
<td class="text-left">{{ row.motivo }}</td>
|
||||
<td class="text-left">{{ row.motivo }}</td>
|
||||
<td class="assignment-actions">
|
||||
<select [(ngModel)]="assignmentUser[row.pdv_id]" class="inline-select">
|
||||
<option value="">Usuario</option>
|
||||
<option *ngFor="let user of userOptions" [value]="user.id">{{ user.name }}</option>
|
||||
</select>
|
||||
<div class="day-checkboxes">
|
||||
<label *ngFor="let day of dayOptions"><input type="checkbox" [checked]="(assignmentDays[row.pdv_id] || []).includes(day)" (change)="toggleDay(row.pdv_id, day, $any($event.target).checked)">{{ day.substring(0, 3) }}</label>
|
||||
</div>
|
||||
<button type="button" class="btn-icon" (click)="assignRoute(row)" [disabled]="assigningId === row.pdv_id" title="Asignar y calcular ruta">
|
||||
<span *ngIf="assigningId === row.pdv_id" class="spinner-inline"></span>
|
||||
<i *ngIf="assigningId !== row.pdv_id" class="pi pi-plus"></i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
<ng-template pTemplate="emptymessage">
|
||||
<tr>
|
||||
<td colspan="8" class="text-center">
|
||||
<td colspan="7" class="text-center">
|
||||
No hay registros asignados
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
</p-table>
|
||||
<div class="table-error" *ngIf="actionError"><i class="pi pi-exclamation-triangle"></i> {{ actionError }}</div>
|
||||
|
||||
+84
-14
@@ -1,36 +1,49 @@
|
||||
import { Component, ChangeDetectorRef } from '@angular/core';
|
||||
import { Component, ChangeDetectorRef, OnDestroy } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { TableModule } from 'primeng/table';
|
||||
import { RouteNoAssignedResponse } from '../../../core/models/route.model';
|
||||
import { RouteState } from '../../../core/route-state/route';
|
||||
import { RouteState, UnassignedAssignment } from '../../../core/route-state/route';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { OrsService } from '../../../core/services/ors.service';
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
selector: 'app-no-assigned-route',
|
||||
imports: [CommonModule, TableModule],
|
||||
imports: [CommonModule, FormsModule, TableModule],
|
||||
templateUrl: './no-assigned-route.component.html',
|
||||
styleUrls: ['./no-assigned-route.component.css']
|
||||
})
|
||||
export class NoAssignedRouteComponent {
|
||||
export class NoAssignedRouteComponent implements OnDestroy {
|
||||
|
||||
noAssignedRoutes: RouteNoAssignedResponse[] = [];
|
||||
isLoading = false;
|
||||
cols: any[] = [];
|
||||
cols: { field: string; header: string }[] = [];
|
||||
private subs: Subscription[] = [];
|
||||
assignmentUser: Record<string, string> = {};
|
||||
assignmentDays: Record<string, string[]> = {};
|
||||
assigningId: number | null = null;
|
||||
actionError: string | null = null;
|
||||
|
||||
constructor(
|
||||
private routesState: RouteState,
|
||||
private cdr: ChangeDetectorRef
|
||||
private cdr: ChangeDetectorRef,
|
||||
private orsService: OrsService
|
||||
) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.routesState.loading$.subscribe(value => {
|
||||
this.isLoading = value;
|
||||
this.cdr.detectChanges();
|
||||
});
|
||||
this.routesState.noAssignedRoutes$.subscribe(data => {
|
||||
this.noAssignedRoutes = [...data];
|
||||
this.cdr.detectChanges();
|
||||
});
|
||||
this.subs.push(
|
||||
this.routesState.loading$.subscribe(value => {
|
||||
this.isLoading = value;
|
||||
this.cdr.detectChanges();
|
||||
})
|
||||
);
|
||||
this.subs.push(
|
||||
this.routesState.noAssignedRoutes$.subscribe(data => {
|
||||
this.noAssignedRoutes = [...data];
|
||||
this.cdr.detectChanges();
|
||||
})
|
||||
);
|
||||
this.cols = [
|
||||
{ field: 'pdv_id', header: 'PDV ID' },
|
||||
{ field: 'pdv_nombre', header: 'Nombre' },
|
||||
@@ -40,4 +53,61 @@ export class NoAssignedRouteComponent {
|
||||
{ field: 'motivo', header: 'Motivo' }
|
||||
];
|
||||
}
|
||||
|
||||
get userOptions(): { id: string; name: string }[] {
|
||||
return this.routesState.getUsuariosUnicos().map(user => ({ id: user.id, name: user.nombre }));
|
||||
}
|
||||
|
||||
get dayOptions(): string[] {
|
||||
return this.routesState.getDiasUnicos();
|
||||
}
|
||||
|
||||
toggleDay(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);
|
||||
}
|
||||
|
||||
async assignRoute(route: RouteNoAssignedResponse): Promise<void> {
|
||||
const userId = this.assignmentUser[String(route.pdv_id)];
|
||||
const days = this.assignmentDays[String(route.pdv_id)] ?? [];
|
||||
if (!userId || !days.length) {
|
||||
this.actionError = 'Selecciona usuario y al menos un día antes de asignar.';
|
||||
return;
|
||||
}
|
||||
const user = this.routesState.getAssignedSnapshot().find(item => String(item.json.usuario_id) === userId);
|
||||
if (!user) return;
|
||||
this.assigningId = route.pdv_id;
|
||||
this.actionError = null;
|
||||
try {
|
||||
const origin = [Number(user.json.longitud_usuario), Number(user.json.latitud_usuario)];
|
||||
const destination = [Number(route.longitud), Number(route.latitud)];
|
||||
const assignments: UnassignedAssignment[] = [];
|
||||
for (const day of days) {
|
||||
const result = await this.orsService.processPairs([{ pdv_id: route.pdv_id, origin, destination }], 1, true);
|
||||
const geo = (result[0] as { geojson?: { features?: { properties?: { summary?: { distance: number; duration: number } } }[] } }).geojson;
|
||||
const summary = geo?.features?.[0]?.properties?.summary;
|
||||
if (!summary) throw new Error('ORS no devolvió una ruta vial');
|
||||
const capacity = this.routesState.canAssignToDay(userId, day, route.minimo_horas_semana, undefined, summary.duration / 3600);
|
||||
if (!capacity.allowed) {
|
||||
this.actionError = `${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.routesState.addAssignedFromUnassignedMany(route, assignments);
|
||||
delete this.assignmentUser[String(route.pdv_id)];
|
||||
delete this.assignmentDays[String(route.pdv_id)];
|
||||
} catch {
|
||||
this.actionError = `No se pudo calcular la ruta vial para ${route.pdv_nombre}.`;
|
||||
} finally {
|
||||
this.assigningId = null;
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
this.subs.forEach(s => s.unsubscribe());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
.kpis-panel {
|
||||
border-top: 3px solid var(--glm-azul);
|
||||
}
|
||||
|
||||
.kpis-heading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
color: var(--glm-azul);
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.3px;
|
||||
}
|
||||
|
||||
.kpis-subtitle {
|
||||
margin: 4px 0 0;
|
||||
color: var(--glm-acero);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.kpis-status {
|
||||
color: var(--glm-verde);
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.kpis-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.export-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid var(--glm-verde);
|
||||
border-radius: 4px;
|
||||
background: var(--glm-verde-bg);
|
||||
color: var(--glm-azul);
|
||||
cursor: pointer;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.export-button:hover {
|
||||
background: var(--glm-verde);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.kpi-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.kpi-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-height: 92px;
|
||||
padding: 14px;
|
||||
background: var(--glm-surface);
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-left: 4px solid var(--glm-azul);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.kpi-primary { border-left-color: var(--glm-azul); }
|
||||
.kpi-success { border-left-color: var(--glm-verde); }
|
||||
.kpi-warning { border-left-color: var(--glm-naranja); }
|
||||
.kpi-blue { border-left-color: var(--glm-acero); }
|
||||
.kpi-orange { border-left-color: var(--glm-naranja); }
|
||||
|
||||
.kpi-icon {
|
||||
display: grid;
|
||||
flex: 0 0 34px;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
place-items: center;
|
||||
border-radius: 50%;
|
||||
background: var(--glm-verde-bg);
|
||||
color: var(--glm-azul);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.kpi-card > div:last-child {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.kpi-label {
|
||||
color: var(--glm-acero);
|
||||
font-size: 0.74rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
.kpi-card strong {
|
||||
color: var(--glm-azul);
|
||||
font-size: 1.45rem;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.kpi-card em {
|
||||
font-size: 0.8rem;
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.kpi-card small {
|
||||
overflow: hidden;
|
||||
color: var(--glm-acero);
|
||||
font-size: 0.73rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.user-load-card {
|
||||
margin-top: 14px;
|
||||
padding: 12px 14px;
|
||||
background: var(--glm-surface);
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.user-load-card h3 {
|
||||
margin: 0 0 8px;
|
||||
color: var(--glm-azul);
|
||||
font-size: 0.82rem;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.user-load-table-wrap {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.user-load-table {
|
||||
width: 100%;
|
||||
min-width: 560px;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.user-load-table th {
|
||||
padding: 7px 8px;
|
||||
background: var(--glm-azul);
|
||||
color: #fff;
|
||||
font-size: 0.72rem;
|
||||
text-align: left;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.user-load-table td {
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid var(--glm-gris-claro);
|
||||
color: var(--glm-gris-oscuro);
|
||||
}
|
||||
|
||||
.user-load-table tbody tr:nth-child(even) {
|
||||
background: var(--glm-gris-claro);
|
||||
}
|
||||
|
||||
.utilization-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.utilization-cell > span:first-child {
|
||||
flex: 0 0 56px;
|
||||
}
|
||||
|
||||
.capacity-warning {
|
||||
cursor: help;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.utilization-bar {
|
||||
display: block;
|
||||
flex: 1 1 140px;
|
||||
min-width: 140px;
|
||||
height: 7px;
|
||||
overflow: hidden;
|
||||
border-radius: 10px;
|
||||
background: var(--glm-gris-medio);
|
||||
}
|
||||
|
||||
.utilization-bar span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: inherit;
|
||||
background: var(--glm-verde);
|
||||
}
|
||||
|
||||
.utilization-cell.warning .utilization-bar span {
|
||||
background: var(--glm-naranja);
|
||||
}
|
||||
|
||||
.utilization-cell.over-capacity .utilization-bar span {
|
||||
background: #c62828;
|
||||
}
|
||||
|
||||
.load-over-capacity td {
|
||||
color: #8f1616;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.reasons-card {
|
||||
margin-top: 14px;
|
||||
padding: 12px 14px;
|
||||
background: var(--glm-verde-bg);
|
||||
border: 1px solid var(--glm-verde-claro);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.reasons-card h3 {
|
||||
margin: 0 0 8px;
|
||||
color: var(--glm-azul);
|
||||
font-size: 0.82rem;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.reason-list {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.reason-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 5px 0;
|
||||
border-bottom: 1px solid rgba(108, 194, 74, 0.25);
|
||||
color: var(--glm-gris-oscuro);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.reason-row:last-child { border-bottom: 0; }
|
||||
.reason-row strong { color: var(--glm-azul); }
|
||||
|
||||
.kpis-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 14px;
|
||||
color: var(--glm-acero);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.kpis-empty i { color: var(--glm-gris-medio); }
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.kpis-heading { flex-direction: column; gap: 6px; }
|
||||
.kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
@media (max-width: 430px) {
|
||||
.kpi-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<div class="kpis-panel">
|
||||
<div class="kpis-heading">
|
||||
<div>
|
||||
<h2 class="section-title">Indicadores de planificación</h2>
|
||||
<p class="kpis-subtitle">Resumen total de la planificación actual</p>
|
||||
</div>
|
||||
<div class="kpis-actions">
|
||||
<span class="kpis-status" *ngIf="hasData"><i class="pi pi-check-circle"></i> Datos disponibles</span>
|
||||
<button type="button" class="export-button" *ngIf="hasData" (click)="exportPlanning()"><i class="pi pi-download"></i> Descargar XLSX</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="kpi-grid">
|
||||
<article class="kpi-card kpi-primary">
|
||||
<div class="kpi-icon"><i class="pi pi-map-marker"></i></div>
|
||||
<div><span class="kpi-label">PDVs totales</span><strong>{{ summary.totalPdvs }}</strong><small>en la planificación</small></div>
|
||||
</article>
|
||||
<article class="kpi-card kpi-success">
|
||||
<div class="kpi-icon"><i class="pi pi-check"></i></div>
|
||||
<div><span class="kpi-label">PDVs asignados</span><strong>{{ summary.assignedPdvs }}</strong><small>{{ summary.coverage | number:'1.1-1' }}% de cobertura</small></div>
|
||||
</article>
|
||||
<article class="kpi-card kpi-warning">
|
||||
<div class="kpi-icon"><i class="pi pi-exclamation-triangle"></i></div>
|
||||
<div><span class="kpi-label">Sin asignar</span><strong>{{ summary.unassignedPdvs }}</strong><small>requieren revisión</small></div>
|
||||
</article>
|
||||
<article class="kpi-card kpi-blue">
|
||||
<div class="kpi-icon"><i class="pi pi-users"></i></div>
|
||||
<div><span class="kpi-label">Usuarios activos</span><strong>{{ summary.users }}</strong><small>{{ summary.days }} días planificados</small></div>
|
||||
</article>
|
||||
<article class="kpi-card kpi-orange">
|
||||
<div class="kpi-icon"><i class="pi pi-compass"></i></div>
|
||||
<div><span class="kpi-label">Distancia total</span><strong>{{ summary.totalDistance | number:'1.0-1' }} <em>km</em></strong><small>{{ summary.averageDistance | number:'1.0-1' }} km promedio por ruta</small></div>
|
||||
</article>
|
||||
<ng-container *ngIf="hasData">
|
||||
<article class="kpi-card kpi-success">
|
||||
<div class="kpi-icon"><i class="pi pi-briefcase"></i></div>
|
||||
<div><span class="kpi-label">Carga de trabajo</span><strong>{{ summary.totalWorkHours | number:'1.0-1' }} <em>h</em></strong><small>horas de trabajo planificadas</small></div>
|
||||
</article>
|
||||
</ng-container>
|
||||
</div>
|
||||
|
||||
<div class="user-load-card" *ngIf="userLoads.length">
|
||||
<h3><i class="pi pi-users"></i> Balance de carga por usuario</h3>
|
||||
<div class="user-load-table-wrap">
|
||||
<table class="user-load-table">
|
||||
<thead>
|
||||
<tr><th>Usuario</th><th>Rutas</th><th>Distancia</th><th>Trabajo</th><th>Utilización</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let load of userLoads" [class.load-over-capacity]="load.status === 'over-capacity'">
|
||||
<td>{{ load.name }}</td>
|
||||
<td>{{ load.routes }}</td>
|
||||
<td>{{ load.distance | number:'1.0-1' }} km</td>
|
||||
<td>{{ load.workHours | number:'1.0-1' }} h</td>
|
||||
<td>
|
||||
<div class="utilization-cell" [ngClass]="utilizationClass(load)">
|
||||
<span>{{ load.utilization | number:'1.0-1' }}%</span>
|
||||
<span class="capacity-warning" *ngIf="load.status === 'over-capacity'" [title]="load.alertMessage" aria-label="Alerta de capacidad">⚠️</span>
|
||||
<span class="utilization-bar" [title]="load.alertMessage"><span [style.width.%]="barWidth(load.utilization)"></span></span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="reasons-card" *ngIf="reasons.length">
|
||||
<h3><i class="pi pi-list"></i> Motivos de PDVs sin asignar</h3>
|
||||
<div class="reason-list">
|
||||
<div class="reason-row" *ngFor="let item of reasons">
|
||||
<span>{{ item.reason }}</span>
|
||||
<strong>{{ item.count }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="kpis-empty" *ngIf="!hasData">
|
||||
<i class="pi pi-chart-bar"></i>
|
||||
<span>Carga una planificación para visualizar sus indicadores.</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,176 @@
|
||||
import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { RouteState } from '../../../core/route-state/route';
|
||||
import { PlanningExportService } from '../../../shared/services/planning-export.service';
|
||||
import { summarizeDailyRoutes } from '../../../shared/utils/route-sequencing.utils';
|
||||
import { RouteAssignedResponse } from '../../../core/models/route.model';
|
||||
|
||||
interface KpiSummary {
|
||||
totalPdvs: number;
|
||||
assignedPdvs: number;
|
||||
unassignedPdvs: number;
|
||||
coverage: number;
|
||||
users: number;
|
||||
days: number;
|
||||
totalDistance: number;
|
||||
averageDistance: number;
|
||||
totalWorkHours: number;
|
||||
}
|
||||
|
||||
interface ReasonSummary {
|
||||
reason: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface UserLoad {
|
||||
id: string;
|
||||
name: string;
|
||||
routes: number;
|
||||
distance: number;
|
||||
workHours: number;
|
||||
capacityHours: number;
|
||||
utilization: number;
|
||||
status: 'ok' | 'warning' | 'over-capacity';
|
||||
alertMessage: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
selector: 'app-planning-kpis',
|
||||
imports: [CommonModule],
|
||||
templateUrl: './planning-kpis.component.html',
|
||||
styleUrl: './planning-kpis.component.css'
|
||||
})
|
||||
export class PlanningKpisComponent implements OnInit, OnDestroy {
|
||||
summary: KpiSummary = this.emptySummary();
|
||||
reasons: ReasonSummary[] = [];
|
||||
userLoads: UserLoad[] = [];
|
||||
hasData = false;
|
||||
|
||||
private readonly subs: Subscription[] = [];
|
||||
|
||||
constructor(
|
||||
private routeState: RouteState,
|
||||
private exportService: PlanningExportService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.subs.push(
|
||||
this.routeState.assignedRoutes$.subscribe(() => this.refresh()),
|
||||
this.routeState.noAssignedRoutes$.subscribe(() => this.refresh())
|
||||
);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.subs.forEach(subscription => subscription.unsubscribe());
|
||||
}
|
||||
|
||||
barWidth(value: number): number {
|
||||
return Math.min(Math.max(value, 0), 100);
|
||||
}
|
||||
|
||||
utilizationClass(load: UserLoad): string {
|
||||
return load.status;
|
||||
}
|
||||
|
||||
exportPlanning(): void {
|
||||
this.exportService.export();
|
||||
}
|
||||
|
||||
private refresh(): void {
|
||||
const assigned = this.routeState.getAssignedSnapshot();
|
||||
const unassigned = this.routeState.getNoAssignedSnapshot();
|
||||
const assignedPdvIds = new Set(assigned.map(route => String(route.json.pdv_id)));
|
||||
// A PDV with at least one scheduled visit is assigned; repeated weekly visits and
|
||||
// partial-assignment alerts must not inflate the planning coverage counters.
|
||||
const unassignedPdvIds = new Set(unassigned
|
||||
.map(route => String(route.pdv_id))
|
||||
.filter(pdvId => !assignedPdvIds.has(pdvId)));
|
||||
const totalPdvs = new Set([...assignedPdvIds, ...unassignedPdvIds]).size;
|
||||
const dailyRoutes = summarizeDailyRoutes(assigned);
|
||||
const totalDistance = dailyRoutes.reduce((sum, day) => sum + day.distanceKm, 0);
|
||||
const totalWorkHours = dailyRoutes.reduce((sum, day) => sum + day.workHours, 0);
|
||||
const users = new Set(assigned.map(route => String(route.json.usuario_id))).size;
|
||||
const days = new Set(assigned.map(route => route.json.dia)).size;
|
||||
const loads = new Map<string, UserLoad>();
|
||||
|
||||
for (const route of assigned) {
|
||||
const key = String(route.json.usuario_id);
|
||||
const current = loads.get(key) ?? {
|
||||
id: key,
|
||||
name: route.json.nombre_usuario,
|
||||
routes: 0,
|
||||
distance: 0,
|
||||
workHours: 0,
|
||||
capacityHours: this.numberValue(route.json.hora_laboral_semanal_usuario),
|
||||
utilization: 0,
|
||||
status: 'ok',
|
||||
alertMessage: ''
|
||||
};
|
||||
current.routes++;
|
||||
// Sequential distance and work are aggregated per user below.
|
||||
loads.set(key, current);
|
||||
}
|
||||
|
||||
this.userLoads = Array.from(loads.values()).map(load => {
|
||||
const userDays = dailyRoutes.filter(day => day.userId === load.id);
|
||||
load.distance = userDays.reduce((sum, day) => sum + day.distanceKm, 0);
|
||||
load.workHours = userDays.reduce((sum, day) => sum + day.workHours, 0);
|
||||
load.utilization = load.capacityHours ? (load.workHours / load.capacityHours) * 100 : 0;
|
||||
load.status = load.utilization > 100 ? 'over-capacity' : load.utilization > 90 ? 'warning' : 'ok';
|
||||
load.alertMessage = load.status === 'over-capacity'
|
||||
? `Alerta: ${load.name} supera el 100% de su capacidad por carga (${load.workHours.toFixed(1)} h de ${load.capacityHours.toFixed(1)} h). Reasigna PDVs o reduce horas.`
|
||||
: load.status === 'warning'
|
||||
? `${load.name} está sobre el 90% de su capacidad por carga (${load.workHours.toFixed(1)} h de ${load.capacityHours.toFixed(1)} h).`
|
||||
: `${load.name} está dentro de capacidad por carga (${load.workHours.toFixed(1)} h de ${load.capacityHours.toFixed(1)} h).`;
|
||||
return load;
|
||||
}).sort((a, b) => b.routes - a.routes || b.workHours - a.workHours);
|
||||
this.summary = {
|
||||
totalPdvs,
|
||||
assignedPdvs: assignedPdvIds.size,
|
||||
unassignedPdvs: unassignedPdvIds.size,
|
||||
coverage: totalPdvs ? (assignedPdvIds.size / totalPdvs) * 100 : 0,
|
||||
users,
|
||||
days,
|
||||
totalDistance,
|
||||
averageDistance: assigned.length ? totalDistance / assigned.length : 0,
|
||||
totalWorkHours,
|
||||
};
|
||||
|
||||
const reasonByPdv = new Map<string, string>();
|
||||
for (const route of unassigned) {
|
||||
const pdvId = String(route.pdv_id);
|
||||
if (assignedPdvIds.has(pdvId) || reasonByPdv.has(pdvId)) continue;
|
||||
const reason = route.motivo?.trim() || 'Sin motivo especificado';
|
||||
reasonByPdv.set(pdvId, reason);
|
||||
}
|
||||
const reasonCounts = new Map<string, number>();
|
||||
for (const reason of reasonByPdv.values()) {
|
||||
reasonCounts.set(reason, (reasonCounts.get(reason) ?? 0) + 1);
|
||||
}
|
||||
this.reasons = Array.from(reasonCounts.entries())
|
||||
.map(([reason, count]) => ({ reason, count }))
|
||||
.sort((a, b) => b.count - a.count);
|
||||
this.hasData = totalPdvs > 0;
|
||||
}
|
||||
|
||||
private numberValue(value: number | string | null | undefined): number {
|
||||
const result = Number(value);
|
||||
return Number.isFinite(result) ? result : 0;
|
||||
}
|
||||
|
||||
private emptySummary(): KpiSummary {
|
||||
return {
|
||||
totalPdvs: 0,
|
||||
assignedPdvs: 0,
|
||||
unassignedPdvs: 0,
|
||||
coverage: 0,
|
||||
users: 0,
|
||||
days: 0,
|
||||
totalDistance: 0,
|
||||
averageDistance: 0,
|
||||
totalWorkHours: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
+508
@@ -0,0 +1,508 @@
|
||||
:host {
|
||||
display: block;
|
||||
height: 100vh;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
#map-overview {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 380px;
|
||||
width: auto;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.overview-sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
width: 380px;
|
||||
z-index: 900;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
padding: 16px;
|
||||
overflow-y: auto;
|
||||
background: var(--glm-surface);
|
||||
border-right: 3px solid var(--glm-verde);
|
||||
}
|
||||
|
||||
.sidebar-brand {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 2px solid var(--glm-gris-medio);
|
||||
}
|
||||
|
||||
.sidebar-logo {
|
||||
height: 42px;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 2px solid var(--glm-gris-medio);
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 7px 12px;
|
||||
background: var(--glm-surface);
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-radius: 4px;
|
||||
color: var(--glm-azul);
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
|
||||
.back-btn:hover {
|
||||
background: var(--glm-verde-bg);
|
||||
border-color: var(--glm-verde);
|
||||
}
|
||||
|
||||
.sidebar-title {
|
||||
margin: 0;
|
||||
font-size: 1rem;
|
||||
color: var(--glm-azul);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.territory-summary { margin: 4px 0 0; color: var(--glm-acero); font-size: .76rem; line-height: 1.35; }
|
||||
.territory-summary i { color: var(--glm-verde); margin-right: 3px; }
|
||||
|
||||
.filters-card {
|
||||
background: var(--glm-verde-bg);
|
||||
border: 1px solid var(--glm-verde-claro);
|
||||
border-radius: 4px;
|
||||
padding: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.filter-label {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
color: var(--glm-azul);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.3px;
|
||||
}
|
||||
|
||||
.filter-select {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-radius: 4px;
|
||||
font-size: 0.9rem;
|
||||
font-family: Arial, sans-serif;
|
||||
background: #fff;
|
||||
color: var(--glm-gris-oscuro);
|
||||
}
|
||||
|
||||
.filter-select:focus {
|
||||
outline: none;
|
||||
border-color: var(--glm-verde);
|
||||
box-shadow: 0 0 0 2px rgba(108, 194, 74, 0.15);
|
||||
}
|
||||
|
||||
.filter-stats {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 6px;
|
||||
font-size: 0.82rem;
|
||||
color: var(--glm-acero);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.filter-empty {
|
||||
font-size: 0.85rem;
|
||||
color: var(--glm-acero);
|
||||
}
|
||||
|
||||
.heatmap-help { display: inline-grid; width: 16px; height: 16px; margin-left: auto; place-items: center; border: 1px solid var(--glm-acero); border-radius: 50%; color: var(--glm-acero); cursor: help; font-size: 0.68rem; font-weight: 700; }
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 24px 12px;
|
||||
color: var(--glm-acero);
|
||||
}
|
||||
|
||||
.empty-state i {
|
||||
font-size: 2rem;
|
||||
margin-bottom: 8px;
|
||||
display: block;
|
||||
color: var(--glm-gris-medio);
|
||||
}
|
||||
|
||||
.error-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
background: var(--glm-rojo-ok);
|
||||
border: 1px solid #F5A6A0;
|
||||
border-radius: 4px;
|
||||
font-size: 0.85rem;
|
||||
color: var(--glm-gris-oscuro);
|
||||
}
|
||||
|
||||
.unassigned-bottom-drawer {
|
||||
position: fixed;
|
||||
left: 398px;
|
||||
right: 18px;
|
||||
bottom: 18px;
|
||||
z-index: 950;
|
||||
overflow: hidden;
|
||||
border: 1px solid #f2bf86;
|
||||
border-left: 4px solid var(--glm-naranja);
|
||||
border-radius: 10px 10px 4px 4px;
|
||||
background: #fff8ed;
|
||||
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.unassigned-drawer-toggle {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
border: 0;
|
||||
background: #fff8ed;
|
||||
color: var(--glm-azul);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.unassigned-drawer-toggle span { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.unassigned-drawer-toggle .pi-exclamation-triangle { color: var(--glm-naranja); }
|
||||
|
||||
.unassigned-drawer-content {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
|
||||
gap: 8px;
|
||||
max-height: 240px;
|
||||
padding: 0 12px 12px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.unassigned-map-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 7px;
|
||||
border: 1px solid #f2bf86;
|
||||
border-radius: 3px;
|
||||
background: #fff;
|
||||
color: var(--glm-gris-oscuro);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.unassigned-map-item:hover,
|
||||
.unassigned-map-item.selected-pending { background: #ffedd9; }
|
||||
|
||||
.pending-icon {
|
||||
display: grid;
|
||||
flex: 0 0 23px;
|
||||
width: 23px;
|
||||
height: 23px;
|
||||
place-items: center;
|
||||
border-radius: 50%;
|
||||
background: var(--glm-naranja);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.pending-text { display: flex; min-width: 0; flex-direction: column; gap: 2px; }
|
||||
.pending-text strong { font-size: 0.78rem; }
|
||||
.pending-text small { overflow: hidden; color: var(--glm-acero); font-size: 0.7rem; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
.unassigned-detail-card { border-top-color: var(--glm-naranja); }
|
||||
|
||||
.pending-edit-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.pending-edit-grid label { display: flex; flex-direction: column; gap: 3px; color: var(--glm-azul); font-size: 0.72rem; font-weight: 700; text-transform: uppercase; }
|
||||
.pending-edit-grid input,
|
||||
.pending-edit-grid select { width: 100%; padding: 6px; border: 1px solid var(--glm-gris-medio); border-radius: 3px; background: #fff; color: var(--glm-gris-oscuro); font: inherit; font-size: 0.8rem; }
|
||||
.day-checkboxes { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.day-checkboxes label { display: inline-flex; align-items: center; gap: 3px; color: var(--glm-acero); font-size: 0.72rem; font-weight: 600; }
|
||||
.wide-field { grid-column: 1 / -1; }
|
||||
.pending-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-top: 10px; }
|
||||
.pending-actions .btn-primary, .pending-actions .btn-secondary { padding: 7px 10px; font-size: 0.78rem; }
|
||||
|
||||
.employee-load-list { display: grid; gap: 5px; max-height: 318px; margin-top: 10px; overflow-y: auto; border-top: 1px solid var(--glm-gris-claro); padding-top: 8px; }
|
||||
.employee-load-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 3px 8px; width: 100%; padding: 7px 8px; border: 1px solid var(--glm-gris-medio); border-radius: 4px; background: #fff; color: var(--glm-gris-oscuro); cursor: pointer; font: inherit; text-align: left; }
|
||||
.employee-load-row:hover, .employee-load-row.selected { border-color: var(--glm-verde); background: var(--glm-verde-bg); }
|
||||
.employee-load-row.over-capacity { border-color: #c9252d; background: var(--glm-rojo-ok); }
|
||||
.employee-load-name { overflow: hidden; color: var(--glm-azul); font-size: 0.78rem; font-weight: 700; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.employee-load-values { color: var(--glm-acero); font-size: 0.7rem; white-space: nowrap; }
|
||||
.employee-load-bar { grid-column: 1 / -1; display: block; height: 6px; overflow: hidden; border-radius: 6px; background: var(--glm-gris-medio); }
|
||||
.employee-load-bar span { display: block; height: 100%; border-radius: inherit; background: var(--glm-verde); }
|
||||
.employee-load-bar.warning span { background: var(--glm-naranja); }
|
||||
.employee-load-bar.over-capacity span { background: #c9252d; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
#map-overview { left: 0; }
|
||||
.overview-sidebar { width: 340px; max-width: calc(100vw - 24px); }
|
||||
.unassigned-bottom-drawer { right: 12px; bottom: 12px; left: 12px; }
|
||||
}
|
||||
|
||||
.info-card {
|
||||
background: var(--glm-surface);
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-radius: 4px;
|
||||
padding: 14px;
|
||||
border-top: 3px solid var(--glm-azul);
|
||||
}
|
||||
|
||||
.map-location-button {
|
||||
margin-top: 0;
|
||||
padding: 6px 9px;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.info-card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
border-bottom: 2px solid var(--glm-verde);
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.info-card-header h3 {
|
||||
margin: 0;
|
||||
font-size: 0.85rem;
|
||||
color: var(--glm-azul);
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.detail-section + .detail-section {
|
||||
margin-top: 14px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--glm-gris-medio);
|
||||
}
|
||||
|
||||
.detail-section h4 {
|
||||
margin: 0 0 5px;
|
||||
color: var(--glm-verde);
|
||||
font-size: 0.76rem;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.reassign-form {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--glm-gris-medio);
|
||||
}
|
||||
|
||||
.reassign-form label { display: flex; flex-direction: column; gap: 3px; color: var(--glm-azul); font-size: 0.72rem; font-weight: 700; text-transform: uppercase; }
|
||||
.reassign-form select { width: 100%; padding: 6px; border: 1px solid var(--glm-gris-medio); border-radius: 3px; background: #fff; color: var(--glm-gris-oscuro); font: inherit; font-size: 0.8rem; }
|
||||
.reassign-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-top: 10px; }
|
||||
.reassign-actions .btn-primary, .reassign-actions .btn-secondary { padding: 7px 10px; font-size: 0.78rem; }
|
||||
.reassign-hint { grid-column: 1 / -1; margin: 0; color: var(--glm-acero); font-size: 0.74rem; }
|
||||
.reassign-form .reassign-actions, .reassign-form .employee-load-list, .reassign-form .error-card { grid-column: 1 / -1; }
|
||||
|
||||
.daily-routes-card { padding: 12px; border: 1px solid var(--glm-gris-medio); border-top: 3px solid var(--glm-azul); border-radius: 4px; background: var(--glm-surface); }
|
||||
.daily-routes-card h3 { margin: 0 0 8px; color: var(--glm-azul); font-size: 0.82rem; text-transform: uppercase; }
|
||||
.daily-route-group { border-bottom: 1px solid var(--glm-gris-claro); }
|
||||
.daily-route-group:last-child { border-bottom: 0; }
|
||||
.daily-route-toggle { display: flex; width: 100%; align-items: center; justify-content: space-between; gap: 8px; padding: 10px 0; border: 0; background: transparent; color: var(--glm-gris-oscuro); cursor: pointer; font: inherit; text-align: left; }
|
||||
.daily-route-toggle:hover { background: var(--glm-gris-claro); }
|
||||
.daily-route-toggle-title { color: var(--glm-azul); font-weight: 700; }
|
||||
.daily-route-toggle > span:last-child { color: var(--glm-acero); font-size: 0.78rem; }
|
||||
.daily-route-group-content { padding-left: 14px; }
|
||||
.daily-route { display: grid; gap: 3px; padding: 8px 0; border-bottom: 1px solid var(--glm-gris-claro); color: var(--glm-gris-oscuro); font-size: 0.78rem; }
|
||||
.daily-route:last-child { border-bottom: 0; }
|
||||
.daily-route span, .daily-route small { color: var(--glm-acero); }
|
||||
.daily-route.over-capacity small { color: #c9252d; font-weight: 700; }
|
||||
.btn-icon:focus-visible, button:focus-visible, select:focus-visible { outline: 3px solid rgba(108, 194, 74, 0.45); outline-offset: 2px; }
|
||||
|
||||
.btn-icon {
|
||||
background: transparent;
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-radius: 4px;
|
||||
padding: 4px 6px;
|
||||
cursor: pointer;
|
||||
color: var(--glm-azul);
|
||||
}
|
||||
|
||||
.btn-icon:hover {
|
||||
background: var(--glm-verde-bg);
|
||||
border-color: var(--glm-verde);
|
||||
}
|
||||
|
||||
.info-list {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.info-list div {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 5px 0;
|
||||
border-bottom: 1px solid var(--glm-gris-claro);
|
||||
}
|
||||
|
||||
.info-list div:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.info-list dt {
|
||||
font-weight: 600;
|
||||
color: var(--glm-azul);
|
||||
font-size: 0.78rem;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.info-list dd {
|
||||
margin: 0;
|
||||
font-size: 0.85rem;
|
||||
color: var(--glm-gris-oscuro);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.overview-loading {
|
||||
position: fixed;
|
||||
top: 16px;
|
||||
right: 16px;
|
||||
z-index: 999;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 14px;
|
||||
background: rgba(255, 255, 255, 0.95);
|
||||
border: 1px solid var(--glm-verde-claro);
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
|
||||
color: var(--glm-acero);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border: 2px solid var(--glm-gris-medio);
|
||||
border-top-color: var(--glm-verde);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--glm-surface);
|
||||
color: var(--glm-azul);
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-radius: 4px;
|
||||
padding: 8px 14px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: var(--glm-verde-bg);
|
||||
border-color: var(--glm-verde);
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.layer-toggles {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin-top: 8px;
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--glm-gris-medio);
|
||||
}
|
||||
|
||||
.toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
color: var(--glm-gris-oscuro);
|
||||
}
|
||||
|
||||
.custom-marker {
|
||||
background: none !important;
|
||||
border: none !important;
|
||||
}
|
||||
|
||||
.location-pin-wrapper {
|
||||
width: 42px;
|
||||
height: 50px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding-top: 3px;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
transition: transform 140ms ease, background-color 140ms ease, box-shadow 140ms ease;
|
||||
}
|
||||
|
||||
.location-pin-wrapper:hover {
|
||||
transform: scale(1.12);
|
||||
background: rgba(255, 255, 255, 0.94);
|
||||
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.location-pin-wrapper .location-pin {
|
||||
position: relative;
|
||||
width: 30px;
|
||||
height: 38px;
|
||||
background: #c9252d;
|
||||
clip-path: polygon(50% 100%, 8% 43%, 5% 31%, 10% 18%, 22% 7%, 36% 2%, 50% 0, 64% 2%, 78% 7%, 90% 18%, 95% 31%, 92% 43%);
|
||||
filter: drop-shadow(0 2px 2px rgba(0, 0, 0, 0.42));
|
||||
}
|
||||
|
||||
.location-pin-wrapper .location-pin span {
|
||||
position: absolute;
|
||||
inset: 8px 0 auto;
|
||||
color: #fff;
|
||||
font: 700 12px Arial, sans-serif;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.marker-inner {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 700;
|
||||
font-size: 12px;
|
||||
color: #fff;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.4);
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
<div id="map-overview"></div>
|
||||
|
||||
<div class="overview-loading" *ngIf="isLoading">
|
||||
<div class="spinner"></div>
|
||||
<p>Cargando rutas ORS... {{ orsProgress }}/{{ orsTotal }}</p>
|
||||
</div>
|
||||
|
||||
<div class="overview-sidebar">
|
||||
<div class="sidebar-brand">
|
||||
<img src="GLM_completo.png" alt="GomezLee Marketing" class="sidebar-logo" />
|
||||
</div>
|
||||
|
||||
<div class="sidebar-header">
|
||||
<button type="button" class="back-btn" (click)="goBack()" aria-label="Volver a la planificación">
|
||||
<i class="pi pi-arrow-left"></i> Volver
|
||||
</button>
|
||||
<h2 class="sidebar-title">Mapa de rutas</h2>
|
||||
</div>
|
||||
<p class="territory-summary" *ngIf="activeTerritories.length"><i class="pi pi-map-marker"></i> {{ activeTerritories.join(', ') }}</p>
|
||||
|
||||
<div class="filters-card" *ngIf="usuarios.length">
|
||||
<label class="filter-label">Usuario</label>
|
||||
<select class="filter-select" [(ngModel)]="selectedUsuarioId" (ngModelChange)="onUsuarioChange()">
|
||||
<option value="Todos">Todos los usuarios</option>
|
||||
<option *ngFor="let u of usuarios" [value]="u.id">{{ u.nombre }} ({{ u.id }})</option>
|
||||
</select>
|
||||
|
||||
<label class="filter-label">Día</label>
|
||||
<select class="filter-select" [(ngModel)]="selectedDia" (ngModelChange)="onDiaChange()">
|
||||
<option value="Todos">Todos</option>
|
||||
<option *ngFor="let d of dias" [value]="d">{{ d }}</option>
|
||||
</select>
|
||||
|
||||
<div class="filter-stats" *ngIf="filteredRoutes.length">
|
||||
<span>{{ uniqueFilteredRoutes.length }} PDVs</span>
|
||||
<span>{{ totalDistancia }} km</span>
|
||||
<span>{{ totalDuracionMin }} min</span>
|
||||
</div>
|
||||
|
||||
<div class="layer-toggles">
|
||||
<label class="toggle">
|
||||
<input type="checkbox" [checked]="showHeat" (change)="toggleHeat()" />
|
||||
<i class="pi pi-fire"></i> Heatmap (carga)
|
||||
<span class="heatmap-help" title="El mapa muestra con mayor intensidad las zonas donde se concentra más carga de trabajo en horas.">?</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="filter-empty" *ngIf="!filteredRoutes.length && !error">
|
||||
Sin rutas para este filtro.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="empty-state" *ngIf="!usuarios.length">
|
||||
<i class="pi pi-inbox"></i>
|
||||
<p>No hay rutas cargadas.</p>
|
||||
<button type="button" class="btn-secondary" (click)="goBack()">Ir a Home</button>
|
||||
</div>
|
||||
|
||||
<div class="error-card" *ngIf="error && usuarios.length">
|
||||
<i class="pi pi-exclamation-triangle"></i>
|
||||
{{ error }}
|
||||
</div>
|
||||
|
||||
<section class="info-card unassigned-detail-card" *ngIf="selectedUnassigned">
|
||||
<div class="info-card-header">
|
||||
<h3>Gestionar PDV sin ruta</h3>
|
||||
<button type="button" class="btn-icon" (click)="selectedUnassigned = null"><i class="pi pi-times"></i></button>
|
||||
</div>
|
||||
<ng-container *ngIf="editingUnassigned; else pendingSummary">
|
||||
<div class="pending-edit-grid">
|
||||
<label>Nombre<input [(ngModel)]="editUnassignedName" type="text"></label>
|
||||
<label>Horas mínimas<input [(ngModel)]="editUnassignedHours" type="number" min="0.01" step="0.25"></label>
|
||||
<label>Latitud<input [(ngModel)]="editUnassignedLat" type="number" step="any"></label>
|
||||
<label>Longitud<input [(ngModel)]="editUnassignedLng" type="number" step="any"></label>
|
||||
<label class="wide-field">Motivo<input [(ngModel)]="editUnassignedReason" type="text"></label>
|
||||
</div>
|
||||
<div class="pending-actions"><button type="button" class="btn-secondary" (click)="saveUnassignedEdit()"><i class="pi pi-check"></i> Guardar</button><button type="button" class="btn-secondary" (click)="cancelUnassignedEdit()">Cancelar</button></div>
|
||||
</ng-container>
|
||||
<ng-template #pendingSummary>
|
||||
<dl class="info-list">
|
||||
<div><dt>PDV</dt><dd>{{ selectedUnassigned.pdv_nombre }}</dd></div>
|
||||
<div><dt>Motivo</dt><dd>{{ selectedUnassigned.motivo }}</dd></div>
|
||||
<div><dt>Coordenadas</dt><dd>{{ selectedUnassigned.latitud }}, {{ selectedUnassigned.longitud }}</dd></div>
|
||||
</dl>
|
||||
<div class="pending-edit-grid">
|
||||
<label>Usuario<select [(ngModel)]="assignmentUser[selectedUnassigned.pdv_id]"><option value="">Seleccionar</option><option *ngFor="let user of unassignedUserOptions" [value]="user.id">{{ user.name }}</option></select></label>
|
||||
<label>Días<div class="day-checkboxes"><label *ngFor="let day of unassignedDayOptions"><input type="checkbox" [checked]="(assignmentDays[selectedUnassigned.pdv_id] || []).includes(day)" (change)="toggleUnassignedDay(selectedUnassigned.pdv_id, day, $any($event.target).checked)">{{ day.substring(0, 3) }}</label></div></label>
|
||||
</div>
|
||||
<div class="pending-actions"><button type="button" class="btn-secondary" (click)="startUnassignedEdit(selectedUnassigned)"><i class="pi pi-pencil"></i> Editar</button><button type="button" class="btn-primary" (click)="assignUnassigned(selectedUnassigned)" [disabled]="assigningUnassignedId === selectedUnassigned.pdv_id"><span *ngIf="assigningUnassignedId === selectedUnassigned.pdv_id" class="spinner-inline"></span><i *ngIf="assigningUnassignedId !== selectedUnassigned.pdv_id" class="pi pi-user-plus"></i> Reasignar</button></div>
|
||||
<div class="employee-load-list" aria-label="Carga de empleados">
|
||||
<button type="button" class="employee-load-row" *ngFor="let employee of unassignedEmployeeLoads" [class.selected]="assignmentUser[selectedUnassigned.pdv_id] === employee.id" [class.over-capacity]="employeeLoadStatus(employee) === 'over-capacity'" (click)="selectUnassignedEmployee(employee.id)">
|
||||
<span class="employee-load-name">{{ employee.name }}</span>
|
||||
<span class="employee-load-values">{{ employee.workHours | number:'1.0-1' }} / {{ employee.capacityHours | number:'1.0-1' }} h · {{ employee.utilization | number:'1.0-1' }}%</span>
|
||||
<span class="employee-load-bar" [ngClass]="employeeLoadStatus(employee)"><span [style.width.%]="employeeLoadWidth(employee)"></span></span>
|
||||
</button>
|
||||
</div>
|
||||
</ng-template>
|
||||
<div class="error-card" *ngIf="unassignedActionError">{{ unassignedActionError }}</div>
|
||||
</section>
|
||||
|
||||
<section class="info-card" *ngIf="selectedRouteDetail">
|
||||
<div class="info-card-header">
|
||||
<h3>Detalle de la ruta</h3>
|
||||
<button type="button" class="btn-icon" (click)="clearSelection()" title="Cerrar detalle" aria-label="Cerrar detalle de ruta">
|
||||
<i class="pi pi-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="detail-section">
|
||||
<h4><i class="pi pi-user"></i> Usuario</h4>
|
||||
<dl class="info-list">
|
||||
<div><dt>Nombre</dt><dd>{{ selectedRouteDetail.json.nombre_usuario }}</dd></div>
|
||||
<div><dt>ID</dt><dd>{{ selectedRouteDetail.json.usuario_id }}</dd></div>
|
||||
<div><dt>Origen</dt><dd>{{ selectedRouteDetail.json.latitud_usuario }}, {{ selectedRouteDetail.json.longitud_usuario }}</dd></div>
|
||||
<div><dt>Horas disponibles</dt><dd>{{ selectedRouteDetail.json.hora_laboral_semanal_usuario }} h/semana</dd></div>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="detail-section">
|
||||
<h4><i class="pi pi-map-marker"></i> PDV</h4>
|
||||
<dl class="info-list">
|
||||
<div><dt>Nombre</dt><dd>{{ selectedRouteDetail.json.nombre_pdv }}</dd></div>
|
||||
<div><dt>ID</dt><dd>{{ selectedRouteDetail.json.pdv_id }}</dd></div>
|
||||
<div><dt>Día</dt><dd>{{ selectedRouteDetail.json.dia }}</dd></div>
|
||||
<div><dt>Orden de visita</dt><dd>{{ selectedVisitOrder }}</dd></div>
|
||||
<div><dt>Origen del tramo</dt><dd>{{ selectedSegmentOrigin }}</dd></div>
|
||||
<div><dt>Destino</dt><dd><button type="button" class="btn-secondary map-location-button" (click)="openDestinationInGoogleMaps()" title="Abrir ubicación en Google Maps"><i class="pi pi-map"></i> Ver en Google Maps</button></dd></div>
|
||||
<div><dt>Horas trabajo</dt><dd>{{ selectedRouteDetail.json.horas_trabajo }}</dd></div>
|
||||
<div><dt>Distancia tramo</dt><dd>{{ selectedSegmentDistance | number:'1.2-2' }} km</dd></div>
|
||||
<div><dt>Duración tramo</dt><dd>{{ selectedSegmentDurationMinutes | number:'1.0-0' }} min</dd></div>
|
||||
</dl>
|
||||
<div class="reassign-actions" *ngIf="!showReassignForm">
|
||||
<button type="button" class="btn-secondary" (click)="moveSelectedVisit(-1)" [disabled]="!canMoveSelectedVisitUp" aria-label="Mover visita anterior"><i class="pi pi-arrow-up"></i> Subir</button>
|
||||
<button type="button" class="btn-secondary" (click)="moveSelectedVisit(1)" [disabled]="!canMoveSelectedVisitDown" aria-label="Mover visita posterior"><i class="pi pi-arrow-down"></i> Bajar</button>
|
||||
<button type="button" class="btn-secondary" (click)="resetSelectedDayOrder()"><i class="pi pi-refresh"></i> Orden automático</button>
|
||||
<button type="button" class="btn-secondary" (click)="startReassignRoute()"><i class="pi pi-user-edit"></i> Reasignar ruta</button>
|
||||
</div>
|
||||
<div class="reassign-form" *ngIf="showReassignForm">
|
||||
<label>Nuevo usuario<select [(ngModel)]="reassignUserId"><option *ngFor="let user of unassignedUserOptions" [value]="user.id">{{ user.name }}</option></select></label>
|
||||
<label>Día<select [(ngModel)]="reassignDay"><option *ngFor="let day of unassignedDayOptions" [value]="day">{{ day }}</option></select></label>
|
||||
<p class="reassign-hint">Se recalcularán la distancia y duración con ruta vial ORS.</p>
|
||||
<div class="reassign-actions"><button type="button" class="btn-primary" (click)="reassignRoute()" [disabled]="reassigningRoute"><span *ngIf="reassigningRoute" class="spinner-inline"></span><i *ngIf="!reassigningRoute" class="pi pi-check"></i> {{ reassigningRoute ? 'Calculando...' : 'Confirmar' }}</button><button type="button" class="btn-secondary" (click)="cancelReassignRoute()" [disabled]="reassigningRoute">Cancelar</button></div>
|
||||
<div class="employee-load-list" aria-label="Carga de empleados">
|
||||
<button type="button" class="employee-load-row" *ngFor="let employee of reassignmentEmployeeLoads" [class.selected]="reassignUserId === employee.id" [class.over-capacity]="employeeLoadStatus(employee) === 'over-capacity'" (click)="selectReassignmentEmployee(employee.id)">
|
||||
<span class="employee-load-name">{{ employee.name }}</span>
|
||||
<span class="employee-load-values">{{ employee.workHours | number:'1.0-1' }} / {{ employee.capacityHours | number:'1.0-1' }} h · {{ employee.utilization | number:'1.0-1' }}%</span>
|
||||
<span class="employee-load-bar" [ngClass]="employeeLoadStatus(employee)"><span [style.width.%]="employeeLoadWidth(employee)"></span></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="error-card" *ngIf="reassignError">{{ reassignError }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="daily-routes-card" *ngIf="dailySummaries.length">
|
||||
<h3>Rutas diarias</h3>
|
||||
<article class="daily-route-group" *ngFor="let group of dailyGroups">
|
||||
<button type="button" class="daily-route-toggle" (click)="toggleDailyRouteDay(group.day)" [attr.aria-expanded]="isDailyRouteDayExpanded(group.day)">
|
||||
<span class="daily-route-toggle-title"><i class="pi" [class.pi-chevron-right]="!isDailyRouteDayExpanded(group.day)" [class.pi-chevron-down]="isDailyRouteDayExpanded(group.day)"></i> {{ group.day }}</span>
|
||||
<span>{{ group.totalStops }} paradas · {{ group.totalDistance | number:'1.1-1' }} km</span>
|
||||
</button>
|
||||
<div class="daily-route-group-content" *ngIf="isDailyRouteDayExpanded(group.day)">
|
||||
<article class="daily-route" *ngFor="let route of group.routes" [class.over-capacity]="route.exceedsCapacity">
|
||||
<strong>{{ route.userName }}</strong>
|
||||
<span>{{ route.routes.length }} paradas · {{ route.distanceKm | number:'1.1-1' }} km</span>
|
||||
<small [attr.aria-label]="route.exceedsCapacity ? 'Capacidad excedida' : 'Dentro de capacidad'">{{ route.totalHours | number:'1.1-1' }} / {{ route.capacityHours | number:'1.1-1' }} h {{ route.exceedsCapacity ? '· Excede capacidad' : '· Capacidad disponible' }}</small>
|
||||
</article>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
|
||||
<section class="unassigned-bottom-drawer" *ngIf="selectedUsuarioId === 'Todos' && selectedDia === 'Todos' && unassignedRoutes.length" [class.open]="isUnassignedDrawerOpen">
|
||||
<button type="button" class="unassigned-drawer-toggle" (click)="toggleUnassignedDrawer()" [attr.aria-expanded]="isUnassignedDrawerOpen">
|
||||
<span><i class="pi pi-exclamation-triangle"></i> PDVs sin ruta ({{ unassignedRoutes.length }})</span>
|
||||
<i class="pi" [class.pi-chevron-up]="!isUnassignedDrawerOpen" [class.pi-chevron-down]="isUnassignedDrawerOpen"></i>
|
||||
</button>
|
||||
<div class="unassigned-drawer-content" *ngIf="isUnassignedDrawerOpen">
|
||||
<button type="button" class="unassigned-map-item" *ngFor="let pending of unassignedRoutes" [class.selected-pending]="selectedUnassigned?.pdv_id === pending.pdv_id" (click)="selectUnassigned(pending)">
|
||||
<span class="pending-icon">!</span>
|
||||
<span class="pending-text"><strong>{{ pending.pdv_nombre }}</strong><small>{{ pending.motivo }}</small></span>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
+1007
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
<div class="projects-topbar"><img src="GLM_completo.png" alt="GomezLee Marketing"><span>Route Planner</span><div class="user-profile" *ngIf="profile.current"><img *ngIf="profile.avatarUrl" [src]="profile.avatarUrl" alt=""><span *ngIf="!profile.avatarUrl" class="avatar-fallback">{{ profile.current.nombre.charAt(0) }}</span><span>{{ profile.current.nombre }}</span></div><div class="topbar-actions"><a routerLink="/home">Mis proyectos</a><button type="button" (click)="signOut()"><i class="pi pi-sign-out"></i> Salir</button></div></div><main class="projects-page narrow"><header><div><h1>Crear proyecto</h1><p>Define el proyecto e importa los PDVs que se planificarán.</p></div></header><section class="project-form"><label>Nombre del proyecto<input [(ngModel)]="name" placeholder="Ej. Ruta Santo Domingo Norte" maxlength="120"></label><label>País<select [(ngModel)]="country"><option value="Republica Dominicana">República Dominicana</option><option value="MEXICO">México</option></select></label><label class="file-label">Archivo PDVs (Excel)<input type="file" accept=".xlsx,.xls" (change)="fileChanged($event)"><span>.xlsx / .xls, máximo 10 MB. El país también se detecta desde el archivo.</span></label><p *ngIf="file">{{ file.name }}</p><p *ngIf="loading">Validando archivo...</p><p class="valid" *ngIf="preview?.valid">{{ preview!.validRows }} PDVs válidos para crear el proyecto.</p><p class="error" *ngIf="preview && !preview.valid">El archivo tiene errores. Corrígelos antes de crear el proyecto.</p><p class="error" *ngIf="error">{{ error }}</p><button class="primary" type="button" [disabled]="!canCreate" (click)="create()">{{ saving ? 'Creando proyecto...' : 'Crear proyecto' }}</button></section></main>
|
||||
@@ -0,0 +1,52 @@
|
||||
import { ChangeDetectorRef, Component } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { ProjectService } from '../../core/services/project.service';
|
||||
import { AuthService } from '../../core/services/auth.service';
|
||||
import { UserProfileService } from '../../core/services/user-profile.service';
|
||||
import { ExcelPreviewService, PreviewResult } from '../../shared/services/excel-preview.service';
|
||||
|
||||
@Component({ standalone: true, selector: 'app-new-project', imports: [CommonModule, FormsModule, RouterLink], templateUrl: './new-project.component.html', styleUrl: './projects.component.css' })
|
||||
export class NewProjectComponent {
|
||||
name = '';
|
||||
country = 'Republica Dominicana';
|
||||
file: File | null = null;
|
||||
preview: PreviewResult | null = null;
|
||||
loading = false;
|
||||
saving = false;
|
||||
error = '';
|
||||
constructor(private projects: ProjectService, private auth: AuthService, public profile: UserProfileService, private previewService: ExcelPreviewService, private router: Router, private cdr: ChangeDetectorRef) {}
|
||||
async signOut(): Promise<void> { await this.auth.signOut(); await this.router.navigate(['/login']); }
|
||||
async fileChanged(event: Event): Promise<void> {
|
||||
const file = (event.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
this.file = file; this.preview = null; this.error = ''; this.loading = true;
|
||||
try {
|
||||
this.preview = await this.previewService.previewFile(file, 'PDV');
|
||||
const workbook = XLSX.read(await file.arrayBuffer(), { type: 'array' });
|
||||
const rows = XLSX.utils.sheet_to_json<Record<string, unknown>>(workbook.Sheets[workbook.SheetNames[0]], { defval: null, raw: true });
|
||||
const value = rows.map(row => Object.entries(row).find(([key]) => key.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase() === 'pais')?.[1]).find(Boolean);
|
||||
const normalized = String(value ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toUpperCase();
|
||||
if (normalized.includes('MEXICO')) this.country = 'MEXICO';
|
||||
else if (normalized.includes('DOMINICANA')) this.country = 'Republica Dominicana';
|
||||
}
|
||||
catch (error: any) { this.error = error?.message ?? 'No se pudo leer el archivo.'; }
|
||||
finally { this.loading = false; this.cdr.detectChanges(); }
|
||||
}
|
||||
get canCreate(): boolean { return !!this.name.trim() && !!this.country && !!this.file && !!this.preview?.valid && !this.saving; }
|
||||
async create(): Promise<void> {
|
||||
if (!this.canCreate || !this.file) return;
|
||||
this.saving = true; this.error = '';
|
||||
try {
|
||||
const workbook = XLSX.read(await this.file.arrayBuffer(), { type: 'array' });
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const rows = XLSX.utils.sheet_to_json<Record<string, unknown>>(sheet, { defval: null, raw: true });
|
||||
const projectRows = rows.map(row => ({ ...row, 'País': this.country }));
|
||||
const project = await this.projects.create(this.name, projectRows);
|
||||
await this.router.navigate(['/proyectos', project.id]);
|
||||
} catch (error: any) { this.error = error?.message ?? 'No se pudo crear el proyecto.'; }
|
||||
finally { this.saving = false; this.cdr.detectChanges(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
<div class="projects-topbar"><img src="GLM_completo.png" alt="GomezLee Marketing"><span>Route Planner</span><div class="user-profile" *ngIf="profile.current"><img *ngIf="profile.avatarUrl" [src]="profile.avatarUrl" alt=""><span *ngIf="!profile.avatarUrl" class="avatar-fallback">{{ profile.current.nombre.charAt(0) }}</span><span>{{ profile.current.nombre }}</span></div><div class="topbar-actions"><button type="button" (click)="signOut()"><i class="pi pi-sign-out"></i> Salir</button></div></div>
|
||||
<main class="projects-page"><a class="manage-employees" routerLink="/empleados"><i class="pi pi-users"></i> Gestionar empleados</a><header><div><h1>Mis proyectos</h1><p>Organiza y conserva tus planificaciones de rutas.</p></div><a class="primary" routerLink="/proyectos/nuevo"><i class="pi pi-plus"></i> Crear proyecto</a></header><p class="error" *ngIf="error">{{ error }}</p><p *ngIf="loading">Cargando proyectos...</p><section class="project-grid" *ngIf="!loading"><article class="project-card" *ngFor="let project of projects"><span class="state">{{ project.estado }}</span><h2>{{ project.nombre }}</h2><p>{{ project.descripcion || 'Sin descripción' }}</p><small>Actualizado: {{ project.updated_at | date:'medium' }}</small><div class="project-card-actions"><button type="button" (click)="open(project)" [disabled]="deletingId === project.id">Abrir proyecto</button><button type="button" class="danger" (click)="remove(project)" [disabled]="deletingId === project.id"><i class="pi pi-trash"></i> {{ deletingId === project.id ? 'Eliminando...' : 'Eliminar' }}</button></div></article><section class="empty" *ngIf="!projects.length"><i class="pi pi-folder-open"></i><h2>Aún no tienes proyectos</h2><p>Crea uno e importa su archivo de PDVs para comenzar.</p><a class="primary" routerLink="/proyectos/nuevo">Crear proyecto</a></section></section></main>
|
||||
@@ -0,0 +1,39 @@
|
||||
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { ProjectService } from '../../core/services/project.service';
|
||||
import { RuteroProyecto } from '../../core/models/project.model';
|
||||
import { AuthService } from '../../core/services/auth.service';
|
||||
import { UserProfileService } from '../../core/services/user-profile.service';
|
||||
|
||||
@Component({ standalone: true, selector: 'app-project-list', imports: [CommonModule, RouterLink], templateUrl: './project-list.component.html', styleUrl: './projects.component.css' })
|
||||
export class ProjectListComponent implements OnInit {
|
||||
projects: RuteroProyecto[] = [];
|
||||
loading = true;
|
||||
deletingId = '';
|
||||
error = '';
|
||||
constructor(private projectsService: ProjectService, private auth: AuthService, public profile: UserProfileService, private router: Router, private cdr: ChangeDetectorRef) {}
|
||||
ngOnInit(): void { void this.load(); }
|
||||
async load(): Promise<void> {
|
||||
this.loading = true;
|
||||
try { this.projects = await this.projectsService.list(); }
|
||||
catch (error: any) { this.error = error?.message ?? 'No se pudieron cargar los proyectos.'; }
|
||||
finally { this.loading = false; this.cdr.detectChanges(); }
|
||||
}
|
||||
open(project: RuteroProyecto): void { void this.router.navigate(['/proyectos', project.id]); }
|
||||
async remove(project: RuteroProyecto): Promise<void> {
|
||||
if (!confirm(`Eliminar permanentemente el proyecto "${project.nombre}" y todos sus PDVs y rutas?`)) return;
|
||||
this.deletingId = project.id;
|
||||
this.error = '';
|
||||
try {
|
||||
await this.projectsService.remove(project.id);
|
||||
this.projects = this.projects.filter(item => item.id !== project.id);
|
||||
} catch (error: any) {
|
||||
this.error = error?.message ?? 'No se pudo eliminar el proyecto.';
|
||||
} finally {
|
||||
this.deletingId = '';
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
}
|
||||
async signOut(): Promise<void> { await this.auth.signOut(); await this.router.navigate(['/login']); }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
.projects-topbar { display:flex; align-items:center; gap:12px; padding:9px 24px; border-bottom:3px solid var(--glm-verde); color:var(--glm-azul); font-weight:700; background:#fff; }.projects-topbar img { height:38px; }.projects-topbar a { margin-left:auto; color:var(--glm-azul); text-decoration:none; }.projects-page { max-width:1100px; margin:0 auto; padding:30px 24px; }.projects-page header { display:flex; justify-content:space-between; align-items:flex-start; gap:20px; border-bottom:3px solid var(--glm-verde); padding-bottom:14px; }.projects-page h1,.projects-page h2 { color:var(--glm-azul); margin:0; }.projects-page header p,.project-card p,small { color:var(--glm-acero); }.primary,.project-card button { display:inline-block; border:1px solid var(--glm-azul); border-radius:4px; padding:9px 12px; background:var(--glm-azul); color:#fff; font:inherit; font-weight:700; text-decoration:none; cursor:pointer; }.project-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(245px,1fr)); gap:16px; margin-top:22px; }.project-card,.project-form,.empty { border:1px solid var(--glm-gris-medio); border-top:3px solid var(--glm-azul); border-radius:4px; padding:18px; background:#fff; }.project-card { display:flex; flex-direction:column; gap:12px; }.project-card button { margin-top:auto; }.state { align-self:flex-start; color:var(--glm-verde); font-size:.75rem; font-weight:700; text-transform:uppercase; }.empty { grid-column:1/-1; text-align:center; padding:38px; }.narrow { max-width:720px; }.project-form { display:grid; gap:16px; margin-top:20px; }.project-form label { display:grid; gap:6px; color:var(--glm-azul); font-size:.8rem; font-weight:700; text-transform:uppercase; }.project-form input { padding:10px; border:1px solid var(--glm-gris-medio); border-radius:4px; font:inherit; }.file-label span { color:var(--glm-acero); font-size:.75rem; text-transform:none; }.error { color:#c9252d; }.valid { color:var(--glm-verde); font-weight:700; } @media(max-width:640px){.projects-page{padding:20px 16px}.projects-page header{display:grid}.projects-topbar{padding:9px 16px}}
|
||||
.project-form input,.project-form select { background:#fff; color:#2f3f48; border-color:#9aaab3; }.project-form select { padding:10px; border:1px solid #9aaab3; border-radius:4px; font:inherit; }.project-form input::placeholder { color:#71808a; opacity:1; }.project-form input:focus,.project-form select:focus { outline:2px solid rgba(108,194,74,.35); border-color:var(--glm-verde); background:#fff; color:#1f2d34; }.project-form input[type=file] { color:#2f3f48; background:#fff; cursor:pointer; }
|
||||
.topbar-actions { display:flex; align-items:center; gap:8px; margin-left:auto; }.topbar-actions button { border:1px solid var(--glm-gris-medio); border-radius:4px; background:#fff; color:var(--glm-azul); cursor:pointer; font:inherit; font-size:.82rem; font-weight:700; padding:8px 12px; }.topbar-actions button:hover { background:var(--glm-verde-bg); border-color:var(--glm-verde); }.manage-employees { display:inline-flex; align-items:center; gap:6px; margin-bottom:14px; border:1px solid var(--glm-gris-medio); border-radius:4px; padding:8px 12px; color:var(--glm-azul); font-weight:700; text-decoration:none; background:#fff; }.manage-employees:hover { background:var(--glm-verde-bg); border-color:var(--glm-verde); }
|
||||
.user-profile { display:flex; align-items:center; gap:8px; margin-left:auto; color:var(--glm-azul); font-size:.84rem; font-weight:700; }.user-profile img,.avatar-fallback { width:30px; height:30px; border-radius:50%; }.user-profile img { object-fit:cover; }.avatar-fallback { display:inline-flex; align-items:center; justify-content:center; background:var(--glm-verde); color:#fff; }
|
||||
.project-card-actions { display:flex; gap:8px; margin-top:auto; }.project-card-actions button { margin-top:0; }.project-card-actions .danger { border-color:#c9252d; background:#fff; color:#c9252d; }.project-card-actions .danger:hover:not(:disabled) { background:#c9252d; color:#fff; }.project-card-actions button:disabled { cursor:not-allowed; opacity:.65; }
|
||||
@@ -87,13 +87,17 @@
|
||||
box-shadow: 0 0 0 3px rgba(108, 194, 74, 0.15);
|
||||
}
|
||||
|
||||
button[type="submit"] {
|
||||
.google-login {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
margin-top: 8px;
|
||||
padding: 11px;
|
||||
background: var(--glm-azul);
|
||||
color: #fff;
|
||||
border: none;
|
||||
background: #fff;
|
||||
color: var(--glm-gris-oscuro);
|
||||
border: 1px solid var(--glm-gris-medio);
|
||||
border-radius: 4px;
|
||||
font-size: 15px;
|
||||
font-family: Arial, sans-serif;
|
||||
@@ -102,15 +106,25 @@ button[type="submit"] {
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
button[type="submit"]:hover:not(:disabled) {
|
||||
background: var(--glm-verde);
|
||||
.google-login:hover:not(:disabled) {
|
||||
border-color: var(--glm-azul);
|
||||
background: var(--glm-verde-bg);
|
||||
}
|
||||
|
||||
button[type="submit"]:disabled {
|
||||
.google-login:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.google-mark { color: #4285f4; font-size: 1.1rem; font-weight: 700; }
|
||||
.domain-note { margin: 10px 0 0; color: var(--glm-acero); font-size: .78rem; text-align: center; }
|
||||
|
||||
.login-error {
|
||||
margin: 12px 0 0;
|
||||
color: #c9252d;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.footer {
|
||||
text-align: center;
|
||||
margin-top: 24px;
|
||||
|
||||
@@ -11,36 +11,15 @@
|
||||
Planifica rutas inteligentes de forma eficiente
|
||||
</p>
|
||||
|
||||
<form (ngSubmit)="login()" #form="ngForm">
|
||||
|
||||
<div class="input-group">
|
||||
<label>Email</label>
|
||||
<input
|
||||
type="email"
|
||||
name="email"
|
||||
[(ngModel)]="email"
|
||||
required
|
||||
placeholder="usuario@empresa.com"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="input-group">
|
||||
<label>Contraseña</label>
|
||||
<input
|
||||
type="password"
|
||||
name="password"
|
||||
[(ngModel)]="password"
|
||||
required
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button type="submit" [disabled]="loading || form.invalid">
|
||||
<span *ngIf="!loading">Iniciar sesión</span>
|
||||
<span *ngIf="loading">Verificando ruta...</span>
|
||||
<div class="login-actions">
|
||||
<button type="button" class="google-login" (click)="loginWithGoogle()" [disabled]="loading">
|
||||
<span class="google-mark">G</span>
|
||||
<span *ngIf="!loading">Continuar con Google</span>
|
||||
<span *ngIf="loading">{{ loadingText }}</span>
|
||||
</button>
|
||||
|
||||
</form>
|
||||
<p class="domain-note">Solo cuentas @gomezleemarketing.com</p>
|
||||
<p class="login-error" *ngIf="error">{{ error }}</p>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
© 2026 Route Planner System
|
||||
|
||||
@@ -1,29 +1,57 @@
|
||||
import { Component, ChangeDetectionStrategy } from '@angular/core';
|
||||
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { AuthService } from '../../core/services/auth.service';
|
||||
import { UserProfileService } from '../../core/services/user-profile.service';
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
selector: 'app-login',
|
||||
imports: [CommonModule, FormsModule],
|
||||
imports: [CommonModule],
|
||||
templateUrl: './login.component.html',
|
||||
styleUrls: ['./login.component.css'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class LoginComponent {
|
||||
export class LoginComponent implements OnInit {
|
||||
|
||||
email = '';
|
||||
password = '';
|
||||
loading = false;
|
||||
error = '';
|
||||
loadingText = 'Redirigiendo a Google...';
|
||||
|
||||
constructor(private router: Router) {}
|
||||
login() {
|
||||
constructor(private router: Router, private auth: AuthService, private profile: UserProfileService, private cdr: ChangeDetectorRef) {}
|
||||
|
||||
async ngOnInit(): Promise<void> {
|
||||
const session = await this.auth.getSession();
|
||||
if (!session) return;
|
||||
this.loading = true;
|
||||
|
||||
setTimeout(() => {
|
||||
this.loadingText = 'Obteniendo datos del usuario...';
|
||||
try {
|
||||
await this.profile.load(session.user.email ?? '', String(session.user.user_metadata?.['avatar_url'] ?? ''));
|
||||
await this.router.navigate(['/home']);
|
||||
} catch (error: any) {
|
||||
await this.auth.signOut();
|
||||
this.error = error?.message ?? 'No se pudieron obtener los datos del usuario.';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
this.router.navigate(['/home']);
|
||||
}, 1500);
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
}
|
||||
|
||||
async loginWithGoogle() {
|
||||
this.error = '';
|
||||
this.loading = true;
|
||||
this.loadingText = 'Redirigiendo a Google...';
|
||||
try {
|
||||
const error = await this.auth.signInWithGoogle();
|
||||
if (error) {
|
||||
this.error = error;
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
this.error = 'No se pudo iniciar sesión. Intenta de nuevo.';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './pdv.schema';
|
||||
export * from './usuario.schema';
|
||||
@@ -0,0 +1,49 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const PDV_REQUIRED_HEADERS = [
|
||||
'ID',
|
||||
'Nombre del PDV',
|
||||
'Segmentación',
|
||||
'Latitud',
|
||||
'Longitud',
|
||||
'Visitas semanales',
|
||||
'Duración visita(horas)',
|
||||
'Prioridad',
|
||||
] as const;
|
||||
|
||||
export const PDV_NORMALIZED_REQUIRED = [
|
||||
'id',
|
||||
'nombre_del_pdv',
|
||||
'segmentacion',
|
||||
'latitud',
|
||||
'longitud',
|
||||
'prioridad',
|
||||
] as const;
|
||||
|
||||
export const SEGMENTACIONES = ['AA', 'A', 'B', 'C', 'D'] as const;
|
||||
|
||||
export const pdvRowSchema = z.object({
|
||||
id: z.union([z.string(), z.number()]).refine(v => String(v).trim() !== '', { message: 'ID requerido' }),
|
||||
nombre_del_pdv: z.string().min(1, 'Nombre del PDV requerido'),
|
||||
segmentacion: z.string().refine(v => (SEGMENTACIONES as readonly string[]).includes(v.toUpperCase()), {
|
||||
message: `Segmentación debe ser ${SEGMENTACIONES.join(', ')}`,
|
||||
}),
|
||||
latitud: z.number().min(-90, 'Latitud mínima -90').max(90, 'Latitud máxima 90'),
|
||||
longitud: z.number().min(-180, 'Longitud mínima -180').max(180, 'Longitud máxima 180'),
|
||||
visitas_semanales: z.number().int('Visitas semanales debe ser entero').min(1, 'Visitas semanales mínimo 1').max(7, 'Visitas semanales máximo 7').optional(),
|
||||
duracion_visitahoras: z.number().min(0.01, 'Duración visita debe ser >0').max(168, 'Duración visita máximo 168').optional(),
|
||||
minimo_horas_semana: z.number().min(0.01, 'Mínimo horas semana debe ser >0').max(168, 'Mínimo horas semana máximo 168').optional(),
|
||||
prioridad: z.number().int('Prioridad debe ser entero').min(1, 'Prioridad mínimo 1').max(5, 'Prioridad máximo 5'),
|
||||
}).superRefine((data, ctx) => {
|
||||
const hasVisitsFormat = data.visitas_semanales !== undefined && data.duracion_visitahoras !== undefined;
|
||||
if (!hasVisitsFormat && data.minimo_horas_semana === undefined) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['minimo_horas_semana'],
|
||||
message: 'Incluye Mínimo horas semana o Visitas semanales + Duración visita(horas)'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type PdvRow = z.infer<typeof pdvRowSchema>;
|
||||
export const PDV_MAX_ROWS = 2000;
|
||||
@@ -0,0 +1,39 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const USUARIO_REQUIRED_HEADERS = [
|
||||
'ID',
|
||||
'Nombre del empleado',
|
||||
'Latitud',
|
||||
'Longitud',
|
||||
'Horas por día usuario',
|
||||
'Horas por semana usuario',
|
||||
] as const;
|
||||
|
||||
export const USUARIO_NORMALIZED_REQUIRED = [
|
||||
'id',
|
||||
'nombre_del_empleado',
|
||||
'latitud',
|
||||
'longitud',
|
||||
'horas_por_dia_usuario',
|
||||
'horas_por_semana_usuario',
|
||||
] as const;
|
||||
|
||||
export const usuarioRowSchema = z.object({
|
||||
id: z.union([z.string(), z.number()]).refine(v => String(v).trim() !== '', { message: 'ID requerido' }),
|
||||
nombre_del_empleado: z.string().min(1, 'Nombre del empleado requerido'),
|
||||
latitud: z.number().min(-90, 'Latitud mínima -90').max(90, 'Latitud máxima 90'),
|
||||
longitud: z.number().min(-180, 'Longitud mínima -180').max(180, 'Longitud máxima 180'),
|
||||
horas_por_dia_usuario: z.number().min(0.5, 'Horas por día mínimo 0.5').max(24, 'Horas por día máximo 24'),
|
||||
horas_por_semana_usuario: z.number().min(1, 'Horas por semana mínimo 1').max(168, 'Horas por semana máximo 168'),
|
||||
}).superRefine((data, ctx) => {
|
||||
if (data.horas_por_semana_usuario > data.horas_por_dia_usuario * 7) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Horas por semana no puede exceder 7 × horas por día',
|
||||
path: ['horas_por_semana_usuario'],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type UsuarioRow = z.infer<typeof usuarioRowSchema>;
|
||||
export const USUARIO_MAX_ROWS = 300;
|
||||
@@ -0,0 +1,217 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { normalizeRow, normalizeHeader, cleanNum } from '../utils/header-normalization.utils';
|
||||
import { pdvRowSchema, PDV_NORMALIZED_REQUIRED, PDV_MAX_ROWS, SEGMENTACIONES } from '../schemas/pdv.schema';
|
||||
import { usuarioRowSchema, USUARIO_NORMALIZED_REQUIRED, USUARIO_MAX_ROWS } from '../schemas/usuario.schema';
|
||||
|
||||
export interface FieldError {
|
||||
row: number; // 1-indexed excel row (2 = first data row)
|
||||
field: string;
|
||||
message: string;
|
||||
value?: unknown;
|
||||
}
|
||||
|
||||
export interface PreviewResult {
|
||||
fileName: string;
|
||||
type: 'PDV' | 'Usuarios';
|
||||
valid: boolean;
|
||||
totalRows: number;
|
||||
validRows: number;
|
||||
headers: string[];
|
||||
normalizedHeaders: string[];
|
||||
missingHeaders: string[];
|
||||
errors: FieldError[];
|
||||
duplicateIds: (string | number)[];
|
||||
sampleValidRows: Record<string, unknown>[];
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ExcelPreviewService {
|
||||
|
||||
async previewFile(file: File, type: 'PDV' | 'Usuarios'): Promise<PreviewResult> {
|
||||
const buffer = await file.arrayBuffer();
|
||||
const workbook = XLSX.read(buffer, { type: 'array', cellDates: true });
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
if (!sheetName || !sheet) {
|
||||
throw new Error(`${type}: El archivo no contiene una hoja válida`);
|
||||
}
|
||||
const rawRows: Record<string, unknown>[] = XLSX.utils.sheet_to_json(sheet, { defval: null, raw: true });
|
||||
|
||||
const headers = this.extractHeaders(sheet);
|
||||
const normalizedHeaders = headers.map(h => normalizeHeader(String(h)));
|
||||
|
||||
const required = type === 'PDV' ? [...PDV_NORMALIZED_REQUIRED] : [...USUARIO_NORMALIZED_REQUIRED];
|
||||
const displayRequired = type === 'PDV'
|
||||
? ['ID', 'Nombre del PDV', 'Segmentación', 'Latitud', 'Longitud', 'Visitas semanales', 'Duración visita(horas)', 'Prioridad']
|
||||
: ['ID', 'Nombre del empleado', 'Latitud', 'Longitud', 'Horas por día usuario', 'Horas por semana usuario'];
|
||||
|
||||
const missingHeaders: string[] = [];
|
||||
for (let i = 0; i < required.length; i++) {
|
||||
if (!normalizedHeaders.includes(required[i])) {
|
||||
missingHeaders.push(displayRequired[i]);
|
||||
}
|
||||
}
|
||||
if (type === 'PDV') {
|
||||
const hasVisitsFormat = normalizedHeaders.includes('visitas_semanales') && normalizedHeaders.includes('duracion_visitahoras');
|
||||
const hasWeeklyHours = normalizedHeaders.includes('minimo_horas_semana');
|
||||
if (!hasVisitsFormat && !hasWeeklyHours) {
|
||||
missingHeaders.push('Mínimo horas semana o Visitas semanales + Duración visita(horas)');
|
||||
}
|
||||
}
|
||||
|
||||
const errors: FieldError[] = [];
|
||||
const repeatedHeaders = normalizedHeaders.filter((header, index) => header && normalizedHeaders.indexOf(header) !== index);
|
||||
if (repeatedHeaders.length) {
|
||||
errors.push({ row: 1, field: 'headers', message: `Columnas duplicadas: ${Array.from(new Set(repeatedHeaders)).join(', ')}` });
|
||||
}
|
||||
if (missingHeaders.length) {
|
||||
errors.push({ row: 1, field: 'headers', message: `Columnas faltantes: ${missingHeaders.join(', ')}` });
|
||||
}
|
||||
|
||||
if (rawRows.length === 0) {
|
||||
errors.push({ row: 1, field: 'file', message: `${type}: Archivo vacío o sin filas de datos` });
|
||||
return this.buildResult(file.name, type, headers, normalizedHeaders, missingHeaders, rawRows, errors, []);
|
||||
}
|
||||
|
||||
const maxRows = type === 'PDV' ? PDV_MAX_ROWS : USUARIO_MAX_ROWS;
|
||||
if (rawRows.length > maxRows) {
|
||||
errors.push({ row: 1, field: 'file', message: `${type}: Máximo ${maxRows} filas permitidas (tiene ${rawRows.length})` });
|
||||
}
|
||||
|
||||
const normalizedRows = rawRows.map(r => normalizeRow(r as Record<string, unknown>));
|
||||
const seenIds = new Map<string, number[]>();
|
||||
const rowErrors: FieldError[] = [];
|
||||
|
||||
normalizedRows.forEach((row, idx) => {
|
||||
const excelRow = idx + 2;
|
||||
const idVal = row['id'];
|
||||
if (idVal !== null && idVal !== undefined && String(idVal).trim() !== '') {
|
||||
const key = String(idVal).trim();
|
||||
if (!seenIds.has(key)) seenIds.set(key, []);
|
||||
seenIds.get(key)!.push(excelRow);
|
||||
}
|
||||
|
||||
// Coerce numeric fields with cleanNum before zod
|
||||
const coerced: Record<string, unknown> = { ...row };
|
||||
if (type === 'PDV') {
|
||||
coerced['latitud'] = this.coerceNum(row['latitud']);
|
||||
coerced['longitud'] = this.coerceNum(row['longitud']);
|
||||
coerced['visitas_semanales'] = this.coerceNum(row['visitas_semanales']);
|
||||
coerced['duracion_visitahoras'] = this.coerceNum(row['duracion_visitahoras']);
|
||||
coerced['minimo_horas_semana'] = this.coerceNum(row['minimo_horas_semana']);
|
||||
coerced['prioridad'] = this.coerceNum(row['prioridad']);
|
||||
if (typeof coerced['segmentacion'] === 'string') {
|
||||
coerced['segmentacion'] = String(coerced['segmentacion']).trim().toUpperCase();
|
||||
}
|
||||
// validate with zod
|
||||
const result = pdvRowSchema.safeParse(coerced);
|
||||
if (!result.success) {
|
||||
for (const issue of result.error.issues) {
|
||||
const field = String(issue.path[0] ?? 'unknown');
|
||||
rowErrors.push({ row: excelRow, field, message: issue.message, value: (row as Record<string, unknown>)[field] ?? coerced[field] });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
coerced['latitud'] = this.coerceNum(row['latitud']);
|
||||
coerced['longitud'] = this.coerceNum(row['longitud']);
|
||||
coerced['horas_por_dia_usuario'] = this.coerceNum(row['horas_por_dia_usuario']);
|
||||
coerced['horas_por_semana_usuario'] = this.coerceNum(row['horas_por_semana_usuario']);
|
||||
const result = usuarioRowSchema.safeParse(coerced);
|
||||
if (!result.success) {
|
||||
for (const issue of result.error.issues) {
|
||||
const field = String(issue.path[0] ?? 'unknown');
|
||||
rowErrors.push({ row: excelRow, field, message: issue.message, value: (row as Record<string, unknown>)[field] ?? coerced[field] });
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const duplicateIds: (string | number)[] = [];
|
||||
for (const [id, rows] of seenIds.entries()) {
|
||||
if (rows.length > 1) {
|
||||
duplicateIds.push(id);
|
||||
for (const r of rows) {
|
||||
rowErrors.push({ row: r, field: 'id', message: `ID duplicado: ${id}`, value: id });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const allErrors = [...errors, ...rowErrors];
|
||||
return this.buildResult(file.name, type, headers, normalizedHeaders, missingHeaders, normalizedRows, allErrors, duplicateIds);
|
||||
}
|
||||
|
||||
private coerceNum(value: unknown): unknown {
|
||||
if (value === null || value === undefined || value === '') return value;
|
||||
const n = cleanNum(value);
|
||||
return Number.isNaN(n) ? value : n;
|
||||
}
|
||||
|
||||
async preparePdvForOptimizer(file: File): Promise<File> {
|
||||
const buffer = await file.arrayBuffer();
|
||||
const workbook = XLSX.read(buffer, { type: 'array', cellDates: true });
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
const rows = XLSX.utils.sheet_to_json(sheet, { defval: null, raw: true })
|
||||
.map(row => normalizeRow(row as Record<string, unknown>));
|
||||
const normalized = rows.map(row => {
|
||||
const weeklyHours = cleanNum(row['minimo_horas_semana']);
|
||||
const visits = cleanNum(row['visitas_semanales']);
|
||||
const duration = cleanNum(row['duracion_visitahoras']);
|
||||
return {
|
||||
'ID': row['id'],
|
||||
'Nombre del PDV': row['nombre_del_pdv'],
|
||||
'Segmentación': row['segmentacion'],
|
||||
'Latitud': cleanNum(row['latitud']),
|
||||
'Longitud': cleanNum(row['longitud']),
|
||||
'Visitas semanales': Number.isFinite(visits) ? visits : 1,
|
||||
'Duración visita(horas)': Number.isFinite(duration) ? duration : weeklyHours,
|
||||
'Prioridad': cleanNum(row['prioridad'])
|
||||
};
|
||||
});
|
||||
const output = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(output, XLSX.utils.json_to_sheet(normalized), 'PDV');
|
||||
const data = XLSX.write(output, { bookType: 'xlsx', type: 'array' });
|
||||
return new File([data], file.name, { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||
}
|
||||
|
||||
private extractHeaders(sheet: XLSX.WorkSheet): string[] {
|
||||
const range = XLSX.utils.decode_range(sheet['!ref'] || 'A1');
|
||||
const headers: string[] = [];
|
||||
for (let c = range.s.c; c <= range.e.c; c++) {
|
||||
const addr = XLSX.utils.encode_cell({ r: range.s.r, c });
|
||||
const cell = sheet[addr];
|
||||
headers.push(cell ? String(cell.v) : '');
|
||||
}
|
||||
return headers.filter(h => h !== '');
|
||||
}
|
||||
|
||||
private buildResult(
|
||||
fileName: string,
|
||||
type: 'PDV' | 'Usuarios',
|
||||
headers: string[],
|
||||
normalizedHeaders: string[],
|
||||
missingHeaders: string[],
|
||||
rows: Record<string, unknown>[],
|
||||
errors: FieldError[],
|
||||
duplicateIds: (string | number)[]
|
||||
): PreviewResult {
|
||||
const validRows = Math.max(0, rows.length - new Set(errors.filter(e => e.field !== 'headers' && e.field !== 'file').map(e => e.row)).size);
|
||||
const hasHeaderErrors = missingHeaders.length > 0;
|
||||
const maxRows = type === 'PDV' ? PDV_MAX_ROWS : USUARIO_MAX_ROWS;
|
||||
const overLimit = rows.length > maxRows;
|
||||
const valid = !hasHeaderErrors && !overLimit && errors.length === 0;
|
||||
return {
|
||||
fileName,
|
||||
type,
|
||||
valid,
|
||||
totalRows: rows.length,
|
||||
validRows: valid ? rows.length : validRows,
|
||||
headers,
|
||||
normalizedHeaders,
|
||||
missingHeaders,
|
||||
errors,
|
||||
duplicateIds,
|
||||
sampleValidRows: rows.slice(0, 3),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { saveAs } from 'file-saver';
|
||||
import { RouteState } from '../../core/route-state/route';
|
||||
import { sequenceRoutes, summarizeDailyRoutes } from '../utils/route-sequencing.utils';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class PlanningExportService {
|
||||
constructor(private routeState: RouteState) {}
|
||||
|
||||
export(): void {
|
||||
const assigned = this.routeState.getAssignedSnapshot();
|
||||
const unassigned = this.routeState.getNoAssignedSnapshot();
|
||||
const users = new Map<string, { nombre: string; rutas: number; distancia: number; trabajo: number; capacidad: number }>();
|
||||
|
||||
for (const route of assigned) {
|
||||
const key = String(route.json.usuario_id);
|
||||
const current = users.get(key) ?? {
|
||||
nombre: route.json.nombre_usuario,
|
||||
rutas: 0,
|
||||
distancia: 0,
|
||||
trabajo: 0,
|
||||
capacidad: Number(route.json.hora_laboral_semanal_usuario) || 0
|
||||
};
|
||||
current.rutas++;
|
||||
current.distancia += Number(route.json.distancia) || 0;
|
||||
current.trabajo += Number.parseFloat(String(route.json.horas_trabajo ?? '')) || 0;
|
||||
users.set(key, current);
|
||||
}
|
||||
|
||||
const total = assigned.length + unassigned.length;
|
||||
const dailyRoutes = summarizeDailyRoutes(assigned);
|
||||
const totalDistance = dailyRoutes.reduce((sum, route) => sum + route.distanceKm, 0);
|
||||
const totalTravel = dailyRoutes.reduce((sum, route) => sum + route.travelHours, 0);
|
||||
const workbook = XLSX.utils.book_new();
|
||||
|
||||
const summary = [
|
||||
{ Indicador: 'PDVs totales', Valor: total },
|
||||
{ Indicador: 'PDVs asignados', Valor: assigned.length },
|
||||
{ Indicador: 'PDVs sin asignar', Valor: unassigned.length },
|
||||
{ Indicador: 'Cobertura (%)', Valor: total ? Number(((assigned.length / total) * 100).toFixed(1)) : 0 },
|
||||
{ Indicador: 'Usuarios activos', Valor: users.size },
|
||||
{ Indicador: 'Días planificados', Valor: new Set(assigned.map(route => route.json.dia)).size },
|
||||
{ Indicador: 'Distancia total (km)', Valor: Number(totalDistance.toFixed(2)) },
|
||||
{ Indicador: 'Desplazamiento total (h)', Valor: Number(totalTravel.toFixed(2)) }
|
||||
];
|
||||
|
||||
const assignedRows = sequenceRoutes(assigned).map(segment => ({
|
||||
'Usuario ID': segment.route.json.usuario_id,
|
||||
Usuario: segment.route.json.nombre_usuario,
|
||||
'PDV ID': segment.route.json.pdv_id,
|
||||
PDV: segment.route.json.nombre_pdv,
|
||||
Día: segment.route.json.dia,
|
||||
'Distancia (km)': segment.route.json.distancia,
|
||||
'Desplazamiento (h)': segment.route.json.horas_desplazamiento,
|
||||
'Horas trabajo': segment.route.json.horas_trabajo,
|
||||
'Horas disponibles': segment.route.json.hora_laboral_semanal_usuario,
|
||||
'Orden visita': segment.order,
|
||||
'Origen del tramo': segment.previousPdvName ?? `Casa de ${segment.route.json.nombre_usuario}`
|
||||
}));
|
||||
const unassignedRows = unassigned.map(route => ({
|
||||
'PDV ID': route.pdv_id,
|
||||
PDV: route.pdv_nombre,
|
||||
'Mínimo horas/semana': route.minimo_horas_semana,
|
||||
Latitud: route.latitud,
|
||||
Longitud: route.longitud,
|
||||
Motivo: route.motivo
|
||||
}));
|
||||
const userRows = Array.from(users, ([id, user]) => {
|
||||
const utilization = user.capacidad ? (user.trabajo / user.capacidad) * 100 : 0;
|
||||
return {
|
||||
'Usuario ID': id,
|
||||
Usuario: user.nombre,
|
||||
Rutas: user.rutas,
|
||||
'Distancia (km)': Number(user.distancia.toFixed(2)),
|
||||
'Horas trabajo': Number(user.trabajo.toFixed(2)),
|
||||
'Capacidad (h)': user.capacidad,
|
||||
'Utilización (%)': Number(utilization.toFixed(1)),
|
||||
Estado: utilization > 100 ? 'Excede capacidad' : utilization > 90 ? 'Riesgo' : 'OK'
|
||||
};
|
||||
});
|
||||
|
||||
this.appendSheet(workbook, summary, 'Resumen');
|
||||
this.appendSheet(workbook, assignedRows, 'Rutas asignadas');
|
||||
this.appendSheet(workbook, unassignedRows, 'PDVs sin asignar');
|
||||
this.appendSheet(workbook, userRows, 'Carga por usuario');
|
||||
this.appendSheet(workbook, dailyRoutes.map(route => ({
|
||||
Usuario: route.userName,
|
||||
Día: route.day,
|
||||
Paradas: route.routes.length,
|
||||
'Distancia secuencial (km)': Number(route.distanceKm.toFixed(2)),
|
||||
'Desplazamiento secuencial (h)': Number(route.travelHours.toFixed(2)),
|
||||
'Carga total (h)': Number(route.totalHours.toFixed(2)),
|
||||
'Capacidad diaria (h)': Number(route.capacityHours.toFixed(2)),
|
||||
Estado: route.exceedsCapacity ? 'Excede capacidad' : 'OK'
|
||||
})), 'Rutas diarias');
|
||||
|
||||
const output = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
|
||||
saveAs(new Blob([output], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 'planificacion_rutas.xlsx');
|
||||
}
|
||||
|
||||
private appendSheet(workbook: XLSX.WorkBook, rows: object[], name: string): void {
|
||||
const sheet = XLSX.utils.json_to_sheet(rows.length ? rows : [{ Información: 'Sin registros' }]);
|
||||
XLSX.utils.book_append_sheet(workbook, sheet, name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
export function normalizeHeader(value: string): string {
|
||||
return value
|
||||
.toLowerCase()
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[^a-z0-9 ]/gi, '')
|
||||
.trim()
|
||||
.replace(/\s+/g, '_');
|
||||
}
|
||||
|
||||
export function cleanNum(value: unknown): number {
|
||||
if (value === null || value === undefined || value === '') return NaN;
|
||||
if (typeof value === 'number') return value;
|
||||
const str = String(value).trim().replace(/[^0-9.\-]/g, '');
|
||||
if (str === '' || str === '-' || str === '.') return NaN;
|
||||
const num = Number(str);
|
||||
return Number.isFinite(num) ? num : NaN;
|
||||
}
|
||||
|
||||
export function normalizeRow(row: Record<string, unknown>): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const key in row) {
|
||||
const newKey = normalizeHeader(key);
|
||||
let val = row[key];
|
||||
if (typeof val === 'string') val = val.trim();
|
||||
out[newKey] = val;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -1 +1,4 @@
|
||||
export * from './remove-special-character.utils';
|
||||
export * from './remove-special-character.utils';
|
||||
export * from './header-normalization.utils';
|
||||
export * from './palette.utils';
|
||||
export * from './route-sequencing.utils';
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
export function colorForUsuario(usuarioId: string | number): { color: string; glow: string } {
|
||||
const str = String(usuarioId);
|
||||
let hash = 0;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0;
|
||||
}
|
||||
hash = Math.abs(hash);
|
||||
// Use a mix of GLM palette + generated HSL to avoid collisions but keep brand feel
|
||||
const glmPalette = ['#6CC24A', '#4F758B', '#FF6A13', '#C4D600', '#5B7F95', '#A4D65E', '#6B8FA3'];
|
||||
const idx = hash % glmPalette.length;
|
||||
// If palette length covers typical usuarios (50 max) collisions low; fallback to HSL for overflow
|
||||
if (hash % 2 === 0) {
|
||||
return { color: glmPalette[idx], glow: glmPalette[idx] };
|
||||
}
|
||||
const h = hash % 360;
|
||||
const s = 65 + (hash % 20);
|
||||
const l = 48 + (hash % 10);
|
||||
const hsl = `hsl(${h} ${s}% ${l}%)`;
|
||||
return { color: hsl, glow: hsl };
|
||||
}
|
||||
|
||||
export function markerStyleForUsuario(usuarioId: string | number): string {
|
||||
return colorForUsuario(usuarioId).color;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { RouteAssignedResponse } from '../../core/models/route.model';
|
||||
|
||||
export interface SequencedRoute {
|
||||
route: RouteAssignedResponse;
|
||||
origin: [number, number];
|
||||
destination: [number, number];
|
||||
order: number;
|
||||
totalStops: number;
|
||||
previousPdvName: string | null;
|
||||
}
|
||||
|
||||
export interface DailyRouteSummary {
|
||||
key: string;
|
||||
userId: string;
|
||||
userName: string;
|
||||
day: string;
|
||||
routes: SequencedRoute[];
|
||||
distanceKm: number;
|
||||
travelHours: number;
|
||||
workHours: number;
|
||||
capacityHours: number;
|
||||
totalHours: number;
|
||||
exceedsCapacity: boolean;
|
||||
}
|
||||
|
||||
export function sequenceRoutes(routes: RouteAssignedResponse[]): SequencedRoute[] {
|
||||
const groups = new Map<string, RouteAssignedResponse[]>();
|
||||
for (const route of routes) {
|
||||
const key = `${route.json.usuario_id}\u0000${route.json.dia}`;
|
||||
const group = groups.get(key) ?? [];
|
||||
group.push(route);
|
||||
groups.set(key, group);
|
||||
}
|
||||
|
||||
const sequenced: SequencedRoute[] = [];
|
||||
for (const group of groups.values()) {
|
||||
const first = group[0].json;
|
||||
let current: [number, number] = [Number(first.longitud_usuario), Number(first.latitud_usuario)];
|
||||
let previousPdvName: string | null = null;
|
||||
const hasManualOrder = group.every(route => Number.isFinite(route.json.visit_order));
|
||||
const remaining = hasManualOrder
|
||||
? [...group].sort((a, b) => Number(a.json.visit_order) - Number(b.json.visit_order))
|
||||
: [...group];
|
||||
|
||||
while (remaining.length) {
|
||||
let nearestIndex = 0;
|
||||
if (!hasManualOrder) {
|
||||
let nearestDistance = Number.POSITIVE_INFINITY;
|
||||
for (let index = 0; index < remaining.length; index++) {
|
||||
const candidate = remaining[index].json;
|
||||
const distance = haversineKm(current, [Number(candidate.longitud_pdv), Number(candidate.latitud_pdv)]);
|
||||
if (distance < nearestDistance) {
|
||||
nearestDistance = distance;
|
||||
nearestIndex = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const [route] = remaining.splice(nearestIndex, 1);
|
||||
const destination: [number, number] = [Number(route.json.longitud_pdv), Number(route.json.latitud_pdv)];
|
||||
sequenced.push({
|
||||
route,
|
||||
origin: current,
|
||||
destination,
|
||||
order: group.length - remaining.length,
|
||||
totalStops: group.length,
|
||||
previousPdvName
|
||||
});
|
||||
current = destination;
|
||||
previousPdvName = route.json.nombre_pdv;
|
||||
}
|
||||
}
|
||||
|
||||
return sequenced;
|
||||
}
|
||||
|
||||
export function summarizeDailyRoutes(routes: RouteAssignedResponse[]): DailyRouteSummary[] {
|
||||
const sequences = sequenceRoutes(routes);
|
||||
const grouped = new Map<string, SequencedRoute[]>();
|
||||
for (const segment of sequences) {
|
||||
const key = `${segment.route.json.usuario_id}\u0000${segment.route.json.dia}`;
|
||||
const group = grouped.get(key) ?? [];
|
||||
group.push(segment);
|
||||
grouped.set(key, group);
|
||||
}
|
||||
return Array.from(grouped, ([key, segments]) => {
|
||||
const first = segments[0].route.json;
|
||||
const distanceKm = segments.reduce((sum, segment) => sum + haversineKm(segment.origin, segment.destination), 0);
|
||||
const travelHours = segments.reduce((sum, segment) => sum + Number(segment.route.json.horas_desplazamiento || 0), 0);
|
||||
const workHours = segments.reduce((sum, segment) => sum + Number(segment.route.json.horas_trabajo || segment.route.json.hora_minima_semanal_pdv || 0), 0);
|
||||
const capacityHours = Number(first.hora_laboral_semanal_usuario || 0) / 5;
|
||||
const totalHours = workHours + travelHours;
|
||||
return {
|
||||
key,
|
||||
userId: String(first.usuario_id),
|
||||
userName: first.nombre_usuario,
|
||||
day: first.dia,
|
||||
routes: segments,
|
||||
distanceKm,
|
||||
travelHours,
|
||||
workHours,
|
||||
capacityHours,
|
||||
totalHours,
|
||||
exceedsCapacity: totalHours > capacityHours
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function haversineKm(origin: [number, number], destination: [number, number]): number {
|
||||
const toRadians = (value: number) => value * Math.PI / 180;
|
||||
const [lon1, lat1] = origin;
|
||||
const [lon2, lat2] = destination;
|
||||
const dLat = toRadians(lat2 - lat1);
|
||||
const dLon = toRadians(lon2 - lon1);
|
||||
const a = Math.sin(dLat / 2) ** 2 +
|
||||
Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) * Math.sin(dLon / 2) ** 2;
|
||||
return 6371 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export const environment = {
|
||||
production: true,
|
||||
n8nWebhookUrl: 'http://localhost:5678/webhook/calcular-camino',
|
||||
orsBaseUrl: 'http://localhost:18080/ors/v2',
|
||||
orsMexicoBaseUrl: 'http://localhost:18081/ors/v2',
|
||||
requestTimeoutMs: 180000,
|
||||
supabaseUrl: 'https://dbit.digitalcompass.agency',
|
||||
userProfileWebhookUrl: 'https://agenteit.digitalcompass.agency/webhook/19486044-4dbd-4751-87ae-f6664148bb8a',
|
||||
supabaseAnonKey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE',
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
export const environment = {
|
||||
production: false,
|
||||
n8nWebhookUrl: 'http://localhost:5678/webhook/calcular-camino',
|
||||
orsBaseUrl: 'http://localhost:18080/ors/v2',
|
||||
orsMexicoBaseUrl: 'http://localhost:18081/ors/v2',
|
||||
requestTimeoutMs: 180000,
|
||||
supabaseUrl: 'https://dbit.digitalcompass.agency',
|
||||
userProfileWebhookUrl: 'https://agenteit.digitalcompass.agency/webhook/19486044-4dbd-4751-87ae-f6664148bb8a',
|
||||
supabaseAnonKey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE',
|
||||
};
|
||||
@@ -6,7 +6,6 @@
|
||||
<base href="/">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🗺️</text></svg>">
|
||||
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
|
||||
@@ -1,5 +1,51 @@
|
||||
@import "primeicons/primeicons.css";
|
||||
|
||||
/* Leaflet creates marker HTML outside Angular's style encapsulation. */
|
||||
.location-pin {
|
||||
position: relative;
|
||||
width: 30px;
|
||||
height: 38px;
|
||||
background: #c9252d;
|
||||
clip-path: polygon(50% 100%, 8% 43%, 5% 31%, 10% 18%, 22% 7%, 36% 2%, 50% 0, 64% 2%, 78% 7%, 90% 18%, 95% 31%, 92% 43%);
|
||||
filter: drop-shadow(0 2px 2px rgba(0, 0, 0, 0.42));
|
||||
}
|
||||
|
||||
.location-pin::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 3px 3px 7px;
|
||||
background: #ff424a;
|
||||
clip-path: polygon(50% 100%, 8% 43%, 5% 31%, 10% 18%, 22% 7%, 36% 2%, 50% 0, 64% 2%, 78% 7%, 90% 18%, 95% 31%, 92% 43%);
|
||||
}
|
||||
|
||||
.location-pin::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
background: #620000;
|
||||
}
|
||||
|
||||
.location-pin span {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
width: 14px;
|
||||
color: #fff;
|
||||
font: 700 9px/14px Arial, sans-serif;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* leaflet.heat creates its canvas in the map overlay pane, outside Angular styles. */
|
||||
.leaflet-heatmap-layer {
|
||||
z-index: 700 !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
:root {
|
||||
--glm-verde: #6CC24A;
|
||||
--glm-verde-claro: #A4D65E;
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
alter table public.rutero_empleados
|
||||
add column if not exists jornada_codigo text not null default 'LUN_VIE_40',
|
||||
add column if not exists horas_descanso_por_dia numeric(4,2) not null default 1,
|
||||
add column if not exists dias_descanso jsonb not null default '[]'::jsonb;
|
||||
|
||||
alter table public.rutero_empleados
|
||||
add constraint rutero_empleados_jornada_valida
|
||||
check (jornada_codigo in ('LUN_DOM_44', 'LUN_SAB_40', 'LUN_SAB_44', 'LUN_VIE_40')) not valid;
|
||||
|
||||
alter table public.rutero_empleados
|
||||
add constraint rutero_empleados_descanso_valido
|
||||
check (horas_descanso_por_dia >= 0 and horas_descanso_por_dia < 24) not valid;
|
||||
|
||||
alter table public.rutero_empleados enable row level security;
|
||||
|
||||
drop policy if exists "Solo GomezLee puede consultar empleados" on public.rutero_empleados;
|
||||
drop policy if exists "Solo GomezLee puede crear empleados" on public.rutero_empleados;
|
||||
drop policy if exists "Solo GomezLee puede editar empleados" on public.rutero_empleados;
|
||||
drop policy if exists "Solo GomezLee puede eliminar empleados" on public.rutero_empleados;
|
||||
|
||||
create policy "Solo GomezLee puede consultar empleados"
|
||||
on public.rutero_empleados for select to authenticated
|
||||
using (lower(coalesce(auth.jwt() ->> 'email', '')) like '%@gomezleemarketing.com');
|
||||
|
||||
create policy "Solo GomezLee puede crear empleados"
|
||||
on public.rutero_empleados for insert to authenticated
|
||||
with check (lower(coalesce(auth.jwt() ->> 'email', '')) like '%@gomezleemarketing.com');
|
||||
|
||||
create policy "Solo GomezLee puede editar empleados"
|
||||
on public.rutero_empleados for update to authenticated
|
||||
using (lower(coalesce(auth.jwt() ->> 'email', '')) like '%@gomezleemarketing.com')
|
||||
with check (lower(coalesce(auth.jwt() ->> 'email', '')) like '%@gomezleemarketing.com');
|
||||
|
||||
create policy "Solo GomezLee puede eliminar empleados"
|
||||
on public.rutero_empleados for delete to authenticated
|
||||
using (lower(coalesce(auth.jwt() ->> 'email', '')) like '%@gomezleemarketing.com');
|
||||
Reference in New Issue
Block a user