kwikid-agent-dashboard 0.0.49 → 0.0.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1549,11 +1549,18 @@ class OpenStreetMapsService {
1549
1549
  this.mapDirectionsService = mapDirectionsService;
1550
1550
  this.httpClient = httpClient;
1551
1551
  this.allMarkers = [];
1552
+ // Geocoded locations by address, so re-plotting does not query Nominatim again
1553
+ this.locationCache = new Map();
1554
+ this.lastGeocodeAt = 0;
1555
+ // Every Nominatim request goes through this chain, so they never overlap
1556
+ this.geocodeQueue = Promise.resolve();
1557
+ // Only the latest plot may draw; an older one still geocoding is dropped
1558
+ this.plotRunId = 0;
1552
1559
  }
1553
1560
  // To get Current Position
1554
1561
  getPosition() {
1555
1562
  return new Promise((resolve, reject) => {
1556
- navigator.geolocation.watchPosition((resp) => {
1563
+ navigator.geolocation.getCurrentPosition((resp) => {
1557
1564
  resolve({
1558
1565
  lng: resp.coords.longitude,
1559
1566
  lat: resp.coords.latitude
@@ -1567,39 +1574,31 @@ class OpenStreetMapsService {
1567
1574
  getLocation(task) {
1568
1575
  return __awaiter(this, void 0, void 0, function* () {
1569
1576
  return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
1570
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
1571
- let encodedAddres;
1577
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
1578
+ let address;
1572
1579
  // If Fetch Address from Multiple Paths
1573
1580
  if (checkObjectPathExists(this.agentService.config, "extendedFlags.taskLocationPaths")) {
1574
1581
  // Get address string from multiple paths
1575
1582
  const config = this.agentService.config.extendedFlags.taskLocationPaths;
1576
- const address = addressConcator(task, config);
1577
- // Encode the Address in URI
1578
- encodedAddres = encodeURI(address);
1583
+ address = addressConcator(task, config);
1579
1584
  }
1580
1585
  // If Fetch Address from Single Path
1581
1586
  else if (checkObjectPathExists(this.agentService.config, "extendedFlags.taskLocationPath")) {
1582
1587
  // Get Address from Single Path
1583
1588
  const config = this.agentService.config.extendedFlags.taskLocationPath;
1584
- const address = getObjectValueFromPath(task, config);
1585
- // Encode the Address in URI
1586
- encodedAddres = encodeURI(address);
1589
+ address = getObjectValueFromPath(task, config);
1587
1590
  }
1588
1591
  // Default Address Paths Avaiable
1589
1592
  else {
1590
- const address = (_k = (_j = (_g = (_d = (_c = (_b = (_a = task === null || task === void 0 ? void 0 : task.extras) === null || _a === void 0 ? void 0 : _a.task_details) === null || _b === void 0 ? void 0 : _b.customer_details) === null || _c === void 0 ? void 0 : _c.address) !== null && _d !== void 0 ? _d : (_f = (_e = task === null || task === void 0 ? void 0 : task.task_details) === null || _e === void 0 ? void 0 : _e.customer_details) === null || _f === void 0 ? void 0 : _f.address) !== null && _g !== void 0 ? _g : (_h = task === null || task === void 0 ? void 0 : task.extras) === null || _h === void 0 ? void 0 : _h.address) !== null && _j !== void 0 ? _j : task === null || task === void 0 ? void 0 : task.address) !== null && _k !== void 0 ? _k : "";
1591
- // Encode the Address in URI
1592
- encodedAddres = encodeURI(address);
1593
+ address =
1594
+ (_k = (_j = (_g = (_d = (_c = (_b = (_a = task === null || task === void 0 ? void 0 : task.extras) === null || _a === void 0 ? void 0 : _a.task_details) === null || _b === void 0 ? void 0 : _b.customer_details) === null || _c === void 0 ? void 0 : _c.address) !== null && _d !== void 0 ? _d : (_f = (_e = task === null || task === void 0 ? void 0 : task.task_details) === null || _e === void 0 ? void 0 : _e.customer_details) === null || _f === void 0 ? void 0 : _f.address) !== null && _g !== void 0 ? _g : (_h = task === null || task === void 0 ? void 0 : task.extras) === null || _h === void 0 ? void 0 : _h.address) !== null && _j !== void 0 ? _j : task === null || task === void 0 ? void 0 : task.address) !== null && _k !== void 0 ? _k : "";
1593
1595
  }
1594
- // URL to geocode Address String to Latitude & Longitude
1595
- const url = `https://nominatim.openstreetmap.org/search?q=${encodedAddres}&format=json`;
1596
- const response = yield fetch(url);
1597
- const data = yield response.json();
1598
- // Set Location {lat: LAT, lng: LNG} from address geocoded
1599
- const isValidLocation = isNotEmptyArray(data) && ((_l = data[0]) === null || _l === void 0 ? void 0 : _l.lat) & ((_m = data[0]) === null || _m === void 0 ? void 0 : _m.lon);
1600
- const location = isValidLocation
1601
- ? { lat: (_o = data[0]) === null || _o === void 0 ? void 0 : _o.lat, lng: (_p = data[0]) === null || _p === void 0 ? void 0 : _p.lon }
1602
- : { lat: null, lng: null };
1596
+ address = String(address !== null && address !== void 0 ? address : "")
1597
+ .replace(/\b(undefined|null)\b/g, " ")
1598
+ .replace(/\s+/g, " ")
1599
+ .trim();
1600
+ const location = Object.assign({}, (yield this.geocodeAddress(address)));
1601
+ const isValidLocation = location.lat !== null && location.lng !== null;
1603
1602
  // Set Location validation & Google Maps URL
1604
1603
  location.isValidLocation = isValidLocation;
1605
1604
  location.color = isValidLocation ? "blue" : "red";
@@ -1608,20 +1607,70 @@ class OpenStreetMapsService {
1608
1607
  }));
1609
1608
  });
1610
1609
  }
1611
- // Get Tasks | Markers Location Co Ordinates
1610
+ // Geocode an address with Nominatim: one request at a time, results cached
1611
+ geocodeAddress(address) {
1612
+ if (!address) {
1613
+ return Promise.resolve({ lat: null, lng: null });
1614
+ }
1615
+ if (!this.locationCache.has(address)) {
1616
+ const request = this.geocodeQueue.then(() => this.fetchLocation(address));
1617
+ this.geocodeQueue = request.catch(() => undefined);
1618
+ this.locationCache.set(address, request);
1619
+ request.then((result) => {
1620
+ // Do not keep failures (rate limit, outage); retry on the next plot
1621
+ if (result.failed) {
1622
+ this.locationCache.delete(address);
1623
+ }
1624
+ });
1625
+ }
1626
+ return this.locationCache
1627
+ .get(address)
1628
+ .then(({ lat, lng }) => ({ lat, lng }));
1629
+ }
1630
+ fetchLocation(address) {
1631
+ var _a, _b;
1632
+ return __awaiter(this, void 0, void 0, function* () {
1633
+ const wait = this.lastGeocodeAt +
1634
+ OpenStreetMapsService.GEOCODE_INTERVAL_MS -
1635
+ Date.now();
1636
+ if (wait > 0) {
1637
+ yield new Promise((resolve) => setTimeout(resolve, wait));
1638
+ }
1639
+ this.lastGeocodeAt = Date.now();
1640
+ try {
1641
+ const url = `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(address)}&format=json&limit=1`;
1642
+ const controller = new AbortController();
1643
+ const timer = setTimeout(() => controller.abort(), OpenStreetMapsService.GEOCODE_TIMEOUT_MS);
1644
+ let data;
1645
+ try {
1646
+ const response = yield fetch(url, { signal: controller.signal });
1647
+ if (!response.ok) {
1648
+ return { lat: null, lng: null, failed: true };
1649
+ }
1650
+ data = yield response.json();
1651
+ }
1652
+ finally {
1653
+ clearTimeout(timer);
1654
+ }
1655
+ const lat = isNotEmptyArray(data) ? parseFloat((_a = data[0]) === null || _a === void 0 ? void 0 : _a.lat) : NaN;
1656
+ const lng = isNotEmptyArray(data) ? parseFloat((_b = data[0]) === null || _b === void 0 ? void 0 : _b.lon) : NaN;
1657
+ return Number.isFinite(lat) && Number.isFinite(lng)
1658
+ ? { lat, lng }
1659
+ : { lat: null, lng: null };
1660
+ }
1661
+ catch (error) {
1662
+ return { lat: null, lng: null, failed: true };
1663
+ }
1664
+ });
1665
+ }
1666
+ // Get Tasks | Markers Location Co Ordinates, in task order
1612
1667
  getMarkersLocation(myMarker, tasks) {
1613
1668
  return __awaiter(this, void 0, void 0, function* () {
1614
- return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
1615
- const markers = [];
1616
- markers.push(myMarker);
1617
- const promises = tasks.map((task) => __awaiter(this, void 0, void 0, function* () {
1618
- const marker = yield this.getLocation(task);
1619
- task = Object.assign(Object.assign({}, task), marker);
1620
- markers.push(task);
1621
- }));
1622
- yield Promise.all(promises);
1623
- resolve(markers);
1624
- }));
1669
+ // Lookups are serialised by geocodeAddress, so this stays within Nominatim's limit
1670
+ const located = yield Promise.all(tasks.map((task) => __awaiter(this, void 0, void 0, function* () {
1671
+ return (Object.assign(Object.assign({}, task), (yield this.getLocation(task))));
1672
+ })));
1673
+ return [myMarker, ...located];
1625
1674
  });
1626
1675
  }
1627
1676
  // To Initialize Open Street Map
@@ -1638,6 +1687,9 @@ class OpenStreetMapsService {
1638
1687
  }
1639
1688
  // To Add Open Street Marker in Map
1640
1689
  addMarker({ lat, lng, title, color }) {
1690
+ if (!this.markersLayer) {
1691
+ this.markersLayer = L.layerGroup().addTo(this.map);
1692
+ }
1641
1693
  L.marker([lat, lng], {
1642
1694
  icon: L.icon({
1643
1695
  iconUrl: color == "red"
@@ -1645,55 +1697,96 @@ class OpenStreetMapsService {
1645
1697
  : "https://kwikid.s3.ap-south-1.amazonaws.com/CONFIG/USER/assets/map-marker-1.png"
1646
1698
  })
1647
1699
  })
1648
- .addTo(this.map)
1649
- .bindPopup(title);
1700
+ .addTo(this.markersLayer)
1701
+ .bindPopup(String(title));
1702
+ }
1703
+ // Remove markers and routes from a previous plot
1704
+ clearMap() {
1705
+ if (this.markersLayer) {
1706
+ this.markersLayer.clearLayers();
1707
+ }
1708
+ if (this.allTasksRoutes) {
1709
+ this.map.removeControl(this.allTasksRoutes);
1710
+ this.allTasksRoutes = undefined;
1711
+ }
1712
+ if (this.selectedTaskRoutes) {
1713
+ this.map.removeControl(this.selectedTaskRoutes);
1714
+ this.selectedTaskRoutes = undefined;
1715
+ }
1650
1716
  }
1651
1717
  // To Plot Open Street Directions for All Tasks
1652
1718
  plotDirectionsForAllTasks(tasks) {
1719
+ if (!this.map || !this.myPosition) {
1720
+ return Promise.resolve(tasks);
1721
+ }
1722
+ this.plotRunId += 1;
1723
+ const plot = this.plotTasks(tasks, this.plotRunId);
1724
+ this.latestPlot = plot;
1725
+ return plot;
1726
+ }
1727
+ plotTasks(tasks, runId) {
1728
+ var _a;
1653
1729
  return __awaiter(this, void 0, void 0, function* () {
1654
- if (this.map) {
1655
- this.allMarkers = [];
1656
- // Create Agent Marker & Plot It.
1657
- const myMarker = {
1658
- lat: this.myPosition.lat,
1659
- lng: this.myPosition.lng,
1660
- title: 0,
1661
- color: "red"
1662
- };
1663
- this.addMarker(myMarker);
1664
- this.allMarkers.push(myMarker);
1665
- // Create Markers for all Tasks
1666
- this.allMarkers = yield this.getMarkersLocation(myMarker, tasks);
1667
- // Run Algorithm to get optimized Routes
1668
- const startingPoint = this.allMarkers[0];
1669
- const unvisitedWaypoints = this.allMarkers.slice(1);
1670
- const optimizedRoute = nearestNeighborAlgorithm(startingPoint, unvisitedWaypoints);
1671
- // Sort All Markers as per optimized routes
1672
- this.allMarkers = this.sortTasksAsPerDistance(optimizedRoute, this.allMarkers, true);
1673
- // Sort All Tasks as per optimized routes
1674
- tasks = this.sortTasksAsPerDistance(optimizedRoute.slice(1), tasks, false);
1675
- // Plot Markers for All Tasks
1676
- tasks.map((task) => {
1677
- if (task === null || task === void 0 ? void 0 : task.isValidLocation) {
1678
- const marker = this.getLocation(task);
1679
- this.addMarker(marker);
1680
- }
1681
- });
1682
- // Set Styles for all Task Routes
1730
+ // Create Agent Marker & Plot It.
1731
+ const myMarker = {
1732
+ lat: this.myPosition.lat,
1733
+ lng: this.myPosition.lng,
1734
+ title: "0",
1735
+ color: "red"
1736
+ };
1737
+ // Locate every task; tasks without a location stay in the list but are not routed
1738
+ const markers = yield this.getMarkersLocation(myMarker, tasks);
1739
+ if (runId !== this.plotRunId) {
1740
+ // A newer plot owns the map; give callers its result instead of stale tasks
1741
+ return this.latestPlot;
1742
+ }
1743
+ this.clearMap();
1744
+ this.addMarker(myMarker);
1745
+ const located = markers.slice(1).filter((marker) => marker.isValidLocation);
1746
+ const notLocated = markers
1747
+ .slice(1)
1748
+ .filter((marker) => !marker.isValidLocation);
1749
+ // Nearest-next visiting order starting from the agent
1750
+ const optimizedRoute = nearestNeighborAlgorithm(myMarker, located);
1751
+ optimizedRoute.slice(1).forEach((marker, index) => {
1752
+ marker.title = String(index + 1);
1753
+ });
1754
+ this.allMarkers = optimizedRoute;
1755
+ // Plot Markers for located Tasks
1756
+ located.forEach((marker) => this.addMarker(marker));
1757
+ // Set Routes for all located Tasks
1758
+ if (located.length > 0) {
1683
1759
  const styles = [
1684
1760
  { color: "blue", opacity: 1, weight: 8 },
1685
1761
  { color: "white", opacity: 0.6, weight: 12 }
1686
1762
  ];
1687
- // Set Routes for all Tasks
1688
- this.allTasksRoutes = this.setRoutes(this.allMarkers, styles);
1689
- this.fitMapBounds();
1763
+ this.allTasksRoutes = this.setRoutes(optimizedRoute, styles);
1690
1764
  }
1691
- return tasks;
1765
+ this.fitMapBounds();
1766
+ // Tasks in visiting order, carrying their location for the selected-task route
1767
+ const ordered = [...optimizedRoute.slice(1), ...notLocated];
1768
+ // clearMap dropped the selected route; redraw it if that task is still listed
1769
+ const selectedId = (_a = this.agentService.currentTaskDetails) === null || _a === void 0 ? void 0 : _a.session_id;
1770
+ const selected = selectedId
1771
+ ? ordered.find((task) => task.session_id === selectedId)
1772
+ : undefined;
1773
+ if (selected === null || selected === void 0 ? void 0 : selected.isValidLocation) {
1774
+ this.agentService.currentTaskDetails = selected;
1775
+ this.plotDirectionsForSelectedTask(selected);
1776
+ }
1777
+ else {
1778
+ // Leave currentTaskDetails alone: it also drives the details panel
1779
+ this.selectedTaskDistanceAndTime = undefined;
1780
+ }
1781
+ return ordered;
1692
1782
  });
1693
1783
  }
1694
1784
  // To plot Open Street Direction for selected Task
1695
1785
  plotDirectionsForSelectedTask(task) {
1696
- if (task !== null) {
1786
+ if (!this.map) {
1787
+ return;
1788
+ }
1789
+ if (task) {
1697
1790
  // Remove Previously Selected Task Route
1698
1791
  if (this.selectedTaskRoutes) {
1699
1792
  this.map.removeControl(this.selectedTaskRoutes);
@@ -1704,7 +1797,7 @@ class OpenStreetMapsService {
1704
1797
  }
1705
1798
  const taskMarker = task;
1706
1799
  // If Location is Available in Task Details
1707
- if (taskMarker.color != "red") {
1800
+ if (taskMarker === null || taskMarker === void 0 ? void 0 : taskMarker.isValidLocation) {
1708
1801
  const markers = [this.allMarkers[0], taskMarker];
1709
1802
  const styles = [
1710
1803
  { color: "green", opacity: 1, weight: 8 },
@@ -1722,7 +1815,9 @@ class OpenStreetMapsService {
1722
1815
  if (this.selectedTaskRoutes) {
1723
1816
  this.map.removeControl(this.selectedTaskRoutes);
1724
1817
  }
1725
- this.map.addControl(this.allTasksRoutes);
1818
+ if (this.allTasksRoutes) {
1819
+ this.map.addControl(this.allTasksRoutes);
1820
+ }
1726
1821
  this.selectedTaskRoutes = undefined;
1727
1822
  }
1728
1823
  this.fitMapBounds();
@@ -1733,46 +1828,57 @@ class OpenStreetMapsService {
1733
1828
  }
1734
1829
  // Set Distance & Time of Selected Task
1735
1830
  setSelectedTaskDistanceAndTime() {
1736
- this.selectedTaskRoutes.on("routesfound", function (e) {
1831
+ this.selectedTaskDistanceAndTime = undefined;
1832
+ this.selectedTaskRoutes.on("routesfound", (e) => {
1737
1833
  const { routes } = e;
1738
1834
  const { summary } = routes[0];
1739
- const distance = summary.totalDistance / 1000;
1740
- const time = Math.round((summary.totalTime % 3600) / 60);
1835
+ const METRES_PER_KM = 1000;
1836
+ const SECONDS_PER_MINUTE = 60;
1837
+ const distance = Math.round((summary.totalDistance / METRES_PER_KM) * 10) / 10; // eslint-disable-line no-magic-numbers
1838
+ const time = Math.round(summary.totalTime / SECONDS_PER_MINUTE);
1741
1839
  this.selectedTaskDistanceAndTime = {
1742
1840
  distance,
1743
1841
  time
1744
1842
  };
1745
1843
  });
1746
1844
  }
1747
- // To sort Open Street Maps Task as per nearest distance
1748
- sortTasksAsPerDistance(order, tasks, isMarker) {
1749
- const sortedTasks = [];
1750
- for (let i = 0; i < tasks.length; i++) {
1751
- const title = isMarker ? order[i].title : order[i].title - 1;
1752
- const task = tasks[title];
1753
- sortedTasks.push(task);
1754
- }
1755
- return sortedTasks;
1756
- }
1757
1845
  // To set Open Street routes in the maps
1758
1846
  setRoutes(markers, styles) {
1759
1847
  return L.Routing.control({
1760
- waypoints: markers,
1848
+ waypoints: markers.map((marker) => L.latLng(marker.lat, marker.lng)),
1761
1849
  lineOptions: {
1762
1850
  styles
1763
1851
  },
1764
1852
  createMarker() {
1765
1853
  return null;
1766
1854
  },
1767
- routeWhileDragging: true
1855
+ addWaypoints: false,
1856
+ fitSelectedRoutes: false,
1857
+ show: false
1768
1858
  }).addTo(this.map);
1769
1859
  }
1770
1860
  // To set Open Street view point on the map
1771
1861
  fitMapBounds() {
1772
- const markerLatLngs = this.allMarkers.map((marker) => L.latLng(marker.lat, marker.lng));
1773
- this.map.fitBounds(markerLatLngs);
1862
+ var _a;
1863
+ const markerLatLngs = ((_a = this.allMarkers) !== null && _a !== void 0 ? _a : [])
1864
+ .filter((marker) => marker && marker.lat !== null && marker.lng !== null)
1865
+ .map((marker) => L.latLng(marker.lat, marker.lng));
1866
+ const PADDING_PX = 40;
1867
+ const SINGLE_MARKER_ZOOM = 13;
1868
+ if (markerLatLngs.length > 1) {
1869
+ this.map.fitBounds(L.latLngBounds(markerLatLngs), {
1870
+ padding: [PADDING_PX, PADDING_PX]
1871
+ });
1872
+ }
1873
+ else if (markerLatLngs.length === 1) {
1874
+ this.map.setView(markerLatLngs[0], SINGLE_MARKER_ZOOM);
1875
+ }
1774
1876
  }
1775
1877
  }
1878
+ // Nominatim allows at most 1 request per second
1879
+ OpenStreetMapsService.GEOCODE_INTERVAL_MS = 1100; // eslint-disable-line no-magic-numbers
1880
+ // A stalled request must not hold up the queue
1881
+ OpenStreetMapsService.GEOCODE_TIMEOUT_MS = 10000; // eslint-disable-line no-magic-numbers
1776
1882
  /** @nocollapse */ OpenStreetMapsService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: OpenStreetMapsService, deps: [{ token: AgentService }, { token: i2$2.MapDirectionsService }, { token: i3$2.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
1777
1883
  /** @nocollapse */ OpenStreetMapsService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: OpenStreetMapsService, providedIn: "root" });
1778
1884
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: OpenStreetMapsService, decorators: [{