diff --git a/.github/ISSUE_TEMPLATE/---bug-report.md b/.github/ISSUE_TEMPLATE/---bug-report.md index 0fcae906b7..710834c877 100644 --- a/.github/ISSUE_TEMPLATE/---bug-report.md +++ b/.github/ISSUE_TEMPLATE/---bug-report.md @@ -3,7 +3,7 @@ name: "\U0001F41E Bug report" about: Create a report to help us improve title: "Your title here" labels: ['bug', 'unconfirmed'] -assignees: Ultrazombie +assignees: mykhailokornieiev --- diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 9430e961d5..5c147395a7 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -3,7 +3,7 @@ name: Feature request about: Suggest an idea for this project title: "Your title here" labels: ['feature'] -assignees: 'Ultrazombie' +assignees: 'mykhailokornieiev' --- diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md index 7f4becfe82..657614c987 100644 --- a/.github/ISSUE_TEMPLATE/question.md +++ b/.github/ISSUE_TEMPLATE/question.md @@ -3,7 +3,7 @@ name: Question about: Describe your questions in detail title: "Your title here" labels: ['question'] -assignees: 'Ultrazombie' +assignees: 'mykhailokornieiev' --- diff --git a/application/pom.xml b/application/pom.xml index f76b721bb0..82ab4cd113 100644 --- a/application/pom.xml +++ b/application/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard application @@ -31,6 +31,7 @@ thingsboard ${project.build.directory}/windows true + true ThingsBoard org.thingsboard.server.ThingsboardServerApplication @@ -221,12 +222,28 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc org.springframework.boot spring-boot-starter-websocket + + org.springframework.boot + spring-boot-jackson2 + + + org.springframework.boot + spring-boot-restclient + + + org.springframework.boot + spring-boot-security-oauth2-client + + + org.springframework.boot + spring-boot-validation + org.springframework.security spring-security-oauth2-client @@ -272,16 +289,16 @@ logback-classic - com.sun.mail - jakarta.mail + jakarta.mail + jakarta.mail-api - jakarta.xml.bind - jakarta.xml.bind-api + org.eclipse.angus + angus-mail - javax.xml.bind - jaxb-api + jakarta.xml.bind + jakarta.xml.bind-api com.twilio.sdk @@ -378,40 +395,31 @@ awaitility test - - org.dbunit - dbunit - test - - - com.github.springtestdbunit - spring-test-dbunit - test - org.testcontainers - cassandra + testcontainers-cassandra test + + + com.datastax.cassandra + cassandra-driver-core + + org.testcontainers - postgresql + testcontainers-postgresql test org.testcontainers - jdbc + testcontainers-jdbc test org.thingsboard netty-mqtt - - org.fusesource.jansi - jansi - 1.8 - org.passay passay @@ -489,6 +497,12 @@ dev.langchain4j langchain4j-open-ai-official + + + io.swagger.core.v3 + swagger-annotations + + dev.langchain4j diff --git a/application/src/main/conf/logback.xml b/application/src/main/conf/logback.xml index 3cc228810d..90766ff70a 100644 --- a/application/src/main/conf/logback.xml +++ b/application/src/main/conf/logback.xml @@ -52,7 +52,6 @@ System.err - true WARN diff --git a/application/src/main/data/json/demo/dashboards/thermostats.json b/application/src/main/data/json/demo/dashboards/thermostats.json index 04f8c1cf28..e1dfe54943 100644 --- a/application/src/main/data/json/demo/dashboards/thermostats.json +++ b/application/src/main/data/json/demo/dashboards/thermostats.json @@ -1303,17 +1303,6 @@ "label": "{i18n:widgets.maps.layer.roadmap}", "provider": "openstreet", "layerType": "OpenStreetMap.Mapnik" - }, - { - "label": "{i18n:widgets.maps.layer.satellite}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery" - }, - { - "label": "{i18n:widgets.maps.layer.hybrid}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery", - "referenceLayer": "openstreetmap_hybrid" } ], "imageSource": null, @@ -1561,17 +1550,6 @@ "label": "{i18n:widgets.maps.layer.roadmap}", "provider": "openstreet", "layerType": "OpenStreetMap.Mapnik" - }, - { - "label": "{i18n:widgets.maps.layer.satellite}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery" - }, - { - "label": "{i18n:widgets.maps.layer.hybrid}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery", - "referenceLayer": "openstreetmap_hybrid" } ], "imageSource": null, @@ -1820,17 +1798,6 @@ "label": "{i18n:widgets.maps.layer.roadmap}", "provider": "openstreet", "layerType": "OpenStreetMap.Mapnik" - }, - { - "label": "{i18n:widgets.maps.layer.satellite}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery" - }, - { - "label": "{i18n:widgets.maps.layer.hybrid}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery", - "referenceLayer": "openstreetmap_hybrid" } ], "imageSource": null, diff --git a/application/src/main/data/json/solutions/fleet_tracking/dashboards/mine_site_monitoring.json b/application/src/main/data/json/solutions/fleet_tracking/dashboards/mine_site_monitoring.json index b4d4d923dc..b475a4085e 100644 --- a/application/src/main/data/json/solutions/fleet_tracking/dashboards/mine_site_monitoring.json +++ b/application/src/main/data/json/solutions/fleet_tracking/dashboards/mine_site_monitoring.json @@ -20,21 +20,10 @@ "settings": { "mapType": "geoMap", "layers": [ - { - "label": "{i18n:widgets.maps.layer.hybrid}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery", - "referenceLayer": "openstreetmap_hybrid" - }, { "label": "{i18n:widgets.maps.layer.roadmap}", "provider": "openstreet", "layerType": "OpenStreetMap.Mapnik" - }, - { - "label": "{i18n:widgets.maps.layer.satellite}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery" } ], "imageSource": null, @@ -1284,21 +1273,10 @@ "settings": { "mapType": "geoMap", "layers": [ - { - "label": "{i18n:widgets.maps.layer.satellite}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery" - }, { "label": "{i18n:widgets.maps.layer.roadmap}", "provider": "openstreet", "layerType": "OpenStreetMap.Mapnik" - }, - { - "label": "{i18n:widgets.maps.layer.hybrid}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery", - "referenceLayer": "openstreetmap_hybrid" } ], "trips": [ @@ -2764,21 +2742,10 @@ "settings": { "mapType": "geoMap", "layers": [ - { - "label": "{i18n:widgets.maps.layer.satellite}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery" - }, { "label": "{i18n:widgets.maps.layer.roadmap}", "provider": "openstreet", "layerType": "OpenStreetMap.Mapnik" - }, - { - "label": "{i18n:widgets.maps.layer.hybrid}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery", - "referenceLayer": "openstreetmap_hybrid" } ], "trips": [ @@ -4371,21 +4338,10 @@ "settings": { "mapType": "geoMap", "layers": [ - { - "label": "{i18n:widgets.maps.layer.satellite}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery" - }, { "label": "{i18n:widgets.maps.layer.roadmap}", "provider": "openstreet", "layerType": "OpenStreetMap.Mapnik" - }, - { - "label": "{i18n:widgets.maps.layer.hybrid}", - "provider": "openstreet", - "layerType": "Esri.WorldImagery", - "referenceLayer": "openstreetmap_hybrid" } ], "imageSource": null, diff --git a/application/src/main/data/json/system/widget_types/google_map.json b/application/src/main/data/json/system/widget_types/google_map.json index 26901b56a6..42214d3862 100644 --- a/application/src/main/data/json/system/widget_types/google_map.json +++ b/application/src/main/data/json/system/widget_types/google_map.json @@ -13,7 +13,7 @@ "templateCss": ".error {\n color: red;\n}\n.tb-labels {\n color: #222;\n font: 12px/1.5 \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n text-align: center;\n width: 200px;\n white-space: nowrap;\n}", "controllerScript": "self.onInit = function() {\n self.ctx.map = new TbMapWidgetV2('google-map', false, self.ctx);\n}\n\nself.onDataUpdated = function() {\n self.ctx.map.update();\n}\n\nself.onResize = function() {\n self.ctx.map.resize();\n}\n\nself.actionSources = function() {\n return TbMapWidgetV2.actionSources();\n}\n\nself.onDestroy = function() {\n self.ctx.map.destroy();\n}\n\nself.typeParameters = function() {\n return {\n hasDataPageLink: true\n };\n}", "settingsDirective": "tb-map-widget-settings-legacy", - "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#9c27b0\",\"settings\":{},\"_hash\":0.9430343126300238,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.1784452363910778,\"funcBody\":\"return \\\"colorpin\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]},{\"type\":\"function\",\"name\":\"Second point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.773875863339494,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#3f51b5\",\"settings\":{},\"_hash\":0.405822538899673,\"funcBody\":\"return \\\"thermometer\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"google-map\",\"gmApiKey\":\"AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q\",\"gmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
Temperature: ${temperature} °C
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#fe7568\",\"useColorFunction\":true,\"colorFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'colorpin') {\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120 * 100;\\n\\t return tinycolor.mix('blue', 'red', percent).toHexString();\\n\\t}\\n\\treturn 'blue';\\n}\\n\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'thermometer') {\\n\\tvar res = {\\n\\t url: images[0],\\n\\t size: 40\\n\\t}\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120;\\n\\t var index = Math.min(3, Math.floor(4 * percent));\\n\\t res.url = images[index];\\n\\t}\\n\\treturn res;\\n}\",\"markerImages\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\",\"tb-image;/api/images/system/map_marker_image_3.png\"],\"showPolygon\":false,\"polygonKeyName\":\"perimeter\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.2,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":3,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"useClusterMarkers\":false,\"zoomOnClick\":true,\"maxClusterRadius\":80,\"animate\":true,\"spiderfyOnMaxZoom\":false,\"showCoverageOnHover\":true,\"chunkedLoading\":false,\"removeOutsideVisibleBounds\":true,\"useIconCreateFunction\":false},\"title\":\"Google Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}" + "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#9c27b0\",\"settings\":{},\"_hash\":0.9430343126300238,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.1784452363910778,\"funcBody\":\"return \\\"colorpin\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]},{\"type\":\"function\",\"name\":\"Second point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.773875863339494,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#3f51b5\",\"settings\":{},\"_hash\":0.405822538899673,\"funcBody\":\"return \\\"thermometer\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"google-map\",\"gmApiKey\":null,\"gmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
Temperature: ${temperature} °C
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#fe7568\",\"useColorFunction\":true,\"colorFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'colorpin') {\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120 * 100;\\n\\t return tinycolor.mix('blue', 'red', percent).toHexString();\\n\\t}\\n\\treturn 'blue';\\n}\\n\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'thermometer') {\\n\\tvar res = {\\n\\t url: images[0],\\n\\t size: 40\\n\\t}\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120;\\n\\t var index = Math.min(3, Math.floor(4 * percent));\\n\\t res.url = images[index];\\n\\t}\\n\\treturn res;\\n}\",\"markerImages\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\",\"tb-image;/api/images/system/map_marker_image_3.png\"],\"showPolygon\":false,\"polygonKeyName\":\"perimeter\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.2,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":3,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"useClusterMarkers\":false,\"zoomOnClick\":true,\"maxClusterRadius\":80,\"animate\":true,\"spiderfyOnMaxZoom\":false,\"showCoverageOnHover\":true,\"chunkedLoading\":false,\"removeOutsideVisibleBounds\":true,\"useIconCreateFunction\":false},\"title\":\"Google Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}" }, "tags": [ "mapping", diff --git a/application/src/main/data/json/system/widget_types/here_map.json b/application/src/main/data/json/system/widget_types/here_map.json index c57fff50c3..718d571a57 100644 --- a/application/src/main/data/json/system/widget_types/here_map.json +++ b/application/src/main/data/json/system/widget_types/here_map.json @@ -13,7 +13,7 @@ "templateCss": ".leaflet-zoom-box {\n\tz-index: 9;\n}\n\n.leaflet-pane { z-index: 4; }\n\n.leaflet-tile-pane { z-index: 2; }\n.leaflet-overlay-pane { z-index: 4; }\n.leaflet-shadow-pane { z-index: 5; }\n.leaflet-marker-pane { z-index: 6; }\n.leaflet-tooltip-pane { z-index: 7; }\n.leaflet-popup-pane { z-index: 8; }\n\n.leaflet-map-pane canvas { z-index: 1; }\n.leaflet-map-pane svg { z-index: 2; }\n\n.leaflet-control {\n\tz-index: 9;\n}\n.leaflet-top,\n.leaflet-bottom {\n\tz-index: 11;\n}\n\n.tb-marker-label {\n border: none;\n background: none;\n box-shadow: none;\n}\n\n.tb-marker-label:before {\n border: none;\n background: none;\n}\n", "controllerScript": "self.onInit = function() {\n self.ctx.map = new TbMapWidgetV2('here', false, self.ctx);\n}\n\nself.onDataUpdated = function() {\n self.ctx.map.update();\n}\n\nself.onResize = function() {\n self.ctx.map.resize();\n}\n\nself.actionSources = function() {\n return TbMapWidgetV2.actionSources();\n}\n\nself.onDestroy = function() {\n self.ctx.map.destroy();\n}\n\nself.typeParameters = function() {\n return {\n hasDataPageLink: true\n };\n}", "settingsDirective": "tb-map-widget-settings-legacy", - "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#9c27b0\",\"settings\":{},\"_hash\":0.9430343126300238,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.1784452363910778,\"funcBody\":\"return \\\"colorpin\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]},{\"type\":\"function\",\"name\":\"Second point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.773875863339494,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#3f51b5\",\"settings\":{},\"_hash\":0.405822538899673,\"funcBody\":\"return \\\"thermometer\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"here\",\"gmApiKey\":\"AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q\",\"gmDefaultMapType\":\"roadmap\",\"mapProvider\":\"HERE.normalDay\",\"useCustomProvider\":false,\"customProviderTileUrl\":\"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\",\"mapProviderHere\":\"HERE.normalDay\",\"credentials\":{\"useV3\":true,\"apiKey\":\"kVXykxAfZ6LS4EbCTO02soFVfjA7HoBzNVVH9u7nzoE\"},\"mapImageUrl\":\"tb-image;/api/images/system/air_quality_monitoring_dashboard_widget_new_openstreetmap_map_image.svg\",\"tmApiKey\":\"84d6d83e0e51e481e50454ccbe8986b\",\"tmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
Temperature: ${temperature} °C
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#fe7569\",\"useColorFunction\":true,\"colorFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'colorpin') {\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120 * 100;\\n\\t return tinycolor.mix('blue', 'red', percent).toHexString();\\n\\t}\\n\\treturn 'blue';\\n}\\n\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'thermometer') {\\n\\tvar res = {\\n\\t url: images[0],\\n\\t size: 40\\n\\t}\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120;\\n\\t var index = Math.min(3, Math.floor(4 * percent));\\n\\t res.url = images[index];\\n\\t}\\n\\treturn res;\\n}\",\"markerImages\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\",\"tb-image;/api/images/system/map_marker_image_3.png\"],\"showPolygon\":false,\"polygonKeyName\":\"coordinates\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.5,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":1,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"useClusterMarkers\":false,\"zoomOnClick\":true,\"maxClusterRadius\":80,\"animate\":true,\"spiderfyOnMaxZoom\":false,\"showCoverageOnHover\":true,\"chunkedLoading\":false,\"removeOutsideVisibleBounds\":true,\"useIconCreateFunction\":false},\"title\":\"HERE Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}" + "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#9c27b0\",\"settings\":{},\"_hash\":0.9430343126300238,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.1784452363910778,\"funcBody\":\"return \\\"colorpin\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]},{\"type\":\"function\",\"name\":\"Second point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.773875863339494,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#3f51b5\",\"settings\":{},\"_hash\":0.405822538899673,\"funcBody\":\"return \\\"thermometer\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"here\",\"gmApiKey\":null,\"gmDefaultMapType\":\"roadmap\",\"mapProvider\":\"HERE.normalDay\",\"useCustomProvider\":false,\"customProviderTileUrl\":\"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\",\"mapProviderHere\":\"HERE.normalDay\",\"credentials\":{\"useV3\":true,\"apiKey\":null},\"mapImageUrl\":\"tb-image;/api/images/system/air_quality_monitoring_dashboard_widget_new_openstreetmap_map_image.svg\",\"tmApiKey\":\"84d6d83e0e51e481e50454ccbe8986b\",\"tmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
Temperature: ${temperature} °C
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#fe7569\",\"useColorFunction\":true,\"colorFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'colorpin') {\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120 * 100;\\n\\t return tinycolor.mix('blue', 'red', percent).toHexString();\\n\\t}\\n\\treturn 'blue';\\n}\\n\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'thermometer') {\\n\\tvar res = {\\n\\t url: images[0],\\n\\t size: 40\\n\\t}\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120;\\n\\t var index = Math.min(3, Math.floor(4 * percent));\\n\\t res.url = images[index];\\n\\t}\\n\\treturn res;\\n}\",\"markerImages\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\",\"tb-image;/api/images/system/map_marker_image_3.png\"],\"showPolygon\":false,\"polygonKeyName\":\"coordinates\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.5,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":1,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"useClusterMarkers\":false,\"zoomOnClick\":true,\"maxClusterRadius\":80,\"animate\":true,\"spiderfyOnMaxZoom\":false,\"showCoverageOnHover\":true,\"chunkedLoading\":false,\"removeOutsideVisibleBounds\":true,\"useIconCreateFunction\":false},\"title\":\"HERE Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}" }, "tags": [ "mapping", diff --git a/application/src/main/data/json/system/widget_types/markers_placement___google_maps.json b/application/src/main/data/json/system/widget_types/markers_placement___google_maps.json index 674cd6e06e..d4d416a471 100644 --- a/application/src/main/data/json/system/widget_types/markers_placement___google_maps.json +++ b/application/src/main/data/json/system/widget_types/markers_placement___google_maps.json @@ -13,7 +13,7 @@ "templateCss": ".error {\n color: red;\n}\n.tb-labels {\n color: #222;\n font: 12px/1.5 \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n text-align: center;\n width: 200px;\n white-space: nowrap;\n}", "controllerScript": "self.onInit = function() {\n self.ctx.map = new TbMapWidgetV2('google-map', false, self.ctx, null, true);\n}\n\nself.onDataUpdated = function() {\n self.ctx.map.update();\n}\n\nself.onResize = function() {\n self.ctx.map.resize();\n}\n\nself.actionSources = function() {\n return TbMapWidgetV2.actionSources();\n}\n\nself.onDestroy = function() {\n self.ctx.map.destroy();\n}\n\nself.typeParameters = function() {\n return {\n hasDataPageLink: true\n };\n}", "settingsDirective": "tb-map-widget-settings-legacy", - "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]},{\"type\":\"function\",\"name\":\"Second point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"fitMapBounds\":true,\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"showLabel\":true,\"label\":\"${entityName}\",\"tooltipPattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}

Delete\",\"markerImageSize\":34,\"gmDefaultMapType\":\"roadmap\",\"gmApiKey\":\"AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q\",\"useColorFunction\":false,\"markerImages\":[],\"useMarkerImageFunction\":false,\"colorFunction\":\"\\n\",\"color\":\"#fe7569\",\"showTooltip\":true,\"autocloseTooltip\":true,\"defaultCenterPosition\":\"0,0\",\"showTooltipAction\":\"click\",\"polygonKeyName\":\"coordinates\",\"polygonOpacity\":0.5,\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":1,\"zoomOnClick\":true,\"defaultZoomLevel\":5,\"provider\":\"google-map\",\"showCoverageOnHover\":true,\"animate\":true,\"maxClusterRadius\":80,\"removeOutsideVisibleBounds\":true,\"mapProvider\":\"HERE.normalDay\",\"draggableMarker\":true,\"editablePolygon\":true,\"mapPageSize\":16384,\"showPolygon\":false,\"polygonTooltipPattern\":\"${entityName}

TimeStamp: ${coordinates|ts:7}

Delete\",\"showPolygonTooltip\":false},\"title\":\"Markers Placement - Google Maps\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{\"tooltipAction\":[{\"name\":\"delete\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id;\\n });\\n\\nwidgetContext.map.setMarkerLocation(entityDatasource[0], null, null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"8d3c0156-0a14-7a6f-0ddd-0ec16b9ffc91\"},{\"name\":\"delete_polygon\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id\\n });\\n\\nwidgetContext.map.savePolygonLocation(entityDatasource[0], null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"46bf69cd-8906-234c-a879-e2e4c92f5b67\"}]},\"showTitleIcon\":false,\"titleIcon\":\"more_horiz\",\"iconColor\":\"rgba(0, 0, 0, 0.87)\",\"iconSize\":\"24px\",\"titleTooltip\":\"\"}" + "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]},{\"type\":\"function\",\"name\":\"Second point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"fitMapBounds\":true,\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"showLabel\":true,\"label\":\"${entityName}\",\"tooltipPattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}

Delete\",\"markerImageSize\":34,\"gmDefaultMapType\":\"roadmap\",\"gmApiKey\":null,\"useColorFunction\":false,\"markerImages\":[],\"useMarkerImageFunction\":false,\"colorFunction\":\"\\n\",\"color\":\"#fe7569\",\"showTooltip\":true,\"autocloseTooltip\":true,\"defaultCenterPosition\":\"0,0\",\"showTooltipAction\":\"click\",\"polygonKeyName\":\"coordinates\",\"polygonOpacity\":0.5,\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":1,\"zoomOnClick\":true,\"defaultZoomLevel\":5,\"provider\":\"google-map\",\"showCoverageOnHover\":true,\"animate\":true,\"maxClusterRadius\":80,\"removeOutsideVisibleBounds\":true,\"mapProvider\":\"HERE.normalDay\",\"draggableMarker\":true,\"editablePolygon\":true,\"mapPageSize\":16384,\"showPolygon\":false,\"polygonTooltipPattern\":\"${entityName}

TimeStamp: ${coordinates|ts:7}

Delete\",\"showPolygonTooltip\":false},\"title\":\"Markers Placement - Google Maps\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{\"tooltipAction\":[{\"name\":\"delete\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id;\\n });\\n\\nwidgetContext.map.setMarkerLocation(entityDatasource[0], null, null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"8d3c0156-0a14-7a6f-0ddd-0ec16b9ffc91\"},{\"name\":\"delete_polygon\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id\\n });\\n\\nwidgetContext.map.savePolygonLocation(entityDatasource[0], null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"46bf69cd-8906-234c-a879-e2e4c92f5b67\"}]},\"showTitleIcon\":false,\"titleIcon\":\"more_horiz\",\"iconColor\":\"rgba(0, 0, 0, 0.87)\",\"iconSize\":\"24px\",\"titleTooltip\":\"\"}" }, "tags": [ "mapping", diff --git a/application/src/main/data/json/system/widget_types/route_map.json b/application/src/main/data/json/system/widget_types/route_map.json index 710756a58a..ff6a10e133 100644 --- a/application/src/main/data/json/system/widget_types/route_map.json +++ b/application/src/main/data/json/system/widget_types/route_map.json @@ -20,7 +20,7 @@ "latestDataKeySettingsDirective": "", "hasBasicMode": true, "basicModeDirective": "tb-map-basic-config", - "defaultConfig": "{\"datasources\":[],\"timewindow\":{\"selectedTab\":0,\"realtime\":{\"realtimeType\":0,\"timewindowMs\":86400000},\"aggregation\":{\"type\":\"NONE\",\"limit\":5000}},\"showTitle\":true,\"backgroundColor\":\"rgba(0, 0, 0, 0)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"mapType\":\"geoMap\",\"layers\":[{\"label\":\"{i18n:widgets.maps.layer.roadmap}\",\"provider\":\"openstreet\",\"layerType\":\"OpenStreetMap.Mapnik\"},{\"label\":\"{i18n:widgets.maps.layer.satellite}\",\"provider\":\"openstreet\",\"layerType\":\"Esri.WorldImagery\"},{\"label\":\"{i18n:widgets.maps.layer.hybrid}\",\"provider\":\"openstreet\",\"layerType\":\"Esri.WorldImagery\",\"referenceLayer\":\"openstreetmap_hybrid\"}],\"trips\":[{\"dsType\":\"function\",\"dsLabel\":\"First route\",\"dsDeviceId\":null,\"dsEntityAliasId\":null,\"dsFilterId\":null,\"additionalDataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Speed\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.17490048149347315,\"funcBody\":\"var value = prevValue;\\nif (!value) {\\n value = 45;\\n}\\nif (time % 500 < 500) {\\n value = value + Math.random() * 40 - 20;\\n if (value < 45) {\\n \\tvalue = 45;\\n } else if (value > 130) {\\n \\tvalue = 130;\\n }\\n}\\nreturn value;\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}],\"label\":{\"show\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}\"},\"tooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
Speed: ${Speed} MPH\",\"offsetX\":0,\"offsetY\":-1,\"patternFunction\":null,\"tagActions\":null},\"click\":{\"type\":\"doNothing\"},\"groups\":null,\"xKey\":{\"name\":\"f(x)\",\"label\":\"latitude\",\"type\":\"function\",\"funcBody\":\"var lats = [37.7696499,\\n37.7699074,\\n37.7699536,\\n37.7697242,\\n37.7695189,\\n37.7696889,\\n37.7697153,\\n37.7701244,\\n37.7700604,\\n37.7705491,\\n37.7715705,\\n37.771752,\\n37.7707533,\\n37.769866];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lats[i];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"yKey\":{\"name\":\"f(x)\",\"label\":\"longitude\",\"type\":\"function\",\"funcBody\":\"var lons = [-122.4261215,\\n-122.4219157,\\n-122.4199623,\\n-122.4179074,\\n-122.4155876,\\n-122.4155521,\\n-122.4163203,\\n-122.4193876,\\n-122.4210496,\\n-122.422284,\\n-122.4232717,\\n-122.4235138,\\n-122.4247605,\\n-122.4258812];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lons[i];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"markerType\":\"image\",\"markerShape\":{\"shape\":\"tripMarkerShape1\",\"size\":34,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerIcon\":{\"icon\":\"arrow_forward\",\"size\":48,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerImage\":{\"type\":\"function\",\"image\":\"/assets/markers/tripShape1.svg\",\"imageSize\":34,\"imageFunction\":\"var speed = data.Speed;\\nvar res = {\\n url: images[0],\\n size: 55\\n};\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n var index = Math.min(2, Math.floor(3 * percent));\\n res.url = images[index];\\n}\\nreturn res;\",\"images\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\"]},\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"rotateMarker\":true,\"offsetAngle\":0,\"showPath\":true,\"pathStrokeWeight\":4,\"pathStrokeColor\":{\"type\":\"function\",\"color\":\"#307FE5\",\"colorFunction\":\"var speed = data.Speed;\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n if (percent < 0.5) {\\n percent *=2*100; \\n return tinycolor.mix('green', 'yellow', percent).setAlpha(0.65).toRgbString();\\n } else {\\n percent = (percent - 0.5)*2*100;\\n return tinycolor.mix('yellow', 'red', percent).setAlpha(0.65).toRgbString();\\n }\\n}\"},\"usePathDecorator\":false,\"pathDecoratorSymbol\":\"arrowHead\",\"pathDecoratorSymbolSize\":10,\"pathDecoratorSymbolColor\":\"#307FE5\",\"pathDecoratorOffset\":20,\"pathEndDecoratorOffset\":20,\"pathDecoratorRepeat\":20,\"showPoints\":false,\"pointSize\":10,\"pointColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"pointTooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-1}}],\"markers\":[],\"polygons\":[],\"circles\":[],\"polylines\":[],\"additionalDataSources\":[],\"controlsPosition\":\"topleft\",\"zoomActions\":[\"scroll\",\"doubleClick\",\"controlButtons\"],\"scales\":[],\"dragModeButton\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"defaultCenterPosition\":\"0,0\",\"defaultZoomLevel\":null,\"minZoomLevel\":16,\"mapPageSize\":16384,\"mapActionButtons\":[],\"tripTimeline\":{\"showTimelineControl\":false,\"timeStep\":1000,\"speedOptions\":[1,5,10,15,25],\"showTimestamp\":true,\"timestampFormat\":{\"format\":\"yyyy-MM-dd HH:mm:ss\",\"lastUpdateAgo\":false,\"custom\":false,\"auto\":false},\"snapToRealLocation\":false,\"locationSnapFilter\":\"return true;\"},\"background\":{\"type\":\"color\",\"color\":\"#fff\",\"overlay\":{\"enabled\":false,\"color\":\"rgba(255,255,255,0.72)\",\"blur\":3}},\"padding\":\"8px\"},\"title\":\"Route Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":null,\"mobileHeight\":null,\"configMode\":\"basic\",\"actions\":{},\"showTitleIcon\":false,\"titleIcon\":\"assistant_navigation\",\"iconColor\":\"#1F6BDD\",\"useDashboardTimewindow\":false,\"displayTimewindow\":true,\"titleFont\":{\"size\":null,\"sizeUnit\":\"px\",\"family\":null,\"weight\":null,\"style\":null,\"lineHeight\":null},\"titleColor\":null,\"titleTooltip\":\"\",\"widgetStyle\":{},\"widgetCss\":\"\",\"pageSize\":1024,\"units\":\"\",\"decimals\":null,\"noDataDisplayMessage\":\"\",\"timewindowStyle\":{\"showIcon\":false,\"iconSize\":\"24px\",\"icon\":null,\"iconPosition\":\"left\",\"font\":{\"size\":12,\"sizeUnit\":\"px\",\"family\":\"Roboto\",\"weight\":\"400\",\"style\":\"normal\",\"lineHeight\":\"16px\"},\"color\":\"rgba(0, 0, 0, 0.38)\",\"displayTypePrefix\":true},\"margin\":\"0px\",\"borderRadius\":\"0px\",\"iconSize\":\"24px\",\"enableDataExport\":false}" + "defaultConfig": "{\"datasources\":[],\"timewindow\":{\"selectedTab\":0,\"realtime\":{\"realtimeType\":0,\"timewindowMs\":86400000},\"aggregation\":{\"type\":\"NONE\",\"limit\":5000}},\"showTitle\":true,\"backgroundColor\":\"rgba(0, 0, 0, 0)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"mapType\":\"geoMap\",\"layers\":[{\"label\":\"{i18n:widgets.maps.layer.roadmap}\",\"provider\":\"openstreet\",\"layerType\":\"OpenStreetMap.Mapnik\"}],\"trips\":[{\"dsType\":\"function\",\"dsLabel\":\"First route\",\"dsDeviceId\":null,\"dsEntityAliasId\":null,\"dsFilterId\":null,\"additionalDataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Speed\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.17490048149347315,\"funcBody\":\"var value = prevValue;\\nif (!value) {\\n value = 45;\\n}\\nif (time % 500 < 500) {\\n value = value + Math.random() * 40 - 20;\\n if (value < 45) {\\n \\tvalue = 45;\\n } else if (value > 130) {\\n \\tvalue = 130;\\n }\\n}\\nreturn value;\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}],\"label\":{\"show\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}\"},\"tooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
Speed: ${Speed} MPH\",\"offsetX\":0,\"offsetY\":-1,\"patternFunction\":null,\"tagActions\":null},\"click\":{\"type\":\"doNothing\"},\"groups\":null,\"xKey\":{\"name\":\"f(x)\",\"label\":\"latitude\",\"type\":\"function\",\"funcBody\":\"var lats = [37.7696499,\\n37.7699074,\\n37.7699536,\\n37.7697242,\\n37.7695189,\\n37.7696889,\\n37.7697153,\\n37.7701244,\\n37.7700604,\\n37.7705491,\\n37.7715705,\\n37.771752,\\n37.7707533,\\n37.769866];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lats[i];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"yKey\":{\"name\":\"f(x)\",\"label\":\"longitude\",\"type\":\"function\",\"funcBody\":\"var lons = [-122.4261215,\\n-122.4219157,\\n-122.4199623,\\n-122.4179074,\\n-122.4155876,\\n-122.4155521,\\n-122.4163203,\\n-122.4193876,\\n-122.4210496,\\n-122.422284,\\n-122.4232717,\\n-122.4235138,\\n-122.4247605,\\n-122.4258812];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lons[i];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"markerType\":\"image\",\"markerShape\":{\"shape\":\"tripMarkerShape1\",\"size\":34,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerIcon\":{\"icon\":\"arrow_forward\",\"size\":48,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerImage\":{\"type\":\"function\",\"image\":\"/assets/markers/tripShape1.svg\",\"imageSize\":34,\"imageFunction\":\"var speed = data.Speed;\\nvar res = {\\n url: images[0],\\n size: 55\\n};\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n var index = Math.min(2, Math.floor(3 * percent));\\n res.url = images[index];\\n}\\nreturn res;\",\"images\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\"]},\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"rotateMarker\":true,\"offsetAngle\":0,\"showPath\":true,\"pathStrokeWeight\":4,\"pathStrokeColor\":{\"type\":\"function\",\"color\":\"#307FE5\",\"colorFunction\":\"var speed = data.Speed;\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n if (percent < 0.5) {\\n percent *=2*100; \\n return tinycolor.mix('green', 'yellow', percent).setAlpha(0.65).toRgbString();\\n } else {\\n percent = (percent - 0.5)*2*100;\\n return tinycolor.mix('yellow', 'red', percent).setAlpha(0.65).toRgbString();\\n }\\n}\"},\"usePathDecorator\":false,\"pathDecoratorSymbol\":\"arrowHead\",\"pathDecoratorSymbolSize\":10,\"pathDecoratorSymbolColor\":\"#307FE5\",\"pathDecoratorOffset\":20,\"pathEndDecoratorOffset\":20,\"pathDecoratorRepeat\":20,\"showPoints\":false,\"pointSize\":10,\"pointColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"pointTooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-1}}],\"markers\":[],\"polygons\":[],\"circles\":[],\"polylines\":[],\"additionalDataSources\":[],\"controlsPosition\":\"topleft\",\"zoomActions\":[\"scroll\",\"doubleClick\",\"controlButtons\"],\"scales\":[],\"dragModeButton\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"defaultCenterPosition\":\"0,0\",\"defaultZoomLevel\":null,\"minZoomLevel\":16,\"mapPageSize\":16384,\"mapActionButtons\":[],\"tripTimeline\":{\"showTimelineControl\":false,\"timeStep\":1000,\"speedOptions\":[1,5,10,15,25],\"showTimestamp\":true,\"timestampFormat\":{\"format\":\"yyyy-MM-dd HH:mm:ss\",\"lastUpdateAgo\":false,\"custom\":false,\"auto\":false},\"snapToRealLocation\":false,\"locationSnapFilter\":\"return true;\"},\"background\":{\"type\":\"color\",\"color\":\"#fff\",\"overlay\":{\"enabled\":false,\"color\":\"rgba(255,255,255,0.72)\",\"blur\":3}},\"padding\":\"8px\"},\"title\":\"Route Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":null,\"mobileHeight\":null,\"configMode\":\"basic\",\"actions\":{},\"showTitleIcon\":false,\"titleIcon\":\"assistant_navigation\",\"iconColor\":\"#1F6BDD\",\"useDashboardTimewindow\":false,\"displayTimewindow\":true,\"titleFont\":{\"size\":null,\"sizeUnit\":\"px\",\"family\":null,\"weight\":null,\"style\":null,\"lineHeight\":null},\"titleColor\":null,\"titleTooltip\":\"\",\"widgetStyle\":{},\"widgetCss\":\"\",\"pageSize\":1024,\"units\":\"\",\"decimals\":null,\"noDataDisplayMessage\":\"\",\"timewindowStyle\":{\"showIcon\":false,\"iconSize\":\"24px\",\"icon\":null,\"iconPosition\":\"left\",\"font\":{\"size\":12,\"sizeUnit\":\"px\",\"family\":\"Roboto\",\"weight\":\"400\",\"style\":\"normal\",\"lineHeight\":\"16px\"},\"color\":\"rgba(0, 0, 0, 0.38)\",\"displayTypePrefix\":true},\"margin\":\"0px\",\"borderRadius\":\"0px\",\"iconSize\":\"24px\",\"enableDataExport\":false}" }, "resources": [ { diff --git a/application/src/main/data/json/system/widget_types/route_map___google.json b/application/src/main/data/json/system/widget_types/route_map___google.json index 5d3bd865a0..620834b9c7 100644 --- a/application/src/main/data/json/system/widget_types/route_map___google.json +++ b/application/src/main/data/json/system/widget_types/route_map___google.json @@ -13,7 +13,7 @@ "templateCss": ".error {\n color: red;\n}\n.tb-labels {\n color: #222;\n font: 12px/1.5 \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n text-align: center;\n width: 200px;\n white-space: nowrap;\n}", "controllerScript": "self.onInit = function() {\n self.ctx.map = new TbMapWidgetV2('google-map', true, self.ctx);\n}\n\nself.onDataUpdated = function() {\n self.ctx.map.update();\n}\n\nself.onLatestDataUpdated = function() {\n self.ctx.map.latestDataUpdate();\n}\n\nself.onResize = function() {\n self.ctx.map.resize();\n}\n\nself.actionSources = function() {\n return TbMapWidgetV2.actionSources();\n}\n\nself.onDestroy = function() {\n self.ctx.map.destroy();\n}\n\nself.typeParameters = function() {\n return {\n hasDataPageLink: true,\n ignoreDataUpdateOnIntervalTick: true,\n hasAdditionalLatestDataKeys: true\n };\n}", "settingsDirective": "tb-route-map-widget-settings", - "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First route\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.5851719234007373,\"funcBody\":\"var lats = [37.7696499,\\n37.7699074,\\n37.7699536,\\n37.7697242,\\n37.7695189,\\n37.7696889,\\n37.7697153,\\n37.7701244,\\n37.7700604,\\n37.7705491,\\n37.7715705,\\n37.771752,\\n37.7707533,\\n37.769866];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lats[i];\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.9015113051937396,\"funcBody\":\"var lons = [-122.4261215,\\n-122.4219157,\\n-122.4199623,\\n-122.4179074,\\n-122.4155876,\\n-122.4155521,\\n-122.4163203,\\n-122.4193876,\\n-122.4210496,\\n-122.422284,\\n-122.4232717,\\n-122.4235138,\\n-122.4247605,\\n-122.4258812];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lons[i];\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Speed\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.7253460349565717,\"funcBody\":\"var value = prevValue;\\nif (time % 500 < 100) {\\n value = value + Math.random() * 40 - 20;\\n if (value < 45) {\\n \\tvalue = 45;\\n } else if (value > 130) {\\n \\tvalue = 130;\\n }\\n}\\nreturn value;\"}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"google-map\",\"gmApiKey\":\"AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q\",\"gmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
Speed: ${Speed} MPH
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#1976d2\",\"useColorFunction\":true,\"colorFunction\":\"var speed = dsData[dsIndex]['Speed'];\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n if (percent < 0.5) {\\n percent *=2*100; \\n return tinycolor.mix('green', 'yellow', percent).toHexString();\\n } else {\\n percent = (percent - 0.5)*2*100;\\n return tinycolor.mix('yellow', 'red', percent).toHexString();\\n }\\n}\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var speed = dsData[dsIndex]['Speed'];\\nvar res = {\\n url: images[0],\\n size: 55\\n};\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n var index = Math.min(2, Math.floor(3 * percent));\\n res.url = images[index];\\n}\\nreturn res;\",\"markerImages\":[\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_0.png\",\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_1.png\",\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_2.png\"],\"showPolygon\":false,\"polygonKeyName\":\"perimeter\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.2,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":3,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"strokeWeight\":4,\"strokeOpacity\":0.65},\"title\":\"Route Map - Google\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"useDashboardTimewindow\":true,\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}" + "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First route\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.5851719234007373,\"funcBody\":\"var lats = [37.7696499,\\n37.7699074,\\n37.7699536,\\n37.7697242,\\n37.7695189,\\n37.7696889,\\n37.7697153,\\n37.7701244,\\n37.7700604,\\n37.7705491,\\n37.7715705,\\n37.771752,\\n37.7707533,\\n37.769866];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lats[i];\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.9015113051937396,\"funcBody\":\"var lons = [-122.4261215,\\n-122.4219157,\\n-122.4199623,\\n-122.4179074,\\n-122.4155876,\\n-122.4155521,\\n-122.4163203,\\n-122.4193876,\\n-122.4210496,\\n-122.422284,\\n-122.4232717,\\n-122.4235138,\\n-122.4247605,\\n-122.4258812];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lons[i];\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Speed\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.7253460349565717,\"funcBody\":\"var value = prevValue;\\nif (time % 500 < 100) {\\n value = value + Math.random() * 40 - 20;\\n if (value < 45) {\\n \\tvalue = 45;\\n } else if (value > 130) {\\n \\tvalue = 130;\\n }\\n}\\nreturn value;\"}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"google-map\",\"gmApiKey\":null,\"gmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
Speed: ${Speed} MPH
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#1976d2\",\"useColorFunction\":true,\"colorFunction\":\"var speed = dsData[dsIndex]['Speed'];\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n if (percent < 0.5) {\\n percent *=2*100; \\n return tinycolor.mix('green', 'yellow', percent).toHexString();\\n } else {\\n percent = (percent - 0.5)*2*100;\\n return tinycolor.mix('yellow', 'red', percent).toHexString();\\n }\\n}\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var speed = dsData[dsIndex]['Speed'];\\nvar res = {\\n url: images[0],\\n size: 55\\n};\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n var index = Math.min(2, Math.floor(3 * percent));\\n res.url = images[index];\\n}\\nreturn res;\",\"markerImages\":[\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_0.png\",\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_1.png\",\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_2.png\"],\"showPolygon\":false,\"polygonKeyName\":\"perimeter\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.2,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":3,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}

TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"strokeWeight\":4,\"strokeOpacity\":0.65},\"title\":\"Route Map - Google\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"useDashboardTimewindow\":true,\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}" }, "tags": [ "mapping", diff --git a/application/src/main/data/json/system/widget_types/trip_map.json b/application/src/main/data/json/system/widget_types/trip_map.json index 9293209f8a..031f1bac3e 100644 --- a/application/src/main/data/json/system/widget_types/trip_map.json +++ b/application/src/main/data/json/system/widget_types/trip_map.json @@ -20,7 +20,7 @@ "latestDataKeySettingsDirective": "", "hasBasicMode": true, "basicModeDirective": "tb-map-basic-config", - "defaultConfig": "{\"datasources\":[],\"timewindow\":{\"selectedTab\":1,\"history\":{\"historyType\":0,\"timewindowMs\":86400000},\"aggregation\":{\"type\":\"NONE\",\"limit\":5000}},\"showTitle\":true,\"backgroundColor\":\"rgba(0, 0, 0, 0)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"mapType\":\"geoMap\",\"layers\":[{\"label\":\"{i18n:widgets.maps.layer.roadmap}\",\"provider\":\"openstreet\",\"layerType\":\"OpenStreetMap.Mapnik\"},{\"label\":\"{i18n:widgets.maps.layer.satellite}\",\"provider\":\"openstreet\",\"layerType\":\"Esri.WorldImagery\"},{\"label\":\"{i18n:widgets.maps.layer.hybrid}\",\"provider\":\"openstreet\",\"layerType\":\"Esri.WorldImagery\",\"referenceLayer\":\"openstreetmap_hybrid\"}],\"trips\":[{\"dsType\":\"function\",\"dsLabel\":\"First point\",\"xKey\":{\"name\":\"f(x)\",\"label\":\"latitude\",\"type\":\"function\",\"funcBody\":\"var gpsData = [\\n37.771210000, -122.510960000,\\n 37.771990000, -122.497070000,\\n 37.772730000, -122.480740000,\\n 37.773360000, -122.466870000,\\n 37.774270000, -122.458520000,\\n 37.771980000, -122.454110000,\\n 37.768250000, -122.453380000,\\n 37.765920000, -122.456810000,\\n 37.765930000, -122.467680000,\\n 37.765500000, -122.477180000,\\n 37.765300000, -122.481660000,\\n 37.764780000, -122.493350000,\\n 37.764120000, -122.508360000,\\n 37.766410000, -122.510260000,\\n 37.770010000, -122.510830000,\\n 37.770980000, -122.510930000\\n];\\n let value = gpsData.indexOf(prevValue); \\nreturn gpsData[(value == -1 ? 0 : (value + 2) % gpsData.length)];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"yKey\":{\"name\":\"f(x)\",\"label\":\"longitude\",\"type\":\"function\",\"funcBody\":\"var gpsData = [\\n37.771210000, -122.510960000,\\n 37.771990000, -122.497070000,\\n 37.772730000, -122.480740000,\\n 37.773360000, -122.466870000,\\n 37.774270000, -122.458520000,\\n 37.771980000, -122.454110000,\\n 37.768250000, -122.453380000,\\n 37.765920000, -122.456810000,\\n 37.765930000, -122.467680000,\\n 37.765500000, -122.477180000,\\n 37.765300000, -122.481660000,\\n 37.764780000, -122.493350000,\\n 37.764120000, -122.508360000,\\n 37.766410000, -122.510260000,\\n 37.770010000, -122.510830000,\\n 37.770980000, -122.510930000\\n];\\n let value = gpsData.indexOf(prevValue); \\nreturn gpsData[(value == -1 ? 1 : (value + 2) % gpsData.length)];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"markerType\":\"shape\",\"markerShape\":{\"shape\":\"tripMarkerShape1\",\"size\":34,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerIcon\":{\"icon\":\"arrow_forward\",\"size\":48,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerImage\":{\"type\":\"image\",\"image\":\"/assets/markers/tripShape1.svg\",\"imageSize\":34},\"markerOffsetX\":0.5,\"markerOffsetY\":0.5,\"positionFunction\":\"return {x: origXPos, y: origYPos};\",\"markerClustering\":{\"enable\":false,\"zoomOnClick\":true,\"maxZoom\":null,\"maxClusterRadius\":80,\"zoomAnimation\":true,\"showCoverageOnHover\":true,\"spiderfyOnMaxZoom\":false,\"chunkedLoad\":false,\"lazyLoad\":true,\"useClusterMarkerColorFunction\":false,\"clusterMarkerColorFunction\":null},\"label\":{\"show\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}\"},\"tooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-0.5},\"click\":{\"type\":\"doNothing\"},\"edit\":{\"enabledActions\":[],\"snappable\":false},\"rotateMarker\":true,\"offsetAngle\":0,\"showPath\":true,\"pathStrokeWeight\":2,\"pathStrokeColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"usePathDecorator\":false,\"pathDecoratorSymbol\":\"arrowHead\",\"pathDecoratorSymbolSize\":10,\"pathDecoratorSymbolColor\":\"#307FE5\",\"pathDecoratorOffset\":20,\"pathEndDecoratorOffset\":20,\"pathDecoratorRepeat\":20,\"showPoints\":false,\"pointSize\":10,\"pointColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"pointTooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-1}}],\"markers\":[],\"polygons\":[],\"circles\":[],\"polylines\":[],\"additionalDataSources\":[],\"controlsPosition\":\"topleft\",\"zoomActions\":[\"scroll\",\"doubleClick\",\"controlButtons\"],\"scales\":[],\"dragModeButton\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"defaultCenterPosition\":\"0,0\",\"defaultZoomLevel\":null,\"minZoomLevel\":16,\"mapPageSize\":16384,\"mapActionButtons\":[],\"tripTimeline\":{\"showTimelineControl\":true,\"timeStep\":1000,\"speedOptions\":[1,5,10,15,25],\"showTimestamp\":true,\"timestampFormat\":{\"format\":\"yyyy-MM-dd HH:mm:ss\",\"lastUpdateAgo\":false,\"custom\":false,\"auto\":false},\"snapToRealLocation\":false,\"locationSnapFilter\":\"return true;\"},\"background\":{\"type\":\"color\",\"color\":\"#fff\",\"overlay\":{\"enabled\":false,\"color\":\"rgba(255,255,255,0.72)\",\"blur\":3}},\"padding\":\"8px\"},\"title\":\"Trip Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":null,\"mobileHeight\":null,\"configMode\":\"basic\",\"actions\":{},\"showTitleIcon\":false,\"titleIcon\":\"assistant_navigation\",\"iconColor\":\"#1F6BDD\",\"useDashboardTimewindow\":false,\"displayTimewindow\":true,\"titleFont\":{\"size\":null,\"sizeUnit\":\"px\",\"family\":null,\"weight\":null,\"style\":null,\"lineHeight\":null},\"titleColor\":null,\"titleTooltip\":\"\",\"widgetStyle\":{},\"widgetCss\":\"\",\"pageSize\":1024,\"units\":\"\",\"decimals\":null,\"noDataDisplayMessage\":\"\",\"timewindowStyle\":{\"showIcon\":false,\"iconSize\":\"24px\",\"icon\":null,\"iconPosition\":\"left\",\"font\":{\"size\":12,\"sizeUnit\":\"px\",\"family\":\"Roboto\",\"weight\":\"400\",\"style\":\"normal\",\"lineHeight\":\"16px\"},\"color\":\"rgba(0, 0, 0, 0.38)\",\"displayTypePrefix\":true},\"margin\":\"0px\",\"borderRadius\":\"0px\",\"iconSize\":\"24px\",\"enableDataExport\":false}" + "defaultConfig": "{\"datasources\":[],\"timewindow\":{\"selectedTab\":1,\"history\":{\"historyType\":0,\"timewindowMs\":86400000},\"aggregation\":{\"type\":\"NONE\",\"limit\":5000}},\"showTitle\":true,\"backgroundColor\":\"rgba(0, 0, 0, 0)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"mapType\":\"geoMap\",\"layers\":[{\"label\":\"{i18n:widgets.maps.layer.roadmap}\",\"provider\":\"openstreet\",\"layerType\":\"OpenStreetMap.Mapnik\"}],\"trips\":[{\"dsType\":\"function\",\"dsLabel\":\"First point\",\"xKey\":{\"name\":\"f(x)\",\"label\":\"latitude\",\"type\":\"function\",\"funcBody\":\"var gpsData = [\\n37.771210000, -122.510960000,\\n 37.771990000, -122.497070000,\\n 37.772730000, -122.480740000,\\n 37.773360000, -122.466870000,\\n 37.774270000, -122.458520000,\\n 37.771980000, -122.454110000,\\n 37.768250000, -122.453380000,\\n 37.765920000, -122.456810000,\\n 37.765930000, -122.467680000,\\n 37.765500000, -122.477180000,\\n 37.765300000, -122.481660000,\\n 37.764780000, -122.493350000,\\n 37.764120000, -122.508360000,\\n 37.766410000, -122.510260000,\\n 37.770010000, -122.510830000,\\n 37.770980000, -122.510930000\\n];\\n let value = gpsData.indexOf(prevValue); \\nreturn gpsData[(value == -1 ? 0 : (value + 2) % gpsData.length)];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"yKey\":{\"name\":\"f(x)\",\"label\":\"longitude\",\"type\":\"function\",\"funcBody\":\"var gpsData = [\\n37.771210000, -122.510960000,\\n 37.771990000, -122.497070000,\\n 37.772730000, -122.480740000,\\n 37.773360000, -122.466870000,\\n 37.774270000, -122.458520000,\\n 37.771980000, -122.454110000,\\n 37.768250000, -122.453380000,\\n 37.765920000, -122.456810000,\\n 37.765930000, -122.467680000,\\n 37.765500000, -122.477180000,\\n 37.765300000, -122.481660000,\\n 37.764780000, -122.493350000,\\n 37.764120000, -122.508360000,\\n 37.766410000, -122.510260000,\\n 37.770010000, -122.510830000,\\n 37.770980000, -122.510930000\\n];\\n let value = gpsData.indexOf(prevValue); \\nreturn gpsData[(value == -1 ? 1 : (value + 2) % gpsData.length)];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"markerType\":\"shape\",\"markerShape\":{\"shape\":\"tripMarkerShape1\",\"size\":34,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerIcon\":{\"icon\":\"arrow_forward\",\"size\":48,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerImage\":{\"type\":\"image\",\"image\":\"/assets/markers/tripShape1.svg\",\"imageSize\":34},\"markerOffsetX\":0.5,\"markerOffsetY\":0.5,\"positionFunction\":\"return {x: origXPos, y: origYPos};\",\"markerClustering\":{\"enable\":false,\"zoomOnClick\":true,\"maxZoom\":null,\"maxClusterRadius\":80,\"zoomAnimation\":true,\"showCoverageOnHover\":true,\"spiderfyOnMaxZoom\":false,\"chunkedLoad\":false,\"lazyLoad\":true,\"useClusterMarkerColorFunction\":false,\"clusterMarkerColorFunction\":null},\"label\":{\"show\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}\"},\"tooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-0.5},\"click\":{\"type\":\"doNothing\"},\"edit\":{\"enabledActions\":[],\"snappable\":false},\"rotateMarker\":true,\"offsetAngle\":0,\"showPath\":true,\"pathStrokeWeight\":2,\"pathStrokeColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"usePathDecorator\":false,\"pathDecoratorSymbol\":\"arrowHead\",\"pathDecoratorSymbolSize\":10,\"pathDecoratorSymbolColor\":\"#307FE5\",\"pathDecoratorOffset\":20,\"pathEndDecoratorOffset\":20,\"pathDecoratorRepeat\":20,\"showPoints\":false,\"pointSize\":10,\"pointColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"pointTooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}

Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-1}}],\"markers\":[],\"polygons\":[],\"circles\":[],\"polylines\":[],\"additionalDataSources\":[],\"controlsPosition\":\"topleft\",\"zoomActions\":[\"scroll\",\"doubleClick\",\"controlButtons\"],\"scales\":[],\"dragModeButton\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"defaultCenterPosition\":\"0,0\",\"defaultZoomLevel\":null,\"minZoomLevel\":16,\"mapPageSize\":16384,\"mapActionButtons\":[],\"tripTimeline\":{\"showTimelineControl\":true,\"timeStep\":1000,\"speedOptions\":[1,5,10,15,25],\"showTimestamp\":true,\"timestampFormat\":{\"format\":\"yyyy-MM-dd HH:mm:ss\",\"lastUpdateAgo\":false,\"custom\":false,\"auto\":false},\"snapToRealLocation\":false,\"locationSnapFilter\":\"return true;\"},\"background\":{\"type\":\"color\",\"color\":\"#fff\",\"overlay\":{\"enabled\":false,\"color\":\"rgba(255,255,255,0.72)\",\"blur\":3}},\"padding\":\"8px\"},\"title\":\"Trip Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":null,\"mobileHeight\":null,\"configMode\":\"basic\",\"actions\":{},\"showTitleIcon\":false,\"titleIcon\":\"assistant_navigation\",\"iconColor\":\"#1F6BDD\",\"useDashboardTimewindow\":false,\"displayTimewindow\":true,\"titleFont\":{\"size\":null,\"sizeUnit\":\"px\",\"family\":null,\"weight\":null,\"style\":null,\"lineHeight\":null},\"titleColor\":null,\"titleTooltip\":\"\",\"widgetStyle\":{},\"widgetCss\":\"\",\"pageSize\":1024,\"units\":\"\",\"decimals\":null,\"noDataDisplayMessage\":\"\",\"timewindowStyle\":{\"showIcon\":false,\"iconSize\":\"24px\",\"icon\":null,\"iconPosition\":\"left\",\"font\":{\"size\":12,\"sizeUnit\":\"px\",\"family\":\"Roboto\",\"weight\":\"400\",\"style\":\"normal\",\"lineHeight\":\"16px\"},\"color\":\"rgba(0, 0, 0, 0.38)\",\"displayTypePrefix\":true},\"margin\":\"0px\",\"borderRadius\":\"0px\",\"iconSize\":\"24px\",\"enableDataExport\":false}" }, "resources": [ { diff --git a/application/src/main/java/org/thingsboard/server/actors/ruleChain/DefaultTbContext.java b/application/src/main/java/org/thingsboard/server/actors/ruleChain/DefaultTbContext.java index 59f0caacc5..7428df1e58 100644 --- a/application/src/main/java/org/thingsboard/server/actors/ruleChain/DefaultTbContext.java +++ b/application/src/main/java/org/thingsboard/server/actors/ruleChain/DefaultTbContext.java @@ -38,6 +38,7 @@ import org.thingsboard.rule.engine.util.TenantIdLoader; import org.thingsboard.script.api.ScriptType; import org.thingsboard.server.actors.ActorSystemContext; import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; @@ -527,7 +528,11 @@ public class DefaultTbContext implements TbContext, TbPeContext { if (attributes != null) { attributes.forEach(attributeKvEntry -> JacksonUtil.addKvEntry(entityNode, attributeKvEntry)); } - return attributesActionMsg(originator, ruleNodeId, scope, ATTRIBUTES_UPDATED, JacksonUtil.toString(entityNode)); + TbMsgMetaData tbMsgMetaData = getActionMetaData(ruleNodeId); + // The saved string values that read back as numbers stay strings for the nodes that parse the notification. + List typeCastDisabledKeys = JsonConverter.numericStringKeys(attributes); + tbMsgMetaData.putTypeCastDisabledKeys(typeCastDisabledKeys); + return attributesActionMsg(originator, tbMsgMetaData, scope, ATTRIBUTES_UPDATED, JacksonUtil.toString(entityNode)); } @Override @@ -537,11 +542,10 @@ public class DefaultTbContext implements TbContext, TbPeContext { if (keys != null) { keys.forEach(attrsArrayNode::add); } - return attributesActionMsg(originator, ruleNodeId, scope, ATTRIBUTES_DELETED, JacksonUtil.toString(entityNode)); + return attributesActionMsg(originator, getActionMetaData(ruleNodeId), scope, ATTRIBUTES_DELETED, JacksonUtil.toString(entityNode)); } - private TbMsg attributesActionMsg(EntityId originator, RuleNodeId ruleNodeId, String scope, TbMsgType actionMsgType, String msgData) { - TbMsgMetaData tbMsgMetaData = getActionMetaData(ruleNodeId); + private TbMsg attributesActionMsg(EntityId originator, TbMsgMetaData tbMsgMetaData, String scope, TbMsgType actionMsgType, String msgData) { tbMsgMetaData.putValue("scope", scope); HasRuleEngineProfile profile = getRuleEngineProfile(originator); return entityActionMsg(originator, tbMsgMetaData, msgData, actionMsgType, profile); diff --git a/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java b/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java index 029abec8f2..60ab8f3649 100644 --- a/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java +++ b/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.config; import jakarta.servlet.http.HttpServletRequest; @@ -17,8 +18,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.core.endpoint.PkceParameterNames; import org.springframework.security.oauth2.core.oidc.OidcScopes; import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames; +import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; import org.springframework.security.web.util.UrlUtils; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.util.UriComponents; @@ -50,7 +51,7 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza private static final String REGISTRATION_ID_URI_VARIABLE_NAME = "registrationId"; private static final char PATH_DELIMITER = '/'; - private final AntPathRequestMatcher authorizationRequestMatcher = new AntPathRequestMatcher( + private final PathPatternRequestMatcher authorizationRequestMatcher = PathPatternRequestMatcher.withDefaults().matcher( DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/{" + REGISTRATION_ID_URI_VARIABLE_NAME + "}"); private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder()); private final StringKeyGenerator secureKeyGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96); @@ -212,7 +213,7 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza Map uriVariables = new HashMap<>(); uriVariables.put("registrationId", clientRegistration.getRegistrationId()); - UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)) + UriComponents uriComponents = UriComponentsBuilder.fromUriString(UrlUtils.buildFullRequestUrl(request)) .replacePath(request.getContextPath()) .replaceQuery(null) .fragment(null) diff --git a/application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java b/application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java index c57cd26470..a0a9ebe038 100644 --- a/application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java +++ b/application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java @@ -1,10 +1,11 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.boot.autoconfigure.security.SecurityProperties; +import org.springframework.boot.security.autoconfigure.web.servlet.SecurityFilterProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; @@ -17,7 +18,7 @@ import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity @EnableMethodSecurity -@Order(SecurityProperties.BASIC_AUTH_ORDER) +@Order(SecurityFilterProperties.BASIC_AUTH_ORDER) @ConditionalOnExpression("'${service.type:null}'=='tb-rule-engine'") public class TbRuleEngineSecurityConfiguration { diff --git a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java index a064a5bbaf..7cddb8fc56 100644 --- a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java +++ b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java @@ -7,7 +7,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.security.SecurityProperties; +import org.springframework.boot.security.autoconfigure.web.servlet.SecurityFilterProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -61,7 +61,7 @@ import java.util.stream.Stream; @Configuration @EnableWebSecurity @EnableMethodSecurity -@Order(SecurityProperties.BASIC_AUTH_ORDER) +@Order(SecurityFilterProperties.BASIC_AUTH_ORDER) @TbCoreComponent public class ThingsboardSecurityConfiguration { diff --git a/application/src/main/java/org/thingsboard/server/controller/AdminController.java b/application/src/main/java/org/thingsboard/server/controller/AdminController.java index 8f6ff14d60..7b33cf7308 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AdminController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AdminController.java @@ -75,7 +75,9 @@ import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.token.JwtTokenFactory; import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.sync.vc.EntitiesVersionControlService; +import org.thingsboard.server.service.sync.vc.autocommit.DefaultTbAutoCommitSettingsService; import org.thingsboard.server.service.sync.vc.autocommit.TbAutoCommitSettingsService; +import org.thingsboard.server.service.sync.vc.repository.DefaultTbRepositorySettingsService; import org.thingsboard.server.service.system.SystemInfoService; import org.thingsboard.server.service.update.UpdateService; @@ -166,6 +168,10 @@ public class AdminController extends BaseController { } else { accessControlService.checkPermission(getCurrentUser(), Resource.WHITE_LABELING, Operation.WRITE); } + String key = adminSettings.getKey(); + if (DefaultTbRepositorySettingsService.SETTINGS_KEY.equals(key) || DefaultTbAutoCommitSettingsService.SETTINGS_KEY.equals(key)) { + throw new ThingsboardException("Settings with key '" + key + "' can be saved only through the version control API", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } adminSettings = checkNotNull(adminSettingsService.saveAdminSettings(tenantId, adminSettings)); if (adminSettings.getKey().equals(MAIL_SETTINGS_KEY)) { ((ObjectNode) adminSettings.getJsonValue()).remove("refreshToken"); diff --git a/application/src/main/java/org/thingsboard/server/controller/AiChatController.java b/application/src/main/java/org/thingsboard/server/controller/AiChatController.java index bbd9366776..6c05737fb3 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AiChatController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AiChatController.java @@ -65,6 +65,15 @@ class AiChatController extends BaseController { aiChatService.updateChat(chatId, request, user); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/{chatId}/stop") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void stopChat(@PathVariable UUID chatId) throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); + aiChatService.stopChat(chatId, user); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping public JsonNode listChats() throws ThingsboardException { @@ -73,6 +82,14 @@ class AiChatController extends BaseController { return aiChatService.listChats(user); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @GetMapping("/status") + public JsonNode listChatStatuses() throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.READ); + return aiChatService.listChatStatuses(user); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/{chatId}/messages") public JsonNode getChatMessages(@PathVariable UUID chatId) throws ThingsboardException { diff --git a/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java b/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java index 3bc73f3428..14fc76ee3a 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java @@ -92,6 +92,14 @@ public class AiSolutionController extends BaseController { return aiSolutionService.createSolution(solutionId, user); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/{solutionId}/stop") + public JsonNode stopSolution(@PathVariable UUID solutionId) throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); + return aiSolutionService.stopSolution(solutionId, user); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PutMapping("/{solutionId}/{dataKey}") public JsonNode updateData(@PathVariable UUID solutionId, @@ -110,6 +118,22 @@ public class AiSolutionController extends BaseController { aiSolutionService.clearStep(solutionId, step, user); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping(value = "/{solutionId}/update", consumes = MediaType.APPLICATION_JSON_VALUE) + public void updateSolution(@PathVariable UUID solutionId, @RequestBody JsonNode request) throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); + aiSolutionService.updateSolution(solutionId, request, user); + } + + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @GetMapping("/{solutionId}/progress") + public JsonNode getInstallProgress(@PathVariable UUID solutionId) throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.READ); + return aiSolutionService.getInstallProgress(solutionId, user); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PostMapping("/{solutionId}/install") public JsonNode installSolution(@PathVariable UUID solutionId, diff --git a/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java b/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java index 6bc50d1253..77d91794fe 100644 --- a/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java +++ b/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java @@ -116,6 +116,10 @@ public class ApiKeyController extends BaseController { UserId userId = new UserId(toUUID(userIdStr)); accessControlService.checkPermission(securityUser, Resource.API_KEY, Operation.READ); User user = checkUserId(userId, Operation.READ); + ApiKeyInfo keyOwner = new ApiKeyInfo(); + keyOwner.setTenantId(user.getTenantId()); + keyOwner.setUserId(userId); + accessControlService.checkPermission(securityUser, Resource.API_KEY, Operation.READ, null, keyOwner); return apiKeyService.findApiKeysByUserId(user.getTenantId(), userId, pageLink); } diff --git a/application/src/main/java/org/thingsboard/server/controller/BaseController.java b/application/src/main/java/org/thingsboard/server/controller/BaseController.java index e597cd192f..ac2750ee56 100644 --- a/application/src/main/java/org/thingsboard/server/controller/BaseController.java +++ b/application/src/main/java/org/thingsboard/server/controller/BaseController.java @@ -148,6 +148,8 @@ import org.thingsboard.server.common.data.menu.CustomMenuInfo; import org.thingsboard.server.common.data.mobile.app.MobileApp; import org.thingsboard.server.common.data.mobile.bundle.MobileAppBundle; import org.thingsboard.server.common.data.notification.targets.NotificationTarget; +import org.thingsboard.server.common.data.notification.template.NotificationTemplate; +import org.thingsboard.server.common.data.notification.template.NotificationTemplateConfig; import org.thingsboard.server.common.data.oauth2.OAuth2Client; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; @@ -894,6 +896,49 @@ public abstract class BaseController { } } + protected void checkReportUser(UserId userId) throws ThingsboardException { + if (!getCurrentUser().getId().equals(userId)) { + checkUserId(userId, Operation.IMPERSONATE); + } + } + + protected UserId resolveReportUser(UserId userId, boolean useCurrentUserCredentials) throws ThingsboardException { + SecurityUser currentUser = getCurrentUser(); + if (useCurrentUserCredentials && !currentUser.getId().equals(userId) && !canImpersonate(userId)) { + return currentUser.getId(); + } + checkReportUser(userId); + return userId; + } + + private boolean canImpersonate(UserId userId) throws ThingsboardException { + SecurityUser currentUser = getCurrentUser(); + User user = userService.findUserById(currentUser.getTenantId(), userId); + return user != null && currentUser.getTenantId().equals(user.getTenantId()) && + accessControlService.hasPermission(currentUser, Resource.USER, Operation.IMPERSONATE, userId, user); + } + + protected void checkTemplateReportUser(NotificationTemplate notificationTemplate) throws ThingsboardException { + NotificationTemplateConfig configuration = notificationTemplate != null ? notificationTemplate.getConfiguration() : null; + if (configuration != null && configuration.isAttachReport() && configuration.getUserId() != null) { + checkReportUser(configuration.getUserId()); + } + } + + protected void checkMsgReportUser(JsonNode msg) throws ThingsboardException { + if (msg == null) { + return; + } + checkReportUserIfPresent(msg.path("reportConfig").path("userId")); + checkReportUserIfPresent(msg.path("userId").path("id")); + } + + private void checkReportUserIfPresent(JsonNode reportUserId) throws ThingsboardException { + if (reportUserId.isTextual() && StringUtils.isNotBlank(reportUserId.asText())) { + checkReportUser(new UserId(toUUID(reportUserId.asText()))); + } + } + UserInfo checkUserInfoId(UserId userId, Operation operation) throws ThingsboardException { try { validateId(userId, id -> "Incorrect userId " + id); @@ -1097,7 +1142,11 @@ public abstract class BaseController { for (EntityId referencedEntityId : calculatedFieldConfig.getReferencedEntities()) { EntityType refEntityType = referencedEntityId.getEntityType(); switch (refEntityType) { - case TENANT -> {} + case TENANT -> { + if (!getTenantId().equals(referencedEntityId)) { + throw permissionDenied(); + } + } case CUSTOMER, ASSET, DEVICE -> checkEntityId(referencedEntityId, Operation.READ); default -> throw new IllegalArgumentException("Unsupported referenced entity type: '" + refEntityType + "'."); } @@ -1246,7 +1295,7 @@ public abstract class BaseController { protected EntityGroupInfo checkEntityGroupId(EntityGroupId entityGroupId, Operation operation) throws ThingsboardException { try { validateId(entityGroupId, id -> "Incorrect entityGroupId " + id); - EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), entityGroupId); + EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId); checkNotNull(entityGroup, "Entity group with id [" + entityGroupId + "] is not found"); accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), operation, entityGroup); return entityGroup; diff --git a/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java b/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java index 918c5dd8db..0aeae3a97d 100644 --- a/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java +++ b/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java @@ -29,6 +29,7 @@ import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.permission.Operation; +import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.dao.subscription.PlatformFeature; import org.thingsboard.server.queue.util.TbCoreComponent; @@ -61,6 +62,7 @@ public class DashboardReportController extends BaseController { private final SystemSecurityService systemSecurityService; public static final String DASHBOARD_ID = "dashboardId"; + public static final String USER_ID = "userId"; @ApiOperation(value = "Download dashboard report (downloadDashboardReport)", notes = "Generate and download a report from the specified dashboard. " + @@ -125,6 +127,14 @@ public class DashboardReportController extends BaseController { DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); checkDashboardInfoId(dashboardId, Operation.READ); + String strUserId = reportConfig.getUserId(); + checkParameter(USER_ID, strUserId); + UserId reportUserId = resolveReportUser(new UserId(toUUID(strUserId)), reportConfig.isUseCurrentUserCredentials()); + reportConfig.setUserId(reportUserId.toString()); + + if (Authority.CUSTOMER_USER.equals(getCurrentUser().getAuthority())) { + reportsServerEndpointUrl = null; + } dashboardReportService.generateReport(getTenantId(), reportConfig, reportsServerEndpointUrl, onSuccess(result), result::setErrorResult); } catch (Exception e) { result.setErrorResult(e); diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java b/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java index cdf2f171c8..40499b2d2f 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java @@ -57,6 +57,7 @@ import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.common.data.permission.ShareGroupRequest; import org.thingsboard.server.common.data.role.Role; +import org.thingsboard.server.common.data.role.RoleType; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.dao.owner.OwnerService; @@ -210,9 +211,8 @@ public class EntityGroupController extends AutoCommitController { @RequestBody EntityGroup entityGroup) throws Exception { SecurityUser currentUser = getCurrentUser(); checkEntityGroupType(entityGroup.getType()); - Operation operation = entityGroup.getId() == null ? Operation.CREATE : Operation.WRITE; EntityId parentEntityId = entityGroup.getOwnerId(); - if (operation == Operation.CREATE) { + if (entityGroup.getId() == null) { if (parentEntityId == null || parentEntityId.isNullUid()) { parentEntityId = currentUser.getOwnerId(); } else { @@ -221,14 +221,12 @@ public class EntityGroupController extends AutoCommitController { "Invalid entity group ownerId!", ThingsboardErrorCode.PERMISSION_DENIED); } } + EntityGroupInfo entityGroupInfo = new EntityGroupInfo(entityGroup, ownersCacheService.fetchOwnersHierarchy(getTenantId(), parentEntityId)); + accessControlService.checkEntityGroupInfoPermission(currentUser, Operation.CREATE, entityGroupInfo); } else { - validateEntityId(parentEntityId, id -> "Incorrect entity group ownerId " + id); + parentEntityId = checkEntityGroupId(entityGroup.getId(), Operation.WRITE).getOwnerId(); } - EntityGroupInfo entityGroupInfo = new EntityGroupInfo(entityGroup, ownersCacheService.fetchOwnersHierarchy(getTenantId(), parentEntityId)); - - accessControlService.checkEntityGroupInfoPermission(currentUser, operation, entityGroupInfo); - return tbEntityGroupService.save(getTenantId(), parentEntityId, entityGroup, getCurrentUser()); } @@ -967,7 +965,11 @@ public class EntityGroupController extends AutoCommitController { for (String strEntityGroupId : strEntityGroupIds) { entityGroupIds.add(new EntityGroupId(toUUID(strEntityGroupId))); } - return checkNotNull(entityGroupService.findEntityGroupEntityInfosByIds(tenantId, entityGroupIds, new PageLink(Integer.MAX_VALUE)).getData()); + List entityGroups = checkNotNull( + entityGroupService.findEntityGroupInfosByIds(tenantId, entityGroupIds, new PageLink(Integer.MAX_VALUE)).getData()); + return filterEntityGroupsByReadPermission(entityGroups).stream() + .map(entityGroup -> new EntityInfo(entityGroup.getId(), entityGroup.getName())) + .toList(); } @ApiOperation(value = "Get Owners (getOwners)", @@ -1145,7 +1147,8 @@ public class EntityGroupController extends AutoCommitController { @ApiOperation(value = "Share the Entity Group (shareEntityGroup)", notes = "Share the entity group with certain user group based on the provided Share Group Request. " + - "The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature." + "The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature. " + + "Each role in 'roleIds' must be a group role readable by the current user, and each of its operations must be granted to the current user for the entity group or its entities." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH + RBAC_GROUP_WRITE_CHECK) @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @PostMapping(value = "/entityGroup/{entityGroupId}/share") @@ -1165,21 +1168,25 @@ public class EntityGroupController extends AutoCommitController { EntityGroupInfo userGroup; if (shareGroupRequest.isAllUserGroup()) { - Optional userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(), - EntityType.USER, EntityGroup.GROUP_ALL_NAME); + Optional userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId()); if (userGroupOptional.isPresent()) { userGroup = userGroupOptional.get(); } else { throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } } else { - userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId()); + userGroup = checkNotNull(entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId())); } accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), Operation.WRITE, userGroup); - List roleIds; + List roles; if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) { - roleIds = shareGroupRequest.getRoleIds(); + roles = new ArrayList<>(); + for (RoleId roleId : shareGroupRequest.getRoleIds()) { + Role role = checkRoleId(roleId, Operation.READ); + checkGroupRoleAllowedForShare(role, entityGroup); + roles.add(role); + } } else { Role role; if (shareGroupRequest.isReadElseWrite()) { @@ -1187,15 +1194,15 @@ public class EntityGroupController extends AutoCommitController { } else { role = roleService.findOrCreateWriteEntityGroupRole(getTenantId(), getCurrentUser().getCustomerId()); } - roleIds = Collections.singletonList(role.getId()); + roles = Collections.singletonList(role); } - for (RoleId roleId : roleIds) { + for (Role role : roles) { GroupPermission groupPermission = new GroupPermission(); groupPermission.setTenantId(getTenantId()); groupPermission.setEntityGroupId(entityGroup.getId()); groupPermission.setEntityGroupType(entityGroup.getType()); - groupPermission.setRoleId(roleId); + groupPermission.setRoleId(role.getId()); groupPermission.setUserGroupId(userGroup.getId()); GroupPermission savedGroupPermission = checkNotNull(groupPermissionService.saveGroupPermission(getTenantId(), groupPermission)); @@ -1246,7 +1253,7 @@ public class EntityGroupController extends AutoCommitController { checkParameter("userGroupId", strUserGroupId); checkParameter("roleId", strRoleId); EntityGroupId userGroupId = new EntityGroupId(toUUID(strUserGroupId)); - EntityGroup userGroup = entityGroupService.findEntityGroupById(getTenantId(), userGroupId); + EntityGroup userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), userGroupId); if (userGroup == null) { throw new ThingsboardException("User group with requested id: " + userGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } @@ -1299,7 +1306,7 @@ public class EntityGroupController extends AutoCommitController { private EntityGroup resolveEntityGroup(UUID entityGroupUuid) throws ThingsboardException { EntityGroupId entityGroupId = new EntityGroupId(entityGroupUuid); - EntityGroup entityGroup = entityGroupService.findEntityGroupById(getTenantId(), entityGroupId); + EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId); if (entityGroup == null) { throw new ThingsboardException("Entity group with requested id: " + entityGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } @@ -1309,15 +1316,14 @@ public class EntityGroupController extends AutoCommitController { private EntityGroupInfo resolveUserGroup(ShareGroupRequest shareGroupRequest) throws ThingsboardException { EntityGroupInfo userGroup; if (shareGroupRequest.isAllUserGroup()) { - Optional userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(), - EntityType.USER, EntityGroup.GROUP_ALL_NAME); + Optional userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId()); if (userGroupOptional.isPresent()) { userGroup = userGroupOptional.get(); } else { throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } } else { - userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId()); + userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId()); } if (userGroup == null) { throw new ThingsboardException("Specified user group wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); @@ -1325,6 +1331,12 @@ public class EntityGroupController extends AutoCommitController { return userGroup; } + private Optional findAllUserGroup(EntityId ownerId) throws ThingsboardException { + TenantId tenantId = getTenantId(); + return entityGroupService.findEntityGroupInfoByTypeAndName(tenantId, ownerId, EntityType.USER, EntityGroup.GROUP_ALL_NAME) + .map(group -> entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, group.getId())); + } + private List resolveRoles(ShareGroupRequest shareGroupRequest) throws ThingsboardException { List roles = new ArrayList<>(1); if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) { @@ -1504,9 +1516,29 @@ public class EntityGroupController extends AutoCommitController { } } - private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set mergedOperations) throws ThingsboardException { + private void checkGroupRoleAllowedForShare(Role role, EntityGroup entityGroup) throws ThingsboardException { + if (role.getType() == RoleType.GENERIC) { + throw new ThingsboardException("Can't assign Generic Role to entity group!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + MergedUserPermissions userPermissions = getCurrentUser().getUserPermissions(); + Resource groupResource = Resource.groupResourceFromGroupType(entityGroup.getType()); + Resource entityResource = Resource.resourceFromEntityType(entityGroup.getType()); + for (Operation operation : toRoleOperations(role)) { + if (!userPermissions.hasGenericPermission(groupResource, operation) + && !userPermissions.hasGenericPermission(entityResource, operation) + && !userPermissions.hasGroupPermissions(entityGroup.getId(), operation)) { + throw permissionDenied(); + } + } + } + + private List toRoleOperations(Role role) { CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, Operation.class); - List roleOperations = JacksonUtil.readValue(role.getPermissions().toString(), collectionType); + return JacksonUtil.readValue(role.getPermissions().toString(), collectionType); + } + + private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set mergedOperations) throws ThingsboardException { + List roleOperations = toRoleOperations(role); if (!mergedOperations.isEmpty() && (mergedOperations.contains(Operation.ALL) || mergedOperations.containsAll(roleOperations))) { GroupPermission savedGroupPermission = groupPermissionService.saveGroupPermission(getTenantId(), new GroupPermission(getTenantId(), userGroup.getId(), role.getId(), entityGroup.getId(), entityGroup.getId().getEntityType(), false)); userPermissionsService.onGroupPermissionUpdated(savedGroupPermission); diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java index 4fe1ff0eb7..583afbaaa8 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java @@ -48,6 +48,7 @@ import org.thingsboard.server.service.security.model.SecurityUser; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutionException; @@ -132,6 +133,11 @@ public class EntityViewController extends BaseController { SecurityUser user = getCurrentUser(); return saveGroupEntity(entityView, strEntityGroupId, strEntityGroupIds, (entityView1, entityGroups) -> { try { + EntityView existingEntityView = entityView1.getId() == null ? null : + entityViewService.findEntityViewById(user.getTenantId(), entityView1.getId()); + if (existingEntityView == null || !hasSameSourceData(existingEntityView, entityView1)) { + checkEntityId(entityView1.getEntityId(), Operation.READ); + } return tbEntityViewService.save(entityView1, entityGroups, new NameConflictStrategy(nameConflictPolicy, uniquifySeparator, uniquifyStrategy), user); } catch (Exception e) { throw handleException(e); @@ -451,4 +457,11 @@ public class EntityViewController extends BaseController { return checkNotNull(entityViewTypes.get()); } + private static boolean hasSameSourceData(EntityView existing, EntityView entityView) { + return Objects.equals(existing.getEntityId(), entityView.getEntityId()) + && Objects.equals(existing.getKeys(), entityView.getKeys()) + && existing.getStartTimeMs() == entityView.getStartTimeMs() + && existing.getEndTimeMs() == entityView.getEndTimeMs(); + } + } diff --git a/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java b/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java index 9d26820989..71d2097da7 100644 --- a/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java +++ b/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java @@ -19,6 +19,7 @@ import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.group.EntityGroupInfo; import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.GroupPermissionId; @@ -116,6 +117,7 @@ public class GroupPermissionController extends BaseController { .checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.CREATE, null, groupPermission); } else { oldGroupPermission = checkGroupPermissionId(groupPermission.getId(), Operation.WRITE); + checkGroupPermissionManageable(oldGroupPermission); } if (groupPermission.isPublic()) { @@ -168,17 +170,7 @@ public class GroupPermissionController extends BaseController { try { GroupPermissionId groupPermissionId = new GroupPermissionId(toUUID(strGroupPermissionId)); GroupPermission groupPermission = checkGroupPermissionId(groupPermissionId, Operation.DELETE); - if (groupPermission.isPublic()) { - throw permissionDenied(); - } - - checkRoleId(groupPermission.getRoleId(), Operation.READ); - if (groupPermission.getUserGroupId() != null && !groupPermission.getUserGroupId().isNullUid()) { - checkEntityGroupId(groupPermission.getUserGroupId(), Operation.WRITE); - } - if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) { - checkEntityGroupId(groupPermission.getEntityGroupId(), Operation.WRITE); - } + checkGroupPermissionManageable(groupPermission); groupPermissionService.deleteGroupPermission(getTenantId(), groupPermissionId); userPermissionsService.onGroupPermissionDeleted(groupPermission); @@ -218,7 +210,8 @@ public class GroupPermissionController extends BaseController { @RequestBody List permissions) throws ThingsboardException, ExecutionException, InterruptedException { TenantId tenantId = getCurrentUser().getTenantId(); accessControlService.checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.READ); - List permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, permissions).get(); + List readablePermissions = permissions.stream().filter(this::isReadableEntityGroup).toList(); + List permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, readablePermissions).get(); return applyPermissionInfo(permissionInfoList); } @@ -255,6 +248,32 @@ public class GroupPermissionController extends BaseController { return groupPermissions; } + private void checkGroupPermissionManageable(GroupPermission groupPermission) throws ThingsboardException { + if (groupPermission.isPublic()) { + throw permissionDenied(); + } + checkRoleId(groupPermission.getRoleId(), Operation.READ); + if (groupPermission.getUserGroupId() != null && !groupPermission.getUserGroupId().isNullUid()) { + checkEntityGroupId(groupPermission.getUserGroupId(), Operation.WRITE); + } + if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) { + checkEntityGroupId(groupPermission.getEntityGroupId(), Operation.WRITE); + } + } + + private boolean isReadableEntityGroup(GroupPermission groupPermission) { + EntityGroupId entityGroupId = groupPermission.getEntityGroupId(); + if (entityGroupId == null || entityGroupId.isNullUid()) { + return true; + } + try { + EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId); + return entityGroup != null && accessControlService.hasEntityGroupInfoPermission(getCurrentUser(), Operation.READ, entityGroup); + } catch (ThingsboardException e) { + return false; + } + } + private boolean isAlreadyAssigned(TenantId tenantId, GroupPermission groupPermission) { if (groupPermission.getEntityGroupId() != null) { return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupIdAndUserGroupIdAndRoleId(tenantId, diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index b6d01d3342..5dc2a0ba9c 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -31,7 +31,6 @@ import java.util.Map; import java.util.UUID; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.permission.Operation; -import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.dao.device.DeviceConnectivityHostSource; import org.thingsboard.server.dao.device.DeviceConnectivityService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; @@ -39,9 +38,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.system.ResolvedBaseUrl; import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.iot_hub.DevicePackageEntityState; -import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService; -import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest; -import org.thingsboard.server.service.iot_hub.DeviceUpdateResult; +import org.thingsboard.server.service.iot_hub.DevicePackageService; +import org.thingsboard.server.service.iot_hub.DevicePackageRequest; +import org.thingsboard.server.service.iot_hub.DevicePackageResult; import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities; import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.InstallPlan; @@ -58,7 +57,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService; public class IotHubController extends BaseController { private final IotHubService iotHubService; - private final DevicePackageUpdateService devicePackageUpdateService; + private final DevicePackageService devicePackageService; private final IotHubInstalledItemService iotHubInstalledItemService; private final DeviceConnectivityService deviceConnectivityService; private final SystemSecurityService systemSecurityService; @@ -103,21 +102,29 @@ public class IotHubController extends BaseController { return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/device/install") + @ResponseBody + public DevicePackageResult installDevicePackage(@RequestBody DevicePackageRequest request) throws ThingsboardException { + checkAllPermissions(); + return devicePackageService.install(getCurrentUser(), request); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/installedItems/{installedItemId}/deviceUpdate/check") @ResponseBody public List checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException { checkAllPermissions(); - return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); + return devicePackageService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PostMapping("/installedItems/{installedItemId}/deviceUpdate") @ResponseBody - public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId, - @RequestBody DeviceUpdateRequest request) throws ThingsboardException { + public DevicePackageResult updateDevicePackage(@PathVariable UUID installedItemId, + @RequestBody DevicePackageRequest request) throws ThingsboardException { checkAllPermissions(); - return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); + return devicePackageService.update(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") @@ -146,6 +153,25 @@ public class IotHubController extends BaseController { return iotHubInstalledItemService.findByTenantId(getTenantId(), itemTypes, itemId, pageLink); } + /** + * The installed items with an update in IoT Hub. The body is what the browser got from IoT Hub on Check for updates: + * the published version id by item id. A POST, as the map of a tenant with many items doesn't fit in a URL. + */ + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/installedItems/withUpdates") + @ResponseBody + public PageData getInstalledItemsWithUpdates(@RequestParam int pageSize, + @RequestParam int page, + @RequestParam(required = false) String textSearch, + @RequestParam(required = false) String sortProperty, + @RequestParam(required = false) String sortOrder, + @RequestParam(required = false) List itemTypes, + @RequestBody Map publishedVersionIds) throws ThingsboardException { + checkAllPermissions(); + PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); + return iotHubInstalledItemService.findByTenantIdWithUpdates(getTenantId(), itemTypes, publishedVersionIds, pageLink); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/installedItems/count") @ResponseBody @@ -197,7 +223,7 @@ public class IotHubController extends BaseController { } private void checkAllPermissions() throws ThingsboardException { - if (!getCurrentUser().getUserPermissions().hasGenericPermission(Resource.ALL, Operation.ALL)) { + if (!getCurrentUser().getUserPermissions().hasGenericPermissionExceptAi(Operation.ALL)) { throw new ThingsboardException("You don't have permissions to use solution templates!", ThingsboardErrorCode.PERMISSION_DENIED); } diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java index 75533b0e79..9d2781c3bc 100644 --- a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java +++ b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java @@ -22,6 +22,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.rule.engine.api.NotificationCenter; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; @@ -38,6 +39,7 @@ import org.thingsboard.server.common.data.notification.NotificationRequestPrevie import org.thingsboard.server.common.data.notification.NotificationType; import org.thingsboard.server.common.data.notification.info.AddonAccessErrorNotificationInfo; import org.thingsboard.server.common.data.notification.info.AddonAccessRequestNotificationInfo; +import org.thingsboard.server.common.data.notification.info.AiCreditsLimitIncreaseRequestNotificationInfo; import org.thingsboard.server.common.data.notification.info.EntitiesLimitIncreaseRequestNotificationInfo; import org.thingsboard.server.common.data.notification.info.NotificationInfo; import org.thingsboard.server.common.data.notification.info.PlanUpgradeRequestNotificationInfo; @@ -72,15 +74,20 @@ import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.translation.TranslationService; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION; @@ -114,6 +121,8 @@ public class NotificationController extends BaseController { private final SystemSecurityService systemSecurityService; private final SubscriptionService subscriptionService; + private final Map aiCreditsRequests = new ConcurrentHashMap<>(); + @ApiOperation(value = "Get notifications (getNotifications)", notes = "Returns the page of notifications for current user." + NEW_LINE + PAGE_DATA_PARAMETERS + @@ -274,6 +283,9 @@ public class NotificationController extends BaseController { } notificationRequest.setTenantId(user.getTenantId()); checkEntity(notificationRequest.getId(), notificationRequest, NOTIFICATION); + checkTemplateReportUser(notificationRequest.getTemplateId() != null ? + notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRequest.getTemplateId()) : + notificationRequest.getTemplate()); List targets = notificationRequest.getTargets().stream() .map(NotificationTargetId::new) .toList(); @@ -496,6 +508,53 @@ public class NotificationController extends BaseController { } } + @ApiOperation(value = "Send AI credits limit increase request notification to System administrators (sendAiCreditsLimitIncreaseRequest)", + notes = "Send AI credits limit increase request notification by Tenant Administrator to System administrators. " + + "TENANT asks for a higher monthly limit of the tenant, POOL for more AI credits for the whole installation. " + + "A request for the same limit is sent once a month." + TENANT_AUTHORITY_PARAGRAPH) + @PostMapping("/notification/aiCreditsLimitIncreaseRequest") + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')") + public void sendAiCreditsLimitIncreaseRequest(@Parameter(description = "Limit to increase", schema = @Schema(allowableValues = {"TENANT", "POOL"})) + @RequestParam(defaultValue = "TENANT") String limitType, + @AuthenticationPrincipal SecurityUser user, + HttpServletRequest request) throws Exception { + boolean pool = "POOL".equals(limitType); + if (!pool && !"TENANT".equals(limitType)) { + throw new IllegalArgumentException("Unsupported limit type: " + limitType); + } + long month = ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1).toInstant().toEpochMilli(); + String requestKey = user.getTenantId().getId() + ":" + limitType; + if (Objects.equals(aiCreditsRequests.put(requestKey, month), month)) { + return; + } + try { + NotificationTarget sysAdmins = notificationTargetService.findNotificationTargetsByTenantIdAndUsersFilterType(TenantId.SYS_TENANT_ID, UsersFilterType.SYSTEM_ADMINISTRATORS) + .stream().findFirst() + .orElseThrow(() -> new IllegalArgumentException("Notification target for 'System administrators' not found")); + String baseUrl = systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request); + Tenant tenant = tenantService.findTenantById(user.getTenantId()); + String limitDescription; + if (pool) { + limitDescription = "all AI credits of this installation's license"; + } else { + long limit = tenantProfileCache.get(user.getTenantId()).getDefaultProfileConfiguration().getMaxAiCredits(); + limitDescription = String.format("its monthly limit of %,d AI credits", limit); + } + NotificationInfo info = AiCreditsLimitIncreaseRequestNotificationInfo.builder() + .userEmail(user.getEmail()) + .tenantName(tenant != null ? tenant.getName() : user.getTenantId().toString()) + .limitDescription(limitDescription) + .increaseLimitActionLabel(pool ? "Add credits" : "Set new limit") + .increaseLimitLink(pool ? "/license" : "/tenants/" + user.getTenantId()) + .baseUrl(baseUrl) + .build(); + notificationCenter.sendSystemNotification(TenantId.SYS_TENANT_ID, sysAdmins.getId(), NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST, info); + } catch (Exception e) { + aiCreditsRequests.remove(requestKey, month); + throw e; + } + } + @ApiOperation(value = "Get notification request preview (getNotificationRequestPreview)", notes = "Returns preview for notification request." + NEW_LINE + "`processedTemplates` shows how the notifications for each delivery method will look like " + diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java index 81194b517b..ae4f824aa2 100644 --- a/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java +++ b/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java @@ -20,17 +20,21 @@ import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.NotificationRuleId; +import org.thingsboard.server.common.data.id.NotificationTargetId; import org.thingsboard.server.common.data.notification.rule.NotificationRule; import org.thingsboard.server.common.data.notification.rule.NotificationRuleInfo; import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerType; +import org.thingsboard.server.common.data.notification.template.NotificationTemplate; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.dao.notification.NotificationRuleService; +import org.thingsboard.server.dao.notification.NotificationTemplateService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.model.SecurityUser; +import java.util.List; import java.util.UUID; import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION; @@ -52,6 +56,7 @@ import static org.thingsboard.server.controller.ControllerConstants.SYSTEM_OR_TE public class NotificationRuleController extends BaseController { private final NotificationRuleService notificationRuleService; + private final NotificationTemplateService notificationTemplateService; @ApiOperation(value = "Save notification rule (saveNotificationRule)", notes = "Creates or updates notification rule. " + NEW_LINE + @@ -106,11 +111,23 @@ public class NotificationRuleController extends BaseController { @AuthenticationPrincipal SecurityUser user) throws Exception { notificationRule.setTenantId(user.getTenantId()); checkEntity(notificationRule.getId(), notificationRule, NOTIFICATION); + if (notificationRule.getTemplateId() != null) { + checkTemplateReportUser(notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRule.getTemplateId())); + } NotificationRuleTriggerType triggerType = notificationRule.getTriggerType(); if ((user.isTenantAdmin() && !triggerType.isTenantLevel()) || (user.isSystemAdmin() && triggerType.isTenantLevel())) { throw new IllegalArgumentException("Trigger type " + triggerType + " is not available"); } + NotificationTemplate template = notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRule.getTemplateId()); + if (template == null || !(template.getTenantId().equals(user.getTenantId()) || template.getTenantId().isSysTenantId())) { + throw new IllegalArgumentException("Notification template not found"); + } + for (List targets : notificationRule.getRecipientsConfig().getTargetsTable().values()) { + for (UUID targetId : targets) { + checkNotificationTargetId(new NotificationTargetId(targetId), Operation.READ); + } + } return doSaveAndLog(EntityType.NOTIFICATION_RULE, notificationRule, notificationRuleService::saveNotificationRule); } diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java index 8f1ead6449..309fe60cb5 100644 --- a/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java +++ b/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java @@ -106,6 +106,7 @@ public class NotificationTemplateController extends BaseController { public NotificationTemplate saveNotificationTemplate(@RequestBody @Valid NotificationTemplate notificationTemplate) throws Exception { notificationTemplate.setTenantId(getTenantId()); checkEntity(notificationTemplate.getId(), notificationTemplate, NOTIFICATION); + checkTemplateReportUser(notificationTemplate); return doSaveAndLog(EntityType.NOTIFICATION_TEMPLATE, notificationTemplate, notificationTemplateService::saveNotificationTemplate); } diff --git a/application/src/main/java/org/thingsboard/server/controller/ReportController.java b/application/src/main/java/org/thingsboard/server/controller/ReportController.java index 12278a78d0..f7c9d4c3a3 100644 --- a/application/src/main/java/org/thingsboard/server/controller/ReportController.java +++ b/application/src/main/java/org/thingsboard/server/controller/ReportController.java @@ -248,9 +248,10 @@ public class ReportController extends BaseController { public ResponseEntity testReportAndDownload(@RequestBody ReportRequest reportRequest) throws Exception { checkFeatureAllowed(PlatformFeature.REPORTING); SecurityUser currentUser = getCurrentUser(); - UserId userId = StringUtils.isNotEmpty(reportRequest.getUserId()) ? new UserId(UUID.fromString(reportRequest.getUserId())) : getCurrentUser().getId(); - EntityId userOwnerId = ownersCacheService.getOwner(currentUser.getTenantId(), userId); + UserId userId = StringUtils.isNotEmpty(reportRequest.getUserId()) ? new UserId(toUUID(reportRequest.getUserId())) : currentUser.getId(); + checkReportUser(userId); checkUserOwnerPermission(currentUser, userId); + EntityId userOwnerId = ownersCacheService.getOwner(currentUser.getTenantId(), userId); AccessJwtToken accessToken = systemSecurityService.createUserAccessToken(currentUser.getTenantId(), userId); ReportTemplateConfig configuration = reportRequest.getReportTemplateConfig(); if (configuration == null) { @@ -301,7 +302,8 @@ public class ReportController extends BaseController { SecurityUser currentUser = getCurrentUser(); UserId userId; if (StringUtils.isNotEmpty(reportRequest.getUserId())) { - userId = new UserId(UUID.fromString(reportRequest.getUserId())); + userId = new UserId(toUUID(reportRequest.getUserId())); + checkReportUser(userId); checkUserOwnerPermission(currentUser, userId); } else { userId = currentUser.getId(); diff --git a/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java b/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java index 2c662da1cb..e8608d1898 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java +++ b/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java @@ -158,8 +158,7 @@ public class RuleEngineController extends BaseController { } else { entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr); } - //Check that this is a valid JSON - JacksonUtil.toJsonNode(requestBody); + checkMsgReportUser(JacksonUtil.toJsonNode(requestBody)); final DeferredResult response = new DeferredResult<>(); accessValidator.validate(currentUser, Operation.WRITE, entityId, new HttpValidationCallback(response, new FutureCallback>() { @Override diff --git a/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java b/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java index 8cc02b2eb8..bb2624509d 100644 --- a/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java +++ b/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.controller; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -21,7 +22,9 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EdgeId; @@ -161,11 +164,26 @@ public class SchedulerEventController extends BaseController { private void checkEventConfigPermissions(SchedulerEvent schedulerEvent) throws ThingsboardException { if (GENERATE_REPORT.equals(schedulerEvent.getType())) { SecurityUser currentUser = getCurrentUser(); - ReportConfig reportConfig = checkNotNull(JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class), - "Report scheduler event configuration should be specified!"); + ReportConfig reportConfig = JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class); + if (reportConfig == null) { + throw new ThingsboardException("Report scheduler event configuration should be specified!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } checkReportTemplateId(reportConfig.getReportTemplateId(), Operation.READ); - UserId reportUserId = checkNotNull(reportConfig.getUserId(), "Report user must be specified!"); + UserId reportUserId = reportConfig.getUserId(); + if (reportUserId == null) { + throw new ThingsboardException("Report user must be specified!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + checkReportUser(reportUserId); checkUserOwnerPermission(currentUser, reportUserId); + } else if (schedulerEvent.getConfiguration() != null) { + if (schedulerEvent.getConfiguration().path("msgBody").path("reportConfig") instanceof ObjectNode reportConfig + && reportConfig.path("useCurrentUserCredentials").asBoolean(false) + && reportConfig.path("userId").isTextual() + && StringUtils.isNotBlank(reportConfig.get("userId").asText())) { + UserId reportUserId = resolveReportUser(new UserId(toUUID(reportConfig.get("userId").asText())), true); + reportConfig.put("userId", reportUserId.toString()); + } + checkMsgReportUser(schedulerEvent.getConfiguration().path("msgBody")); } } diff --git a/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java b/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java index 3122c978d1..945bb50108 100644 --- a/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java +++ b/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java @@ -64,6 +64,9 @@ public class SelfRegistrationController extends BaseController { if (selfRegistrationParams.getNotificationRecipient() != null) { checkNotificationTargetId(selfRegistrationParams.getNotificationRecipient(), Operation.READ); } + if (selfRegistrationParams.getDomainId() != null) { + checkDomainId(selfRegistrationParams.getDomainId(), Operation.READ); + } if (Authority.TENANT_ADMIN.equals(authority)) { savedSelfRegistrationParams = whiteLabelingService.saveTenantSelfRegistrationParams(getTenantId(), selfRegistrationParams); JsonNode privacyPolicyNode = whiteLabelingService.getTenantPrivacyPolicy(securityUser.getTenantId()); diff --git a/application/src/main/java/org/thingsboard/server/controller/SignUpController.java b/application/src/main/java/org/thingsboard/server/controller/SignUpController.java index 305385a8e3..7a3cf1eec2 100644 --- a/application/src/main/java/org/thingsboard/server/controller/SignUpController.java +++ b/application/src/main/java/org/thingsboard/server/controller/SignUpController.java @@ -79,7 +79,6 @@ import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.UserPrincipal; import org.thingsboard.server.service.security.model.token.JwtTokenFactory; import org.thingsboard.server.service.security.system.SystemSecurityService; -import org.thingsboard.server.utils.MiscUtils; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -209,7 +208,7 @@ public class SignUpController extends BaseController { UserCredentials savedUserCredentials = saveUserCredentials(savedUser, signUpRequest); try { - sendEmailVerification(tenantId, request, savedUserCredentials, email, null, signUpRequest.getPkgName(), signUpRequest.getPlatform()); + sendEmailVerification(tenantId, request, savedUser, savedUserCredentials, email, signUpRequest.getPkgName(), signUpRequest.getPlatform()); } catch (ThingsboardException e) { customerService.deleteCustomer(tenantId, savedCustomer.getId()); throw e; @@ -227,11 +226,9 @@ public class SignUpController extends BaseController { return SignUpResult.SUCCESS; } - private void sendEmailVerification(TenantId tenantId, HttpServletRequest request, UserCredentials userCredentials, - String targetEmail, String baseUrl, String pkgName, PlatformType platformType) throws ThingsboardException { - if (baseUrl == null) { - baseUrl = MiscUtils.constructBaseUrl(request); - } + private void sendEmailVerification(TenantId tenantId, HttpServletRequest request, User user, UserCredentials userCredentials, + String targetEmail, String pkgName, PlatformType platformType) throws ThingsboardException { + String baseUrl = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), request); String activationLink = String.format("%s/api/noauth/activateEmail?emailCode=%s", baseUrl, userCredentials.getActivateToken()); if (!StringUtils.isEmpty(pkgName)) { checkNotNull(platformType); @@ -265,7 +262,7 @@ public class SignUpController extends BaseController { } @ApiOperation(value = "Resend Activation Email (resendEmailActivation)", - notes = "Request to resend the activation email for the user. Checks that user was not activated yet.") + notes = "Request to resend the activation email for a user who signed up through this domain or mobile application and has not verified the email yet.") @PostMapping(value = "/noauth/resendEmailActivation") public void resendEmailActivation( @Parameter(description = "Email of the user.", required = true, example = "john.doe@company.com") @@ -285,19 +282,17 @@ public class SignUpController extends BaseController { } User existingUser = userService.findUserByEmail(TenantId.SYS_TENANT_ID, email); - if (existingUser != null) { - UserCredentials credentials = userService.findUserCredentialsByUserId(existingUser.getTenantId(), existingUser.getId()); - if (credentials.isEnabled()) { - throw new DataValidationException("User with email '" + existingUser.getEmail() + "' " - + " is already active!"); - } else { - credentials = userService.checkUserActivationToken(tenantId, credentials); - sendEmailVerification(tenantId, request, credentials, email, null, pkgName, platform); - } - } else { + if (existingUser == null || !tenantId.equals(existingUser.getTenantId())) { throw new DataValidationException("User with email '" + email + "' " + " is not registered!"); } + UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, existingUser.getId()); + if (credentials.isEnabled() || credentials.getActivateToken() == null || credentials.getPassword() == null) { + throw new DataValidationException("User with email '" + existingUser.getEmail() + "' " + + " is already active!"); + } + credentials = userService.checkUserActivationToken(tenantId, credentials); + sendEmailVerification(tenantId, request, existingUser, credentials, email, pkgName, platform); } @ApiOperation(value = "Activate User using code from Email (activateEmail)", @@ -395,16 +390,19 @@ public class SignUpController extends BaseController { if (userCredentials.getPassword() == null) { throw new ThingsboardException("Unable to activate user!", ThingsboardErrorCode.PERMISSION_DENIED); } + User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId()); + if (user == null || !tenantId.equals(user.getTenantId())) { + throw new ThingsboardException("Invalid email code!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } String encodedPassword = userCredentials.getPassword(); UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, emailCode, encodedPassword); - User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId()); long acceptedTs = System.currentTimeMillis(); user.setPrivacyPolicyAccepted(acceptedTs); user.setTermsOfUseAccepted(acceptedTs); user = userService.saveUser(tenantId, user); UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal, getMergedUserPermissions(user, false)); - String baseUrl = MiscUtils.constructBaseUrl(request); + String baseUrl = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), request); String loginUrl; if (!StringUtils.isEmpty(pkgName)) { loginUrl = UriComponentsBuilder.fromUriString(baseUrl).path("/api/noauth/login") @@ -574,10 +572,11 @@ public class SignUpController extends BaseController { List permissions = selfRegistrationParams.getPermissions(); for (GroupPermission permission : permissions) { + permission.setId(null); permission.setTenantId(tenantId); permission.setUserGroupId(usersEntityGroup.getId()); if (permission.getEntityGroupId() != null) { - EntityGroup entityGroup = entityGroupService.findEntityGroupById(tenantId, permission.getEntityGroupId()); + EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, permission.getEntityGroupId()); if (entityGroup != null) { permission.setEntityGroupType(entityGroup.getType()); groupPermissionService.saveGroupPermission(tenantId, permission); diff --git a/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java b/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java index 7196fe5c92..2bf6be25da 100644 --- a/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java +++ b/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java @@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.UsageInfo; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.permission.Operation; -import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.dao.usage.UsageInfoService; import org.thingsboard.server.queue.util.TbCoreComponent; @@ -30,7 +29,7 @@ public class UsageInfoController extends BaseController { @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping(value = "/usage") public UsageInfo getTenantUsageInfo() throws ThingsboardException { - if (!getMergedUserPermissions(getCurrentUser(), false).hasGenericPermission(Resource.ALL, Operation.READ)) { + if (!getMergedUserPermissions(getCurrentUser(), false).hasGenericPermissionExceptAi(Operation.READ)) { throw new ThingsboardException("You don't have permission to read UsageInfo!", PERMISSION_DENIED); } return checkNotNull(usageInfoService.getUsageInfo(getCurrentUser().getTenantId())); diff --git a/application/src/main/java/org/thingsboard/server/controller/UserController.java b/application/src/main/java/org/thingsboard/server/controller/UserController.java index e27dc20357..25dff3c9d4 100644 --- a/application/src/main/java/org/thingsboard/server/controller/UserController.java +++ b/application/src/main/java/org/thingsboard/server/controller/UserController.java @@ -292,7 +292,7 @@ public class UserController extends BaseController { HttpServletRequest request) throws ThingsboardException { SecurityUser securityUser = getCurrentUser(); User user = checkNotNull(userService.findUserByEmail(securityUser.getTenantId(), email)); - accessControlService.checkPermission(securityUser, Resource.USER, Operation.READ, user.getId(), user); + accessControlService.checkPermission(securityUser, Resource.USER, Operation.WRITE, user.getId(), user); UserActivationLink activationLink = tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), user.getId(), request); try { @@ -323,7 +323,7 @@ public class UserController extends BaseController { HttpServletRequest request) throws ThingsboardException { checkParameter(USER_ID, strUserId); UserId userId = new UserId(toUUID(strUserId)); - checkUserId(userId, Operation.READ); + checkUserId(userId, Operation.WRITE); SecurityUser securityUser = getCurrentUser(); return tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), userId, request); } diff --git a/application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java b/application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java new file mode 100644 index 0000000000..643def19d2 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.exception; + +import lombok.Getter; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; + +@Getter +public class AiCreditsExceededException extends ThingsboardRuntimeException { + + public static final String TENANT_LIMIT = "TENANT"; + + private final String limitType; + + public AiCreditsExceededException(String limitType) { + super("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS); + this.limitType = limitType; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java b/application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java new file mode 100644 index 0000000000..19996a2c73 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.exception; + +import io.swagger.v3.oas.annotations.media.Schema; +import org.springframework.http.HttpStatus; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; + +@Schema +public class ThingsboardAiCreditsExceededResponse extends ThingsboardErrorResponse { + + private final String aiCreditsLimit; + + protected ThingsboardAiCreditsExceededResponse(String message, String aiCreditsLimit) { + super(message, ThingsboardErrorCode.TOO_MANY_REQUESTS, HttpStatus.TOO_MANY_REQUESTS); + this.aiCreditsLimit = aiCreditsLimit; + } + + public static ThingsboardAiCreditsExceededResponse of(String message, String aiCreditsLimit) { + return new ThingsboardAiCreditsExceededResponse(message, aiCreditsLimit); + } + + @Schema(description = "Which AI credits limit is used up: TENANT for the tenant's monthly limit", accessMode = Schema.AccessMode.READ_ONLY) + public String getAiCreditsLimit() { + return aiCreditsLimit; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java b/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java index a522c03652..4923bbb451 100644 --- a/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java +++ b/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java @@ -12,7 +12,7 @@ import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.exception.ExceptionUtils; import org.hibernate.exception.ConstraintViolationException; -import org.springframework.boot.web.servlet.error.ErrorController; +import org.springframework.boot.webmvc.error.ErrorController; import org.springframework.dao.DataAccessException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -93,6 +93,7 @@ public class ThingsboardErrorResponseHandler extends ResponseEntityExceptionHand errorCodeToStatusMap.put(ThingsboardErrorCode.ENTITIES_LIMIT_EXCEEDED, HttpStatus.FORBIDDEN); errorCodeToStatusMap.put(ThingsboardErrorCode.VERSION_CONFLICT, HttpStatus.CONFLICT); errorCodeToStatusMap.put(ThingsboardErrorCode.SETUP_INCOMPLETE, HttpStatus.LOCKED); + errorCodeToStatusMap.put(ThingsboardErrorCode.SERVICE_UNAVAILABLE, HttpStatus.SERVICE_UNAVAILABLE); } private static ThingsboardErrorCode statusToErrorCode(HttpStatus status) { @@ -198,6 +199,12 @@ public class ThingsboardErrorResponseHandler extends ResponseEntityExceptionHand } private void handleThingsboardRuntimeException(ThingsboardRuntimeException thingsboardRuntimeException, HttpServletResponse response) throws IOException { + if (thingsboardRuntimeException instanceof AiCreditsExceededException aiCreditsExceeded) { + response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); + JacksonUtil.writeValue(response.getWriter(), + ThingsboardAiCreditsExceededResponse.of(aiCreditsExceeded.getMessage(), aiCreditsExceeded.getLimitType())); + return; + } ThingsboardErrorCode errorCode = thingsboardRuntimeException.getErrorCode(); HttpStatus status = errorCodeToStatus(errorCode); response.setStatus(status.value()); diff --git a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java index 07d14417bd..5a5d08f6c7 100644 --- a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java +++ b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java @@ -226,7 +226,7 @@ public class ThingsboardInstallService { } catch (EntityCapExceededException e) { // A deliberate pre-flight refusal: report the plain policy message, not an unexpected failure. throw new ThingsboardInstallException(e.getMessage(), e); - } catch (Exception e) { + } catch (Throwable e) { log.error("Unexpected error during ThingsBoard installation!", e); throw new ThingsboardInstallException("Unexpected error during ThingsBoard installation!", e); } finally { diff --git a/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java b/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java index f3b60383eb..174fe9cb85 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java @@ -17,6 +17,7 @@ import org.thingsboard.server.common.data.ApiUsageRecordKey; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.stats.TbApiUsageReportClient; +import org.thingsboard.server.exception.AiCreditsExceededException; import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.ai.transport.TbAiChannelRejectedException; @@ -152,9 +153,9 @@ class DefaultTbAiService implements TbAiService { private static String toUserFriendlyMessage(Throwable e) { if (e instanceof TimeoutException) { - return "Request timed out"; + return TbAiOperations.TIMED_OUT_MESSAGE; } else if (e instanceof TbAiChannelUnavailableException) { - return "Service unavailable"; + return TbAiOperations.UNAVAILABLE_MESSAGE; } else if (e instanceof TbAiChannelRejectedException || e instanceof ThingsboardRuntimeException) { return e.getMessage(); } @@ -176,13 +177,15 @@ class DefaultTbAiService implements TbAiService { case 404 -> ThingsboardErrorCode.ITEM_NOT_FOUND; case 409 -> ThingsboardErrorCode.VERSION_CONFLICT; case 429 -> ThingsboardErrorCode.TOO_MANY_REQUESTS; + case 401, 403 -> ThingsboardErrorCode.PERMISSION_DENIED; + case 502, 503, 504 -> ThingsboardErrorCode.SERVICE_UNAVAILABLE; default -> ThingsboardErrorCode.GENERAL; }; } private void checkApiUsage(SecurityUser user) { if (!apiUsageStateService.getApiUsageState(user.getTenantId()).isAiEnabled()) { - throw new ThingsboardRuntimeException("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS); + throw new AiCreditsExceededException(AiCreditsExceededException.TENANT_LIMIT); } } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java b/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java index 2eae20227a..c355f38b05 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java @@ -15,8 +15,12 @@ public interface AiChatService { void updateChat(UUID chatId, JsonNode request, SecurityUser user); + void stopChat(UUID chatId, SecurityUser user); + JsonNode listChats(SecurityUser user); + JsonNode listChatStatuses(SecurityUser user); + JsonNode getChatMessages(UUID chatId, SecurityUser user); void deleteChat(UUID chatId, SecurityUser user); diff --git a/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java b/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java index 1b15fc8045..0fff311678 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java @@ -9,6 +9,8 @@ import org.springframework.stereotype.Service; import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChatOperationRequest; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.cache.limits.RateLimitService; +import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.transport.TbAiOperation; @@ -27,15 +29,17 @@ import java.util.UUID; class DefaultAiChatService implements AiChatService { private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true); + static final String RATE_LIMITED = "RATE_LIMITED"; private final TbAiService tbAiService; private final TbAiTransport tbAiTransport; private final TbAiOperations operations; + private final RateLimitService rateLimitService; @Override public JsonNode createChat(JsonNode request, SecurityUser user) { return tbAiService.process(tokenProvider -> operations.execute( - new TbAiOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request)), user, tokenProvider), user, false); + new TbAiOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request)), user, tokenProvider), user, true); } @Override @@ -50,12 +54,24 @@ class DefaultAiChatService implements AiChatService { new TbAiOperation(ChannelProtocol.CHAT_LIST, null), user, tokenProvider), user, false); } + @Override + public JsonNode listChatStatuses(SecurityUser user) { + return tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.CHAT_STATUS, null), user, tokenProvider), user, false); + } + @Override public JsonNode getChatMessages(UUID chatId, SecurityUser user) { return tbAiService.process(tokenProvider -> operations.execute( new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS)), user, tokenProvider), user, false); } + @Override + public void stopChat(UUID chatId, SecurityUser user) { + tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.CHAT_STOP, new ChatOperationRequest(chatId, null)), user, tokenProvider), user, false); + } + @Override public void deleteChat(UUID chatId, SecurityUser user) { tbAiService.process(tokenProvider -> operations.execute( @@ -67,6 +83,14 @@ class DefaultAiChatService implements AiChatService { UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin, SecurityUser user ) { + if (!rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, user.getTenantId())) { + return Flux.just(ServerSentEvent.builder() + .event("error") + .data(JacksonUtil.toString(JacksonUtil.newObjectNode() + .put("message", "Rate limit exceeded") + .put("code", RATE_LIMITED))) + .build()); + } var link = new TbAiTurnLink(); return tbAiService.processStream(chatId, tokenProvider -> { var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin); diff --git a/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java b/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java index b0f7763131..5e5582df98 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java @@ -25,10 +25,16 @@ public interface AiSolutionService { void clearStep(UUID solutionId, SolutionStep step, SecurityUser user); + JsonNode stopSolution(UUID solutionId, SecurityUser user); + JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user); JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user); void deleteSolution(UUID solutionId, SecurityUser user); + void updateSolution(UUID solutionId, JsonNode request, SecurityUser user); + + JsonNode getInstallProgress(UUID solutionId, SecurityUser user); + } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java b/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java index c110699cbd..91d8297daa 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java @@ -10,12 +10,15 @@ import org.thingsboard.ai.common.data.solution.SolutionStep; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.common.data.util.CollectionsUtil; +import org.thingsboard.server.cache.limits.RateLimitService; +import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.SolutionChatRequest; import org.thingsboard.ai.common.channel.SolutionDataRequest; import org.thingsboard.ai.common.channel.SolutionOperationRequest; import org.thingsboard.ai.common.channel.SolutionStepRequest; +import org.thingsboard.ai.common.channel.SolutionUpdateRequest; import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.transport.TbAiOperation; import org.thingsboard.server.service.ai.transport.TbAiOperations; @@ -32,11 +35,12 @@ public class DefaultAiSolutionService implements AiSolutionService { private final TbAiService tbAiService; private final TbAiOperations operations; + private final RateLimitService rateLimitService; @Override public JsonNode startNew(SecurityUser user) { return tbAiService.process(tokenProvider -> operations.execute( - new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user, false); + new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user); } @Override @@ -58,6 +62,9 @@ public class DefaultAiSolutionService implements AiSolutionService { if (StringUtils.isBlank(text) && attached == null) { throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS); } + if (!rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, user.getTenantId())) { + throw new ThingsboardRuntimeException("Rate limit exceeded", ThingsboardErrorCode.TOO_MANY_REQUESTS); + } return tbAiService.process(tokenProvider -> operations.execute( new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, attached)), user, tokenProvider), user); } @@ -80,6 +87,12 @@ public class DefaultAiSolutionService implements AiSolutionService { new TbAiOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step)), user, tokenProvider), user, false); } + @Override + public JsonNode stopSolution(UUID solutionId, SecurityUser user) { + return tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.SOLUTION_STOP, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false); + } + @Override public JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user) { return tbAiService.process(tokenProvider -> operations.execute( @@ -100,4 +113,16 @@ public class DefaultAiSolutionService implements AiSolutionService { new TbAiOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false); } + @Override + public void updateSolution(UUID solutionId, JsonNode request, SecurityUser user) { + tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.SOLUTION_UPDATE, new SolutionUpdateRequest(solutionId, request)), user, tokenProvider), user, false); + } + + @Override + public JsonNode getInstallProgress(UUID solutionId, SecurityUser user) { + return tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.SOLUTION_PROGRESS, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false); + } + } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java index 5d6b1c4846..f336bc1c4a 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java @@ -52,7 +52,7 @@ class ChannelTbAiOperations { } catch (NotStartedException e) { if (attempt >= 2) { log.warn("AI channel operation '{}' was refused twice: {}", operation.type(), e.getMessage()); - return failure("Service unavailable"); + return failure(HttpStatus.SERVICE_UNAVAILABLE, TbAiOperations.UNAVAILABLE_MESSAGE); } log.debug("AI channel operation '{}' was not started ({}), retrying on a new channel", operation.type(), e.getMessage()); fresh = true; @@ -76,8 +76,8 @@ class ChannelTbAiOperations { } } - static TbAiResponse failure(String message) { - return TbAiResponse.builder().success(false).error(message).build(); + static TbAiResponse failure(HttpStatus status, String message) { + return TbAiResponse.builder().success(false).status(status.value()).error(message).build(); } static TbAiResponse toResponse(OperationResult result) { @@ -136,15 +136,15 @@ class ChannelTbAiOperations { return result.get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - return failure("Request interrupted"); + return failure(HttpStatus.SERVICE_UNAVAILABLE, "Request interrupted"); } catch (TimeoutException e) { - return failure("Request timed out"); + return failure(HttpStatus.GATEWAY_TIMEOUT, TbAiOperations.TIMED_OUT_MESSAGE); } catch (ExecutionException e) { if (e.getCause() instanceof NotStartedException notStarted) { throw notStarted; } log.warn("AI channel operation '{}' failed: {}", operation.type(), ExceptionUtils.getRootCauseMessage(e)); - return failure("Service unavailable"); + return failure(HttpStatus.SERVICE_UNAVAILABLE, TbAiOperations.UNAVAILABLE_MESSAGE); } finally { finish(); } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java index c8e49e4797..9cedb4a509 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java @@ -25,7 +25,7 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * Runs a chat turn on a pooled channel and re-emits its events as SSE. A turn the channel did not start (refused, or * closed with 1001 before any frame for it) is retried once on a new channel; a channel that cannot be opened fails - * the turn with "Service unavailable". + * the turn with {@link TbAiOperations#UNAVAILABLE_MESSAGE}. */ @Slf4j @Component @@ -166,7 +166,7 @@ class ChannelTbAiTransport implements TbAiTransport { end(null); } else { log.warn("[{}] AI channel closed during the turn [{}] {}", chatId, code, reason); - end(errorEvent("Service unavailable")); + end(errorEvent(TbAiOperations.UNAVAILABLE_MESSAGE)); } } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java index 9cb93f24d1..a5875c01df 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java @@ -2,6 +2,8 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.ai.transport; +import com.auth0.jwt.JWT; +import com.auth0.jwt.exceptions.JWTDecodeException; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException; import jakarta.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; @@ -13,6 +15,7 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.TbAiChannelClient; +import org.thingsboard.ai.common.client.TbAiClaims; import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiHeaders; import org.thingsboard.common.util.ThingsBoardThreadFactory; @@ -120,11 +123,17 @@ class TbAiChannelPool { PoolKey key = new PoolKey(context.tenantId(), context.userId()); CompletableFuture pending = null; if (!fresh) { + String limits = limitsOf(currentToken(context)); Group group = groups.computeIfAbsent(key, k -> new Group()); synchronized (group) { long now = nanoClock.getAsLong(); for (int i = group.connections.size() - 1; i >= 0; i--) { TbAiPooledConnection connection = group.connections.get(i); + if (connection.isStaleFor(limits)) { + log.debug("[{}] Retiring an AI channel opened with other limits", key); + connection.retire(); + continue; + } if (connection.tryReserve(now)) { return CompletableFuture.completedFuture(connection); } @@ -185,7 +194,9 @@ class TbAiChannelPool { private CompletableFuture connect(TbAiTurnContext context, PoolKey key, boolean pooled) { var connection = new TbAiPooledConnection(key, context.clientOrigin(), pooled, maxOperationsPerConnection, channelClient.codec(), this, nanoClock.getAsLong()); - channelClient.connect(handshakeTokenProvider(context), connection) + String token = currentToken(context); + connection.handshakeLimits(limitsOf(token)); + channelClient.connect(handshakeTokenProvider(context, token), connection) .subscribeOn(Schedulers.boundedElastic()) .subscribe(connection::opened, error -> connection.failed(toConnectError(error))); return connection.ready() @@ -298,13 +309,32 @@ class TbAiChannelPool { return true; } - private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context) { + private static String currentToken(TbAiTurnContext context) { + try { + return context.tokenProvider() != null ? context.tokenProvider().getToken() : null; + } catch (RuntimeException e) { + return null; + } + } + + static String limitsOf(String token) { + if (token == null) { + return null; + } + try { + return JWT.decode(token).getClaim(TbAiClaims.PROFILE_CONFIG).asString(); + } catch (JWTDecodeException e) { + return null; + } + } + + private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context, String token) { TbAiClient.TokenProvider delegate = context.tokenProvider(); String acceptLanguage = context.acceptLanguage(); return new TbAiClient.TokenProvider() { @Override public String getToken() { - return delegate.getToken(); + return token != null ? token : delegate.getToken(); } @Override @@ -324,7 +354,7 @@ class TbAiChannelPool { if (cause instanceof WebSocketClientHandshakeException handshake && handshake.response() != null) { int status = handshake.response().status().code(); if (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value()) { - return new TbAiChannelRejectedException(HttpStatus.valueOf(status).getReasonPhrase()); + return new TbAiChannelRejectedException(HttpStatus.valueOf(status)); } } if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) { diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java index b0dc2324a7..2b63861a53 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java @@ -2,13 +2,20 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.ai.transport; +import lombok.Getter; +import org.springframework.http.HttpStatus; + /** * TB AI refused the channel handshake with 401 or 403; the reason phrase is shown to the user. */ +@Getter public class TbAiChannelRejectedException extends RuntimeException { - public TbAiChannelRejectedException(String reason) { - super(reason); + private final HttpStatus status; + + public TbAiChannelRejectedException(HttpStatus status) { + super(status.getReasonPhrase()); + this.status = status; } } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java index 32052870c1..80fa6a1e23 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java @@ -4,6 +4,7 @@ package org.thingsboard.server.service.ai.transport; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse; @@ -17,6 +18,9 @@ import org.thingsboard.server.service.security.system.SystemSecurityService; @RequiredArgsConstructor public class TbAiOperations { + public static final String UNAVAILABLE_MESSAGE = "The AI service is unavailable. Try again."; + public static final String TIMED_OUT_MESSAGE = "The AI service did not answer in time. Try again."; + private final ChannelTbAiOperations channelOperations; private final SystemSecurityService systemSecurityService; @@ -33,9 +37,9 @@ public class TbAiOperations { return channelOperations.execute(operation, context); } catch (TbAiChannelUnavailableException e) { log.warn("[{}][{}] AI channel unavailable for '{}': {}", context.tenantId(), context.userId(), operation.type(), e.getMessage()); - return ChannelTbAiOperations.failure("Service unavailable"); + return ChannelTbAiOperations.failure(HttpStatus.SERVICE_UNAVAILABLE, UNAVAILABLE_MESSAGE); } catch (TbAiChannelRejectedException e) { - return ChannelTbAiOperations.failure(e.getMessage()); + return ChannelTbAiOperations.failure(e.getStatus(), e.getMessage()); } } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java index 3b77aad205..b5f0b606d1 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java @@ -32,7 +32,7 @@ final class TbAiPooledConnection implements ChannelFrameListener { // Protocol version 1 is the baseline. A later feature that this ThingsBoard handles goes here, so TB AI can tell // before using it that this ThingsBoard understands it. - static final List CLIENT_CAPABILITIES = List.of(); + static final List CLIENT_CAPABILITIES = List.of(ChannelProtocol.CHAT_KIT_CAPABILITY); private final TbAiChannelPool.PoolKey key; private final String origin; @@ -54,6 +54,7 @@ final class TbAiPooledConnection implements ChannelFrameListener { private volatile ChannelSession session; private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES; private volatile List serverCapabilities = List.of(); + private volatile String handshakeLimits; /** * Created with one reservation for the caller that opens it, so callers waiting on the same handshake cannot @@ -198,6 +199,20 @@ final class TbAiPooledConnection implements ChannelFrameListener { } } + void handshakeLimits(String limits) { + this.handshakeLimits = limits; + } + + /** + * True when the channel shook hands with other limits than the caller's current token carries (the tenant + * profile's rate limits among them): its view of the user is out of date, so it should take no new work. Claims + * that change on every signing, such as the client address or the issue time, do not count. + */ + boolean isStaleFor(String currentLimits) { + String limits = handshakeLimits; + return currentLimits != null && limits != null && !limits.equals(currentLimits); + } + void retire() { boolean close; synchronized (lock) { diff --git a/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java b/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java index 45263ef7fd..069fd5083d 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java @@ -6,6 +6,7 @@ package org.thingsboard.server.service.edge; import com.fasterxml.jackson.databind.JsonNode; import jakarta.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; +import org.apache.hc.client5.http.config.ConnectionConfig; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.client5.http.impl.classic.HttpClients; @@ -134,7 +135,6 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService { httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(createConnectionManager(true)).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setHttpClient(httpClient); - factory.setConnectTimeout(CONNECT_TIMEOUT); return new RestTemplate(factory); } else if (proxyEnabled) { log.warn("Going to use Proxy Server: [{}:{}]", System.getProperty("tb.proxy.host"), System.getProperty("tb.proxy.port")); @@ -143,13 +143,11 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService { .setProxy(new HttpHost("https", System.getProperty("tb.proxy.host"), Integer.parseInt(System.getProperty("tb.proxy.port")))).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setHttpClient(httpClient); - factory.setConnectTimeout(CONNECT_TIMEOUT); return new RestTemplate(factory); } else { httpClient = HttpClients.custom().setConnectionManager(createConnectionManager(false)).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setHttpClient(httpClient); - factory.setConnectTimeout(CONNECT_TIMEOUT); return new RestTemplate(factory); } } @@ -157,8 +155,10 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService { private HttpClientConnectionManager createConnectionManager(boolean systemProperties) { var socketFactory = systemProperties ? SSLConnectionSocketFactory.getSystemSocketFactory() : SSLConnectionSocketFactory.getSocketFactory(); var socketConfig = SocketConfig.custom().setSoTimeout(Timeout.of(READ_TIMEOUT, TimeUnit.MILLISECONDS)).build(); + var connectionConfig = ConnectionConfig.custom().setConnectTimeout(Timeout.of(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)).build(); return PoolingHttpClientConnectionManagerBuilder.create() .setDefaultSocketConfig(socketConfig) + .setDefaultConnectionConfig(connectionConfig) .setSSLSocketFactory(socketFactory).build(); } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java index 04d7939917..0f51d5525d 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java @@ -193,7 +193,7 @@ public abstract class BaseTelemetryProcessor extends BaseEdgeProcessor { } } case ENTITY_GROUP -> { - EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupById(tenantId, new EntityGroupId(entityId.getId())); + EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupInfoByTenantIdAndId(tenantId, new EntityGroupId(entityId.getId())); if (entityGroup != null) { metaData.putValue("entityGroupName", entityGroup.getName()); metaData.putValue("entityGroupType", entityGroup.getType().name()); diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java index ddb154c88a..a045db3b86 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.entitiy.user; import com.fasterxml.jackson.databind.JsonNode; @@ -39,7 +40,7 @@ import java.util.stream.Collectors; @Slf4j public class DefaultTbUserSettingsService implements TbUserSettingsService { - private static final int MAX_DASHBOARD_INFO_LIST_SIZE = 10; + private static final int MAX_DASHBOARD_INFO_LIST_SIZE = 50; private static final Predicate EMPTY_TITLE = i -> StringUtils.isEmpty(i.getTitle()); private final UserSettingsService settingsService; diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java new file mode 100644 index 0000000000..4c7a4dbeb4 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.install.lts; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.notification.NotificationType; +import org.thingsboard.server.dao.notification.DefaultNotifications; +import org.thingsboard.server.dao.notification.NotificationSettingsService; +import org.thingsboard.server.queue.util.TbCoreComponent; + +@Slf4j +@Component +@TbCoreComponent +@RequiredArgsConstructor +public class V4_4_2_0Migration implements Migration { + + private final NotificationSettingsService notificationSettingsService; + private final DefaultNotifications defaultNotifications; + + @Override + public String getVersion() { + return "4.4.2.0"; + } + + @Override + public void apply() { + createAiCreditsLimitIncreaseRequestTemplate(); + } + + private void createAiCreditsLimitIncreaseRequestTemplate() { + if (notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) { + log.debug("The AI credits limit increase request notification template already exists"); + return; + } + defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest); + log.info("Created the AI credits limit increase request notification template"); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java b/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java index 88b58152ed..212c59aa5d 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java +++ b/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java @@ -31,7 +31,7 @@ class EntityViewGroupAllUpdater extends EntityGroupAllPaginatedUpdater compositeCallback = operationCount > 1 ? new CompositeCallback(operationCount, callback) : callback; if (hasTelemetry) { - process(sessionInfo, data.getPostTelemetryMsg(), compositeCallback); + process(sessionInfo, data.getPostTelemetryMsg(), data.getTelemetryTypeCastDisabledKeysList(), compositeCallback); } if (hasAttributes) { - process(sessionInfo, data.getPostAttributesMsg(), compositeCallback); + process(sessionInfo, data.getPostAttributesMsg(), data.getAttributesTypeCastDisabledKeysList(), compositeCallback); } }; } @@ -226,11 +227,11 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage IntegrationCallback compositeCallback = operationCount > 1 ? new CompositeCallback(operationCount, callback) : callback; if (hasTelemetry) { - process(asset, data.getPostTelemetryMsg(), compositeCallback); + process(asset, data.getPostTelemetryMsg(), data.getTelemetryTypeCastDisabledKeysList(), compositeCallback); } if (hasAttributes) { - process(asset, data.getPostAttributesMsg(), compositeCallback); + process(asset, data.getPostAttributesMsg(), data.getAttributesTypeCastDisabledKeysList(), compositeCallback); } }; } @@ -363,6 +364,11 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage @Override public void process(SessionInfoProto sessionInfo, PostTelemetryMsg msg, IntegrationCallback callback) { + process(sessionInfo, msg, Collections.emptySet(), callback); + } + + // typeCastDisabledKeys: the keys whose string values the converter kept as strings, passed to the rule engine in the metadata. + void process(SessionInfoProto sessionInfo, PostTelemetryMsg msg, Collection typeCastDisabledKeys, IntegrationCallback callback) { try { if (msg.getTsKvListCount() == 0) { callback.onSuccess(null); @@ -381,6 +387,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage metaData.putValue("deviceName", sessionInfo.getDeviceName()); metaData.putValue("deviceType", sessionInfo.getDeviceType()); metaData.putValue("ts", tsKv.getTs() + ""); + metaData.putTypeCastDisabledKeys(typeCastDisabledKeys); JsonObject json = JsonUtils.getJsonObject(tsKv.getKvList()); sendToRuleEngine(tenantId, deviceId, sessionInfo, json, metaData, TbMsgType.POST_TELEMETRY_REQUEST, packCallback); } @@ -391,6 +398,10 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage @Override public void process(SessionInfoProto sessionInfo, PostAttributeMsg msg, IntegrationCallback callback) { + process(sessionInfo, msg, Collections.emptySet(), callback); + } + + void process(SessionInfoProto sessionInfo, PostAttributeMsg msg, Collection typeCastDisabledKeys, IntegrationCallback callback) { try { TenantId tenantId = TenantId.fromUUID(new UUID(sessionInfo.getTenantIdMSB(), sessionInfo.getTenantIdLSB())); DeviceId deviceId = new DeviceId(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB())); @@ -399,6 +410,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage TbMsgMetaData metaData = new TbMsgMetaData(); metaData.putValue("deviceName", sessionInfo.getDeviceName()); metaData.putValue("deviceType", sessionInfo.getDeviceType()); + metaData.putTypeCastDisabledKeys(typeCastDisabledKeys); sendToRuleEngine(tenantId, deviceId, sessionInfo, json, metaData, TbMsgType.POST_ATTRIBUTES_REQUEST, new IntegrationTbQueueCallback(new ApiStatsProxyCallback<>(tenantId, getCustomerId(sessionInfo), msg.getKvList().size(), callback))); } catch (Exception e) { @@ -717,7 +729,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage return metaData; } - private void process(Asset asset, PostTelemetryMsg msg, IntegrationCallback callback) { + private void process(Asset asset, PostTelemetryMsg msg, Collection typeCastDisabledKeys, IntegrationCallback callback) { try { if (msg.getTsKvListCount() == 0) { callback.onSuccess(null); @@ -733,6 +745,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage metaData.putValue("assetName", asset.getName()); metaData.putValue("assetType", asset.getType()); metaData.putValue("ts", tsKv.getTs() + ""); + metaData.putTypeCastDisabledKeys(typeCastDisabledKeys); JsonObject json = JsonUtils.getJsonObject(tsKv.getKvList()); sendToRuleEngine(asset.getTenantId(), asset.getId(), asset.getAssetProfileId(), asset.getCustomerId(), json, metaData, TbMsgType.POST_TELEMETRY_REQUEST, packCallback); @@ -742,12 +755,13 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage } } - private void process(Asset asset, PostAttributeMsg msg, IntegrationCallback callback) { + private void process(Asset asset, PostAttributeMsg msg, Collection typeCastDisabledKeys, IntegrationCallback callback) { try { JsonObject json = JsonUtils.getJsonObject(msg.getKvList()); TbMsgMetaData metaData = new TbMsgMetaData(); metaData.putValue("assetName", asset.getName()); metaData.putValue("assetType", asset.getType()); + metaData.putTypeCastDisabledKeys(typeCastDisabledKeys); sendToRuleEngine(asset.getTenantId(), asset.getId(), asset.getAssetProfileId(), asset.getCustomerId(), json, metaData, TbMsgType.POST_ATTRIBUTES_REQUEST, new IntegrationTbQueueCallback(new ApiStatsProxyCallback<>(asset.getTenantId(), asset.getCustomerId(), msg.getKvList().size(), callback))); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java similarity index 70% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java index f4604beea4..e025d41fe0 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java @@ -9,6 +9,8 @@ import com.fasterxml.jackson.databind.node.TextNode; import com.google.gson.JsonParser; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.client.RestClientException; @@ -16,10 +18,13 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.GroupEntity; +import org.thingsboard.server.common.data.HasCustomerId; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.HasVersion; @@ -30,14 +35,17 @@ import org.thingsboard.server.common.data.exception.EntityVersionMismatchExcepti import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.ConverterId; +import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; @@ -63,9 +71,12 @@ import org.thingsboard.server.dao.subscription.PlatformFeature; import org.thingsboard.server.dao.subscription.SubscriptionService; import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.exception.EntitiesLimitExceededException; +import org.thingsboard.server.exception.ThingsboardEntitiesLimitExceededResponse; +import org.thingsboard.server.exception.ThingsboardErrorResponse; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; +import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.rule.TbRuleChainService; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; @@ -86,18 +97,17 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * Applies an update of an installed device package in one transaction. The install wizard resolves the templates - * of the new version (the same way it installs them) and sends the entity of each step; this service checks the - * plan, saves every entity and the new version of the installed item together, and rolls all of it back on a - * failure. The side effects of the saves (actors, integration restart, edge, caches) run after commit, so a - * rollback leaves no trace; the audit log, version control and the attributes, which aren't transactional, - * are written after commit too. + * Installs a device package, or updates an installed one, in one transaction. The install wizard resolves the + * templates of the version and sends the entity of each step; this service checks the plan, saves every entity + * and the installed item together, and rolls all of it back on a failure. The side effects of the saves (actors, + * integration restart, edge, caches) run after commit, so a rollback leaves no trace; the audit log, version control + * and the attributes, which aren't transactional, are written after commit too. */ @Service @TbCoreComponent @Slf4j @RequiredArgsConstructor -public class DefaultDevicePackageUpdateService extends AbstractTbEntityService implements DevicePackageUpdateService { +public class DefaultDevicePackageService extends AbstractTbEntityService implements DevicePackageService { // Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id} private static final Map STEP_ALIASES = Map.of( @@ -110,7 +120,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i "DOWNLINK_CONVERTER", "downlinkConverter", "INTEGRATION", "integration"); private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}"); - private static final String UNEXPECTED_ERROR = "Failed to update the device package"; + private static final String UNEXPECTED_ERROR = "Failed to save the device package"; private final IotHubInstalledItemService installedItemService; private final IotHubRestClient iotHubRestClient; @@ -129,6 +139,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private final AttributesService attributesService; private final TelemetrySubscriptionService telemetryService; private final TransactionTemplate transactionTemplate; + private final ProjectInfo projectInfo; @Override public List check(SecurityUser user, IotHubInstalledItemId installedItemId) { @@ -162,33 +173,168 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } @Override - public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) { + public DevicePackageResult install(SecurityUser user, DevicePackageRequest request) { + TenantId tenantId = user.getTenantId(); + log.info("[{}] Installing device package version {}", tenantId, request.getVersionId()); + DevicePackageResult result = apply(user, "install of version " + request.getVersionId(), () -> { + if (request.getVersionId() == null || request.getFromVersionId() != null || toUuid(request.getVersionId()) == null) { + throw new IllegalArgumentException("Invalid install request"); + } + Placement placement = placement(tenantId, request); + JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); + if (versionInfo == null) { + throw new IllegalArgumentException("Failed to get version info from IoT Hub"); + } + // The package owns nothing yet, so overwriting an entity the tenant has needs a confirmation + DeviceInstalledItemDescriptor previous = new DeviceInstalledItemDescriptor(); + validateInstallSteps(request); + validate(tenantId, previous, request); + return transactionTemplate.execute(status -> { + Applied applied = applySteps(tenantId, previous, request, null, placement); + IotHubInstalledItem installedItem = new IotHubInstalledItem(); + installedItem.setTenantId(tenantId); + installedItem.setItemId(UUID.fromString(versionInfo.get("itemId").asText())); + installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setItemType("DEVICE"); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(applied.descriptor()); + installedItemService.save(tenantId, installedItem); + return applied; + }); + }); + if (result.isSuccess()) { + reportInstall(user, request.getVersionId()); + log.info("[{}] Installed device package version {}", tenantId, request.getVersionId()); + } + return result; + } + + @Override + public DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request) { TenantId tenantId = user.getTenantId(); log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId()); - Applied applied; - try { + DevicePackageResult result = apply(user, "update of " + installedItemId, () -> { DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId); JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) { throw new IllegalArgumentException("The version belongs to another item"); } - validatePlan(devicePackage, request); - checkFeatures(tenantId, request); - validateIntegrations(tenantId, request); - applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo)); + validate(tenantId, devicePackage.descriptor(), request); + return transactionTemplate.execute(status -> { + IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); + Applied applied = applySteps(tenantId, devicePackage.descriptor(), request, installedItem.getItemVersionId(), Placement.NONE); + installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(applied.descriptor()); + installedItemService.save(tenantId, installedItem); + return applied; + }); + }); + if (result.isSuccess()) { + log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); + } + return result; + } + + /** Runs the planned change and, once it committed, what isn't transactional; a failure leaves nothing changed. */ + private DevicePackageResult apply(SecurityUser user, String operation, PackageChange change) { + TenantId tenantId = user.getTenantId(); + Applied applied; + try { + applied = change.apply(); } catch (StepFailure e) { - log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause()); - return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey); + log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause()); + return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey, limitOf(e.getCause())); } catch (RestClientException e) { - log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e); - return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null); + log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e); + return DevicePackageResult.error("IoT Hub is unavailable. Try again later.", null); } catch (Exception e) { - log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e); - return DeviceUpdateResult.error(userMessage(e), null); + log.warn("[{}] Device package {} failed, nothing was changed", tenantId, operation, e); + return DevicePackageResult.error(userMessage(e), null); } afterCommit(user, tenantId, applied); - log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); - return DeviceUpdateResult.success(applied.descriptor(), applied.outputs()); + return DevicePackageResult.success(applied.descriptor(), applied.outputs()); + } + + /** Counts the install on the Hub; the package is installed whether or not the Hub hears of it. */ + private void reportInstall(SecurityUser user, String versionId) { + TenantId tenantId = user.getTenantId(); + try { + InstallReport report = DefaultIotHubService.buildInstallReport(tenantId.getId(), user.getId().getId(), + projectInfo.getProjectVersion(), projectInfo.getProductType()); + iotHubRestClient.reportVersionInstalled(versionId, report); + } catch (Exception e) { + log.warn("[{}] Failed to report install for version {}: {}", tenantId, versionId, e.getMessage()); + } + } + + /** + * At install a kept entity is one the user chose to use as it is: the package doesn't own it. An existing device or + * gateway is never overwritten: its credentials are what its firmware uses. + */ + private static void validateInstallSteps(DevicePackageRequest request) { + if (request.getSteps() == null) { + return; + } + for (DevicePackageRequest.Step step : request.getSteps()) { + boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); + if ((step.getAction() == DevicePackageRequest.Action.KEEP && !"use-existing".equals(step.getResolution())) + || (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway)) { + throw new IllegalArgumentException("Invalid install step: " + step.getName()); + } + } + } + + /** + * The customer and the device group the install was opened from; each must be the tenant's. The group's own + * permission isn't checked again: the endpoint's checkAllPermissions already requires ALL operations on ALL resources. + */ + private Placement placement(TenantId tenantId, DevicePackageRequest request) { + CustomerId customerId = request.getCustomerId() != null && !CustomerId.NULL_UUID.equals(request.getCustomerId()) + ? new CustomerId(request.getCustomerId()) : null; + if (customerId != null && !isTenantsCustomer(tenantId, customerId)) { + throw new IllegalArgumentException("Invalid install request"); + } + if (request.getEntityGroupId() == null) { + return new Placement(customerId, customerId, null); + } + EntityGroup group = entityGroupService.findEntityGroupById(tenantId, new EntityGroupId(request.getEntityGroupId())); + EntityId owner = group != null ? group.getOwnerId() : null; + boolean tenants = owner != null && (tenantId.equals(owner) + || (owner.getEntityType() == EntityType.CUSTOMER && isTenantsCustomer(tenantId, new CustomerId(owner.getId())))); + if (group == null || group.getType() != EntityType.DEVICE || !tenants) { + throw new IllegalArgumentException("Invalid install request"); + } + // As a device saved into a group: with no customer given, a new one goes to the group's customer + CustomerId deviceCustomerId = customerId == null && owner.getEntityType() == EntityType.CUSTOMER ? new CustomerId(owner.getId()) : customerId; + return new Placement(customerId, deviceCustomerId, group); + } + + private boolean isTenantsCustomer(TenantId tenantId, CustomerId customerId) { + Customer customer = customerService.findCustomerById(tenantId, customerId); + return customer != null && tenantId.equals(customer.getTenantId()); + } + + /** + * Puts the entity in the customer the install was opened from. An overwrite never changes the owner, with or without + * a customer: the dao would move the entity past the owner change, leaving its groups and the owner cache stale. + */ + private static void assignCustomer(GroupEntity entity, CustomerId customerId, GroupEntity current, DevicePackageRequest.Step step) { + if (customerId != null) { + entity.setOwnerId(customerId); + } + if (current != null && !current.getOwnerId().equals(entity.getOwnerId())) { + throw new IllegalArgumentException(step.getName() + " belongs to another owner"); + } + } + + /** What is checked before the transaction: the plan, the tenant's plan features and the integrations' configuration. */ + private void validate(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request) throws Exception { + validatePlan(ownedIds(previous), request); + checkFeatures(tenantId, request); + validateIntegrations(tenantId, request); } private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) { @@ -201,50 +347,49 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } /** - * The update may only change what the package owns, or what the user confirmed. The device and the gateway, + * The device package may only change what it owns, or what the user confirmed. Its own device and gateway, * whose credentials the firmware uses, are never changed. */ - private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) { + private void validatePlan(Set ownedIds, DevicePackageRequest request) { if (request.getSteps() == null || request.getSteps().isEmpty()) { - throw new IllegalArgumentException("The update has no steps"); + throw new IllegalArgumentException("The device package has no steps"); } - Set ownedIds = ownedIds(devicePackage.descriptor()); // A form's values are saved under its key too, so an entity step may not share it Set stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>(); - for (DeviceUpdateRequest.Step step : request.getSteps()) { + for (DevicePackageRequest.Step step : request.getSteps()) { if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { - throw new IllegalArgumentException("Invalid update step: " + step.getName()); + throw new IllegalArgumentException("Invalid step: " + step.getName()); } if (!stateKeys.add(step.stateKey())) { - throw new IllegalArgumentException("Duplicate update step: " + step.stateKey()); + throw new IllegalArgumentException("Duplicate step: " + step.stateKey()); } boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); switch (step.getAction()) { case KEEP, OVERWRITE -> { if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) { - throw new IllegalArgumentException("No entity for update step: " + step.getName()); + throw new IllegalArgumentException("No entity for step: " + step.getName()); } boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && !owned && !step.isConfirmed() + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && !owned && !step.isConfirmed() && !"GATEWAY_CONNECTOR".equals(step.getType())) { throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName()); } - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && deviceOrGateway && owned) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway && owned) { throw new IllegalArgumentException("The device and its credentials don't change on update"); } } case CREATE -> { } } - if (step.getAction() != DeviceUpdateRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { - throw new IllegalArgumentException("No entity data for update step: " + step.getName()); + if (step.getAction() != DevicePackageRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { + throw new IllegalArgumentException("No entity data for step: " + step.getName()); } } } /** Integrations and converters are saved as through their API, which needs the feature in the tenant's plan. */ - private void checkFeatures(TenantId tenantId, DeviceUpdateRequest request) { - boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DeviceUpdateRequest.Action.KEEP + private void checkFeatures(TenantId tenantId, DevicePackageRequest request) { + boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DevicePackageRequest.Action.KEEP && ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER"))); if (savesIntegrations) { subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); @@ -252,13 +397,13 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } /** The configuration of an integration is checked by a remote call, so before the transaction. */ - private void validateIntegrations(TenantId tenantId, DeviceUpdateRequest request) throws Exception { - for (DeviceUpdateRequest.Step step : request.getSteps()) { - if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DeviceUpdateRequest.Action.KEEP) { + private void validateIntegrations(TenantId tenantId, DevicePackageRequest request) throws Exception { + for (DevicePackageRequest.Step step : request.getSteps()) { + if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DevicePackageRequest.Action.KEEP) { continue; } ObjectNode body = step.getEntity().deepCopy(); - // Converters this update creates have no id yet; the configuration doesn't depend on them + // Converters the request creates have no id yet; the configuration doesn't depend on them body.remove(List.of("id", "defaultConverterId", "downlinkConverterId")); Integration integration = JacksonUtil.treeToValue(body, Integration.class); integration.setTenantId(tenantId); @@ -274,9 +419,12 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } } - private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { - IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); - DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); + /** + * Saves the entities of the steps and builds the descriptor of the installed item, which the caller saves in the + * same transaction. previous is what the package had: on install an empty descriptor, and installedVersionId null. + */ + private Applied applySteps(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request, UUID installedVersionId, + Placement placement) { Set ownedIds = ownedIds(previous); Map aliasOutputs = new HashMap<>(); Map outputs = new LinkedHashMap<>(); @@ -289,23 +437,25 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i }); } List stepEntityIds = new ArrayList<>(); - Map usedExistingIds = usedExistingIds(previous); + Map usedExistingIds = new LinkedHashMap<>(); + previous.getUsedExistingEntityIdsIncludingLegacy().forEach(id -> usedExistingIds.put(id.getId(), id)); List saved = new ArrayList<>(); - List connectorSteps = new ArrayList<>(); + List grouped = new ArrayList<>(); + List connectorSteps = new ArrayList<>(); List attributes = new ArrayList<>(); DashboardId dashboardId = null; - for (DeviceUpdateRequest.Step step : request.getSteps()) { + for (DevicePackageRequest.Step step : request.getSteps()) { try { if ("GATEWAY_CONNECTOR".equals(step.getType())) { // A connector lives in the gateway's attributes, which aren't transactional: saved after commit - if (step.getAction() != DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() != DevicePackageRequest.Action.KEEP) { connectorSteps.add(copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs))); } continue; } JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null; - StepResult result = applyStep(tenantId, step, entity); + StepResult result = applyStep(tenantId, step, entity, placement); ObjectNode output = result.output(); aliasOutputs.put(STEP_ALIASES.get(step.getType()), output); outputs.put(step.stateKey(), output); @@ -317,7 +467,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i state.put("resolution", resolution); // A kept entity keeps the checksum of what the package left: the current one would take the // user's changes for the package's, and the next update would overwrite them without a warning - String checksum = step.getAction() == DeviceUpdateRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); + String checksum = step.getAction() == DevicePackageRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); if (checksum != null) { state.put("checksum", checksum); } @@ -343,8 +493,15 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (result.saved() != null) { saved.add(result.saved()); } - if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(resolution)) { - // As at install, the step's attributes go with the entity it saved; written after commit + if (placement.entityGroup() != null && result.saved() != null && result.saved().created() + && result.entityId().getEntityType() == EntityType.DEVICE) { + entityGroupService.addEntityToEntityGroup(tenantId, placement.entityGroup().getId(), result.entityId()); + grouped.add(result.saved()); + } + // The step's attributes go with the entity it saved; at install also onto an entity the user chose to + // use, as the install always did. Written after commit + boolean install = installedVersionId == null; + if (install || (step.getAction() != DevicePackageRequest.Action.KEEP && !"use-existing".equals(resolution))) { attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes())); } } catch (StepFailure e) { @@ -356,7 +513,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i // An update to the installed version itself, e.g. of ThingsBoard's default converter only, sends just the steps // it changes: the other steps and the forms keep their install state - if (UUID.fromString(request.getVersionId()).equals(installedItem.getItemVersionId()) && previous.getInstallState() != null) { + if (UUID.fromString(request.getVersionId()).equals(installedVersionId) && previous.getInstallState() != null) { previous.getInstallState().forEach((key, value) -> { if (value instanceof ObjectNode state) { installState.putIfAbsent(key, state); @@ -376,15 +533,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i carryMetadataStates(previous, tracked, state); descriptor.setInstallState(state); - installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); - installedItem.setItemName(versionInfo.get("name").asText()); - installedItem.setVersion(versionInfo.get("version").asText()); - installedItem.setDescriptor(descriptor); - installedItemService.save(tenantId, installedItem); // Resolved once every entity is saved: attributes may refer to a later step's entity List resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(), resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList(); - return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs); + return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs, placement.entityGroup(), grouped); } /** The checksums the installed device packages recorded, by entity. */ @@ -422,7 +574,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * Another update of the package, e.g. a second click or another tab, waits here until this one commits, and then * fails: the plan was made for the version installed before. Without it both would create the new entities. */ - private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request) { + private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DevicePackageRequest request) { IotHubInstalledItem installedItem = installedItemService.findByIdForUpdate(tenantId, devicePackage.installedItem().getId()); UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId(); if (installedItem == null || !planned.equals(installedItem.getItemVersionId()) @@ -432,11 +584,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return installedItem; } - private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + private StepResult applyStep(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) throws ThingsboardException { return switch (step.getType()) { case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity); - case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity); - case "DASHBOARD" -> saveDashboard(tenantId, step, entity); + case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity, placement); + case "DASHBOARD" -> saveDashboard(tenantId, step, entity, placement); case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity); case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity); case "INTEGRATION" -> saveIntegration(tenantId, step, entity); @@ -444,16 +596,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i }; } - private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDeviceProfile(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null; DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class); profile.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(profile, id, current, step); // The tenant's default profile stays the default one @@ -466,31 +618,34 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDevice(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) { DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null; Device device; boolean created = false; - if (step.getAction() == DeviceUpdateRequest.Action.CREATE) { + if (step.getAction() == DevicePackageRequest.Action.CREATE) { Device template = JacksonUtil.treeToValue(entity, Device.class); template.setTenantId(tenantId); template.setId(null); template.setVersion(null); + assignCustomer(template, placement.deviceCustomerId(), null, step); device = deviceService.saveDevice(template); created = true; } else { Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null; device = existing(tenantId, current, step); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { - // Another device the user chose to overwrite; the package's own device never changes + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { + // On update, another device the user chose to overwrite; it keeps its credentials. The package's own + // device never changes, and an install never overwrites one Device template = JacksonUtil.treeToValue(entity, Device.class); template.setTenantId(tenantId); prepareOverwrite(template, id, current, step); + assignCustomer(template, placement.customerId(), current, step); device = deviceService.saveDevice(template); created = true; } } DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); - if (created && step.getCredentials() != null && step.getCredentials().isObject()) { + if (step.getAction() == DevicePackageRequest.Action.CREATE && step.getCredentials() != null && step.getCredentials().isObject()) { credentials = applyCredentials(tenantId, credentials, step.getCredentials()); } ObjectNode output = output(device.getId(), device.getName()); @@ -500,7 +655,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if ("GATEWAY".equals(step.getType())) { output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download"); } - SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DeviceUpdateRequest.Action.CREATE) : null; + SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DevicePackageRequest.Action.CREATE) : null; return new StepResult(device.getId(), output, null, saved); } @@ -520,16 +675,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials); } - private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDashboard(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) { DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null; Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getTitle()); } Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class); dashboard.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(dashboard, id, current, step); // The dashboard keeps its owner and the customers it is assigned to @@ -537,25 +692,27 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i dashboard.setCustomerId(current.getCustomerId()); } dashboard.setAssignedCustomers(current.getAssignedCustomers()); + assignCustomer(dashboard, placement.customerId(), current, step); } else { dashboard.setId(null); dashboard.setVersion(null); + assignCustomer(dashboard, placement.customerId(), null, step); } Dashboard result = dashboardService.saveDashboard(dashboard); return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle())); } - private StepResult saveRuleChain(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + private StepResult saveRuleChain(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) throws ThingsboardException { RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null; RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity; RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class); ruleChain.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(ruleChain, id, current, step); // A rule chain the tenant made its root one stays the root @@ -578,17 +735,17 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveConverter(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null; Converter current = id != null ? converterService.findConverterById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } Converter converter = JacksonUtil.treeToValue(entity, Converter.class); converter.setTenantId(tenantId); converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(converter, id, current, step); } else { @@ -599,10 +756,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveIntegration(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null; Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); Integration merged = withMergedMetadata(current, step.getMetadata()); if (merged != null) { @@ -613,7 +770,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } Integration integration = JacksonUtil.treeToValue(entity, Integration.class); integration.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(integration, id, current, step); // The devices keep sending to the same endpoint @@ -668,7 +825,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i /** * A copy of the integration with the step's metadata entries merged into its metadata; null when that changes nothing. - * A copy: the integration may be the cache's own instance, which a rolled back update must not change. + * A copy: the integration may be the cache's own instance, which a rolled back install or update must not change. */ private static Integration withMergedMetadata(Integration integration, JsonNode entries) { if (entries == null || !entries.isObject() || entries.isEmpty()) { @@ -698,7 +855,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * The overwritten entity keeps its id and its current name (the user may have renamed it). The version the * user reviewed makes the save fail if someone changed the entity since. */ - private void prepareOverwrite(Object entity, EntityId id, Object current, DeviceUpdateRequest.Step step) { + private void prepareOverwrite(Object entity, EntityId id, Object current, DevicePackageRequest.Step step) { switch (entity) { case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); } case Device d -> { d.setId((DeviceId) id); d.setName(((Device) current).getName()); } @@ -715,9 +872,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i ((HasVersion) entity).setVersion(currentVersion); } - private T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) { + private T existing(TenantId tenantId, T current, DevicePackageRequest.Step step) { if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) { - throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again."); + throw new IllegalArgumentException(step.getName() + " was deleted meanwhile. Check the package again."); } return current; } @@ -745,9 +902,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * transaction may come from the cache, which is evicted only after commit. A rule chain is read back with * its metadata, which isn't cached. */ - private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DeviceUpdateRequest.Step step, ObjectNode output) { + private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DevicePackageRequest.Step step, ObjectNode output) { String checksum = entity instanceof RuleChain ? packageEntities.checksum(tenantId, id) : EntityChecksum.of(entity); - return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DeviceUpdateRequest.Action.CREATE)); + return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DevicePackageRequest.Action.CREATE)); } private static ObjectNode output(EntityId id, String name) { @@ -775,7 +932,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } } - /** Replaces ${.} of entities this update has saved, e.g. the id of a converter it created. */ + /** Replaces ${.} of entities the request has saved, e.g. the id of a converter it created. */ static JsonNode resolvePlaceholders(JsonNode node, Map aliasOutputs) { if (node == null) { return null; @@ -834,17 +991,29 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null; } - /** What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the update. */ + /** + * What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the install + * or update. + */ private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) { for (SavedEntity saved : applied.saved()) { try { - logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), + CustomerId customerId = saved.entity() instanceof HasCustomerId owned ? owned.getCustomerId() : null; + logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), customerId, saved.created() ? ActionType.ADDED : ActionType.UPDATED, user); if (saved.id().getEntityType() != EntityType.DEVICE) { autoCommit(user, saved.id()); } } catch (Exception e) { - log.warn("[{}] Failed to log the device package update of {}", tenantId, saved.id(), e); + log.warn("[{}] Failed to log the device package change of {}", tenantId, saved.id(), e); + } + } + for (SavedEntity saved : applied.grouped()) { + try { + logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), ((HasCustomerId) saved.entity()).getCustomerId(), + ActionType.ADDED_TO_ENTITY_GROUP, user, saved.id().toString(), applied.entityGroup().getId().toString(), applied.entityGroup().getName()); + } catch (Exception e) { + log.warn("[{}] Failed to log adding {} to its entity group", tenantId, saved.id(), e); } } for (StepAttributes step : applied.attributes()) { @@ -855,7 +1024,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e); } } - for (DeviceUpdateRequest.Step step : applied.connectorSteps()) { + for (DevicePackageRequest.Step step : applied.connectorSteps()) { try { saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity()); } catch (Exception e) { @@ -903,9 +1072,20 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database * error, as a common message, with the details in the log. */ + static JsonNode limitOf(Throwable e) { + SubscriptionException subscription = ExceptionUtils.throwableOfType(e, SubscriptionException.class); + if (subscription != null) { + return JacksonUtil.valueToTree(ThingsboardErrorResponse.ofSubscriptionViolation(subscription.getMessage(), subscription.getErrorCode(), + subscription.getEntry(), subscription.getValue(), HttpStatus.FORBIDDEN)); + } + EntitiesLimitExceededException entities = ExceptionUtils.throwableOfType(e, EntitiesLimitExceededException.class); + return entities == null ? null + : JacksonUtil.valueToTree(ThingsboardEntitiesLimitExceededResponse.of(entities.getMessage(), entities.getEntityType(), entities.getLimit())); + } + static String userMessage(Throwable e) { if (e instanceof EntityVersionMismatchException) { - return "Someone changed it while you were reviewing the update. Check the update again."; + return "Someone changed it meanwhile. Check the package again."; } if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException || e instanceof SubscriptionException) { @@ -927,29 +1107,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i */ private static Set ownedIds(DeviceInstalledItemDescriptor descriptor) { Set ids = new HashSet<>(createdIds(descriptor).keySet()); - ids.removeAll(usedExistingIds(descriptor).keySet()); - return ids; - } - - /** - * The entities the user chose to use as they were. An install made before the descriptor kept them has them only in - * its install state, which the first update carries over into the descriptor. - */ - private static Map usedExistingIds(DeviceInstalledItemDescriptor descriptor) { - Map ids = new LinkedHashMap<>(); - if (descriptor.getUsedExistingEntityIds() != null) { - descriptor.getUsedExistingEntityIds().forEach(id -> ids.put(id.getId(), id)); - return ids; - } - Map createdIds = createdIds(descriptor); - if (descriptor.getInstallState() != null) { - descriptor.getInstallState().values().forEach(state -> { - UUID id = toUuid(state.path("entityOutput").path("id").asText()); - if (id != null && "use-existing".equals(state.path("resolution").asText()) && createdIds.containsKey(id)) { - ids.put(id, createdIds.get(id)); - } - }); - } + descriptor.getUsedExistingEntityIdsIncludingLegacy().forEach(id -> ids.remove(id.getId())); return ids; } @@ -961,8 +1119,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return ids; } - private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) { - DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class); + private static DevicePackageRequest.Step copyWithEntity(DevicePackageRequest.Step step, JsonNode entity) { + DevicePackageRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DevicePackageRequest.Step.class); if (entity != null) { copy.setEntity(entity); } @@ -972,6 +1130,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) { } + @FunctionalInterface + private interface PackageChange { + Applied apply() throws Exception; + } + private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) { } @@ -982,8 +1145,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } private record Applied(DeviceInstalledItemDescriptor descriptor, Map outputs, List saved, - List connectorSteps, List attributes, - Map aliasOutputs) { + List connectorSteps, List attributes, + Map aliasOutputs, EntityGroup entityGroup, List grouped) { + } + + /** + * Where an install opened from a customer's or a device group's page puts its entities. A new device follows the + * group's customer when no customer is given, as a device saved into a group does; an update has none. + */ + private record Placement(CustomerId customerId, CustomerId deviceCustomerId, EntityGroup entityGroup) { + static final Placement NONE = new Placement(null, null, null); } /** A step that failed: the transaction rolls back, and the wizard shows which step it was. */ diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index ddbe8ec5d7..86f6456300 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -8,15 +8,22 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.stereotype.Service; import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.Dashboard; +import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.cf.CalculatedField; import org.thingsboard.server.common.data.cf.CalculatedFieldType; +import org.thingsboard.server.common.data.cf.configuration.ArgumentsBasedCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.group.EntityGroupInfo; @@ -43,6 +50,7 @@ import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescript import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; import org.thingsboard.server.common.data.subscription.SubscriptionException; +import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; @@ -91,8 +99,11 @@ import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; @Service @TbCoreComponent @@ -251,7 +262,7 @@ public class DefaultIotHubService implements IotHubService { } private EntityGroupInfo checkEntityGroup(SecurityUser user, EntityGroupId entityGroupId) throws ThingsboardException { - EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoById(user.getTenantId(), entityGroupId); + EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(user.getTenantId(), entityGroupId); if (entityGroup == null) { throw new IllegalArgumentException("Entity group with id [" + entityGroupId + "] is not found"); } @@ -268,6 +279,7 @@ public class DefaultIotHubService implements IotHubService { } calculatedField.setId(null); calculatedField.setTenantId(tenantId); + mapTenantReferences(calculatedField, tenantId); if (data != null && data.has("entityId")) { EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class); calculatedField.setEntityId(entityId); @@ -292,6 +304,7 @@ public class DefaultIotHubService implements IotHubService { } alarmRule.setId(null); alarmRule.setTenantId(tenantId); + mapTenantReferences(alarmRule, tenantId); if (data != null && data.has("entityId")) { EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class); alarmRule.setEntityId(entityId); @@ -421,7 +434,7 @@ public class DefaultIotHubService implements IotHubService { String itemType = installedItem.getItemType(); if ("DEVICE".equals(itemType)) { - // Updated in one transaction from the install wizard of the new version, see DevicePackageUpdateService + // Updated in one transaction from the install wizard of the new version, see DevicePackageService throw new IllegalArgumentException("A device package is updated by the install wizard of the new version"); } IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); @@ -531,6 +544,7 @@ public class DefaultIotHubService implements IotHubService { existing.setName(newCf.getName()); existing.setType(newCf.getType()); existing.setConfiguration(newCf.getConfiguration()); + mapTenantReferences(existing, tenantId); tbCalculatedFieldService.save(existing, user); } @@ -551,9 +565,26 @@ public class DefaultIotHubService implements IotHubService { existing.setName(newCf.getName()); existing.setType(newCf.getType()); existing.setConfiguration(newCf.getConfiguration()); + mapTenantReferences(existing, tenantId); tbCalculatedFieldService.save(existing, user); } + private void mapTenantReferences(CalculatedField calculatedField, TenantId tenantId) { + if (calculatedField.getConfiguration() instanceof GeofencingCalculatedFieldConfiguration geofencingCfg) { + geofencingCfg.getZoneGroups().values().forEach(zoneGroupConfiguration -> { + if (zoneGroupConfiguration.getRefEntityId() != null && zoneGroupConfiguration.getRefEntityId().getEntityType() == EntityType.TENANT) { + zoneGroupConfiguration.setRefEntityId(tenantId); + } + }); + } else if (calculatedField.getConfiguration() instanceof ArgumentsBasedCalculatedFieldConfiguration argBasedConfig) { + argBasedConfig.getArguments().values().forEach(argument -> { + if (argument.getRefEntityId() != null && argument.getRefEntityId().getEntityType() == EntityType.TENANT) { + argument.setRefEntityId(tenantId); + } + }); + } + } + private void updateRuleChain(TenantId tenantId, RuleChainInstalledItemDescriptor descriptor, byte[] fileData) throws Exception { JsonNode json = JacksonUtil.toJsonNode(new String(fileData)); RuleChainMetaData metadata; @@ -674,6 +705,8 @@ public class DefaultIotHubService implements IotHubService { UUID itemId = UUID.fromString(versionInfo.get("itemId").asText()); String version = versionInfo.get("version").asText(); + validateDevicePackageEntities(tenantId, descriptor); + IotHubInstalledItem installedItem = new IotHubInstalledItem(); installedItem.setTenantId(tenantId); installedItem.setItemId(itemId); @@ -720,7 +753,9 @@ public class DefaultIotHubService implements IotHubService { /** * Deletes what a device package created, except the entities another installed device package * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package, - * and the ones the user had before and the package took as they were (use existing). + * and the ones the user had before and the package took as they were (use existing). A device profile that devices + * still use stays too, e.g. with the devices a LoRaWAN integration created, and any kept profile keeps what it refers + * to: TB deletes neither. * A kept integration loses the metadata entries the package added. */ private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, @@ -729,7 +764,7 @@ public class DefaultIotHubService implements IotHubService { if (createdEntityIds == null || createdEntityIds.isEmpty()) { return; } - Set usedExisting = usedExistingIds(descriptor); + Set usedExisting = descriptor.getUsedExistingEntityIdsIncludingLegacy().stream().map(EntityId::getId).collect(Collectors.toSet()); List otherPackages = new ArrayList<>(); Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, otherPackages); // An entity goes before what it refers to: a device before its profile, a profile before its default dashboard @@ -737,22 +772,42 @@ public class DefaultIotHubService implements IotHubService { List ordered = new ArrayList<>(createdEntityIds); Collections.reverse(ordered); ordered.sort(Comparator.comparingInt(id -> DELETE_ORDER.getOrDefault(id.getEntityType(), DELETE_ORDER.size()))); + // What a kept profile refers to: its default rule chain and dashboard, which come after it in the order + Set referencedByKeptProfiles = new HashSet<>(); for (EntityId entityId : ordered) { if (usedExisting.contains(entityId.getId())) { log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId()); removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); + profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId())); continue; } Set usedBy = usedByOtherPackages.get(entityId.getId()); if (usedBy != null) { log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy); removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); + profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId())); + continue; + } + if (referencedByKeptProfiles.contains(entityId.getId())) { + log.info("[{}] Kept {} {}: a kept device profile refers to it", tenantId, entityId.getEntityType(), entityId.getId()); + continue; + } + // The package's own devices are deleted by now; the ones left came from elsewhere, e.g. a LoRaWAN integration + long devices = countProfileDevices(tenantId, entityId, Set.of()); + if (devices > 0) { + log.info("[{}] Kept device profile {}: devices use it ({})", tenantId, entityId.getId(), devices); + profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId())); continue; } try { deleteDevicePackageEntity(tenantId, entityId, user); } catch (Exception e) { - log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e); + // A reference the package doesn't know of, e.g. a profile the user made later with the package's rule chain + if (ExceptionUtils.indexOfType(e, DataValidationException.class) >= 0) { + log.info("[{}] Kept {} {}: {}", tenantId, entityId.getEntityType(), entityId.getId(), ExceptionUtils.getRootCauseMessage(e)); + } else { + log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e); + } } } } @@ -773,8 +828,8 @@ public class DefaultIotHubService implements IotHubService { return; } try { - Integration integration = integrationService.findIntegrationById(tenantId, new IntegrationId(entityId.getId())); - if (integration == null || !(integration.getConfiguration() != null + // Only an integration of this tenant: the id comes from the stored descriptor + if (!(findDevicePackageEntity(tenantId, entityId) instanceof Integration integration) || !(integration.getConfiguration() != null && integration.getConfiguration().get("metadata") instanceof ObjectNode metadata) || keys.stream().noneMatch(metadata::has)) { return; @@ -811,16 +866,26 @@ public class DefaultIotHubService implements IotHubService { throw new IllegalArgumentException("Installed item not found"); } List kept = new ArrayList<>(); + List referenced = new ArrayList<>(); Set usedByItems = new HashSet<>(); int usedExistingCount = 0; if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { - Set usedExisting = usedExistingIds(dd); + Set usedExisting = dd.getUsedExistingEntityIdsIncludingLegacy().stream().map(EntityId::getId).collect(Collectors.toSet()); Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>()); + // The delete removes these before the profiles, so they don't keep a profile; a kept device does + Set deletedDevices = new HashSet<>(); + dd.getCreatedEntityIds().stream() + .filter(id -> id.getEntityType() == EntityType.DEVICE && !usedExisting.contains(id.getId()) && !usedByOtherPackages.containsKey(id.getId())) + .forEach(id -> deletedDevices.add(id.getId())); + Set created = new HashSet<>(); + dd.getCreatedEntityIds().forEach(id -> created.add(id.getId())); + Set keptIds = new HashSet<>(); for (EntityId entityId : dd.getCreatedEntityIds()) { Set usedBy = usedByOtherPackages.get(entityId.getId()); boolean taken = usedExisting.contains(entityId.getId()); if (usedBy != null || taken) { - kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null))); + kept.add(keptEntity(tenantId, entityId)); + keptIds.add(entityId.getId()); } if (usedBy != null) { usedByItems.addAll(usedBy); @@ -829,17 +894,65 @@ public class DefaultIotHubService implements IotHubService { usedExistingCount++; } } + for (EntityId entityId : dd.getCreatedEntityIds()) { + if (!keptIds.contains(entityId.getId()) && countProfileDevices(tenantId, entityId, deletedDevices) > 0) { + referenced.add(keptEntity(tenantId, entityId)); + keptIds.add(entityId.getId()); + } + } + // A kept profile, for whatever reason, keeps what it refers to + for (EntityId entityId : dd.getCreatedEntityIds()) { + if (!keptIds.contains(entityId.getId())) { + continue; + } + for (EntityId reference : profileReferences(tenantId, entityId)) { + if (created.contains(reference.getId()) && keptIds.add(reference.getId())) { + referenced.add(keptEntity(tenantId, reference)); + } + } + } } - return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount); + return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount, referenced); } - /** The entities the package took as they were at install (use existing); none for installs before 4.4.1 kept them. */ - private static Set usedExistingIds(DeviceInstalledItemDescriptor descriptor) { - Set ids = new HashSet<>(); - if (descriptor.getUsedExistingEntityIds() != null) { - descriptor.getUsedExistingEntityIds().forEach(id -> ids.add(id.getId())); + private InstalledItemKeptEntities.KeptEntity keptEntity(TenantId tenantId, EntityId entityId) { + String name = findDevicePackageEntity(tenantId, entityId) != null + ? entityService.fetchEntityName(tenantId, entityId).orElse(null) : null; + return new InstalledItemKeptEntities.KeptEntity(entityId, name); + } + + /** The default rule chains and dashboard of a device profile, which TB doesn't delete while it refers to them; none for another entity. */ + private List profileReferences(TenantId tenantId, EntityId profileId) { + List references = new ArrayList<>(); + if (profileId.getEntityType() != EntityType.DEVICE_PROFILE) { + return references; + } + DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(profileId.getId())); + if (profile != null) { + Stream.of(profile.getDefaultRuleChainId(), profile.getDefaultEdgeRuleChainId(), profile.getDefaultDashboardId()) + .filter(Objects::nonNull) + .forEach(references::add); + } + return references; + } + + /** + * How many devices use the device profile {@code entityId}, apart from {@code excludedDevices}; 0 for another entity. + * TB doesn't delete a profile that devices use. + */ + private long countProfileDevices(TenantId tenantId, EntityId entityId, Set excludedDevices) { + if (entityId.getEntityType() != EntityType.DEVICE_PROFILE) { + return 0; } - return ids; + DeviceProfileId profileId = new DeviceProfileId(entityId.getId()); + long count = deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(tenantId, profileId, new PageLink(1)).getTotalElements(); + for (UUID deviceId : excludedDevices) { + Device device = deviceService.findDeviceById(tenantId, new DeviceId(deviceId)); + if (device != null && profileId.equals(device.getDeviceProfileId())) { + count--; + } + } + return Math.max(count, 0); } /** The other installed device packages' entities, by id; the packages' descriptors go to {@code otherPackages}. */ @@ -864,36 +977,56 @@ public class DefaultIotHubService implements IotHubService { return usedBy; } - private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException { - switch (entityId.getEntityType()) { - case DEVICE -> { - var device = deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId())); - if (device != null) tbDeviceService.delete(device, user); - } - case DEVICE_PROFILE -> { - var profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId())); - if (profile != null) tbDeviceProfileService.delete(profile, user); - } - case DASHBOARD -> { - var dashboard = dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId())); - if (dashboard != null) tbDashboardService.delete(dashboard, user); - } - case RULE_CHAIN -> { - var ruleChain = ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId())); - if (ruleChain != null) tbRuleChainService.delete(ruleChain, user); - } - case INTEGRATION -> { - IntegrationId integrationId = new IntegrationId(entityId.getId()); - var integration = integrationService.findIntegrationById(tenantId, integrationId); - if (integration != null) { - integrationService.deleteIntegration(tenantId, integrationId); - } - } - case CONVERTER -> { - var converter = converterService.findConverterById(tenantId, new ConverterId(entityId.getId())); - if (converter != null) tbConverterService.delete(converter, user); + private void validateDevicePackageEntities(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) { + if (descriptor == null) { + throw new IllegalArgumentException("Device package descriptor is required"); + } + List entityIds = new ArrayList<>(); + if (descriptor.getCreatedEntityIds() != null) { + entityIds.addAll(descriptor.getCreatedEntityIds()); + } + if (descriptor.getDashboardId() != null) { + entityIds.add(descriptor.getDashboardId()); + } + if (descriptor.getUsedExistingEntityIds() != null) { + entityIds.addAll(descriptor.getUsedExistingEntityIds()); + } + for (EntityId entityId : entityIds) { + if (entityId == null || findDevicePackageEntity(tenantId, entityId) == null) { + throw new IllegalArgumentException("Device package entity not found: " + entityId); } - default -> log.warn("[{}] Unsupported entity type for device package delete: {}", tenantId, entityId.getEntityType()); + } + } + + private HasTenantId findDevicePackageEntity(TenantId tenantId, EntityId entityId) { + HasTenantId entity = switch (entityId.getEntityType()) { + case DEVICE -> deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId())); + case DEVICE_PROFILE -> deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId())); + case DASHBOARD -> dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId())); + case RULE_CHAIN -> ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId())); + case INTEGRATION -> integrationService.findIntegrationById(tenantId, new IntegrationId(entityId.getId())); + case CONVERTER -> converterService.findConverterById(tenantId, new ConverterId(entityId.getId())); + default -> null; + }; + return entity != null && tenantId.equals(entity.getTenantId()) ? entity : null; + } + + private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException { + HasTenantId entity = findDevicePackageEntity(tenantId, entityId); + if (entity instanceof Device device) { + tbDeviceService.delete(device, user); + } else if (entity instanceof DeviceProfile profile) { + tbDeviceProfileService.delete(profile, user); + } else if (entity instanceof Dashboard dashboard) { + tbDashboardService.delete(dashboard, user); + } else if (entity instanceof RuleChain ruleChain) { + tbRuleChainService.delete(ruleChain, user); + } else if (entity instanceof Integration integration) { + integrationService.deleteIntegration(tenantId, integration.getId()); + } else if (entity instanceof Converter converter) { + tbConverterService.delete(converter, user); + } else { + log.warn("[{}] Skipped device package entity {}: not found", tenantId, entityId); } } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java similarity index 67% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java index a62f556c57..f79f023672 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java @@ -10,28 +10,33 @@ import java.util.Map; import java.util.UUID; /** - * The update of an installed device package as the install wizard planned it: the entity of each install step - * of the new version, already resolved from its template, and what to do with it. The server applies all of it - * in one transaction, together with the new version of the installed item, or nothing. + * The install or update of a device package as the install wizard planned it: the entity of each install step + * of the version being installed, already resolved from its template, and what to do with it. The server applies + * all of it in one transaction, together with the installed item, or nothing. */ @Data -public class DeviceUpdateRequest { +public class DevicePackageRequest { private String versionId; - // The version installed when the wizard planned the update; the update fails if the package changed since + // Update only: the version installed when the wizard planned the update, which fails if the package changed since private UUID fromVersionId; - // The install method of the new version's steps; the installed one when not set + // The install method of the steps; an update without it keeps the installed one private String selectedInstallMethod; // The form values of the install state, by step: the server adds the entities to it private Map installState; + // Install only, from a customer's or a device group's page: the customer the device, the gateway and the dashboard + // go to, and the group the created device or gateway is added to. An update ignores them + private UUID customerId; + private UUID entityGroupId; private List steps; public enum Action { - // Taken as it is: the new version doesn't change it, or the user kept an entity they had + // Taken as it is: an update's new version doesn't change it, or the user kept an entity they had KEEP, // Takes the entity from the step OVERWRITE, - // A new entity: new in this version, deleted since install, or a copy next to one with the same name + // A new entity: one the package installs, a step new in this version or deleted since install, or a copy + // next to one with the same name CREATE } @@ -51,13 +56,13 @@ public class DeviceUpdateRequest { private Long expectedVersion; // The user confirmed overwriting an entity of another package or one they didn't install with this package private boolean confirmed; - // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity this - // update creates is left for the server, which knows its id only once it is created. + // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity the + // request creates is left for the server, which knows its id only once it is created. private JsonNode entity; // DEVICE and GATEWAY: the credentials template, if any private JsonNode credentials; // OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity, - // they may keep ${.} of an entity this update creates. + // they may keep ${.} of an entity the request creates. private JsonNode serverAttributes; private JsonNode sharedAttributes; // The resolution the install state records for it @@ -65,7 +70,8 @@ public class DeviceUpdateRequest { // INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the // integration, e.g. one the package took as it was; null removes an entry private JsonNode metadata; - // UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check + // UPLINK_CONVERTER: the step takes ThingsBoard's default converter. The install state records it, so that a later + // update checks that converter against ThingsBoard's default one private boolean defaultConverter; /** diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java similarity index 55% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java index 5c8ec6e8d7..f7d75ff652 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.iot_hub; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.AllArgsConstructor; import lombok.Data; @@ -17,7 +18,7 @@ import java.util.Map; @Data @NoArgsConstructor @AllArgsConstructor -public class DeviceUpdateResult { +public class DevicePackageResult { private boolean success; private String errorMessage; @@ -25,13 +26,19 @@ public class DeviceUpdateResult { private DeviceInstalledItemDescriptor descriptor; // By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token} private Map outputs; + // When a step failed on an entity or subscription limit: the same body ThingsBoard answers such a request with (403) + private JsonNode limit; - public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { - return new DeviceUpdateResult(true, null, null, descriptor, outputs); + public static DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { + return new DevicePackageResult(true, null, null, descriptor, outputs, null); } - public static DeviceUpdateResult error(String errorMessage, String failedStep) { - return new DeviceUpdateResult(false, errorMessage, failedStep, null, null); + public static DevicePackageResult error(String errorMessage, String failedStep) { + return error(errorMessage, failedStep, null); + } + + public static DevicePackageResult error(String errorMessage, String failedStep, JsonNode limit) { + return new DevicePackageResult(false, errorMessage, failedStep, null, null, limit); } } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java similarity index 59% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java index 5688056c98..60103c6e01 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java @@ -7,13 +7,16 @@ import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; -/** Updates an installed device package to another version of its item. */ -public interface DevicePackageUpdateService { +/** Installs a device package, or updates an installed one to another version of its item. */ +public interface DevicePackageService { /** The package's entities as they are now: whether they still exist, changed since, or are shared. */ List check(SecurityUser user, IotHubInstalledItemId installedItemId); + /** Installs the version in one transaction, together with its installed item, or nothing. */ + DevicePackageResult install(SecurityUser user, DevicePackageRequest request); + /** Applies the update in one transaction, together with the new version of the installed item, or nothing. */ - DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request); + DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request); } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java index ad517c5327..7c3cfdbeb7 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java @@ -9,7 +9,10 @@ import org.thingsboard.server.common.data.id.EntityId; import java.util.List; -/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */ +/** + * What deleting an installed item keeps: what other installed items use too, what the user had before it, and what other + * tenant entities refer to (a LoRaWAN integration creates its devices on the first uplink, not the package). + */ @Data @NoArgsConstructor @AllArgsConstructor @@ -20,6 +23,9 @@ public class InstalledItemKeptEntities { private int usedByItemsCount; // How many of the kept entities the user had before and the package took as they were (use existing) private int usedExistingCount; + // What other tenant entities refer to: the package's device profiles that devices use, and the default rule chains and + // dashboard of a kept profile. Apart from entities, which an update reads as shared with other packages + private List referencedEntities; @Data @NoArgsConstructor diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java index a12470271f..b404844e70 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; import jakarta.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; diff --git a/application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java b/application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java index b7759287af..28b0d9d27c 100644 --- a/application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java +++ b/application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java @@ -106,6 +106,8 @@ public class TbMailSender extends JavaMailSenderImpl { } } javaMailProperties.put(MAIL_PROP + protocol + ".starttls.enable", enableTls); + // Angus Mail checks the server identity unless this is set + javaMailProperties.put(MAIL_PROP + protocol + ".ssl.checkserveridentity", "false"); if (enableTls && jsonConfig.has("tlsVersion") && !jsonConfig.get("tlsVersion").isNull()) { String tlsVersion = jsonConfig.get("tlsVersion").asText(); if (StringUtils.isNoneEmpty(tlsVersion)) { diff --git a/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java b/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java index 496afd8323..9625fa596e 100644 --- a/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java +++ b/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java @@ -114,6 +114,9 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple NotificationTemplate notificationTemplate; if (request.getTemplateId() != null) { notificationTemplate = notificationTemplateService.findNotificationTemplateById(tenantId, request.getTemplateId()); + if (notificationTemplate != null && !isTenantOrSystem(tenantId, notificationTemplate.getTenantId())) { + notificationTemplate = null; + } } else { notificationTemplate = request.getTemplate(); } @@ -126,7 +129,7 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple List targets = new ArrayList<>(); for (UUID targetId : request.getTargets()) { NotificationTarget target = notificationTargetService.findNotificationTargetById(tenantId, new NotificationTargetId(targetId)); - if (target != null) { + if (target != null && tenantId.equals(target.getTenantId())) { targets.add(target); } else { log.debug("Unknown notification target {} in request {}", targetId, request); @@ -516,6 +519,10 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple return "notification"; } + private static boolean isTenantOrSystem(TenantId tenantId, TenantId ownerId) { + return tenantId.equals(ownerId) || ownerId.isSysTenantId(); + } + @Autowired public void setChannels(List channels, NotificationCenter webNotificationChannel) { this.channels = channels.stream().collect(Collectors.toMap(NotificationChannel::getDeliveryMethod, c -> c)); diff --git a/application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java b/application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java index 9c7f4b0721..6837db7846 100644 --- a/application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java +++ b/application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java @@ -10,7 +10,7 @@ import lombok.RequiredArgsConstructor; import lombok.Setter; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; diff --git a/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java b/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java index fdee2f9c41..a4dc0125ea 100644 --- a/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java +++ b/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.notification.provider; import com.github.benmanes.caffeine.cache.Cache; @@ -52,8 +53,11 @@ public class DefaultFirebaseService implements FirebaseService { } }); + // mutable-content lets the iOS app's notification service extension + // add the template icon to the push before iOS shows it Aps.Builder apsConfig = Aps.builder() - .setSound("default"); + .setSound("default") + .setMutableContent(true); if (badge != null) { apsConfig.setBadge(badge); } diff --git a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java index 63c840e7e1..3d7e67456c 100644 --- a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java +++ b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java @@ -26,6 +26,7 @@ import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.common.data.widget.WidgetTypeDetails; import org.thingsboard.server.dao.resource.ImageService; import org.thingsboard.server.dao.resource.ResourceService; +import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.security.model.SecurityUser; @@ -57,6 +58,22 @@ public class DefaultTbResourceService extends AbstractTbEntityService implements @Override public TbResourceInfo save(TbResource resource, SecurityUser user) throws ThingsboardException { + if (resource.getId() != null) { + TbResourceInfo existing = checkNotNull(resourceService.findResourceInfoById(resource.getTenantId(), resource.getId())); + if ((resource.getResourceType() != null && resource.getResourceType() != existing.getResourceType()) || + (resource.getResourceSubType() != null && resource.getResourceSubType() != existing.getResourceSubType())) { + throw new DataValidationException("Resource type can't be changed"); + } + resource.setTenantId(existing.getTenantId()); + resource.setCustomerId(existing.getCustomerId()); + resource.setResourceType(existing.getResourceType()); + resource.setResourceSubType(existing.getResourceSubType()); + resource.setResourceKey(existing.getResourceKey()); + resource.setCreatedTime(existing.getCreatedTime()); + if (resource.getData() == null) { + resource.setEtag(existing.getEtag()); + } + } if (resource.getResourceType() == ResourceType.IMAGE) { throw new IllegalArgumentException("Image resource type is not supported"); } diff --git a/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java b/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java index 7cd5cc685c..9859d9052b 100644 --- a/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java +++ b/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java @@ -274,7 +274,7 @@ public class DefaultSchedulerService extends AbstractPartitionBasedService entityGroupFuture = entityGroupService.findEntityGroupInfoByIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId())); + ListenableFuture entityGroupFuture = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId())); Futures.addCallback(entityGroupFuture, getCallback(callback, entityGroup -> { if (entityGroup == null) { return ValidationResult.entityNotFound("Entity group with requested id wasn't found!"); diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java b/application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java index 2db08ca0b7..41af05e308 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java +++ b/application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java @@ -1,11 +1,15 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.security.auth; import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.token.RawAccessJwtToken; +import java.util.Collection; + public abstract class AbstractJwtAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = -6212297506742428406L; @@ -14,7 +18,7 @@ public abstract class AbstractJwtAuthenticationToken extends AbstractAuthenticat private SecurityUser securityUser; public AbstractJwtAuthenticationToken(RawAccessJwtToken unsafeToken) { - super(null); + super((Collection) null); this.rawAccessToken = unsafeToken; this.setAuthenticated(false); } diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java b/application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java index 6ff5ef42be..fe4b9fc987 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java +++ b/application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java @@ -4,7 +4,7 @@ package org.thingsboard.server.service.security.auth.jwt; import jakarta.servlet.http.HttpServletRequest; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; @@ -19,8 +19,9 @@ public class SkipPathRequestMatcher implements RequestMatcher { public SkipPathRequestMatcher(List pathsToSkip, List pathsToProcess) { Assert.notNull(pathsToSkip, "List of paths to skip is required."); - List skip = pathsToSkip.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList()); - List process = pathsToProcess.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList()); + PathPatternRequestMatcher.Builder builder = PathPatternRequestMatcher.withDefaults(); + List skip = pathsToSkip.stream().map(builder::matcher).collect(Collectors.toList()); + List process = pathsToProcess.stream().map(builder::matcher).collect(Collectors.toList()); skipMatchers = new OrRequestMatcher(skip); processMatchers = new OrRequestMatcher(process); } diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java index 95de1eda02..4730ebb2b0 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java +++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.security.auth.oauth2; import com.fasterxml.jackson.core.JsonProcessingException; import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @@ -28,7 +29,7 @@ public class CustomOAuth2ClientMapper extends AbstractOAuth2ClientMapper impleme private static final String PROVIDER_ACCESS_TOKEN = "provider-access-token"; - private RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); + private final RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); @Override public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Client auth2Client) { @@ -37,15 +38,16 @@ public class CustomOAuth2ClientMapper extends AbstractOAuth2ClientMapper impleme return getOrCreateSecurityUserFromOAuth2User(oauth2User, auth2Client); } - private synchronized OAuth2User getOAuth2User(OAuth2AuthenticationToken token, String providerAccessToken, OAuth2CustomMapperConfig custom) { + private OAuth2User getOAuth2User(OAuth2AuthenticationToken token, String providerAccessToken, OAuth2CustomMapperConfig custom) { + RestTemplateBuilder builder = restTemplateBuilder; if (!StringUtils.isEmpty(custom.getUsername()) && !StringUtils.isEmpty(custom.getPassword())) { - restTemplateBuilder = restTemplateBuilder.basicAuthentication(custom.getUsername(), custom.getPassword()); + builder = builder.basicAuthentication(custom.getUsername(), custom.getPassword()); } if (custom.isSendToken() && !StringUtils.isEmpty(providerAccessToken)) { - restTemplateBuilder = restTemplateBuilder.defaultHeader(PROVIDER_ACCESS_TOKEN, providerAccessToken); + builder = builder.defaultHeader(PROVIDER_ACCESS_TOKEN, providerAccessToken); } - RestTemplate restTemplate = restTemplateBuilder.build(); + RestTemplate restTemplate = builder.build(); String request; try { request = JacksonUtil.getObjectMapperWithJavaTimeModule().writeValueAsString(token.getPrincipal()); diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java index 1a0bd06dcf..065db93fc7 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java +++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.security.auth.oauth2; import jakarta.servlet.http.HttpServletRequest; @@ -7,7 +8,7 @@ import lombok.Data; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java b/application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java index 98aff443a0..af4f2af719 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java +++ b/application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java @@ -1,12 +1,15 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.security.auth.pat; import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.token.ApiKeyAuthRequest; import java.io.Serial; +import java.util.Collection; public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken { @@ -17,7 +20,7 @@ public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken { private SecurityUser securityUser; public ApiKeyAuthenticationToken(ApiKeyAuthRequest apiKeyAuthRequest) { - super(null); + super((Collection) null); this.apiKeyAuthRequest = apiKeyAuthRequest; setAuthenticated(false); } diff --git a/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java b/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java index 632dae9836..56fdba5d93 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java +++ b/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java @@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.id.HasId; import org.thingsboard.server.common.data.id.ReportTemplateId; import org.thingsboard.server.common.data.id.TbResourceId; import org.thingsboard.server.common.data.menu.CustomMenuInfo; +import org.thingsboard.server.common.data.pat.ApiKeyInfo; import org.thingsboard.server.common.data.permission.GroupPermission; import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Resource; @@ -525,6 +526,9 @@ public class CustomerUserPermissions extends AbstractPermissions { if (!user.getTenantId().equals(entity.getTenantId())) { return false; } + if (!(entity instanceof ApiKeyInfo apiKeyInfo) || !user.getId().equals(apiKeyInfo.getUserId())) { + return false; + } // This entity does not have groups, so we are checking only generic level permissions return user.getUserPermissions().hasGenericPermission(Resource.API_KEY, operation); } diff --git a/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java b/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java index 5a582026fd..ff2185e91b 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java +++ b/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java @@ -332,7 +332,7 @@ public class DefaultSystemSecurityService implements SystemSecurityService { @Override public AccessJwtToken createUserAccessToken(TenantId tenantId, UserId userId) throws ThingsboardException { User user = userService.findUserById(tenantId, userId); - if (user == null) { + if (user == null || !user.getTenantId().equals(tenantId)) { throw new ThingsboardException("Configured user [id: " + userId + "] was not found in system. Please use other user credentials.", ThingsboardErrorCode.BAD_REQUEST_PARAMS); } UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, userId); diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java b/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java index 742f9b22ec..4e8467cba5 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java @@ -422,7 +422,13 @@ public class DefaultTbEntityDataSubscriptionService implements TbEntityDataSubsc List entities = ctx.getEntitiesData(); ctx.cancelTasks(); ctx.clearEntitySubscriptions(); - if (entities.isEmpty()) { + if (ctx.isOwnerScoped()) { + ctx.fetchAlarms(); + TbAlarmDataSubCtx finalCtx = ctx; + ScheduledFuture task = scheduler.scheduleWithFixedDelay( + () -> refreshAlarmQuery(finalCtx), dynamicPageLinkRefreshInterval, dynamicPageLinkRefreshInterval, TimeUnit.SECONDS); + finalCtx.setRefreshTask(task); + } else if (entities.isEmpty()) { AlarmDataUpdate update = new AlarmDataUpdate(cmd.getCmdId(), new PageData<>(), null, 0, 0); ctx.sendWsMsg(update); } else { diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java index 6306ad7ab3..10db008227 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java @@ -66,6 +66,9 @@ public abstract class TbAbstractDataSubCtx newDataMap) { + } + @Override protected synchronized void update() { PageData newData = findEntityData(); @@ -78,6 +81,7 @@ public abstract class TbAbstractDataSubCtx newDataMap = newData.getData().stream().collect(Collectors.toMap(EntityData::getEntityId, Function.identity(), (a, b) -> a)); if (oldDataMap.size() == newDataMap.size() && oldDataMap.keySet().equals(newDataMap.keySet())) { log.trace("[{}][{}] No updates to entity data found", sessionRef.getSessionId(), cmdId); + onSameEntities(newDataMap); } else { this.data = newData; doUpdate(newDataMap); diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java index 3b7c0824c1..fb2bef81ef 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java @@ -101,7 +101,10 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { return; } AlarmDataUpdate update; - if (!entitiesMap.isEmpty()) { + if (isOwnerScoped()) { + setAndMergeAlarmsData(findOwnerAlarms()); + update = new AlarmDataUpdate(cmdId, alarms, null, maxEntitiesPerAlarmSubscription, 0); + } else if (!entitiesMap.isEmpty()) { long start = System.currentTimeMillis(); PageData alarms = alarmService.findAlarmDataByQueryForEntities(getTenantId(), getMergedUserPermissions(), query, getOrderedEntityIds()); @@ -116,9 +119,39 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { sendWsMsg(update); } + public boolean isOwnerScoped() { + return query != null && query.getEntityFilter() == null; + } + + private PageData findOwnerAlarms() { + long start = System.currentTimeMillis(); + PageData result = alarmService.findAlarmDataByQuery(getTenantId(), getCustomerId(), getMergedUserPermissions(), query); + stats.getAlarmQueryInvocationCnt().incrementAndGet(); + stats.getAlarmQueryTimeSpent().addAndGet(System.currentTimeMillis() - start); + return result; + } + + private void refreshOwnerAlarms() { + if (stopped) { + return; + } + PageData fresh = findOwnerAlarms(); + if (alarms != null && alarms.getTotalElements() == fresh.getTotalElements() && alarms.getData().equals(fresh.getData())) { + return; + } + setAndMergeAlarmsData(fresh); + sendWsMsg(new AlarmDataUpdate(cmdId, alarms, null, maxEntitiesPerAlarmSubscription, 0)); + } + public void fetchData() { resetInvocationCounter(); log.trace("[{}] Fetching data: {}", cmdId, alarmInvocationAttempts); + if (isOwnerScoped()) { + data = PageData.emptyPageData(); + entitiesMap.clear(); + tooManyEntities = false; + return; + } super.fetchData(); entitiesMap.clear(); tooManyEntities = data.hasNext(); @@ -232,6 +265,9 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { } public void cleanupOldAlarms() { + if (query.getPageLink().getTimeWindow() <= 0) { + return; + } long expTime = System.currentTimeMillis() - query.getPageLink().getTimeWindow(); boolean shouldRefresh = false; for (AlarmData alarmData : alarms.getData()) { @@ -248,7 +284,7 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { private boolean filter(Alarm alarm) { AlarmDataPageLink filter = query.getPageLink(); long startTs = System.currentTimeMillis() - filter.getTimeWindow(); - if (alarm.getCreatedTime() < startTs) { + if (filter.getTimeWindow() > 0 && alarm.getCreatedTime() < startTs) { //Skip update that does not match time window. return false; } @@ -292,6 +328,11 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { } public synchronized void checkAndResetInvocationCounter() { + if (isOwnerScoped()) { + resetInvocationCounter(); + refreshOwnerAlarms(); + return; + } boolean fetchNeeded = this.alarmInvocationAttempts > maxAlarmQueriesPerRefreshInterval; resetInvocationCounter(); if (fetchNeeded) { diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java index 1197da0d09..fa599ecac0 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java @@ -3,6 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.subscription; +import java.util.Objects; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -177,6 +178,38 @@ public class TbEntityDataSubCtx extends TbAbstractDataSubCtx { }); } + @Override + protected void onSameEntities(Map newDataMap) { + List changed = new ArrayList<>(); + for (EntityData current : data.getData()) { + EntityData fresh = newDataMap.get(current.getEntityId()); + Map freshFields = fresh != null && fresh.getLatest() != null ? fresh.getLatest().get(EntityKeyType.ENTITY_FIELD) : null; + if (freshFields == null || freshFields.isEmpty() || current.getLatest() == null) { + continue; + } + if (!sameFieldValues(current.getLatest().get(EntityKeyType.ENTITY_FIELD), freshFields)) { + current.getLatest().put(EntityKeyType.ENTITY_FIELD, freshFields); + changed.add(new EntityData(current.getEntityId(), false, false, Map.of(EntityKeyType.ENTITY_FIELD, freshFields), null)); + } + } + if (!changed.isEmpty()) { + sendWsMsg(new EntityDataUpdate(cmdId, null, changed, maxEntitiesPerDataSubscription)); + } + } + + private static boolean sameFieldValues(Map current, Map fresh) { + if (current == null || current.size() != fresh.size()) { + return false; + } + for (Map.Entry entry : fresh.entrySet()) { + TsValue value = current.get(entry.getKey()); + if (value == null || !Objects.equals(value.getValue(), entry.getValue().getValue())) { + return false; + } + } + return true; + } + @Override public synchronized void doUpdate(Map newDataMap) { this.updateLatestTsData(this.data); diff --git a/application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java b/application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java index d5ecca2d90..5282b0df56 100644 --- a/application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java +++ b/application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java @@ -7,7 +7,7 @@ import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; diff --git a/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java b/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java index 7bb4775f16..bec30a395e 100644 --- a/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java +++ b/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.utils; import com.google.common.hash.HashFunction; @@ -43,13 +44,20 @@ public class MiscUtils { getPort(request)); } - public static String getScheme(HttpServletRequest request){ - String scheme = request.getScheme(); + public static String getScheme(HttpServletRequest request) { String forwardedProto = request.getHeader("x-forwarded-proto"); - if (forwardedProto != null) { - scheme = forwardedProto; + if (isHttpScheme(forwardedProto)) { + return forwardedProto.toLowerCase(); + } + String scheme = request.getScheme(); + if (forwardedProto == null && isHttpScheme(scheme)) { + return scheme.toLowerCase(); } - return scheme; + return request.isSecure() ? "https" : "http"; + } + + private static boolean isHttpScheme(String scheme) { + return "http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme); } public static String getDomainName(HttpServletRequest request){ diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 992977aa83..35ba0f140d 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -13,6 +13,9 @@ server: port: "${HTTP_BIND_PORT:8080}" # Server forward headers strategy. Required for SWAGGER UI when reverse proxy is used forward_headers_strategy: "${HTTP_FORWARD_HEADERS_STRATEGY:framework}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" # Server SSL configuration ssl: # Enable/disable SSL support @@ -1205,16 +1208,15 @@ spring.mvc.cors: allow-credentials: "${TB_CORS_ALLOW_CREDENTIALS:true}" # General spring parameters -# Miscellaneous Spring Boot settings including circular references, Freemarker, async request timeout, path matching strategy, and static resource chain. +# Miscellaneous Spring Boot settings including circular references, Freemarker, async request timeout, and path matching strategy. spring.main.allow-circular-references: "true" # Spring Boot configuration property that controls whether circular dependencies between beans are allowed. spring.freemarker.checkTemplateLocation: "false" # spring freemarker configuration spring.mvc.async.request-timeout: "${SPRING_MVC_ASYNC_REQUEST_TIMEOUT:30000}" # The default timeout for asynchronous requests in milliseconds spring.mvc.pathmatch.matching-strategy: "ANT_PATH_MATCHER" # For endpoints matching in Swagger -spring.resources.chain: - compressed: "true" # This property enables or disables support for serving pre-compressed resources (for example, a .gzip or .br file) - strategy: - content: - enabled: "true" # This property enables or disables the content Version Strategy. This strategy allows Spring to generate a unique version for static resources, which is based on the content of the resource +spring.http.converters.preferred-json-mapper: "jackson2" # JSON mapper for HTTP message conversion; ThingsBoard uses Jackson 2 +spring.web.resources.chain: + enabled: "true" # Enables the Spring resource chain explicitly instead of relying on a webjars locator being on the classpath + compressed: "true" # Serve the pre-compressed .br/.gz copies of the UI files built by ui-ngx when the client accepts them spring.servlet.multipart.max-file-size: "${SPRING_SERVLET_MULTIPART_MAX_FILE_SIZE:50MB}" # Total file size cannot exceed 50MB when configuring file uploads spring.servlet.multipart.max-request-size: "${SPRING_SERVLET_MULTIPART_MAX_REQUEST_SIZE:50MB}" # Total request size for a multipart/form-data cannot exceed 50MB @@ -2554,7 +2556,7 @@ queue: # Statistics printing interval for Edge services print-interval-ms: "${TB_QUEUE_EDGE_STATS_PRINT_INTERVAL_MS:60000}" integration: - # Name of hash function used for consistent hash ring in Cluster Mode. See architecture docs for more details. Valid values - murmur3_32, murmur3_128 or sha256 + # Number of partitions in each integration queue; there is one queue per integration type. Must match TB_QUEUE_INTEGRATION_PARTITIONS on the Integration Executors, otherwise downlinks, integration validation and Check connection may not reach the executor that runs the integration. partitions: "${TB_QUEUE_INTEGRATION_PARTITIONS:3}" # For high-priority notifications that require minimum latency and processing time notifications_topic: "${TB_QUEUE_INTEGRATION_NOTIFICATIONS_TOPIC:tb_integration_executor.notifications}" diff --git a/application/src/test/java/org/thingsboard/server/actors/rule/DefaultTbContextTest.java b/application/src/test/java/org/thingsboard/server/actors/rule/DefaultTbContextTest.java index 4d17129844..c6f59216ac 100644 --- a/application/src/test/java/org/thingsboard/server/actors/rule/DefaultTbContextTest.java +++ b/application/src/test/java/org/thingsboard/server/actors/rule/DefaultTbContextTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.actors.rule; import org.junit.jupiter.api.BeforeEach; @@ -20,12 +21,18 @@ import org.thingsboard.server.actors.ruleChain.RuleChainOutputMsg; import org.thingsboard.server.actors.ruleChain.RuleNodeCtx; import org.thingsboard.server.actors.ruleChain.RuleNodeToRuleChainTellNextMsg; import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.debug.DebugSettings; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.RuleNodeId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.kv.AttributeKvEntry; +import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; +import org.thingsboard.server.common.data.kv.DataType; +import org.thingsboard.server.common.data.kv.LongDataEntry; +import org.thingsboard.server.common.data.kv.StringDataEntry; import org.thingsboard.server.common.data.msg.TbMsgType; import org.thingsboard.server.common.data.msg.TbNodeConnectionType; import org.thingsboard.server.common.data.rule.RuleNode; @@ -41,10 +48,12 @@ import org.thingsboard.server.queue.common.SimpleTbQueueCallback; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -1093,6 +1102,35 @@ class DefaultTbContextTest { .build(); } + @Test + public void givenSavedStringAttributes_whenAttributesUpdatedActionMsg_thenNumericStringsStayStringsWhenParsed() { + List attributes = List.of( + new BaseAttributeKvEntry(new StringDataEntry("joinEui", "0000000000000000"), 0L), + new BaseAttributeKvEntry(new StringDataEntry("devEui", "70B3D57ED0012345"), 0L), + new BaseAttributeKvEntry(new LongDataEntry("fCnt", 42L), 0L)); + + TbMsg msg = defaultTbContext.attributesUpdatedActionMsg(TENANT_ID, RULE_NODE_ID, DataConstants.CLIENT_SCOPE, attributes); + + assertThat(msg.getType()).isEqualTo(TbMsgType.ATTRIBUTES_UPDATED.name()); + assertThat(msg.getMetaData().getValue(DataConstants.SCOPE)).isEqualTo(DataConstants.CLIENT_SCOPE); + assertThat(msg.getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isEqualTo("[\"joinEui\"]"); + Map parsed = JsonConverter.attributesFromMsg(msg).stream() + .collect(Collectors.toMap(AttributeKvEntry::getKey, Function.identity())); + assertThat(parsed.get("joinEui").getDataType()).isEqualTo(DataType.STRING); + assertThat(parsed.get("joinEui").getValue()).isEqualTo("0000000000000000"); + assertThat(parsed.get("devEui").getDataType()).isEqualTo(DataType.STRING); + assertThat(parsed.get("fCnt").getDataType()).isEqualTo(DataType.LONG); + } + + @Test + public void givenNoNumericStringAttributes_whenAttributesUpdatedActionMsg_thenNoTypeCastDisabledKeys() { + List attributes = List.of(new BaseAttributeKvEntry(new LongDataEntry("fCnt", 42L), 0L)); + + TbMsg msg = defaultTbContext.attributesUpdatedActionMsg(TENANT_ID, RULE_NODE_ID, DataConstants.CLIENT_SCOPE, attributes); + + assertThat(msg.getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isNull(); + } + private TbMsg getTbMsgWithQueueName() { return TbMsg.newMsg() .queueName(DataConstants.MAIN_QUEUE_NAME) diff --git a/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java b/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java index b195e76b71..c5acf4f6b9 100644 --- a/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java +++ b/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java @@ -70,8 +70,8 @@ import java.util.function.Consumer; import java.util.function.Predicate; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.testcontainers.shaded.org.awaitility.Awaitility.await; @Slf4j @DaoSqlTest diff --git a/application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java b/application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java index 01132b8004..a518a9e307 100644 --- a/application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java @@ -9,10 +9,10 @@ import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.util.concurrent.Futures; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.RandomStringUtils; import org.junit.Test; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.test.context.TestPropertySource; -import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Device; diff --git a/application/src/test/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolverTest.java b/application/src/test/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolverTest.java new file mode 100644 index 0000000000..a8723cc54d --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolverTest.java @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.config; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.thingsboard.server.dao.oauth2.OAuth2ClientService; +import org.thingsboard.server.service.security.model.token.OAuth2AppTokenFactory; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verifyNoInteractions; + +@ExtendWith(MockitoExtension.class) +class CustomOAuth2AuthorizationRequestResolverTest { + + @Mock + private ClientRegistrationRepository clientRegistrationRepository; + @Mock + private OAuth2ClientService oAuth2ClientService; + @Mock + private OAuth2AppTokenFactory oAuth2AppTokenFactory; + @InjectMocks + private CustomOAuth2AuthorizationRequestResolver resolver; + + @Test + void resolvesTheRegistrationIdFromTheAuthorizationPath() { + given(clientRegistrationRepository.findByRegistrationId("abc-123")).willReturn(ClientRegistration.withRegistrationId("abc-123") + .clientId("client") + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/") + .authorizationUri("https://idp.example.com/authorize") + .tokenUri("https://idp.example.com/token") + .build()); + + OAuth2AuthorizationRequest request = resolver.resolve(new MockHttpServletRequest("GET", "/oauth2/authorization/abc-123")); + + assertThat(request.getAttributes()).containsEntry(OAuth2ParameterNames.REGISTRATION_ID, "abc-123"); + assertThat(request.getAuthorizationUri()).isEqualTo("https://idp.example.com/authorize"); + } + + @Test + void ignoresDeeperPaths() { + assertThat(resolver.resolve(new MockHttpServletRequest("GET", "/oauth2/authorization/abc/extra"))).isNull(); + verifyNoInteractions(clientRegistrationRepository); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/config/JsonMapperWiringTest.java b/application/src/test/java/org/thingsboard/server/config/JsonMapperWiringTest.java new file mode 100644 index 0000000000..a3716f7df1 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/config/JsonMapperWiringTest.java @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.config; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; +import org.thingsboard.server.controller.AbstractControllerTest; +import org.thingsboard.server.dao.service.DaoSqlTest; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@DaoSqlTest +public class JsonMapperWiringTest extends AbstractControllerTest { + + @Autowired + private RequestMappingHandlerAdapter handlerAdapter; + + @Autowired + private ObjectMapper objectMapper; + + @Test + public void mvcUsesJackson2() { + List> converters = handlerAdapter.getMessageConverters(); + assertThat(converters).noneMatch(c -> c.getClass().getName().startsWith("org.springframework.http.converter.json.JacksonJson")); + MappingJackson2HttpMessageConverter json = converters.stream() + .filter(MappingJackson2HttpMessageConverter.class::isInstance) + .map(MappingJackson2HttpMessageConverter.class::cast) + .findFirst().orElseThrow(); + assertThat(json.getObjectMapper()).isSameAs(objectMapper); + assertThat(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java b/application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java new file mode 100644 index 0000000000..e42066f0b1 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +package org.thingsboard.server.config; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.http.converter.autoconfigure.HttpMessageConvertersAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.autoconfigure.DispatcherServletAutoConfiguration; +import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.context.WebApplicationContext; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.zip.GZIPOutputStream; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.http.HttpHeaders.ACCEPT_ENCODING; +import static org.springframework.http.HttpHeaders.CONTENT_ENCODING; +import static org.springframework.http.HttpHeaders.VARY; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +/** + * Loads the real thingsboard.yml, so the test fails if its static resource chain keys stop binding again. + */ +@SpringBootTest(classes = StaticResourceCompressionTest.WebMvcConfig.class, properties = "spring.config.name=thingsboard") +public class StaticResourceCompressionTest { + + private static final byte[] JS = "console.log('ThingsBoard');\n".repeat(100).getBytes(StandardCharsets.UTF_8); + private static final byte[] JS_GZ = gzip(JS); + private static final byte[] CSS = "@font-face { src: url(font.woff2); }\n".getBytes(StandardCharsets.UTF_8); + + @TempDir + static Path webRoot; + + @Autowired + private WebApplicationContext webApplicationContext; + + private MockMvc mvc; + + @DynamicPropertySource + static void staticLocations(DynamicPropertyRegistry registry) { + registry.add("spring.web.resources.static-locations", () -> webRoot.toUri().toString()); + } + + @BeforeAll + static void createStaticFiles() throws IOException { + Files.write(webRoot.resolve("main.js"), JS); + Files.write(webRoot.resolve("main.js.gz"), JS_GZ); + Files.write(webRoot.resolve("styles.css"), CSS); + Files.write(webRoot.resolve("font.woff2"), new byte[]{1, 2, 3}); + } + + @BeforeEach + void setUpMockMvc() { + mvc = webAppContextSetup(webApplicationContext).build(); + } + + @Test + public void servesPrebuiltGzipWhenClientAcceptsIt() throws Exception { + mvc.perform(get("/main.js").header(ACCEPT_ENCODING, "gzip, deflate, br")) + .andExpect(status().isOk()) + .andExpect(header().string(CONTENT_ENCODING, "gzip")) + .andExpect(header().string(VARY, containsString(ACCEPT_ENCODING))) + .andExpect(content().contentTypeCompatibleWith("text/javascript")) + .andExpect(content().bytes(JS_GZ)); + } + + @Test + public void servesRawFileWhenClientDoesNotAcceptGzip() throws Exception { + mvc.perform(get("/main.js")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(CONTENT_ENCODING)) + .andExpect(content().bytes(JS)); + } + + @Test + public void servesStylesheetUnchanged() throws Exception { + // the content version strategy would rewrite url(font.woff2) to url(font-.woff2) + mvc.perform(get("/styles.css").header(ACCEPT_ENCODING, "gzip")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(CONTENT_ENCODING)) + .andExpect(content().bytes(CSS)); + } + + // not @Configuration: @ComponentScan("org.thingsboard.server") in other tests would pick it up + @ImportAutoConfiguration({DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class}) + static class WebMvcConfig { + } + + private static byte[] gzip(byte[] data) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(out)) { + gzip.write(data); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return out.toByteArray(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/config/ThingsboardYmlDefaultsTest.java b/application/src/test/java/org/thingsboard/server/config/ThingsboardYmlDefaultsTest.java new file mode 100644 index 0000000000..ef1f079902 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/config/ThingsboardYmlDefaultsTest.java @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.config; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.PropertySource; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.ClassPathResource; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class ThingsboardYmlDefaultsTest { + + @Test + void tomcatMaxParameterCountDefaultsTo10000() throws IOException { + List> sources = new YamlPropertySourceLoader().load("thingsboard", new ClassPathResource("thingsboard.yml")); + StandardEnvironment environment = new StandardEnvironment(); + sources.forEach(environment.getPropertySources()::addLast); + assertThat(environment.getProperty("server.tomcat.max-parameter-count", Integer.class)).isEqualTo(10000); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java index 489a8b550e..84d55ea636 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java @@ -7,9 +7,9 @@ import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootContextLoader; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; @@ -63,7 +63,8 @@ public abstract class AbstractControllerTest extends AbstractNotifyEntityTest { public static final String WS_URL = "ws://localhost:"; - @LocalServerPort + // This class is also the context's configuration bean, which is created before the server port is known + @Value("${local.server.port:0}") protected int serverPort; protected volatile TbTestWebSocketClient wsClient; // lazy diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java index dc1e88d4ab..67a9aed4ad 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java @@ -46,12 +46,14 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.test.web.servlet.request.AbstractMockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.MailService; import org.thingsboard.server.actors.DefaultTbActorSystem; @@ -334,14 +336,15 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { }; @Autowired - void setConverters(HttpMessageConverter[] converters) { + void setConverters(RequestMappingHandlerAdapter handlerAdapter) { + List> converters = handlerAdapter.getMessageConverters(); - this.mappingJackson2HttpMessageConverter = Arrays.stream(converters) + this.mappingJackson2HttpMessageConverter = converters.stream() .filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter) .findAny() .get(); - this.stringHttpMessageConverter = Arrays.stream(converters) + this.stringHttpMessageConverter = converters.stream() .filter(hmc -> hmc instanceof StringHttpMessageConverter) .findAny() .get(); @@ -761,7 +764,7 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { doPost("/api/auth/logout").andExpect(status().isOk()); } - protected void setJwtToken(MockHttpServletRequestBuilder request) { + protected void setJwtToken(AbstractMockHttpServletRequestBuilder request) { if (this.token != null) { request.header(ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER, BEARER_HEADER_PREFIX + this.token); } diff --git a/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java index b571440e70..76683aea2f 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java @@ -10,6 +10,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Test; import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; @@ -17,9 +18,11 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.model.JwtSettings; import org.thingsboard.server.dao.secret.SecretConfigurationService; import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.dao.settings.AdminSettingsService; import java.nio.charset.StandardCharsets; import java.util.Base64; +import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; @@ -44,6 +47,9 @@ public class AdminControllerTest extends AbstractControllerTest { @MockitoBean private SecretConfigurationService secretConfigurationService; + @Autowired + private AdminSettingsService adminSettingsService; + @Test public void testFindAdminSettingsByKey() throws Exception { loginSysAdmin(); @@ -111,6 +117,30 @@ public class AdminControllerTest extends AbstractControllerTest { .andExpect(statusReason(containsString("is prohibited"))); } + @Test + public void testSaveAdminSettingsRefusesVersionControlKeys() throws Exception { + loginTenantAdmin(); + checkVersionControlKeysRefused(tenantId); + + loginSysAdmin(); + checkVersionControlKeysRefused(TenantId.SYS_TENANT_ID); + } + + private void checkVersionControlKeysRefused(TenantId settingsTenantId) throws Exception { + Map values = Map.of( + "entitiesVersionControl", "{\"repositoryUri\":\"repo1\",\"defaultBranch\":\"main\"}", + "autoCommitSettings", "{}"); + for (Map.Entry entry : values.entrySet()) { + AdminSettings settings = new AdminSettings(); + settings.setKey(entry.getKey()); + settings.setJsonValue(JacksonUtil.toJsonNode(entry.getValue())); + doPost("/api/admin/settings", settings) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("version control API"))); + assertThat(adminSettingsService.findAdminSettingsByTenantIdAndKey(settingsTenantId, entry.getKey())).isNull(); + } + } + @Test public void testMailOAuth2AuthorizationStoresOnlyInAppPrevUri() throws Exception { loginSysAdmin(); diff --git a/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java index cec0df49ee..e0f675d3e8 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java @@ -98,6 +98,32 @@ public class AlarmRuleControllerTest extends AbstractControllerTest { .andExpect(status().isOk()); } + @Test + public void testSaveAlarmRuleWithOtherTenantReference() throws Exception { + Device testDevice = createDevice("Test device", "1234567890"); + AlarmRuleDefinition alarmRule = createTestAlarmRule(testDevice.getId(), "High Temperature"); + alarmRule.getConfiguration().getArguments().get("temperature").setRefEntityId(tenantId); + + doPost("/api/alarm/rule", alarmRule).andExpect(status().isForbidden()); + + PageData alarmRules = doGetTypedWithPageLink( + "/api/alarm/rules/" + EntityType.DEVICE + "/" + testDevice.getUuidId() + "?", + new TypeReference<>() {}, new PageLink(10)); + assertThat(alarmRules.getData()).isEmpty(); + } + + @Test + public void testSaveAlarmRuleWithOwnTenantReference() throws Exception { + Device testDevice = createDevice("Test device", "1234567890"); + AlarmRuleDefinition alarmRule = createTestAlarmRule(testDevice.getId(), "High Temperature"); + alarmRule.getConfiguration().getArguments().get("temperature").setRefEntityId(savedTenant.getId()); + + AlarmRuleDefinition saved = saveAlarmRule(alarmRule); + + assertThat(saved.getId()).isNotNull(); + assertThat(saved.getConfiguration().getArguments().get("temperature").getRefEntityId()).isEqualTo(savedTenant.getId()); + } + @Test public void testGetAlarmRuleById() throws Exception { Device testDevice = createDevice("Test device", "1234567890"); diff --git a/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java index b0cca491a3..b19cb3131b 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java @@ -234,6 +234,57 @@ public class ApiKeyControllerTest extends AbstractControllerTest { doDelete("/api/apiKey/" + savedApiKey.getId().getId()).andExpect(status().isOk()); } + @Test + public void testCustomerUserListsOwnApiKeys() throws Exception { + loginCustomerAdminUser(); + ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true); + apiKeyInfo.setUserId(customerAdminUserId); + doPost("/api/apiKey", apiKeyInfo, ApiKey.class); + + PageData pageData = doGetTypedWithPageLink("/api/apiKeys/" + customerAdminUserId + "?", new TypeReference<>() {}, new PageLink(10, 0)); + Assert.assertEquals(1, pageData.getData().size()); + Assert.assertEquals(customerAdminUserId, pageData.getData().get(0).getUserId()); + } + + @Test + public void testTenantAdminListsCustomerUserApiKeys() throws Exception { + ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true); + apiKeyInfo.setUserId(customerUserId); + doPost("/api/apiKey", apiKeyInfo, ApiKey.class); + + PageData pageData = doGetTypedWithPageLink("/api/apiKeys/" + customerUserId + "?", new TypeReference<>() {}, new PageLink(10, 0)); + Assert.assertEquals(1, pageData.getData().size()); + Assert.assertEquals(customerUserId, pageData.getData().get(0).getUserId()); + } + + @Test + public void testCustomerUserCannotListOtherUserApiKeys() throws Exception { + loginCustomerAdminUser(); + doGet("/api/user/" + customerUserId).andExpect(status().isOk()); + doGet("/api/apiKeys/" + customerUserId + "?pageSize=10&page=0").andExpect(status().isForbidden()); + } + + @Test + public void testCustomerUserCannotReadOtherUserApiKeyRelations() throws Exception { + ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true); + apiKeyInfo.setUserId(customerUserId); + ApiKey apiKey = doPost("/api/apiKey", apiKeyInfo, ApiKey.class); + + loginCustomerAdminUser(); + doGet("/api/relations?fromId=" + apiKey.getId().getId() + "&fromType=API_KEY").andExpect(status().isForbidden()); + } + + @Test + public void testCustomerUserCannotDeleteTenantAdminApiKey() throws Exception { + ApiKey apiKey = doPost("/api/apiKey", constructApiKeyInfo("Test API key description", true), ApiKey.class); + + loginCustomerAdminUser(); + doDelete("/api/apiKey/" + apiKey.getId().getId()).andExpect(status().isForbidden()); + + loginTenantAdmin(); + doDelete("/api/apiKey/" + apiKey.getId().getId()).andExpect(status().isOk()); + } + private ApiKeyInfo constructApiKeyInfo(String description, boolean enabled) { ApiKeyInfo apiKeyInfo = new ApiKeyInfo(); apiKeyInfo.setDescription(description); diff --git a/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java index 7fd2d8e9be..78d22aec65 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java @@ -16,7 +16,11 @@ import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.UserActivationLink; import org.thingsboard.server.common.data.UserInfo; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.permission.Operation; +import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.UserCredentials; import org.thingsboard.server.common.data.security.model.SecuritySettings; @@ -24,6 +28,7 @@ import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.dao.user.UserCredentialsDao; import org.thingsboard.server.service.security.auth.rest.LoginRequest; import org.thingsboard.server.service.security.model.ChangePasswordRequest; +import org.thingsboard.server.service.security.permission.AccessControlService; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; @@ -33,6 +38,8 @@ import static org.assertj.core.api.Assertions.within; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -43,6 +50,9 @@ public class AuthControllerTest extends AbstractControllerTest { @MockitoSpyBean private UserCredentialsDao userCredentialsDao; + @MockitoSpyBean + private AccessControlService accessControlService; + @After public void tearDown() throws Exception { loginSysAdmin(); @@ -287,6 +297,26 @@ public class AuthControllerTest extends AbstractControllerTest { assertThat(getUser(user.getId()).getAdditionalInfo().get("userActivated").asBoolean()).isTrue(); } + @Test + public void testActivationLinkRequiresWritePermissionOnUser() throws Exception { + loginTenantAdmin(); + User user = new User(); + user.setAuthority(Authority.TENANT_ADMIN); + user.setEmail("pending-user@thingsboard.org"); + user = doPost("/api/user", user, User.class); + + doThrow(new ThingsboardException("You don't have permission to perform this operation!", ThingsboardErrorCode.PERMISSION_DENIED)) + .when(accessControlService).checkPermission(any(), eq(Resource.USER), eq(Operation.WRITE), eq(user.getId()), any()); + + doGet("/api/user/" + user.getId() + "/activationLinkInfo").andExpect(status().isForbidden()); + doGet("/api/user/" + user.getId() + "/activationLink").andExpect(status().isForbidden()); + doPost("/api/user/sendActivationMail?email=" + user.getEmail()).andExpect(status().isForbidden()); + + Mockito.reset(accessControlService); + assertThat(getActivationLinkInfo(user).value()).isNotBlank(); + doPost("/api/user/sendActivationMail?email=" + user.getEmail()).andExpect(status().isOk()); + } + @Test public void testGetPageWithoutRedirect() throws Exception { doGet("/login").andExpect(status().isOk()); diff --git a/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java index 55d3930fec..34ba0d1cf8 100644 --- a/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.controller; +import com.fasterxml.jackson.core.type.TypeReference; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -41,6 +42,7 @@ import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -298,6 +300,48 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest { doGet("/api/calculatedField/" + savedCalculatedField.getId().getId()).andExpect(status().isNotFound()); } + @Test + public void testSaveCalculatedFieldWithOtherTenantReference() throws Exception { + Device testDevice = createDevice("Test device", "1234567890"); + CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), Map.of("T", getArgument(tenantId))); + + doPost("/api/calculatedField", calculatedField).andExpect(status().isForbidden()); + + PageData calculatedFields = doGetTyped("/api/DEVICE/" + testDevice.getId().getId() + "/calculatedFields?pageSize=10&page=0", + new TypeReference<>() {}); + assertThat(calculatedFields.getData()).isEmpty(); + } + + @Test + public void testSaveCalculatedFieldWithOwnTenantReference() throws Exception { + Device testDevice = createDevice("Test device", "1234567890"); + CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), Map.of("T", getArgument(savedTenant.getId()))); + + CalculatedField savedCalculatedField = doPost("/api/calculatedField", calculatedField, CalculatedField.class); + + assertThat(savedCalculatedField.getId()).isNotNull(); + assertThat(savedCalculatedField.getConfiguration().getReferencedEntities()).containsExactly(savedTenant.getId()); + } + + @Test + public void testSaveCalculatedFieldChecksEveryReference() throws Exception { + loginTenantAdmin(); + Device otherTenantDevice = createDevice("Other device", "0987654321"); + login("tenant2@thingsboard.org", "testPassword1"); + + Device testDevice = createDevice("Test device", "1234567890"); + Map arguments = new LinkedHashMap<>(); + arguments.put("T", getArgument(savedTenant.getId())); + arguments.put("H", getArgument(otherTenantDevice.getId())); + CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), arguments); + + doPost("/api/calculatedField", calculatedField).andExpect(status().isNotFound()); + } + + private CalculatedField getSimpleCalculatedField(EntityId entityId, Map arguments) { + return getCalculatedField(entityId, CalculatedFieldType.SIMPLE, getSimpleCalculatedFieldConfig(arguments)); + } + private CalculatedField getSimpleCalculatedField(EntityId entityId) { return getCalculatedField(entityId, CalculatedFieldType.SIMPLE); } @@ -385,14 +429,13 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest { } private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig() { - SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration(); + return getSimpleCalculatedFieldConfig(Map.of("T", getArgument(null))); + } - Argument argument = new Argument(); - argument.setRefEntityId(null); - ReferencedEntityKey refEntityKey = new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null); - argument.setRefEntityKey(refEntityKey); + private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig(Map arguments) { + SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration(); - config.setArguments(Map.of("T", argument)); + config.setArguments(arguments); config.setExpression("T - (100 - H) / 5"); @@ -404,4 +447,11 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest { return config; } + private Argument getArgument(EntityId refEntityId) { + Argument argument = new Argument(); + argument.setRefEntityId(refEntityId); + argument.setRefEntityKey(new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null)); + return argument; + } + } diff --git a/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java index 48d5a691f6..083b94e183 100644 --- a/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java @@ -5,6 +5,7 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -12,7 +13,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.test.web.servlet.MvcResult; -import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntityInfo; @@ -657,6 +657,120 @@ public class CustomMenuControllerTest extends AbstractControllerTest { assertThat(currentMenu.get("items")).isEmpty(); } + @Test + public void testCustomerUserMenuIgnoresMenuOfOtherTenant() throws Exception { + loginDifferentTenant(); + CustomMenu otherTenantMenu = new CustomMenu(); + otherTenantMenu.setName(RandomStringUtils.randomAlphabetic(10)); + otherTenantMenu.setScope(CMScope.CUSTOMER); + otherTenantMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN); + otherTenantMenu = doPost("/api/customMenu", otherTenantMenu, CustomMenu.class); + idsToRemove.add(otherTenantMenu.getUuidId()); + CustomMenuConfig otherTenantMenuConfig = putRandomMenuConfig(otherTenantMenu.getId()); + String otherTenantMenuUrl = ((CustomMenuItem) otherTenantMenuConfig.getItems().get(2)).getUrl(); + + loginTenantAdmin(); + Customer customer = doGet("/api/customer/" + customerId.getId(), Customer.class); + customer.setCustomMenuId(otherTenantMenu.getId()); + doPost("/api/customer", customer).andExpect(status().isOk()); + + loginCustomerUser(); + JsonNode customerUserMenu = doGet("/api/customMenu", JsonNode.class); + assertThat(customerUserMenu.toString()).doesNotContain(otherTenantMenuUrl); + } + + @Test + public void testTenantUserMenuIgnoresMenuOfOtherTenant() throws Exception { + loginDifferentTenant(); + CustomMenu otherTenantMenu = new CustomMenu(); + otherTenantMenu.setName(RandomStringUtils.randomAlphabetic(10)); + otherTenantMenu.setScope(CMScope.TENANT); + otherTenantMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN); + otherTenantMenu = doPost("/api/customMenu", otherTenantMenu, CustomMenu.class); + idsToRemove.add(otherTenantMenu.getUuidId()); + CustomMenuConfig otherTenantMenuConfig = putRandomMenuConfig(otherTenantMenu.getId()); + String otherTenantMenuUrl = ((CustomMenuItem) otherTenantMenuConfig.getItems().get(2)).getUrl(); + + loginTenantAdmin(); + User tenantAdmin = doGet("/api/user/" + tenantAdminUserId.getId(), User.class); + tenantAdmin.setCustomMenuId(otherTenantMenu.getId()); + doPost("/api/user", tenantAdmin).andExpect(status().isOk()); + assertThat(doGet("/api/user/" + tenantAdminUserId.getId(), User.class).getCustomMenuId()).isEqualTo(otherTenantMenu.getId()); + + JsonNode tenantAdminMenu = doGet("/api/customMenu", JsonNode.class); + assertThat(tenantAdminMenu.toString()).doesNotContain(otherTenantMenuUrl); + } + + @Test + public void testCustomMenuAssigneeListContainsOnlyCustomersOfMenuTenant() throws Exception { + loginTenantAdmin(); + CustomMenu customerMenu = new CustomMenu(); + customerMenu.setName(RandomStringUtils.randomAlphabetic(10)); + customerMenu.setScope(CMScope.CUSTOMER); + customerMenu.setAssigneeType(CMAssigneeType.CUSTOMERS); + customerMenu = doPost("/api/customMenu?assignToList=" + customerId, customerMenu, CustomMenu.class); + + loginDifferentTenant(); + Customer otherTenantCustomer = new Customer(); + otherTenantCustomer.setTitle("Other Tenant Customer"); + otherTenantCustomer.setCustomMenuId(customerMenu.getId()); + otherTenantCustomer = doPost("/api/customer", otherTenantCustomer, Customer.class); + + loginTenantAdmin(); + List assigneeList = doGetTyped("/api/customMenu/" + customerMenu.getId() + "/assigneeList", new TypeReference<>() {}); + assertThat(assigneeList).extracting(EntityInfo::getId).containsExactly(customerId); + doDelete("/api/customMenu/" + customerMenu.getId() + "?force=true").andExpect(status().isOk()); + + loginDifferentTenant(); + Customer otherTenantCustomerAfterDelete = doGet("/api/customer/" + otherTenantCustomer.getId(), Customer.class); + assertThat(otherTenantCustomerAfterDelete.getCustomMenuId()).isEqualTo(customerMenu.getId()); + } + + @Test + public void testCustomMenuAssigneeListContainsOnlyUsersOfMenuTenant() throws Exception { + loginTenantAdmin(); + CustomMenu userMenu = new CustomMenu(); + userMenu.setName(RandomStringUtils.randomAlphabetic(10)); + userMenu.setScope(CMScope.TENANT); + userMenu.setAssigneeType(CMAssigneeType.USERS); + userMenu = doPost("/api/customMenu?assignToList=" + tenantAdminUserId, userMenu, CustomMenu.class); + + loginDifferentTenant(); + User otherTenantUser = new User(); + otherTenantUser.setAuthority(Authority.TENANT_ADMIN); + otherTenantUser.setTenantId(differentTenantId); + otherTenantUser.setEmail("othertenantuser@thingsboard.org"); + otherTenantUser.setCustomMenuId(userMenu.getId()); + otherTenantUser = doPost("/api/user", otherTenantUser, User.class); + assertThat(otherTenantUser.getCustomMenuId()).isEqualTo(userMenu.getId()); + + loginTenantAdmin(); + List assigneeList = doGetTyped("/api/customMenu/" + userMenu.getId() + "/assigneeList", new TypeReference<>() {}); + assertThat(assigneeList).extracting(EntityInfo::getId).containsExactly(tenantAdminUserId); + doDelete("/api/customMenu/" + userMenu.getId() + "?force=true").andExpect(status().isOk()); + + loginDifferentTenant(); + User otherTenantUserAfterDelete = doGet("/api/user/" + otherTenantUser.getId(), User.class); + assertThat(otherTenantUserAfterDelete.getCustomMenuId()).isEqualTo(userMenu.getId()); + } + + @Test + public void testTenantUserGetsAssignedSystemMenu() throws Exception { + loginSysAdmin(); + CustomMenu systemMenu = new CustomMenu(); + systemMenu.setName(RandomStringUtils.randomAlphabetic(10)); + systemMenu.setScope(CMScope.TENANT); + systemMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN); + systemMenu = doPost("/api/customMenu", systemMenu, CustomMenu.class); + idsToRemove.add(systemMenu.getUuidId()); + CustomMenuConfig systemMenuConfig = putRandomMenuConfig(systemMenu.getId()); + doPut("/api/customMenu/" + systemMenu.getId() + "/assign/USERS", List.of(tenantAdminUserId.getId())); + + loginTenantAdmin(); + JsonNode tenantAdminMenu = doGet("/api/customMenu", JsonNode.class); + assertCustomMenuConfig(tenantAdminMenu, systemMenuConfig); + } + private MvcResult getUserCustomMenu() throws Exception { return getUserCustomMenu(null); } diff --git a/application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java new file mode 100644 index 0000000000..a54efa04ab --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java @@ -0,0 +1,195 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.controller; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.web.servlet.ResultActions; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.DashboardReportService; +import org.thingsboard.server.common.data.Dashboard; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.dashboardreport.DashboardReportConfig; +import org.thingsboard.server.common.data.dashboardreport.DashboardReportData; +import org.thingsboard.server.common.data.group.EntityGroup; +import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.permission.GroupPermission; +import org.thingsboard.server.common.data.role.Role; +import org.thingsboard.server.common.data.role.RoleType; +import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.dao.service.DaoSqlTest; + +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@DaoSqlTest +public class DashboardReportControllerTest extends AbstractControllerTest { + + private static final String DASHBOARD_VIEWER_EMAIL = "dashboard.viewer@thingsboard.org"; + private static final String DASHBOARD_VIEWER_PASSWORD = "viewer"; + private static final String REPORTS_SERVER_URL = "http://localhost:8383"; + private static final String REPORT_BASE_URL = "http://localhost:8081"; + + @MockitoSpyBean + private DashboardReportService dashboardReportService; + + private Dashboard dashboard; + + @Before + public void beforeTest() throws Exception { + loginSubCustomerAdminUser(); + Dashboard dashboard = new Dashboard(); + dashboard.setTitle("Sub-customer dashboard"); + this.dashboard = doPost("/api/dashboard", dashboard, Dashboard.class); + + doAnswer(invocation -> { + Consumer onSuccess = invocation.getArgument(3); + DashboardReportData reportData = new DashboardReportData(); + reportData.setData(new byte[]{1}); + reportData.setName("report.pdf"); + reportData.setContentType("application/pdf"); + onSuccess.accept(reportData); + return null; + }).when(dashboardReportService).generateReport(any(), any(), any(), any(), any()); + } + + @Test + public void testDownloadTestReportRequiresPermissionOverReportUser() throws Exception { + loginDifferentTenant(); + UserId otherTenantUserId = savedDifferentTenantUser.getId(); + loginDifferentCustomer(); + + loginCustomerAdminUser(); + doPostTestReport(tenantAdminUserId.toString()).andExpect(status().isForbidden()); + doPostTestReport(differentCustomerUserId.toString()).andExpect(status().isForbidden()); + doPostTestReport(otherTenantUserId.toString()).andExpect(status().isForbidden()); + + loginSubCustomerAdminUser(); + doPostTestReport(customerAdminUserId.toString()).andExpect(status().isForbidden()); + + loginTenantAdmin(); + doPostTestReport(otherTenantUserId.toString()).andExpect(status().isForbidden()); + + createDashboardViewer(); + login(DASHBOARD_VIEWER_EMAIL, DASHBOARD_VIEWER_PASSWORD); + doPostTestReport(customerAdminUserId.toString()).andExpect(status().isForbidden()); + doPostTestReport(customerUserId.toString()).andExpect(status().isForbidden()); + + verify(dashboardReportService, never()).generateReport(any(), any(), any(), any(), any()); + } + + @Test + public void testDownloadTestReportAllowedForOwnUser() throws Exception { + loginCustomerAdminUser(); + doPostTestReport(customerAdminUserId.toString()).andExpect(status().isOk()); + verifyReportGenerated(customerAdminUserId); + + UserId dashboardViewerId = createDashboardViewer(); + login(DASHBOARD_VIEWER_EMAIL, DASHBOARD_VIEWER_PASSWORD); + doPostTestReport(dashboardViewerId.toString()).andExpect(status().isOk()); + verifyReportGenerated(dashboardViewerId); + } + + @Test + public void testDownloadTestReportAllowedForOwnedUser() throws Exception { + loginTenantAdmin(); + doPostTestReport(customerUserId.toString()).andExpect(status().isOk()); + verifyReportGenerated(customerUserId); + + loginCustomerAdminUser(); + doPostTestReport(subCustomerAdminUserId.toString()).andExpect(status().isOk()); + verifyReportGenerated(subCustomerAdminUserId); + doPostTestReport(customerUserId.toString()).andExpect(status().isOk()); + } + + @Test + public void testDownloadTestReportWithCurrentUserCredentialsUsesCurrentUserWhenReportUserNotAccessible() throws Exception { + loginCustomerAdminUser(); + doPostTestReport(tenantAdminUserId.toString(), null, true).andExpect(status().isOk()); + verifyReportGenerated(customerAdminUserId); + } + + @Test + public void testDownloadTestReportRequiresUserId() throws Exception { + loginCustomerAdminUser(); + doPostTestReport(null).andExpect(status().isBadRequest()); + doPostTestReport("not-a-uuid").andExpect(status().isBadRequest()); + verify(dashboardReportService, never()).generateReport(any(), any(), any(), any(), any()); + } + + @Test + public void testDownloadTestReportUsesSystemReportServerForCustomerUser() throws Exception { + loginCustomerAdminUser(); + doPostTestReport(customerAdminUserId.toString(), REPORTS_SERVER_URL).andExpect(status().isOk()); + verify(dashboardReportService).generateReport(eq(tenantId), any(), isNull(), any(), any()); + + loginTenantAdmin(); + doPostTestReport(tenantAdminUserId.toString(), REPORTS_SERVER_URL).andExpect(status().isOk()); + verify(dashboardReportService).generateReport(eq(tenantId), any(), eq(REPORTS_SERVER_URL), any(), any()); + } + + private UserId createDashboardViewer() throws Exception { + loginTenantAdmin(); + Role role = new Role(); + role.setTenantId(tenantId); + role.setCustomerId(customerId); + role.setType(RoleType.GENERIC); + role.setName("Dashboard viewer"); + role.setPermissions(JacksonUtil.toJsonNode("{\"DASHBOARD\":[\"READ\"]}")); + role = doPost("/api/role", role, Role.class); + + EntityGroup userGroup = new EntityGroup(); + userGroup.setName("Dashboard viewers"); + userGroup.setType(EntityType.USER); + userGroup.setOwnerId(customerId); + userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class); + doPost("/api/groupPermission", new GroupPermission(tenantId, userGroup.getId(), role.getId(), null, null, false), GroupPermission.class); + + User user = new User(); + user.setAuthority(Authority.CUSTOMER_USER); + user.setTenantId(tenantId); + user.setCustomerId(customerId); + user.setEmail(DASHBOARD_VIEWER_EMAIL); + return createUser(user, DASHBOARD_VIEWER_PASSWORD, userGroup.getId()).getId(); + } + + private ResultActions doPostTestReport(String userId) throws Exception { + return doPostTestReport(userId, null); + } + + private ResultActions doPostTestReport(String userId, String reportsServerEndpointUrl) throws Exception { + return doPostTestReport(userId, reportsServerEndpointUrl, false); + } + + private ResultActions doPostTestReport(String userId, String reportsServerEndpointUrl, boolean useCurrentUserCredentials) throws Exception { + DashboardReportConfig reportConfig = new DashboardReportConfig(); + reportConfig.setBaseUrl(REPORT_BASE_URL); + reportConfig.setDashboardId(dashboard.getId().toString()); + reportConfig.setTimezone("UTC"); + reportConfig.setNamePattern("report"); + reportConfig.setType("pdf"); + reportConfig.setUserId(userId); + reportConfig.setUseCurrentUserCredentials(useCurrentUserCredentials); + String url = "/api/report/test"; + if (reportsServerEndpointUrl != null) { + url += "?reportsServerEndpointUrl=" + reportsServerEndpointUrl; + } + return doPostAsync(url, reportConfig, TimeUnit.SECONDS.toMillis(30)); + } + + private void verifyReportGenerated(UserId userId) throws Exception { + verify(dashboardReportService).generateReport(eq(tenantId), argThat(config -> userId.toString().equals(config.getUserId())), any(), any(), any()); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java b/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java index 6a0631fd98..bf401d10fe 100644 --- a/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java @@ -62,7 +62,7 @@ public class DevelopmentNoticeCaptureStampTest { .as("no subscribing call to %s in the capture path to order against", STAMP_METHOD) .isTrue(); - int captured = capture.indexOf("html2canvas("); + int captured = capture.indexOf("domToCanvas("); int serialised = capture.indexOf("toDataURL"); assertThat(captured).as("no capture call found to order against").isNotNegative(); assertThat(serialised).as("no serialisation call found to order against").isNotNegative(); diff --git a/application/src/test/java/org/thingsboard/server/controller/DeviceControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/DeviceControllerTest.java index bf39aa94ce..63423a1bdb 100644 --- a/application/src/test/java/org/thingsboard/server/controller/DeviceControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/DeviceControllerTest.java @@ -10,6 +10,7 @@ import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; +import org.awaitility.Awaitility; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -23,7 +24,6 @@ import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.test.context.ContextConfiguration; -import org.testcontainers.shaded.org.awaitility.Awaitility; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.server.common.data.AttributeScope; diff --git a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java index 99fa4a51a6..2fb378e9b7 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java @@ -3,40 +3,52 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; +import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; +import org.springframework.test.web.servlet.ResultActions; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityInfo; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.group.EntityGroupInfo; +import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EntityGroupId; +import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IdBased; +import org.thingsboard.server.common.data.id.RoleId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.permission.GroupPermission; import org.thingsboard.server.common.data.permission.GroupPermissionInfo; +import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.ShareGroupRequest; import org.thingsboard.server.common.data.role.Role; import org.thingsboard.server.common.data.role.RoleType; import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.dao.grouppermission.GroupPermissionService; import org.thingsboard.server.dao.role.RoleService; import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.UUID; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @DaoSqlTest @@ -45,6 +57,12 @@ public class EntityGroupControllerTest extends AbstractControllerTest { @Autowired private RoleService roleService; + @Autowired + private GroupPermissionService groupPermissionService; + + private static final String GROUP_MANAGER_PERMISSIONS = + "{\"DEVICE_GROUP\":[\"READ\",\"WRITE\"],\"USER_GROUP\":[\"READ\",\"WRITE\"],\"GROUP_PERMISSION\":[\"CREATE\"],\"ROLE\":[\"READ\"]}"; + private Tenant savedTenant; private User tenantAdmin; @@ -89,6 +107,300 @@ public class EntityGroupControllerTest extends AbstractControllerTest { Assert.assertEquals(savedEntityGroup.getName(), foundEntityGroup.getName()); } + @Test + public void testShouldNotChangeEntityGroupOwnerAsGroupOwner() throws Exception { + loginTenantAdmin(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setName("Device Group"); + entityGroup.setType(EntityType.DEVICE); + EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + + savedEntityGroup.setOwnerId(customerId); + doPost("/api/entityGroup", savedEntityGroup) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("Entity group owner can't be changed!"))); + + assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getOwnerId()).isEqualTo(tenantId); + } + + @Test + public void testShouldNotChangeEntityGroupType() throws Exception { + loginTenantAdmin(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setName("Device Group"); + entityGroup.setType(EntityType.DEVICE); + EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + + savedEntityGroup.setType(EntityType.USER); + doPost("/api/entityGroup", savedEntityGroup) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("Entity group type can't be changed!"))); + + assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getType()).isEqualTo(EntityType.DEVICE); + } + + @Test + public void testShouldNotMoveTenantEntityGroupToCustomerAsCustomerAdmin() throws Exception { + EntityGroup tenantAdministratorsGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, tenantId, + EntityType.USER, EntityGroup.GROUP_TENANT_ADMINS_NAME).get(); + + loginCustomerAdminUser(); + EntityGroup movedEntityGroup = new EntityGroup(tenantAdministratorsGroup); + movedEntityGroup.setOwnerId(customerId); + doPost("/api/entityGroup", movedEntityGroup) + .andExpect(status().isForbidden()); + + assertThat(entityGroupService.findEntityGroupById(tenantId, tenantAdministratorsGroup.getId()).getOwnerId()).isEqualTo(tenantId); + } + + @Test + public void testShouldNotMoveEntityGroupSharedWithWriteAccess() throws Exception { + loginTenantAdmin(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setName("Shared Device Group"); + entityGroup.setType(EntityType.DEVICE); + EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + var shareGroupRequest = new ShareGroupRequest(customerId, true, null, false, Collections.emptyList()); + doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, savedEntityGroup.getId().toString()) + .andExpect(status().isOk()); + + loginCustomerAdminUser(); + EntityGroup sharedEntityGroup = doGet("/api/entityGroup/" + savedEntityGroup.getId().getId(), EntityGroup.class); + sharedEntityGroup.setOwnerId(customerId); + doPost("/api/entityGroup", sharedEntityGroup) + .andExpect(status().isForbidden()); + + assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getOwnerId()).isEqualTo(tenantId); + } + + @Test + public void testShouldNotMoveOtherTenantEntityGroup() throws Exception { + loginDifferentTenant(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setName("Other Tenant Device Group"); + entityGroup.setType(EntityType.DEVICE); + EntityGroup otherTenantEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + + loginCustomerAdminUser(); + otherTenantEntityGroup.setOwnerId(customerId); + doPost("/api/entityGroup", otherTenantEntityGroup) + .andExpect(status().isNotFound()); + + assertThat(entityGroupService.findEntityGroupById(differentTenantId, otherTenantEntityGroup.getId()).getOwnerId()).isEqualTo(differentTenantId); + } + + @Test + public void testGetEntityGroupInfosByIdsReturnsOnlyOwnTenantGroups() throws Exception { + loginTenantAdmin(); + EntityGroup ownGroup = new EntityGroup(); + ownGroup.setName("Own Device Group"); + ownGroup.setType(EntityType.DEVICE); + ownGroup = doPost("/api/entityGroup", ownGroup, EntityGroup.class); + + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + List entityInfos = doGetTyped("/api/entityGroupInfos?entityGroupIds=" + ownGroup.getId().getId() + "," + otherTenantGroup.getId().getId(), + new TypeReference<>() {}); + assertThat(entityInfos).extracting(EntityInfo::getId).containsExactly(ownGroup.getId()); + } + + @Test + public void testGetEntityGroupInfosByIdsReturnsOnlyReadableGroups() throws Exception { + loginTenantAdmin(); + EntityGroup tenantGroup = new EntityGroup(); + tenantGroup.setName("Tenant Device Group"); + tenantGroup.setType(EntityType.DEVICE); + tenantGroup = doPost("/api/entityGroup", tenantGroup, EntityGroup.class); + + loginCustomerAdminUser(); + EntityGroup customerGroup = new EntityGroup(); + customerGroup.setName("Customer Device Group"); + customerGroup.setType(EntityType.DEVICE); + customerGroup.setOwnerId(customerId); + customerGroup = doPost("/api/entityGroup", customerGroup, EntityGroup.class); + + List entityInfos = doGetTyped("/api/entityGroupInfos?entityGroupIds=" + customerGroup.getId().getId() + "," + tenantGroup.getId().getId(), + new TypeReference<>() {}); + assertThat(entityInfos).extracting(EntityInfo::getId).containsExactly(customerGroup.getId()); + } + + @Test + public void testShareGroupWithUserGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantUserGroup = new EntityGroup(); + otherTenantUserGroup.setName("Other Tenant User Group"); + otherTenantUserGroup.setType(EntityType.USER); + otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setName("Shared Device Group"); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, false, otherTenantUserGroup.getId(), true, null); + doPost("/api/entityGroup/" + deviceGroup.getId().getId() + "/share", shareGroupRequest) + .andExpect(status().isNotFound()) + .andExpect(statusReason(not(containsString(otherTenantUserGroup.getName())))); + } + + @Test + public void testShareGroupV2WithUserGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantUserGroup = new EntityGroup(); + otherTenantUserGroup.setName("Other Tenant User Group"); + otherTenantUserGroup.setType(EntityType.USER); + otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setName("Shared Device Group"); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, false, otherTenantUserGroup.getId(), true, null); + doPost("/api/v2/entityGroup/" + deviceGroup.getId().getId() + "/share", shareGroupRequest) + .andExpect(status().isNotFound()) + .andExpect(statusReason(not(containsString(otherTenantUserGroup.getName())))); + } + + @Test + public void testShareGroupWithAllUsersGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + + ShareGroupRequest unknownOwnerRequest = new ShareGroupRequest(TenantId.fromUUID(UUID.randomUUID()), true, null, true, null); + doPost("/api/entityGroup/{entityGroupId}/share", unknownOwnerRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + ShareGroupRequest otherTenantRequest = new ShareGroupRequest(differentTenantId, true, null, true, null); + doPost("/api/entityGroup/{entityGroupId}/share", otherTenantRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + assertThat(findSharedUserGroupIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareGroupWithAllUsersGroupOfOwnCustomerSharesWithThatGroup() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + EntityGroup customerAllUsersGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, customerId, + EntityType.USER, EntityGroup.GROUP_ALL_NAME).get(); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(customerId, true, null, true, null); + doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString()) + .andExpect(status().isOk()); + assertThat(findSharedUserGroupIds(deviceGroup)).containsExactly(customerAllUsersGroup.getId()); + } + + @Test + public void testShareGroupV2WithAllUsersGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + + ShareGroupRequest unknownOwnerRequest = new ShareGroupRequest(TenantId.fromUUID(UUID.randomUUID()), true, null, true, null); + doPost("/api/v2/entityGroup/{entityGroupId}/share", unknownOwnerRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + ShareGroupRequest otherTenantRequest = new ShareGroupRequest(differentTenantId, true, null, true, null); + doPost("/api/v2/entityGroup/{entityGroupId}/share", otherTenantRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + assertThat(findSharedUserGroupIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareGroupV2WithAllUsersGroupOfOwnCustomerSharesWithThatGroup() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + EntityGroup customerAllUsersGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, customerId, + EntityType.USER, EntityGroup.GROUP_ALL_NAME).get(); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(customerId, true, null, true, null); + doPost("/api/v2/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString()) + .andExpect(status().isOk()); + assertThat(findSharedUserGroupIds(deviceGroup)).containsExactly(customerAllUsersGroup.getId()); + } + + @Test + public void testShareGroupToChildOwnerUserGroupWithGroupsOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantUserGroup = new EntityGroup(); + otherTenantUserGroup.setName("Other Tenant User Group"); + otherTenantUserGroup.setType(EntityType.USER); + otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class); + EntityGroup otherTenantDeviceGroup = new EntityGroup(); + otherTenantDeviceGroup.setName("Other Tenant Device Group"); + otherTenantDeviceGroup.setType(EntityType.DEVICE); + otherTenantDeviceGroup = doPost("/api/entityGroup", otherTenantDeviceGroup, EntityGroup.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setName("Shared Device Group"); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + EntityGroup userGroup = new EntityGroup(); + userGroup.setName("Own User Group"); + userGroup.setType(EntityType.USER); + userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class); + Role role = new Role(); + role.setName("Read Group Role"); + role.setType(RoleType.GROUP); + role.setPermissions(JacksonUtil.valueToTree(List.of(Operation.READ))); + role = doPost("/api/role", role, Role.class); + + doPost("/api/entityGroup/" + deviceGroup.getId().getId() + "/" + otherTenantUserGroup.getId().getId() + "/" + role.getId().getId() + "/share") + .andExpect(status().isNotFound()); + doPost("/api/entityGroup/" + otherTenantDeviceGroup.getId().getId() + "/" + userGroup.getId().getId() + "/" + role.getId().getId() + "/share") + .andExpect(status().isNotFound()); + } + + @Test + public void testGetAttributesOfEntityGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Asset Group"); + otherTenantGroup.setType(EntityType.ASSET); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + doGetAsync("/api/plugins/telemetry/ENTITY_GROUP/" + otherTenantGroup.getId().getId() + "/values/attributes") + .andExpect(status().isNotFound()); + } + + @Test + public void testGetEntityGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Asset Group"); + otherTenantGroup.setType(EntityType.ASSET); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + doGet("/api/entityGroup/" + otherTenantGroup.getId().getId()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(not(containsString(otherTenantGroup.getName())))); + } + + @Test + public void testShouldNotUpdateNonExistingEntityGroup() throws Exception { + loginTenantAdmin(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setId(new EntityGroupId(UUID.randomUUID())); + entityGroup.setName("Non-existing Device Group"); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setOwnerId(tenantId); + doPost("/api/entityGroup", entityGroup) + .andExpect(status().isNotFound()); + } + @Test public void testSaveEntityGroupWithSameName() throws Exception { EntityGroup entityGroup = new EntityGroup(); @@ -314,4 +626,164 @@ public class EntityGroupControllerTest extends AbstractControllerTest { Assert.assertNotNull(foundDashboard2); } + @Test + public void testShareEntityGroupWithGroupRole() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId); + Role groupRole = createRole(tenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]"); + + shareWithRoles(deviceGroup, customerId, groupRole.getId()) + .andExpect(status().isOk()); + + assertThat(findSharedRoleIds(deviceGroup)).containsExactly(groupRole.getId()); + } + + @Test + public void testShareEntityGroupRejectsGenericRole() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId); + Role genericRole = createRole(tenantId, null, "Generic role", RoleType.GENERIC, "{\"DEVICE\":[\"READ\"]}"); + + shareWithRoles(deviceGroup, customerId, genericRole.getId()) + .andExpect(status().isBadRequest()); + + assertThat(findSharedRoleIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareEntityGroupRequiresReadableRole() throws Exception { + createDifferentTenant(); + Role otherTenantRole = createRole(differentTenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]"); + + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId); + + shareWithRoles(deviceGroup, customerId, otherTenantRole.getId()) + .andExpect(status().isForbidden()); + + assertThat(findSharedRoleIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareEntityGroupSavesNothingWhenAnyRoleRejected() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId); + Role groupRole = createRole(tenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]"); + Role genericRole = createRole(tenantId, null, "Generic role", RoleType.GENERIC, "{\"DEVICE\":[\"READ\"]}"); + + shareWithRoles(deviceGroup, customerId, groupRole.getId(), genericRole.getId()) + .andExpect(status().isBadRequest()); + + assertThat(findSharedRoleIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareEntityGroupRequiresRoleOperationsHeldByUser() throws Exception { + loginTenantAdmin(); + User manager = createGroupManager(createCustomerUserGroup(), GROUP_MANAGER_PERMISSIONS); + EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId); + Role readRole = createRole(tenantId, customerId, "Read role", RoleType.GROUP, "[\"READ\"]"); + Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]"); + + login(manager.getEmail(), "manager"); + shareWithRoles(deviceGroup, customerId, rpcRole.getId()) + .andExpect(status().isForbidden()); + assertThat(findSharedRoleIds(deviceGroup)).isEmpty(); + + shareWithRoles(deviceGroup, customerId, readRole.getId()) + .andExpect(status().isOk()); + assertThat(findSharedRoleIds(deviceGroup)).containsExactly(readRole.getId()); + } + + @Test + public void testShareEntityGroupAllowsRoleOperationsHeldOnEntities() throws Exception { + loginTenantAdmin(); + User manager = createGroupManager(createCustomerUserGroup(), + "{\"DEVICE_GROUP\":[\"READ\",\"WRITE\"],\"DEVICE\":[\"RPC_CALL\"],\"USER_GROUP\":[\"READ\",\"WRITE\"],\"GROUP_PERMISSION\":[\"CREATE\"],\"ROLE\":[\"READ\"]}"); + EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId); + Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]"); + + login(manager.getEmail(), "manager"); + shareWithRoles(deviceGroup, customerId, rpcRole.getId()) + .andExpect(status().isOk()); + assertThat(findSharedRoleIds(deviceGroup)).containsExactly(rpcRole.getId()); + } + + @Test + public void testShareEntityGroupAllowsRoleOperationsHeldOnSharedGroup() throws Exception { + loginTenantAdmin(); + EntityGroup managers = createCustomerUserGroup(); + User manager = createGroupManager(managers, GROUP_MANAGER_PERMISSIONS); + EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId); + Role groupRpcRole = createRole(tenantId, customerId, "RPC role", RoleType.GROUP, "[\"RPC_CALL\"]"); + GroupPermission groupRpcPermission = new GroupPermission(); + groupRpcPermission.setRoleId(groupRpcRole.getId()); + groupRpcPermission.setUserGroupId(managers.getId()); + groupRpcPermission.setEntityGroupId(deviceGroup.getId()); + groupRpcPermission.setEntityGroupType(deviceGroup.getType()); + doPost("/api/groupPermission", groupRpcPermission, GroupPermission.class); + Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]"); + + login(manager.getEmail(), "manager"); + shareWithRoles(deviceGroup, customerId, rpcRole.getId()) + .andExpect(status().isOk()); + assertThat(findSharedRoleIds(deviceGroup)).contains(rpcRole.getId()); + } + + private EntityGroup createCustomerUserGroup() throws Exception { + EntityGroup userGroup = new EntityGroup(); + userGroup.setType(EntityType.USER); + userGroup.setName("Group managers"); + userGroup.setOwnerId(customerId); + return doPost("/api/entityGroup", userGroup, EntityGroup.class); + } + + private User createGroupManager(EntityGroup userGroup, String permissions) throws Exception { + Role managerRole = createRole(tenantId, customerId, "Group manager", RoleType.GENERIC, permissions); + GroupPermission managerPermission = new GroupPermission(); + managerPermission.setRoleId(managerRole.getId()); + managerPermission.setUserGroupId(userGroup.getId()); + doPost("/api/groupPermission", managerPermission, GroupPermission.class); + + User manager = new User(); + manager.setAuthority(Authority.CUSTOMER_USER); + manager.setTenantId(tenantId); + manager.setCustomerId(customerId); + manager.setEmail("groupmanager@thingsboard.org"); + return createUser(manager, "manager", userGroup.getId()); + } + + private EntityGroup createDeviceGroup(String name, EntityId ownerId) throws Exception { + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName(name); + entityGroup.setOwnerId(ownerId); + return doPost("/api/entityGroup", entityGroup, EntityGroup.class); + } + + private Role createRole(TenantId roleTenantId, CustomerId roleCustomerId, String name, RoleType type, String permissions) { + Role role = new Role(); + role.setTenantId(roleTenantId); + role.setCustomerId(roleCustomerId); + role.setType(type); + role.setName(name); + role.setPermissions(JacksonUtil.toJsonNode(permissions)); + return roleService.saveRole(roleTenantId, role); + } + + private ResultActions shareWithRoles(EntityGroup entityGroup, CustomerId targetCustomerId, RoleId... roleIds) throws Exception { + var shareGroupRequest = new ShareGroupRequest(targetCustomerId, true, null, false, List.of(roleIds)); + return doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, entityGroup.getId().toString()); + } + + private List findSharedRoleIds(EntityGroup entityGroup) { + return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100)) + .getData().stream().map(GroupPermission::getRoleId).collect(Collectors.toList()); + } + + private List findSharedUserGroupIds(EntityGroup entityGroup) { + return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100)) + .getData().stream().map(GroupPermission::getUserGroupId).collect(Collectors.toList()); + } + } diff --git a/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java index 12561a35d2..48c508f43f 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java @@ -353,6 +353,94 @@ public class EntityViewControllerTest extends AbstractControllerTest { deleteDifferentTenant(); } + @Test + public void testSaveEntityViewWithEntityOfOtherTenant() throws Exception { + loginDifferentTenant(); + + String name = "Entity view of other tenant device"; + EntityView entityView = createEntityView(name, 0, 0); + doPost("/api/entityView", entityView) + .andExpect(status().is4xxClientError()); + + doGet("/api/tenant/entityViews?entityViewName=" + name) + .andExpect(status().isNotFound()); + + deleteDifferentTenant(); + } + + @Test + public void testUpdateEntityViewByCustomerUserToEntityNotAssignedToCustomer() throws Exception { + EntityView savedView = getNewSavedEntityView("Customer entity view"); + doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk()); + doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/DEVICE/" + testDevice.getId().getId()).andExpect(status().isOk()); + + Device otherDevice = new Device(); + otherDevice.setName("Device not assigned to customer"); + otherDevice.setType("default"); + otherDevice = doPost("/api/device", otherDevice, Device.class); + + loginCustomerAdminUser(); + + EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + customerView.setEntityId(otherDevice.getId()); + doPost("/api/entityView", customerView) + .andExpect(status().isForbidden()); + + EntityView foundView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + assertEquals(testDevice.getId(), foundView.getEntityId()); + } + + @Test + public void testUpdateEntityViewByCustomerUserKeepingEntity() throws Exception { + EntityView savedView = getNewSavedEntityView("Customer entity view"); + doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk()); + + loginCustomerAdminUser(); + + EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + customerView.setName("Customer entity view renamed"); + EntityView updatedView = doPost("/api/entityView", customerView, EntityView.class); + + assertEquals("Customer entity view renamed", updatedView.getName()); + assertEquals(testDevice.getId(), updatedView.getEntityId()); + } + + @Test + public void testUpdateEntityViewKeysByCustomerUserWithEntityNotAssignedToCustomer() throws Exception { + EntityView savedView = getNewSavedEntityView("Customer entity view"); + doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk()); + + loginCustomerAdminUser(); + + EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + customerView.setKeys(new TelemetryEntityView(List.of("tsKey1"), new AttributesEntityView())); + doPost("/api/entityView", customerView) + .andExpect(status().isForbidden()); + + customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + customerView.setStartTimeMs(1L); + doPost("/api/entityView", customerView) + .andExpect(status().isForbidden()); + + EntityView foundView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + assertEquals(telemetry, foundView.getKeys()); + assertEquals(0L, foundView.getStartTimeMs()); + } + + @Test + public void testFindEntityViewByOldNameAfterRename() throws Exception { + String oldName = "Entity view old name"; + EntityView savedView = getNewSavedEntityView(oldName); + doGet("/api/tenant/entityViews?entityViewName=" + oldName) + .andExpect(status().isOk()); + + savedView.setName("Entity view new name"); + doPost("/api/entityView", savedView, EntityView.class); + + doGet("/api/tenant/entityViews?entityViewName=" + oldName) + .andExpect(status().isNotFound()); + } + @Test public void testDeleteEntityView() throws Exception { Customer customer = doPost("/api/customer", getNewCustomer("My customer"), Customer.class); @@ -380,6 +468,7 @@ public class EntityViewControllerTest extends AbstractControllerTest { public void testSaveEntityViewWithEmptyName() throws Exception { EntityView entityView = new EntityView(); entityView.setType("default"); + entityView.setEntityId(testDevice.getId()); Mockito.reset(tbClusterService, auditLogService); diff --git a/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java index 342151bee4..dd16575a86 100644 --- a/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java @@ -3,23 +3,27 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; +import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.permission.AllowedPermissionsInfo; import org.thingsboard.server.common.data.permission.GroupPermission; import org.thingsboard.server.common.data.permission.GroupPermissionInfo; +import org.thingsboard.server.common.data.permission.ShareGroupRequest; import org.thingsboard.server.common.data.role.Role; import org.thingsboard.server.common.data.role.RoleType; import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.dao.grouppermission.GroupPermissionService; import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.ArrayList; @@ -35,6 +39,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DaoSqlTest public class GroupPermissionControllerTest extends AbstractControllerTest { + @Autowired + private GroupPermissionService groupPermissionService; + private IdComparator idComparator; private Tenant savedTenant; private User tenantAdmin; @@ -278,6 +285,222 @@ public class GroupPermissionControllerTest extends AbstractControllerTest { checkPermissionOwners(loadedGroupPermissionsInfo, List.of(subCustomerId)); } + @Test + public void testLoadUserGroupPermissionInfosReturnsOnlyOwnTenantData() throws Exception { + loginDifferentTenant(); + Role otherTenantRole = doPost("/api/role", newRole("Other Tenant Role", RoleType.GROUP), Role.class); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + Role ownRole = doPost("/api/role", newRole("Own Role", RoleType.GROUP), Role.class); + + GroupPermission otherTenantRolePermission = new GroupPermission(); + otherTenantRolePermission.setRoleId(otherTenantRole.getId()); + GroupPermission otherTenantGroupPermission = new GroupPermission(); + otherTenantGroupPermission.setRoleId(ownRole.getId()); + otherTenantGroupPermission.setEntityGroupId(otherTenantGroup.getId()); + + List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", + List.of(otherTenantRolePermission, otherTenantGroupPermission), new TypeReference<>() {}); + assertThat(infos).isEmpty(); + } + + @Test + public void testLoadUserGroupPermissionInfosReturnsOnlyReadableGroups() throws Exception { + loginTenantAdmin(); + Role role = doPost("/api/role", newRole("Group Role", RoleType.GROUP), Role.class); + EntityGroup tenantGroup = new EntityGroup(); + tenantGroup.setType(EntityType.DEVICE); + tenantGroup.setName("Tenant Device Group"); + tenantGroup = doPost("/api/entityGroup", tenantGroup, EntityGroup.class); + + loginCustomerAdminUser(); + EntityGroup customerGroup = new EntityGroup(); + customerGroup.setType(EntityType.DEVICE); + customerGroup.setName("Customer Device Group"); + customerGroup.setOwnerId(customerId); + customerGroup = doPost("/api/entityGroup", customerGroup, EntityGroup.class); + + GroupPermission tenantGroupPermission = new GroupPermission(); + tenantGroupPermission.setRoleId(role.getId()); + tenantGroupPermission.setEntityGroupId(tenantGroup.getId()); + GroupPermission customerGroupPermission = new GroupPermission(); + customerGroupPermission.setRoleId(role.getId()); + customerGroupPermission.setEntityGroupId(customerGroup.getId()); + + List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", + List.of(tenantGroupPermission, customerGroupPermission), new TypeReference<>() {}); + assertThat(infos).extracting(GroupPermissionInfo::getEntityGroupId).containsExactly(customerGroup.getId()); + } + + @Test + public void testLoadUserGroupPermissionInfosKeepsSystemRoles() throws Exception { + loginTenantAdmin(); + EntityGroup tenantAdminsGroup = findGroupByOwnerIdTypeAndName(tenantId, EntityType.USER, EntityGroup.GROUP_TENANT_ADMINS_NAME); + List storedInfos = doGetTyped("/api/userGroup/" + tenantAdminsGroup.getId() + "/groupPermissions", + new TypeReference<>() {}); + assertThat(storedInfos).isNotEmpty(); + assertThat(storedInfos).allSatisfy(info -> assertThat(info.getRole().getTenantId().isSysTenantId()).isTrue()); + + List permissions = storedInfos.stream().map(GroupPermission::new).toList(); + List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", permissions, new TypeReference<>() {}); + assertThat(infos).hasSameSizeAs(permissions); + assertThat(infos).allSatisfy(info -> assertThat(info.getRole()).isNotNull()); + } + + @Test + public void testShareGroupWithRoleOfOtherTenantIsRejected() throws Exception { + loginDifferentTenant(); + Role otherTenantRole = doPost("/api/role", newRole("Other Tenant Role", RoleType.GROUP), Role.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup.setName("Shared Device Group"); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, true, null, false, List.of(otherTenantRole.getId())); + doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString()) + .andExpect(status().isForbidden()); + + assertThat(groupPermissionService.findGroupPermissionByTenantIdAndRoleId(tenantId, otherTenantRole.getId(), new PageLink(10)).getData()).isEmpty(); + } + + private Role newRole(String roleName, RoleType roleType) { + Role role = new Role(); + role.setName(roleName); + role.setType(roleType); + return role; + } + + @Test + public void testCustomerAdminCannotUpdateTenantGroupPermission() throws Exception { + loginTenantAdmin(); + EntityGroup tenantUserGroup = saveUserGroup("Tenant users"); + Role tenantRole = doPost("/api/role", createRole("Tenant role", RoleType.GENERIC), Role.class); + GroupPermission groupPermission = new GroupPermission(); + groupPermission.setRoleId(tenantRole.getId()); + groupPermission.setUserGroupId(tenantUserGroup.getId()); + groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class); + + loginCustomerAdminUser(); + Role customerRole = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class); + GroupPermission update = new GroupPermission(groupPermission); + update.setUserGroupId(findCustomerAdminsGroup(customerId).getId()); + update.setRoleId(customerRole.getId()); + doPost("/api/groupPermission", update).andExpect(status().isForbidden()); + + loginTenantAdmin(); + GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class); + assertEquals(tenantUserGroup.getId(), stored.getUserGroupId()); + assertEquals(tenantRole.getId(), stored.getRoleId()); + } + + @Test + public void testCustomerAdminCannotMoveGroupPermissionFromTenantUserGroup() throws Exception { + loginCustomerAdminUser(); + Role customerRole = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class); + EntityGroup customerUserGroup = saveUserGroup("Customer users"); + + loginTenantAdmin(); + EntityGroup tenantUserGroup = saveUserGroup("Tenant users"); + GroupPermission groupPermission = new GroupPermission(); + groupPermission.setRoleId(customerRole.getId()); + groupPermission.setUserGroupId(tenantUserGroup.getId()); + groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class); + + loginCustomerAdminUser(); + GroupPermission update = new GroupPermission(groupPermission); + update.setUserGroupId(customerUserGroup.getId()); + doPost("/api/groupPermission", update).andExpect(status().isForbidden()); + + loginTenantAdmin(); + GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class); + assertEquals(tenantUserGroup.getId(), stored.getUserGroupId()); + } + + @Test + public void testCustomerAdminCannotUpdateGroupPermissionOfTenantEntityGroup() throws Exception { + loginCustomerAdminUser(); + Role customerRole = doPost("/api/role", createRole("Customer group role", RoleType.GROUP), Role.class); + EntityGroup customerUserGroup = saveUserGroup("Customer users"); + EntityGroup customerDeviceGroup = saveDeviceGroup("Customer devices"); + + loginTenantAdmin(); + EntityGroup tenantDeviceGroup = saveDeviceGroup("Tenant devices"); + GroupPermission groupPermission = new GroupPermission(); + groupPermission.setRoleId(customerRole.getId()); + groupPermission.setUserGroupId(customerUserGroup.getId()); + groupPermission.setEntityGroupId(tenantDeviceGroup.getId()); + groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class); + + loginCustomerAdminUser(); + GroupPermission update = new GroupPermission(groupPermission); + update.setEntityGroupId(customerDeviceGroup.getId()); + doPost("/api/groupPermission", update).andExpect(status().isForbidden()); + + loginTenantAdmin(); + GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class); + assertEquals(tenantDeviceGroup.getId(), stored.getEntityGroupId()); + } + + @Test + public void testPublicGroupPermissionIsNotUpdatable() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = saveDeviceGroup("Public devices"); + doPost("/api/entityGroup/" + deviceGroup.getUuidId() + "/makePublic").andExpect(status().isOk()); + List permissions = doGetTyped("/api/entityGroup/" + deviceGroup.getUuidId() + "/groupPermissions", + new TypeReference<>() {}); + assertEquals(1, permissions.size()); + GroupPermission publicPermission = doGet("/api/groupPermission/" + permissions.get(0).getUuidId(), GroupPermission.class); + assertTrue(publicPermission.isPublic()); + + EntityGroup userGroup = saveUserGroup("Other users"); + GroupPermission update = new GroupPermission(publicPermission); + update.setPublic(false); + update.setUserGroupId(userGroup.getId()); + doPost("/api/groupPermission", update).andExpect(status().isForbidden()); + + GroupPermission stored = doGet("/api/groupPermission/" + publicPermission.getUuidId(), GroupPermission.class); + assertTrue(stored.isPublic()); + assertEquals(publicPermission.getUserGroupId(), stored.getUserGroupId()); + } + + @Test + public void testCustomerAdminUpdatesOwnGroupPermission() throws Exception { + loginCustomerAdminUser(); + EntityGroup firstUserGroup = saveUserGroup("First customer users"); + EntityGroup secondUserGroup = saveUserGroup("Second customer users"); + Role role = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class); + GroupPermission groupPermission = new GroupPermission(); + groupPermission.setRoleId(role.getId()); + groupPermission.setUserGroupId(firstUserGroup.getId()); + groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class); + + groupPermission.setUserGroupId(secondUserGroup.getId()); + doPost("/api/groupPermission", groupPermission).andExpect(status().isOk()); + + GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class); + assertEquals(secondUserGroup.getId(), stored.getUserGroupId()); + } + + private EntityGroup saveUserGroup(String name) throws Exception { + EntityGroup userGroup = new EntityGroup(); + userGroup.setType(EntityType.USER); + userGroup.setName(name); + return doPost("/api/entityGroup", userGroup, EntityGroup.class); + } + + private EntityGroup saveDeviceGroup(String name) throws Exception { + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup.setName(name); + return doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + } + private void checkPermissionOwners(List groupPermissionsInfos, List ownerIds) { for (GroupPermissionInfo groupPermissionInfo : groupPermissionsInfos) { assertTrue(ownerIds.contains(groupPermissionInfo.getUserGroupOwnerId())); diff --git a/application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java index d37121847d..eff12bf015 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java @@ -307,7 +307,7 @@ public class ImageControllerTest extends AbstractControllerTest { Map expectedHeaders = Map.of( "Baker Street, 221B.png", "attachment; filename=\"Baker Street, 221B.png\"", "\"Baker Street\", 221B.png", "attachment; filename=\"\\\"Baker Street\\\", 221B.png\"", - "Хрещатик, 22.png", "attachment; filename=\"=?UTF-8?Q?=D0=A5=D1=80=D0=B5=D1=89=D0=B0=D1=82=D0=B8=D0=BA,_22.png?=\"; " + + "Хрещатик, 22.png", "attachment; filename=\"________, 22.png\"; " + "filename*=UTF-8''%D0%A5%D1%80%D0%B5%D1%89%D0%B0%D1%82%D0%B8%D0%BA%2C%2022.png" ); diff --git a/application/src/test/java/org/thingsboard/server/controller/IntegrationControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/IntegrationControllerTest.java index b23ddbc671..f74f782f5b 100644 --- a/application/src/test/java/org/thingsboard/server/controller/IntegrationControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/IntegrationControllerTest.java @@ -5,13 +5,13 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import org.awaitility.Awaitility; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.TestPropertySource; -import org.testcontainers.shaded.org.awaitility.Awaitility; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.EntityInfo; import org.thingsboard.server.common.data.IntegrationConvertersInfo; diff --git a/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java index c5f9695396..1de79b3f5d 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java @@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.AlarmSeverity; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.id.ReportTemplateId; +import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.job.Job; import org.thingsboard.server.common.data.job.JobStatus; import org.thingsboard.server.common.data.job.JobType; @@ -101,6 +102,8 @@ import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -826,6 +829,35 @@ public class ReportControllerTest extends AbstractControllerTest { doPost("/api/v2/report/test", request).andExpect(status().isOk()); } + @Test + public void testTestReportRequiresPermissionOverReportUser() throws Exception { + loginDifferentTenant(); + UserId otherTenantUserId = savedDifferentTenantUser.getId(); + loginTenantAdmin(); + + ReportRequest request = new ReportRequest(); + request.setReportTemplateConfig(buildReportTemplate(TbReportFormat.CSV).getConfiguration()); + request.setUserId(otherTenantUserId.toString()); + doPost("/api/v2/report/test", request).andExpect(status().isForbidden()); + + verify(tbReportService, never()).generateTestReport(any()); + } + + @Test + public void testRequestReportRequiresPermissionOverReportUser() throws Exception { + loginDifferentTenant(); + UserId otherTenantUserId = savedDifferentTenantUser.getId(); + loginTenantAdmin(); + + ReportTemplate reportTemplate = doPost("/api/reportTemplate", buildReportTemplate(TbReportFormat.CSV), ReportTemplate.class); + ReportRequest request = new ReportRequest(); + request.setReportTemplateId(reportTemplate.getId()); + request.setUserId(otherTenantUserId.toString()); + doPost("/api/v2/report/request", request).andExpect(status().isForbidden()); + + assertThat(findJobs(List.of(JobType.REPORT), List.of(reportTemplate.getId().getId()))).isEmpty(); + } + private TimeseriesTableComponent buildTimeseriesTableComponent(String devicesAliasId) { return buildTimeseriesTableComponent(devicesAliasId, buildCurrentDateTimeWindow()); } diff --git a/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java index c468f3fd55..273b7b9910 100644 --- a/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java @@ -16,6 +16,7 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.msg.TbMsgType; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; @@ -242,6 +243,32 @@ public class RuleEngineControllerTest extends AbstractControllerTest { verifyNoInteractions(ruleEngineCallService); } + @Test + public void testHandleRuleEngineRequestRequiresPermissionOverReportUser() throws Exception { + loginCustomerAdminUser(); + + doPost("/api/rule-engine/", (Object) reportRequestBody(tenantAdminUserId)) + .andExpect(status().isForbidden()); + doPost("/api/rule-engine/", (Object) reportConfigRequestBody(tenantAdminUserId)) + .andExpect(status().isForbidden()); + verifyNoInteractions(ruleEngineCallService); + + TbMsg responseMsg = TbMsg.newMsg() + .type(TbMsgType.REST_API_REQUEST) + .originator(customerAdminUserId) + .copyMetaData(TbMsgMetaData.EMPTY) + .data(RESPONSE_BODY) + .build(); + mockRestApiCallToRuleEngine(responseMsg); + + String ownReportRequestBody = reportRequestBody(customerAdminUserId); + doPostAsyncWithTypedResponse("/api/rule-engine/", ownReportRequestBody, new TypeReference() { + }, status().isOk()); + ArgumentCaptor requestMsgCaptor = ArgumentCaptor.forClass(TbMsg.class); + verify(ruleEngineCallService).processRestApiCallToRuleEngine(eq(tenantId), any(UUID.class), requestMsgCaptor.capture(), eq(false), any(Consumer.class)); + assertThat(requestMsgCaptor.getValue().getData()).isEqualTo(ownReportRequestBody); + } + @Test public void testHandleRuleEngineRequestUnauthorized() throws Exception { doPost("/api/rule-engine/", (Object) REQUEST_BODY) @@ -249,6 +276,14 @@ public class RuleEngineControllerTest extends AbstractControllerTest { .andExpect(statusReason(containsString("Authentication failed"))); } + private String reportRequestBody(UserId userId) { + return "{\"reportConfig\":{\"userId\":\"" + userId.getId() + "\"}}"; + } + + private String reportConfigRequestBody(UserId userId) { + return "{\"userId\":{\"id\":\"" + userId.getId() + "\"}}"; + } + private void mockRestApiCallToRuleEngine(TbMsg responseMsg) { doAnswer(invocation -> { Consumer consumer = invocation.getArgument(4); diff --git a/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java index 00c25ef349..4d52fd804d 100644 --- a/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java @@ -276,6 +276,48 @@ public class SchedulerEventControllerTest extends AbstractControllerTest { assertThat(reportInfos.getData()).hasSize(0); } + @Test + public void testSaveReportEventRequiresPermissionOverReportUser() throws Exception { + ReportTemplate template = doPost("/api/reportTemplate", buildTemplate("CSV report template", ReportTemplateType.REPORT, TbReportFormat.CSV), ReportTemplate.class); + + loginCustomerAdminUser(); + doPost("/api/schedulerEvent", createReportSchedulerEvent(template.getId(), tenantAdminUserId)).andExpect(status().isForbidden()); + doPost("/api/schedulerEvent", createDashboardReportSchedulerEvent(tenantAdminUserId)).andExpect(status().isForbidden()); + doPost("/api/schedulerEvent", createReportConfigMsgSchedulerEvent(tenantAdminUserId)).andExpect(status().isForbidden()); + assertThat(findSchedulerEvents(null, null)).isEmpty(); + + SchedulerEvent reportEvent = createReportSchedulerEvent(template.getId(), customerAdminUserId); + ((ObjectNode) reportEvent.getSchedule()).put("startTime", System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)); + assertThat(saveSchedulerEvent(reportEvent).getId()).isNotNull(); + assertThat(saveSchedulerEvent(createDashboardReportSchedulerEvent(customerAdminUserId)).getId()).isNotNull(); + + loginTenantAdmin(); + assertThat(saveSchedulerEvent(createDashboardReportSchedulerEvent(customerUserId)).getId()).isNotNull(); + } + + @Test + public void testSaveDashboardReportEventWithCurrentUserCredentialsUsesSaverWhenReportUserNotAccessible() throws Exception { + loginCustomerAdminUser(); + SchedulerEvent saved = saveSchedulerEvent(createDashboardReportSchedulerEvent(tenantAdminUserId, true)); + assertThat(saved.getConfiguration().get("msgBody").get("reportConfig").get("userId").asText()).isEqualTo(customerAdminUserId.toString()); + } + + @Test + public void testSaveDashboardReportEventWithCurrentUserCredentialsKeepsAccessibleReportUser() throws Exception { + SchedulerEvent saved = saveSchedulerEvent(createDashboardReportSchedulerEvent(customerAdminUserId, true)); + assertThat(saved.getConfiguration().get("msgBody").get("reportConfig").get("userId").asText()).isEqualTo(customerAdminUserId.toString()); + } + + @Test + public void testSaveReportEventRequiresReportUser() throws Exception { + ReportTemplate template = doPost("/api/reportTemplate", buildTemplate("CSV report template", ReportTemplateType.REPORT, TbReportFormat.CSV), ReportTemplate.class); + doPost("/api/schedulerEvent", createReportSchedulerEvent(template.getId(), null)).andExpect(status().isBadRequest()); + + SchedulerEvent noConfigurationEvent = createReportSchedulerEvent(template.getId(), tenantAdminUserId); + noConfigurationEvent.setConfiguration(null); + doPost("/api/schedulerEvent", noConfigurationEvent).andExpect(status().isBadRequest()); + } + private ReportTemplate buildTemplate(String templateName, ReportTemplateType report, TbReportFormat format) { ReportTemplate template = new ReportTemplate(); template.setName(templateName); @@ -310,6 +352,39 @@ public class SchedulerEventControllerTest extends AbstractControllerTest { return schedulerEvent; } + private SchedulerEvent createDashboardReportSchedulerEvent(UserId userId) { + return createDashboardReportSchedulerEvent(userId, false); + } + + private SchedulerEvent createDashboardReportSchedulerEvent(UserId userId, boolean useCurrentUserCredentials) { + SchedulerEvent schedulerEvent = createSchedulerEvent(); + schedulerEvent.setType("generateDashboardReport"); + ObjectNode reportConfig = JacksonUtil.newObjectNode(); + reportConfig.put("namePattern", "report-%d{yyyy-MM-dd_HH:mm:ss}"); + reportConfig.put("type", "pdf"); + reportConfig.put("useCurrentUserCredentials", useCurrentUserCredentials); + reportConfig.put("userId", userId.toString()); + ObjectNode msgBody = JacksonUtil.newObjectNode(); + msgBody.set("reportConfig", reportConfig); + msgBody.put("sendEmail", false); + ObjectNode configuration = JacksonUtil.newObjectNode(); + configuration.put("msgType", "generateDashboardReport"); + configuration.set("msgBody", msgBody); + schedulerEvent.setConfiguration(configuration); + return schedulerEvent; + } + + private SchedulerEvent createReportConfigMsgSchedulerEvent(UserId userId) { + SchedulerEvent schedulerEvent = createSchedulerEvent(); + ObjectNode msgBody = JacksonUtil.newObjectNode(); + msgBody.set("userId", JacksonUtil.valueToTree(userId)); + ObjectNode configuration = JacksonUtil.newObjectNode(); + configuration.put("msgType", "Custom Msg"); + configuration.set("msgBody", msgBody); + schedulerEvent.setConfiguration(configuration); + return schedulerEvent; + } + private SchedulerEvent saveSchedulerEvent(SchedulerEvent schedulerEvent) { return doPost("/api/schedulerEvent", schedulerEvent, SchedulerEvent.class); } diff --git a/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java index b100aa38c6..333f291b66 100644 --- a/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java @@ -4,16 +4,20 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; -import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.CustomerInfo; import org.thingsboard.server.common.data.Dashboard; @@ -26,6 +30,7 @@ import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.domain.Domain; import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.id.DashboardId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.menu.CMAssigneeType; import org.thingsboard.server.common.data.menu.CMScope; import org.thingsboard.server.common.data.menu.CustomMenu; @@ -37,6 +42,12 @@ import org.thingsboard.server.common.data.notification.NotificationDeliveryMetho import org.thingsboard.server.common.data.notification.NotificationType; import org.thingsboard.server.common.data.oauth2.PlatformType; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.permission.GroupPermission; +import org.thingsboard.server.common.data.permission.GroupPermissionInfo; +import org.thingsboard.server.common.data.role.Role; +import org.thingsboard.server.common.data.role.RoleType; +import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.common.data.security.UserCredentials; import org.thingsboard.server.common.data.selfregistration.DefaultDashboardParams; import org.thingsboard.server.common.data.selfregistration.HomeDashboardParams; import org.thingsboard.server.common.data.selfregistration.MobileRedirectParams; @@ -47,8 +58,10 @@ import org.thingsboard.server.common.data.selfregistration.V2CaptchaParams; import org.thingsboard.server.common.data.selfregistration.WebSelfRegistrationParams; import org.thingsboard.server.common.data.signup.SignUpRequest; import org.thingsboard.server.common.data.signup.SignUpResult; +import org.thingsboard.server.common.data.wl.WhiteLabelingType; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.group.EntityGroupService; +import org.thingsboard.server.dao.grouppermission.GroupPermissionService; import org.thingsboard.server.dao.menu.CustomMenuDao; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.dao.settings.AdminSettingsService; @@ -57,6 +70,7 @@ import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.dao.wl.WhiteLabelingService; import org.thingsboard.server.service.entitiy.TbLogEntityActionService; +import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -68,10 +82,14 @@ import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -87,6 +105,8 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { public static final String CUSTOMER_TEST_EMAIL = "signup-customer@thingsboard.org"; public static final String CUSTOMER_TITLE_PREFIX = "Prefix-"; + public static final String CONFIGURED_BASE_URL = "https://configured.example.com"; + public static final String OTHER_HOST = "other.example.com"; private static List idsToRemove = new ArrayList<>(); private EntityGroup customerGroup; @@ -116,6 +136,9 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { @Autowired protected WhiteLabelingService whiteLabelingService; + @Autowired + private GroupPermissionService groupPermissionService; + @Before public void beforeTest() throws Exception { loginTenantAdmin(); @@ -167,6 +190,41 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { removeCreatedUser(user); } + @Test + public void testSelfRegisterUserCreatesNewGroupPermissions() throws Exception { + EntityGroup userGroup = new EntityGroup(); + userGroup.setType(EntityType.USER); + userGroup.setName("Existing permission users"); + userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class); + Role role = new Role(); + role.setName("Existing permission role"); + role.setType(RoleType.GENERIC); + role = doPost("/api/role", role, Role.class); + GroupPermission existingPermission = new GroupPermission(); + existingPermission.setUserGroupId(userGroup.getId()); + existingPermission.setRoleId(role.getId()); + existingPermission = doPost("/api/groupPermission", existingPermission, GroupPermission.class); + + GroupPermission selfRegistrationPermission = new GroupPermission(existingPermission); + createWebSelfRegistrationSettings(List.of(selfRegistrationPermission)); + String email = "signup-permissions@thingsboard.org"; + doSignUp(createWebSignUpRequest(email)); + + GroupPermission storedPermission = doGet("/api/groupPermission/" + existingPermission.getUuidId(), GroupPermission.class); + assertThat(storedPermission.getUserGroupId()).isEqualTo(userGroup.getId()); + + User user = userService.findUserByEmail(tenantId, email); + EntityGroup selfRegistrationGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, user.getCustomerId(), EntityType.USER, + "Self Registration Users").orElseThrow(); + List selfRegistrationPermissions = doGetTyped("/api/userGroup/" + selfRegistrationGroup.getUuidId() + "/groupPermissions", + new TypeReference<>() {}); + assertThat(selfRegistrationPermissions).hasSize(1); + assertThat(selfRegistrationPermissions.get(0).getId()).isNotEqualTo(existingPermission.getId()); + assertThat(selfRegistrationPermissions.get(0).getRoleId()).isEqualTo(role.getId()); + + removeCreatedUser(user); + } + @Test public void testSelfRegisterUserFromMobileApp() throws Exception { String appSecret = StringUtils.randomAlphanumeric(24); @@ -320,6 +378,223 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { removeCreatedUser(user); } + @Test + public void testSelfRegisterUserSkipsPermissionForGroupOfOtherTenant() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + Role role = new Role(); + role.setName("Self Registration Group Role"); + role.setType(RoleType.GROUP); + role.setPermissions(JacksonUtil.toJsonNode("[\"READ\"]")); + role = doPost("/api/role", role, Role.class); + GroupPermission permission = new GroupPermission(); + permission.setRoleId(role.getId()); + permission.setEntityGroupId(otherTenantGroup.getId()); + createWebSelfRegistrationSettings(List.of(permission)); + + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + + assertThat(groupPermissionService.findGroupPermissionByTenantIdAndRoleId(tenantId, role.getId(), new PageLink(10)).getData()).isEmpty(); + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testResendEmailActivationForPendingSignUpUser() throws Exception { + createWebSelfRegistrationSettings(); + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + + Mockito.clearInvocations(mailService); + doPost("/api/noauth/resendEmailActivation?email=" + CUSTOMER_TEST_EMAIL).andExpect(status().isOk()); + + verify(mailService, times(1)).sendActivationEmail(eq(tenantId), anyString(), anyLong(), eq(CUSTOMER_TEST_EMAIL)); + + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testResendEmailActivationSendsNothingForUserOfOtherTenant() throws Exception { + createWebSelfRegistrationSettings(); + createDifferentTenant(); + + User otherUser = new User(); + otherUser.setAuthority(Authority.TENANT_ADMIN); + otherUser.setTenantId(differentTenantId); + otherUser.setEmail("other.tenant.user@thingsboard.org"); + otherUser = doPost("/api/user?sendActivationMail=false", otherUser, User.class); + + UserCredentials credentials = userService.findUserCredentialsByUserId(differentTenantId, otherUser.getId()); + credentials.setPassword("abcdef123"); + credentials = userService.saveUserCredentials(differentTenantId, credentials); + + Mockito.clearInvocations(mailService); + doPost("/api/noauth/resendEmailActivation?email=" + otherUser.getEmail()).andExpect(status().isBadRequest()); + + verify(mailService, never()).sendActivationEmail(any(), anyString(), anyLong(), anyString()); + UserCredentials credentialsAfter = userService.findUserCredentialsByUserId(differentTenantId, otherUser.getId()); + assertThat(credentialsAfter.getActivateToken()).isEqualTo(credentials.getActivateToken()); + assertThat(credentialsAfter.getActivateTokenExpTime()).isEqualTo(credentials.getActivateTokenExpTime()); + + deleteDifferentTenant(); + } + + @Test + public void testResendEmailActivationSendsNothingForDisabledActivatedUser() throws Exception { + createWebSelfRegistrationSettings(); + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + + User user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL); + UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, user.getId()); + userService.activateUserCredentials(tenantId, credentials.getActivateToken(), credentials.getPassword()); + userService.setUserCredentialsEnabled(tenantId, user.getId(), false); + + Mockito.clearInvocations(mailService); + doPost("/api/noauth/resendEmailActivation?email=" + CUSTOMER_TEST_EMAIL).andExpect(status().isBadRequest()); + + verify(mailService, never()).sendActivationEmail(any(), anyString(), anyLong(), anyString()); + assertThat(userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken()).isNull(); + + removeCreatedUser(user); + } + + @Test + public void testActivationEmailLinkUsesConfiguredBaseUrl() throws Exception { + createWebSelfRegistrationSettings(); + AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL); + try { + Mockito.clearInvocations(mailService); + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + + assertThat(captureActivationLink()).startsWith(CONFIGURED_BASE_URL + "/api/noauth/activateEmail?emailCode="); + } finally { + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings); + } + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testActivationEmailLinkUsesRequestBaseUrlWhenGeneralBaseUrlIsMissing() throws Exception { + createWebSelfRegistrationSettings(); + AdminSettings generalSettings = setGeneralBaseUrl(null); + try { + Mockito.clearInvocations(mailService); + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + + assertThat(captureActivationLink()).startsWith("http://localhost:80/api/noauth/activateEmail?emailCode="); + } finally { + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings); + } + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testResendActivationEmailLinkUsesConfiguredBaseUrl() throws Exception { + String appSecret = StringUtils.randomAlphanumeric(24); + String mobilePkgName = "my.test.android.app"; + createMobileSelfRegistrationSettings(mobilePkgName, appSecret, PlatformType.ANDROID, createDashboard(), createDashboard()); + AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL); + try { + doSignUp(createMobileSignUpRequest(CUSTOMER_TEST_EMAIL, mobilePkgName, appSecret, PlatformType.ANDROID)); + + Mockito.clearInvocations(mailService); + mockMvc.perform(post("/api/noauth/resendEmailActivation") + .param("email", CUSTOMER_TEST_EMAIL) + .param("pkgName", mobilePkgName) + .param("platform", PlatformType.ANDROID.name()) + .header("Host", OTHER_HOST)) + .andExpect(status().isOk()); + + assertThat(captureActivationLink()).startsWith(CONFIGURED_BASE_URL + "/api/noauth/activateEmail?emailCode="); + } finally { + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings); + } + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testAccountActivatedEmailLinkUsesConfiguredBaseUrl() throws Exception { + createWebSelfRegistrationSettings(); + AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL); + User user; + try { + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL); + String activateToken = userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken(); + + Mockito.clearInvocations(mailService); + doPost("/api/noauth/activateByEmailCode?emailCode=" + activateToken).andExpect(status().isOk()); + + verify(mailService, times(1)).sendAccountActivatedEmail(eq(tenantId), eq(CONFIGURED_BASE_URL + "/login"), eq(CUSTOMER_TEST_EMAIL)); + } finally { + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings); + } + removeCreatedUser(user); + } + + @Test + public void testActivationEmailLinkUsesHttpSchemeForNonHttpForwardedProto() throws Exception { + createWebSelfRegistrationSettings(); + + Mockito.clearInvocations(mailService); + mockMvc.perform(post("/api/noauth/signup") + .contentType(contentType) + .content(json(createWebSignUpRequest(CUSTOMER_TEST_EMAIL))) + .header("X-Forwarded-Proto", "ftp")) + .andExpect(status().isOk()); + + URI activationLink = URI.create(captureActivationLink()); + assertThat(activationLink.getScheme()).isEqualTo("http"); + assertThat(activationLink.getHost()).isEqualTo("localhost"); + + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testActivationByEmailCodeOnOtherTenantSettingsIsRejected() throws Exception { + createWebSelfRegistrationSettings(); + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + User user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL); + String activateToken = userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken(); + + createDifferentTenant(); + createWebSelfRegistrationParams(OTHER_HOST, Collections.emptyList()); + + mockMvc.perform(post("/api/noauth/activateByEmailCode") + .param("emailCode", activateToken) + .header("Host", OTHER_HOST)) + .andExpect(status().isBadRequest()); + + assertThat(userService.findUserCredentialsByUserId(tenantId, user.getId()).isEnabled()).isFalse(); + + deleteDifferentTenant(); + removeCreatedUser(user); + } + + @Test + public void testSaveSelfRegistrationParamsWithDomainOfOtherTenantIsForbidden() throws Exception { + String domainName = "signup-other-tenant.example.com"; + Domain savedDomain = doPost("/api/domain", constructDomain(domainName), Domain.class); + + loginDifferentTenant(); + WebSelfRegistrationParams selfRegistrationParams = new WebSelfRegistrationParams(); + selfRegistrationParams.setTitle("Please sign up"); + selfRegistrationParams.setPrivacyPolicy("Privacy policy"); + selfRegistrationParams.setTermsOfUse("Terms of use"); + selfRegistrationParams.setDomainId(savedDomain.getId()); + selfRegistrationParams.setPermissions(Collections.emptyList()); + + doPost("/api/selfRegistration/selfRegistrationParams", selfRegistrationParams) + .andExpect(status().isForbidden()); + + assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.SELF_REGISTRATION)).isNull(); + assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.PRIVACY_POLICY)).isNull(); + assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.TERMS_OF_USE)).isNull(); + } + protected SignUpRequest createWebSignUpRequest(String email) { var signUpRequest = new SignUpRequest(); signUpRequest.setFields(Map.of(SignUpFieldId.EMAIL, email, @@ -388,8 +663,39 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { Assert.assertNull("Expected that created user is deleted but one found!", found); } + private String captureActivationLink() throws Exception { + ArgumentCaptor activationLink = ArgumentCaptor.forClass(String.class); + verify(mailService, times(1)).sendActivationEmail(eq(tenantId), activationLink.capture(), anyLong(), eq(CUSTOMER_TEST_EMAIL)); + return activationLink.getValue(); + } + + private AdminSettings setGeneralBaseUrl(String baseUrl) { + AdminSettings generalSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general"); + AdminSettings updatedSettings = new AdminSettings(generalSettings); + ObjectNode jsonValue = generalSettings.getJsonValue().deepCopy(); + if (baseUrl != null) { + jsonValue.put("baseUrl", baseUrl); + } else { + jsonValue.remove("baseUrl"); + } + jsonValue.put("prohibitDifferentUrl", true); + updatedSettings.setJsonValue(jsonValue); + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, updatedSettings); + return generalSettings; + } + private void createWebSelfRegistrationSettings() { - Domain domain = constructDomain("localhost"); + createWebSelfRegistrationSettings(Collections.emptyList()); + } + + private void createWebSelfRegistrationSettings(List permissions) { + createWebSelfRegistrationParams("localhost", permissions); + createNotificationTemplate(NotificationType.USER_ACTIVATED, "User activated", "User ${userEmail} was activated", NotificationDeliveryMethod.WEB); + createNotificationTemplate(NotificationType.USER_REGISTERED, "User registered", "User ${userEmail} was registered", NotificationDeliveryMethod.WEB); + } + + private void createWebSelfRegistrationParams(String domainName, List permissions) { + Domain domain = constructDomain(domainName); Domain savedDomain = doPost("/api/domain", domain, Domain.class); WebSelfRegistrationParams selfRegistrationParams = new WebSelfRegistrationParams(); @@ -402,13 +708,10 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { selfRegistrationParams.setShowPrivacyPolicy(true); selfRegistrationParams.setDomainId(savedDomain.getId()); selfRegistrationParams.setNotificationRecipient(createNotificationTarget(currentUserId).getId()); - selfRegistrationParams.setPermissions(Collections.emptyList()); + selfRegistrationParams.setPermissions(permissions); doPost("/api/selfRegistration/selfRegistrationParams", selfRegistrationParams, JsonNode.class); - - createNotificationTemplate(NotificationType.USER_ACTIVATED, "User activated", "User ${userEmail} was activated", NotificationDeliveryMethod.WEB); - createNotificationTemplate(NotificationType.USER_REGISTERED, "User registered", "User ${userEmail} was registered", NotificationDeliveryMethod.WEB); } private void createMobileSelfRegistrationSettings(String mobilePkgName, String appSecret, PlatformType platformType, diff --git a/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java index 1aae2d7fa5..fec9f9cb4d 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java @@ -22,6 +22,7 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.EntityInfo; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.ResourceSubType; import org.thingsboard.server.common.data.ResourceType; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.TbResource; @@ -32,6 +33,7 @@ import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.group.EntityGroupInfo; import org.thingsboard.server.common.data.id.TbResourceId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.lwm2m.LwM2mObject; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; @@ -926,6 +928,160 @@ public class TbResourceControllerTest extends AbstractControllerTest { assertThat(download(savedResource.getId())).asBase64Encoded().isEqualTo(newData); } + @Test + public void testUpdateResourceInfoKeepsStoredTenant() throws Exception { + TbResourceInfo savedResource = saveJsModule(); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setTenantId(null); + resourceInfo.setTitle("Updated title"); + Mockito.reset(tbClusterService, auditLogService); + TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(updatedResource.getTenantId()).isEqualTo(savedTenant.getId()); + assertThat(updatedResource.getTitle()).isEqualTo("Updated title"); + testNotifyEntityAllOneTimeLogEntityActionEntityEqClass(updatedResource, updatedResource.getId(), updatedResource.getId(), + savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), + ActionType.UPDATED, ActionType.UPDATED); + resourceInfo = findResourceInfo(savedResource.getId()); + assertThat(resourceInfo.getTenantId()).isEqualTo(savedTenant.getId()); + assertThat(resourceInfo.getTitle()).isEqualTo("Updated title"); + + resourceInfo.setTenantId(TenantId.SYS_TENANT_ID); + doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(savedTenant.getId()); + + loginDifferentTenant(); + login(tenantAdmin.getEmail(), "testPassword1"); + resourceInfo.setTenantId(savedDifferentTenant.getId()); + doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(savedTenant.getId()); + + deleteDifferentTenant(); + } + + @Test + public void testUpdateResourceInfoKeepsStoredKeyAndEtag() throws Exception { + TbResourceInfo savedResource = saveJsModule(); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setTitle("Updated title"); + resourceInfo.setResourceKey("other-key"); + resourceInfo.setEtag("0"); + resourceInfo.setCreatedTime(1); + TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(updatedResource.getTitle()).isEqualTo("Updated title"); + assertThat(updatedResource.getResourceKey()).isEqualTo(savedResource.getResourceKey()); + assertThat(updatedResource.getEtag()).isEqualTo(savedResource.getEtag()); + assertThat(updatedResource.getCreatedTime()).isEqualTo(savedResource.getCreatedTime()); + + resourceInfo = findResourceInfo(savedResource.getId()); + assertThat(resourceInfo.getResourceKey()).isEqualTo(savedResource.getResourceKey()); + assertThat(resourceInfo.getEtag()).isEqualTo(savedResource.getEtag()); + } + + @Test + public void testUpdateResourceInfoRefusesTypeChange() throws Exception { + TbResourceInfo savedResource = saveJsModule(); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setResourceType(ResourceType.GENERAL); + doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("can't be changed"))); + + resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setResourceSubType(ResourceSubType.MODULE); + doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("can't be changed"))); + + resourceInfo = findResourceInfo(savedResource.getId()); + assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE); + assertThat(resourceInfo.getResourceSubType()).isEqualTo(ResourceSubType.EXTENSION); + + resourceInfo.setTitle("Updated title"); + ObjectNode request = (ObjectNode) JacksonUtil.valueToTree(resourceInfo); + request.putNull("resourceType"); + request.putNull("resourceSubType"); + TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", request, TbResourceInfo.class); + assertThat(updatedResource.getTitle()).isEqualTo("Updated title"); + resourceInfo = findResourceInfo(savedResource.getId()); + assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE); + assertThat(resourceInfo.getResourceSubType()).isEqualTo(ResourceSubType.EXTENSION); + } + + @Test + public void testSaveResourceWithIdKeepsStoredTypeKeyAndEtag() throws Exception { + TbResourceInfo savedResource = saveJsModule(); + + TbResource resource = new TbResource(findResourceInfo(savedResource.getId())); + resource.setResourceType(ResourceType.GENERAL); + doPost("/api/resource", resource) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("can't be changed"))); + + resource.setResourceType(ResourceType.JS_MODULE); + resource.setTitle("Updated title"); + resource.setResourceKey("other-key"); + resource.setEtag("0"); + TbResourceInfo updatedResource = doPost("/api/resource", resource, TbResourceInfo.class); + assertThat(updatedResource.getTitle()).isEqualTo("Updated title"); + assertThat(updatedResource.getResourceKey()).isEqualTo(savedResource.getResourceKey()); + assertThat(updatedResource.getEtag()).isEqualTo(savedResource.getEtag()); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE); + assertThat(resourceInfo.getResourceKey()).isEqualTo(savedResource.getResourceKey()); + assertThat(resourceInfo.getEtag()).isEqualTo(savedResource.getEtag()); + } + + @Test + public void testSysAdminUpdateResourceInfoKeepsSystemTenant() throws Exception { + loginSysAdmin(); + TbResourceInfo savedResource = saveJsModule(); + assertThat(savedResource.getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setTenantId(savedTenant.getId()); + TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(updatedResource.getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID); + assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID); + + doDelete("/api/resource/" + savedResource.getUuidId()).andExpect(status().isOk()); + } + + @Test + public void testUpdateResourceInfoKeepsStoredCustomer() throws Exception { + Customer storedCustomer = saveCustomer("Stored resource customer"); + Customer otherCustomer = saveCustomer("Other resource customer"); + + TbResource resource = new TbResource(); + resource.setResourceType(ResourceType.JS_MODULE); + resource.setResourceSubType(ResourceSubType.EXTENSION); + resource.setTitle("Js resource"); + resource.setFileName(JS_TEST_FILE_NAME); + resource.setEncodedData(TEST_DATA); + resource.setCustomerId(storedCustomer.getId()); + TbResourceInfo savedResource = doPost("/api/resource", resource, TbResourceInfo.class); + assertThat(savedResource.getCustomerId()).isEqualTo(storedCustomer.getId()); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setCustomerId(otherCustomer.getId()); + TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(updatedResource.getCustomerId()).isEqualTo(storedCustomer.getId()); + + resourceInfo.setCustomerId(null); + updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(updatedResource.getCustomerId()).isEqualTo(storedCustomer.getId()); + assertThat(findResourceInfo(savedResource.getId()).getCustomerId()).isEqualTo(storedCustomer.getId()); + } + + private Customer saveCustomer(String title) throws Exception { + Customer customer = new Customer(); + customer.setTitle(title); + return doPost("/api/customer", customer, Customer.class); + } + @Test public void testGetLwm2mListObjectsPage() throws Exception { loginTenantAdmin(); @@ -1087,6 +1243,16 @@ public class TbResourceControllerTest extends AbstractControllerTest { return uploadResource(HttpMethod.POST, "/api/resource/upload", tbResource.getFileName(), tbResource.getResourceType().getMediaType(), data, parts); } + private TbResourceInfo saveJsModule() throws Exception { + TbResource resource = new TbResource(); + resource.setResourceType(ResourceType.JS_MODULE); + resource.setResourceSubType(ResourceSubType.EXTENSION); + resource.setTitle("Js resource"); + resource.setFileName(JS_TEST_FILE_NAME); + resource.setEncodedData(TEST_DATA); + return save(resource); + } + private TbResourceInfo findResourceInfo(TbResourceId id) throws Exception { return doGet("/api/resource/info/" + id, TbResourceInfo.class); } diff --git a/application/src/test/java/org/thingsboard/server/controller/TrendzApiControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/TrendzApiControllerTest.java index 99dddc6ae4..b7b19952b7 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TrendzApiControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/TrendzApiControllerTest.java @@ -2,11 +2,11 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.controller; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MvcResult; -import org.testcontainers.shaded.com.fasterxml.jackson.core.type.TypeReference; -import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.SortOrder; diff --git a/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java index 8574bd7bd0..04ccbcc671 100644 --- a/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java @@ -4,11 +4,11 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import org.awaitility.Awaitility; import org.junit.After; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.web.servlet.MvcResult; -import org.testcontainers.shaded.org.awaitility.Awaitility; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.StringUtils; diff --git a/application/src/test/java/org/thingsboard/server/controller/WidgetTypeControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/WidgetTypeControllerTest.java index 777d720d3d..77f318036b 100644 --- a/application/src/test/java/org/thingsboard/server/controller/WidgetTypeControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/WidgetTypeControllerTest.java @@ -6,11 +6,11 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; +import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntityType; diff --git a/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java index f6c34f1ffa..e4a78643f5 100644 --- a/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java @@ -20,6 +20,7 @@ import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput; import org.thingsboard.server.common.data.debug.DebugSettings; import org.thingsboard.server.common.data.id.CalculatedFieldId; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.cf.CalculatedFieldService; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.CalculatedFieldRequestMsg; @@ -109,6 +110,40 @@ public class CalculatedFieldEdgeTest extends AbstractEdgeTest { checkCalculatedFieldOnCloud(uplinkMsg, uuid, calculatedField.getName()); } + @Test + public void testSendCalculatedFieldToCloudSavesItUnderEdgeTenant() throws Exception { + Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge(); + + SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration(); + CalculatedField calculatedField = createSimpleCalculatedField(savedDevice.getId(), config); + calculatedField.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + UUID uuid = Uuids.timeBased(); + UplinkMsg uplinkMsg = getUplinkMsg(uuid, calculatedField, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); + + checkCalculatedFieldOnCloud(uplinkMsg, uuid, calculatedField.getName()); + + CalculatedField calculatedFieldFromCloud = doGet("/api/calculatedField/" + uuid, CalculatedField.class); + Assert.assertEquals(tenantId, calculatedFieldFromCloud.getTenantId()); + } + + @Test + public void testSendCalculatedFieldWithOtherTenantReferenceToCloud() throws Exception { + Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge(); + + SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration(); + CalculatedField calculatedField = createSimpleCalculatedField(savedDevice.getId(), config); + config.getArguments().get("T").setRefEntityId(TenantId.fromUUID(UUID.randomUUID())); + UUID uuid = Uuids.timeBased(); + UplinkMsg uplinkMsg = getUplinkMsg(uuid, calculatedField, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsg); + Assert.assertTrue(edgeImitator.waitForResponses()); + + Assert.assertFalse(edgeImitator.getLatestResponseMsg().getSuccess()); + doGet("/api/calculatedField/" + uuid).andExpect(status().isNotFound()); + } + @Test public void testSendCalculatedFieldRequestToCloud() throws Exception { Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge(); diff --git a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java index db600a0d17..49736cdb3d 100644 --- a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java @@ -679,6 +679,61 @@ public class DeviceEdgeTest extends AbstractEdgeTest { Assert.assertEquals(deviceName + " Updated", device.getName()); } + @Test + public void testSendDeviceToCloudAddsDeviceOnlyToGroupOfEdgeTenant() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + loginTenantAdmin(); + + Device deviceMsg = buildDeviceForUplinkMsg("Edge Device In Group", "test"); + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder(); + deviceUpdateMsgBuilder.setIdMSB(deviceMsg.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setIdLSB(deviceMsg.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdMSB(otherTenantGroup.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdLSB(otherTenantGroup.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setEntity(JacksonUtil.toString(deviceMsg)); + deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); + uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + + Device device = doGet("/api/device/" + deviceMsg.getId().getId(), Device.class); + Assert.assertNotNull(device); + Assert.assertFalse(entityGroupService.isEntityInGroup(differentTenantId, device.getId(), otherTenantGroup.getId())); + } + + @Test + public void testDeleteDeviceFromGroupOnCloudKeepsGroupsOfOtherTenant() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + Device otherTenantDevice = saveDevice("Other Tenant Device", "test", otherTenantGroup.getId()); + loginTenantAdmin(); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder(); + deviceUpdateMsgBuilder.setIdMSB(otherTenantDevice.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setIdLSB(otherTenantDevice.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdMSB(otherTenantGroup.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdLSB(otherTenantGroup.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE); + uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + + Assert.assertTrue(entityGroupService.isEntityInGroup(differentTenantId, otherTenantDevice.getId(), otherTenantGroup.getId())); + } + @Test public void testRpcCall() throws Exception { Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); diff --git a/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java index 176481a248..4bb40b6a87 100644 --- a/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java @@ -18,6 +18,7 @@ import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityViewId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.service.DaoSqlTest; @@ -191,6 +192,69 @@ public class EntityViewEdgeTest extends AbstractEdgeTest { Assert.assertNotEquals(entityViewOnCloudName, entityView.getName()); } + @Test + public void testEntityViewFromEdgeSavedInEdgeTenant() throws Exception { + Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); + + EntityView entityViewMsg = buildEntityViewForUplinkMsg(device, "Edge EntityView 3"); + entityViewMsg.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + EntityViewUpdateMsg.Builder entityViewUpdateMsgBuilder = EntityViewUpdateMsg.newBuilder(); + entityViewUpdateMsgBuilder.setIdMSB(entityViewMsg.getUuidId().getMostSignificantBits()); + entityViewUpdateMsgBuilder.setIdLSB(entityViewMsg.getUuidId().getLeastSignificantBits()); + entityViewUpdateMsgBuilder.setEntity(JacksonUtil.toString(entityViewMsg)); + entityViewUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); + uplinkMsgBuilder.addEntityViewUpdateMsg(entityViewUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.expectMessageAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + Assert.assertTrue(edgeImitator.getLatestResponseMsg().getSuccess()); + + EntityView entityView = doGet("/api/entityView/" + entityViewMsg.getUuidId(), EntityView.class); + Assert.assertEquals(tenantId, entityView.getTenantId()); + } + + @Test + public void testEntityViewFromEdgeWithIdOfOtherTenantViewNotSaved() throws Exception { + Device edgeDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge(); + + loginDifferentTenant(); + Device otherTenantDevice = new Device(); + otherTenantDevice.setName("Other tenant device"); + otherTenantDevice.setType("default"); + otherTenantDevice = doPost("/api/device", otherTenantDevice, Device.class); + EntityView otherTenantView = saveEntityView("Other tenant EntityView", otherTenantDevice.getId(), null); + loginTenantAdmin(); + + EntityView entityViewMsg = buildEntityViewForUplinkMsg(edgeDevice, "Edge EntityView 4"); + entityViewMsg.setId(otherTenantView.getId()); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + EntityViewUpdateMsg.Builder entityViewUpdateMsgBuilder = EntityViewUpdateMsg.newBuilder(); + entityViewUpdateMsgBuilder.setIdMSB(entityViewMsg.getUuidId().getMostSignificantBits()); + entityViewUpdateMsgBuilder.setIdLSB(entityViewMsg.getUuidId().getLeastSignificantBits()); + entityViewUpdateMsgBuilder.setEntity(JacksonUtil.toString(entityViewMsg)); + entityViewUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE); + uplinkMsgBuilder.addEntityViewUpdateMsg(entityViewUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + Assert.assertFalse(edgeImitator.getLatestResponseMsg().getSuccess()); + + loginDifferentTenant(); + EntityView storedView = doGet("/api/entityView/" + otherTenantView.getUuidId(), EntityView.class); + Assert.assertEquals(differentTenantId, storedView.getTenantId()); + Assert.assertEquals("Other tenant EntityView", storedView.getName()); + Assert.assertEquals(otherTenantDevice.getId(), storedView.getEntityId()); + Assert.assertEquals(otherTenantView.getCustomerId(), storedView.getCustomerId()); + Assert.assertEquals(otherTenantView.getOwnerId(), storedView.getOwnerId()); + loginTenantAdmin(); + } + @Test public void testSendUnassignEntityViewFromGroupOnEdgeToCloud() throws Exception { Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); diff --git a/application/src/test/java/org/thingsboard/server/edge/OtaPackageEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/OtaPackageEdgeTest.java index eb856e854a..3be9b81c81 100644 --- a/application/src/test/java/org/thingsboard/server/edge/OtaPackageEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/OtaPackageEdgeTest.java @@ -4,12 +4,12 @@ package org.thingsboard.server.edge; import com.google.protobuf.AbstractMessage; +import org.awaitility.Awaitility; import org.junit.Assert; import org.junit.Test; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.testcontainers.shaded.org.awaitility.Awaitility; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntityType; diff --git a/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java index 031b646b00..c4f4e25942 100644 --- a/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java @@ -390,4 +390,49 @@ public class TelemetryEdgeTest extends AbstractEdgeTest { }); } + @Test + public void testSendEntityGroupAttributesAndTelemetryForGroupOfDifferentTenantToCloud() throws Exception { + loginDifferentTenant(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName("Different Tenant Device Group"); + EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + loginTenantAdmin(); + + EntityDataProto entityData = EntityDataProto.newBuilder() + .setEntityIdMSB(savedEntityGroup.getUuidId().getMostSignificantBits()) + .setEntityIdLSB(savedEntityGroup.getUuidId().getLeastSignificantBits()) + .setEntityType(EntityType.ENTITY_GROUP.name()) + .setAttributesUpdatedMsg(TransportProtos.PostAttributeMsg.newBuilder() + .addKv(TransportProtos.KeyValueProto.newBuilder() + .setKey("groupKey") + .setType(TransportProtos.KeyValueType.STRING_V) + .setStringV("groupValue").build()) + .build()) + .setPostAttributeScope(DataConstants.SERVER_SCOPE) + .setPostTelemetryMsg(TransportProtos.PostTelemetryMsg.newBuilder() + .addTsKvList(TransportProtos.TsKvListProto.newBuilder() + .setTs(System.currentTimeMillis()) + .addKv(TransportProtos.KeyValueProto.newBuilder() + .setKey("groupTemperature") + .setType(TransportProtos.KeyValueType.LONG_V) + .setLongV(25).build()) + .build()) + .build()) + .build(); + sendUplinkMsgAndWaitForResponse(uplinkMsgBuilder -> uplinkMsgBuilder.addEntityData(entityData)); + + loginDifferentTenant(); + String keysUrl = "/api/plugins/telemetry/ENTITY_GROUP/" + savedEntityGroup.getUuidId() + "/keys/"; + Awaitility.await() + .pollDelay(3, TimeUnit.SECONDS) + .atMost(10, TimeUnit.SECONDS) + .untilAsserted(() -> { + List attributeKeys = doGetAsyncTyped(keysUrl + "attributes/" + DataConstants.SERVER_SCOPE, new TypeReference<>() {}); + Assert.assertTrue(attributeKeys.isEmpty()); + List timeseriesKeys = doGetAsyncTyped(keysUrl + "timeseries", new TypeReference<>() {}); + Assert.assertTrue(timeseriesKeys.isEmpty()); + }); + } + } diff --git a/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java index 629e6f9f15..b00b9f5380 100644 --- a/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java @@ -5,11 +5,11 @@ package org.thingsboard.server.edge; import com.fasterxml.jackson.databind.JsonNode; import com.google.protobuf.AbstractMessage; +import org.awaitility.Awaitility; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.testcontainers.shaded.org.awaitility.Awaitility; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EdgeUtils; diff --git a/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java b/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java index d45fdf064d..e74f41f643 100644 --- a/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java @@ -3,6 +3,10 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.install; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -11,6 +15,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; +import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.server.dao.sql.citus.CitusSchemaService; @@ -26,6 +31,7 @@ import org.thingsboard.server.service.install.TsDatabaseSchemaService; import org.thingsboard.server.service.install.update.CacheCleanupService; import org.thingsboard.server.service.install.update.DataUpdateService; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.doThrow; @@ -189,6 +195,34 @@ class ThingsboardInstallServiceTest { verify(databaseEntitiesUpgradeService, never()).upgradeDatabase(anyBoolean()); } + @Test + void anErrorDuringAFreshInstallIsReportedAsAnInstallFailure() throws Exception { + ReflectionTestUtils.setField(installService, "isUpgrade", false); + ExceptionInInitializerError error = new ExceptionInInitializerError("Fontconfig head is null"); + doThrow(error).when(systemDataLoaderService).loadSystemWidgets(); + Logger logger = (Logger) LoggerFactory.getLogger(ThingsboardInstallService.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + assertThatThrownBy(() -> installService.performInstall()) + .isInstanceOf(ThingsboardInstallException.class) + .hasCause(error); + + assertThat(appender.list) + .filteredOn(e -> e.getLevel() == Level.ERROR) + .singleElement() + .satisfies(e -> { + assertThat(e.getFormattedMessage()).isEqualTo("Unexpected error during ThingsBoard installation!"); + assertThat(e.getThrowableProxy().getClassName()).isEqualTo(ExceptionInInitializerError.class.getName()); + assertThat(e.getThrowableProxy().getMessage()).isEqualTo("Fontconfig head is null"); + assertThat(e.getThrowableProxy().getStackTraceElementProxyArray()).isNotEmpty(); + }); + } finally { + logger.detachAppender(appender); + } + } + @Test void postgresToCitusUpgradeFailsWhenCitusSchemaServiceMissing() { ReflectionTestUtils.setField(installService, "isUpgrade", true); diff --git a/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java index 4f48e5c6c2..245760f276 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java @@ -4,6 +4,7 @@ package org.thingsboard.server.service.ai; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import org.springframework.http.HttpStatus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -170,8 +171,9 @@ class DefaultTbAiServiceTest { } @ParameterizedTest - @CsvSource({"400, BAD_REQUEST_PARAMS", "413, BAD_REQUEST_PARAMS", "403, GENERAL", "404, ITEM_NOT_FOUND", - "409, VERSION_CONFLICT", "429, TOO_MANY_REQUESTS", "401, GENERAL", "500, GENERAL", "0, GENERAL"}) + @CsvSource({"400, BAD_REQUEST_PARAMS", "413, BAD_REQUEST_PARAMS", "403, PERMISSION_DENIED", "404, ITEM_NOT_FOUND", + "409, VERSION_CONFLICT", "429, TOO_MANY_REQUESTS", "401, PERMISSION_DENIED", "500, GENERAL", "0, GENERAL", + "502, SERVICE_UNAVAILABLE", "503, SERVICE_UNAVAILABLE", "504, SERVICE_UNAVAILABLE"}) void shouldKeepTheStatusOfTheAiService_whenProcessAndResponseIsFailure(int status, ThingsboardErrorCode errorCode) { // GIVEN given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState()); @@ -189,7 +191,7 @@ class DefaultTbAiServiceTest { void shouldReportCreditsThenThrowGeneral_whenProcessAndResponseIsFailure() { // GIVEN given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState()); - given(call.apply(any())).willReturn(TbAiResponse.builder().success(false).error("Upstream rejected").creditsUsed(42).build()); + given(call.apply(any())).willReturn(TbAiResponse.builder().success(false).status(500).error("Upstream rejected").creditsUsed(42).build()); // WHEN Throwable thrown = catchThrowable(() -> service.process(call, user, true)); @@ -493,12 +495,12 @@ class DefaultTbAiServiceTest { static List upstreamErrors() { return List.of( // PE-side inactivity timeout from the .timeout(...) operator - arguments(new TimeoutException("inactivity"), "Request timed out"), + arguments(new TimeoutException("inactivity"), TbAiOperations.TIMED_OUT_MESSAGE), // the AI channel cannot be opened or closed before the turn started - arguments(new TbAiChannelUnavailableException("Connection refused", null), "Service unavailable"), + arguments(new TbAiChannelUnavailableException("Connection refused", null), TbAiOperations.UNAVAILABLE_MESSAGE), // the channel handshake was refused: the reason phrase is shown - arguments(new TbAiChannelRejectedException("Unauthorized"), "Unauthorized"), - arguments(new TbAiChannelRejectedException("Forbidden"), "Forbidden"), + arguments(new TbAiChannelRejectedException(HttpStatus.UNAUTHORIZED), "Unauthorized"), + arguments(new TbAiChannelRejectedException(HttpStatus.FORBIDDEN), "Forbidden"), // any other unexpected throwable arguments(new RuntimeException("boom"), "Internal error") ); diff --git a/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java index a5606a95bf..1ea3dcd21c 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java @@ -17,6 +17,9 @@ import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChatOperationRequest; import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.cache.limits.RateLimitService; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.transport.TbAiTransport; import org.thingsboard.server.service.ai.transport.TbAiTurnContext; @@ -53,23 +56,25 @@ class DefaultAiChatServiceTest { TbAiOperations operations; @Mock TbAiTransport tbAiTransport; + @Mock + RateLimitService rateLimitService; DefaultAiChatService service; @BeforeEach void setUp() { - service = new DefaultAiChatService(tbAiService, tbAiTransport, operations); + service = new DefaultAiChatService(tbAiService, tbAiTransport, operations, rateLimitService); lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class))) .thenReturn(tbAiResponse); } @Test - void shouldProcessWithoutCreditCheckAndDelegateToClient_whenCreateChatCalled() { + void shouldProcessWithCreditCheckAndDelegateToClient_whenCreateChatCalled() { // GIVEN JsonNode request = createChatRequest("New chat"); UUID chatId = UUID.randomUUID(); JsonNode expectedResponse = TextNode.valueOf(chatId.toString()); - given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse); + given(tbAiService.process(any(), same(user), eq(true))).willReturn(expectedResponse); // WHEN JsonNode result = service.createChat(request, user); @@ -77,7 +82,7 @@ class DefaultAiChatServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(true).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_CREATE.equals(operation.type()) && Objects.equals(new ChatOperationRequest(null, request), operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -94,7 +99,7 @@ class DefaultAiChatServiceTest { service.updateChat(chatId, request, user); // THEN - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_UPDATE.equals(operation.type()) && Objects.equals(new ChatOperationRequest(chatId, request), operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -113,7 +118,7 @@ class DefaultAiChatServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_LIST.equals(operation.type()) && Objects.equals(null, operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -132,7 +137,7 @@ class DefaultAiChatServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_MESSAGES.equals(operation.type()) && Objects.equals(new ChatOperationRequest(chatId, JacksonUtil.newObjectNode().put("toolCards", true)), operation.payload())), same(user), same(tokenProvider)); @@ -149,12 +154,28 @@ class DefaultAiChatServiceTest { service.deleteChat(chatId, user); // THEN - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_DELETE.equals(operation.type()) && Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); } + @Test + void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStopChatCalled() { + // GIVEN + UUID chatId = UUID.randomUUID(); + given(tbAiService.process(any(), same(user), eq(false))).willReturn(null); + + // WHEN + service.stopChat(chatId, user); + + // THEN + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); + then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_STOP.equals(operation.type()) + && Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider)); + then(tbAiService).shouldHaveNoMoreInteractions(); + } + @Test void shouldProcessStreamAndDelegateToTransportWithTurnContext_whenSendChatMessageWithClientContextCalled() { // GIVEN @@ -166,6 +187,9 @@ class DefaultAiChatServiceTest { .event("assistantMessage") .data("{\"message\":\"ok\"}") .build()); + TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + given(user.getTenantId()).willReturn(tenantId); + given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(true); given(tbAiService.processStream(eq(chatId), any(), same(user), any(TbAiTurnLink.class), eq(true))).willReturn(expectedStream); var clientOrigin = "https://tb.example.com"; var expectedContext = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin); @@ -184,6 +208,26 @@ class DefaultAiChatServiceTest { then(tbAiService).shouldHaveNoMoreInteractions(); } + @Test + void shouldAnswerWithRateLimitedError_whenTenantExceedsAiChatRequestsLimit() { + // GIVEN + UUID chatId = UUID.randomUUID(); + TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + given(user.getTenantId()).willReturn(tenantId); + given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(false); + + // WHEN + var events = service.sendChatMessage(chatId, sendMessageBody("And how many assets?", "DEVICE_LIST"), + "tb-access-token", "en-US", "https://tb.example.com", user).collectList().block(); + + // THEN + assertThat(events).hasSize(1); + assertThat(events.get(0).event()).isEqualTo("error"); + assertThat(events.get(0).data()).isEqualTo("{\"message\":\"Rate limit exceeded\",\"code\":\"RATE_LIMITED\"}"); + then(tbAiService).shouldHaveNoInteractions(); + then(tbAiTransport).shouldHaveNoInteractions(); + } + @Test void shouldFollowTheRunningTurnWithoutCreditCheck_whenResumeChatCalled() { // GIVEN @@ -211,9 +255,9 @@ class DefaultAiChatServiceTest { } @SuppressWarnings({"rawtypes", "unchecked"}) - private TbAiService.TbAiCall captureProcessCall() { + private TbAiService.TbAiCall captureProcessCall(boolean checkCredits) { ArgumentCaptor callCaptor = ArgumentCaptor.forClass(TbAiService.TbAiCall.class); - then(tbAiService).should().process(callCaptor.capture(), same(user), eq(false)); + then(tbAiService).should().process(callCaptor.capture(), same(user), eq(checkCredits)); return callCaptor.getValue(); } diff --git a/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java index 723dc0131e..1ca652aff1 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java @@ -22,7 +22,10 @@ import org.thingsboard.ai.common.channel.SolutionStepRequest; import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.data.solution.SolutionStep; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.cache.limits.RateLimitService; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.transport.TbAiOperation; @@ -58,6 +61,10 @@ class DefaultAiSolutionServiceTest { TbAiOperations operations; @Mock SecurityUser user; + @Mock + RateLimitService rateLimitService; + + TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); String clientOrigin = "https://tb.example.com"; @@ -65,16 +72,18 @@ class DefaultAiSolutionServiceTest { @BeforeEach void setUp() { - service = new DefaultAiSolutionService(tbAiService, operations); + service = new DefaultAiSolutionService(tbAiService, operations, rateLimitService); + lenient().when(user.getTenantId()).thenReturn(tenantId); + lenient().when(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).thenReturn(true); lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class))) .thenReturn(tbAiResponse); } @Test - void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStartNewCalled() { + void shouldProcessWithCreditCheckAndDelegateToClient_whenStartNewCalled() { // GIVEN JsonNode expectedResponse = solutionResponse(UUID.randomUUID(), "Energy Monitoring", false, false); - given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse); + given(tbAiService.process(any(), same(user))).willReturn(expectedResponse); // WHEN JsonNode result = service.startNew(user); @@ -82,7 +91,7 @@ class DefaultAiSolutionServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCallWithCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_START.equals(operation.type()) && Objects.equals(null, operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -136,6 +145,20 @@ class DefaultAiSolutionServiceTest { then(tbAiService).shouldHaveNoInteractions(); } + @Test + void shouldRefuseWithTooManyRequestsWithoutCallingTheAiService_whenTheTenantIsOverTheChatRequestsLimit() { + // GIVEN + given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(false); + + // WHEN + Throwable thrown = catchThrowable(() -> service.chat(UUID.randomUUID(), SolutionStep.INITIAL_CONFIGURATION, "Add humidity", List.of(), user)); + + // THEN + assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("Rate limit exceeded"); + assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.TOO_MANY_REQUESTS); + then(tbAiService).shouldHaveNoInteractions(); + } + @ParameterizedTest @EnumSource(SolutionStep.class) void shouldProcessWithCreditCheckAndDelegateToClient_whenChatCalled(SolutionStep step) { @@ -214,6 +237,22 @@ class DefaultAiSolutionServiceTest { then(tbAiService).shouldHaveNoMoreInteractions(); } + @Test + void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStopSolutionCalled() { + // GIVEN + UUID solutionId = UUID.randomUUID(); + given(tbAiService.process(any(), same(user), eq(false))).willReturn(null); + + // WHEN + service.stopSolution(solutionId, user); + + // THEN + assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse); + then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_STOP.equals(operation.type()) + && Objects.equals(new SolutionOperationRequest(solutionId), operation.payload())), same(user), same(tokenProvider)); + then(tbAiService).shouldHaveNoMoreInteractions(); + } + @Test void shouldProcessWithoutCreditCheckAndDelegateToClient_whenInstallSolutionCalled() { // GIVEN diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java index c5771a6b26..3665c2476c 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java @@ -189,7 +189,8 @@ class ChannelTbAiOperationsTest { // THEN assertThat(response.isSuccess()).isFalse(); - assertThat(response.getError()).isEqualTo("Service unavailable"); + assertThat(response.getStatus()).isEqualTo(503); + assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE); assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1); } @@ -239,7 +240,8 @@ class ChannelTbAiOperationsTest { // THEN assertThat(response.isSuccess()).isFalse(); - assertThat(response.getError()).isEqualTo("Service unavailable"); + assertThat(response.getStatus()).isEqualTo(503); + assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE); assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1); assertThat(server.connections.get()).isEqualTo(1); } diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java index a7095f83e3..7635a173e1 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java @@ -72,7 +72,7 @@ class ChannelTbAiTransportTest { assertThat(second).hasSize(3); assertThat(server.connections.get()).isEqualTo(1); ChannelHello hello = server.codec.fromPayload(server.received(ChannelProtocol.HELLO).getFirst().payload(), ChannelHello.class); - assertThat(hello).isEqualTo(new ChannelHello(1, TbAiPooledConnection.CLIENT_CAPABILITIES, "https://tb.example.com", null)); + assertThat(hello).isEqualTo(new ChannelHello(1, List.of("chat.kit"), "https://tb.example.com", null)); ChannelFrame send = server.received(ChannelProtocol.CHAT_SEND).getFirst(); ChatTurnRequest turnRequest = server.codec.fromPayload(send.payload(), ChatTurnRequest.class); assertThat(turnRequest.request()).isEqualTo(request); diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java index 4b5a5e41df..fcf55c4214 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java @@ -7,17 +7,24 @@ import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.client.TbAiHeaders; +import org.thingsboard.ai.common.client.TbAiTokenFactory; +import org.thingsboard.ai.common.data.usage.RateLimitScope; +import org.thingsboard.ai.common.data.usage.RateLimitedApi; +import org.thingsboard.ai.common.data.user.ProfileConfig; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.service.security.model.SecurityUser; +import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -28,6 +35,8 @@ import static org.mockito.Mockito.mock; class TbAiChannelPoolTest { static final String TB_VERSION = "4.4.0"; + static final TbAiTokenFactory TOKEN_FACTORY = new TbAiTokenFactory("test", Base64.getEncoder() + .encodeToString("tb-ai-channel-pool-test-signing-key-".repeat(2).getBytes(StandardCharsets.UTF_8)), Duration.ofMinutes(60)); AtomicLong now = new AtomicLong(1_000_000_000L); FakeTbAiServer server = FakeTbAiServer.start((connection, frame) -> {}); @@ -246,6 +255,68 @@ class TbAiChannelPoolTest { await().atMost(5, TimeUnit.SECONDS).until(() -> pool.pooledConnections() == 0); } + @Test + void shouldRetireIdleChannel_whenTheTokenCarriesOtherLimits() { + // GIVEN + pool = pool(10); + SecurityUser user = user(); + AtomicReference token = new AtomicReference<>(token("10:60", "198.51.100.10")); + TbAiTurnContext context = context(user, token); + TbAiPooledConnection before = join(pool.acquire(context, false)); + before.unreserve(now.get()); + + // WHEN + token.set(token("1:60", "198.51.100.10")); + TbAiPooledConnection after = join(pool.acquire(context, false)); + + // THEN + assertThat(after).isNotSameAs(before); + assertThat(server.connections.get()).isEqualTo(2); + await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1); + } + + @Test + void shouldFinishTheRunningCallOnAStaleChannel_thenCloseIt() { + // GIVEN + pool = pool(10); + AtomicReference token = new AtomicReference<>(token("10:60", "198.51.100.10")); + TbAiTurnContext context = context(user(), token); + TbAiPooledConnection busy = join(pool.acquire(context, false)); + + // WHEN + token.set(token("1:60", "198.51.100.10")); + TbAiPooledConnection next = join(pool.acquire(context, false)); + int openWhileBusy = server.openConnections.get(); + busy.unreserve(now.get()); + + // THEN + assertThat(next).isNotSameAs(busy); + assertThat(openWhileBusy).isEqualTo(2); + await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1); + } + + @Test + void shouldKeepChannel_whenOnlyTheClientAddressChanged() { + // GIVEN + pool = pool(10); + AtomicReference token = new AtomicReference<>(token("10:60", "198.51.100.10")); + TbAiTurnContext context = context(user(), token); + TbAiPooledConnection desktop = join(pool.acquire(context, false)); + desktop.unreserve(now.get()); + + // WHEN + token.set(token("10:60", "203.0.113.20")); + TbAiPooledConnection mobile = join(pool.acquire(context, false)); + mobile.unreserve(now.get()); + token.set(token("10:60", "198.51.100.10")); + TbAiPooledConnection desktopAgain = join(pool.acquire(context, false)); + + // THEN + assertThat(mobile).isSameAs(desktop); + assertThat(desktopAgain).isSameAs(desktop); + assertThat(server.connections.get()).isEqualTo(1); + } + TbAiChannelPool pool(int maxConnections) { return new TbAiChannelPool(server.client(), TB_VERSION, maxConnections, 20, Duration.ofSeconds(60), Duration.ofMinutes(10), now::get, false); } @@ -265,4 +336,14 @@ class TbAiChannelPoolTest { return new TbAiTurnContext(user, null, null, () -> "token", origin); } + static TbAiTurnContext context(SecurityUser user, AtomicReference token) { + return new TbAiTurnContext(user, null, null, token::get, "https://tb.example.com"); + } + + static String token(String chatRequestsLimit, String clientAddress) { + ProfileConfig profileConfig = new ProfileConfig(); + profileConfig.setRateLimits(Map.of(RateLimitedApi.AI_CHAT_REQUESTS, Map.of(RateLimitScope.TENANT, chatRequestsLimit))); + return TOKEN_FACTORY.createToken(UUID.randomUUID().toString(), profileConfig, Map.of("clientAddress", clientAddress)); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java index eb751dba12..c0217ea02f 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.ai.transport; +import org.springframework.http.HttpStatus; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.thingsboard.ai.common.channel.ChannelProtocol; @@ -50,19 +51,21 @@ class TbAiOperationsTest { // THEN assertThat(response.isSuccess()).isFalse(); - assertThat(response.getError()).isEqualTo("Service unavailable"); + assertThat(response.getStatus()).isEqualTo(503); + assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE); } @Test void shouldReturnRejection_whenChannelHandshakeIsRefused() { // GIVEN - given(channel.execute(operation, context)).willThrow(new TbAiChannelRejectedException("Unauthorized")); + given(channel.execute(operation, context)).willThrow(new TbAiChannelRejectedException(HttpStatus.UNAUTHORIZED)); // WHEN TbAiResponse response = operations.execute(operation, context); // THEN assertThat(response.isSuccess()).isFalse(); + assertThat(response.getStatus()).isEqualTo(401); assertThat(response.getError()).isEqualTo("Unauthorized"); } diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java index b77252bf94..028c865290 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java @@ -14,7 +14,6 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import java.time.Duration; -import java.util.List; import java.util.UUID; import java.util.concurrent.TimeoutException; @@ -71,7 +70,7 @@ class TbAiPooledConnectionTest { } @Test - void shouldSendHelloWithoutCapabilities_whenSessionOpens() { + void shouldSendHelloWithItsCapabilities_whenSessionOpens() { // GIVEN TbAiPooledConnection connection = connection(); ChannelSession session = openSession(); @@ -83,12 +82,30 @@ class TbAiPooledConnectionTest { // THEN then(session).should().send(ChannelFrame.of(ChannelProtocol.HELLO, - codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, List.of(), "https://tb.example.com", null)))); + codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, TbAiPooledConnection.CLIENT_CAPABILITIES, "https://tb.example.com", null)))); then(session).should(never()).close(anyInt(), anyString()); assertThat(connection.ready()).isCompletedWithValue(connection); assertThat(connection.maxFrameBytes()).isEqualTo(1024); } + @Test + void shouldBeStale_whenTheCallerHoldsOtherLimits() { + // GIVEN + TbAiPooledConnection connection = connection(); + connection.handshakeLimits("limits-before-the-profile-change"); + + // WHEN-THEN + assertThat(connection.isStaleFor("limits-after-the-profile-change")).isTrue(); + assertThat(connection.isStaleFor("limits-before-the-profile-change")).isFalse(); + assertThat(connection.isStaleFor(null)).isFalse(); + } + + @Test + void shouldNotBeStale_whenItsHandshakeLimitsAreUnknown() { + // WHEN-THEN + assertThat(connection().isStaleFor("any-limits")).isFalse(); + } + TbAiPooledConnection connection() { return new TbAiPooledConnection(key, "https://tb.example.com", false, 20, codec, pool, System.nanoTime()); } diff --git a/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/GeofencingValueArgumentEntryTest.java b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/GeofencingValueArgumentEntryTest.java index eb9fe521f3..1f51ed9e25 100644 --- a/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/GeofencingValueArgumentEntryTest.java +++ b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/GeofencingValueArgumentEntryTest.java @@ -1,13 +1,14 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.cf.ctx.state; -import io.hypersistence.utils.hibernate.type.json.internal.JacksonUtil; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.geo.PerimeterDefinition; import org.thingsboard.server.common.data.id.AssetId; import org.thingsboard.server.common.data.id.EntityId; diff --git a/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java b/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java index 208c4ae00e..e509d2666d 100644 --- a/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java @@ -2105,6 +2105,7 @@ public class EntityServiceTest extends AbstractControllerTest { entityView.setCustomerId(customerId); entityView.setName("test"); entityView.setType("default"); + entityView.setEntityId(deviceId); customerEntityIds.add(entityViewService.saveEntityView(entityView).getId()); EntityGroup entityGroup = new EntityGroup(); @@ -3876,12 +3877,18 @@ public class EntityServiceTest extends AbstractControllerTest { @Test public void testEntityViewEntityMapping() { + Device device = new Device(); + device.setTenantId(tenantId); + device.setName("Device for entity view"); + device.setType("default"); + device = deviceService.saveDevice(device); + EntityView entityView = new EntityView(); entityView.setTenantId(tenantId); entityView.setCustomerId(customerId); entityView.setName("test"); entityView.setType("default"); - entityView.setEntityId(new DeviceId(UUID.randomUUID())); + entityView.setEntityId(device.getId()); entityView.setKeys(new TelemetryEntityView(List.of("test"), null)); entityView.setStartTimeMs(124); entityView.setEndTimeMs(256); @@ -3913,12 +3920,18 @@ public class EntityServiceTest extends AbstractControllerTest { @Test public void testFindEntitiesWithEntityViewFilter() { + Device device = new Device(); + device.setTenantId(tenantId); + device.setName("Device for entity view"); + device.setType("default"); + device = deviceService.saveDevice(device); + EntityView entityView = new EntityView(); entityView.setTenantId(tenantId); entityView.setCustomerId(customerId); entityView.setName("test"); entityView.setType("default"); - entityView.setEntityId(new DeviceId(UUID.randomUUID())); + entityView.setEntityId(device.getId()); entityView.setKeys(new TelemetryEntityView(List.of("test"), null)); entityView.setStartTimeMs(124); entityView.setEndTimeMs(256); diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java index bbdb95c466..0d557be89b 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java @@ -57,9 +57,9 @@ public class MigrationIntegrationTest extends AbstractControllerTest { private static final String SCHEMA_UPDATE_SQL = "schema_update.sql"; // Versions with a registered bean but no schema_update.sql, because their whole change is programmatic: - // 4.3.1.5 rewrites one JSON column through the DAO. Entries here opt out of the dir/bean check below, + // 4.3.1.5 rewrites one JSON column through the DAO, 4.4.2.0 adds a notification template. Entries here opt out of the dir/bean check below, // so add one only when the version genuinely ships no SQL. - private static final Set SQL_LESS_ALLOWED = Set.of("4.3.1.5"); + private static final Set SQL_LESS_ALLOWED = Set.of("4.3.1.5", "4.4.2.0"); @Autowired private MigrationService migrationService; diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java new file mode 100644 index 0000000000..37dc7bd57e --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.install.lts; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.notification.NotificationType; +import org.thingsboard.server.dao.notification.DefaultNotifications; +import org.thingsboard.server.dao.notification.NotificationSettingsService; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class V4_4_2_0MigrationTest { + + @Mock + private NotificationSettingsService notificationSettingsService; + @Mock + private DefaultNotifications defaultNotifications; + + @InjectMocks + private V4_4_2_0Migration migration; + + @Test + void hasItsVersion() { + assertEquals("4.4.2.0", migration.getVersion()); + } + + @Test + void createsAiCreditsLimitIncreaseRequestTemplateWhenMissing() { + when(notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) + .thenReturn(false); + + migration.apply(); + + verify(defaultNotifications).create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest); + } + + @Test + void keepsAiCreditsLimitIncreaseRequestTemplateWhenPresent() { + when(notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) + .thenReturn(true); + + migration.apply(); + + verify(defaultNotifications, never()).create(any(), any()); + } +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java b/application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java new file mode 100644 index 0000000000..f939680b3f --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.install.update; + +import org.junit.jupiter.api.Test; +import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.group.EntityGroup; +import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.dao.customer.CustomerService; +import org.thingsboard.server.dao.entityview.EntityViewService; +import org.thingsboard.server.dao.group.EntityGroupService; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +class EntityViewGroupAllUpdaterTest { + + @Test + void testUnassignFromCustomerSavesWithoutValidation() { + EntityViewService entityViewService = mock(EntityViewService.class); + EntityViewGroupAllUpdater updater = new EntityViewGroupAllUpdater(entityViewService, mock(CustomerService.class), + mock(EntityGroupService.class), new EntityGroup(), true); + EntityView entityView = new EntityView(); + entityView.setCustomerId(new CustomerId(UUID.randomUUID())); + + updater.unassignFromCustomer(entityView); + + verify(entityViewService).saveEntityView(entityView, false); + assertThat(entityView.getCustomerId().isNullUid()).isTrue(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/integration/DefaultPlatformIntegrationServiceTest.java b/application/src/test/java/org/thingsboard/server/service/integration/DefaultPlatformIntegrationServiceTest.java index 9e25bd44c9..83f55e632b 100644 --- a/application/src/test/java/org/thingsboard/server/service/integration/DefaultPlatformIntegrationServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/integration/DefaultPlatformIntegrationServiceTest.java @@ -2,6 +2,8 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.integration; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -11,25 +13,44 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.integration.api.IntegrationCallback; +import org.thingsboard.integration.api.converter.DedicatedConverterConfig; +import org.thingsboard.integration.api.converter.DedicatedConverterUtil; +import org.thingsboard.integration.api.converter.DedicatedUplinkData; +import org.thingsboard.integration.api.converter.wrapper.ThingsStackConverterUnwrapper; +import org.thingsboard.integration.api.data.ContentType; +import org.thingsboard.integration.api.data.UplinkMetaData; +import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.id.AssetId; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.integration.AbstractIntegration; +import org.thingsboard.server.common.data.kv.DataType; +import org.thingsboard.server.common.data.kv.KvEntry; +import org.thingsboard.server.common.data.msg.TbMsgType; import org.thingsboard.server.common.data.relation.EntityRelation; import org.thingsboard.server.common.msg.TbMsg; +import org.thingsboard.server.common.msg.TbMsgMetaData; import org.thingsboard.server.common.msg.queue.TbCallback; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.relation.RelationService; import org.thingsboard.server.exception.ThingsboardRuntimeException; +import org.thingsboard.server.gen.integration.AssetUplinkDataProto; +import org.thingsboard.server.gen.integration.DeviceUplinkDataProto; import org.thingsboard.server.gen.transport.TransportProtos.DeviceActivityProto; +import org.thingsboard.server.gen.transport.TransportProtos.KeyValueProto; +import org.thingsboard.server.gen.transport.TransportProtos.KeyValueType; +import org.thingsboard.server.gen.transport.TransportProtos.PostTelemetryMsg; import org.thingsboard.server.gen.transport.TransportProtos.ToRuleEngineMsg; import org.thingsboard.server.queue.TbQueueCallback; import org.thingsboard.server.queue.TbQueueProducer; @@ -38,15 +59,22 @@ import org.thingsboard.server.queue.common.TbRuleEngineProducerService; import org.thingsboard.server.service.profile.DefaultTbAssetProfileCache; import org.thingsboard.server.service.profile.DefaultTbDeviceProfileCache; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutorService; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -484,4 +512,220 @@ public class DefaultPlatformIntegrationServiceTest { verify(customerService).saveCustomer(any(Customer.class)); } + @Test + public void whenDeviceUplinkFromTypedConverter_thenStringIdentifiersStayStringsAfterRuleNodeParsing() throws Exception { + AbstractIntegration integration = mock(AbstractIntegration.class); + when(integration.getTenantId()).thenReturn(TENANT_ID); + when(integration.getId()).thenReturn(new IntegrationId(UUID.randomUUID())); + Device device = new Device(); + device.setId(DEVICE_ID); + device.setTenantId(TENANT_ID); + device.setName("ttn-device"); + device.setType("default"); + device.setDeviceProfileId(new DeviceProfileId(UUID.randomUUID())); + when(deviceService.findDeviceByTenantIdAndName(TENANT_ID, device.getName())).thenReturn(device); + doAnswer(_ -> null).when(service).onActivity(any(), any(), anyLong()); + + DedicatedUplinkData uplink = parseThingsStackUplink(); + DeviceUplinkDataProto data = DeviceUplinkDataProto.newBuilder() + .setDeviceName(device.getName()) + .setDeviceType(device.getType()) + .setPostTelemetryMsg(JsonConverter.convertToTelemetryProto(uplink.getTelemetryJson(), uplink.getTelemetryTypeCastDisabledKeys())) + .setPostAttributesMsg(JsonConverter.convertToAttributesProto(uplink.getAttributesJson(), uplink.getAttributesTypeCastDisabledKeys())) + .addAllTelemetryTypeCastDisabledKeys(uplink.getTelemetryTypeCastDisabledKeys()) + .addAllAttributesTypeCastDisabledKeys(uplink.getAttributesTypeCastDisabledKeys()) + .build(); + + service.processUplinkData(integration, data, mock(IntegrationCallback.class)).run(); + + assertThingsStackUplinkTypes(captureRuleEngineMsgs()); + } + + @Test + public void whenAssetUplinkFromTypedConverter_thenStringIdentifiersStayStringsAfterRuleNodeParsing() throws Exception { + AbstractIntegration integration = mock(AbstractIntegration.class); + when(integration.getTenantId()).thenReturn(TENANT_ID); + Asset asset = new Asset(); + asset.setId(ASSET_ID); + asset.setTenantId(TENANT_ID); + asset.setName("ttn-asset"); + asset.setType("default"); + when(assetService.findAssetByTenantIdAndName(TENANT_ID, asset.getName())).thenReturn(asset); + + DedicatedUplinkData uplink = parseThingsStackUplink(); + AssetUplinkDataProto data = AssetUplinkDataProto.newBuilder() + .setAssetName(asset.getName()) + .setAssetType(asset.getType()) + .setPostTelemetryMsg(JsonConverter.convertToTelemetryProto(uplink.getTelemetryJson(), uplink.getTelemetryTypeCastDisabledKeys())) + .setPostAttributesMsg(JsonConverter.convertToAttributesProto(uplink.getAttributesJson(), uplink.getAttributesTypeCastDisabledKeys())) + .addAllTelemetryTypeCastDisabledKeys(uplink.getTelemetryTypeCastDisabledKeys()) + .addAllAttributesTypeCastDisabledKeys(uplink.getAttributesTypeCastDisabledKeys()) + .build(); + + service.processUplinkData(integration, data, mock(IntegrationCallback.class)).run(); + + assertThingsStackUplinkTypes(captureRuleEngineMsgs()); + } + + @Test + public void whenUplinkHasNoKeptStrings_thenTypeCastDisabledKeysMetadataIsNotAdded() { + AbstractIntegration integration = mock(AbstractIntegration.class); + when(integration.getTenantId()).thenReturn(TENANT_ID); + when(integration.getId()).thenReturn(new IntegrationId(UUID.randomUUID())); + Device device = new Device(); + device.setId(DEVICE_ID); + device.setTenantId(TENANT_ID); + device.setName("http-device"); + device.setType("default"); + device.setDeviceProfileId(new DeviceProfileId(UUID.randomUUID())); + when(deviceService.findDeviceByTenantIdAndName(TENANT_ID, device.getName())).thenReturn(device); + doAnswer(_ -> null).when(service).onActivity(any(), any(), anyLong()); + + DeviceUplinkDataProto data = DeviceUplinkDataProto.newBuilder() + .setDeviceName(device.getName()) + .setDeviceType(device.getType()) + .setPostAttributesMsg(JsonConverter.convertToAttributesProto(JsonParser.parseString("{\"devAddr\": \"01020304\", \"model\": \"x1\"}"))) + .build(); + + service.processUplinkData(integration, data, mock(IntegrationCallback.class)).run(); + + List msgs = captureRuleEngineMsgs(); + assertThat(msgs).hasSize(1); + assertThat(msgs.get(0).getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isNull(); + } + + @Test + public void whenDecoderSendsLongDecimal_thenItIsNotMarkedAndIsSavedAsNumber() throws Exception { + AbstractIntegration integration = mock(AbstractIntegration.class); + when(integration.getTenantId()).thenReturn(TENANT_ID); + when(integration.getId()).thenReturn(new IntegrationId(UUID.randomUUID())); + Device device = new Device(); + device.setId(DEVICE_ID); + device.setTenantId(TENANT_ID); + device.setName("ttn-device"); + device.setType("default"); + device.setDeviceProfileId(new DeviceProfileId(UUID.randomUUID())); + when(deviceService.findDeviceByTenantIdAndName(TENANT_ID, device.getName())).thenReturn(device); + doAnswer(_ -> null).when(service).onActivity(any(), any(), anyLong()); + + DedicatedUplinkData uplink = parseThingsStackUplink(); + PostTelemetryMsg telemetry = JsonConverter.convertToTelemetryProto(uplink.getTelemetryJson(), uplink.getTelemetryTypeCastDisabledKeys()); + // The proto parser keeps a decimal with more than 16 fraction digits as a string. + assertThat(telemetry.getTsKvList(0).getKvList()) + .filteredOn(kv -> kv.getKey().equals("pressure")) + .extracting(KeyValueProto::getType, KeyValueProto::getStringV) + .containsExactly(tuple(KeyValueType.STRING_V, "21.50000000000000000000")); + DeviceUplinkDataProto data = DeviceUplinkDataProto.newBuilder() + .setDeviceName(device.getName()) + .setDeviceType(device.getType()) + .setPostTelemetryMsg(telemetry) + .setPostAttributesMsg(JsonConverter.convertToAttributesProto(uplink.getAttributesJson(), uplink.getAttributesTypeCastDisabledKeys())) + .addAllTelemetryTypeCastDisabledKeys(uplink.getTelemetryTypeCastDisabledKeys()) + .addAllAttributesTypeCastDisabledKeys(uplink.getAttributesTypeCastDisabledKeys()) + .build(); + + service.processUplinkData(integration, data, mock(IntegrationCallback.class)).run(); + + List msgs = captureRuleEngineMsgs(); + TbMsg telemetryMsg = msgs.stream().filter(msg -> msg.isTypeOf(TbMsgType.POST_TELEMETRY_REQUEST)).findFirst().orElseThrow(); + TbMsg attributesMsg = msgs.stream().filter(msg -> msg.isTypeOf(TbMsgType.POST_ATTRIBUTES_REQUEST)).findFirst().orElseThrow(); + assertThat(telemetryMsg.getTypeCastDisabledKeys()).containsExactlyInAnyOrder("devAddr"); + assertThat(attributesMsg.getTypeCastDisabledKeys()).containsExactlyInAnyOrder("eui", "joinEui", "hardwareVersion", "firmwareVersion"); + assertThingsStackUplinkTypes(msgs); + } + + @Test + public void whenRemoteIntegrationSendsNoKeys_thenTypeCastDisabledKeysMetadataIsNotAdded() throws Exception { + AbstractIntegration integration = mock(AbstractIntegration.class); + when(integration.getTenantId()).thenReturn(TENANT_ID); + when(integration.getId()).thenReturn(new IntegrationId(UUID.randomUUID())); + Device device = new Device(); + device.setId(DEVICE_ID); + device.setTenantId(TENANT_ID); + device.setName("old-remote-device"); + device.setType("default"); + device.setDeviceProfileId(new DeviceProfileId(UUID.randomUUID())); + when(deviceService.findDeviceByTenantIdAndName(TENANT_ID, device.getName())).thenReturn(device); + doAnswer(_ -> null).when(service).onActivity(any(), any(), anyLong()); + + // An older remote integration builds the same protos without the type-cast-disabled key fields. + DedicatedUplinkData uplink = parseThingsStackUplink(); + DeviceUplinkDataProto data = DeviceUplinkDataProto.newBuilder() + .setDeviceName(device.getName()) + .setDeviceType(device.getType()) + .setPostTelemetryMsg(JsonConverter.convertToTelemetryProto(uplink.getTelemetryJson(), uplink.getTelemetryTypeCastDisabledKeys())) + .setPostAttributesMsg(JsonConverter.convertToAttributesProto(uplink.getAttributesJson(), uplink.getAttributesTypeCastDisabledKeys())) + .build(); + + service.processUplinkData(integration, data, mock(IntegrationCallback.class)).run(); + + List msgs = captureRuleEngineMsgs(); + assertThat(msgs).hasSize(2); + assertThat(msgs).allSatisfy(msg -> assertThat(msg.getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isNull()); + } + + // What the typed TTN converter produces: unwrapped event keys plus the decoder output + // {"telemetry": {"temperature": "22.5", "pressure": 21.50000000000000000000}}. + private static DedicatedUplinkData parseThingsStackUplink() throws Exception { + String payload = """ + { + "end_device_ids": { + "device_id": "ttn-device", + "application_ids": {"application_id": "test-app"}, + "dev_eui": "70B3D57ED0000001", + "join_eui": "0000000000000000", + "dev_addr": "01020304" + }, + "received_at": "2026-11-17T09:46:05.447941836Z", + "uplink_message": { + "f_port": 1, + "f_cnt": 101, + "frm_payload": "AgI7AAMANwJxDGA=", + "decoded_payload": {"temperature": "22.5"}, + "version_ids": {"brand_id": "acme", "model_id": "sensor", "hardware_version": "1.0", "firmware_version": "1.01", "band_id": "EU_863_870"}, + "rx_metadata": [{"gateway_ids": {"gateway_id": "gw"}, "rssi": -22, "channel_rssi": -22, "snr": 11}], + "settings": {"data_rate": {"lora": {"bandwidth": 125000, "spreading_factor": 11}}, "frequency": "867700000"} + } + } + """; + ThingsStackConverterUnwrapper unwrapper = new ThingsStackConverterUnwrapper(); + UplinkMetaData metadata = unwrapper.unwrap(payload.getBytes(StandardCharsets.UTF_8), new UplinkMetaData<>(ContentType.JSON, Map.of())).getSecond(); + + DedicatedConverterConfig config = new DedicatedConverterConfig(); + config.setType(EntityType.DEVICE); + config.setName("Device $eui"); + config.setAttributes(Set.of("eui", "joinEui", "hardwareVersion", "firmwareVersion")); + config.setTelemetry(Set.of("devAddr", "fCnt")); + + JsonObject decoded = JsonParser.parseString("{\"telemetry\": {\"temperature\": \"22.5\", \"pressure\": 21.50000000000000000000}}").getAsJsonObject(); + return DedicatedConverterUtil.parseUplinkData(config, decoded, metadata, unwrapper.getKeys()); + } + + private List captureRuleEngineMsgs() { + ArgumentCaptor msgCaptor = ArgumentCaptor.forClass(TbMsg.class); + verify(ruleEngineProducerService, atLeastOnce()).sendToRuleEngine(eq(integrationRuleEngineMsgProducer), eq(TENANT_ID), msgCaptor.capture(), any(TbQueueCallback.class)); + return msgCaptor.getAllValues(); + } + + // Parses each message the way the save attributes / save time series nodes do. + private static void assertThingsStackUplinkTypes(List msgs) { + Map kvs = new HashMap<>(); + for (TbMsg msg : msgs) { + if (msg.isTypeOf(TbMsgType.POST_ATTRIBUTES_REQUEST)) { + JsonConverter.attributesFromMsg(msg).forEach(kv -> kvs.put(kv.getKey(), kv)); + } else { + JsonConverter.telemetryFromMsg(msg, 0L).values().forEach(list -> list.forEach(kv -> kvs.put(kv.getKey(), kv))); + } + } + assertThat(kvs.values()).extracting(KvEntry::getKey, KvEntry::getDataType, KvEntry::getValue).containsExactlyInAnyOrder( + tuple("eui", DataType.STRING, "70B3D57ED0000001"), + tuple("joinEui", DataType.STRING, "0000000000000000"), + tuple("hardwareVersion", DataType.STRING, "1.0"), + tuple("firmwareVersion", DataType.STRING, "1.01"), + tuple("devAddr", DataType.STRING, "01020304"), + tuple("fCnt", DataType.LONG, 101L), + tuple("temperature", DataType.DOUBLE, 22.5), + tuple("pressure", DataType.DOUBLE, 21.5)); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/integration/IntegrationActivityManagerTest.java b/application/src/test/java/org/thingsboard/server/service/integration/IntegrationActivityManagerTest.java index e729826633..9deef281ac 100644 --- a/application/src/test/java/org/thingsboard/server/service/integration/IntegrationActivityManagerTest.java +++ b/application/src/test/java/org/thingsboard/server/service/integration/IntegrationActivityManagerTest.java @@ -697,7 +697,7 @@ public class IntegrationActivityManagerTest { IntegrationCallback callbackMock = mock(IntegrationCallback.class); doCallRealMethod().when(integrationServiceMock).processUplinkData(eq(integration), any(UUID.class), eq(uplinkDataProto), eq(callbackMock)); - doCallRealMethod().when(integrationServiceMock).process(any(), eq(uplinkDataProto.getPostTelemetryMsg()), any()); + doCallRealMethod().when(integrationServiceMock).process(any(), eq(uplinkDataProto.getPostTelemetryMsg()), any(), any()); long expectedTime = 123L; when(integrationServiceMock.getCurrentTimeMillis()).thenReturn(expectedTime); @@ -734,7 +734,7 @@ public class IntegrationActivityManagerTest { .setPostAttributesMsg(postAttributeMsg).build(); doCallRealMethod().when(integrationServiceMock).processUplinkData(eq(integration), any(UUID.class), eq(uplinkDataProto), isNull()); - doCallRealMethod().when(integrationServiceMock).process(any(), eq(uplinkDataProto.getPostAttributesMsg()), isNull()); + doCallRealMethod().when(integrationServiceMock).process(any(), eq(uplinkDataProto.getPostAttributesMsg()), any(), isNull()); long expectedTime = 123L; when(integrationServiceMock.getCurrentTimeMillis()).thenReturn(expectedTime); diff --git a/application/src/test/java/org/thingsboard/server/service/integration/TypedConverterUplinkTypesTest.java b/application/src/test/java/org/thingsboard/server/service/integration/TypedConverterUplinkTypesTest.java new file mode 100644 index 0000000000..acf6960825 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/integration/TypedConverterUplinkTypesTest.java @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.integration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.After; +import org.junit.Test; +import org.springframework.test.context.TestPropertySource; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.converter.Converter; +import org.thingsboard.server.common.data.converter.ConverterType; +import org.thingsboard.server.common.data.debug.DebugSettings; +import org.thingsboard.server.common.data.integration.IntegrationType; +import org.thingsboard.server.dao.service.DaoSqlTest; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * An uplink through a typed (version 2) LoRaWAN converter and the default root rule chain: + * identifiers the network server sends as strings are saved as strings, decoder output is still cast. + */ +@TestPropertySource(properties = { + "js.evaluator=local", + "service.integrations.supported=ALL" +}) +@DaoSqlTest +public class TypedConverterUplinkTypesTest extends AbstractIntegrationTest { + + private static final String EUI = "1000000000000001"; + private static final String DEV_ADDR = "01020304"; + + private static final String DECODER = """ + var data = JSON.parse(String.fromCharCode.apply(String, payload)); + return {attributes: {}, telemetry: {temperature: data.temperature}}; + """; + + @After + public void afterTest() throws Exception { + if (integration != null) { + disableIntegration(); + removeIntegration(integration); + } + } + + @Override + protected JsonNode createIntegrationClientConfiguration() { + return JacksonUtil.newObjectNode(); + } + + @Test + public void givenChirpStackUplink_whenSaved_thenStringIdentifiersStayStrings() throws Exception { + loginTenantAdmin(); + createTypedConverter(); + createIntegration("Typed ChirpStack integration", IntegrationType.CHIRPSTACK); + enableIntegration(); + waitUntilIntegrationStarted(tenantId, integration.getId()); + + doPost("/api/v1/integrations/chirpstack/{routingKey}", chirpStackUplink(), integration.getRoutingKey()).andExpect(status().isOk()); + + String deviceName = "Device " + EUI; + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> + doGet("/api/tenant/devices?deviceName={name}", deviceName).andReturn().getResponse().getStatus() == 200); + Device device = doGet("/api/tenant/devices?deviceName={name}", Device.class, deviceName); + + String attributesUrl = "/api/plugins/telemetry/DEVICE/" + device.getUuidId() + "/values/attributes/CLIENT_SCOPE?keys=eui,devAddr"; + Map attributes = new HashMap<>(); + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> { + attributes.clear(); + doGetAsync(attributesUrl, JsonNode.class).forEach(kv -> attributes.put(kv.get("key").asText(), kv.get("value"))); + return attributes.size() == 2; + }); + assertThat(attributes.get("eui").isTextual()).as("eui is a string: %s", attributes.get("eui")).isTrue(); + assertThat(attributes.get("eui").asText()).isEqualTo(EUI); + assertThat(attributes.get("devAddr").isTextual()).as("devAddr is a string: %s", attributes.get("devAddr")).isTrue(); + assertThat(attributes.get("devAddr").asText()).isEqualTo(DEV_ADDR); + + String telemetryUrl = "/api/plugins/telemetry/DEVICE/" + device.getUuidId() + "/values/timeseries?keys=fCnt,temperature&useStrictDataTypes=true"; + Map telemetry = new HashMap<>(); + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> { + telemetry.clear(); + JsonNode latest = doGetAsync(telemetryUrl, JsonNode.class); + for (String key : List.of("fCnt", "temperature")) { + if (latest.has(key) && !latest.get(key).isEmpty()) { + telemetry.put(key, latest.get(key).get(0).get("value")); + } + } + return telemetry.size() == 2; + }); + assertThat(telemetry.get("fCnt").isIntegralNumber()).as("fCnt is a number: %s", telemetry.get("fCnt")).isTrue(); + assertThat(telemetry.get("fCnt").asLong()).isEqualTo(10L); + // The decoder returns "22.5" as a string; the usual type cast still applies to it. + assertThat(telemetry.get("temperature").isNumber()).as("temperature is a number: %s", telemetry.get("temperature")).isTrue(); + assertThat(telemetry.get("temperature").asDouble()).isEqualTo(22.5); + } + + private void createTypedConverter() { + ObjectNode configuration = JacksonUtil.newObjectNode(); + configuration.put("type", "DEVICE"); + configuration.put("name", "Device $eui"); + configuration.put("profile", "default"); + configuration.set("attributes", JacksonUtil.toJsonNode("[\"eui\", \"devAddr\"]")); + configuration.set("telemetry", JacksonUtil.toJsonNode("[\"fCnt\"]")); + configuration.put("scriptLang", "JS"); + configuration.put("decoder", DECODER); + + Converter converter = new Converter(); + converter.setTenantId(tenantId); + converter.setName("Typed ChirpStack converter"); + converter.setType(ConverterType.UPLINK); + converter.setIntegrationType(IntegrationType.CHIRPSTACK); + converter.setConverterVersion(2); + converter.setConfiguration(configuration); + converter.setDebugSettings(DebugSettings.all()); + uplinkConverter = doPost("/api/converter", converter, Converter.class); + } + + private static JsonNode chirpStackUplink() { + return JacksonUtil.toJsonNode(""" + { + "deduplicationId": "3ac7e3c4-4401-4b8d-9386-a5c902f9202d", + "time": "2026-11-17T09:34:15.775023242+00:00", + "deviceInfo": { + "tenantId": "52f14cd4-c6f1-4fbd-8f87-4025e1d49242", + "tenantName": "ChirpStack", + "applicationId": "17c82e96-be03-4f38-aef3-f83d48582d97", + "applicationName": "Test application", + "deviceProfileId": "14855bf7-d10d-4aee-b618-ebfcb64dc7ad", + "deviceProfileName": "default", + "deviceName": "Chirpstack", + "devEui": "%s" + }, + "devAddr": "%s", + "dr": 1, + "fCnt": 10, + "fPort": 80, + "object": {"temperature": "22.5"}, + "rxInfo": [{"uplinkId": 1, "rssi": -22, "snr": 10.5}], + "txInfo": {"frequency": 867100000, "modulation": {"lora": {"bandwidth": 125000, "spreadingFactor": 11, "codeRate": "CR_4_5"}}} + } + """.formatted(EUI, DEV_ADDR)); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/integration/template/IntegrationPackageExportServiceTest.java b/application/src/test/java/org/thingsboard/server/service/integration/template/IntegrationPackageExportServiceTest.java index 664733f426..6b6b61a381 100644 --- a/application/src/test/java/org/thingsboard/server/service/integration/template/IntegrationPackageExportServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/integration/template/IntegrationPackageExportServiceTest.java @@ -816,6 +816,11 @@ class IntegrationPackageExportServiceTest { assertThat(entry.get("secretSupport")).isEqualTo(true); assertThat(entry.get("defaultValue")).isEqualTo(""); } + + assertThat(result.formEntries()).filteredOn(e -> "tuyaAccessId".equals(e.get("key"))) + .extracting(e -> e.get("label")).containsExactly("Access ID"); + assertThat(result.formEntries()).filteredOn(e -> "tuyaAccessKey".equals(e.get("key"))) + .extracting(e -> e.get("label")).containsExactly("Access Secret"); } @Test diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java similarity index 58% rename from application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java rename to application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java index 38595a0c71..a53d9f8dff 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java @@ -8,6 +8,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -16,12 +17,17 @@ import org.mockito.quality.Strictness; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.client.RestClientException; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.HasName; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.debug.DebugSettings; import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; @@ -30,23 +36,30 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode; +import org.thingsboard.server.common.data.subscription.SubscriptionEntry; import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.dao.converter.ConverterService; +import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.device.DeviceCredentialsService; import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.entity.EntityService; +import org.thingsboard.server.dao.group.EntityGroupService; import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.subscription.PlatformFeature; @@ -54,28 +67,35 @@ import org.thingsboard.server.dao.subscription.SubscriptionService; import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.service.entitiy.TbLogEntityActionService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; +import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; +import org.thingsboard.server.exception.EntitiesLimitExceededException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.ExecutionException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) -class DefaultDevicePackageUpdateServiceTest { +class DefaultDevicePackageServiceTest { private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); private final SecurityUser user = mock(SecurityUser.class); @@ -119,18 +139,30 @@ class DefaultDevicePackageUpdateServiceTest { private TelemetrySubscriptionService telemetryService; @Mock private IotHubService iotHubService; + @Mock + private ProjectInfo projectInfo; + @Mock + private CustomerService customerService; + @Mock + private EntityGroupService entityGroupService; @InjectMocks - private DefaultDevicePackageUpdateService service; + private DefaultDevicePackageService service; private IotHubInstalledItem installedItem; // Set when the transaction callback threw, so the transaction would roll back private final List rolledBack = new ArrayList<>(); + private boolean inTransaction; + private final List savedInTransaction = new ArrayList<>(); + // What must run after commit: the audit log, the Hub install report and the attributes, each marked if it ran inside + private final List afterCommitCalls = new ArrayList<>(); @BeforeEach void setUp() { ReflectionTestUtils.setField(service, "entityService", entityService); ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService); + ReflectionTestUtils.setField(service, "customerService", customerService); + ReflectionTestUtils.setField(service, "entityGroupService", entityGroupService); when(user.getTenantId()).thenReturn(tenantId); DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); @@ -158,11 +190,14 @@ class DefaultDevicePackageUpdateServiceTest { when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo); when(transactionTemplate.execute(any())).thenAnswer(invocation -> { + inTransaction = true; try { return invocation.>getArgument(0).doInTransaction(null); } catch (RuntimeException e) { rolledBack.add(e); throw e; + } finally { + inTransaction = false; } }); when(packageEntities.checksum(any(), any())).thenReturn("checksum"); @@ -184,7 +219,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "milesight-iot-am308").put("description", "new")), keep("AM308", "DEVICE", deviceId), overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "Template title")))); @@ -218,10 +253,10 @@ class DefaultDevicePackageUpdateServiceTest { dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); + DevicePackageRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -237,10 +272,10 @@ class DefaultDevicePackageUpdateServiceTest { dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId); overview.setId("main-dashboard"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(overview)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(overview)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -256,7 +291,7 @@ class DefaultDevicePackageUpdateServiceTest { ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -266,10 +301,10 @@ class DefaultDevicePackageUpdateServiceTest { @Test void useExistingOfAPackageEntity_staysThePackages() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -282,10 +317,10 @@ class DefaultDevicePackageUpdateServiceTest { // At install the user picked their own dashboard: the install adds it to createdEntityIds too ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -295,9 +330,9 @@ class DefaultDevicePackageUpdateServiceTest { @Test void overwritingAnEntityUsedAtInstall_needsAConfirmation() { ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -308,7 +343,7 @@ class DefaultDevicePackageUpdateServiceTest { Dashboard shared = dashboard(9L); DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null); when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot); - when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0)); + when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0, List.of())); // This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it"); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own)); @@ -327,10 +362,10 @@ class DefaultDevicePackageUpdateServiceTest { // v2 dropped the dashboard step: the install state no longer has it, createdEntityIds does ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of()); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -343,9 +378,9 @@ class DefaultDevicePackageUpdateServiceTest { DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); installed.setUsedExistingEntityIds(List.of(dashboardId)); installed.setInstallState(Map.of()); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -358,7 +393,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); when(entityService.fetchEntity(any(), any())).thenReturn(Optional.of(dashboard(9L))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isTrue(); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId); @@ -377,13 +412,13 @@ class DefaultDevicePackageUpdateServiceTest { current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId); step.setResolution("use-existing"); ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"); entries.putNull("profile.milesight-iot-am308"); step.setMetadata(entries); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); ArgumentCaptor saved = ArgumentCaptor.forClass(Integration.class); @@ -411,7 +446,7 @@ class DefaultDevicePackageUpdateServiceTest { integration.setId(integrationId); when(entityService.fetchEntity(tenantId, integrationId)).thenReturn(Optional.of(integration)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -438,11 +473,11 @@ class DefaultDevicePackageUpdateServiceTest { current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, tenantsIntegrationId)).thenReturn(current); when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId); step.setResolution("use-existing"); step.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -465,10 +500,10 @@ class DefaultDevicePackageUpdateServiceTest { configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId); step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); verify(integrationService, never()).saveIntegration(any()); @@ -476,12 +511,12 @@ class DefaultDevicePackageUpdateServiceTest { @Test void twoStepsWithOneKey_areRejected() { - DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); first.setId("main-dashboard"); - DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId); + DevicePackageRequest.Step second = keep("Details", "DASHBOARD", dashboardId); second.setId("main-dashboard"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(first, second)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(first, second)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -489,25 +524,25 @@ class DefaultDevicePackageUpdateServiceTest { @Test void twoStepsOfOneTypeAndName_areRejected() { - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( keep("Dashboard", "DASHBOARD", dashboardId), keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isFalse(); - assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: DASHBOARD:Dashboard"); + assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: DASHBOARD:Dashboard"); verify(transactionTemplate, never()).execute(any()); } @Test void stepWithTheKeyOfAForm_isRejected() { - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setId("Settings"); - DeviceUpdateRequest request = request(step); + DevicePackageRequest request = request(step); request.setInstallState(Map.of("Settings", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("interval", 10)))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isFalse(); - assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: Settings"); + assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: Settings"); verify(transactionTemplate, never()).execute(any()); } @@ -532,14 +567,14 @@ class DefaultDevicePackageUpdateServiceTest { legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"), "Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("integrationName", "TTN my-app")))); - DeviceUpdateRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId); + DevicePackageRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId); uplink.setDefaultConverter(true); - DeviceUpdateRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId); + DevicePackageRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId); ttn.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); - DeviceUpdateRequest request = request(uplink, ttn); + DevicePackageRequest request = request(uplink, ttn); request.setInstallState(Map.of("Configuration", installed.getInstallState().get("Configuration"))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); @@ -563,7 +598,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")), overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); @@ -580,12 +615,12 @@ class DefaultDevicePackageUpdateServiceTest { void entityChangedSinceTheCheck_isAVersionConflict() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); assertThat(result.isSuccess()).isFalse(); assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); - assertThat(result.getErrorMessage()).contains("Check the update again"); + assertThat(result.getErrorMessage()).contains("Check the package again"); verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); } @@ -608,7 +643,7 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode integration = JacksonUtil.newObjectNode().put("name", "Template name").put("type", "TTN").put("edgeTemplate", true); integration.set("defaultConverterId", JacksonUtil.newObjectNode().put("entityType", "CONVERTER").put("id", "${uplinkConverter.id}")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")), overwrite("TTN", "INTEGRATION", integrationId, 2L, integration))); @@ -640,12 +675,12 @@ class DefaultDevicePackageUpdateServiceTest { IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting)); when(installedItemService.findByTenantId(any(), any(), any(), any())) .thenReturn(new PageData<>(List.of(installedItem, creator, taker), 1, 3, false)); - DeviceUpdateRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, + DevicePackageRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); step.setConfirmed(true); step.setDefaultConverter(true); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("UPLINK_CONVERTER:Uplink"); @@ -672,14 +707,14 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode versionInfo = JacksonUtil.newObjectNode().put("itemId", itemId.toString()).put("name", "AM308").put("version", "1.0.0"); when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo); // ThingsBoard's default converter changed: only the converter step is sent - DeviceUpdateRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L, + DevicePackageRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L, JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); step.setId("uplink"); step.setDefaultConverter(true); - DeviceUpdateRequest request = request(step); + DevicePackageRequest request = request(step); request.setVersionId(installedVersionId.toString()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); @@ -697,7 +732,7 @@ class DefaultDevicePackageUpdateServiceTest { void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isTrue(); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard"); @@ -707,7 +742,7 @@ class DefaultDevicePackageUpdateServiceTest { void overwritingAnEntityOfAnotherPackage_needsAConfirmation() { DashboardId foreign = new DashboardId(UUID.randomUUID()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d")))); assertThat(result.isSuccess()).isFalse(); @@ -716,7 +751,7 @@ class DefaultDevicePackageUpdateServiceTest { @Test void theDeviceIsNeverOverwritten() { - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d")))); assertThat(result.isSuccess()).isFalse(); @@ -729,7 +764,7 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString()); when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(other); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isFalse(); verify(transactionTemplate, never()).execute(any()); @@ -743,7 +778,7 @@ class DefaultDevicePackageUpdateServiceTest { updated.setItemVersionId(UUID.fromString(versionId)); when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); assertThat(result.isSuccess()).isFalse(); @@ -754,10 +789,10 @@ class DefaultDevicePackageUpdateServiceTest { @Test void planOfAnotherInstalledVersion_isRejected() { - DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId)); + DevicePackageRequest request = request(keep("AM308", "DEVICE", deviceId)); request.setFromVersionId(UUID.randomUUID()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -768,7 +803,7 @@ class DefaultDevicePackageUpdateServiceTest { doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED)) .when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); assertThat(result.isSuccess()).isFalse(); @@ -780,10 +815,10 @@ class DefaultDevicePackageUpdateServiceTest { void attributesOfAnOverwrittenEntity_areSavedAfterCommit() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")); step.setServerAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); assertThat(result.isSuccess()).isTrue(); ArgumentCaptor saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); @@ -829,12 +864,38 @@ class DefaultDevicePackageUpdateServiceTest { @Test void userMessage_showsValidationMessagesAndHidesInternalOnes() { - assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached"))) + assertThat(DefaultDevicePackageService.userMessage(new DataValidationException("Rule chains limit reached"))) .isEqualTo("Rule chains limit reached"); - assertThat(DefaultDevicePackageUpdateService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) - .contains("Check the update again"); - assertThat(DefaultDevicePackageUpdateService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) - .isEqualTo("Failed to update the device package"); + assertThat(DefaultDevicePackageService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) + .contains("Check the package again"); + assertThat(DefaultDevicePackageService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) + .isEqualTo("Failed to save the device package"); + } + + @Test + void limitOf_givesTheLimitResponseBody_whenAStepHitsASubscriptionLimit() { + JsonNode limit = DefaultDevicePackageService.limitOf(new RuntimeException("step failed", new SubscriptionException( + "Maximum allowed devices limit reached!", SubscriptionErrorCode.LIMIT_REACHED, SubscriptionEntry.DEVICE_COUNT, 5))); + + assertThat(limit.get("errorCode").asInt()).isEqualTo(40); + assertThat(limit.get("message").asText()).isEqualTo("Maximum allowed devices limit reached!"); + assertThat(limit.get("subscriptionErrorCode").asText()).isEqualTo("LIMIT_REACHED"); + assertThat(limit.get("subscriptionEntry").asText()).isEqualTo("DEVICE_COUNT"); + assertThat(limit.at("/subscriptionValue/value").asLong()).isEqualTo(5); + } + + @Test + void limitOf_givesTheLimitResponseBody_whenAStepHitsATenantProfileLimit() { + JsonNode limit = DefaultDevicePackageService.limitOf(new EntitiesLimitExceededException(TenantId.SYS_TENANT_ID, EntityType.DASHBOARD, 10)); + + assertThat(limit.get("errorCode").asInt()).isEqualTo(41); + assertThat(limit.get("entityType").asText()).isEqualTo("DASHBOARD"); + assertThat(limit.get("limit").asLong()).isEqualTo(10); + } + + @Test + void limitOf_givesNothing_whenTheFailureIsNotALimit() { + assertThat(DefaultDevicePackageService.limitOf(new DataValidationException("Device with such name already exists!"))).isNull(); } @Test @@ -842,12 +903,431 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode device = JacksonUtil.newObjectNode().put("id", "123"); ObjectNode node = JacksonUtil.newObjectNode().put("a", "${device.id}").put("b", "x ${device.id} ${gateway.id}"); - ObjectNode resolved = (ObjectNode) DefaultDevicePackageUpdateService.resolvePlaceholders(node, Map.of("device", device)); + ObjectNode resolved = (ObjectNode) DefaultDevicePackageService.resolvePlaceholders(node, Map.of("device", device)); assertThat(resolved.get("a").asText()).isEqualTo("123"); assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}"); } + @Test + void installSavesTheEntitiesAndTheInstalledItemInOneTransaction() { + mockInstall(); + DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId); + integrationStep.setResolution("use-existing"); + + DevicePackageResult result = service.install(user, request( + create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")), + integrationStep, + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + verify(transactionTemplate).execute(any()); + assertThat(savedInTransaction).containsExactly("DEVICE_PROFILE", "DASHBOARD", "INSTALLED_ITEM"); + ArgumentCaptor saved = ArgumentCaptor.forClass(IotHubInstalledItem.class); + verify(installedItemService).save(eq(tenantId), saved.capture()); + IotHubInstalledItem item = saved.getValue(); + assertThat(item.getTenantId()).isEqualTo(tenantId); + assertThat(item.getItemId()).isEqualTo(itemId); + assertThat(item.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); + assertThat(item.getVersion()).isEqualTo("1.0.1"); + assertThat(item.getItemName()).isEqualTo("AM308"); + assertThat(item.getItemType()).isEqualTo("DEVICE"); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) item.getDescriptor(); + assertThat(descriptor.getCreatedEntityIds()).containsExactly(profileId, integrationId, dashboardId); + assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(integrationId); + assertThat(descriptor.getDashboardId()).isEqualTo(dashboardId); + Map state = descriptor.getInstallState(); + assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("entityOutput").get("id").asText()).isEqualTo(profileId.getId().toString()); + assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("checksum").isTextual()).isTrue(); + assertThat(state.get("DASHBOARD:Dashboard").get("entityOutput").get("id").asText()).isEqualTo(dashboardId.getId().toString()); + assertThat(state.get("DASHBOARD:Dashboard").get("checksum").isTextual()).isTrue(); + assertThat(state.get("INTEGRATION:TTN").get("entityOutput").get("id").asText()).isEqualTo(integrationId.getId().toString()); + assertThat(state.get("INTEGRATION:TTN").get("resolution").asText()).isEqualTo("use-existing"); + assertThat(result.getDescriptor()).isSameAs(descriptor); + assertThat(result.getOutputs()).containsOnlyKeys("DEVICE_PROFILE:AM308 profile", "INTEGRATION:TTN", "DASHBOARD:Dashboard"); + assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "REPORT"); + } + + @Test + void installFailureOnALaterStepSavesNothing() { + mockInstall(); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); + + DevicePackageResult result = service.install(user, request( + create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); + assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached"); + assertThat(rolledBack).hasSize(1); + verify(installedItemService, never()).save(any(), any()); + verifyNoInteractions(logEntityActionService, telemetryService); + verify(iotHubRestClient, never()).reportVersionInstalled(any(), any()); + } + + @Test + void installOverwriteOfAnExistingEntityNeedsAConfirmation() { + mockInstall(); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); + + DevicePackageResult result = service.install(user, request( + overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Overwriting an entity of another package needs a confirmation: Dashboard"); + verify(transactionTemplate, never()).execute(any()); + verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWithBadIntegrationCredentialsSavesNothing() throws Exception { + mockInstall(); + doThrow(new ExecutionException(new IllegalStateException("Wrong API key"))) + .when(tbIntegrationService).validateIntegrationConfiguration(eq(tenantId), any()); + + DevicePackageResult result = service.install(user, request( + create("TTN", "INTEGRATION", JacksonUtil.newObjectNode().put("name", "TTN").put("type", "TTN")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("INTEGRATION:TTN"); + assertThat(result.getErrorMessage()).isEqualTo("Wrong API key"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWhenHubIsUnavailableSavesNothing() { + mockInstall(); + when(iotHubRestClient.getVersionInfo(versionId)).thenThrow(new RestClientException("Connection refused")); + + DevicePackageResult result = service.install(user, request( + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("IoT Hub is unavailable. Try again later."); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installReportsToTheHubAfterCommitAndIgnoresAReportFailure() { + mockInstall(); + doAnswer(i -> { + recordAfterCommit("REPORT"); + throw new RestClientException("Connection refused"); + }).when(iotHubRestClient).reportVersionInstalled(eq(versionId), any()); + + DevicePackageResult result = service.install(user, request( + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + InOrder order = inOrder(installedItemService, logEntityActionService, iotHubRestClient); + order.verify(installedItemService).save(eq(tenantId), any()); + order.verify(logEntityActionService).logEntityAction(eq(tenantId), eq(dashboardId), any(), any(), eq(ActionType.ADDED), eq(user)); + order.verify(iotHubRestClient).reportVersionInstalled(eq(versionId), any()); + assertThat(afterCommitCalls).containsExactly("AUDIT", "REPORT"); + } + + @Test + void installRejectsAFromVersion() { + mockInstall(); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setFromVersionId(installedVersionId); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installKeepStepMustUseExisting() { + mockInstall(); + DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId); + integrationStep.setResolution("created"); + + DevicePackageResult result = service.install(user, request(integrationStep)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: TTN"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installRejectsAMalformedVersionId() { + mockInstall(); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setVersionId("not-a-uuid"); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(iotHubRestClient, never()).getVersionInfo(any()); + verify(transactionTemplate, never()).execute(any()); + } + + @Test + void installAssignsTheCustomerToTheDeviceAndTheDashboard() { + mockInstall(); + CustomerId customerId = customerOf(tenantId); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setCustomerId(customerId.getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor device = ArgumentCaptor.forClass(Device.class); + verify(deviceService).saveDevice(device.capture()); + assertThat(device.getValue().getCustomerId()).isEqualTo(customerId); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getCustomerId()).isEqualTo(customerId); + } + + @Test + void installAddsTheDeviceToTheEntityGroup() { + mockInstall(); + EntityGroup group = new EntityGroup(); + group.setId(new EntityGroupId(UUID.randomUUID())); + group.setType(EntityType.DEVICE); + group.setName("Warehouse sensors"); + group.setOwnerId(tenantId); + when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setEntityGroupId(group.getId().getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId); + verify(entityGroupService, never()).addEntityToEntityGroup(any(), any(), eq(dashboardId)); + assertThat(savedInTransaction).contains("ENTITY_GROUP"); + verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), any(), eq(ActionType.ADDED_TO_ENTITY_GROUP), + eq(user), eq(deviceId.toString()), eq(group.getId().toString()), eq("Warehouse sensors")); + assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "AUDIT", "REPORT"); + } + + @Test + void installRejectsACustomerOfAnotherTenant() { + mockInstall(); + CustomerId customerId = customerOf(TenantId.fromUUID(UUID.randomUUID())); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setCustomerId(customerId.getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void updateIgnoresCustomerAndEntityGroup() { + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); + DevicePackageRequest request = request(overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))); + request.setCustomerId(UUID.randomUUID()); + request.setEntityGroupId(UUID.randomUUID()); + + DevicePackageResult result = service.update(user, installedItem.getId(), request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getCustomerId()).isNull(); + verifyNoInteractions(customerService, entityGroupService); + } + + @Test + void updateOverwriteOfACustomerDeviceThatChangesItsOwnerFails() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + Device current = new Device(otherId); + current.setTenantId(tenantId); + current.setName("AM308 spare"); + current.setCustomerId(customerOf(tenantId)); + when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current); + DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare")); + step.setConfirmed(true); + + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("DEVICE:AM308 spare"); + assertThat(result.getErrorMessage()).isEqualTo("AM308 spare belongs to another owner"); + verify(deviceService, never()).saveDevice(any(Device.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void updateOverwriteOfAnotherDeviceKeepsItsCredentials() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + Device current = new Device(otherId); + current.setTenantId(tenantId); + current.setName("AM308 spare"); + when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current); + when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> i.getArgument(0)); + DeviceCredentials credentials = new DeviceCredentials(); + credentials.setDeviceId(otherId); + credentials.setCredentialsId("existing-token"); + when(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, otherId)).thenReturn(credentials); + DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare")); + step.setConfirmed(true); + step.setCredentials(JacksonUtil.newObjectNode().put("credentialsType", "ACCESS_TOKEN").put("credentialsId", "package-token")); + + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + + assertThat(result.isSuccess()).isTrue(); + verify(deviceService).saveDevice(any(Device.class)); + verify(deviceCredentialsService, never()).updateDeviceCredentials(any(), any()); + assertThat(result.getOutputs().get("DEVICE:AM308 spare").get("token").asText()).isEqualTo("existing-token"); + } + + @Test + void installRejectsAnOverwriteOfADeviceOrGateway() { + mockInstall(); + for (String type : new String[]{"DEVICE", "GATEWAY"}) { + DevicePackageRequest.Step step = overwrite("AM308", type, deviceId, 1L, JacksonUtil.newObjectNode().put("name", "AM308")); + step.setConfirmed(true); + + DevicePackageResult result = service.install(user, request(step)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: AM308"); + } + verify(transactionTemplate, never()).execute(any()); + verify(deviceService, never()).saveDevice(any(Device.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWritesStepAttributesOnAUsedExistingEntityAfterCommit() { + mockInstall(); + DevicePackageRequest.Step deviceStep = keep("AM308", "DEVICE", deviceId); + deviceStep.setResolution("use-existing"); + deviceStep.setServerAttributes(JacksonUtil.newObjectNode().put("model", "AM308")); + deviceStep.setSharedAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}")); + + DevicePackageResult result = service.install(user, request(deviceStep, + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); + verify(telemetryService, times(2)).saveAttributes(saved.capture()); + assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getEntityId).containsOnly(deviceId); + assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getScope).containsExactly(AttributeScope.SERVER_SCOPE, AttributeScope.SHARED_SCOPE); + assertThat(saved.getAllValues().get(0).getEntries().get(0).getValueAsString()).isEqualTo("AM308"); + assertThat(saved.getAllValues().get(1).getEntries().get(0).getValueAsString()).isEqualTo(deviceId.getId().toString()); + // The kept device isn't saved, so only the dashboard is audited + assertThat(afterCommitCalls).containsExactly("AUDIT", "ATTRIBUTES", "ATTRIBUTES", "REPORT"); + } + + @Test + void installIntoACustomerGroupGivesTheDeviceTheGroupsCustomer() { + mockInstall(); + CustomerId groupCustomer = customerOf(tenantId); + EntityGroup group = new EntityGroup(); + group.setId(new EntityGroupId(UUID.randomUUID())); + group.setType(EntityType.DEVICE); + group.setName("Customer sensors"); + group.setOwnerId(groupCustomer); + when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setEntityGroupId(group.getId().getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor device = ArgumentCaptor.forClass(Device.class); + verify(deviceService).saveDevice(device.capture()); + assertThat(device.getValue().getCustomerId()).isEqualTo(groupCustomer); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getOwnerId()).isEqualTo(tenantId); + verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId); + verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), eq(groupCustomer), eq(ActionType.ADDED), eq(user)); + } + + private CustomerId customerOf(TenantId owner) { + Customer customer = new Customer(new CustomerId(UUID.randomUUID())); + customer.setTenantId(owner); + when(customerService.findCustomerById(tenantId, customer.getId())).thenReturn(customer); + return customer.getId(); + } + + /** The new entities get these ids; each save records that it ran inside the transaction. */ + private void mockInstall() { + when(user.getId()).thenReturn(new UserId(UUID.randomUUID())); + when(projectInfo.getProjectVersion()).thenReturn("4.4.1"); + when(projectInfo.getProductType()).thenReturn("PE"); + when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> { + recordSave("DEVICE_PROFILE"); + DeviceProfile profile = i.getArgument(0); + profile.setId(profileId); + return profile; + }); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> { + recordSave("DASHBOARD"); + Dashboard dashboard = i.getArgument(0); + dashboard.setId(dashboardId); + return dashboard; + }); + when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> { + recordSave("DEVICE"); + Device device = i.getArgument(0); + device.setId(deviceId); + return device; + }); + doAnswer(i -> { + recordSave("ENTITY_GROUP"); + return null; + }).when(entityGroupService).addEntityToEntityGroup(any(), any(), any()); + when(installedItemService.save(any(), any())).thenAnswer(i -> { + recordSave("INSTALLED_ITEM"); + return i.getArgument(1); + }); + Integration integration = new Integration(); + integration.setId(integrationId); + integration.setTenantId(tenantId); + integration.setName("TTN my-app"); + when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(integration); + doAnswer(i -> { + recordAfterCommit("AUDIT"); + return null; + }).when(logEntityActionService).logEntityAction(any(TenantId.class), any(EntityId.class), any(HasName.class), nullable(CustomerId.class), + any(ActionType.class), any(User.class), any(Object[].class)); + doAnswer(i -> { + recordAfterCommit("REPORT"); + return null; + }).when(iotHubRestClient).reportVersionInstalled(any(), any()); + doAnswer(i -> { + recordAfterCommit("ATTRIBUTES"); + return null; + }).when(telemetryService).saveAttributes(any(AttributesSaveRequest.class)); + } + + private void recordSave(String what) { + if (inTransaction) { + savedInTransaction.add(what); + } + } + + private void recordAfterCommit(String what) { + afterCommitCalls.add(inTransaction ? what + " in transaction" : what); + } + private IotHubInstalledItem otherPackage(Map installState) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setInstallState(installState); @@ -875,35 +1355,35 @@ class DefaultDevicePackageUpdateServiceTest { return dashboard; } - private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) { - DeviceUpdateRequest request = new DeviceUpdateRequest(); + private DevicePackageRequest request(DevicePackageRequest.Step... steps) { + DevicePackageRequest request = new DevicePackageRequest(); request.setVersionId(versionId); request.setSteps(List.of(steps)); return request; } - private static DeviceUpdateRequest.Step keep(String name, String type, EntityId id) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.KEEP); + private static DevicePackageRequest.Step keep(String name, String type, EntityId id) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.KEEP); step.setEntityId(id.getId()); return step; } - private static DeviceUpdateRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.OVERWRITE); + private static DevicePackageRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.OVERWRITE); step.setEntityId(id.getId()); step.setExpectedVersion(version); step.setEntity(entity); return step; } - private static DeviceUpdateRequest.Step create(String name, String type, ObjectNode entity) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.CREATE); + private static DevicePackageRequest.Step create(String name, String type, ObjectNode entity) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.CREATE); step.setEntity(entity); return step; } - private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) { - DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step(); + private static DevicePackageRequest.Step step(String name, String type, DevicePackageRequest.Action action) { + DevicePackageRequest.Step step = new DevicePackageRequest.Step(); step.setName(name); step.setType(type); step.setAction(action); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index a81368450c..a7ac68bd8e 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -3,6 +3,10 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.iot_hub; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; @@ -14,16 +18,37 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.LoggerFactory; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.cf.CalculatedField; +import org.thingsboard.server.common.data.cf.CalculatedFieldType; +import org.thingsboard.server.common.data.cf.configuration.AlarmCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.Argument; +import org.thingsboard.server.common.data.cf.configuration.ArgumentType; +import org.thingsboard.server.common.data.cf.configuration.ArgumentsBasedCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.CalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.ReferencedEntityKey; +import org.thingsboard.server.common.data.cf.configuration.SimpleCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput; +import org.thingsboard.server.common.data.cf.configuration.geofencing.EntityCoordinates; +import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingReportStrategy; +import org.thingsboard.server.common.data.cf.configuration.geofencing.ZoneGroupConfiguration; +import org.thingsboard.server.common.data.id.CalculatedFieldId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; +import org.thingsboard.server.common.data.id.RuleChainId; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.integration.Integration; +import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor; +import org.thingsboard.server.common.data.iot_hub.CalculatedFieldInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor; @@ -32,6 +57,7 @@ import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.id.ConverterId; import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.dao.cf.CalculatedFieldService; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.converter.ConverterService; import org.thingsboard.server.dao.device.DeviceProfileService; @@ -39,12 +65,16 @@ import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.entity.EntityService; import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; +import org.thingsboard.server.service.entitiy.cf.TbCalculatedFieldService; +import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService; import org.thingsboard.server.service.entitiy.converter.TbConverterService; import org.thingsboard.server.service.entitiy.device.TbDeviceService; import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileService; +import org.thingsboard.server.service.rule.TbRuleChainService; import org.thingsboard.server.service.security.model.SecurityUser; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; @@ -60,6 +90,7 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -76,6 +107,10 @@ class DefaultIotHubServiceTest { @Mock private IotHubInstalledItemService iotHubInstalledItemService; @Mock + private TbCalculatedFieldService tbCalculatedFieldService; + @Mock + private CalculatedFieldService calculatedFieldService; + @Mock private DeviceService deviceService; @Mock private EntityService entityService; @@ -95,6 +130,12 @@ class DefaultIotHubServiceTest { private ConverterService converterService; @Mock private TbConverterService tbConverterService; + @Mock + private DevicePackageEntities devicePackageEntities; + @Mock + private RuleChainService ruleChainService; + @Mock + private TbRuleChainService tbRuleChainService; @Spy @InjectMocks @@ -459,6 +500,151 @@ class DefaultIotHubServiceTest { assertThat(result.getErrorMessage()).contains("install failed"); } + @Test + void doInstallVersion_calculatedField_mapsTenantReferencesToInstallingTenant() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "CF", "1.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(calculatedFieldFileData()); + when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0)); + when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1)); + + service.doInstallVersion(user, versionId, null, null); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class); + verify(tbCalculatedFieldService).save(captor.capture(), eq(user)); + assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId); + } + + @Test + void updateItemVersion_calculatedField_mapsTenantReferencesToInstallingTenant() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + CalculatedFieldId calculatedFieldId = new CalculatedFieldId(UUID.randomUUID()); + CalculatedFieldInstalledItemDescriptor descriptor = new CalculatedFieldInstalledItemDescriptor(); + descriptor.setCalculatedFieldId(calculatedFieldId); + IotHubInstalledItem item = installedItem(UUID.randomUUID()); + item.setItemType("CALCULATED_FIELD"); + item.setItemVersionId(UUID.randomUUID()); + item.setDescriptor(descriptor); + when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item); + when(iotHubRestClient.getVersionInfo(anyString())) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "CF", "2.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(calculatedFieldFileData()); + CalculatedField existing = new CalculatedField(calculatedFieldId); + existing.setTenantId(tenantId); + when(calculatedFieldService.findById(tenantId, calculatedFieldId)).thenReturn(existing); + + UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), versionId, true, null); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class); + verify(tbCalculatedFieldService).save(captor.capture(), eq(user)); + assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId); + } + + @Test + void doInstallVersion_alarmRule_mapsTenantReferencesToInstallingTenant() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "ALARM_RULE", "Alarm", "1.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(alarmRuleFileData()); + when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0)); + when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1)); + + service.doInstallVersion(user, versionId, null, null); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class); + verify(tbCalculatedFieldService).save(captor.capture(), eq(user)); + assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId); + } + + @Test + void updateItemVersion_alarmRule_mapsTenantReferencesToInstallingTenant() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + CalculatedFieldId calculatedFieldId = new CalculatedFieldId(UUID.randomUUID()); + AlarmRuleInstalledItemDescriptor descriptor = new AlarmRuleInstalledItemDescriptor(); + descriptor.setCalculatedFieldId(calculatedFieldId); + IotHubInstalledItem item = installedItem(UUID.randomUUID()); + item.setItemType("ALARM_RULE"); + item.setItemVersionId(UUID.randomUUID()); + item.setDescriptor(descriptor); + when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item); + when(iotHubRestClient.getVersionInfo(anyString())) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "ALARM_RULE", "Alarm", "2.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(alarmRuleFileData()); + CalculatedField existing = new CalculatedField(calculatedFieldId); + existing.setTenantId(tenantId); + when(calculatedFieldService.findById(tenantId, calculatedFieldId)).thenReturn(existing); + + UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), versionId, true, null); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class); + verify(tbCalculatedFieldService).save(captor.capture(), eq(user)); + assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId); + } + + @Test + void doInstallVersion_geofencingCalculatedField_mapsZoneGroupTenantReferencesToInstallingTenant() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "Geofencing", "1.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(geofencingFileData()); + when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0)); + when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1)); + + service.doInstallVersion(user, versionId, null, null); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class); + verify(tbCalculatedFieldService).save(captor.capture(), eq(user)); + assertThat(((GeofencingCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getZoneGroups().get("zones").getRefEntityId()).isEqualTo(tenantId); + } + + private byte[] calculatedFieldFileData() { + SimpleCalculatedFieldConfiguration configuration = new SimpleCalculatedFieldConfiguration(); + configuration.setArguments(Map.of("T", otherTenantArgument())); + configuration.setExpression("T"); + return fileData(CalculatedFieldType.SIMPLE, configuration); + } + + private byte[] alarmRuleFileData() { + AlarmCalculatedFieldConfiguration configuration = new AlarmCalculatedFieldConfiguration(); + configuration.setArguments(Map.of("T", otherTenantArgument())); + configuration.setCreateRules(Map.of()); + return fileData(CalculatedFieldType.ALARM, configuration); + } + + private byte[] geofencingFileData() { + ZoneGroupConfiguration zoneGroup = new ZoneGroupConfiguration("perimeter", GeofencingReportStrategy.REPORT_PRESENCE_STATUS_ONLY, false); + zoneGroup.setRefEntityId(TenantId.fromUUID(UUID.randomUUID())); + GeofencingCalculatedFieldConfiguration configuration = new GeofencingCalculatedFieldConfiguration(); + configuration.setEntityCoordinates(new EntityCoordinates("latitude", "longitude")); + configuration.setZoneGroups(Map.of("zones", zoneGroup)); + configuration.setOutput(new TimeSeriesOutput()); + return fileData(CalculatedFieldType.GEOFENCING, configuration); + } + + private Argument otherTenantArgument() { + Argument argument = new Argument(); + argument.setRefEntityId(TenantId.fromUUID(UUID.randomUUID())); + argument.setRefEntityKey(new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null)); + return argument; + } + + private byte[] fileData(CalculatedFieldType type, CalculatedFieldConfiguration configuration) { + CalculatedField calculatedField = new CalculatedField(); + calculatedField.setEntityId(new DeviceId(UUID.randomUUID())); + calculatedField.setType(type); + calculatedField.setName("CF"); + calculatedField.setConfiguration(configuration); + return JacksonUtil.toString(calculatedField).getBytes(StandardCharsets.UTF_8); + } + @Test void deleteInstalledItem_devicePackage_removesEachEntityBeforeWhatItRefersTo() throws Exception { mockTenant(); @@ -467,6 +653,10 @@ class DefaultIotHubServiceTest { profile.setDefaultDashboardId(dashboard.getId()); Integration integration = new Integration(new IntegrationId(UUID.randomUUID())); Converter converter = new Converter(new ConverterId(UUID.randomUUID())); + profile.setTenantId(tenantId); + dashboard.setTenantId(tenantId); + integration.setTenantId(tenantId); + converter.setTenantId(tenantId); // The profile and the integration listed first: in reverse order of creation, the dashboard would go before the // profile that refers to it, and the converter before the integration that uses it. IotHubInstalledItem deleted = devicePackage(profile.getId(), dashboard.getId(), integration.getId(), converter.getId()); @@ -474,6 +664,7 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + noDevices(profile.getId()); when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard); when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration); when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter); @@ -499,6 +690,7 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false)); Device device = new Device(deviceId); + device.setTenantId(tenantId); when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); service.deleteInstalledItem(user, deleted.getId()); @@ -604,6 +796,7 @@ class DefaultIotHubServiceTest { mockTenant(); IntegrationId integrationId = new IntegrationId(UUID.randomUUID()); Converter converter = new Converter(new ConverterId(UUID.randomUUID())); + converter.setTenantId(tenantId); when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter); IotHubInstalledItem deleted = devicePackage(converter.getId(), integrationId); // The converter and the integration steps shared the name: the integration's state replaced the converter's @@ -643,6 +836,12 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(checked, first, second, unrelated), 1, 4, false)); + DeviceProfile sharedProfile = new DeviceProfile(sharedProfileId); + sharedProfile.setTenantId(tenantId); + when(deviceProfileService.findDeviceProfileById(tenantId, sharedProfileId)).thenReturn(sharedProfile); + Dashboard sharedDashboard = new Dashboard(sharedDashboardId); + sharedDashboard.setTenantId(tenantId); + when(dashboardService.findDashboardById(tenantId, sharedDashboardId)).thenReturn(sharedDashboard); when(entityService.fetchEntityName(tenantId, sharedProfileId)).thenReturn(Optional.of("Shared profile")); when(entityService.fetchEntityName(tenantId, sharedDashboardId)).thenReturn(Optional.of("Shared dashboard")); @@ -665,6 +864,7 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); Device device = new Device(deviceId); + device.setTenantId(tenantId); when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); service.deleteInstalledItem(user, deleted.getId()); @@ -682,6 +882,9 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(checked), 1, 1, false)); + Dashboard usersDashboard = new Dashboard(usersDashboardId); + usersDashboard.setTenantId(tenantId); + when(dashboardService.findDashboardById(tenantId, usersDashboardId)).thenReturn(usersDashboard); when(entityService.fetchEntityName(tenantId, usersDashboardId)).thenReturn(Optional.of("My dashboard")); InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); @@ -691,6 +894,59 @@ class DefaultIotHubServiceTest { assertThat(kept.getUsedExistingCount()).isEqualTo(1); } + @Test + void deleteInstalledItem_devicePackageInstalledBefore441_keepsEntitiesTheUserHadBefore() { + mockTenant(); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DashboardId usersDashboardId = new DashboardId(UUID.randomUUID()); + IotHubInstalledItem deleted = devicePackageInstalledBefore441(deviceId, usersDashboardId); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + // Found, so only the use-existing rule keeps it + Dashboard usersDashboard = new Dashboard(usersDashboardId); + usersDashboard.setTenantId(tenantId); + lenient().when(dashboardService.findDashboardById(tenantId, usersDashboardId)).thenReturn(usersDashboard); + Device device = new Device(deviceId); + device.setTenantId(tenantId); + when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(tbDeviceService).delete(device, user); + verify(tbDashboardService, never()).delete(any(), any()); + } + + @Test + void findKeptEntities_devicePackageInstalledBefore441_namesTheEntitiesTheUserHadBefore() { + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DashboardId usersDashboardId = new DashboardId(UUID.randomUUID()); + IotHubInstalledItem checked = devicePackageInstalledBefore441(deviceId, usersDashboardId); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked), 1, 1, false)); + Dashboard usersDashboard = new Dashboard(usersDashboardId); + usersDashboard.setTenantId(tenantId); + lenient().when(dashboardService.findDashboardById(tenantId, usersDashboardId)).thenReturn(usersDashboard); + when(entityService.fetchEntityName(tenantId, usersDashboardId)).thenReturn(Optional.of("My dashboard")); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getEntities()).containsExactly(new InstalledItemKeptEntities.KeptEntity(usersDashboardId, "My dashboard")); + assertThat(kept.getUsedExistingCount()).isEqualTo(1); + } + + /** An install made before 4.4.1: the dashboard the user took as it was is only in the install state, under the step name. */ + private IotHubInstalledItem devicePackageInstalledBefore441(DeviceId deviceId, DashboardId usersDashboardId) { + IotHubInstalledItem installedItem = devicePackage(deviceId, usersDashboardId); + ObjectNode device = JacksonUtil.newObjectNode().put("resolution", "created"); + device.set("entityOutput", JacksonUtil.newObjectNode().put("id", deviceId.getId().toString())); + ObjectNode dashboard = JacksonUtil.newObjectNode().put("resolution", "use-existing"); + dashboard.set("entityOutput", JacksonUtil.newObjectNode().put("id", usersDashboardId.getId().toString())); + ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Device", device, "Dashboard", dashboard)); + return installedItem; + } + @Test void findKeptEntities_devicePackageSharingNothing_keepsNothing() { IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID())); @@ -736,6 +992,185 @@ class DefaultIotHubServiceTest { return integration; } + @Test + void findKeptEntities_devicePackage_namesTheProfileDevicesUseAndWhatItRefersTo_apartFromTheShared() { + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + profile.setTenantId(tenantId); + RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID())); + ruleChain.setTenantId(tenantId); + RuleChainId ruleChainId = ruleChain.getId(); + Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID())); + dashboard.setTenantId(tenantId); + DashboardId dashboardId = dashboard.getId(); + profile.setDefaultRuleChainId(ruleChainId); + profile.setDefaultDashboardId(dashboardId); + // The user's, not the package's: not listed + profile.setDefaultEdgeRuleChainId(new RuleChainId(UUID.randomUUID())); + Device packageDevice = new Device(new DeviceId(UUID.randomUUID())); + packageDevice.setDeviceProfileId(profile.getId()); + IotHubInstalledItem checked = devicePackage(ruleChainId, dashboardId, profile.getId(), packageDevice.getId()); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked), 1, 1, false)); + // 3 devices on the profile: the package's own, which the delete removes first, and 2 the integration created + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any())) + .thenReturn(new PageData<>(List.of(), 3, 3, true)); + when(deviceService.findDeviceById(tenantId, packageDevice.getId())).thenReturn(packageDevice); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + when(ruleChainService.findRuleChainById(tenantId, ruleChainId)).thenReturn(ruleChain); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); + when(entityService.fetchEntityName(tenantId, profile.getId())).thenReturn(Optional.of("smartico-l2-lr")); + when(entityService.fetchEntityName(tenantId, ruleChainId)).thenReturn(Optional.of("Smartico L2-LR")); + when(entityService.fetchEntityName(tenantId, dashboardId)).thenReturn(Optional.of("Smartico L2-LR Fleet")); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + // An update reads entities as shared with other packages: the profile is not among them + assertThat(kept.getEntities()).isEmpty(); + assertThat(kept.getReferencedEntities()).containsExactly( + new InstalledItemKeptEntities.KeptEntity(profile.getId(), "smartico-l2-lr"), + new InstalledItemKeptEntities.KeptEntity(ruleChainId, "Smartico L2-LR"), + new InstalledItemKeptEntities.KeptEntity(dashboardId, "Smartico L2-LR Fleet")); + } + + @Test + void findKeptEntities_devicePackage_aKeptDeviceKeepsItsProfile() { + DeviceProfileId profileId = new DeviceProfileId(UUID.randomUUID()); + DeviceId sharedDeviceId = new DeviceId(UUID.randomUUID()); + IotHubInstalledItem checked = devicePackage(profileId, sharedDeviceId); + IotHubInstalledItem other = devicePackage(sharedDeviceId); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked, other), 1, 2, false)); + // The only device on the profile is the one another package uses: the delete keeps it, so it keeps the profile + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profileId), any())) + .thenReturn(new PageData<>(List.of(sharedDeviceId), 1, 1, false)); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profileId); + } + + @Test + void findKeptEntities_devicePackage_aSharedProfileKeepsWhatItRefersTo() { + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + RuleChainId edgeRuleChainId = new RuleChainId(UUID.randomUUID()); + profile.setDefaultRuleChainId(ruleChainId); + profile.setDefaultEdgeRuleChainId(edgeRuleChainId); + IotHubInstalledItem checked = devicePackage(ruleChainId, edgeRuleChainId, profile.getId()); + IotHubInstalledItem other = devicePackage(profile.getId()); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked, other), 1, 2, false)); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profile.getId()); + assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId) + .containsExactly(ruleChainId, edgeRuleChainId); + } + + @Test + void deleteInstalledItem_devicePackage_keepsTheProfileDevicesUseAndWhatItRefersTo() throws Exception { + mockTenant(); + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + DashboardId dashboardId = new DashboardId(UUID.randomUUID()); + profile.setDefaultRuleChainId(ruleChainId); + profile.setDefaultDashboardId(dashboardId); + IotHubInstalledItem deleted = devicePackage(ruleChainId, dashboardId, profile.getId()); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any())) + .thenReturn(new PageData<>(List.of(new DeviceId(UUID.randomUUID())), 1, 1, false)); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(tbDeviceProfileService, never()).delete(any(), any()); + verify(tbRuleChainService, never()).delete(any(), any()); + verify(tbDashboardService, never()).delete(any(), any()); + verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId()); + } + + @Test + void deleteInstalledItem_devicePackage_aSharedProfileKeepsItsRuleChain() throws Exception { + mockTenant(); + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + profile.setDefaultRuleChainId(ruleChainId); + IotHubInstalledItem deleted = devicePackage(ruleChainId, profile.getId()); + IotHubInstalledItem other = devicePackage(profile.getId()); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false)); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(tbDeviceProfileService, never()).delete(any(), any()); + verify(tbRuleChainService, never()).delete(any(), any()); + } + + @Test + void deleteInstalledItem_devicePackage_anEntitySomethingElseRefersToStays_loggedAsKept() throws Exception { + // A profile the user made after the install uses the package's rule chain + List logs = deleteRuleChainFailingWith( + new DataValidationException("The rule chain referenced by the device profiles cannot be deleted!")); + + assertThat(logs).anySatisfy(event -> { + assertThat(event.getLevel()).isEqualTo(Level.INFO); + assertThat(event.getFormattedMessage()).contains("Kept RULE_CHAIN").contains("referenced by the device profiles"); + }); + assertThat(logs).noneMatch(event -> event.getLevel() == Level.ERROR); + } + + @Test + void deleteInstalledItem_devicePackage_aFailedDelete_staysAnError() throws Exception { + List logs = deleteRuleChainFailingWith(new RuntimeException("Database is down")); + + assertThat(logs).anySatisfy(event -> { + assertThat(event.getLevel()).isEqualTo(Level.ERROR); + assertThat(event.getFormattedMessage()).contains("Failed to delete device package entity"); + }); + } + + /** Deletes a package whose only entity is a rule chain that fails to delete with {@code failure}; the service's logs. */ + private List deleteRuleChainFailingWith(Exception failure) throws Exception { + mockTenant(); + RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID())); + ruleChain.setTenantId(tenantId); + IotHubInstalledItem deleted = devicePackage(ruleChain.getId()); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + when(ruleChainService.findRuleChainById(tenantId, ruleChain.getId())).thenReturn(ruleChain); + doThrow(failure).when(tbRuleChainService).delete(ruleChain, user); + Logger logger = (Logger) LoggerFactory.getLogger(DefaultIotHubService.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + Level level = logger.getLevel(); + logger.setLevel(Level.INFO); + try { + service.deleteInstalledItem(user, deleted.getId()); + } finally { + logger.setLevel(level); + logger.detachAppender(appender); + } + // The delete goes on either way + verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId()); + return appender.list; + } + + private void noDevices(DeviceProfileId profileId) { + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profileId), any())) + .thenReturn(new PageData<>(List.of(), 0, 0, false)); + } + private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setCreatedEntityIds(List.of(createdEntityIds)); @@ -744,4 +1179,184 @@ class DefaultIotHubServiceTest { return item; } + private Dashboard dashboard(TenantId owner) { + Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID())); + dashboard.setTenantId(owner); + return dashboard; + } + + private Device device(TenantId owner) { + Device device = new Device(new DeviceId(UUID.randomUUID())); + device.setTenantId(owner); + return device; + } + + private DeviceInstalledItemDescriptor devicePackageDescriptor(EntityId... createdEntityIds) { + DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); + descriptor.setCreatedEntityIds(List.of(createdEntityIds)); + return descriptor; + } + + @Test + void registerDeviceInstall_unknownEntity_rejectedAndNotSaved() { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0")); + Device knownDevice = device(tenantId); + Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID())); + when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice); + when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard); + + InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, + devicePackageDescriptor(knownDevice.getId(), unknownDashboard.getId())); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).save(any(), any()); + verify(tbDeviceService, never()).delete(any(Device.class), any()); + verify(tbDashboardService, never()).delete(any(Dashboard.class), any()); + } + + @Test + void registerDeviceInstall_unknownDashboardId_rejectedAndNotSaved() { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0")); + Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID())); + when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard); + DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor(); + descriptor.setDashboardId(unknownDashboard.getId()); + + InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + + @Test + void registerDeviceInstall_knownEntities_saved() { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0")); + Device knownDevice = device(tenantId); + Dashboard knownDashboard = dashboard(tenantId); + when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice); + when(dashboardService.findDashboardById(tenantId, knownDashboard.getId())).thenReturn(knownDashboard); + DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor(knownDevice.getId(), knownDashboard.getId()); + descriptor.setDashboardId(knownDashboard.getId()); + when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(inv -> inv.getArgument(1)); + + InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor); + + assertThat(result.isSuccess()).isTrue(); + verify(iotHubInstalledItemService).save(eq(tenantId), any(IotHubInstalledItem.class)); + } + + @Test + void deleteInstalledItem_devicePackage_skipsEntityNotFound() throws Exception { + mockTenant(); + Device knownDevice = device(tenantId); + Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID())); + when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice); + when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard); + UUID id = UUID.randomUUID(); + IotHubInstalledItem item = installedItem(id); + item.setDescriptor(devicePackageDescriptor(knownDevice.getId(), unknownDashboard.getId())); + when(iotHubInstalledItemService.findById(tenantId, new IotHubInstalledItemId(id))).thenReturn(item); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(item), 1, 1, false)); + + service.deleteInstalledItem(user, new IotHubInstalledItemId(id)); + + verify(tbDeviceService).delete(knownDevice, user); + verify(tbDashboardService, never()).delete(any(Dashboard.class), any()); + verify(iotHubInstalledItemService).deleteById(tenantId, new IotHubInstalledItemId(id)); + } + + @Test + void deleteInstalledItem_devicePackage_deletesItsIntegrationAndConverter() throws Exception { + mockTenant(); + Integration integration = new Integration(new IntegrationId(UUID.randomUUID())); + integration.setTenantId(tenantId); + Converter converter = new Converter(new ConverterId(UUID.randomUUID())); + converter.setTenantId(tenantId); + Integration unknownIntegration = new Integration(new IntegrationId(UUID.randomUUID())); + unknownIntegration.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration); + when(integrationService.findIntegrationById(tenantId, unknownIntegration.getId())).thenReturn(unknownIntegration); + when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter); + UUID id = UUID.randomUUID(); + IotHubInstalledItem item = installedItem(id); + item.setDescriptor(devicePackageDescriptor(converter.getId(), integration.getId(), unknownIntegration.getId())); + when(iotHubInstalledItemService.findById(tenantId, new IotHubInstalledItemId(id))).thenReturn(item); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(item), 1, 1, false)); + + service.deleteInstalledItem(user, new IotHubInstalledItemId(id)); + + verify(integrationService).deleteIntegration(tenantId, integration.getId()); + verify(integrationService, never()).deleteIntegration(tenantId, unknownIntegration.getId()); + verify(tbConverterService).delete(converter, user); + verify(iotHubInstalledItemService).deleteById(tenantId, new IotHubInstalledItemId(id)); + } + + @Test + void registerDeviceInstall_usedExistingEntityOfAnotherTenant_rejectedAndNotSaved() { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0")); + Device knownDevice = device(tenantId); + when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice); + Dashboard otherTenantDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID())); + when(dashboardService.findDashboardById(tenantId, otherTenantDashboard.getId())).thenReturn(otherTenantDashboard); + DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor(knownDevice.getId()); + descriptor.setUsedExistingEntityIds(List.of(otherTenantDashboard.getId())); + + InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + + @Test + void deleteInstalledItem_devicePackage_leavesTheIntegrationOfAnotherTenantAsItIs() { + mockTenant(); + IntegrationId integrationId = new IntegrationId(UUID.randomUUID()); + IotHubInstalledItem deleted = devicePackage(integrationId); + setIntegrationState(deleted, integrationId, Map.of("profile.milesight-iot-am308", "am308-custom")); + ((DeviceInstalledItemDescriptor) deleted.getDescriptor()).setUsedExistingEntityIds(List.of(integrationId)); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + Integration otherTenantIntegration = integration(integrationId, Map.of("profile.milesight-iot-am308", "am308-custom")); + otherTenantIntegration.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(otherTenantIntegration); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(integrationService, never()).saveIntegration(any()); + verify(integrationService, never()).deleteIntegration(any(), any()); + } + + @Test + void findKeptEntities_devicePackage_namesNoEntityOfAnotherTenant() { + DashboardId otherTenantDashboardId = new DashboardId(UUID.randomUUID()); + IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID()), otherTenantDashboardId); + ((DeviceInstalledItemDescriptor) checked.getDescriptor()).setUsedExistingEntityIds(List.of(otherTenantDashboardId)); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked), 1, 1, false)); + Dashboard otherTenantDashboard = new Dashboard(otherTenantDashboardId); + otherTenantDashboard.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + when(dashboardService.findDashboardById(tenantId, otherTenantDashboardId)).thenReturn(otherTenantDashboard); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getEntities()).containsExactly(new InstalledItemKeptEntities.KeptEntity(otherTenantDashboardId, null)); + verify(entityService, never()).fetchEntityName(any(), any()); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/mail/TbMailSenderTest.java b/application/src/test/java/org/thingsboard/server/service/mail/TbMailSenderTest.java index dcac2daf1a..ecc373e796 100644 --- a/application/src/test/java/org/thingsboard/server/service/mail/TbMailSenderTest.java +++ b/application/src/test/java/org/thingsboard/server/service/mail/TbMailSenderTest.java @@ -21,6 +21,7 @@ import java.util.Properties; import java.util.UUID; import java.util.stream.Stream; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; @@ -63,6 +64,21 @@ public class TbMailSenderTest { verify(tbMailSender, times(1)).testConnectionSuper(); } + @Test + public void testServerIdentityCheckIsDisabled() { + var json = JacksonUtil.newObjectNode(); + json.put("smtpProtocol", "smtps"); + json.put("smtpHost", "10.0.0.1"); + json.put("smtpPort", "465"); + json.put("timeout", "10000"); + json.put("username", ""); + json.put("enableTls", true); + + TbMailSender sender = new TbMailSender(null, TenantId.SYS_TENANT_ID, json); + + assertEquals("false", sender.getJavaMailProperties().getProperty("mail.smtps.ssl.checkserveridentity")); + } + @Test public void testGiveMailTenantSettings_noFallbackToSystem() { var json = JacksonUtil.newObjectNode(); diff --git a/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java index 9b91c00669..fc79a220d6 100644 --- a/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java +++ b/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java @@ -1123,6 +1123,42 @@ public class NotificationApiTest extends AbstractNotificationApiTest { assertThat(getAvailableDeliveryMethods()).doesNotContain(NotificationDeliveryMethod.MOBILE_APP); } + @Test + public void testNotificationRequest_templateOfOtherTenant_returnsBadRequest() throws Exception { + loginDifferentTenant(); + NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.GENERAL, "Subject", "Text", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + long requestsCount = findNotificationRequests().getTotalElements(); + + NotificationRequest notificationRequest = NotificationRequest.builder() + .targets(List.of(target.getUuidId())) + .templateId(otherTemplate.getId()) + .additionalConfig(new NotificationRequestConfig()) + .build(); + doPost("/api/notification/request", notificationRequest).andExpect(status().isBadRequest()); + + assertThat(findNotificationRequests().getTotalElements()).isEqualTo(requestsCount); + } + + @Test + public void testNotificationRequest_systemTemplate_isDelivered() throws Exception { + loginSysAdmin(); + NotificationTemplate systemTemplate = createNotificationTemplate(NotificationType.GENERAL, "Subject", "Text", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRequest notificationRequest = NotificationRequest.builder() + .tenantId(tenantId) + .templateId(systemTemplate.getId()) + .originatorEntityId(tenantAdminUserId) + .targets(List.of(target.getUuidId())) + .build(); + NotificationRequestStats stats = submitNotificationRequestAndWait(notificationRequest); + assertThat(stats.getErrors()).isEmpty(); + assertThat(stats.getSent().get(NotificationDeliveryMethod.WEB).get()).isOne(); + } + private NotificationRequestStats submitNotificationRequestAndWait(NotificationRequest notificationRequest) throws Exception { SettableFuture future = SettableFuture.create(); notificationCenter.processNotificationRequest(notificationRequest.getTenantId(), notificationRequest, new FutureCallback<>() { diff --git a/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java index 93bf08af0a..fb45e6c772 100644 --- a/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java +++ b/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java @@ -46,6 +46,7 @@ import org.thingsboard.server.common.data.device.data.DeviceData; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.AlarmId; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.NotificationTemplateId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.common.data.notification.Notification; @@ -899,6 +900,136 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { }); } + @Test + public void testSaveNotificationRule_templateOfOtherTenant_returnsBadRequest() throws Exception { + loginDifferentTenant(); + NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = newDeviceCreatedRule(otherTemplate.getId(), List.of(target.getUuidId())); + doPost("/api/notification/rule", rule).andExpect(status().isBadRequest()); + + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName()); + } + + @Test + public void testSaveNotificationRule_targetOfOtherTenant_returnsForbidden() throws Exception { + loginDifferentTenant(); + NotificationTarget otherTarget = createNotificationTarget(savedDifferentTenantUser.getId()); + loginTenantAdmin(); + NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + + NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(otherTarget.getUuidId())); + doPost("/api/notification/rule", rule).andExpect(status().isForbidden()); + + NotificationTemplate alarmTemplate = createNotificationTemplate(NotificationType.ALARM, "Alarm", "Alarm", NotificationDeliveryMethod.WEB); + NotificationTarget ownTarget = createNotificationTarget(tenantAdminUserId); + NotificationRule alarmRule = new NotificationRule(); + alarmRule.setName("Alarm rule " + UUID.randomUUID()); + alarmRule.setEnabled(true); + alarmRule.setTemplateId(alarmTemplate.getId()); + alarmRule.setTriggerType(NotificationRuleTriggerType.ALARM); + AlarmNotificationRuleTriggerConfig triggerConfig = new AlarmNotificationRuleTriggerConfig(); + triggerConfig.setNotifyOn(Set.of(AlarmAction.CREATED)); + alarmRule.setTriggerConfig(triggerConfig); + EscalatedNotificationRuleRecipientsConfig recipientsConfig = new EscalatedNotificationRuleRecipientsConfig(); + recipientsConfig.setEscalationTable(Map.of( + 0, List.of(ownTarget.getUuidId()), + 60, List.of(otherTarget.getUuidId()) + )); + alarmRule.setRecipientsConfig(recipientsConfig); + doPost("/api/notification/rule", alarmRule).andExpect(status().isForbidden()); + + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName) + .doesNotContain(rule.getName(), alarmRule.getName()); + } + + @Test + public void testSaveNotificationRule_systemTemplate_isSaved() throws Exception { + loginSysAdmin(); + NotificationTemplate systemTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = saveNotificationRule(newDeviceCreatedRule(systemTemplate.getId(), List.of(target.getUuidId()))); + + try { + assertThat(rule.getId()).isNotNull(); + assertThat(rule.getTemplateId()).isEqualTo(systemTemplate.getId()); + } finally { + // the rule references a system template, which afterEach deletes before the tenant + notificationRuleService.deleteNotificationRuleById(tenantId, rule.getId()); + } + } + + @Test + public void testSaveNotificationRule_nonExistentTarget_returnsNotFound() throws Exception { + NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + + NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(UUID.randomUUID())); + doPost("/api/notification/rule", rule).andExpect(status().isNotFound()); + + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName()); + } + + @Test + public void testRuleProcessing_deliversOnlyToTargetsOfRuleTenant() throws Exception { + loginDifferentTenant(); + NotificationTarget otherTarget = createNotificationTarget(savedDifferentTenantUser.getId()); + loginTenantAdmin(); + NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Device created", "Device created", NotificationDeliveryMethod.WEB); + NotificationTarget ownTarget = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(ownTarget.getUuidId(), otherTarget.getUuidId())); + rule.setTenantId(tenantId); + notificationRuleService.saveNotificationRule(tenantId, rule); + notificationRulesCache.evict(tenantId); + + createDevice("Device 1", "default", "111"); + await().atMost(TIMEOUT, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).contains("Device created")); + + loginDifferentTenant(); + await().during(3, TimeUnit.SECONDS).atMost(5, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).doesNotContain("Device created")); + } + + @Test + public void testRuleProcessing_templateOfOtherTenant_deliversNothing() throws Exception { + loginDifferentTenant(); + NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Device created", "Device created", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = newDeviceCreatedRule(otherTemplate.getId(), List.of(target.getUuidId())); + rule.setTenantId(tenantId); + notificationRuleService.saveNotificationRule(tenantId, rule); + notificationRulesCache.evict(tenantId); + + createDevice("Device 1", "default", "111"); + await().during(3, TimeUnit.SECONDS).atMost(5, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).doesNotContain("Device created")); + } + + private NotificationRule newDeviceCreatedRule(NotificationTemplateId templateId, List targets) { + EntityActionNotificationRuleTriggerConfig triggerConfig = new EntityActionNotificationRuleTriggerConfig(); + triggerConfig.setEntityTypes(Set.of(EntityType.DEVICE)); + triggerConfig.setCreated(true); + + NotificationRule rule = new NotificationRule(); + rule.setName("Device created " + UUID.randomUUID()); + rule.setEnabled(true); + rule.setTemplateId(templateId); + rule.setTriggerType(NotificationRuleTriggerType.ENTITY_ACTION); + rule.setTriggerConfig(triggerConfig); + + DefaultNotificationRuleRecipientsConfig recipientsConfig = DefaultNotificationRuleRecipientsConfig.forTriggerType(NotificationRuleTriggerType.ENTITY_ACTION); + recipientsConfig.setTargets(targets); + rule.setRecipientsConfig(recipientsConfig); + return rule; + } + private R checkNotificationAfter(Callable action, BiConsumer check) throws Exception { if (getWsClient().getLastDataUpdate() == null) { getWsClient().subscribeForUnreadNotifications(10).waitForReply(true); diff --git a/application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java index 8df57c6a2a..e8ed81a632 100644 --- a/application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java +++ b/application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java @@ -9,9 +9,18 @@ import org.junit.Before; import org.junit.Test; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultMatcher; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.id.IdBased; +import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod; +import org.thingsboard.server.common.data.notification.NotificationRequest; +import org.thingsboard.server.common.data.notification.NotificationRequestConfig; import org.thingsboard.server.common.data.notification.NotificationType; +import org.thingsboard.server.common.data.notification.rule.DefaultNotificationRuleRecipientsConfig; +import org.thingsboard.server.common.data.notification.rule.NotificationRule; +import org.thingsboard.server.common.data.notification.rule.NotificationRuleInfo; +import org.thingsboard.server.common.data.notification.rule.trigger.config.EntityActionNotificationRuleTriggerConfig; +import org.thingsboard.server.common.data.notification.targets.NotificationTarget; import org.thingsboard.server.common.data.notification.template.EmailDeliveryMethodNotificationTemplate; import org.thingsboard.server.common.data.notification.template.NotificationTemplate; import org.thingsboard.server.common.data.notification.template.NotificationTemplateConfig; @@ -21,6 +30,7 @@ import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.List; import java.util.Map; +import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -86,6 +96,91 @@ public class NotificationTemplateApiTest extends AbstractNotificationApiTest { .containsOnly(generalNotificationTemplate.getId(), alarmNotificationTemplate.getId(), entityActionNotificationTemplate.getId()); } + @Test + public void testSaveTemplateWithReportRequiresPermissionOverReportUser() throws Exception { + UserId otherTenantUserId = getDifferentTenantUserId(); + + NotificationTemplate notificationTemplate = buildTemplateWithReport(otherTenantUserId); + save(notificationTemplate, status().isForbidden()); + + notificationTemplate.getConfiguration().setUserId(tenantAdminUserId); + save(notificationTemplate, status().isOk()); + } + + @Test + public void testNotificationRequestWithReportRequiresPermissionOverReportUser() throws Exception { + UserId otherTenantUserId = getDifferentTenantUserId(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRequest inlineTemplateRequest = NotificationRequest.builder() + .targets(List.of(target.getUuidId())) + .template(buildTemplateWithReport(otherTenantUserId)) + .additionalConfig(new NotificationRequestConfig()) + .build(); + doPost("/api/notification/request", inlineTemplateRequest).andExpect(status().isForbidden()); + + NotificationTemplate storedTemplate = saveTemplateWithReportUser(otherTenantUserId); + NotificationRequest storedTemplateRequest = NotificationRequest.builder() + .targets(List.of(target.getUuidId())) + .templateId(storedTemplate.getId()) + .additionalConfig(new NotificationRequestConfig()) + .build(); + doPost("/api/notification/request", storedTemplateRequest).andExpect(status().isForbidden()); + + assertThat(findNotificationRequests().getData()).isEmpty(); + } + + @Test + public void testSaveRuleWithReportTemplateRequiresPermissionOverReportUser() throws Exception { + UserId otherTenantUserId = getDifferentTenantUserId(); + NotificationTemplate storedTemplate = saveTemplateWithReportUser(otherTenantUserId); + + EntityActionNotificationRuleTriggerConfig triggerConfig = new EntityActionNotificationRuleTriggerConfig(); + triggerConfig.setEntityTypes(Set.of(EntityType.DEVICE)); + triggerConfig.setCreated(true); + NotificationRule rule = new NotificationRule(); + rule.setName("Device created"); + rule.setEnabled(true); + rule.setTemplateId(storedTemplate.getId()); + rule.setTriggerType(triggerConfig.getTriggerType()); + rule.setTriggerConfig(triggerConfig); + DefaultNotificationRuleRecipientsConfig recipientsConfig = DefaultNotificationRuleRecipientsConfig.forTriggerType(triggerConfig.getTriggerType()); + recipientsConfig.setTargets(List.of(createNotificationTarget(tenantAdminUserId).getUuidId())); + rule.setRecipientsConfig(recipientsConfig); + + doPost("/api/notification/rule", rule).andExpect(status().isForbidden()); + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName()); + } + + private UserId getDifferentTenantUserId() throws Exception { + loginDifferentTenant(); + UserId userId = savedDifferentTenantUser.getId(); + loginTenantAdmin(); + return userId; + } + + private NotificationTemplate buildTemplateWithReport(UserId userId) { + NotificationTemplate notificationTemplate = new NotificationTemplate(); + notificationTemplate.setName("Template with report"); + notificationTemplate.setNotificationType(NotificationType.GENERAL); + NotificationTemplateConfig config = new NotificationTemplateConfig(); + EmailDeliveryMethodNotificationTemplate emailTemplate = new EmailDeliveryMethodNotificationTemplate(); + emailTemplate.setEnabled(true); + emailTemplate.setSubject("Report"); + emailTemplate.setBody("Report"); + config.setDeliveryMethodsTemplates(Map.of(NotificationDeliveryMethod.EMAIL, emailTemplate)); + config.setAttachReport(true); + config.setUserId(userId); + notificationTemplate.setConfiguration(config); + return notificationTemplate; + } + + private NotificationTemplate saveTemplateWithReportUser(UserId userId) { + NotificationTemplate notificationTemplate = buildTemplateWithReport(userId); + notificationTemplate.setTenantId(tenantId); + return notificationTemplateService.saveNotificationTemplate(tenantId, notificationTemplate); + } + private String saveAndGetError(NotificationTemplate notificationTemplate, ResultMatcher statusMatcher) throws Exception { return getErrorMessage(save(notificationTemplate, statusMatcher)); } diff --git a/application/src/test/java/org/thingsboard/server/service/permission/UserPermissionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/permission/UserPermissionServiceTest.java index 3cf0b128dd..6253818743 100644 --- a/application/src/test/java/org/thingsboard/server/service/permission/UserPermissionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/permission/UserPermissionServiceTest.java @@ -10,6 +10,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; @@ -56,7 +57,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@ExtendWith(SpringExtension.class) +@ExtendWith({SpringExtension.class, MockitoExtension.class}) public class UserPermissionServiceTest { @Mock diff --git a/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java b/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java index 2469f8b703..aacf9ccb84 100644 --- a/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java @@ -358,6 +358,21 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { }); } + @Test + public void testSaveTbResourceWithUnknownIdIsRefused() { + TbResourceId resourceId = new TbResourceId(Uuids.timeBased()); + TbResource resource = new TbResource(); + resource.setId(resourceId); + resource.setResourceType(ResourceType.JS_MODULE); + resource.setTitle("My resource"); + resource.setFileName(DEFAULT_FILE_NAME); + + assertThatThrownBy(() -> tbResourceService.save(resource)) + .isInstanceOf(ThingsboardException.class) + .hasMessageContaining("wasn't found"); + assertThat(resourceService.findResourceInfoById(TenantId.SYS_TENANT_ID, resourceId)).isNull(); + } + @Test public void testSaveLwm2mTbResourceWithXXE() { TbResource resource = new TbResource(); diff --git a/application/src/test/java/org/thingsboard/server/service/ruleengine/DefaultRuleEngineCallServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ruleengine/DefaultRuleEngineCallServiceTest.java index e705abb72b..25b680cdb7 100644 --- a/application/src/test/java/org/thingsboard/server/service/ruleengine/DefaultRuleEngineCallServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ruleengine/DefaultRuleEngineCallServiceTest.java @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.ruleengine; +import org.awaitility.Awaitility; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,7 +11,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; -import org.testcontainers.shaded.org.awaitility.Awaitility; import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.DataConstants; diff --git a/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java b/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java index 4bc4fbed43..72de51dc2d 100644 --- a/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java +++ b/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java @@ -4,6 +4,8 @@ package org.thingsboard.server.service.scheduler.sql; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.util.concurrent.ListeningScheduledExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import org.awaitility.Awaitility; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -11,13 +13,22 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfileInfo; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.OtaPackageInfo; +import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; +import org.thingsboard.server.common.data.group.EntityGroup; +import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.scheduler.SchedulerEvent; import org.thingsboard.server.controller.AbstractControllerTest; +import org.thingsboard.server.dao.ota.DeviceGroupOtaPackageService; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.service.scheduler.DefaultSchedulerService; +import java.util.Map; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -31,7 +42,9 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.thingsboard.server.common.data.DataConstants.UPDATE_FIRMWARE; import static org.thingsboard.server.common.data.msg.TbMsgType.RPC_CALL_FROM_SERVER_TO_DEVICE; +import static org.thingsboard.server.common.data.ota.OtaPackageType.FIRMWARE; import static org.thingsboard.server.dao.scheduler.BaseSchedulerEventService.getOriginatorId; @DaoSqlTest @@ -43,6 +56,9 @@ public class SchedulerEventTest extends AbstractControllerTest { @Autowired TbServiceInfoProvider serviceInfoProvider; + @Autowired + DeviceGroupOtaPackageService deviceGroupOtaPackageService; + @Before public void before() throws Exception { loginTenantAdmin(); @@ -126,6 +142,52 @@ public class SchedulerEventTest extends AbstractControllerTest { ), any()); } + @Test + public void shouldNotUpdateFirmwareOfDeviceGroupOfAnotherTenant() throws Exception { + DeviceProfileInfo deviceProfile = doGet("/api/deviceProfileInfo/default", DeviceProfileInfo.class); + SaveOtaPackageInfoRequest firmwareRequest = new SaveOtaPackageInfoRequest(); + firmwareRequest.setDeviceProfileId(new DeviceProfileId(deviceProfile.getId().getId())); + firmwareRequest.setType(FIRMWARE); + firmwareRequest.setTitle("My firmware"); + firmwareRequest.setVersion("v1.0"); + firmwareRequest.setUsesUrl(false); + OtaPackageInfo firmware = doPost("/api/otaPackage", firmwareRequest, OtaPackageInfo.class); + + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Devices"); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + loginTenantAdmin(); + + Object originalExecutor = ReflectionTestUtils.getField(schedulerService, "scheduledExecutor"); + ListeningScheduledExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor()); + ReflectionTestUtils.setField(schedulerService, "scheduledExecutor", executor); + try { + SchedulerEvent schedulerEvent = new SchedulerEvent(); + schedulerEvent.setName("Firmware update"); + schedulerEvent.setType(UPDATE_FIRMWARE); + schedulerEvent.setEnabled(true); + ObjectNode schedule = JacksonUtil.newObjectNode(); + schedule.put("startTime", Long.MAX_VALUE); + schedule.put("timezone", "UTC"); + schedulerEvent.setSchedule(schedule); + schedulerEvent.setOriginatorId(otherTenantGroup.getId()); + ObjectNode configuration = JacksonUtil.newObjectNode(); + configuration.set("msgBody", JacksonUtil.valueToTree(firmware.getId())); + schedulerEvent.setConfiguration(configuration); + SchedulerEvent savedSchedulerEvent = doPost("/api/schedulerEvent", schedulerEvent, SchedulerEvent.class); + + Map eventsMetaData = (Map) ReflectionTestUtils.getField(schedulerService, "eventsMetaData"); + Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> eventsMetaData.containsKey(savedSchedulerEvent.getId())); + ReflectionTestUtils.invokeMethod(schedulerService, "processEvent", tenantId, savedSchedulerEvent.getId()); + } finally { + ReflectionTestUtils.setField(schedulerService, "scheduledExecutor", originalExecutor); + executor.shutdownNow(); + } + assertThat(deviceGroupOtaPackageService.findDeviceGroupOtaPackageByGroupIdAndType(otherTenantGroup.getId(), FIRMWARE)).isNull(); + } + private SchedulerEvent createSchedulerEvent(EntityId originatorId, boolean enabled) { SchedulerEvent schedulerEvent = new SchedulerEvent(); schedulerEvent.setName("TestRpc"); diff --git a/application/src/test/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcherTest.java b/application/src/test/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcherTest.java new file mode 100644 index 0000000000..74b08353c7 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcherTest.java @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.security.auth.jwt; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.API_ENTRY_POINT; +import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.CURRENT_USER_BY_ID_ENTRY_POINT; +import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.DEVICE_API_ENTRY_POINT; +import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.DEVICE_CONNECTIVITY_CERTIFICATE_DOWNLOAD_ENTRY_POINT; +import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.FORM_BASED_LOGIN_ENTRY_POINT; +import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.LOGIN_LOGO_ENTRY_POINT; +import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.SETUP_ENTRY_POINT; + +class SkipPathRequestMatcherTest { + + private final SkipPathRequestMatcher matcher = new SkipPathRequestMatcher( + List.of(FORM_BASED_LOGIN_ENTRY_POINT, DEVICE_API_ENTRY_POINT, SETUP_ENTRY_POINT, + DEVICE_CONNECTIVITY_CERTIFICATE_DOWNLOAD_ENTRY_POINT, LOGIN_LOGO_ENTRY_POINT), + List.of(API_ENTRY_POINT, CURRENT_USER_BY_ID_ENTRY_POINT)); + + @Test + void processesProtectedApiPaths() { + assertThat(matcher.matches(request("/api/device/123"))).isTrue(); + assertThat(matcher.matches(request("/api/user/0a1b2c3d-0000-1111-2222-333344445555"))).isTrue(); + } + + @Test + void skipsListedPaths() { + assertThat(matcher.matches(request("/api/auth/login"))).isFalse(); + assertThat(matcher.matches(request("/api/v1/token/telemetry"))).isFalse(); + assertThat(matcher.matches(request("/api/v1"))).isFalse(); + assertThat(matcher.matches(request("/api/noauth/setup/status"))).isFalse(); + assertThat(matcher.matches(request("/api/device-connectivity/mqtt/certificate/download"))).isFalse(); + } + + @Test + void singleSegmentWildcardsDoNotSpanSegments() { + assertThat(matcher.matches(request("/api/noauth/whiteLabel/loginLogo/abc/def"))).isFalse(); + assertThat(matcher.matches(request("/api/noauth/whiteLabel/loginLogo/abc/def/ghi"))).isTrue(); + } + + @Test + void doesNotSkipNearMisses() { + assertThat(matcher.matches(request("/api/auth/login/"))).isTrue(); + assertThat(matcher.matches(request("/api/auth/loginx"))).isTrue(); + assertThat(matcher.matches(request("/API/auth/login"))).isFalse(); + } + + @Test + void ignoresPathsOutsideApi() { + assertThat(matcher.matches(request("/static/index.html"))).isFalse(); + } + + private static MockHttpServletRequest request(String path) { + MockHttpServletRequest request = new MockHttpServletRequest("GET", path); + request.setServletPath(path); + return request; + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapperTest.java b/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapperTest.java new file mode 100644 index 0000000000..df66b09e1b --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapperTest.java @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.security.auth.oauth2; + +import com.sun.net.httpserver.HttpServer; +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; +import org.springframework.security.oauth2.core.user.DefaultOAuth2User; +import org.thingsboard.common.util.SsrfProtectionValidator; +import org.thingsboard.server.common.data.oauth2.MapperType; +import org.thingsboard.server.common.data.oauth2.OAuth2Client; +import org.thingsboard.server.common.data.oauth2.OAuth2CustomMapperConfig; +import org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig; +import org.thingsboard.server.dao.oauth2.OAuth2User; +import org.thingsboard.server.service.security.model.SecurityUser; + +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class CustomOAuth2ClientMapperTest { + + private static final String PROVIDER_ACCESS_TOKEN = "provider-access-token"; + + private final List> receivedHeaders = new CopyOnWriteArrayList<>(); + private final CustomOAuth2ClientMapper mapper = new CustomOAuth2ClientMapper() { + @Override + protected SecurityUser getOrCreateSecurityUserFromOAuth2User(OAuth2User oauth2User, OAuth2Client oAuth2Client) { + return null; + } + }; + + private HttpServer server; + private boolean uriValidationEnabled; + private OAuth2AuthenticationToken token; + + @BeforeEach + public void setUp() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/mapper", exchange -> { + Map headers = new HashMap<>(); + String authorization = exchange.getRequestHeaders().getFirst("Authorization"); + if (authorization != null) { + headers.put("Authorization", authorization); + } + String providerToken = exchange.getRequestHeaders().getFirst(PROVIDER_ACCESS_TOKEN); + if (providerToken != null) { + headers.put(PROVIDER_ACCESS_TOKEN, providerToken); + } + receivedHeaders.add(headers); + byte[] body = "{\"email\":\"user@example.com\"}".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + exchange.getResponseBody().write(body); + exchange.close(); + }); + server.start(); + + uriValidationEnabled = SsrfProtectionValidator.isEnabled(); + SsrfProtectionValidator.setEnabled(false); + + token = mock(OAuth2AuthenticationToken.class); + when(token.getPrincipal()).thenReturn(new DefaultOAuth2User(List.of(), Map.of("email", "user@example.com"), "email")); + } + + @AfterEach + public void tearDown() { + server.stop(0); + SsrfProtectionValidator.setEnabled(uriValidationEnabled); + } + + @Test + public void sendsOwnCredentialsAndTokenWhenConfigured() { + login(client("user", "pass", true), "token-1"); + login(client("user2", "pass2", true), "token-2"); + + assertThat(receivedHeaders).containsExactly( + Map.of("Authorization", basic("user", "pass"), PROVIDER_ACCESS_TOKEN, "token-1"), + Map.of("Authorization", basic("user2", "pass2"), PROVIDER_ACCESS_TOKEN, "token-2")); + } + + @Test + public void sendsNoAuthorizationHeaderWhenClientHasNoCredentials() { + login(client("user", "pass", true), "token-1"); + login(client(null, null, false), "token-2"); + + assertThat(receivedHeaders).hasSize(2); + assertThat(receivedHeaders.get(1)).isEmpty(); + } + + @Test + public void sendsNoProviderTokenWhenSendTokenIsOff() { + login(client("user", "pass", true), "token-1"); + login(client("user", "pass", false), "token-2"); + + assertThat(receivedHeaders).hasSize(2); + assertThat(receivedHeaders.get(1)).isEqualTo(Map.of("Authorization", basic("user", "pass"))); + } + + private void login(OAuth2Client client, String providerAccessToken) { + mapper.getOrCreateUserByClientPrincipal(mock(HttpServletRequest.class), token, providerAccessToken, client); + } + + private OAuth2Client client(String username, String password, boolean sendToken) { + OAuth2CustomMapperConfig custom = OAuth2CustomMapperConfig.builder() + .url("http://127.0.0.1:" + server.getAddress().getPort() + "/mapper") + .username(username) + .password(password) + .sendToken(sendToken) + .build(); + OAuth2Client client = new OAuth2Client(); + client.setMapperConfig(OAuth2MapperConfig.builder().type(MapperType.CUSTOM).custom(custom).build()); + return client; + } + + private static String basic(String username, String password) { + return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8)); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java b/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java index 9a46775ede..3c71a289d4 100644 --- a/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java @@ -16,9 +16,12 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.MailService; import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.permission.MergedUserPermissions; import org.thingsboard.server.common.data.security.UserCredentials; import org.thingsboard.server.common.data.security.model.SecuritySettings; import org.thingsboard.server.common.data.security.model.UserPasswordPolicy; @@ -28,6 +31,8 @@ import org.thingsboard.server.dao.settings.AdminSettingsService; import org.thingsboard.server.dao.settings.SecuritySettingsService; import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.dao.wl.WhiteLabelingService; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.security.model.token.AccessJwtToken; import org.thingsboard.server.service.security.model.token.JwtTokenFactory; import org.thingsboard.server.service.security.permission.UserPermissionsService; @@ -37,6 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -252,4 +258,33 @@ public class DefaultSystemSecurityServiceTest { return request; } + @Test + public void testCreateUserAccessTokenForUserOfSameTenant() throws Exception { + User user = createUser(tenantId); + when(userService.findUserById(tenantId, userId)).thenReturn(user); + when(userService.findUserCredentialsByUserId(tenantId, userId)).thenReturn(userCredentials); + when(userPermissionsService.getMergedPermissions(user, false)).thenReturn(mock(MergedUserPermissions.class)); + AccessJwtToken token = mock(AccessJwtToken.class); + when(tokenFactory.createAccessJwtToken(any(SecurityUser.class))).thenReturn(token); + + assertThat(systemSecurityService.createUserAccessToken(tenantId, userId)).isSameAs(token); + } + + @Test + public void testCreateUserAccessTokenForUserOfOtherTenantFails() { + when(userService.findUserById(tenantId, userId)).thenReturn(createUser(TenantId.fromUUID(UUID.randomUUID()))); + + assertThatThrownBy(() -> systemSecurityService.createUserAccessToken(tenantId, userId)) + .isInstanceOfSatisfying(ThingsboardException.class, e -> assertThat(e.getErrorCode()).isEqualTo(ThingsboardErrorCode.BAD_REQUEST_PARAMS)); + + verify(tokenFactory, never()).createAccessJwtToken(any()); + } + + private User createUser(TenantId userTenantId) { + User user = new User(userId); + user.setTenantId(userTenantId); + user.setEmail(username); + return user; + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java new file mode 100644 index 0000000000..a27ad861f8 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.subscription; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.alarm.Alarm; +import org.thingsboard.server.common.data.id.AlarmId; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.query.AlarmData; +import org.thingsboard.server.common.data.query.AlarmDataPageLink; +import org.thingsboard.server.common.data.query.AlarmDataQuery; +import org.thingsboard.server.common.data.query.SingleEntityFilter; +import org.thingsboard.server.dao.alarm.AlarmService; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.ws.WebSocketService; +import org.thingsboard.server.service.ws.WebSocketSessionRef; +import org.thingsboard.server.service.ws.telemetry.cmd.v2.AlarmDataUpdate; +import org.thingsboard.server.service.ws.telemetry.cmd.v2.CmdUpdate; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; + +@ExtendWith(MockitoExtension.class) +public class TbAlarmDataSubCtxTest { + + private final String sessionId = "session"; + private final int cmdId = 7; + private final int maxEntitiesPerAlarmSubscription = 100; + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + private final DeviceId deviceId = new DeviceId(UUID.randomUUID()); + + @Mock + private WebSocketService webSocketService; + @Mock + private AlarmService alarmService; + @Mock + private WebSocketSessionRef sessionRef; + @Mock + private SecurityUser securityUser; + + private TbAlarmDataSubCtx subCtx; + + @BeforeEach + public void setUp() { + lenient().when(sessionRef.getSessionId()).thenReturn(sessionId); + lenient().when(sessionRef.getSecurityCtx()).thenReturn(securityUser); + lenient().when(securityUser.getTenantId()).thenReturn(tenantId); + subCtx = new TbAlarmDataSubCtx("service", webSocketService, mock(), mock(), mock(), new SubscriptionServiceStatistics(), + alarmService, sessionRef, cmdId, maxEntitiesPerAlarmSubscription, 10); + } + + @Test + public void shouldBeOwnerScoped_onlyWhenQueryHasNoEntityFilter() { + assertThat(subCtx.isOwnerScoped()).isFalse(); + + subCtx.setQuery(query(null, 0)); + assertThat(subCtx.isOwnerScoped()).isTrue(); + + subCtx.setQuery(query(new SingleEntityFilter(), 0)); + assertThat(subCtx.isOwnerScoped()).isFalse(); + } + + @Test + public void shouldSendNothing_whenOwnerScopedRefreshReturnsTheSamePage() { + AlarmDataQuery query = query(null, 0); + subCtx.setQuery(query); + List alarms = List.of(alarmData(), alarmData()); + subCtx.setAlarms(new PageData<>(alarms, 1, 2, false)); + given(alarmService.findAlarmDataByQuery(eq(tenantId), any(), any(), same(query))) + .willReturn(new PageData<>(new ArrayList<>(alarms), 1, 2, false)); + + subCtx.checkAndResetInvocationCounter(); + + then(alarmService).should().findAlarmDataByQuery(eq(tenantId), any(), any(), same(query)); + then(webSocketService).shouldHaveNoInteractions(); + } + + @Test + public void shouldSendTheFreshPage_whenOwnerScopedRefreshReturnsAChangedPage() { + AlarmDataQuery query = query(null, 0); + subCtx.setQuery(query); + subCtx.setAlarms(new PageData<>(List.of(alarmData()), 1, 1, false)); + PageData fresh = new PageData<>(List.of(alarmData(), alarmData()), 1, 2, false); + given(alarmService.findAlarmDataByQuery(eq(tenantId), any(), any(), same(query))).willReturn(fresh); + + subCtx.checkAndResetInvocationCounter(); + + ArgumentCaptor updateCaptor = ArgumentCaptor.forClass(CmdUpdate.class); + then(webSocketService).should().sendUpdate(eq(sessionId), updateCaptor.capture()); + AlarmDataUpdate update = (AlarmDataUpdate) updateCaptor.getValue(); + assertThat(update.getCmdId()).isEqualTo(cmdId); + assertThat(update.getData()).isSameAs(fresh); + assertThat(update.getUpdate()).isNull(); + assertThat(update.getAllowedEntities()).isEqualTo(maxEntitiesPerAlarmSubscription); + assertThat(subCtx.getAlarms()).isSameAs(fresh); + assertThat(subCtx.getAlarmsMap()).hasSize(2); + } + + @Test + public void shouldNotTouchAlarms_whenCleanupCalledWithoutTimeWindow() { + subCtx.setQuery(query(new SingleEntityFilter(), 0)); + + subCtx.cleanupOldAlarms(); + + then(alarmService).shouldHaveNoInteractions(); + then(webSocketService).shouldHaveNoInteractions(); + } + + private static AlarmDataQuery query(SingleEntityFilter entityFilter, long timeWindow) { + AlarmDataPageLink pageLink = new AlarmDataPageLink(10, 0, null, null, false, false, 0, 0, timeWindow, null, null, null, null); + return new AlarmDataQuery(entityFilter, pageLink, null, null, null, null); + } + + private AlarmData alarmData() { + Alarm alarm = new Alarm(new AlarmId(UUID.randomUUID())); + alarm.setOriginator(deviceId); + return new AlarmData(alarm, deviceId); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java index d104f8d4f4..8a50384edc 100644 --- a/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.subscription; import org.apache.commons.lang3.RandomStringUtils; @@ -32,10 +33,12 @@ import java.util.Map; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.never; @ExtendWith(MockitoExtension.class) public class TbEntityDataSubCtxTest { @@ -57,7 +60,7 @@ public class TbEntityDataSubCtxTest { @BeforeEach public void setUp() { - when(webSocketSessionRef.getSessionId()).thenReturn(sessionId); + lenient().when(webSocketSessionRef.getSessionId()).thenReturn(sessionId); subCtx = new TbEntityDataSubCtx(serviceId, webSocketService, mock(), mock(), mock(), mock(), webSocketSessionRef, cmdId, maxEntitiesPerDataSubscription); Map subToEntityIdMap = new HashMap<>(); @@ -114,4 +117,64 @@ public class TbEntityDataSubCtxTest { assertThat(entityDataUpdate.getAllowedEntities()).isEqualTo(maxEntitiesPerDataSubscription); } + @Test + public void shouldSendOnlyChangedEntity_whenEntityFieldValueChanged() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + setCurrentData(entityWithFields(deviceId, "name", "Thermostat"), entityWithFields(otherId, "name", "Pump")); + Map changedFields = Map.of("name", new TsValue(2L, "Thermostat 2")); + + subCtx.onSameEntities(Map.of( + deviceId, new EntityData(deviceId, false, false, Map.of(EntityKeyType.ENTITY_FIELD, changedFields), null), + otherId, entityWithFields(otherId, "name", "Pump"))); + + ArgumentCaptor cmdUpdateCaptor = ArgumentCaptor.forClass(CmdUpdate.class); + then(webSocketService).should().sendUpdate(eq(sessionId), cmdUpdateCaptor.capture()); + EntityDataUpdate update = (EntityDataUpdate) cmdUpdateCaptor.getValue(); + assertThat(update.getCmdId()).isEqualTo(cmdId); + assertThat(update.getData()).isNull(); + assertThat(update.getUpdate()).singleElement().satisfies(entityData -> { + assertThat(entityData.getEntityId()).isEqualTo(deviceId); + assertThat(entityData.getLatest()).isEqualTo(Map.of(EntityKeyType.ENTITY_FIELD, changedFields)); + }); + assertThat(currentFields(deviceId)).isEqualTo(changedFields); + } + + @Test + public void shouldSendNothing_whenEntityFieldValuesUnchanged() { + setCurrentData(entityWithFields(deviceId, "name", "Thermostat")); + + subCtx.onSameEntities(Map.of(deviceId, entityWithFields(deviceId, "name", "Thermostat"))); + + then(webSocketService).should(never()).sendUpdate(any(), any()); + } + + @Test + public void shouldSkipEntity_whenFreshEntityFieldsMissingOrEmpty() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + setCurrentData(entityWithFields(deviceId, "name", "Thermostat"), entityWithFields(otherId, "name", "Pump")); + + subCtx.onSameEntities(Map.of(otherId, new EntityData(otherId, false, false, new HashMap<>(Map.of(EntityKeyType.ENTITY_FIELD, Map.of())), null))); + + then(webSocketService).should(never()).sendUpdate(any(), any()); + assertThat(currentFields(deviceId)).containsOnlyKeys("name"); + assertThat(currentFields(otherId)).containsOnlyKeys("name"); + } + + private void setCurrentData(EntityData... entities) { + ReflectionTestUtils.setField(subCtx, "data", new PageData<>(List.of(entities), 1, entities.length, false)); + } + + @SuppressWarnings("unchecked") + private Map currentFields(EntityId entityId) { + PageData data = (PageData) ReflectionTestUtils.getField(subCtx, "data"); + return data.getData().stream().filter(entityData -> entityData.getEntityId().equals(entityId)) + .findFirst().orElseThrow().getLatest().get(EntityKeyType.ENTITY_FIELD); + } + + private static EntityData entityWithFields(EntityId entityId, String key, String value) { + Map> latest = new HashMap<>(); + latest.put(EntityKeyType.ENTITY_FIELD, new HashMap<>(Map.of(key, new TsValue(1L, value)))); + return new EntityData(entityId, false, false, latest, null); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/sync/vc/VersionControlTest.java b/application/src/test/java/org/thingsboard/server/service/sync/vc/VersionControlTest.java index c05cdfe553..41f3a077bb 100644 --- a/application/src/test/java/org/thingsboard/server/service/sync/vc/VersionControlTest.java +++ b/application/src/test/java/org/thingsboard/server/service/sync/vc/VersionControlTest.java @@ -2605,7 +2605,7 @@ public class VersionControlTest extends AbstractControllerTest { reportConfig.put("type", "pdf"); reportConfig.put("timezone", "Europe/Kiev"); reportConfig.put("useCurrentUserCredentials", true); - reportConfig.put("userId", "7a306270-4820-11f0-bc58-39b3596e763d"); + reportConfig.put("userId", tenantAdmin1.getId().toString()); reportConfig.put("dashboardId", dashboardId.toString()); reportConfig.put("state", ""); diff --git a/application/src/test/java/org/thingsboard/server/utils/MiscUtilsTest.java b/application/src/test/java/org/thingsboard/server/utils/MiscUtilsTest.java new file mode 100644 index 0000000000..1680f5a739 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/utils/MiscUtilsTest.java @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.utils; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +import java.net.URI; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MiscUtilsTest { + + @Test + public void testBaseUrlUsesForwardedHttpsScheme() { + MockHttpServletRequest request = newRequest(); + request.addHeader("x-forwarded-proto", "https"); + + assertThat(MiscUtils.constructBaseUrl(request)).isEqualTo("https://localhost:443"); + } + + @Test + public void testForwardedSchemeIsLowerCased() { + MockHttpServletRequest request = newRequest(); + request.addHeader("x-forwarded-proto", "HTTPS"); + + assertThat(MiscUtils.getScheme(request)).isEqualTo("https"); + } + + @Test + public void testNonHttpForwardedSchemeFallsBackToHttp() { + MockHttpServletRequest request = newRequest(); + request.addHeader("x-forwarded-proto", "ftp"); + + assertThat(MiscUtils.getScheme(request)).isEqualTo("http"); + URI baseUrl = URI.create(MiscUtils.constructBaseUrl(request)); + assertThat(baseUrl.getScheme()).isEqualTo("http"); + assertThat(baseUrl.getHost()).isEqualTo("localhost"); + } + + @Test + public void testNonHttpForwardedSchemeOnSecureRequestFallsBackToHttps() { + MockHttpServletRequest request = newRequest(); + request.addHeader("x-forwarded-proto", "ftp"); + request.setSecure(true); + + assertThat(MiscUtils.getScheme(request)).isEqualTo("https"); + assertThat(URI.create(MiscUtils.constructBaseUrl(request)).getHost()).isEqualTo("localhost"); + } + + @Test + public void testRequestSchemeIsUsedWithoutForwardedHeader() { + MockHttpServletRequest request = newRequest(); + request.setScheme("https"); + + assertThat(MiscUtils.getScheme(request)).isEqualTo("https"); + } + + @Test + public void testNonHttpRequestSchemeFallsBackToHttp() { + MockHttpServletRequest request = newRequest(); + request.setScheme("ftp"); + + assertThat(MiscUtils.getScheme(request)).isEqualTo("http"); + } + + private MockHttpServletRequest newRequest() { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServerName("localhost"); + return request; + } + +} diff --git a/common/actor/pom.xml b/common/actor/pom.xml index fa3037517c..d4932cd35d 100644 --- a/common/actor/pom.xml +++ b/common/actor/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/agent-api/pom.xml b/common/agent-api/pom.xml index 4b52297231..c6dbbc1d89 100644 --- a/common/agent-api/pom.xml +++ b/common/agent-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/cache/pom.xml b/common/cache/pom.xml index 0c4ca035a0..d6608c3fe3 100644 --- a/common/cache/pom.xml +++ b/common/cache/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/cache/src/main/java/org/thingsboard/server/cache/RedisTbTransactionalCache.java b/common/cache/src/main/java/org/thingsboard/server/cache/RedisTbTransactionalCache.java index 0a43ef9e10..5a6bfe7fe6 100644 --- a/common/cache/src/main/java/org/thingsboard/server/cache/RedisTbTransactionalCache.java +++ b/common/cache/src/main/java/org/thingsboard/server/cache/RedisTbTransactionalCache.java @@ -22,8 +22,8 @@ import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.thingsboard.server.common.data.FstStatsService; import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPool; +import redis.clients.jedis.RedisClusterClient; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisRedirectionException; import redis.clients.jedis.util.JedisClusterCRC16; @@ -259,7 +259,11 @@ public abstract class RedisTbTransactionalCache - * Commands sent through the cluster command executor renew the slot map themselves, on MOVED and on repeated - * connection errors. Commands that need one node connection (WATCH/MULTI, a script pinned to one slot) borrow it - * through {@link #getConnectionFromSlot(int)}, which bypasses that executor. When such a command fails because the - * cluster topology changed, the caller must call {@link #renewSlotCache()}. Otherwise every later call goes to the - * old node again, and if that node's address is gone, it fails until the JVM restarts. - */ -public class TbJedisCluster extends JedisCluster { - - /** - * @param topologyRefreshPeriod period of the background slot map refresh, or {@code null} to disable it - */ - public TbJedisCluster(Set clusterNodes, JedisClientConfig clientConfig, GenericObjectPoolConfig poolConfig, - Duration topologyRefreshPeriod, int maxAttempts) { - // Same retry budget as the JedisCluster constructor used by Spring's JedisConnectionFactory. - super(clusterNodes, clientConfig, poolConfig, topologyRefreshPeriod, maxAttempts, - Duration.ofMillis((long) clientConfig.getSocketTimeoutMillis() * maxAttempts)); - } - - /** - * Reloads the slot map from the cluster. Seed nodes are asked first, so this works even when every known node - * address has changed. Returns immediately if another thread is already renewing it. - */ - public void renewSlotCache() { - ((ClusterConnectionProvider) provider).renewSlotCache(); - } - -} diff --git a/common/cache/src/main/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactory.java b/common/cache/src/main/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactory.java index f1efc0276a..ed2a253dac 100644 --- a/common/cache/src/main/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactory.java +++ b/common/cache/src/main/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactory.java @@ -6,26 +6,36 @@ import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.data.redis.connection.RedisClusterConfiguration; import org.springframework.data.redis.connection.jedis.JedisClientConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.data.redis.util.RedisClientLibraryInfo; import org.thingsboard.server.common.data.StringUtils; +import redis.clients.jedis.ClientSetInfoConfig; import redis.clients.jedis.Connection; import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.DriverInfo; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisClientConfig; -import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.RedisClusterClient; +import redis.clients.jedis.providers.ClusterConnectionProvider; import java.time.Duration; import java.util.Set; import java.util.stream.Collectors; /** - * Cluster connection factory that creates a {@link TbJedisCluster}, so the cache can renew the Jedis slot map after - * a topology change, and the slot map is also refreshed in the background. + * Cluster connection factory whose Jedis slot map can be renewed on demand and is also refreshed in the background. + *

+ * Commands sent through the cluster command executor renew the slot map themselves, on MOVED and on repeated + * connection errors. Commands that need one node connection (WATCH/MULTI, a script pinned to one slot) borrow it + * through {@link RedisClusterClient#getConnectionFromSlot(int)}, which bypasses that executor. When such a command + * fails because the cluster topology changed, the caller must call {@link #renewSlotCache()}. Otherwise every later + * call goes to the old node again, and if that node's address is gone, it fails until the JVM restarts. */ public class TbJedisClusterConnectionFactory extends JedisConnectionFactory { - private static final int DEFAULT_MAX_REDIRECTS = 5; // same default as JedisConnectionFactory#createCluster + private static final int DEFAULT_MAX_REDIRECTS = 5; // same default as JedisConnectionFactory#createRedisClusterClient private final Duration topologyRefreshPeriod; + private volatile ClusterConnectionProvider connectionProvider; /** * @param topologyRefreshPeriod period of the background slot map refresh, or {@code null} to disable it @@ -37,12 +47,33 @@ public class TbJedisClusterConnectionFactory extends JedisConnectionFactory { } @Override - protected JedisCluster createCluster(RedisClusterConfiguration clusterConfig, GenericObjectPoolConfig poolConfig) { + protected RedisClusterClient createRedisClusterClient(RedisClusterConfiguration clusterConfig) { Set nodes = clusterConfig.getClusterNodes().stream() .map(node -> new HostAndPort(node.getHost(), node.getPort())) .collect(Collectors.toSet()); int maxRedirects = clusterConfig.getMaxRedirects() != null ? clusterConfig.getMaxRedirects() : DEFAULT_MAX_REDIRECTS; - return new TbJedisCluster(nodes, createClusterClientConfig(clusterConfig), poolConfig, topologyRefreshPeriod, maxRedirects); + JedisClientConfig clientConfig = createClusterClientConfig(clusterConfig); + GenericObjectPoolConfig poolConfig = getPoolConfig(); + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, clientConfig, poolConfig, topologyRefreshPeriod); + + RedisClusterClient.Builder builder = RedisClusterClient.builder(); + builder.nodes(nodes).clientConfig(clientConfig).maxAttempts(maxRedirects).poolConfig(poolConfig); + getClientConfiguration().getClientCustomizer().ifPresent(customizer -> customizer.customize(builder)); + builder.connectionProvider(provider); + RedisClusterClient client = builder.build(); + connectionProvider = provider; + return client; + } + + /** + * Reloads the slot map from the cluster. Seed nodes are asked first, so this works even when every known node + * address has changed. Returns immediately if another thread is already renewing it, or if the factory is not started. + */ + public void renewSlotCache() { + ClusterConnectionProvider provider = connectionProvider; + if (provider != null) { + provider.renewSlotCache(); + } } /** @@ -54,6 +85,9 @@ public class TbJedisClusterConnectionFactory extends JedisConnectionFactory { clientConfiguration.getClientName().ifPresent(builder::clientName); builder.connectionTimeoutMillis(Math.toIntExact(clientConfiguration.getConnectTimeout().toMillis())); builder.socketTimeoutMillis(Math.toIntExact(clientConfiguration.getReadTimeout().toMillis())); + builder.clientSetInfoConfig(new ClientSetInfoConfig(DriverInfo.builder() + .addUpstreamDriver(RedisClientLibraryInfo.FRAMEWORK_NAME, RedisClientLibraryInfo.getVersion()) + .build())); builder.database(getDatabase()); if (StringUtils.isNotEmpty(clusterConfig.getUsername())) { builder.user(clusterConfig.getUsername()); @@ -65,7 +99,7 @@ public class TbJedisClusterConnectionFactory extends JedisConnectionFactory { clientConfiguration.getHostnameVerifier().ifPresent(builder::hostnameVerifier); clientConfiguration.getSslParameters().ifPresent(builder::sslParameters); } - clientConfiguration.getCustomizer().ifPresent(customizer -> customizer.customize(builder)); + clientConfiguration.getClientConfigCustomizer().ifPresent(customizer -> customizer.customize(builder)); return builder.build(); } diff --git a/common/cache/src/test/java/org/thingsboard/server/cache/RedisTbTransactionalCacheTest.java b/common/cache/src/test/java/org/thingsboard/server/cache/RedisTbTransactionalCacheTest.java index b3c77c0864..ab3b26c1c0 100644 --- a/common/cache/src/test/java/org/thingsboard/server/cache/RedisTbTransactionalCacheTest.java +++ b/common/cache/src/test/java/org/thingsboard/server/cache/RedisTbTransactionalCacheTest.java @@ -11,10 +11,10 @@ import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisScriptingCommands; import org.springframework.data.redis.connection.ReturnType; -import org.springframework.data.redis.connection.jedis.JedisClusterConnection; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.exceptions.JedisMovedDataException; import java.nio.charset.StandardCharsets; @@ -25,6 +25,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -41,7 +42,8 @@ class RedisTbTransactionalCacheTest { private static final String CACHE_NAME = "testCache"; - private JedisConnectionFactory connectionFactory; + private TbJedisClusterConnectionFactory connectionFactory; + private RedisConnection connection; private RedisScriptingCommands scriptingCommands; @Test @@ -86,7 +88,7 @@ class RedisTbTransactionalCacheTest { @Test void givenClusterTopologyError_whenRetryOnClusterTopologyChange_thenRenewsSlotMapAndRetriesOnce() { TestRedisCache cache = createCache(""); - TbJedisCluster cluster = mockCluster(); + TbJedisClusterConnectionFactory cluster = mockClusterAwareFactory(); AtomicInteger attempts = new AtomicInteger(); String result = cache.retryOnClusterTopologyChange(() -> { @@ -104,7 +106,7 @@ class RedisTbTransactionalCacheTest { @Test void givenClusterTopologyErrorTwice_whenRetryOnClusterTopologyChange_thenThrowsAfterOneRetry() { TestRedisCache cache = createCache(""); - TbJedisCluster cluster = mockCluster(); + TbJedisClusterConnectionFactory cluster = mockClusterAwareFactory(); AtomicInteger attempts = new AtomicInteger(); assertThatThrownBy(() -> cache.retryOnClusterTopologyChange(() -> { @@ -119,7 +121,7 @@ class RedisTbTransactionalCacheTest { @Test void givenOtherError_whenRetryOnClusterTopologyChange_thenThrowsWithoutRenewing() { TestRedisCache cache = createCache(""); - TbJedisCluster cluster = mockCluster(); + TbJedisClusterConnectionFactory cluster = mockClusterAwareFactory(); AtomicInteger attempts = new AtomicInteger(); assertThatThrownBy(() -> cache.retryOnClusterTopologyChange(() -> { @@ -142,7 +144,20 @@ class RedisTbTransactionalCacheTest { })).isInstanceOf(RedisConnectionFailureException.class); assertThat(attempts).hasValue(1); - verify(connectionFactory, never()).getClusterConnection(); + verify(connectionFactory, never()).renewSlotCache(); + } + + @Test + void givenWatchFailsAndCloseFails_whenWatch_thenThrowsWatchErrorWithCloseErrorSuppressed() { + TestRedisCache cache = createCache(""); + JedisConnectionException watchError = new JedisConnectionException("Failed to connect to 10.0.0.1:6379."); + JedisException closeError = new JedisException("Could not return the broken resource to the pool"); + doThrow(watchError).when(connection).watch(any(byte[][].class)); + doThrow(closeError).when(connection).close(); + + assertThatThrownBy(() -> cache.watch(new byte[][]{cache.getRawKey("myKey")})) + .isSameAs(watchError) + .hasSuppressedException(closeError); } @Test @@ -155,18 +170,14 @@ class RedisTbTransactionalCacheTest { assertThat(RedisTbTransactionalCache.isClusterTopologyError(new IllegalStateException())).isFalse(); } - private TbJedisCluster mockCluster() { - TbJedisCluster cluster = mock(TbJedisCluster.class); - JedisClusterConnection clusterConnection = mock(JedisClusterConnection.class); - when(clusterConnection.getNativeConnection()).thenReturn(cluster); + private TbJedisClusterConnectionFactory mockClusterAwareFactory() { when(connectionFactory.isRedisClusterAware()).thenReturn(true); - when(connectionFactory.getClusterConnection()).thenReturn(clusterConnection); - return cluster; + return connectionFactory; } private TestRedisCache createCache(String keyPrefix) { - connectionFactory = mock(JedisConnectionFactory.class); - RedisConnection connection = mock(RedisConnection.class); + connectionFactory = mock(TbJedisClusterConnectionFactory.class); + connection = mock(RedisConnection.class); scriptingCommands = mock(RedisScriptingCommands.class); when(connectionFactory.isRedisClusterAware()).thenReturn(false); when(connectionFactory.getConnection()).thenReturn(connection); diff --git a/common/cache/src/test/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactoryTest.java b/common/cache/src/test/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactoryTest.java index 3ae1764cfb..3c52a5f93d 100644 --- a/common/cache/src/test/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactoryTest.java +++ b/common/cache/src/test/java/org/thingsboard/server/cache/TbJedisClusterConnectionFactoryTest.java @@ -5,7 +5,9 @@ package org.thingsboard.server.cache; import org.junit.jupiter.api.Test; import org.springframework.data.redis.connection.RedisClusterConfiguration; import org.springframework.data.redis.connection.jedis.JedisClientConfiguration; +import org.springframework.data.redis.connection.jedis.JedisClusterConnection; import redis.clients.jedis.JedisClientConfig; +import redis.clients.jedis.RedisClusterClient; import javax.net.ssl.SSLSocketFactory; import java.time.Duration; @@ -60,4 +62,23 @@ class TbJedisClusterConnectionFactoryTest { assertThat(config.getSslSocketFactory()).isSameAs(sslSocketFactory); } + @Test + void whenStart_thenClusterClientIsBuiltThroughOverride() { + RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration(List.of("127.0.0.1:6379")); + RedisClusterClient client = mock(RedisClusterClient.class); + var factory = new TbJedisClusterConnectionFactory(clusterConfig, JedisClientConfiguration.defaultConfiguration(), null) { + @Override + protected RedisClusterClient createRedisClusterClient(RedisClusterConfiguration config) { + return client; + } + }; + + factory.start(); + try { + assertThat(((JedisClusterConnection) factory.getClusterConnection()).getNativeConnection()).isSameAs(client); + } finally { + factory.stop(); + } + } + } diff --git a/common/cluster-api/pom.xml b/common/cluster-api/pom.xml index eee7fa9f3f..334d47c32c 100644 --- a/common/cluster-api/pom.xml +++ b/common/cluster-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/coap-server/pom.xml b/common/coap-server/pom.xml index fd8a22fd53..19109218ea 100644 --- a/common/coap-server/pom.xml +++ b/common/coap-server/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common @@ -49,8 +49,8 @@ spring-context - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/dao-api/pom.xml b/common/dao-api/pom.xml index aec399929c..0df941cff1 100644 --- a/common/dao-api/pom.xml +++ b/common/dao-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java index eec419f9ef..a89f5a32b3 100644 --- a/common/dao-api/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java +++ b/common/dao-api/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java @@ -109,6 +109,8 @@ public interface AlarmService extends EntityDaoService { PageData findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query, Collection orderedEntityIds); + PageData findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query); + Set getPropagationEntityIds(Alarm alarm); Set getPropagationEntityIds(Alarm alarm, List types); diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/group/EntityGroupService.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/group/EntityGroupService.java index 177a94438a..5f2c6897d2 100644 --- a/common/dao-api/src/main/java/org/thingsboard/server/dao/group/EntityGroupService.java +++ b/common/dao-api/src/main/java/org/thingsboard/server/dao/group/EntityGroupService.java @@ -37,6 +37,10 @@ public interface EntityGroupService extends EntityDaoService { ListenableFuture findEntityGroupInfoByIdAsync(TenantId tenantId, EntityGroupId entityGroupId); + EntityGroupInfo findEntityGroupInfoByTenantIdAndId(TenantId tenantId, EntityGroupId entityGroupId); + + ListenableFuture findEntityGroupInfoByTenantIdAndIdAsync(TenantId tenantId, EntityGroupId entityGroupId); + EntityGroup saveEntityGroup(TenantId tenantId, EntityId parentEntityId, EntityGroup entityGroup); EntityGroup createEntityGroupAll(TenantId tenantId, EntityId parentEntityId, EntityType groupType); diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/util/TbAutoConfiguration.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/util/TbAutoConfiguration.java index 4e43963725..d49c16bb4f 100644 --- a/common/dao-api/src/main/java/org/thingsboard/server/dao/util/TbAutoConfiguration.java +++ b/common/dao-api/src/main/java/org/thingsboard/server/dao/util/TbAutoConfiguration.java @@ -1,16 +1,18 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao.util; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration; -import org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration; -import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) -@EnableAutoConfiguration(exclude = {CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class, RedisAutoConfiguration.class}) +@EnableAutoConfiguration(excludeName = { + "org.springframework.boot.cassandra.autoconfigure.CassandraAutoConfiguration", + "org.springframework.boot.data.cassandra.autoconfigure.DataCassandraAutoConfiguration", + "org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration" +}) public @interface TbAutoConfiguration { } diff --git a/common/data/pom.xml b/common/data/pom.xml index 3bb8c137d1..c92b144a3e 100644 --- a/common/data/pom.xml +++ b/common/data/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/exception/ThingsboardErrorCode.java b/common/data/src/main/java/org/thingsboard/server/common/data/exception/ThingsboardErrorCode.java index f6228df527..bb24122330 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/exception/ThingsboardErrorCode.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/exception/ThingsboardErrorCode.java @@ -22,7 +22,8 @@ public enum ThingsboardErrorCode { ENTITIES_LIMIT_EXCEEDED(41), PASSWORD_VIOLATION(45), DATABASE(46), - SETUP_INCOMPLETE(47); + SETUP_INCOMPLETE(47), + SERVICE_UNAVAILABLE(48); private int errorCode; diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java index 269eafd106..90507f183b 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java @@ -3,22 +3,50 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.common.data.iot_hub; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.JsonNode; import lombok.Data; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.EntityId; +import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Set; @Data public class DeviceInstalledItemDescriptor implements IotHubInstalledItemDescriptor { private List createdEntityIds; - // Of createdEntityIds, the entities the user chose to use as they were: the package doesn't own them + // Of createdEntityIds, the entities the user chose to use as they were: the package doesn't own them. + // Read them with getUsedExistingEntityIdsIncludingLegacy(): installs without this field keep them only in installState. private List usedExistingEntityIds; private DashboardId dashboardId; private String selectedInstallMethod; private Map installState; + /** + * The entities the user chose to use as they were. An install whose descriptor has no usedExistingEntityIds marks + * them only in its install state, with the resolution "use-existing". + */ + @JsonIgnore + public Set getUsedExistingEntityIdsIncludingLegacy() { + if (usedExistingEntityIds != null) { + return new LinkedHashSet<>(usedExistingEntityIds); + } + Set usedExisting = new LinkedHashSet<>(); + if (createdEntityIds == null || installState == null) { + return usedExisting; + } + Set markedIds = new HashSet<>(); + installState.values().forEach(state -> { + if (state != null && "use-existing".equals(state.path("resolution").asText())) { + markedIds.add(state.path("entityOutput").path("id").asText()); + } + }); + createdEntityIds.stream().filter(id -> markedIds.contains(id.getId().toString())).forEach(usedExisting::add); + return usedExisting; + } + } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/limit/LimitedApi.java b/common/data/src/main/java/org/thingsboard/server/common/data/limit/LimitedApi.java index a04ba1bd9c..88531dc13f 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/limit/LimitedApi.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/limit/LimitedApi.java @@ -57,7 +57,7 @@ public enum LimitedApi { WS_SUBSCRIPTIONS("WS subscriptions", false), CALCULATED_FIELD_DEBUG_EVENTS("calculated field debug events", true), TRENDZ_PUBLIC_SYNC("Trendz sync from public endpoint", false), - AI_CHAT_REQUESTS("AI chat requests", true); + AI_CHAT_REQUESTS(DefaultTenantProfileConfiguration::getAiChatRequestsPerTenantRateLimit, "AI chat requests", true, true); private final Function configExtractor; private final boolean perTenant; diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/notification/NotificationType.java b/common/data/src/main/java/org/thingsboard/server/common/data/notification/NotificationType.java index 3708bd0eb8..43ca459aaa 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/notification/NotificationType.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/notification/NotificationType.java @@ -24,6 +24,7 @@ public enum NotificationType { ADDON_ACCESS_REQUEST(true), ADDON_ACCESS_ERROR(true), PLAN_UPGRADE_REQUEST(true), + AI_CREDITS_LIMIT_INCREASE_REQUEST(true), API_USAGE_LIMIT, RULE_NODE, INTEGRATION_LIFECYCLE_EVENT, diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java b/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java new file mode 100644 index 0000000000..dee1b1378f --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +package org.thingsboard.server.common.data.notification.info; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; + +import static org.thingsboard.server.common.data.util.CollectionsUtil.mapOf; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class AiCreditsLimitIncreaseRequestNotificationInfo implements NotificationInfo { + + private String userEmail; + private String tenantName; + private String limitDescription; + private String increaseLimitActionLabel; + private String increaseLimitLink; + private String baseUrl; + + @Override + public Map getTemplateData() { + return mapOf( + "userEmail", userEmail, + "tenantName", tenantName, + "limitDescription", limitDescription, + "increaseLimitActionLabel", increaseLimitActionLabel, + "increaseLimitLink", increaseLimitLink, + "baseUrl", baseUrl + ); + } + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/NotificationInfo.java b/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/NotificationInfo.java index ad8b61402d..32ba0d43dd 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/NotificationInfo.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/NotificationInfo.java @@ -35,6 +35,7 @@ import java.util.Map; @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.IntegrationLifecycleEventNotificationInfo", schema = IntegrationLifecycleEventNotificationInfo.class), @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.NewPlatformVersionNotificationInfo", schema = NewPlatformVersionNotificationInfo.class), @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.PlanUpgradeRequestNotificationInfo", schema = PlanUpgradeRequestNotificationInfo.class), + @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.AiCreditsLimitIncreaseRequestNotificationInfo", schema = AiCreditsLimitIncreaseRequestNotificationInfo.class), @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.RateLimitsNotificationInfo", schema = RateLimitsNotificationInfo.class), @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.ReportGeneratedNotificationInfo", schema = ReportGeneratedNotificationInfo.class), @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.ResourcesShortageNotificationInfo", schema = ResourcesShortageNotificationInfo.class), @@ -64,6 +65,7 @@ import java.util.Map; @JsonSubTypes.Type(IntegrationLifecycleEventNotificationInfo.class), @JsonSubTypes.Type(NewPlatformVersionNotificationInfo.class), @JsonSubTypes.Type(PlanUpgradeRequestNotificationInfo.class), + @JsonSubTypes.Type(AiCreditsLimitIncreaseRequestNotificationInfo.class), @JsonSubTypes.Type(RateLimitsNotificationInfo.class), @JsonSubTypes.Type(ReportGeneratedNotificationInfo.class), @JsonSubTypes.Type(ResourcesShortageNotificationInfo.class), diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/permission/MergedUserPermissions.java b/common/data/src/main/java/org/thingsboard/server/common/data/permission/MergedUserPermissions.java index 7244289778..12afeed071 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/permission/MergedUserPermissions.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/permission/MergedUserPermissions.java @@ -12,6 +12,7 @@ import org.thingsboard.server.common.data.id.EntityGroupId; import java.io.Serializable; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -40,6 +41,8 @@ public final class MergedUserPermissions implements Serializable { @Schema(description = "Map of read entity time-series permissions per resource. Used on the UI to enable/disable certain tabs.") private final Map readTsPermissions; + public static final Set AI_RESOURCES = Set.of(Resource.AI, Resource.AI_MODEL); + public static final MergedUserPermissions ALL = new MergedUserPermissions(Map.of(Resource.ALL, Set.of(Operation.ALL)), Collections.emptyMap()); @JsonCreator @@ -134,6 +137,32 @@ public final class MergedUserPermissions implements Serializable { return hasGenericResourcePermission(resource, operation) || hasGenericAllPermission(operation); } + /** + * True when the user has the operation on every resource except the AI ones ({@link #AI_RESOURCES}): either through + * {@link Resource#ALL}, or resource by resource, as a role that allows everything but excludes AI is merged. + */ + public boolean hasGenericPermissionExceptAi(Operation operation) { + if (hasGenericAllPermission(operation)) { + return true; + } + return Arrays.stream(Resource.values()) + .filter(resource -> resource != Resource.ALL && !AI_RESOURCES.contains(resource)) + .allMatch(resource -> hasEveryOperation(resource, operation)); + } + + private boolean hasEveryOperation(Resource resource, Operation operation) { + Set valid = Resource.operationsByResource.get(resource); + if (valid == null) { + return true; + } + if (operation != Operation.ALL) { + return !valid.contains(operation) || hasGenericResourcePermission(resource, operation); + } + List required = valid.stream().filter(op -> op != Operation.ALL).toList(); + return required.isEmpty() ? hasGenericResourcePermission(resource, Operation.ALL) + : required.stream().allMatch(op -> hasGenericResourcePermission(resource, op)); + } + private boolean hasGenericAllPermission(Operation operation) { Set operations = genericPermissions.get(Resource.ALL); return operations != null && checkOperation(operations, operation); diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/limit/LimitedApiTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/limit/LimitedApiTest.java index b9a8c2525a..3e92803c92 100644 --- a/common/data/src/test/java/org/thingsboard/server/common/data/limit/LimitedApiTest.java +++ b/common/data/src/test/java/org/thingsboard/server/common/data/limit/LimitedApiTest.java @@ -80,7 +80,9 @@ class LimitedApiTest { Map.entry(LimitedApi.INTEGRATION_MSGS_PER_DEVICE, () -> verify(config).getIntegrationMsgsPerDeviceRateLimit()), Map.entry(LimitedApi.INTEGRATION_MSGS_PER_ASSET, () -> - verify(config).getIntegrationMsgsPerAssetRateLimit()) + verify(config).getIntegrationMsgsPerAssetRateLimit()), + Map.entry(LimitedApi.AI_CHAT_REQUESTS, () -> + verify(config).getAiChatRequestsPerTenantRateLimit()) ); Set expected = verifierMap.keySet(); diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/permission/MergedUserPermissionsTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/permission/MergedUserPermissionsTest.java new file mode 100644 index 0000000000..d606067a43 --- /dev/null +++ b/common/data/src/test/java/org/thingsboard/server/common/data/permission/MergedUserPermissionsTest.java @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.common.data.permission; + +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +class MergedUserPermissionsTest { + + @Test + void shouldAllowEverythingExceptAi_whenTheRoleAllowsAll() { + MergedUserPermissions permissions = new MergedUserPermissions(Map.of(Resource.ALL, Set.of(Operation.ALL)), Collections.emptyMap()); + + assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isTrue(); + assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); + } + + @Test + void shouldAllowEverythingExceptAi_whenAllIsAllowedAndTheAiResourcesAreExcluded() { + MergedUserPermissions permissions = new MergedUserPermissions(expandedExceptAi(Operation.ALL), Collections.emptyMap()); + + assertThat(permissions.hasGenericPermission(Resource.ALL, Operation.ALL)).isFalse(); + assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isTrue(); + assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); + } + + @Test + void shouldNotAllowEverything_whenAnotherResourceIsExcluded() { + Map> generic = expandedExceptAi(Operation.ALL); + generic.get(Resource.DEVICE).remove(Operation.WRITE); + + MergedUserPermissions permissions = new MergedUserPermissions(generic, Collections.emptyMap()); + + assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isFalse(); + assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); + } + + @Test + void shouldAllowReadOnly_whenReadIsAllowedOnEverythingExceptAi() { + MergedUserPermissions permissions = new MergedUserPermissions(expandedExceptAi(Operation.READ), Collections.emptyMap()); + + assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); + assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isFalse(); + } + + static Map> expandedExceptAi(Operation allowed) { + Map> generic = new HashMap<>(); + for (Resource resource : Resource.values()) { + Set valid = Resource.operationsByResource.get(resource); + if (resource == Resource.ALL || MergedUserPermissions.AI_RESOURCES.contains(resource) || valid == null) { + continue; + } + Set operations = new HashSet<>(valid); + if (allowed == Operation.ALL) { + if (operations.size() > 1) { + operations.remove(Operation.ALL); + } + } else { + operations.retainAll(Set.of(allowed)); + } + if (!operations.isEmpty()) { + generic.put(resource, operations); + } + } + return generic; + } + +} diff --git a/common/discovery-api/pom.xml b/common/discovery-api/pom.xml index aba7b8e3b7..777b87dda0 100644 --- a/common/discovery-api/pom.xml +++ b/common/discovery-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/pom.xml b/common/edge-api/pom.xml index 2e9dad6ae6..94c1d060cd 100644 --- a/common/edge-api/pom.xml +++ b/common/edge-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common @@ -63,8 +63,8 @@ spring-context - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web io.netty diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index e2001ba7fb..b502f01dad 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -44,6 +44,7 @@ enum EdgeVersion { V_4_2_2_7 = 4227; V_4_2_2_8 = 4228; V_4_2_2_9 = 4229; + V_4_2_2_10 = 42210; V_4_3_0_1 = 15; V_4_3_1 = 4310; V_4_3_1_1 = 4311; @@ -55,10 +56,12 @@ enum EdgeVersion { V_4_3_1_7 = 4317; V_4_3_1_8 = 4318; V_4_3_1_9 = 4319; + V_4_3_1_10 = 43110; V_4_4_0 = 4400; V_4_4_0_1 = 4401; V_4_4_0_2 = 4402; V_4_4_1 = 4410; + V_4_4_2 = 4420; V_LATEST = 99999; } diff --git a/common/edqs/pom.xml b/common/edqs/pom.xml index b9e850af8c..53de0d7fd3 100644 --- a/common/edqs/pom.xml +++ b/common/edqs/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common @@ -63,8 +63,8 @@ discovery-api - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web com.github.ben-manes.caffeine diff --git a/common/integration/apache-pulsar/pom.xml b/common/integration/apache-pulsar/pom.xml index 610872f5e9..5a29905333 100644 --- a/common/integration/apache-pulsar/pom.xml +++ b/common/integration/apache-pulsar/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -36,8 +36,8 @@ script-api - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/integration/aws-integrations/pom.xml b/common/integration/aws-integrations/pom.xml index d313be19bc..ad590eaa00 100644 --- a/common/integration/aws-integrations/pom.xml +++ b/common/integration/aws-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -34,8 +34,8 @@ script-api - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/integration/azure-integrations/pom.xml b/common/integration/azure-integrations/pom.xml index 8fd70d9c54..d9ddee4e1a 100644 --- a/common/integration/azure-integrations/pom.xml +++ b/common/integration/azure-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -34,8 +34,8 @@ script-api - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/integration/cluster-integration-api/pom.xml b/common/integration/cluster-integration-api/pom.xml index 1d4596b74d..5d9c43df9c 100644 --- a/common/integration/cluster-integration-api/pom.xml +++ b/common/integration/cluster-integration-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/coap-integrations/pom.xml b/common/integration/coap-integrations/pom.xml index b00bcb6d09..b76cf5bbee 100644 --- a/common/integration/coap-integrations/pom.xml +++ b/common/integration/coap-integrations/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -38,11 +38,6 @@ org.thingsboard.common.script script-api - - org.springframework.boot - spring-boot-starter-web - provided - org.springframework spring-web diff --git a/common/integration/gcloud-integrations/pom.xml b/common/integration/gcloud-integrations/pom.xml index 472aeefa9d..cc169746c0 100644 --- a/common/integration/gcloud-integrations/pom.xml +++ b/common/integration/gcloud-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -30,8 +30,8 @@ integration-api - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/integration/http-integrations/pom.xml b/common/integration/http-integrations/pom.xml index c476648e2a..343522df6f 100644 --- a/common/integration/http-integrations/pom.xml +++ b/common/integration/http-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -35,7 +35,7 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc provided @@ -53,7 +53,11 @@ org.springframework.boot - spring-boot-starter-webflux + spring-boot-starter-webclient + + + org.springframework.boot + spring-boot-jackson2 @@ -68,7 +72,7 @@ org.testcontainers - junit-jupiter + testcontainers-junit-jupiter test diff --git a/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/kpn/KpnIntegration.java b/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/kpn/KpnIntegration.java index f34166c2e4..218de80717 100644 --- a/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/kpn/KpnIntegration.java +++ b/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/kpn/KpnIntegration.java @@ -183,7 +183,7 @@ public class KpnIntegration> extends BasicHttpIn } headers.set("x-client-id", mdMap.get(SUB_CUSTOMER_ID_PARAM)); } - String uriString = UriComponentsBuilder.fromHttpUrl(KPN_BASE_URL + DOWNLINK_PATH) + String uriString = UriComponentsBuilder.fromUriString(KPN_BASE_URL + DOWNLINK_PATH) .query("port=" + mdMap.get(FPORT_PARAM)) .encode() .toUriString(); diff --git a/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/loriot/LoriotIntegration.java b/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/loriot/LoriotIntegration.java index 1a9662241f..5fc373db0f 100644 --- a/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/loriot/LoriotIntegration.java +++ b/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/loriot/LoriotIntegration.java @@ -72,10 +72,10 @@ public class LoriotIntegration extends BasicHttpIntegration t.sslContext(sslContext)); + HttpClient httpClient = HttpClient.create() + .runOn(context.getEventLoopGroup()) + .secure(t -> t.sslContext(sslContext)); this.webClient = WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) diff --git a/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/thingpark/ThingParkIntegration.java b/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/thingpark/ThingParkIntegration.java index 38c0028a13..1306e44661 100644 --- a/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/thingpark/ThingParkIntegration.java +++ b/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/thingpark/ThingParkIntegration.java @@ -69,10 +69,10 @@ public class ThingParkIntegration extends AbstractHttpIntegration t.sslContext(sslContext)); + HttpClient httpClient = HttpClient.create() + .runOn(context.getEventLoopGroup()) + .secure(t -> t.sslContext(sslContext)); this.webClient = WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) diff --git a/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/web/LowercaseHeaderNamesAutoConfiguration.java b/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/web/LowercaseHeaderNamesAutoConfiguration.java new file mode 100644 index 0000000000..bb839595df --- /dev/null +++ b/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/web/LowercaseHeaderNamesAutoConfiguration.java @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.integration.http.web; + +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.core.Ordered; + +@AutoConfiguration +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) +public class LowercaseHeaderNamesAutoConfiguration { + + @Bean + public FilterRegistrationBean lowercaseHeaderNamesFilter() { + FilterRegistrationBean registration = new FilterRegistrationBean<>(new LowercaseHeaderNamesFilter()); + registration.setOrder(Ordered.HIGHEST_PRECEDENCE); + return registration; + } + +} diff --git a/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/web/LowercaseHeaderNamesFilter.java b/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/web/LowercaseHeaderNamesFilter.java new file mode 100644 index 0000000000..85e643c2a6 --- /dev/null +++ b/common/integration/http-integrations/src/main/java/org/thingsboard/integration/http/web/LowercaseHeaderNamesFilter.java @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.integration.http.web; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.Collections; +import java.util.Enumeration; +import java.util.Locale; + +/** + * Reports request header names in lower case, as Tomcat 10 did. Tomcat 11 keeps the case the client sent, + * which breaks code that copies the names into a map and reads it by a lower-case name. + */ +public class LowercaseHeaderNamesFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { + chain.doFilter(new HttpServletRequestWrapper(request) { + @Override + public Enumeration getHeaderNames() { + return Collections.enumeration(Collections.list(super.getHeaderNames()).stream() + .map(name -> name.toLowerCase(Locale.ROOT)) + .distinct() + .toList()); + } + }, response); + } + +} diff --git a/common/integration/http-integrations/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/common/integration/http-integrations/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 0000000000..89b0377af0 --- /dev/null +++ b/common/integration/http-integrations/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +org.thingsboard.integration.http.web.LowercaseHeaderNamesAutoConfiguration diff --git a/common/integration/http-integrations/src/test/java/org/thingsboard/integration/http/web/LowercaseHeaderNamesFilterTest.java b/common/integration/http-integrations/src/test/java/org/thingsboard/integration/http/web/LowercaseHeaderNamesFilterTest.java new file mode 100644 index 0000000000..ec9d5772b7 --- /dev/null +++ b/common/integration/http-integrations/src/test/java/org/thingsboard/integration/http/web/LowercaseHeaderNamesFilterTest.java @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.integration.http.web; + +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.core.Ordered; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; + +class LowercaseHeaderNamesFilterTest { + + private final MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HeadersController()) + .addFilters(new LowercaseHeaderNamesFilter()) + .build(); + + @Test + void requestHeaderMapHasLowercaseNames() throws Exception { + mockMvc.perform(post("/headers").header("testHeader", "testValue").header("Stripe-Signature", "t=1")) + .andExpect(content().string("testheader=testValue,stripe-signature=t=1")); + } + + @Test + void multipartRequestHeadersHaveLowercaseNames() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest("POST", "/multipart"); + request.addHeader("testHeader", "testValue"); + MockFilterChain chain = new MockFilterChain(); + + new LowercaseHeaderNamesFilter().doFilter(request, new MockHttpServletResponse(), chain); + + StandardMultipartHttpServletRequest multipart = new StandardMultipartHttpServletRequest((HttpServletRequest) chain.getRequest(), true); + assertThat(multipart.getRequestHeaders().toSingleValueMap()).containsEntry("testheader", "testValue"); + } + + @Test + void registeredFirstInServletApplications() { + new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(LowercaseHeaderNamesAutoConfiguration.class)) + .run(context -> assertThat(context.getBean(FilterRegistrationBean.class).getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE)); + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(LowercaseHeaderNamesAutoConfiguration.class)) + .run(context -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class)); + } + + @RestController + static class HeadersController { + + @PostMapping("/headers") + String headers(@RequestHeader Map headers) { + return "testheader=" + headers.get("testheader") + ",stripe-signature=" + headers.get("stripe-signature"); + } + + } + +} diff --git a/common/integration/integration-api/pom.xml b/common/integration/integration-api/pom.xml index 15617a0a3a..fcbfac5d49 100644 --- a/common/integration/integration-api/pom.xml +++ b/common/integration/integration-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -84,8 +84,8 @@ commons-lang3 - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/AbstractIntegration.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/AbstractIntegration.java index 6e4558874f..d395fffe17 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/AbstractIntegration.java +++ b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/AbstractIntegration.java @@ -186,9 +186,11 @@ public abstract class AbstractIntegration implements ThingsboardPlatformInteg } if (data.getTelemetry() != null) { builder.setPostTelemetryMsg(data.getTelemetry()); + builder.addAllTelemetryTypeCastDisabledKeys(data.getTelemetryTypeCastDisabledKeys()); } if (data.getAttributesUpdate() != null) { builder.setPostAttributesMsg(data.getAttributesUpdate()); + builder.addAllAttributesTypeCastDisabledKeys(data.getAttributesTypeCastDisabledKeys()); } context.processUplinkData(builder.build(), new IntegrationCallback<>() { @Override @@ -233,9 +235,11 @@ public abstract class AbstractIntegration implements ThingsboardPlatformInteg } if (data.getTelemetry() != null) { builder.setPostTelemetryMsg(data.getTelemetry()); + builder.addAllTelemetryTypeCastDisabledKeys(data.getTelemetryTypeCastDisabledKeys()); } if (data.getAttributesUpdate() != null) { builder.setPostAttributesMsg(data.getAttributesUpdate()); + builder.addAllAttributesTypeCastDisabledKeys(data.getAttributesTypeCastDisabledKeys()); } context.processUplinkData(builder.build(), new IntegrationCallback<>() { @Override diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java index a944217d1d..db95baad29 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java +++ b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java @@ -41,8 +41,8 @@ public final class DedicatedConverterUtil { // String values of unwrapperKeys skip the type cast, so devAddr "01020304" stays a string. public static DedicatedUplinkData parseUplinkData(DedicatedConverterConfig config, JsonObject src, UplinkMetaData metadata, Set unwrapperKeys) { Map kvMap = new HashMap<>(metadata.getKvMap()); - Set telemetryNoCastKeys = new HashSet<>(); - Set attributesNoCastKeys = new HashSet<>(); + Set telemetryTypeCastDisabledKeys = new HashSet<>(); + Set attributesTypeCastDisabledKeys = new HashSet<>(); JsonElement telemetry; if (src.has(TELEMETRY)) { @@ -51,20 +51,20 @@ public final class DedicatedConverterUtil { if (telemetry.isJsonArray()) { JsonArray telemetryArray = telemetry.getAsJsonArray(); Set decoderKeys = getTelemetryKeys(telemetryArray); - addMetadataTelemetry(telemetryArray, kvMap, config.getTelemetry(), unwrapperKeys, telemetryNoCastKeys); - // The no-cast keys apply to every array element, so a key the decoder also sends is cast as before. - telemetryNoCastKeys.removeAll(decoderKeys); + addMetadataTelemetry(telemetryArray, kvMap, config.getTelemetry(), unwrapperKeys, telemetryTypeCastDisabledKeys); + // The type-cast-disabled keys apply to every array element, so a key the decoder also sends is cast as before. + telemetryTypeCastDisabledKeys.removeAll(decoderKeys); } else if (telemetry.isJsonObject()) { var obj = telemetry.getAsJsonObject(); if (obj.has(VALUES)) { var values = obj.get(VALUES).getAsJsonObject(); - addKvs(values, kvMap, config.getTelemetry(), unwrapperKeys, telemetryNoCastKeys); + addKvs(values, kvMap, config.getTelemetry(), unwrapperKeys, telemetryTypeCastDisabledKeys); } else { - addKvs(obj, kvMap, config.getTelemetry(), unwrapperKeys, telemetryNoCastKeys); + addKvs(obj, kvMap, config.getTelemetry(), unwrapperKeys, telemetryTypeCastDisabledKeys); } } } else { - telemetry = addKvs(new JsonObject(), kvMap, config.getTelemetry(), unwrapperKeys, telemetryNoCastKeys); + telemetry = addKvs(new JsonObject(), kvMap, config.getTelemetry(), unwrapperKeys, telemetryTypeCastDisabledKeys); } JsonObject attributes; @@ -74,7 +74,7 @@ public final class DedicatedConverterUtil { attributes = new JsonObject(); } - addKvs(attributes, kvMap, config.getAttributes(), unwrapperKeys, attributesNoCastKeys); + addKvs(attributes, kvMap, config.getAttributes(), unwrapperKeys, attributesTypeCastDisabledKeys); EntityType entityType = getProperty(src, "type", EntityType::valueOf, config::getType); String entityName = getProperty(src, "name", () -> processTemplate(config.getName(), kvMap)); @@ -95,8 +95,8 @@ public final class DedicatedConverterUtil { .group(group) .telemetry(telemetry) .attributes(attributes) - .telemetryNoCastKeys(telemetryNoCastKeys) - .attributesNoCastKeys(attributesNoCastKeys) + .telemetryTypeCastDisabledKeys(telemetryTypeCastDisabledKeys) + .attributesTypeCastDisabledKeys(attributesTypeCastDisabledKeys) .build(); } @@ -117,17 +117,17 @@ public final class DedicatedConverterUtil { // The metadata keys join the script's element at the uplink ts, where the script's values win as in an object result. // Without such an element they get their own one at the uplink ts: an element without ts is saved at the server time. - private static void addMetadataTelemetry(JsonArray telemetry, Map kvMap, Set keys, Set unwrapperKeys, Set noCastKeys) { + private static void addMetadataTelemetry(JsonArray telemetry, Map kvMap, Set keys, Set unwrapperKeys, Set typeCastDisabledKeys) { Long uplinkTs = getUplinkTs(kvMap); if (uplinkTs != null) { for (JsonElement element : telemetry) { if (element.isJsonObject() && isValuesAtTs(element.getAsJsonObject(), uplinkTs)) { - addKvs(element.getAsJsonObject().getAsJsonObject(VALUES), kvMap, keys, unwrapperKeys, noCastKeys); + addKvs(element.getAsJsonObject().getAsJsonObject(VALUES), kvMap, keys, unwrapperKeys, typeCastDisabledKeys); return; } } } - JsonObject values = addKvs(new JsonObject(), kvMap, keys, unwrapperKeys, noCastKeys); + JsonObject values = addKvs(new JsonObject(), kvMap, keys, unwrapperKeys, typeCastDisabledKeys); if (values.isEmpty()) { return; } @@ -175,14 +175,14 @@ public final class DedicatedConverterUtil { return keys; } - private static JsonObject addKvs(JsonObject kvsObj, Map kvMap, Set keys, Set unwrapperKeys, Set noCastKeys) { + private static JsonObject addKvs(JsonObject kvsObj, Map kvMap, Set keys, Set unwrapperKeys, Set typeCastDisabledKeys) { if (CollectionsUtil.isNotEmpty(keys) && !kvMap.isEmpty()) { kvMap.entrySet().stream() .filter(e -> keys.contains(e.getKey()) && !kvsObj.has(e.getKey())) .forEach(e -> { kvsObj.add(e.getKey(), GSON.toJsonTree(e.getValue())); if (e.getValue() instanceof String && unwrapperKeys.contains(e.getKey())) { - noCastKeys.add(e.getKey()); + typeCastDisabledKeys.add(e.getKey()); } }); } diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverter.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverter.java index 7f99ff891f..498861f89c 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverter.java +++ b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverter.java @@ -96,17 +96,19 @@ public class DedicatedScriptUplinkDataConverter extends AbstractUplinkDataConver Map currentOnValueTelemetryUpdate = this.currentUpdateOnlyTelemetryPerEntity.getOrDefault(name, new ConcurrentHashMap<>()); Map currentOnValueAttributesUpdate = this.currentUpdateOnlyAttributesPerEntity.getOrDefault(name, new ConcurrentHashMap<>()); - TransportProtos.PostTelemetryMsg parsedTelemetry = JsonConverter.convertToTelemetryProto(uplinkData.getTelemetryJson(), uplinkData.getTelemetryNoCastKeys()); + TransportProtos.PostTelemetryMsg parsedTelemetry = JsonConverter.convertToTelemetryProto(uplinkData.getTelemetryJson(), uplinkData.getTelemetryTypeCastDisabledKeys()); if (!this.updateOnlyKeys.isEmpty()) { parsedTelemetry = filterTelemetryOnKeyValueUpdateAndUpdateMap(parsedTelemetry, currentOnValueTelemetryUpdate); } builder.telemetry(parsedTelemetry); - TransportProtos.PostAttributeMsg parsedAttributes = JsonConverter.convertToAttributesProto(uplinkData.getAttributesJson(), uplinkData.getAttributesNoCastKeys()); + TransportProtos.PostAttributeMsg parsedAttributes = JsonConverter.convertToAttributesProto(uplinkData.getAttributesJson(), uplinkData.getAttributesTypeCastDisabledKeys()); if (!this.updateOnlyKeys.isEmpty()) { parsedAttributes = filterAttributeOnKeyValueUpdateAndUpdateMap(parsedAttributes, currentOnValueAttributesUpdate); } builder.attributesUpdate(parsedAttributes); + builder.telemetryTypeCastDisabledKeys(uplinkData.getTelemetryTypeCastDisabledKeys()); + builder.attributesTypeCastDisabledKeys(uplinkData.getAttributesTypeCastDisabledKeys()); if (!currentOnValueTelemetryUpdate.isEmpty()) { this.currentUpdateOnlyTelemetryPerEntity.put(name, currentOnValueTelemetryUpdate); diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedUplinkData.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedUplinkData.java index f0fe325bc6..2c16028afb 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedUplinkData.java +++ b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedUplinkData.java @@ -25,9 +25,9 @@ public class DedicatedUplinkData { private final JsonElement telemetry; private final JsonElement attributes; @JsonIgnore - private final Set telemetryNoCastKeys; + private final Set telemetryTypeCastDisabledKeys; @JsonIgnore - private final Set attributesNoCastKeys; + private final Set attributesTypeCastDisabledKeys; @JsonRawValue public String getTelemetry() { diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/data/UplinkData.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/data/UplinkData.java index 6bffa3844b..e4aff6b473 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/data/UplinkData.java +++ b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/data/UplinkData.java @@ -7,6 +7,9 @@ import lombok.Data; import org.thingsboard.server.gen.transport.TransportProtos.PostAttributeMsg; import org.thingsboard.server.gen.transport.TransportProtos.PostTelemetryMsg; +import java.util.Collections; +import java.util.Set; + @Data @Builder public class UplinkData { @@ -23,5 +26,10 @@ public class UplinkData { private final PostAttributeMsg attributesUpdate; private final PostAttributeMsg constants; private final boolean isAsset; + // Keys whose numeric-looking string values the converter kept as strings. + @Builder.Default + private final Set telemetryTypeCastDisabledKeys = Collections.emptySet(); + @Builder.Default + private final Set attributesTypeCastDisabledKeys = Collections.emptySet(); } diff --git a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/AbstractIntegrationUplinkProtoTest.java b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/AbstractIntegrationUplinkProtoTest.java new file mode 100644 index 0000000000..449719902e --- /dev/null +++ b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/AbstractIntegrationUplinkProtoTest.java @@ -0,0 +1,100 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.integration.api; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.thingsboard.integration.api.data.UplinkData; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.integration.Integration; +import org.thingsboard.server.gen.integration.AssetUplinkDataProto; +import org.thingsboard.server.gen.integration.DeviceUplinkDataProto; +import org.thingsboard.server.gen.transport.TransportProtos.PostAttributeMsg; +import org.thingsboard.server.gen.transport.TransportProtos.PostTelemetryMsg; +import org.thingsboard.server.gen.transport.TransportProtos.TsKvListProto; + +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class AbstractIntegrationUplinkProtoTest { + + private static final PostTelemetryMsg TELEMETRY = PostTelemetryMsg.newBuilder().addTsKvList(TsKvListProto.newBuilder().setTs(1L)).build(); + private static final PostAttributeMsg ATTRIBUTES = PostAttributeMsg.newBuilder().build(); + + private IntegrationContext context; + private AbstractIntegration integration; + + @BeforeEach + public void setUp() { + context = mock(IntegrationContext.class); + when(context.getRateLimitService()).thenReturn(Optional.empty()); + Integration configuration = new Integration(); + configuration.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + integration = new AbstractIntegration<>() { + @Override + public void process(String msg) { + } + + @Override + public void destroy() { + } + }; + integration.setConfiguration(configuration); + } + + @Test + public void testDeviceUplinkProtoCarriesTypeCastDisabledKeys() throws Exception { + integration.processUplinkData(context, UplinkData.builder() + .deviceName("d").deviceType("default") + .telemetry(TELEMETRY).attributesUpdate(ATTRIBUTES) + .telemetryTypeCastDisabledKeys(Set.of("devAddr")) + .attributesTypeCastDisabledKeys(Set.of("joinEui", "hardwareVersion")) + .build()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(DeviceUplinkDataProto.class); + verify(context).processUplinkData(captor.capture(), any()); + DeviceUplinkDataProto proto = captor.getValue(); + assertThat(proto.getTelemetryTypeCastDisabledKeysList()).containsExactly("devAddr"); + assertThat(proto.getAttributesTypeCastDisabledKeysList()).containsExactlyInAnyOrder("joinEui", "hardwareVersion"); + assertThat(DeviceUplinkDataProto.parseFrom(proto.toByteArray())).isEqualTo(proto); + } + + @Test + public void testAssetUplinkProtoCarriesTypeCastDisabledKeys() throws Exception { + integration.processUplinkData(context, UplinkData.builder() + .isAsset(true).assetName("a").assetType("default") + .telemetry(TELEMETRY).attributesUpdate(ATTRIBUTES) + .telemetryTypeCastDisabledKeys(Set.of("devAddr")) + .attributesTypeCastDisabledKeys(Set.of("joinEui")) + .build()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AssetUplinkDataProto.class); + verify(context).processUplinkData(captor.capture(), any()); + AssetUplinkDataProto proto = captor.getValue(); + assertThat(proto.getTelemetryTypeCastDisabledKeysList()).containsExactly("devAddr"); + assertThat(proto.getAttributesTypeCastDisabledKeysList()).containsExactly("joinEui"); + assertThat(AssetUplinkDataProto.parseFrom(proto.toByteArray())).isEqualTo(proto); + } + + @Test + public void testUplinkWithoutTypeCastDisabledKeysLeavesProtoFieldsEmpty() { + integration.processUplinkData(context, UplinkData.builder() + .deviceName("d").deviceType("default") + .telemetry(TELEMETRY).attributesUpdate(ATTRIBUTES) + .build()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(DeviceUplinkDataProto.class); + verify(context).processUplinkData(captor.capture(), any()); + assertThat(captor.getValue().getTelemetryTypeCastDisabledKeysList()).isEmpty(); + assertThat(captor.getValue().getAttributesTypeCastDisabledKeysList()).isEmpty(); + } + +} diff --git a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java index 15ea42a432..cc4a773c9e 100644 --- a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java +++ b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java @@ -31,8 +31,8 @@ import java.util.Set; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; import static org.thingsboard.server.gen.transport.TransportProtos.KeyValueType.DOUBLE_V; import static org.thingsboard.server.gen.transport.TransportProtos.KeyValueType.LONG_V; import static org.thingsboard.server.gen.transport.TransportProtos.KeyValueType.STRING_V; @@ -44,7 +44,7 @@ public class DedicatedScriptUplinkDataConverterTest { @BeforeEach public void startup() { - uplinkDataConverter = new DedicatedScriptUplinkDataConverter(any(), any(), any()); + uplinkDataConverter = new DedicatedScriptUplinkDataConverter(null, null, null); ReflectionTestUtils.setField(uplinkDataConverter, "converterUnwrapper", thingsStackUnwrapper); } @@ -62,6 +62,9 @@ public class DedicatedScriptUplinkDataConverterTest { assertKv(attributes.get("rssi"), LONG_V, -22L); assertKv(attributes.get("snr"), DOUBLE_V, 11.0); assertKv(attributes.get("frequency"), LONG_V, 868100000L); + assertTrue(uplink.getAttributesTypeCastDisabledKeys().containsAll(Set.of("devAddr", "eui"))); + assertFalse(uplink.getAttributesTypeCastDisabledKeys().contains("fCnt")); + assertTrue(uplink.getTelemetryTypeCastDisabledKeys().isEmpty()); } @ParameterizedTest @@ -77,6 +80,8 @@ public class DedicatedScriptUplinkDataConverterTest { assertKv(telemetry.get("rssi"), LONG_V, -22L); assertKv(telemetry.get("snr"), DOUBLE_V, 11.0); assertKv(toMap(uplink.getAttributesUpdate().getKvList()).get("eui"), STRING_V, "1000000000000001"); + assertEquals(Set.of("devAddr"), uplink.getTelemetryTypeCastDisabledKeys()); + assertEquals(Set.of("eui"), uplink.getAttributesTypeCastDisabledKeys()); } @Test @@ -161,6 +166,7 @@ public class DedicatedScriptUplinkDataConverterTest { UplinkData uplink = uplinkDataConverter.parseUplinkData(uplinkJson, unwrapThingsStack("05060708")); assertKv(toMap(uplink.getAttributesUpdate().getKvList()).get("devAddr"), LONG_V, 1020304L); + assertFalse(uplink.getAttributesTypeCastDisabledKeys().contains("devAddr")); } @Test diff --git a/common/integration/kafka-integrations/pom.xml b/common/integration/kafka-integrations/pom.xml index a6604aaa9b..72903d57d5 100644 --- a/common/integration/kafka-integrations/pom.xml +++ b/common/integration/kafka-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -34,8 +34,8 @@ script-api - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/integration/mqtt-integrations/pom.xml b/common/integration/mqtt-integrations/pom.xml index b3d3a1dcb0..62368cdaf3 100644 --- a/common/integration/mqtt-integrations/pom.xml +++ b/common/integration/mqtt-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -47,7 +47,12 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + provided + + + org.springframework.boot + spring-boot-jackson2 provided diff --git a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/AbstractMqttIntegration.java b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/AbstractMqttIntegration.java index facbd80692..f556037fd0 100644 --- a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/AbstractMqttIntegration.java +++ b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/AbstractMqttIntegration.java @@ -249,7 +249,7 @@ public abstract class AbstractMqttIntegration exte protected Optional initSslContext(MqttClientConfiguration configuration) throws SSLException { Optional result = configuration.getCredentials().initSslContext(); if (configuration.isSsl() && result.isEmpty()) { - result = Optional.of(SslContextBuilder.forClient().build()); + result = Optional.of(SslContextBuilder.forClient().endpointIdentificationAlgorithm(null).build()); } return result; } diff --git a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/azure/AzureIotHubSasCredentials.java b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/azure/AzureIotHubSasCredentials.java index ad717ce76d..c235b9aedd 100644 --- a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/azure/AzureIotHubSasCredentials.java +++ b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/azure/AzureIotHubSasCredentials.java @@ -7,7 +7,7 @@ import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import lombok.Data; import lombok.extern.slf4j.Slf4j; -import org.apache.tomcat.util.codec.binary.Base64; +import org.apache.commons.codec.binary.Base64; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.thingsboard.common.util.AzureIotHubUtil; import org.thingsboard.integration.mqtt.credentials.MqttClientCredentials; @@ -39,6 +39,7 @@ public class AzureIotHubSasCredentials implements MqttClientCredentials { caCert = AzureIotHubUtil.getDefaultCaCert(); } return Optional.of(SslContextBuilder.forClient() + .endpointIdentificationAlgorithm(null) .trustManager(createAndInitTrustManagerFactory()) .clientAuth(ClientAuth.REQUIRE) .build()); diff --git a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/credentials/CertPemClientCredentials.java b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/credentials/CertPemClientCredentials.java index ed46485831..5e76cfb8a9 100644 --- a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/credentials/CertPemClientCredentials.java +++ b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/credentials/CertPemClientCredentials.java @@ -52,6 +52,7 @@ public class CertPemClientCredentials implements MqttClientCredentials { try { Security.addProvider(new BouncyCastleProvider()); return Optional.of(SslContextBuilder.forClient() + .endpointIdentificationAlgorithm(null) .keyManager(createAndInitKeyManagerFactory()) .trustManager(createAndInitTrustManagerFactory()) .clientAuth(ClientAuth.REQUIRE) diff --git a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/ttn/TtnIntegration.java b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/ttn/TtnIntegration.java index 8f972f3e99..fcc5bac2f1 100644 --- a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/ttn/TtnIntegration.java +++ b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/ttn/TtnIntegration.java @@ -59,6 +59,7 @@ public class TtnIntegration extends BasicMqttIntegration { if (configuration.isSsl()) { Security.addProvider(new BouncyCastleProvider()); return Optional.of(SslContextBuilder.forClient() + .endpointIdentificationAlgorithm(null) .keyManager((KeyManagerFactory) null) .trustManager((File) null) .clientAuth(ClientAuth.NONE) diff --git a/common/integration/opcua-integrations/pom.xml b/common/integration/opcua-integrations/pom.xml index 79302fd0ec..3a7e8adc58 100644 --- a/common/integration/opcua-integrations/pom.xml +++ b/common/integration/opcua-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -35,13 +35,22 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + provided + + + org.springframework.boot + spring-boot-jackson2 provided org.eclipse.milo sdk-client + + javax.xml.bind + jaxb-api + diff --git a/common/integration/opcua-integrations/src/main/java/org/thingsboard/integration/opcua/OpcUaConfigurationTools.java b/common/integration/opcua-integrations/src/main/java/org/thingsboard/integration/opcua/OpcUaConfigurationTools.java index 108bd7832e..4e1cc63534 100644 --- a/common/integration/opcua-integrations/src/main/java/org/thingsboard/integration/opcua/OpcUaConfigurationTools.java +++ b/common/integration/opcua-integrations/src/main/java/org/thingsboard/integration/opcua/OpcUaConfigurationTools.java @@ -3,7 +3,7 @@ package org.thingsboard.integration.opcua; import lombok.extern.slf4j.Slf4j; -import org.apache.tomcat.util.codec.binary.Base64; +import org.apache.commons.codec.binary.Base64; import java.io.ByteArrayInputStream; import java.io.IOException; diff --git a/common/integration/pom.xml b/common/integration/pom.xml index 3ee67d5101..767aedcbaa 100644 --- a/common/integration/pom.xml +++ b/common/integration/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/integration/rabbitmq-integrations/pom.xml b/common/integration/rabbitmq-integrations/pom.xml index ac28a4cd67..ab0891c19b 100644 --- a/common/integration/rabbitmq-integrations/pom.xml +++ b/common/integration/rabbitmq-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -30,8 +30,8 @@ integration-api - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/integration/remote-integration-api/pom.xml b/common/integration/remote-integration-api/pom.xml index 2db388a166..79b3773494 100644 --- a/common/integration/remote-integration-api/pom.xml +++ b/common/integration/remote-integration-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -62,8 +62,8 @@ spring-context - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web io.netty diff --git a/common/integration/tuya-integrations/pom.xml b/common/integration/tuya-integrations/pom.xml index 11805ef149..239c2767b1 100644 --- a/common/integration/tuya-integrations/pom.xml +++ b/common/integration/tuya-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration @@ -34,8 +34,8 @@ script-api - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/integration/tuya-integrations/src/main/java/org/thingsboard/integration/tuya/TuyaIntegration.java b/common/integration/tuya-integrations/src/main/java/org/thingsboard/integration/tuya/TuyaIntegration.java index cf0423225b..11ab63a3a6 100644 --- a/common/integration/tuya-integrations/src/main/java/org/thingsboard/integration/tuya/TuyaIntegration.java +++ b/common/integration/tuya-integrations/src/main/java/org/thingsboard/integration/tuya/TuyaIntegration.java @@ -14,7 +14,6 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; -import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import org.thingsboard.common.util.HmacSHA256Util; import org.thingsboard.common.util.JacksonUtil; @@ -231,6 +230,7 @@ public class TuyaIntegration extends AbstractIntegration { UplinkData uplinkDataResult = UplinkData.builder().deviceName(uplinkData.getDeviceName()) .deviceType(uplinkData.getDeviceType()).telemetry(uplinkData.getTelemetry()) .attributesUpdate(uplinkData.getAttributesUpdate()).customerName(uplinkData.getCustomerName()) + .telemetryTypeCastDisabledKeys(uplinkData.getTelemetryTypeCastDisabledKeys()).attributesTypeCastDisabledKeys(uplinkData.getAttributesTypeCastDisabledKeys()) .build(); this.processUplinkDataBlocking(this.context, uplinkDataResult); } @@ -438,7 +438,7 @@ public class TuyaIntegration extends AbstractIntegration { private RequestEntity createGetRequest(String path, boolean getToken) throws Exception { HttpMethod httpMethod = HttpMethod.GET; String ts = String.valueOf(System.currentTimeMillis()); - MultiValueMap httpHeaders = createHeaders(ts); + HttpHeaders httpHeaders = createHeaders(ts); String strToSign; if (getToken) { strToSign = tuyaIntegrationConfiguration.getAccessId() + ts + formatStringToSign(path, getBodyHash(null), httpMethod); @@ -455,7 +455,7 @@ public class TuyaIntegration extends AbstractIntegration { private RequestEntity createPostRequest(String path, ObjectNode body) throws Exception { HttpMethod httpMethod = HttpMethod.POST; String ts = String.valueOf(System.currentTimeMillis()); - MultiValueMap httpHeaders = createHeaders(ts); + HttpHeaders httpHeaders = createHeaders(ts); httpHeaders.add("access_token", accessToken.getAccessToken()); String strToSign = tuyaIntegrationConfiguration.getAccessId() + accessToken.getAccessToken() + ts + formatStringToSign(path, getBodyHash(body.toString()), httpMethod); diff --git a/common/integration/tuya-integrations/src/main/java/org/thingsboard/integration/tuya/TuyaIntegrationConfiguration.java b/common/integration/tuya-integrations/src/main/java/org/thingsboard/integration/tuya/TuyaIntegrationConfiguration.java index f7c6184128..710e8605f2 100644 --- a/common/integration/tuya-integrations/src/main/java/org/thingsboard/integration/tuya/TuyaIntegrationConfiguration.java +++ b/common/integration/tuya-integrations/src/main/java/org/thingsboard/integration/tuya/TuyaIntegrationConfiguration.java @@ -19,7 +19,7 @@ public class TuyaIntegrationConfiguration { secret = true, group = "Tuya Connection", required = true) private String accessId; - @TemplateField(key = "tuyaAccessKey", label = "Access key", + @TemplateField(key = "tuyaAccessKey", label = "Access Secret", type = FormFieldType.PASSWORD, secret = true, group = "Tuya Connection", required = true) private String accessKey; diff --git a/common/message/pom.xml b/common/message/pom.xml index 05f4d7a4ea..e048cd5802 100644 --- a/common/message/pom.xml +++ b/common/message/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/message/src/main/java/org/thingsboard/server/common/msg/TbMsg.java b/common/message/src/main/java/org/thingsboard/server/common/msg/TbMsg.java index aa72bfe1bb..34f571b32e 100644 --- a/common/message/src/main/java/org/thingsboard/server/common/msg/TbMsg.java +++ b/common/message/src/main/java/org/thingsboard/server/common/msg/TbMsg.java @@ -28,6 +28,7 @@ import org.thingsboard.server.common.msg.queue.TbMsgCallback; import java.io.Serializable; import java.util.List; import java.util.Objects; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; @@ -270,6 +271,16 @@ public final class TbMsg implements Serializable { return ts; } + /** + * The keys whose numeric-looking string values must stay strings when the message data is parsed again. + * + * @see TbMsgMetaData#putTypeCastDisabledKeys + */ + @JsonIgnore + public Set getTypeCastDisabledKeys() { + return metaData.getTypeCastDisabledKeys(); + } + private TbMsgType getInternalType(String type) { if (type != null) { try { diff --git a/common/message/src/main/java/org/thingsboard/server/common/msg/TbMsgMetaData.java b/common/message/src/main/java/org/thingsboard/server/common/msg/TbMsgMetaData.java index 1fc0806ef9..295b3ebee5 100644 --- a/common/message/src/main/java/org/thingsboard/server/common/msg/TbMsgMetaData.java +++ b/common/message/src/main/java/org/thingsboard/server/common/msg/TbMsgMetaData.java @@ -1,14 +1,21 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.common.msg; import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Data; +import org.thingsboard.server.common.data.StringUtils; import java.io.Serializable; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @Data @@ -16,6 +23,15 @@ public final class TbMsgMetaData implements Serializable { public static final TbMsgMetaData EMPTY = new TbMsgMetaData(0); + /** + * Carries the keys whose numeric-looking string values must stay strings, from an integration uplink or an attributes + * updated notification, to the rule nodes that parse the message data again with {@code JsonConverter}. + */ + public static final String TYPE_CAST_DISABLED_KEYS = "typeCastDisabledKeys"; + + private static final ObjectMapper TYPE_CAST_DISABLED_KEYS_MAPPER = new ObjectMapper(); + private static final TypeReference> TYPE_CAST_DISABLED_KEYS_TYPE = new TypeReference<>() {}; + private final Map data; public TbMsgMetaData() { @@ -44,6 +60,34 @@ public final class TbMsgMetaData implements Serializable { } } + // A JSON array, since keys may contain commas. + public void putTypeCastDisabledKeys(Collection keys) { + if (keys != null && !keys.isEmpty()) { + try { + putValue(TYPE_CAST_DISABLED_KEYS, TYPE_CAST_DISABLED_KEYS_MAPPER.writeValueAsString(keys)); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException("The given keys cannot be written as a JSON array: " + keys, e); + } + } + } + + /** + * Returns the keys written by {@link #putTypeCastDisabledKeys(Collection)}; empty when there are none or the value is not a JSON array. + */ + @JsonIgnore + public Set getTypeCastDisabledKeys() { + String value = getValue(TYPE_CAST_DISABLED_KEYS); + if (StringUtils.isEmpty(value)) { + return Collections.emptySet(); + } + try { + Set keys = TYPE_CAST_DISABLED_KEYS_MAPPER.readValue(value, TYPE_CAST_DISABLED_KEYS_TYPE); + return keys != null ? keys : Collections.emptySet(); + } catch (JsonProcessingException e) { + return Collections.emptySet(); + } + } + public Map values() { return new HashMap<>(data); } diff --git a/common/message/src/test/java/org/thingsboard/server/common/msg/TbMsgMetaDataTest.java b/common/message/src/test/java/org/thingsboard/server/common/msg/TbMsgMetaDataTest.java index 1494384acd..30e3c57842 100644 --- a/common/message/src/test/java/org/thingsboard/server/common/msg/TbMsgMetaDataTest.java +++ b/common/message/src/test/java/org/thingsboard/server/common/msg/TbMsgMetaDataTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.common.msg; import com.fasterxml.jackson.core.type.TypeReference; @@ -7,9 +8,15 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.msg.TbMsgType; +import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.UUID; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; public class TbMsgMetaDataTest { @@ -40,4 +47,54 @@ public class TbMsgMetaDataTest { Map dataActual = tbMsgMetaData.copy().getData(); assertEquals(metadataExpected.size() - 1, dataActual.size()); } + + @Test + public void testPutAndGetTypeCastDisabledKeysRoundTripKeysWithCommas() { + TbMsgMetaData metaData = new TbMsgMetaData(); + metaData.putTypeCastDisabledKeys(List.of("a,b", "c\"d")); + assertThat(metaData.getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isEqualTo("[\"a,b\",\"c\\\"d\"]"); + assertThat(metaData.getTypeCastDisabledKeys()).containsExactlyInAnyOrder("a,b", "c\"d"); + } + + @Test + public void testPutTypeCastDisabledKeysSkipsEmptyAndNull() { + TbMsgMetaData metaData = new TbMsgMetaData(); + metaData.putTypeCastDisabledKeys(Set.of()); + metaData.putTypeCastDisabledKeys(null); + assertThat(metaData.getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isNull(); + assertThat(metaData.getTypeCastDisabledKeys()).isEmpty(); + } + + @Test + public void testGetTypeCastDisabledKeysIsEmptyForInvalidValue() { + TbMsgMetaData metaData = new TbMsgMetaData(); + metaData.putValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS, "joinEui,devAddr"); + assertThat(metaData.getTypeCastDisabledKeys()).isEmpty(); + metaData.putValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS, "{\"a\":1}"); + assertThat(metaData.getTypeCastDisabledKeys()).isEmpty(); + metaData.putValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS, "null"); + assertThat(metaData.getTypeCastDisabledKeys()).isEmpty(); + assertThat(new TbMsgMetaData().getTypeCastDisabledKeys()).isEqualTo(Set.of()); + } + + @Test + public void testTbMsgReadsTypeCastDisabledKeysFromItsMetaData() { + TbMsgMetaData metaData = new TbMsgMetaData(); + metaData.putTypeCastDisabledKeys(List.of("joinEui")); + TbMsg msg = TbMsg.newMsg() + .type(TbMsgType.POST_ATTRIBUTES_REQUEST) + .originator(new DeviceId(UUID.randomUUID())) + .metaData(metaData) + .data("{}") + .build(); + assertThat(msg.getTypeCastDisabledKeys()).containsExactly("joinEui"); + assertThat(TbMsg.newMsg() + .type(TbMsgType.POST_ATTRIBUTES_REQUEST) + .originator(new DeviceId(UUID.randomUUID())) + .metaData(new TbMsgMetaData()) + .data("{}") + .build() + .getTypeCastDisabledKeys()).isEmpty(); + } + } diff --git a/common/pom.xml b/common/pom.xml index ecef58c721..82668ff2a9 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard common diff --git a/common/proto/pom.xml b/common/proto/pom.xml index 49e8d9e7bc..aae9f9c406 100644 --- a/common/proto/pom.xml +++ b/common/proto/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common @@ -63,7 +63,12 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + provided + + + org.springframework.boot + spring-boot-jackson2 provided diff --git a/common/proto/src/main/java/org/thingsboard/server/common/adaptor/JsonConverter.java b/common/proto/src/main/java/org/thingsboard/server/common/adaptor/JsonConverter.java index cecb4fb4ed..4a08382420 100644 --- a/common/proto/src/main/java/org/thingsboard/server/common/adaptor/JsonConverter.java +++ b/common/proto/src/main/java/org/thingsboard/server/common/adaptor/JsonConverter.java @@ -17,12 +17,14 @@ import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; import org.thingsboard.server.common.data.kv.BooleanDataEntry; +import org.thingsboard.server.common.data.kv.DataType; import org.thingsboard.server.common.data.kv.DoubleDataEntry; import org.thingsboard.server.common.data.kv.JsonDataEntry; import org.thingsboard.server.common.data.kv.KvEntry; import org.thingsboard.server.common.data.kv.LongDataEntry; import org.thingsboard.server.common.data.kv.StringDataEntry; import org.thingsboard.server.common.data.util.TbPair; +import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.gateway.metrics.GatewayMetadata; import org.thingsboard.server.gen.transport.TransportProtos; import org.thingsboard.server.gen.transport.TransportProtos.AttributeUpdateNotificationMsg; @@ -59,6 +61,7 @@ import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.function.Consumer; +import java.util.stream.Collectors; public class JsonConverter { @@ -80,10 +83,10 @@ public class JsonConverter { return convertToTelemetryProto(jsonElement, System.currentTimeMillis()); } - // String values of noCastKeys stay strings even when type cast is enabled. - public static PostTelemetryMsg convertToTelemetryProto(JsonElement jsonElement, Set noCastKeys) throws JsonSyntaxException { + // String values of typeCastDisabledKeys stay strings even when type cast is enabled. + public static PostTelemetryMsg convertToTelemetryProto(JsonElement jsonElement, Set typeCastDisabledKeys) throws JsonSyntaxException { PostTelemetryMsg.Builder builder = PostTelemetryMsg.newBuilder(); - convertToTelemetry(jsonElement, System.currentTimeMillis(), null, builder, noCastKeys); + convertToTelemetry(jsonElement, System.currentTimeMillis(), null, builder, typeCastDisabledKeys); return builder.build(); } @@ -130,13 +133,13 @@ public class JsonConverter { return element; } - private static void convertToTelemetry(JsonElement jsonElement, long systemTs, Map> result, PostTelemetryMsg.Builder builder, Set noCastKeys) { + private static void convertToTelemetry(JsonElement jsonElement, long systemTs, Map> result, PostTelemetryMsg.Builder builder, Set typeCastDisabledKeys) { if (jsonElement.isJsonObject()) { - parseObject(systemTs, result, builder, jsonElement.getAsJsonObject(), noCastKeys); + parseObject(systemTs, result, builder, jsonElement.getAsJsonObject(), typeCastDisabledKeys); } else if (jsonElement.isJsonArray()) { jsonElement.getAsJsonArray().forEach(je -> { if (je.isJsonObject()) { - parseObject(systemTs, result, builder, je.getAsJsonObject(), noCastKeys); + parseObject(systemTs, result, builder, je.getAsJsonObject(), typeCastDisabledKeys); } else { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + je); } @@ -146,12 +149,12 @@ public class JsonConverter { } } - private static void parseObject(long systemTs, Map> result, PostTelemetryMsg.Builder builder, JsonObject jo, Set noCastKeys) { + private static void parseObject(long systemTs, Map> result, PostTelemetryMsg.Builder builder, JsonObject jo, Set typeCastDisabledKeys) { try { if (result != null) { - parseObject(result, systemTs, jo); + parseObject(result, systemTs, jo, typeCastDisabledKeys); } else { - parseObject(builder, systemTs, jo, noCastKeys); + parseObject(builder, systemTs, jo, typeCastDisabledKeys); } } catch (Exception e) { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + jo); @@ -197,11 +200,11 @@ public class JsonConverter { return convertToAttributesProto(jsonObject, Collections.emptySet()); } - // String values of noCastKeys stay strings even when type cast is enabled. - public static PostAttributeMsg convertToAttributesProto(JsonElement jsonObject, Set noCastKeys) throws JsonSyntaxException { + // String values of typeCastDisabledKeys stay strings even when type cast is enabled. + public static PostAttributeMsg convertToAttributesProto(JsonElement jsonObject, Set typeCastDisabledKeys) throws JsonSyntaxException { if (jsonObject.isJsonObject()) { PostAttributeMsg.Builder result = PostAttributeMsg.newBuilder(); - List keyValueList = parseProtoValues(jsonObject.getAsJsonObject(), noCastKeys); + List keyValueList = parseProtoValues(jsonObject.getAsJsonObject(), typeCastDisabledKeys); result.addAllKv(keyValueList); return result.build(); } else { @@ -219,22 +222,22 @@ public class JsonConverter { return result; } - private static void parseObject(PostTelemetryMsg.Builder builder, long systemTs, JsonObject jo, Set noCastKeys) { + private static void parseObject(PostTelemetryMsg.Builder builder, long systemTs, JsonObject jo, Set typeCastDisabledKeys) { if (jo.has("ts") && jo.has("values")) { - parseWithTs(builder, jo, noCastKeys); + parseWithTs(builder, jo, typeCastDisabledKeys); } else { - parseWithoutTs(builder, systemTs, jo, noCastKeys); + parseWithoutTs(builder, systemTs, jo, typeCastDisabledKeys); } } - private static void parseWithoutTs(PostTelemetryMsg.Builder request, long systemTs, JsonObject jo, Set noCastKeys) { + private static void parseWithoutTs(PostTelemetryMsg.Builder request, long systemTs, JsonObject jo, Set typeCastDisabledKeys) { TsKvListProto.Builder builder = TsKvListProto.newBuilder(); builder.setTs(systemTs); - builder.addAllKv(parseProtoValues(jo, noCastKeys)); + builder.addAllKv(parseProtoValues(jo, typeCastDisabledKeys)); request.addTsKvList(builder.build()); } - private static void parseWithTs(PostTelemetryMsg.Builder request, JsonObject jo, Set noCastKeys) { + private static void parseWithTs(PostTelemetryMsg.Builder request, JsonObject jo, Set typeCastDisabledKeys) { JsonElement tsJsonElement = jo.get("ts"); if (tsJsonElement.isJsonNull()) { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + "ts is null!"); @@ -243,12 +246,12 @@ public class JsonConverter { } else { TsKvListProto.Builder builder = TsKvListProto.newBuilder(); builder.setTs(tsJsonElement.getAsLong()); - builder.addAllKv(parseProtoValues(jo.get("values").getAsJsonObject(), noCastKeys)); + builder.addAllKv(parseProtoValues(jo.get("values").getAsJsonObject(), typeCastDisabledKeys)); request.addTsKvList(builder.build()); } } - private static List parseProtoValues(JsonObject valuesObject, Set noCastKeys) { + private static List parseProtoValues(JsonObject valuesObject, Set typeCastDisabledKeys) { List result = new ArrayList<>(); for (Entry valueEntry : valuesObject.entrySet()) { JsonElement element = valueEntry.getValue(); @@ -259,7 +262,7 @@ public class JsonConverter { String message = String.format("String value length [%d] for key [%s] is greater than maximum allowed [%d]", value.getAsString().length(), valueEntry.getKey(), maxStringValueLength); throw new JsonSyntaxException(message); } - if (isTypeCastEnabled && !noCastKeys.contains(valueEntry.getKey()) && NumberUtils.isParsable(value.getAsString())) { + if (isTypeCastEnabled && !typeCastDisabledKeys.contains(valueEntry.getKey()) && isNumericString(value.getAsString())) { try { result.add(buildNumericKeyValueProto(value, valueEntry.getKey())); } catch (RuntimeException th) { @@ -631,10 +634,41 @@ public class JsonConverter { } public static List convertToAttributes(JsonElement element, long ts) { - return parseValues(element.getAsJsonObject()).stream().map(kv -> new BaseAttributeKvEntry(kv, ts)).toList(); + return convertToAttributes(element, ts, Collections.emptySet()); } - private static List parseValues(JsonObject valuesObject) { + /** + * Returns the keys of the string entries that this converter would cast to a number, in entry order, so that a message + * built from typed entries, such as an attributes updated notification, can mark them to read back as strings. + */ + public static List numericStringKeys(Collection entries) { + if (entries == null) { + return Collections.emptyList(); + } + return entries.stream() + .filter(entry -> entry.getDataType() == DataType.STRING && isNumericString(entry.getValueAsString())) + .map(KvEntry::getKey) + .collect(Collectors.toList()); + } + + private static boolean isNumericString(String value) { + return NumberUtils.isParsable(value); + } + + /** + * Turns a rule engine message's data into attributes, with the current time as their ts. + * Honours {@link TbMsg#getTypeCastDisabledKeys()}: the keys marked to stay strings by the integration on an uplink, + * and by the save attributes node on its attributes updated notification. + */ + public static List attributesFromMsg(TbMsg msg) { + return convertToAttributes(JsonParser.parseString(msg.getData()), System.currentTimeMillis(), msg.getTypeCastDisabledKeys()); + } + + private static List convertToAttributes(JsonElement element, long ts, Set typeCastDisabledKeys) { + return parseValues(element.getAsJsonObject(), typeCastDisabledKeys).stream().map(kv -> new BaseAttributeKvEntry(kv, ts)).toList(); + } + + private static List parseValues(JsonObject valuesObject, Set typeCastDisabledKeys) { List result = new ArrayList<>(); for (Entry valueEntry : valuesObject.entrySet()) { JsonElement element = valueEntry.getValue(); @@ -645,7 +679,7 @@ public class JsonConverter { String message = String.format("String value length [%d] for key [%s] is greater than maximum allowed [%d]", value.getAsString().length(), valueEntry.getKey(), maxStringValueLength); throw new JsonSyntaxException(message); } - if (isTypeCastEnabled && NumberUtils.isParsable(value.getAsString())) { + if (isTypeCastEnabled && !typeCastDisabledKeys.contains(valueEntry.getKey()) && isNumericString(value.getAsString())) { try { parseNumericValue(result, valueEntry, value); } catch (RuntimeException th) { @@ -680,29 +714,53 @@ public class JsonConverter { return convertToTelemetry(jsonElement, systemTs, true); } + /** + * Turns a rule engine message's data into telemetry; {@code ts} is used for values that carry no ts of their own. + * Honours {@link TbMsg#getTypeCastDisabledKeys()}: the keys the integration marked to stay strings. + */ + public static Map> telemetryFromMsg(TbMsg msg, long ts) throws JsonSyntaxException { + return convertToTelemetry(JsonParser.parseString(msg.getData()), ts, false, msg.getTypeCastDisabledKeys()); + } + + /** + * Same as {@link #telemetryFromMsg(TbMsg, long)}, with the result sorted by ts. + */ + public static Map> sortedTelemetryFromMsg(TbMsg msg, long ts) throws JsonSyntaxException { + return convertToTelemetry(JsonParser.parseString(msg.getData()), ts, true, msg.getTypeCastDisabledKeys()); + } + public static Map> convertToTelemetry(JsonElement jsonElement, long systemTs, boolean sorted) throws JsonSyntaxException { + return convertToTelemetry(jsonElement, systemTs, sorted, Collections.emptySet()); + } + + private static Map> convertToTelemetry(JsonElement jsonElement, long systemTs, boolean sorted, Set typeCastDisabledKeys) throws + JsonSyntaxException { Map> result = sorted ? new TreeMap<>() : new HashMap<>(); - convertToTelemetry(jsonElement, systemTs, result, null, Collections.emptySet()); + convertToTelemetry(jsonElement, systemTs, result, null, typeCastDisabledKeys); return result; } - private static void parseObject(Map> result, long systemTs, JsonObject jo) { + private static void parseObject(Map> result, long systemTs, JsonObject jo, Set typeCastDisabledKeys) { if (jo.has("ts") && jo.has("values")) { - parseWithTs(result, jo); + parseWithTs(result, jo, typeCastDisabledKeys); } else { - parseWithoutTs(result, systemTs, jo); + parseWithoutTs(result, systemTs, jo, typeCastDisabledKeys); } } - private static void parseWithoutTs(Map> result, long systemTs, JsonObject jo) { - for (KvEntry entry : parseValues(jo)) { + private static void parseWithoutTs(Map> result, long systemTs, JsonObject jo, Set typeCastDisabledKeys) { + for (KvEntry entry : parseValues(jo, typeCastDisabledKeys)) { result.computeIfAbsent(systemTs, tmp -> new ArrayList<>()).add(entry); } } public static void parseWithTs(Map> result, JsonObject jo) { + parseWithTs(result, jo, Collections.emptySet()); + } + + private static void parseWithTs(Map> result, JsonObject jo, Set typeCastDisabledKeys) { JsonElement tsJsonElement = jo.get("ts"); if (tsJsonElement.isJsonNull()) { throw new JsonSyntaxException(CAN_T_PARSE_VALUE + "ts is null!"); @@ -711,7 +769,7 @@ public class JsonConverter { } else { long ts = tsJsonElement.getAsLong(); JsonObject valuesObject = jo.get("values").getAsJsonObject(); - for (KvEntry entry : parseValues(valuesObject)) { + for (KvEntry entry : parseValues(valuesObject, typeCastDisabledKeys)) { result.computeIfAbsent(ts, tmp -> new ArrayList<>()).add(entry); } } diff --git a/common/proto/src/main/proto/integration.proto b/common/proto/src/main/proto/integration.proto index 2284b1dd70..88e317a1a3 100644 --- a/common/proto/src/main/proto/integration.proto +++ b/common/proto/src/main/proto/integration.proto @@ -74,6 +74,8 @@ message DeviceUplinkDataProto { transport.PostTelemetryMsg postTelemetryMsg = 5; transport.PostAttributeMsg postAttributesMsg = 6; string deviceLabel = 7; + repeated string telemetryTypeCastDisabledKeys = 8; + repeated string attributesTypeCastDisabledKeys = 9; } message AssetUplinkDataProto { @@ -84,6 +86,8 @@ message AssetUplinkDataProto { transport.PostTelemetryMsg postTelemetryMsg = 5; transport.PostAttributeMsg postAttributesMsg = 6; string assetLabel = 7; + repeated string telemetryTypeCastDisabledKeys = 8; + repeated string attributesTypeCastDisabledKeys = 9; } message EntityViewDataProto { diff --git a/common/proto/src/test/java/org/thingsboard/server/common/adaptor/JsonConverterTest.java b/common/proto/src/test/java/org/thingsboard/server/common/adaptor/JsonConverterTest.java index a06f47494c..53793c9991 100644 --- a/common/proto/src/test/java/org/thingsboard/server/common/adaptor/JsonConverterTest.java +++ b/common/proto/src/test/java/org/thingsboard/server/common/adaptor/JsonConverterTest.java @@ -10,10 +10,27 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Isolated; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; +import org.thingsboard.server.common.data.kv.DataType; +import org.thingsboard.server.common.data.kv.DoubleDataEntry; +import org.thingsboard.server.common.data.kv.KvEntry; +import org.thingsboard.server.common.data.kv.LongDataEntry; +import org.thingsboard.server.common.data.kv.StringDataEntry; +import org.thingsboard.server.common.data.msg.TbMsgType; +import org.thingsboard.server.common.msg.TbMsg; +import org.thingsboard.server.common.msg.TbMsgMetaData; import org.thingsboard.server.gen.transport.TransportProtos.KeyValueProto; import org.thingsboard.server.gen.transport.TransportProtos.KeyValueType; +import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; @Isolated("JsonConverter static settings being modified") public class JsonConverterTest { @@ -100,7 +117,7 @@ public class JsonConverterTest { } @Test - public void testParseAttributesProtoWithNoCastKeys() { + public void testParseAttributesProtoWithTypeCastDisabledKeys() { var json = JsonParser.parseString("{\"devAddr\": \"01020304\", \"fCnt\": \"42\", \"rssi\": -110}"); var kvList = JsonConverter.convertToAttributesProto(json, Set.of("devAddr")).getKvList(); assertKv(kvList.get(0), KeyValueType.STRING_V, "01020304"); @@ -109,7 +126,7 @@ public class JsonConverterTest { } @Test - public void testParseTelemetryProtoWithNoCastKeys() { + public void testParseTelemetryProtoWithTypeCastDisabledKeys() { var json = JsonParser.parseString("{\"ts\": 1000, \"values\": {\"eui\": \"1000000000000001\", \"fCnt\": \"42\", \"snr\": 9.5}}"); var tsKvList = JsonConverter.convertToTelemetryProto(json, Set.of("eui")).getTsKvList(0); Assertions.assertEquals(1000L, tsKvList.getTs()); @@ -124,6 +141,115 @@ public class JsonConverterTest { assertKv(kvList.get(0), KeyValueType.LONG_V, "1020304"); } + @Test + public void testAttributesFromMsgWithTypeCastDisabledKeys() { + var msg = msg("{\"joinEui\": \"0000000000000000\", \"hardwareVersion\": \"1.0\", \"fCnt\": \"42\", \"rssi\": -110}", Set.of("joinEui", "hardwareVersion")); + Map kvs = toMap(JsonConverter.attributesFromMsg(msg)); + assertEntry(kvs.get("joinEui"), DataType.STRING, "0000000000000000"); + assertEntry(kvs.get("hardwareVersion"), DataType.STRING, "1.0"); + assertEntry(kvs.get("fCnt"), DataType.LONG, 42L); + assertEntry(kvs.get("rssi"), DataType.LONG, -110L); + } + + @Test + public void testConvertToAttributesCastsNumericStrings() { + var json = JsonParser.parseString("{\"joinEui\": \"0000000000000000\", \"hardwareVersion\": \"1.0\"}"); + Map kvs = toMap(JsonConverter.convertToAttributes(json, 1000L)); + assertEntry(kvs.get("joinEui"), DataType.LONG, 0L); + assertEntry(kvs.get("hardwareVersion"), DataType.DOUBLE, 1.0); + } + + @Test + public void testAttributesFromMsgWithoutTypeCastDisabledKeysCastsNumericStrings() { + var msg = msg("{\"joinEui\": \"0000000000000000\", \"hardwareVersion\": \"1.0\"}", Set.of()); + Map kvs = toMap(JsonConverter.attributesFromMsg(msg)); + assertEntry(kvs.get("joinEui"), DataType.LONG, 0L); + assertEntry(kvs.get("hardwareVersion"), DataType.DOUBLE, 1.0); + } + + @Test + public void testTelemetryFromMsgWithTypeCastDisabledKeys() { + var msg = msg("{\"devAddr\": \"01020304\", \"fCnt\": \"42\"}", Set.of("devAddr")); + Map> tsKv = JsonConverter.telemetryFromMsg(msg, 1000L); + Map kvs = toMap(tsKv.get(1000L)); + assertEntry(kvs.get("devAddr"), DataType.STRING, "01020304"); + assertEntry(kvs.get("fCnt"), DataType.LONG, 42L); + } + + @Test + public void testSortedTelemetryFromMsgWithTsAndTypeCastDisabledKeys() { + var msg = msg("[{\"ts\": 2000, \"values\": {\"devAddr\": \"01020304\", \"snr\": \"9.5\"}}, {\"ts\": 1000, \"values\": {\"devAddr\": \"01020305\"}}]", Set.of("devAddr")); + Map> tsKv = JsonConverter.sortedTelemetryFromMsg(msg, 0L); + Assertions.assertEquals(List.of(1000L, 2000L), List.copyOf(tsKv.keySet())); + assertEntry(toMap(tsKv.get(1000L)).get("devAddr"), DataType.STRING, "01020305"); + Map kvs = toMap(tsKv.get(2000L)); + assertEntry(kvs.get("devAddr"), DataType.STRING, "01020304"); + assertEntry(kvs.get("snr"), DataType.DOUBLE, 9.5); + } + + @Test + public void testConvertToTelemetryCastsNumericStrings() { + var json = JsonParser.parseString("{\"ts\": 1000, \"values\": {\"devAddr\": \"01020304\"}}"); + assertEntry(JsonConverter.convertToTelemetry(json, 0L).get(1000L).get(0), DataType.LONG, 1020304L); + assertEntry(JsonConverter.convertToSortedTelemetry(json, 0L).get(1000L).get(0), DataType.LONG, 1020304L); + } + + @Test + public void testTelemetryFromMsgWithoutTypeCastDisabledKeysCastsNumericStrings() { + var msg = msg("{\"ts\": 1000, \"values\": {\"devAddr\": \"01020304\"}}", Set.of()); + assertEntry(JsonConverter.telemetryFromMsg(msg, 0L).get(1000L).get(0), DataType.LONG, 1020304L); + assertEntry(JsonConverter.sortedTelemetryFromMsg(msg, 0L).get(1000L).get(0), DataType.LONG, 1020304L); + } + + @Test + public void testTelemetryFromMsgWithTypeCastDisabledKeysWhenTypeCastDisabled() { + JsonConverter.setTypeCastEnabled(false); + var msg = msg("{\"devAddr\": \"01020304\", \"fCnt\": \"42\"}", Set.of("devAddr")); + Map kvs = toMap(JsonConverter.telemetryFromMsg(msg, 1000L).get(1000L)); + assertEntry(kvs.get("devAddr"), DataType.STRING, "01020304"); + assertEntry(kvs.get("fCnt"), DataType.STRING, "42"); + } + + @Test + public void testNumericStringKeysListsOnlyStringsThatWouldBeCast() { + assertThat(JsonConverter.numericStringKeys(List.of( + new BaseAttributeKvEntry(new StringDataEntry("joinEui", "0000000000000000"), 0L), + new BaseAttributeKvEntry(new StringDataEntry("firmwareVersion", "1.10"), 0L), + new BaseAttributeKvEntry(new StringDataEntry("devEui", "70B3D57ED0012345"), 0L), + new BaseAttributeKvEntry(new LongDataEntry("fCnt", 42L), 0L), + new BaseAttributeKvEntry(new DoubleDataEntry("rssi", -97.5), 0L)))) + .containsExactly("joinEui", "firmwareVersion"); + } + + @Test + public void testNumericStringKeysIsEmptyWithoutNumericStrings() { + assertThat(JsonConverter.numericStringKeys(List.of( + new BaseAttributeKvEntry(new StringDataEntry("devEui", "70B3D57ED0012345"), 0L), + new BaseAttributeKvEntry(new LongDataEntry("fCnt", 42L), 0L)))).isEmpty(); + assertThat(JsonConverter.numericStringKeys(null)).isEmpty(); + } + + private static TbMsg msg(String data, Set typeCastDisabledKeys) { + TbMsgMetaData metaData = new TbMsgMetaData(); + metaData.putTypeCastDisabledKeys(typeCastDisabledKeys); + return TbMsg.newMsg() + .type(TbMsgType.POST_TELEMETRY_REQUEST) + .originator(new DeviceId(UUID.randomUUID())) + .metaData(metaData) + .data(data) + .build(); + } + + private static Map toMap(List entries) { + return entries.stream().collect(Collectors.toMap(KvEntry::getKey, Function.identity())); + } + + private static void assertEntry(KvEntry entry, DataType type, Object value) { + Assertions.assertNotNull(entry); + Assertions.assertEquals(type, entry.getDataType()); + Assertions.assertEquals(value, entry.getValue()); + } + private static void assertKv(KeyValueProto kv, KeyValueType type, String value) { Assertions.assertEquals(type, kv.getType()); String actual = switch (type) { diff --git a/common/queue/pom.xml b/common/queue/pom.xml index 7b5351abba..001ae31e66 100644 --- a/common/queue/pom.xml +++ b/common/queue/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/report/pom.xml b/common/report/pom.xml index 7aa634f468..34f19c64d1 100644 --- a/common/report/pom.xml +++ b/common/report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common @@ -58,13 +58,17 @@ rest-client compile + + org.springframework + spring-web + org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webclient org.springframework.boot - spring-boot-starter-webflux + spring-boot-jackson2 io.projectreactor.netty diff --git a/common/script/pom.xml b/common/script/pom.xml index 2fa3adae61..bd93302014 100644 --- a/common/script/pom.xml +++ b/common/script/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/script/remote-js-client/pom.xml b/common/script/remote-js-client/pom.xml index d04821e04f..9868dceaea 100644 --- a/common/script/remote-js-client/pom.xml +++ b/common/script/remote-js-client/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT script org.thingsboard.common.script @@ -47,8 +47,8 @@ message - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/script/script-api/pom.xml b/common/script/script-api/pom.xml index 081a2f3976..f7318222fd 100644 --- a/common/script/script-api/pom.xml +++ b/common/script/script-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT script org.thingsboard.common.script @@ -87,8 +87,8 @@ tbel - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/stats/pom.xml b/common/stats/pom.xml index 2873f94f9c..95d485d3c6 100644 --- a/common/stats/pom.xml +++ b/common/stats/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/coap/pom.xml b/common/transport/coap/pom.xml index 9a28d7c95c..7b2057706d 100644 --- a/common/transport/coap/pom.xml +++ b/common/transport/coap/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/http/pom.xml b/common/transport/http/pom.xml index f9f462da66..e12c064ae0 100644 --- a/common/transport/http/pom.xml +++ b/common/transport/http/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.common.transport @@ -32,7 +32,12 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + provided + + + org.springframework.boot + spring-boot-jackson2 provided diff --git a/common/transport/http/src/main/java/org/thingsboard/server/transport/http/HttpTransportContext.java b/common/transport/http/src/main/java/org/thingsboard/server/transport/http/HttpTransportContext.java index 811416f7f8..68187b3d45 100644 --- a/common/transport/http/src/main/java/org/thingsboard/server/transport/http/HttpTransportContext.java +++ b/common/transport/http/src/main/java/org/thingsboard/server/transport/http/HttpTransportContext.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.transport.http; import lombok.Getter; @@ -8,7 +9,7 @@ import org.apache.coyote.ProtocolHandler; import org.apache.coyote.http11.Http11NioProtocol; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer; +import org.springframework.boot.tomcat.TomcatConnectorCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.thingsboard.server.common.transport.TransportContext; diff --git a/common/transport/http/src/main/java/org/thingsboard/server/transport/http/config/TransportSecurityConfiguration.java b/common/transport/http/src/main/java/org/thingsboard/server/transport/http/config/TransportSecurityConfiguration.java index 6b167a6203..928d12e438 100644 --- a/common/transport/http/src/main/java/org/thingsboard/server/transport/http/config/TransportSecurityConfiguration.java +++ b/common/transport/http/src/main/java/org/thingsboard/server/transport/http/config/TransportSecurityConfiguration.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.transport.http.config; import org.springframework.beans.factory.annotation.Value; @@ -12,7 +13,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; @Configuration @EnableWebSecurity @@ -32,7 +33,7 @@ public class TransportSecurityConfiguration { @Order(1) SecurityFilterChain httpTransportFilterChain(HttpSecurity http) throws Exception { http - .securityMatcher(AntPathRequestMatcher.antMatcher(DEVICE_API_ENTRY_POINT)) + .securityMatcher(PathPatternRequestMatcher.withDefaults().matcher(DEVICE_API_ENTRY_POINT)) .cors(cors -> { }) .csrf(AbstractHttpConfigurer::disable) diff --git a/common/transport/http/src/test/java/org/thingsboard/server/transport/http/DeviceApiControllerTest.java b/common/transport/http/src/test/java/org/thingsboard/server/transport/http/DeviceApiControllerTest.java index 5d84a19bf4..ea8144ad2a 100644 --- a/common/transport/http/src/test/java/org/thingsboard/server/transport/http/DeviceApiControllerTest.java +++ b/common/transport/http/src/test/java/org/thingsboard/server/transport/http/DeviceApiControllerTest.java @@ -100,4 +100,31 @@ class DeviceApiControllerTest { assertThat(response.getValue().getHeaders().get(HttpHeaders.CONTENT_DISPOSITION)) .containsExactly("attachment; filename=\"Baker Street, 221B.bin\""); } + + @Test + void getOtaPackageCallbackWithNonAsciiFileName() { + UUID otaPackageId = UUID.randomUUID(); + OtaPackageDataCache otaPackageDataCache = Mockito.mock(OtaPackageDataCache.class); + Mockito.when(otaPackageDataCache.get(otaPackageId.toString(), 0, 0)).thenReturn(new byte[]{1, 2, 3}); + TransportContext transportContext = Mockito.mock(TransportContext.class); + Mockito.when(transportContext.getOtaPackageDataCache()).thenReturn(otaPackageDataCache); + DeferredResult responseWriter = Mockito.mock(DeferredResult.class); + + var callback = new DeviceApiController.GetOtaPackageCallback(transportContext, responseWriter, "Title", "1.0", 0, 0); + callback.onSuccess(TransportProtos.GetOtaPackageResponseMsg.newBuilder() + .setResponseStatus(TransportProtos.ResponseStatus.SUCCESS) + .setOtaPackageIdMSB(otaPackageId.getMostSignificantBits()) + .setOtaPackageIdLSB(otaPackageId.getLeastSignificantBits()) + .setTitle("Title") + .setVersion("1.0") + .setContentType("application/octet-stream") + .setFileName("Müller Прошивка.bin") + .build()); + + ArgumentCaptor response = ArgumentCaptor.forClass(ResponseEntity.class); + Mockito.verify(responseWriter).setResult(response.capture()); + assertThat(response.getValue().getHeaders().get(HttpHeaders.CONTENT_DISPOSITION)) + .containsExactly("attachment; filename=\"Mueller ________.bin\"; filename*=UTF-8''M%C3%BCller%20%D0%9F%D1%80%D0%BE%D1%88%D0%B8%D0%B2%D0%BA%D0%B0.bin"); + assertThat(response.getValue().getHeaders().get("x-filename")).containsExactly("Müller Прошивка.bin"); + } } diff --git a/common/transport/lwm2m/pom.xml b/common/transport/lwm2m/pom.xml index ccc051900f..d122e6b529 100644 --- a/common/transport/lwm2m/pom.xml +++ b/common/transport/lwm2m/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/DefaultLwM2mTransportService.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/DefaultLwM2mTransportService.java index d669148bef..c4c7422be7 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/DefaultLwM2mTransportService.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/DefaultLwM2mTransportService.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.transport.lwm2m.server; import jakarta.annotation.PreDestroy; @@ -108,6 +109,10 @@ public class DefaultLwM2mTransportService implements LwM2MTransportService, Smar @PreDestroy public void shutdown() { + LeshanServer server = this.server; + if (server == null) { + return; + } try { log.info("Stopping LwM2M transport server!"); server.destroy(); diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/model/LwM2MModelConfigServiceImpl.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/model/LwM2MModelConfigServiceImpl.java index 766ec91b9a..453686d975 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/model/LwM2MModelConfigServiceImpl.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/model/LwM2MModelConfigServiceImpl.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.transport.lwm2m.server.model; import jakarta.annotation.PreDestroy; @@ -65,7 +66,7 @@ public class LwM2MModelConfigServiceImpl implements LwM2MModelConfigService { @Autowired private LwM2MTelemetryLogService logService; - ConcurrentMap currentModelConfigs; + ConcurrentMap currentModelConfigs = new ConcurrentHashMap<>(); @AfterStartUp(order = AfterStartUp.BEFORE_TRANSPORT_SERVICE) public void init() { diff --git a/common/transport/lwm2m/src/test/java/org/thingsboard/server/transport/lwm2m/server/model/LwM2MModelConfigServiceImplTest.java b/common/transport/lwm2m/src/test/java/org/thingsboard/server/transport/lwm2m/server/model/LwM2MModelConfigServiceImplTest.java index 5de1add340..079086a0e7 100644 --- a/common/transport/lwm2m/src/test/java/org/thingsboard/server/transport/lwm2m/server/model/LwM2MModelConfigServiceImplTest.java +++ b/common/transport/lwm2m/src/test/java/org/thingsboard/server/transport/lwm2m/server/model/LwM2MModelConfigServiceImplTest.java @@ -1,9 +1,11 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.transport.lwm2m.server.model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.server.transport.lwm2m.server.store.TbLwM2MModelConfigStore; import java.util.Collections; @@ -11,6 +13,7 @@ import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.mock; @@ -57,4 +60,9 @@ class LwM2MModelConfigServiceImplTest { assertThat(service.currentModelConfigs).isEmpty(); } + @Test + void testDestroyBeforeInit() { + assertThatCode(() -> ReflectionTestUtils.invokeMethod(service, "destroy")).doesNotThrowAnyException(); + } + } diff --git a/common/transport/mqtt/pom.xml b/common/transport/mqtt/pom.xml index b499a5f591..bd6affb863 100644 --- a/common/transport/mqtt/pom.xml +++ b/common/transport/mqtt/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/pom.xml b/common/transport/pom.xml index 103dde135d..de208689cf 100644 --- a/common/transport/pom.xml +++ b/common/transport/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/snmp/pom.xml b/common/transport/snmp/pom.xml index d3a02e9848..bfa14cdd91 100644 --- a/common/transport/snmp/pom.xml +++ b/common/transport/snmp/pom.xml @@ -11,7 +11,7 @@ org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport diff --git a/common/transport/transport-api/pom.xml b/common/transport/transport-api/pom.xml index d141135c0d..1e86888779 100644 --- a/common/transport/transport-api/pom.xml +++ b/common/transport/transport-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.common.transport @@ -90,7 +90,12 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + provided + + + org.springframework.boot + spring-boot-jackson2 provided diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/config/ssl/SslCredentialsWebServerCustomizer.java b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/config/ssl/SslCredentialsWebServerCustomizer.java index 34af157c2e..63d2c85084 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/config/ssl/SslCredentialsWebServerCustomizer.java +++ b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/config/ssl/SslCredentialsWebServerCustomizer.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.common.transport.config.ssl; import lombok.extern.slf4j.Slf4j; @@ -7,7 +8,7 @@ import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.boot.web.server.autoconfigure.ServerProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.ssl.NoSuchSslBundleException; import org.springframework.boot.ssl.SslBundle; @@ -15,7 +16,7 @@ import org.springframework.boot.ssl.SslBundles; import org.springframework.boot.ssl.SslStoreBundle; import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.WebServerFactoryCustomizer; -import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; +import org.springframework.boot.web.server.servlet.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; diff --git a/common/transport/transport-api/src/test/java/org/thingsboard/server/common/transport/config/ssl/SslCredentialsWebServerCustomizerTest.java b/common/transport/transport-api/src/test/java/org/thingsboard/server/common/transport/config/ssl/SslCredentialsWebServerCustomizerTest.java index 4fa8e17466..b0b1bc9342 100644 --- a/common/transport/transport-api/src/test/java/org/thingsboard/server/common/transport/config/ssl/SslCredentialsWebServerCustomizerTest.java +++ b/common/transport/transport-api/src/test/java/org/thingsboard/server/common/transport/config/ssl/SslCredentialsWebServerCustomizerTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.common.transport.config.ssl; import org.junit.jupiter.api.BeforeEach; @@ -10,7 +11,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; -import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.boot.web.server.autoconfigure.ServerProperties; import org.springframework.boot.ssl.SslBundle; import org.springframework.boot.ssl.SslBundles; import org.springframework.test.util.ReflectionTestUtils; diff --git a/common/util/pom.xml b/common/util/pom.xml index 0fe6b896a4..970c553e91 100644 --- a/common/util/pom.xml +++ b/common/util/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/version-control/pom.xml b/common/version-control/pom.xml index 1b80246053..9f68f11d8e 100644 --- a/common/version-control/pom.xml +++ b/common/version-control/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common @@ -47,8 +47,8 @@ spring-context - org.springframework.boot - spring-boot-starter-web + org.springframework + spring-web provided diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java index afe209b96f..675c642ef3 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java @@ -150,7 +150,7 @@ public class DefaultGitSyncService implements GitSyncService { private Path getRepoDirectory(RepositorySettings settings) { // using uri to define folder name in case repo url is changed String name = URI.create(settings.getRepositoryUri()).getPath().replaceAll("[^a-zA-Z]", ""); - return Path.of(repositoriesFolder, name); + return GitRepository.resolveDirectory(repositoriesFolder, name); } private RevCommit getLastCommit(String key) { diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java index e1113315ec..5e4b9f4c65 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java @@ -358,7 +358,8 @@ public class DefaultGitRepositoryService implements GitRepositoryService { private GitRepository openOrCloneRepository(TenantId tenantId, RepositorySettings settings, boolean fetch) throws Exception { log.debug("[{}] Init tenant repository started.", tenantId); - Path repositoryDirectory = Path.of(repositoriesFolder, settings.isLocalOnly() ? "local_" + settings.getRepositoryUri() : tenantId.getId().toString()); + String directoryName = settings.isLocalOnly() ? "local_" + settings.getRepositoryUri() : tenantId.getId().toString(); + Path repositoryDirectory = GitRepository.resolveDirectory(repositoriesFolder, directoryName); GitRepository repository = GitRepository.openOrClone(repositoryDirectory, settings, fetch); repositories.put(tenantId, repository); log.debug("[{}] Init tenant repository completed.", tenantId); diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java index 9bb8e61ef9..c371c81bd8 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java @@ -476,6 +476,15 @@ public class GitRepository { return git.getRepository().resolve(rev); } + public static Path resolveDirectory(String repositoriesFolder, String directoryName) { + Path root = Path.of(repositoriesFolder).toAbsolutePath().normalize(); + Path directory = root.resolve(directoryName).normalize(); + if (!root.equals(directory.getParent()) || !directoryName.equals(directory.getFileName().toString())) { + throw new IllegalArgumentException("Repository directory name must be a single path segment"); + } + return directory; + } + @SneakyThrows public static boolean exists(String directory) { File gitDirectory = Path.of(directory, ".git").toFile(); diff --git a/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java new file mode 100644 index 0000000000..c7fdda9cc6 --- /dev/null +++ b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.sync.vc; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.sync.vc.RepositorySettings; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class DefaultGitRepositoryServiceTest { + + @TempDir + Path tempDir; + + private DefaultGitRepositoryService service; + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + + @BeforeEach + public void setUp() { + service = new DefaultGitRepositoryService(); + ReflectionTestUtils.setField(service, "repositoriesFolder", tempDir.toString()); + } + + @Test + public void localRepositoryIsCreatedDirectlyUnderRepositoriesFolder() throws Exception { + RepositorySettings settings = localSettings("repo1"); + + service.initRepository(tenantId, settings, false); + + assertThat(tempDir.resolve("local_repo1").resolve(".git")).isDirectory(); + assertThat(service.getRepositorySettings(tenantId)).isEqualTo(settings); + } + + @Test + public void localRepositoryNameWithMultipleSegmentsIsRejected() throws Exception { + Path marker = tempDir.resolve("keep").resolve("marker.txt"); + Files.createDirectories(marker.getParent()); + Files.writeString(marker, "content"); + + assertThatThrownBy(() -> service.initRepository(tenantId, localSettings("repo1/main"), false)) + .isInstanceOf(IllegalArgumentException.class); + + assertThat(tempDir.resolve("local_repo1")).doesNotExist(); + assertThat(marker).exists(); + assertThat(service.getRepositorySettings(tenantId)).isNull(); + } + + private RepositorySettings localSettings(String repositoryUri) { + RepositorySettings settings = new RepositorySettings(); + settings.setRepositoryUri(repositoryUri); + settings.setDefaultBranch("main"); + settings.setLocalOnly(true); + return settings; + } + +} diff --git a/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java new file mode 100644 index 0000000000..0ca2fd59cc --- /dev/null +++ b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.sync.vc; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class GitRepositoryTest { + + @TempDir + Path tempDir; + + @Test + public void directoryIsResolvedDirectlyUnderRepositoriesFolder() { + assertThat(GitRepository.resolveDirectory(tempDir.toString(), "repo1")) + .isEqualTo(tempDir.toAbsolutePath().normalize().resolve("repo1")); + } + + @Test + public void emptyDirectoryNameIsRejected() { + assertThatThrownBy(() -> GitRepository.resolveDirectory(tempDir.toString(), "")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void directoryNameThatIsNotNormalizedIsRejected() { + assertThatThrownBy(() -> GitRepository.resolveDirectory(tempDir.toString(), "./repo1")) + .isInstanceOf(IllegalArgumentException.class); + } + +} diff --git a/dao/pom.xml b/dao/pom.xml index 7945a562ff..ed9386f4df 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard dao @@ -96,16 +96,6 @@ awaitility test - - org.dbunit - dbunit - test - - - com.github.springtestdbunit - spring-test-dbunit - test - org.apache.commons commons-lang3 @@ -123,8 +113,8 @@ hibernate-validator - org.glassfish - jakarta.el + org.glassfish.expressly + expressly org.springframework @@ -205,22 +195,28 @@ org.testcontainers - cassandra + testcontainers-cassandra test + + + com.datastax.cassandra + cassandra-driver-core + + org.testcontainers - postgresql + testcontainers-postgresql test org.testcontainers - jdbc + testcontainers-jdbc test org.testcontainers - junit-jupiter + testcontainers-junit-jupiter test @@ -243,10 +239,6 @@ org.thingsboard.rule-engine rule-engine-api - - io.hypersistence - hypersistence-utils-hibernate-63 - com.github.weisj jsvg @@ -258,7 +250,7 @@ org.thingsboard.license client - 3.0.0 + 3.0.5 @@ -296,11 +288,4 @@ - - - - thingsboard-repo - https://repo.thingsboard.io/artifactory/libs-release-public - - diff --git a/dao/src/main/java/org/thingsboard/server/dao/ThingsboardPostgreSQLDialect.java b/dao/src/main/java/org/thingsboard/server/dao/ThingsboardPostgreSQLDialect.java index eeeab86039..1fd6368b12 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/ThingsboardPostgreSQLDialect.java +++ b/dao/src/main/java/org/thingsboard/server/dao/ThingsboardPostgreSQLDialect.java @@ -1,10 +1,12 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao; import lombok.extern.slf4j.Slf4j; import org.hibernate.boot.model.FunctionContributions; import org.hibernate.dialect.PostgreSQLDialect; +import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo; import org.hibernate.query.sqm.function.SqmFunctionRegistry; import org.hibernate.type.BasicTypeRegistry; import org.hibernate.type.StandardBasicTypes; @@ -12,6 +14,13 @@ import org.hibernate.type.StandardBasicTypes; @Slf4j public class ThingsboardPostgreSQLDialect extends PostgreSQLDialect { + public ThingsboardPostgreSQLDialect() { + } + + public ThingsboardPostgreSQLDialect(DialectResolutionInfo info) { + super(info); + } + @Override public void initializeFunctionRegistry(FunctionContributions functionContributions) { log.trace("initializeFunctionRegistry [{}]", functionContributions); diff --git a/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java b/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java index d600e84f15..276e5a044c 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java @@ -73,6 +73,8 @@ public interface AlarmDao extends Dao { PageData findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query, Collection orderedEntityIds); + PageData findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query); + Set findAlarmSeverities(TenantId tenantId, EntityId entityId, AlarmStatusFilter asf, String assigneeId); /** diff --git a/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java b/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java index fba8bcefc0..154e4df5b2 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java @@ -217,6 +217,13 @@ public class BaseAlarmService extends AbstractCachedEntityService findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query) { + validateId(tenantId, id -> INCORRECT_TENANT_ID + id); + validateEntityDataPageLink(query.getPageLink()); + return alarmDao.findAlarmDataByQuery(tenantId, customerId, mergedUserPermissions, query); + } + @Override @Transactional public AlarmApiCallResult delAlarm(TenantId tenantId, EntityId originator, AlarmId alarmId) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/config/DedicatedEventsJpaDaoConfig.java b/dao/src/main/java/org/thingsboard/server/dao/config/DedicatedEventsJpaDaoConfig.java index f06dc9058d..e290f6e3b4 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/config/DedicatedEventsJpaDaoConfig.java +++ b/dao/src/main/java/org/thingsboard/server/dao/config/DedicatedEventsJpaDaoConfig.java @@ -5,9 +5,9 @@ package org.thingsboard.server.dao.config; import com.zaxxer.hikari.HikariDataSource; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.boot.jdbc.autoconfigure.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; +import org.springframework.boot.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; diff --git a/dao/src/main/java/org/thingsboard/server/dao/config/JpaDaoConfig.java b/dao/src/main/java/org/thingsboard/server/dao/config/JpaDaoConfig.java index aba566732c..1976fbd896 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/config/JpaDaoConfig.java +++ b/dao/src/main/java/org/thingsboard/server/dao/config/JpaDaoConfig.java @@ -6,9 +6,9 @@ package org.thingsboard.server.dao.config; import com.zaxxer.hikari.HikariDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.boot.jdbc.autoconfigure.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; +import org.springframework.boot.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; diff --git a/dao/src/main/java/org/thingsboard/server/dao/group/BaseEntityGroupService.java b/dao/src/main/java/org/thingsboard/server/dao/group/BaseEntityGroupService.java index 75b51d3442..80fc2d92c0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/group/BaseEntityGroupService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/group/BaseEntityGroupService.java @@ -183,6 +183,20 @@ public class BaseEntityGroupService extends AbstractCachedEntityService INCORRECT_ENTITY_GROUP_ID + id); + return entityGroupInfoDao.findByTenantIdAndId(tenantId, entityGroupId.getId()); + } + + @Override + public ListenableFuture findEntityGroupInfoByTenantIdAndIdAsync(TenantId tenantId, EntityGroupId entityGroupId) { + log.trace("Executing findEntityGroupInfoByTenantIdAndIdAsync, tenantId [{}], entityGroupId [{}]", tenantId, entityGroupId); + validateId(entityGroupId, id -> INCORRECT_ENTITY_GROUP_ID + id); + return entityGroupInfoDao.findByTenantIdAndIdAsync(tenantId, entityGroupId.getId()); + } + @Override public EntityGroup saveEntityGroup(TenantId tenantId, EntityId parentEntityId, EntityGroup entityGroup) { log.trace("Executing saveEntityGroup [{}]", entityGroup); @@ -1211,6 +1225,12 @@ public class BaseEntityGroupService extends AbstractCachedEntityService { + EntityGroupInfo findByTenantIdAndId(TenantId tenantId, UUID entityGroupId); + + ListenableFuture findByTenantIdAndIdAsync(TenantId tenantId, UUID entityGroupId); + EntityInfo findEntityGroupEntityInfoById(TenantId tenantId, UUID entityGroupId); PageData findEntityGroupsByType(UUID tenantId, UUID parentEntityId, EntityType parentEntityType, EntityType groupType, PageLink pageLink); diff --git a/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java index 7a62e5ae0b..4fa030ef64 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java @@ -15,6 +15,7 @@ import org.springframework.transaction.annotation.Transactional; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.group.EntityGroup; +import org.thingsboard.server.common.data.group.EntityGroupInfo; import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.GroupPermissionId; @@ -303,13 +304,16 @@ public class GroupPermissionServiceImpl extends AbstractEntityService implements } private ListenableFuture fetchUserGroupPermissionInfoAsync(TenantId tenantId, GroupPermission groupPermission) { - ListenableFuture roleFuture = roleDao.findByIdAsync(tenantId, groupPermission.getRoleId().getId()); + ListenableFuture roleFuture = findRoleAsync(tenantId, groupPermission.getRoleId()); return Futures.transformAsync(roleFuture, role -> { GroupPermissionInfo groupPermissionInfo = new GroupPermissionInfo(groupPermission); groupPermissionInfo.setRole(role); if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) { - ListenableFuture entityGroup = entityGroupService.findEntityGroupByIdAsync(tenantId, groupPermission.getEntityGroupId()); + ListenableFuture entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(tenantId, groupPermission.getEntityGroupId()); return Futures.transform(entityGroup, entityGroup1 -> { + if (entityGroup1 == null) { + return null; + } groupPermissionInfo.setEntityGroupName(entityGroup1.getName()); groupPermissionInfo.setEntityGroupType(entityGroup1.getType()); EntityId ownerId = entityGroup1.getOwnerId(); @@ -324,12 +328,15 @@ public class GroupPermissionServiceImpl extends AbstractEntityService implements } private ListenableFuture fetchEntityGroupPermissionInfoAsync(TenantId tenantId, GroupPermission groupPermission) { - ListenableFuture roleFuture = roleDao.findByIdAsync(tenantId, groupPermission.getRoleId().getId()); + ListenableFuture roleFuture = findRoleAsync(tenantId, groupPermission.getRoleId()); return Futures.transformAsync(roleFuture, role -> { GroupPermissionInfo groupPermissionInfo = new GroupPermissionInfo(groupPermission); groupPermissionInfo.setRole(role); - ListenableFuture userGroup = entityGroupService.findEntityGroupByIdAsync(tenantId, groupPermission.getUserGroupId()); + ListenableFuture userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(tenantId, groupPermission.getUserGroupId()); return Futures.transform(userGroup, userGroup1 -> { + if (userGroup1 == null) { + return null; + } groupPermissionInfo.setUserGroupName(userGroup1.getName()); EntityId ownerId = userGroup1.getOwnerId(); groupPermissionInfo.setUserGroupOwnerId(ownerId); @@ -339,6 +346,12 @@ public class GroupPermissionServiceImpl extends AbstractEntityService implements }, MoreExecutors.directExecutor()); } + private ListenableFuture findRoleAsync(TenantId tenantId, RoleId roleId) { + return Futures.transform(roleDao.findByIdAsync(tenantId, roleId.getId()), + role -> role != null && (tenantId.equals(role.getTenantId()) || role.getTenantId().isSysTenantId()) ? role : null, + MoreExecutors.directExecutor()); + } + private final PaginatedRemover tenantGroupPermissionRemover = new PaginatedRemover<>() { @Override diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java index b99cf18981..7373a8fb81 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java @@ -25,6 +25,10 @@ public interface IotHubInstalledItemDao extends Dao { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id, not empty; only the items installed in another version + PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink); + List findInstalledItemIdsByTenantId(TenantId tenantId); List findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection itemIds); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java index 072506dfca..17f3361738 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java @@ -25,6 +25,10 @@ public interface IotHubInstalledItemService { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id; only the items installed in another version + PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink); + List findInstalledItemIdsByTenantId(TenantId tenantId); List findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection itemIds); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java index d69060cd94..90fe24e0d6 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java @@ -14,6 +14,7 @@ import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.model.sql.IotHubInstalledItemEntity; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -49,6 +50,27 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService { return iotHubInstalledItemDao.findByTenantId(tenantId, itemTypes, itemId, pageLink); } + @Override + public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink) { + validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); + // Only the tenant's installed items, so the map can't outgrow the query's bind parameter limit; an item IoT Hub + // publishes no version of has nothing to update to + Map published = new HashMap<>(); + if (publishedVersionIds != null && !publishedVersionIds.isEmpty()) { + for (UUID itemId : iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId)) { + UUID versionId = publishedVersionIds.get(itemId); + if (versionId != null) { + published.put(itemId, versionId); + } + } + } + if (published.isEmpty()) { + return PageData.emptyPageData(); + } + return iotHubInstalledItemDao.findByTenantIdWithUpdates(tenantId, itemTypes, published, pageLink); + } + @Override public List findInstalledItemIdsByTenantId(TenantId tenantId) { return iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java index 0a652fa014..55c1c050e4 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java @@ -185,8 +185,10 @@ public class CustomMenuServiceImpl extends AbstractCachedEntityService Collections.emptyList(); case CUSTOMERS -> customerService.findCustomersByCustomMenuId(customMenuInfo.getId()).stream() + .filter(customer -> isAvailableToTenant(customMenuInfo, customer.getTenantId())) .map(customer -> new EntityInfo(customer.getId(), customer.getName())).toList(); case USERS -> userService.findUsersByCustomMenuId(customMenuInfo.getId()).stream() + .filter(user -> isAvailableToTenant(customMenuInfo, user.getTenantId())) .map(user -> new EntityInfo(user.getId(), user.getName())).toList(); default -> throw new RuntimeException("Invalid custom menu assignee type '" + customMenuInfo.getAssigneeType() + "' specified for custom menu!"); @@ -334,7 +336,7 @@ public class CustomMenuServiceImpl extends AbstractCachedEntityService extends Bas @Column(name = API_KEY_INTERNAL_COLUMN_NAME) private boolean internal; - @Type(JsonBinaryType.class) + @Convert(converter = JsonConverter.class) + @JdbcType(PostgreSQLJsonPGObjectJsonType.class) @Column(name = API_KEY_PERMISSIONS_COLUMN_NAME, columnDefinition = "json") private JsonNode permissions; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AbstractCustomMenuEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AbstractCustomMenuEntity.java index bea249f642..7cf6fa2b19 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AbstractCustomMenuEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AbstractCustomMenuEntity.java @@ -2,14 +2,12 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.dao.model.sql; -import io.hypersistence.utils.hibernate.type.array.StringArrayType; import jakarta.persistence.Column; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.MappedSuperclass; import lombok.Data; import lombok.EqualsAndHashCode; -import org.hibernate.annotations.Type; import org.thingsboard.server.common.data.id.CustomMenuId; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.TenantId; @@ -49,7 +47,6 @@ public abstract class AbstractCustomMenuEntity extends @Enumerated(EnumType.STRING) private CMAssigneeType assigneeType; - @Type(StringArrayType.class) @Column(name = ModelConstants.CUSTOM_MENU_USER_GROUP_NAMES, columnDefinition = "text[]") private String[] userGroupNames; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AbstractDeviceEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AbstractDeviceEntity.java index c29827b566..bf69e4f947 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AbstractDeviceEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AbstractDeviceEntity.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao.model.sql; import com.fasterxml.jackson.databind.JsonNode; @@ -10,7 +11,7 @@ import jakarta.persistence.MappedSuperclass; import lombok.Data; import lombok.EqualsAndHashCode; import org.hibernate.annotations.JdbcType; -import org.hibernate.dialect.PostgreSQLJsonPGObjectJsonbType; +import org.hibernate.dialect.type.PostgreSQLJsonPGObjectJsonbType; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.device.data.DeviceData; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentAppEventEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentAppEventEntity.java index ac19edf921..68b18c9255 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentAppEventEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentAppEventEntity.java @@ -12,7 +12,7 @@ import jakarta.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import org.hibernate.annotations.JdbcType; -import org.hibernate.dialect.PostgreSQLJsonPGObjectJsonbType; +import org.hibernate.dialect.type.PostgreSQLJsonPGObjectJsonbType; import com.fasterxml.jackson.core.type.TypeReference; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.agent.AgentAppEvent; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentBulkActionEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentBulkActionEntity.java index dfebcfd62c..1d853a0f74 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentBulkActionEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentBulkActionEntity.java @@ -13,7 +13,7 @@ import jakarta.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import org.hibernate.annotations.JdbcType; -import org.hibernate.dialect.PostgreSQLJsonPGObjectJsonbType; +import org.hibernate.dialect.type.PostgreSQLJsonPGObjectJsonbType; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.agent.AgentAppEventActionType; import org.thingsboard.server.common.data.agent.AgentBulkAction; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentInfoEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentInfoEntity.java index f2274b3035..def5b4b644 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentInfoEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AgentInfoEntity.java @@ -10,7 +10,7 @@ import lombok.Data; import lombok.EqualsAndHashCode; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.JdbcType; -import org.hibernate.dialect.PostgreSQLJsonPGObjectJsonType; +import org.hibernate.dialect.type.PostgreSQLJsonPGObjectJsonType; import org.thingsboard.server.common.data.EntityInfo; import org.thingsboard.server.common.data.agent.AgentInfo; import org.thingsboard.server.dao.model.ModelConstants; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AiModelEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AiModelEntity.java index 8393fdc485..3903b64965 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/AiModelEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/AiModelEntity.java @@ -3,14 +3,15 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao.model.sql; -import io.hypersistence.utils.hibernate.type.json.JsonBinaryType; import jakarta.persistence.Column; +import jakarta.persistence.Convert; import jakarta.persistence.Entity; import jakarta.persistence.Table; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import org.hibernate.annotations.Type; +import org.hibernate.annotations.JdbcType; +import org.hibernate.dialect.type.PostgreSQLJsonPGObjectJsonbType; import org.hibernate.proxy.HibernateProxy; import org.thingsboard.server.common.data.ai.AiModel; import org.thingsboard.server.common.data.ai.model.AiModelConfig; @@ -18,6 +19,7 @@ import org.thingsboard.server.common.data.id.AiModelId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.model.BaseVersionedEntity; import org.thingsboard.server.dao.model.ModelConstants; +import org.thingsboard.server.dao.util.mapping.AiModelConfigConverter; import java.util.Collections; import java.util.LinkedHashSet; @@ -50,7 +52,8 @@ public class AiModelEntity extends BaseVersionedEntity { @Column(name = ModelConstants.AI_MODEL_NAME_COLUMN_NAME, nullable = false) private String name; - @Type(JsonBinaryType.class) + @Convert(converter = AiModelConfigConverter.class) + @JdbcType(PostgreSQLJsonPGObjectJsonbType.class) @Column(name = ModelConstants.AI_MODEL_CONFIGURATION_COLUMN_NAME, nullable = false, columnDefinition = "JSONB") private AiModelConfig configuration; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/DeviceInfoEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/DeviceInfoEntity.java index b662e03268..3f63afca9f 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/DeviceInfoEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/DeviceInfoEntity.java @@ -12,7 +12,7 @@ import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.JdbcType; -import org.hibernate.dialect.PostgreSQLJsonPGObjectJsonType; +import org.hibernate.dialect.type.PostgreSQLJsonPGObjectJsonType; import org.thingsboard.server.common.data.DeviceInfo; import org.thingsboard.server.common.data.EntityInfo; import org.thingsboard.server.dao.model.ModelConstants; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/DeviceProfileEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/DeviceProfileEntity.java index 0394140823..7312869801 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/DeviceProfileEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/DeviceProfileEntity.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao.model.sql; import com.fasterxml.jackson.databind.JsonNode; @@ -14,7 +15,7 @@ import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.hibernate.annotations.JdbcType; -import org.hibernate.dialect.PostgreSQLJsonPGObjectJsonbType; +import org.hibernate.dialect.type.PostgreSQLJsonPGObjectJsonbType; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceProfileProvisionType; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/EntityGroupInfoEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/EntityGroupInfoEntity.java index af59ff8281..307f922d37 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/EntityGroupInfoEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/EntityGroupInfoEntity.java @@ -10,7 +10,7 @@ import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.JdbcType; -import org.hibernate.dialect.PostgreSQLJsonPGObjectJsonType; +import org.hibernate.dialect.type.PostgreSQLJsonPGObjectJsonType; import org.thingsboard.server.common.data.group.EntityGroupInfo; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.dao.model.ModelConstants; diff --git a/dao/src/main/java/org/thingsboard/server/dao/model/sql/IotHubInstalledItemEntity.java b/dao/src/main/java/org/thingsboard/server/dao/model/sql/IotHubInstalledItemEntity.java index 9fb385cabc..661151d46f 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/model/sql/IotHubInstalledItemEntity.java +++ b/dao/src/main/java/org/thingsboard/server/dao/model/sql/IotHubInstalledItemEntity.java @@ -1,15 +1,17 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao.model.sql; -import io.hypersistence.utils.hibernate.type.json.JsonBinaryType; import jakarta.persistence.Column; +import jakarta.persistence.Convert; import jakarta.persistence.Entity; import jakarta.persistence.Table; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import org.hibernate.annotations.Type; +import org.hibernate.annotations.JdbcType; +import org.hibernate.dialect.type.PostgreSQLJsonPGObjectJsonbType; import org.hibernate.proxy.HibernateProxy; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; @@ -17,6 +19,7 @@ import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItemDescriptor; import org.thingsboard.server.dao.model.BaseSqlEntity; import org.thingsboard.server.dao.model.ModelConstants; +import org.thingsboard.server.dao.util.mapping.IotHubInstalledItemDescriptorConverter; import java.util.Collections; import java.util.LinkedHashSet; @@ -54,7 +57,8 @@ public class IotHubInstalledItemEntity extends BaseSqlEntity""") .build()) .build(); + public static final DefaultNotification aiCreditsLimitIncreaseRequest = DefaultNotification.builder() + .name("AI credits limit increase request") + .type(NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST) + .subject("AI credits limit increase request") + .text("${userEmail} from tenant ${tenantName} has used ${limitDescription} and is requesting more AI credits.") + .icon("auto_awesome") + .button("${increaseLimitActionLabel}").link("${increaseLimitLink}") + .emailTemplate(DefaultEmailTemplate.builder() + .subject("AI credits limit increase request") + .body(""" + + + + + + +
+ + + + + + + + + + + + +
AI credits limit increase request
${userEmail} from tenant ${tenantName} has used ${limitDescription} and is requesting more AI credits.
+ ${increaseLimitActionLabel} +
+
""") + .build()) + .build(); public static final DefaultNotification apiFeatureWarningForSysadmin = DefaultNotification.builder() .name("API feature warning notification for sysadmin") .type(NotificationType.API_USAGE_LIMIT) diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidator.java index 091bf16e4d..e240b560e6 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidator.java @@ -29,6 +29,10 @@ public class AdminSettingsDataValidator extends DataValidator { protected AdminSettings validateUpdate(TenantId tenantId, AdminSettings adminSettings) { AdminSettings existentAdminSettings = adminSettingsService.findAdminSettingsById(tenantId, adminSettings.getId()); if (existentAdminSettings != null) { + TenantId targetTenantId = adminSettings.getTenantId() != null ? adminSettings.getTenantId() : TenantId.SYS_TENANT_ID; + if (!existentAdminSettings.getTenantId().equals(targetTenantId)) { + throw new DataValidationException("Can't move existing admin settings entry to different tenant!"); + } if (!existentAdminSettings.getKey().equals(adminSettings.getKey())) { throw new DataValidationException("Changing key of admin settings entry is prohibited!"); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidator.java index 3bd186ebe1..9ae93f3b6d 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidator.java @@ -5,6 +5,8 @@ package org.thingsboard.server.dao.service.validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.cf.CalculatedField; import org.thingsboard.server.common.data.cf.CalculatedFieldType; import org.thingsboard.server.common.data.cf.configuration.ArgumentsBasedCalculatedFieldConfiguration; @@ -12,26 +14,36 @@ import org.thingsboard.server.common.data.cf.configuration.RelationPathQueryDyna import org.thingsboard.server.common.data.cf.configuration.ScheduledUpdateSupportedCalculatedFieldConfiguration; import org.thingsboard.server.common.data.cf.configuration.aggregation.RelatedEntitiesAggregationCalculatedFieldConfiguration; import org.thingsboard.server.common.data.cf.configuration.aggregation.single.EntityAggregationCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.dao.cf.CalculatedFieldDao; +import org.thingsboard.server.dao.entity.EntityDaoRegistry; import org.thingsboard.server.dao.service.DataValidator; import org.thingsboard.server.dao.usagerecord.ApiLimitService; import org.thingsboard.server.exception.DataValidationException; +import java.util.EnumSet; import java.util.Map; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @Component public class CalculatedFieldDataValidator extends DataValidator { + private static final Set SUPPORTED_ENTITY_TYPES = EnumSet.of( + EntityType.CUSTOMER, EntityType.ASSET, EntityType.DEVICE, EntityType.ASSET_PROFILE, EntityType.DEVICE_PROFILE); + @Autowired private CalculatedFieldDao calculatedFieldDao; @Autowired private ApiLimitService apiLimitService; + @Autowired + private EntityDaoRegistry entityDaoRegistry; + @Override protected void validateDataImpl(TenantId tenantId, CalculatedField calculatedField) { validateNumberOfArgumentsPerCF(tenantId, calculatedField); @@ -40,6 +52,13 @@ public class CalculatedFieldDataValidator extends DataValidator validateRelationQuerySourceArguments(tenantId, calculatedField); validateRelatedAggregationConfiguration(tenantId, calculatedField); validateEntityAggregationConfiguration(tenantId, calculatedField); + if (calculatedField.getTenantId() == null) { + throw new DataValidationException("Calculated field should be assigned to tenant!"); + } + validateEntityTenant(calculatedField.getTenantId(), calculatedField.getEntityId()); + for (EntityId referencedEntityId : calculatedField.getConfiguration().getReferencedEntities()) { + validateReferencedEntityTenant(calculatedField.getTenantId(), referencedEntityId); + } } @Override @@ -62,6 +81,9 @@ public class CalculatedFieldDataValidator extends DataValidator if (old == null) { throw new DataValidationException("Can't update non existing calculated field!"); } + if (!old.getTenantId().equals(calculatedField.getTenantId())) { + throw new DataValidationException("Can't update calculated field tenant id!"); + } return old; } @@ -140,4 +162,28 @@ public class CalculatedFieldDataValidator extends DataValidator } } + private void validateReferencedEntityTenant(TenantId cfTenantId, EntityId entityId) { + EntityType entityType = entityId.getEntityType(); + switch (entityType) { + case TENANT -> { + if (!cfTenantId.equals(entityId)) { + throw new DataValidationException("Referenced tenant must be the calculated field's tenant!"); + } + } + case CUSTOMER, ASSET, DEVICE -> validateEntityTenant(cfTenantId, entityId); + default -> throw new DataValidationException("Calculated fields do not support '" + entityType + "' for referenced entities."); + } + } + + private void validateEntityTenant(TenantId cfTenantId, EntityId entityId) { + EntityType entityType = entityId.getEntityType(); + if (!SUPPORTED_ENTITY_TYPES.contains(entityType)) { + throw new DataValidationException("Entity type '" + entityType + "' does not support calculated fields."); + } + HasTenantId entity = entityDaoRegistry.getDao(entityType).findById(cfTenantId, entityId.getId()); + if (entity == null || !cfTenantId.equals(entity.getTenantId())) { + throw new DataValidationException(entityType.getNormalName() + " with id [" + entityId.getId() + "] does not belong to the calculated field's tenant!"); + } + } + } diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidator.java index c61523bed3..a85566c037 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidator.java @@ -8,9 +8,12 @@ import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.HasId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.customer.CustomerDao; +import org.thingsboard.server.dao.entity.EntityService; import org.thingsboard.server.dao.entityview.EntityViewDao; import org.thingsboard.server.dao.entityview.EntityViewService; import org.thingsboard.server.dao.service.DataValidator; @@ -35,6 +38,10 @@ public class EntityViewDataValidator extends DataValidator { @Autowired private CustomerDao customerDao; + @Autowired + @Lazy + private EntityService entityService; + @Override protected void validateCreate(TenantId tenantId, EntityView entityView) { validateNameUniqueness(entityView, null, entityViewService::findEntityViewByTenantIdAndName, "Entity view with such name already exists!"); @@ -63,6 +70,21 @@ public class EntityViewDataValidator extends DataValidator { throw new DataValidationException("Entity view is referencing to non-existent tenant!"); } } + if (entityView.getEntityId() == null) { + throw new DataValidationException("Entity view should be assigned to entity!"); + } + HasId entity; + try { + entity = entityService.fetchEntity(entityView.getTenantId(), entityView.getEntityId()).orElse(null); + } catch (IllegalArgumentException e) { + entity = null; + } + if (entity == null) { + throw new DataValidationException("Entity view is referencing to non-existent entity!"); + } + if (!(entity instanceof HasTenantId hasTenantId) || !entityView.getTenantId().equals(hasTenantId.getTenantId())) { + throw new DataValidationException("Can't assign entity view to entity from different tenant!"); + } if (entityView.getCustomerId() == null) { entityView.setCustomerId(new CustomerId(NULL_UUID)); } else if (!entityView.getCustomerId().getId().equals(NULL_UUID)) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/GroupPermissionDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/GroupPermissionDataValidator.java index 4e5116a491..93f0a6eddd 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/GroupPermissionDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/GroupPermissionDataValidator.java @@ -12,7 +12,7 @@ import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.permission.GroupPermission; import org.thingsboard.server.common.data.role.Role; -import org.thingsboard.server.dao.group.EntityGroupDao; +import org.thingsboard.server.dao.group.EntityGroupInfoDao; import org.thingsboard.server.dao.grouppermission.GroupPermissionDao; import org.thingsboard.server.dao.role.RoleDao; import org.thingsboard.server.dao.service.DataValidator; @@ -24,7 +24,7 @@ import org.thingsboard.server.exception.DataValidationException; public class GroupPermissionDataValidator extends DataValidator { private final TenantService tenantService; - private final EntityGroupDao entityGroupDao; + private final EntityGroupInfoDao entityGroupInfoDao; private final RoleDao roleDao; private final GroupPermissionDao groupPermissionDao; @@ -52,7 +52,7 @@ public class GroupPermissionDataValidator extends DataValidator if (groupPermission.getUserGroupId() == null || groupPermission.getUserGroupId().isNullUid()) { throw new DataValidationException("Group Permission userGroupId should be specified!"); } else { - EntityGroup entityGroup = entityGroupDao.findById(tenantId, groupPermission.getUserGroupId().getId()); + EntityGroup entityGroup = entityGroupInfoDao.findByTenantIdAndId(groupPermission.getTenantId(), groupPermission.getUserGroupId().getId()); if (entityGroup == null) { throw new DataValidationException("Group Permission is referencing to non-existent user group!"); } else if (entityGroup.getType() != EntityType.USER) { @@ -63,7 +63,7 @@ public class GroupPermissionDataValidator extends DataValidator throw new DataValidationException("Group Permission roleId should be specified!"); } else { Role role = roleDao.findById(tenantId, groupPermission.getRoleId().getId()); - if (role == null) { + if (role == null || !(role.getTenantId().equals(groupPermission.getTenantId()) || role.getTenantId().isSysTenantId())) { throw new DataValidationException("Group Permission is referencing to non-existent role!"); } } @@ -72,7 +72,7 @@ public class GroupPermissionDataValidator extends DataValidator } if (!groupPermission.getEntityGroupId().isNullUid()) { - EntityGroup entityGroup = entityGroupDao.findById(tenantId, groupPermission.getEntityGroupId().getId()); + EntityGroup entityGroup = entityGroupInfoDao.findByTenantIdAndId(groupPermission.getTenantId(), groupPermission.getEntityGroupId().getId()); if (entityGroup == null) { throw new DataValidationException("Group Permission is referencing to non-existent entity group!"); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/JpaAbstractDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/JpaAbstractDao.java index 644832b7e0..59d76619da 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/JpaAbstractDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/JpaAbstractDao.java @@ -10,7 +10,6 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.OptimisticLockException; import jakarta.persistence.PersistenceContext; import lombok.extern.slf4j.Slf4j; -import org.hibernate.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.jdbc.core.JdbcTemplate; @@ -113,13 +112,10 @@ public abstract class JpaAbstractDao, D> if (entity.getUuid() == null) { getEntityManager().persist(entity); } else { - if (entity instanceof HasVersion) { - /* - * Hibernate 6 does not allow creating versioned entities with preset IDs. - * Bypassing by calling the underlying session directly - * */ - Session session = getEntityManager().unwrap(Session.class); - session.save(entity); + if (entity instanceof HasVersion versionedEntity) { + // a null version makes persist() treat the entity as new despite its preset id + versionedEntity.setVersion(null); + getEntityManager().persist(entity); } else { entity = getEntityManager().merge(entity); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java index f8c990657a..6d7aa5fb6b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java @@ -12,6 +12,8 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.JpaSort; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; @@ -145,6 +147,25 @@ public class JpaAlarmDao extends JpaAbstractDao implements A return findByIdAsync(tenantId, key); } + private static final String SEVERITY_PROPERTY = "severity"; + + private static final String SEVERITY_RANK = "(case a.severity" + + Arrays.stream(AlarmSeverity.values()) + .map(severity -> " when " + AlarmSeverity.class.getName() + "." + severity.name() + " then " + severity.ordinal()) + .collect(Collectors.joining()) + + " else " + AlarmSeverity.values().length + " end)"; + + private static Pageable toAlarmPageable(PageLink pageLink) { + Pageable pageable = DaoUtil.toPageable(pageLink); + if (pageable.getSort().getOrderFor(SEVERITY_PROPERTY) == null) { + return pageable; + } + List orders = pageable.getSort().stream() + .map(order -> SEVERITY_PROPERTY.equals(order.getProperty()) ? JpaSort.unsafe(order.getDirection(), SEVERITY_RANK).iterator().next() : order) + .toList(); + return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(orders)); + } + @Override public PageData findAlarms(TenantId tenantId, AlarmQuery query) { log.trace("Try to find alarms by entity [{}], status [{}] and pageLink [{}]", query.getAffectedEntityId(), query.getStatus(), query.getPageLink()); @@ -164,7 +185,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } else { @@ -179,7 +200,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -201,7 +222,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -230,7 +251,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } else { @@ -247,7 +268,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -273,7 +294,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -309,6 +330,11 @@ public class JpaAlarmDao extends JpaAbstractDao implements A return alarmQueryRepository.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, query, orderedEntityIds); } + @Override + public PageData findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query) { + return alarmQueryRepository.findAlarmDataByQuery(tenantId, customerId, mergedUserPermissions, query); + } + @Override public Set findAlarmSeverities(TenantId tenantId, EntityId entityId, AlarmStatusFilter asf, String assigneeId) { return alarmRepository.findAlarmSeverities(tenantId.getId(), entityId.getId(), entityId.getEntityType().name(), diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java index eeffe3a19c..01290bc3aa 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java @@ -16,6 +16,12 @@ import java.util.UUID; public interface EntityGroupInfoRepository extends JpaRepository { + String OWNED_WITHIN_TENANT = "((e.ownerId = :tenantId AND e.ownerType = 'TENANT') OR " + + "(e.ownerType = 'CUSTOMER' AND EXISTS (SELECT 1 FROM CustomerEntity c WHERE c.id = e.ownerId AND c.tenantId = :tenantId)))"; + + @Query("SELECT e FROM EntityGroupInfoEntity e WHERE e.id = :entityGroupId AND " + OWNED_WITHIN_TENANT) + EntityGroupInfoEntity findByTenantIdAndId(@Param("tenantId") UUID tenantId, @Param("entityGroupId") UUID entityGroupId); + @Query("SELECT new org.thingsboard.server.common.data.EntityInfo(e.id, 'ENTITY_GROUP', e.name) " + "FROM EntityGroupEntity e " + "WHERE e.id = :entityGroupId") @@ -65,16 +71,20 @@ public interface EntityGroupInfoRepository extends JpaRepository findEntityGroupsByIds(@Param("entityGroupIds") List entityGroupIds, + Page findEntityGroupsByIds(@Param("tenantId") UUID tenantId, + @Param("entityGroupIds") List entityGroupIds, @Param("textSearch") String textSearch, Pageable pageable); @Query("SELECT new org.thingsboard.server.common.data.EntityInfo(e.id, 'ENTITY_GROUP', e.name) " + "FROM EntityGroupEntity e " + "WHERE e.id IN :entityGroupIds " + + "AND " + OWNED_WITHIN_TENANT + " " + "AND (:textSearch IS NULL OR ilike(e.name, CONCAT('%', :textSearch, '%')) = true)") - Page findEntityGroupEntityInfosByIds(@Param("entityGroupIds") List entityGroupIds, + Page findEntityGroupEntityInfosByIds(@Param("tenantId") UUID tenantId, + @Param("entityGroupIds") List entityGroupIds, @Param("textSearch") String textSearch, Pageable pageable); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java index b0d7c837c8..bc4e675502 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.dao.sql.group; +import com.google.common.util.concurrent.ListenableFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; @@ -38,6 +39,16 @@ public class JpaEntityGroupInfoDao extends JpaAbstractDao findByTenantIdAndIdAsync(TenantId tenantId, UUID entityGroupId) { + return service.submit(() -> findByTenantIdAndId(tenantId, entityGroupId)); + } + @Override public EntityInfo findEntityGroupEntityInfoById(TenantId tenantId, UUID entityGroupId) { return entityGroupInfoRepository.findEntityGroupEntityInfoById(entityGroupId); @@ -90,6 +101,7 @@ public class JpaEntityGroupInfoDao extends JpaAbstractDao findEntityGroupsByIds(UUID tenantId, List entityGroupIds, PageLink pageLink) { return DaoUtil.toPageData(entityGroupInfoRepository .findEntityGroupsByIds( + tenantId, entityGroupIds, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); @@ -99,6 +111,7 @@ public class JpaEntityGroupInfoDao extends JpaAbstractDao findEntityGroupEntityInfosByIds(UUID tenantId, List entityGroupIds, PageLink pageLink) { return DaoUtil.pageToPageData(entityGroupInfoRepository .findEntityGroupEntityInfosByIds( + tenantId, entityGroupIds, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java index 693166b7e0..c09f8c12f5 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java @@ -33,17 +33,29 @@ interface IotHubInstalledItemRepository extends JpaRepository findInstalledItemIdsByTenantIdAndItemIdIn(@Param("tenantId") UUID tenantId, @Param("itemIds") Collection itemIds); + /** + * The tenant's installed items, by type, item and text. With {@code updatesOnly}, only the items with an update: an item + * of {@code publishedItemIds} whose installed version is not among {@code publishedVersionIds} (version ids are unique, + * so: not the published version of its item). A flag, as Hibernate can't type {@code :uuids IS NULL}. + */ @Query(""" SELECT item FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) AND (:itemId IS NULL OR item.itemId = :itemId) + AND (:updatesOnly = false + OR (item.itemId IN :publishedItemIds AND item.itemVersionId NOT IN :publishedVersionIds)) AND (:textSearch IS NULL OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) """) - Page findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable); + Page findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, + @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, + @Param("updatesOnly") boolean updatesOnly, + @Param("publishedItemIds") Collection publishedItemIds, + @Param("publishedVersionIds") Collection publishedVersionIds, + Pageable pageable); @Query(""" SELECT COUNT(item) FROM IotHubInstalledItemEntity item diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java index d07d8f5dd4..4c91e5137b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java @@ -48,11 +48,30 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { + return find(tenantId, itemTypes, itemId, null, pageLink); + } + + @Override + public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink) { + return find(tenantId, itemTypes, null, publishedVersionIds, pageLink); + } + + // Never matches: the query binds the published ids even when it doesn't filter by them + private static final Set NO_IDS = Set.of(new UUID(0, 0)); + + // One query for both lists, so the only-updates list filters and searches as the plain one does + private PageData find(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink) { + boolean updatesOnly = publishedVersionIds != null; return DaoUtil.toPageData(repository.findByTenantId( tenantId.getId(), itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, itemId, StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), + updatesOnly, + updatesOnly ? publishedVersionIds.keySet() : NO_IDS, + updatesOnly ? publishedVersionIds.values() : NO_IDS, toPageRequest(pageLink)) ); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmDataAdapter.java b/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmDataAdapter.java index 51a421ca3e..fabefaa6b2 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmDataAdapter.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmDataAdapter.java @@ -36,7 +36,8 @@ public class AlarmDataAdapter { public static PageData createAlarmData(EntityDataPageLink pageLink, List> rows, int totalElements, Collection orderedEntityIds) { - Map entityIdMap = orderedEntityIds.stream().collect(Collectors.toMap(EntityId::getId, Function.identity())); + Map entityIdMap = orderedEntityIds == null ? Collections.emptyMap() + : orderedEntityIds.stream().collect(Collectors.toMap(EntityId::getId, Function.identity())); int totalPages = pageLink.getPageSize() > 0 ? (int) Math.ceil((float) totalElements / pageLink.getPageSize()) : 1; int startIndex = pageLink.getPageSize() * pageLink.getPage(); boolean hasNext = pageLink.getPageSize() > 0 && totalElements > startIndex + rows.size(); @@ -101,7 +102,7 @@ public class AlarmDataAdapter { alarm.setPropagateRelationTypes(Collections.emptyList()); } UUID entityUuid = (UUID) row.get(ModelConstants.ENTITY_ID_COLUMN); - EntityId entityId = entityIdMap.get(entityUuid); + EntityId entityId = entityIdMap.isEmpty() ? alarm.getOriginator() : entityIdMap.get(entityUuid); Object originatorNameObj = row.get(ModelConstants.ALARM_ORIGINATOR_NAME_PROPERTY); String originatorName = originatorNameObj != null ? originatorNameObj.toString() : null; Object originatorLabelObj = row.get(ModelConstants.ALARM_ORIGINATOR_LABEL_PROPERTY); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmQueryRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmQueryRepository.java index de0a7e4ab9..74bbb0246e 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmQueryRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmQueryRepository.java @@ -19,6 +19,8 @@ public interface AlarmQueryRepository { PageData findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query, Collection orderedEntityIds); + PageData findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query); + long countAlarmsByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmCountQuery query, Collection orderedEntityIds); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java index c6487d3532..31ed47cd88 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java @@ -31,12 +31,14 @@ import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.dao.sql.citus.CitusSettings; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; @Repository @@ -45,6 +47,18 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { private static final Map alarmFieldColumnMap = new HashMap<>(); + private static final String SEVERITY_RANK = "case a." + ModelConstants.ALARM_SEVERITY_PROPERTY + + Arrays.stream(AlarmSeverity.values()) + .map(severity -> " when '" + severity.name() + "' then " + severity.ordinal()) + .collect(Collectors.joining()) + + " else " + AlarmSeverity.values().length + " end"; + + private static final Set ALARM_TABLE_SORT_COLUMNS = Set.of(ModelConstants.CREATED_TIME_PROPERTY, ModelConstants.ALARM_ACK_TS_PROPERTY, + ModelConstants.ALARM_CLEAR_TS_PROPERTY, ModelConstants.ALARM_ASSIGN_TS_PROPERTY, ModelConstants.ALARM_END_TS_PROPERTY, + ModelConstants.ALARM_START_TS_PROPERTY, ModelConstants.ALARM_ACKNOWLEDGED_PROPERTY, ModelConstants.ALARM_CLEARED_PROPERTY, + ModelConstants.ALARM_TYPE_PROPERTY, ModelConstants.ALARM_SEVERITY_PROPERTY, ModelConstants.ALARM_ORIGINATOR_ID_PROPERTY, + ModelConstants.ALARM_ORIGINATOR_TYPE_PROPERTY, ModelConstants.ALARM_ASSIGNEE_ID_PROPERTY); + private static final String ASSIGNEE_EMAIL_KEY = "assigneeEmail"; private static final String ASSIGNEE_LAST_NAME_KEY = "assigneeLastName"; private static final String ASSIGNEE_FIRST_NAME_KEY = "assigneeFirstName"; @@ -133,20 +147,40 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { @Override public PageData findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query, Collection orderedEntityIds) { + return findAlarmData(tenantId, null, mergedUserPermissions, query, orderedEntityIds); + } + + @Override + public PageData findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query) { + return findAlarmData(tenantId, customerId, mergedUserPermissions, query, null); + } + + private PageData findAlarmData(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, + AlarmDataQuery query, Collection orderedEntityIds) { if (!mergedUserPermissions.hasGenericPermission(Resource.ALARM, Operation.READ)) { return PageData.emptyPageData(); } + boolean ownerScoped = orderedEntityIds == null; return transactionTemplate.execute(trStatus -> { AlarmDataPageLink pageLink = query.getPageLink(); + boolean searchPropagatedAlarms = !ownerScoped && pageLink.isSearchPropagatedAlarms(); SqlQueryContext ctx = new SqlQueryContext(new QueryContext(tenantId, null, EntityType.ALARM, mergedUserPermissions, null), citusSettings.isEnabled()); - ctx.addUuidListParameter("entity_ids", orderedEntityIds.stream().map(EntityId::getId).collect(Collectors.toList())); StringBuilder selectPart = new StringBuilder(FIELDS_SELECTION); StringBuilder fromPart = new StringBuilder(" from alarm_info a "); StringBuilder wherePart = new StringBuilder(" where "); StringBuilder sortPart = new StringBuilder(" order by "); StringBuilder joinPart = new StringBuilder(); boolean addAnd = false; - if (pageLink.isSearchPropagatedAlarms()) { + if (ownerScoped) { + selectPart.append(" a.originator_id as entity_id "); + ctx.addUuidParameter("owner_tenant_id", tenantId.getId()); + wherePart.append(" a.tenant_id = :owner_tenant_id"); + if (customerId != null && !customerId.isNullUid()) { + ctx.addUuidParameter("owner_customer_id", customerId.getId()); + wherePart.append(" and a.customer_id = :owner_customer_id"); + } + addAnd = true; + } else if (searchPropagatedAlarms) { selectPart.append(" ea.entity_id as entity_id "); fromPart.append(JOIN_ENTITY_ALARMS); wherePart.append(buildPermissionsQuery(tenantId, ctx, mergedUserPermissions)); @@ -154,7 +188,13 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { } else { selectPart.append(" a.originator_id as entity_id "); } + if (!ownerScoped) { + ctx.addUuidListParameter("entity_ids", orderedEntityIds.stream().map(EntityId::getId).collect(Collectors.toList())); + } EntityDataSortOrder sortOrder = pageLink.getSortOrder(); + if (ownerScoped && (sortOrder == null || !EntityKeyType.ALARM_FIELD.equals(sortOrder.getKey().getType()))) { + sortOrder = new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "createdTime"), EntityDataSortOrder.Direction.DESC); + } if (sortOrder != null && EntityKeyType.ALARM_FIELD.equals(sortOrder.getKey().getType()) && ASSIGNEE_KEY.equalsIgnoreCase(sortOrder.getKey().getKey())) { sortOrder = new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, ASSIGNEE_EMAIL_KEY), sortOrder.getDirection()); @@ -178,9 +218,12 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { if ("status".equalsIgnoreCase(sortOrderKey)) { selectPart.append(", a.status as status "); } - sortPart.append(alarmFieldColumnMap.getOrDefault(sortOrderKey, sortOrderKey)) + String sortColumn = alarmFieldColumnMap.getOrDefault(sortOrderKey, sortOrderKey); + sortPart.append(ModelConstants.ALARM_SEVERITY_PROPERTY.equals(sortColumn) ? SEVERITY_RANK : sortColumn) .append(" ").append(sortOrder.getDirection().name()); - if (pageLink.isSearchPropagatedAlarms()) { + if (ownerScoped) { + sortPart.append(", a.created_time desc, a.id desc"); + } else if (searchPropagatedAlarms) { wherePart.append(" and ea.entity_id in (:entity_ids)"); } else { addAndIfNeeded(wherePart, addAnd); @@ -201,7 +244,7 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { entityIdIdx++; } joinPart.append(" as e(id, priority)) e "); - if (pageLink.isSearchPropagatedAlarms()) { + if (searchPropagatedAlarms) { if (textSearchQuery.isEmpty()) { joinPart.append("on ea.entity_id = e.id"); } else { @@ -233,7 +276,7 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { addAnd = true; ctx.addLongParameter("startTime", startTs); wherePart.append("a.created_time >= :startTime"); - if (pageLink.isSearchPropagatedAlarms()) { + if (searchPropagatedAlarms) { wherePart.append(" and ea.created_time >= :startTime"); } } @@ -243,7 +286,7 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { addAnd = true; ctx.addLongParameter("endTime", endTs); wherePart.append("a.created_time <= :endTime"); - if (pageLink.isSearchPropagatedAlarms()) { + if (searchPropagatedAlarms) { wherePart.append(" and ea.created_time <= :endTime"); } } @@ -253,7 +296,7 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { addAnd = true; ctx.addStringListParameter("alarmTypes", pageLink.getTypeList()); wherePart.append("a.type in (:alarmTypes)"); - if (pageLink.isSearchPropagatedAlarms()) { + if (searchPropagatedAlarms) { wherePart.append(" and ea.alarm_type in (:alarmTypes)"); } } @@ -294,7 +337,9 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { } else { mainQuery = String.format("select * from (%s%s) a %s WHERE %s", mainQuery, wherePart, joinPart, textSearchQuery); } - String countQuery = String.format("select count(*) from (%s) result", mainQuery); + String countQuery = ownerScoped && textSearchQuery.isEmpty() + ? String.format("select count(*) from alarm a %s", wherePart) + : String.format("select count(*) from (%s) result", mainQuery); long queryTs = System.currentTimeMillis(); int totalElements; try { @@ -309,8 +354,11 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { String dataQuery = mainQuery + sortPart; int startIndex = pageLink.getPageSize() * pageLink.getPage(); - if (pageLink.getPageSize() > 0) { - dataQuery = String.format("%s limit %s offset %s", dataQuery, pageLink.getPageSize(), startIndex); + String limitPart = pageLink.getPageSize() > 0 ? String.format(" limit %s offset %s", pageLink.getPageSize(), startIndex) : ""; + if (ownerScoped && textSearchQuery.isEmpty() && ALARM_TABLE_SORT_COLUMNS.contains(alarmFieldColumnMap.getOrDefault(sortOrder.getKey().getKey(), sortOrder.getKey().getKey()))) { + dataQuery = String.format("%s%s where a.id in (select a.id from alarm a %s%s%s)%s", selectPart, fromPart, wherePart, sortPart, limitPart, sortPart); + } else { + dataQuery = dataQuery + limitPart; } queryTs = System.currentTimeMillis(); List> rows; diff --git a/dao/src/main/java/org/thingsboard/server/dao/util/ImageUtils.java b/dao/src/main/java/org/thingsboard/server/dao/util/ImageUtils.java index 94d0b93b3d..673797f091 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/util/ImageUtils.java +++ b/dao/src/main/java/org/thingsboard/server/dao/util/ImageUtils.java @@ -70,7 +70,7 @@ public class ImageUtils { if (mediaTypeToFileExtension(mediaType).equals("svg")) { try { return processSvgImage(data, mediaType, thumbnailMaxDimension); - } catch (Exception e) { + } catch (Exception | LinkageError e) { if (log.isDebugEnabled()) { // printing stacktrace log.warn("Couldn't process SVG image, leaving preview as original image", e); } else { diff --git a/dao/src/main/java/org/thingsboard/server/dao/util/mapping/AiModelConfigConverter.java b/dao/src/main/java/org/thingsboard/server/dao/util/mapping/AiModelConfigConverter.java new file mode 100644 index 0000000000..adab7cc865 --- /dev/null +++ b/dao/src/main/java/org/thingsboard/server/dao/util/mapping/AiModelConfigConverter.java @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.util.mapping; + +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.ai.model.AiModelConfig; + +@Converter +public class AiModelConfigConverter implements AttributeConverter { + + @Override + public String convertToDatabaseColumn(AiModelConfig config) { + return JacksonUtil.toString(config); + } + + @Override + public AiModelConfig convertToEntityAttribute(String json) { + return JacksonUtil.fromString(json, AiModelConfig.class); + } + +} diff --git a/dao/src/main/java/org/thingsboard/server/dao/util/mapping/IotHubInstalledItemDescriptorConverter.java b/dao/src/main/java/org/thingsboard/server/dao/util/mapping/IotHubInstalledItemDescriptorConverter.java new file mode 100644 index 0000000000..fd0820e2b4 --- /dev/null +++ b/dao/src/main/java/org/thingsboard/server/dao/util/mapping/IotHubInstalledItemDescriptorConverter.java @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.util.mapping; + +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItemDescriptor; + +@Converter +public class IotHubInstalledItemDescriptorConverter implements AttributeConverter { + + @Override + public String convertToDatabaseColumn(IotHubInstalledItemDescriptor descriptor) { + return JacksonUtil.toString(descriptor); + } + + @Override + public IotHubInstalledItemDescriptor convertToEntityAttribute(String json) { + return JacksonUtil.fromString(json, IotHubInstalledItemDescriptor.class); + } + +} diff --git a/dao/src/test/java/org/thingsboard/server/dao/AbstractNoSqlContainer.java b/dao/src/test/java/org/thingsboard/server/dao/AbstractNoSqlContainer.java index f5e2af9f55..7e0d34cc66 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/AbstractNoSqlContainer.java +++ b/dao/src/test/java/org/thingsboard/server/dao/AbstractNoSqlContainer.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao; import com.github.dockerjava.api.command.InspectContainerResponse; @@ -7,8 +8,8 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.junit.ClassRule; import org.junit.rules.ExternalResource; -import org.testcontainers.containers.CassandraContainer; -import org.testcontainers.containers.delegate.CassandraDatabaseDelegate; +import org.testcontainers.cassandra.CassandraContainer; +import org.testcontainers.cassandra.CassandraDatabaseDelegate; import org.testcontainers.delegate.DatabaseDelegate; import org.testcontainers.ext.ScriptUtils; @@ -27,7 +28,6 @@ public abstract class AbstractNoSqlContainer { "cassandra/schema-ts-latest.cql" ); - @ClassRule(order = 0) public static final CassandraContainer cassandra = (CassandraContainer) new CassandraContainer("cassandra:5.0") { @Override protected void containerIsStarted(InspectContainerResponse containerInfo) { @@ -61,7 +61,7 @@ public abstract class AbstractNoSqlContainer { .withEnv("MAX_HEAP_SIZE", "512M") .withEnv("CASSANDRA_CLUSTER_NAME", "ThingsBoard Cluster"); - @ClassRule(order = 1) + @ClassRule(order = 0) public static ExternalResource resource = new ExternalResource() { @Override protected void before() throws Throwable { diff --git a/dao/src/test/java/org/thingsboard/server/dao/AbstractRedisClusterContainer.java b/dao/src/test/java/org/thingsboard/server/dao/AbstractRedisClusterContainer.java index 7a17bacbbf..8d48ac4165 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/AbstractRedisClusterContainer.java +++ b/dao/src/test/java/org/thingsboard/server/dao/AbstractRedisClusterContainer.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao; import lombok.extern.slf4j.Slf4j; @@ -26,21 +27,15 @@ public class AbstractRedisClusterContainer { "VALKEY_NODES", NODES ); - @ClassRule(order = 1) public static GenericContainer redis1 = new GenericContainer<>(IMAGE).withEnv(ENVS).withEnv("VALKEY_PORT_NUMBER", "6371").withNetworkMode("host").withLogConsumer(AbstractRedisClusterContainer::consumeLog); - @ClassRule(order = 2) public static GenericContainer redis2 = new GenericContainer<>(IMAGE).withEnv(ENVS).withEnv("VALKEY_PORT_NUMBER", "6372").withNetworkMode("host").withLogConsumer(AbstractRedisClusterContainer::consumeLog); - @ClassRule(order = 3) public static GenericContainer redis3 = new GenericContainer<>(IMAGE).withEnv(ENVS).withEnv("VALKEY_PORT_NUMBER", "6373").withNetworkMode("host").withLogConsumer(AbstractRedisClusterContainer::consumeLog); - @ClassRule(order = 4) public static GenericContainer redis4 = new GenericContainer<>(IMAGE).withEnv(ENVS).withEnv("VALKEY_PORT_NUMBER", "6374").withNetworkMode("host").withLogConsumer(AbstractRedisClusterContainer::consumeLog); - @ClassRule(order = 5) public static GenericContainer redis5 = new GenericContainer<>(IMAGE).withEnv(ENVS).withEnv("VALKEY_PORT_NUMBER", "6375").withNetworkMode("host").withLogConsumer(AbstractRedisClusterContainer::consumeLog); - @ClassRule(order = 6) public static GenericContainer redis6 = new GenericContainer<>(IMAGE).withEnv(ENVS).withEnv("VALKEY_PORT_NUMBER", "6376").withNetworkMode("host").withLogConsumer(AbstractRedisClusterContainer::consumeLog); - @ClassRule(order = 100) + @ClassRule(order = 0) public static ExternalResource resource = new ExternalResource() { @Override protected void before() throws Throwable { diff --git a/dao/src/test/java/org/thingsboard/server/dao/AbstractRedisContainer.java b/dao/src/test/java/org/thingsboard/server/dao/AbstractRedisContainer.java index 5a6fd0ff9a..a5aeb9676b 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/AbstractRedisContainer.java +++ b/dao/src/test/java/org/thingsboard/server/dao/AbstractRedisContainer.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao; import lombok.extern.slf4j.Slf4j; @@ -13,13 +14,12 @@ import java.util.List; @Slf4j public class AbstractRedisContainer { - @ClassRule(order = 0) public static GenericContainer redis = new GenericContainer<>("bitnamilegacy/valkey:8.0") .withEnv("ALLOW_EMPTY_PASSWORD","yes") .withLogConsumer(s -> log.warn(((OutputFrame) s).getUtf8String().trim())) .withExposedPorts(6379); - @ClassRule(order = 1) + @ClassRule(order = 0) public static ExternalResource resource = new ExternalResource() { @Override protected void before() throws Throwable { diff --git a/dao/src/test/java/org/thingsboard/server/dao/aspect/SqlDaoCallsAspectTest.java b/dao/src/test/java/org/thingsboard/server/dao/aspect/SqlDaoCallsAspectTest.java new file mode 100644 index 0000000000..3c9caeb8b8 --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/aspect/SqlDaoCallsAspectTest.java @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.aspect; + +import org.junit.Test; +import org.springframework.aop.framework.Advised; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.TestPropertySource; +import org.thingsboard.server.dao.device.DeviceDao; +import org.thingsboard.server.dao.service.AbstractServiceTest; +import org.thingsboard.server.dao.service.DaoSqlTest; + +import static org.assertj.core.api.Assertions.assertThat; + +@DaoSqlTest +@TestPropertySource(properties = "sql.log_tenant_stats=true") +public class SqlDaoCallsAspectTest extends AbstractServiceTest { + + @Autowired + private DeviceDao deviceDao; + + @Test + public void sqlDaoCallsAspectAdvisesSqlDaos() { + assertThat(deviceDao).isInstanceOf(Advised.class); + assertThat(((Advised) deviceDao).getAdvisors()).anyMatch(a -> a.toString().contains("SqlDaoCallsAspect")); + } + +} diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/AbstractServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/AbstractServiceTest.java index aff733ff6e..a99a283d9d 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/AbstractServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/AbstractServiceTest.java @@ -6,6 +6,7 @@ package org.thingsboard.server.dao.service; import com.datastax.oss.driver.api.core.uuid.Uuids; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.commons.lang3.NotImplementedException; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -19,7 +20,6 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.testcontainers.shaded.org.apache.commons.lang3.NotImplementedException; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/AdminSettingsServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/AdminSettingsServiceTest.java index 8248c6c278..1d27812eb1 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/AdminSettingsServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/AdminSettingsServiceTest.java @@ -103,6 +103,63 @@ public class AdminSettingsServiceTest extends AbstractServiceTest { }).hasMessageContaining("already exists"); } + @Test + public void whenUpdatingSettingsOfAnotherTenantById_thenSaveIsRejectedAndStoredSettingsUnchanged() { + AdminSettings systemSettings = saveSettings(SYSTEM_TENANT_ID, 1); + AdminSettings systemSettingsCopy = new AdminSettings(systemSettings); + systemSettingsCopy.setTenantId(tenantId); + systemSettingsCopy.setJsonValue(JacksonUtil.newObjectNode().put("v", 2)); + assertThatThrownBy(() -> adminSettingsService.saveAdminSettings(tenantId, systemSettingsCopy)) + .isInstanceOf(DataValidationException.class) + .hasMessageContaining("different tenant"); + AdminSettings storedSystemSettings = adminSettingsService.findAdminSettingsById(SYSTEM_TENANT_ID, systemSettings.getId()); + assertThat(storedSystemSettings.getTenantId()).isEqualTo(SYSTEM_TENANT_ID); + assertThat(storedSystemSettings.getJsonValue()).isEqualTo(systemSettings.getJsonValue()); + + AdminSettings tenantSettings = saveSettings(tenantId, 1); + AdminSettings tenantSettingsCopy = new AdminSettings(tenantSettings); + tenantSettingsCopy.setTenantId(SYSTEM_TENANT_ID); + tenantSettingsCopy.setJsonValue(JacksonUtil.newObjectNode().put("v", 2)); + assertThatThrownBy(() -> adminSettingsService.saveAdminSettings(SYSTEM_TENANT_ID, tenantSettingsCopy)) + .isInstanceOf(DataValidationException.class) + .hasMessageContaining("different tenant"); + AdminSettings storedTenantSettings = adminSettingsService.findAdminSettingsById(tenantId, tenantSettings.getId()); + assertThat(storedTenantSettings.getTenantId()).isEqualTo(tenantId); + assertThat(storedTenantSettings.getJsonValue()).isEqualTo(tenantSettings.getJsonValue()); + } + + @Test + public void whenUpdatingOwnSettingsById_thenSaved() { + AdminSettings tenantSettings = saveSettings(tenantId, 1); + tenantSettings.setJsonValue(JacksonUtil.newObjectNode().put("v", 2)); + adminSettingsService.saveAdminSettings(tenantId, tenantSettings); + AdminSettings storedTenantSettings = adminSettingsService.findAdminSettingsById(tenantId, tenantSettings.getId()); + assertThat(storedTenantSettings.getTenantId()).isEqualTo(tenantId); + assertThat(storedTenantSettings.getJsonValue()).isEqualTo(tenantSettings.getJsonValue()); + + AdminSettings systemSettings = saveSettings(SYSTEM_TENANT_ID, 1); + systemSettings.setTenantId(null); + systemSettings.setJsonValue(JacksonUtil.newObjectNode().put("v", 2)); + adminSettingsService.saveAdminSettings(SYSTEM_TENANT_ID, systemSettings); + AdminSettings storedSystemSettings = adminSettingsService.findAdminSettingsById(SYSTEM_TENANT_ID, systemSettings.getId()); + assertThat(storedSystemSettings.getTenantId()).isEqualTo(SYSTEM_TENANT_ID); + assertThat(storedSystemSettings.getJsonValue()).isEqualTo(systemSettings.getJsonValue()); + + storedSystemSettings.setJsonValue(JacksonUtil.newObjectNode().put("v", 3)); + adminSettingsService.saveAdminSettings(tenantId, storedSystemSettings); + AdminSettings updatedSystemSettings = adminSettingsService.findAdminSettingsById(SYSTEM_TENANT_ID, systemSettings.getId()); + assertThat(updatedSystemSettings.getTenantId()).isEqualTo(SYSTEM_TENANT_ID); + assertThat(updatedSystemSettings.getJsonValue()).isEqualTo(storedSystemSettings.getJsonValue()); + } + + private AdminSettings saveSettings(TenantId tenantId, int value) { + AdminSettings settings = new AdminSettings(); + settings.setTenantId(tenantId); + settings.setKey(RandomStringUtils.randomAlphanumeric(15)); + settings.setJsonValue(JacksonUtil.newObjectNode().put("v", value)); + return adminSettingsService.saveAdminSettings(tenantId, settings); + } + @Test public void testFindAllByTenantId() { int pageSize = 10; diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/AgentServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/AgentServiceTest.java index b13c737c7b..7bd8c2a52c 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/AgentServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/AgentServiceTest.java @@ -4,11 +4,11 @@ package org.thingsboard.server.dao.service; import com.datastax.oss.driver.api.core.uuid.Uuids; import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.commons.lang3.RandomStringUtils; import org.junit.Assert; import org.junit.Test; import org.junit.jupiter.api.Assertions; import org.springframework.beans.factory.annotation.Autowired; -import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.StringUtils; diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java index 069f7d07b2..38397e2069 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java @@ -64,14 +64,17 @@ import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.exception.DataValidationException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; @DaoSqlTest public class AlarmServiceTest extends AbstractServiceTest { @@ -729,6 +732,131 @@ public class AlarmServiceTest extends AbstractServiceTest { Assert.assertEquals(customerAlarm, new AlarmInfo(customerAlarms.getData().get(0))); } + @Test + public void testFindAlarmDataByQueryWithoutEntityFilter() { + Customer customer = new Customer(); + customer.setTitle("TestCustomer"); + customer.setTenantId(tenantId); + customer = customerService.saveCustomer(customer); + + Device tenantDevice = new Device(); + tenantDevice.setName("TestTenantDevice"); + tenantDevice.setType("default"); + tenantDevice.setTenantId(tenantId); + tenantDevice = deviceService.saveDevice(tenantDevice); + + Device customerDevice = new Device(); + customerDevice.setName("TestCustomerDevice"); + customerDevice.setType("default"); + customerDevice.setTenantId(tenantId); + customerDevice.setCustomerId(customer.getId()); + customerDevice = deviceService.saveDevice(customerDevice); + + long ts = System.currentTimeMillis(); + AlarmInfo tenantAlarm = alarmService.createAlarm(AlarmCreateOrUpdateActiveRequest.builder() + .tenantId(tenantId) + .originator(tenantDevice.getId()) + .type(TEST_ALARM) + .severity(AlarmSeverity.CRITICAL) + .startTs(ts).build()).getAlarm(); + AlarmInfo clearedAlarm = alarmService.createAlarm(AlarmCreateOrUpdateActiveRequest.builder() + .tenantId(tenantId) + .originator(tenantDevice.getId()) + .type("Cleared Alarm") + .severity(AlarmSeverity.MAJOR) + .startTs(ts).build()).getAlarm(); + alarmService.clearAlarm(tenantId, clearedAlarm.getOriginator(), clearedAlarm.getId(), System.currentTimeMillis(), null, true); + await().atMost(1, TimeUnit.SECONDS).until(() -> System.currentTimeMillis() > tenantAlarm.getCreatedTime() + 1); + AlarmInfo customerAlarm = alarmService.createAlarm(AlarmCreateOrUpdateActiveRequest.builder() + .tenantId(tenantId) + .customerId(customer.getId()) + .originator(customerDevice.getId()) + .type(TEST_ALARM) + .severity(AlarmSeverity.MAJOR) + .startTs(ts).build()).getAlarm(); + + AlarmDataPageLink pageLink = new AlarmDataPageLink(); + pageLink.setPage(0); + pageLink.setPageSize(10); + pageLink.setStatusList(List.of(AlarmSearchStatus.ACTIVE)); + AlarmDataQuery query = new AlarmDataQuery(null, pageLink, null, null, null, Collections.emptyList()); + + PageData tenantAlarms = alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, query); + Assert.assertEquals(2, tenantAlarms.getTotalElements()); + Assert.assertEquals(List.of(customerAlarm.getId(), tenantAlarm.getId()), tenantAlarms.getData().stream().map(AlarmData::getId).toList()); + Assert.assertEquals(List.of(customerDevice.getId(), tenantDevice.getId()), tenantAlarms.getData().stream().map(AlarmData::getEntityId).toList()); + + PageData customerAlarms = alarmService.findAlarmDataByQuery(tenantId, customer.getId(), mergedUserPermissions, query); + Assert.assertEquals(List.of(customerAlarm.getId()), customerAlarms.getData().stream().map(AlarmData::getId).toList()); + + pageLink.setSeverityList(List.of(AlarmSeverity.CRITICAL)); + PageData criticalAlarms = alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, query); + Assert.assertEquals(List.of(tenantAlarm.getId()), criticalAlarms.getData().stream().map(AlarmData::getId).toList()); + + pageLink.setSeverityList(null); + pageLink.setPageSize(1); + PageData firstPage = alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, query); + Assert.assertEquals(1, firstPage.getData().size()); + Assert.assertEquals(2, firstPage.getTotalElements()); + Assert.assertTrue(firstPage.hasNext()); + } + + @Test + public void testSortAlarmDataBySeverityPriority() { + Device device = new Device(); + device.setName("TestSeverityDevice"); + device.setType("default"); + device.setTenantId(tenantId); + device = deviceService.saveDevice(device); + + long ts = System.currentTimeMillis(); + List ids = new ArrayList<>(); + for (AlarmSeverity severity : List.of(AlarmSeverity.INDETERMINATE, AlarmSeverity.CRITICAL, AlarmSeverity.WARNING, AlarmSeverity.MAJOR, AlarmSeverity.MINOR)) { + ids.add(alarmService.createAlarm(AlarmCreateOrUpdateActiveRequest.builder() + .tenantId(tenantId) + .originator(device.getId()) + .type("Severity " + severity) + .severity(severity) + .startTs(ts).build()).getAlarm().getId()); + } + List byPriority = List.of(ids.get(1), ids.get(3), ids.get(4), ids.get(2), ids.get(0)); + + AlarmDataPageLink pageLink = new AlarmDataPageLink(); + pageLink.setPage(0); + pageLink.setPageSize(10); + pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.ASC)); + AlarmDataQuery ownerQuery = new AlarmDataQuery(null, pageLink, null, null, null, Collections.emptyList()); + + Assert.assertEquals(byPriority, alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery) + .getData().stream().map(AlarmData::getId).toList()); + Assert.assertEquals(byPriority, alarmService.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, toQuery(pageLink), List.of(device.getId())) + .getData().stream().map(AlarmData::getId).toList()); + + pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.DESC)); + Assert.assertEquals(byPriority.reversed(), alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery) + .getData().stream().map(AlarmData::getId).toList()); + + pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.ASC)); + pageLink.setTextSearch("Severity"); + Assert.assertEquals(byPriority, alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery) + .getData().stream().map(AlarmData::getId).toList()); + Assert.assertEquals(byPriority, alarmService.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, toQuery(pageLink), List.of(device.getId())) + .getData().stream().map(AlarmData::getId).toList()); + + List types = Arrays.stream(AlarmSeverity.values()).map(severity -> "Severity " + severity).toList(); + for (SortOrder.Direction direction : SortOrder.Direction.values()) { + List expected = direction == SortOrder.Direction.ASC ? byPriority : byPriority.reversed(); + TimePageLink timePageLink = new TimePageLink(10, 0, null, new SortOrder("severity", direction), null, null); + Assert.assertEquals(expected, alarmService.findAlarmsV2(tenantId, AlarmQueryV2.builder() + .affectedEntityId(device.getId()).pageLink(timePageLink).build()).getData().stream().map(AlarmInfo::getId).toList()); + Assert.assertEquals(expected, alarmService.findAlarmsV2(tenantId, AlarmQueryV2.builder() + .typeList(types).pageLink(timePageLink).build()).getData().stream().map(AlarmInfo::getId).toList()); + Assert.assertEquals(expected, alarmService.findAlarms(tenantId, AlarmQuery.builder() + .affectedEntityId(device.getId()).pageLink(new TimePageLink(10, 0, "Severity", new SortOrder("severity", direction), null, null)).build()) + .getData().stream().map(AlarmInfo::getId).toList()); + } + } + private AlarmDataQuery toQuery(AlarmDataPageLink pageLink) { return toQuery(pageLink, Collections.emptyList()); } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/AssetServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/AssetServiceTest.java index 5476e4d3a0..09f224e5df 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/AssetServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/AssetServiceTest.java @@ -6,6 +6,7 @@ package org.thingsboard.server.dao.service; import com.datastax.oss.driver.api.core.uuid.Uuids; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; +import org.awaitility.Awaitility; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; @@ -16,7 +17,6 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.apache.commons.lang3.RandomStringUtils; -import org.testcontainers.shaded.org.awaitility.Awaitility; import org.thingsboard.common.util.ThingsBoardThreadFactory; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntitySubtype; diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/CustomerServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/CustomerServiceTest.java index fbb8b782d0..a9ae88c6d7 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/CustomerServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/CustomerServiceTest.java @@ -8,13 +8,13 @@ import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; +import org.awaitility.Awaitility; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.jupiter.api.Assertions; import org.springframework.beans.factory.annotation.Autowired; -import org.testcontainers.shaded.org.awaitility.Awaitility; import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.StringUtils; diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/DeviceServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/DeviceServiceTest.java index 2a2d99d056..12fbf2068b 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/DeviceServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/DeviceServiceTest.java @@ -6,6 +6,7 @@ package org.thingsboard.server.dao.service; import com.datastax.oss.driver.api.core.uuid.Uuids; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; +import org.awaitility.Awaitility; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; @@ -19,7 +20,6 @@ import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; -import org.testcontainers.shaded.org.awaitility.Awaitility; import org.thingsboard.common.util.ThingsBoardThreadFactory; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/EntityGroupServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/EntityGroupServiceTest.java index 99eda2f067..a9564579d4 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/EntityGroupServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/EntityGroupServiceTest.java @@ -15,6 +15,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.ShortEntityView; @@ -31,6 +32,7 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IdBased; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.AttributesSaveResult; import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; @@ -45,6 +47,7 @@ import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.attributes.AttributesService; +import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.group.EntityGroupService; @@ -81,6 +84,8 @@ public class EntityGroupServiceTest extends AbstractServiceTest { EntityGroupService entityGroupService; @Autowired EdgeService edgeService; + @Autowired + CustomerService customerService; private MergedUserPermissions mergedUserPermissions; @@ -100,6 +105,34 @@ public class EntityGroupServiceTest extends AbstractServiceTest { executor.shutdownNow(); } + @Test + public void testFindEntityGroupInfoByTenantIdAndId() { + EntityGroup tenantGroup = new EntityGroup(); + tenantGroup.setName("Tenant Device Group"); + tenantGroup.setType(EntityType.DEVICE); + tenantGroup = entityGroupService.saveEntityGroup(tenantId, tenantId, tenantGroup); + + Customer customer = new Customer(); + customer.setTenantId(tenantId); + customer.setTitle("Group Owner Customer"); + customer = customerService.saveCustomer(customer); + EntityGroup customerGroup = new EntityGroup(); + customerGroup.setName("Customer Device Group"); + customerGroup.setType(EntityType.DEVICE); + customerGroup = entityGroupService.saveEntityGroup(tenantId, customer.getId(), customerGroup); + + TenantId otherTenantId = createTenant().getId(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup = entityGroupService.saveEntityGroup(otherTenantId, otherTenantId, otherTenantGroup); + + assertThat(entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, tenantGroup.getId()).getId()).isEqualTo(tenantGroup.getId()); + assertThat(entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, customerGroup.getId()).getId()).isEqualTo(customerGroup.getId()); + assertThat(entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, otherTenantGroup.getId())).isNull(); + assertThat(entityGroupService.findEntityGroupInfoByTenantIdAndId(otherTenantId, otherTenantGroup.getId()).getId()).isEqualTo(otherTenantGroup.getId()); + } + @Test public void testFindGroupEntityIds() throws ExecutionException, InterruptedException, TimeoutException { List> futures = new ArrayList<>(97); @@ -515,6 +548,55 @@ public class EntityGroupServiceTest extends AbstractServiceTest { .hasMessage("Entity '" + entityGroupId.getEntityType() + "' is not a group entity!"); } + @Test + public void testShouldNotChangeEntityGroupOwnerOnUpdate() { + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName("Device Group"); + EntityGroup savedEntityGroup = entityGroupService.saveEntityGroup(tenantId, tenantId, entityGroup); + + CustomerId customerId = new CustomerId(UUID.randomUUID()); + EntityGroup movedEntityGroup = new EntityGroup(savedEntityGroup); + movedEntityGroup.setOwnerId(customerId); + + assertThatThrownBy(() -> entityGroupService.saveEntityGroup(tenantId, customerId, movedEntityGroup)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Entity group owner can't be changed!"); + assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getOwnerId()).isEqualTo(tenantId); + } + + @Test + public void testShouldNotChangeEntityGroupTypeOnUpdate() { + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName("Device Group"); + EntityGroup savedEntityGroup = entityGroupService.saveEntityGroup(tenantId, tenantId, entityGroup); + + EntityGroup retypedEntityGroup = new EntityGroup(savedEntityGroup); + retypedEntityGroup.setType(EntityType.USER); + + assertThatThrownBy(() -> entityGroupService.saveEntityGroup(tenantId, tenantId, retypedEntityGroup)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Entity group type can't be changed!"); + assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getType()).isEqualTo(EntityType.DEVICE); + } + + @Test + public void testShouldUpdateEntityGroupWithSameOwner() { + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName("Device Group"); + EntityGroup savedEntityGroup = entityGroupService.saveEntityGroup(tenantId, tenantId, entityGroup); + + EntityGroup renamedEntityGroup = new EntityGroup(savedEntityGroup); + renamedEntityGroup.setName("Renamed Device Group"); + entityGroupService.saveEntityGroup(tenantId, tenantId, renamedEntityGroup); + + EntityGroup foundEntityGroup = entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()); + assertThat(foundEntityGroup.getName()).isEqualTo("Renamed Device Group"); + assertThat(foundEntityGroup.getOwnerId()).isEqualTo(tenantId); + } + private ListenableFuture saveStringAttribute(EntityId entityId, String key, String value, AttributeScope scope) { KvEntry attrValue = new StringDataEntry(key, value); AttributeKvEntry attr = new BaseAttributeKvEntry(attrValue, 42L); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java new file mode 100644 index 0000000000..65fe12ae2b --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -0,0 +1,136 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.service; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.page.SortOrder; +import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +@DaoSqlTest +public class IotHubInstalledItemServiceTest extends AbstractServiceTest { + + @Autowired + IotHubInstalledItemService installedItemService; + + private final UUID trackerItemId = UUID.randomUUID(); + private final UUID sensorItemId = UUID.randomUUID(); + private final UUID unpublishedItemId = UUID.randomUUID(); + private final UUID trackerPublished = UUID.randomUUID(); + private final UUID sensorPublished = UUID.randomUUID(); + + private void install(String name, UUID itemId, UUID versionId) { + IotHubInstalledItem item = new IotHubInstalledItem(); + item.setTenantId(tenantId); + item.setItemId(itemId); + item.setItemVersionId(versionId); + item.setItemName(name); + item.setItemType("WIDGET"); + item.setVersion("1.0.0"); + item.setDescriptor(new WidgetInstalledItemDescriptor()); + installedItemService.save(tenantId, item); + } + + /** a and c are up to date, b and d have an update (d is a second install of a's item in an older version), e has no published version. */ + private void installFive() { + install("a", sensorItemId, sensorPublished); + install("b", trackerItemId, UUID.randomUUID()); + install("c", sensorItemId, sensorPublished); + install("d", sensorItemId, UUID.randomUUID()); + install("e", unpublishedItemId, UUID.randomUUID()); + } + + private Map published() { + return Map.of(trackerItemId, trackerPublished, sensorItemId, sensorPublished); + } + + private static List names(PageData page) { + return page.getData().stream().map(IotHubInstalledItem::getItemName).toList(); + } + + @Test + public void withUpdates_onlyTheItemsWithAnUpdate_inThePageSort() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.DESC)); + + PageData page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), byName); + + assertThat(names(page)).containsExactly("d", "b"); + assertThat(page.getTotalElements()).isEqualTo(2); + } + + @Test + public void withUpdates_pagesAndTotal() { + installFive(); + SortOrder byName = new SortOrder("itemName", SortOrder.Direction.ASC); + + PageData first = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), + new PageLink(1, 0, null, byName)); + PageData second = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), + new PageLink(1, 1, null, byName)); + + assertThat(names(first)).containsExactly("b"); + assertThat(names(second)).containsExactly("d"); + assertThat(first.getTotalElements()).isEqualTo(2); + assertThat(first.hasNext()).isTrue(); + assertThat(second.hasNext()).isFalse(); + } + + @Test + public void withUpdates_keepsTheSearchAndTheTypes() { + installFive(); + // "b" is in no item type or version, only in the name of b + PageLink search = new PageLink(10, 0, "b", new SortOrder("itemName", SortOrder.Direction.ASC)); + + assertThat(names(installedItemService.findByTenantIdWithUpdates(tenantId, List.of("WIDGET"), published(), search))) + .containsExactly("b"); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, List.of("DEVICE"), published(), + new PageLink(10)).getData()).isEmpty(); + } + + @Test + public void plainList_sameQuery_isNotFiltered() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); + + assertThat(names(installedItemService.findByTenantId(tenantId, null, null, byName))).containsExactly("a", "b", "c", "d", "e"); + assertThat(names(installedItemService.findByTenantId(tenantId, null, sensorItemId, byName))).containsExactly("a", "c", "d"); + } + + @Test + public void withUpdates_ignoresItemsTheTenantHasNotInstalled() { + installFive(); + Map published = new HashMap<>(published()); + for (int i = 0; i < 20_000; i++) { + published.put(UUID.randomUUID(), UUID.randomUUID()); + } + + PageData page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published, + new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC))); + + // 40k bind parameters would be over PostgreSQL's limit of 32767 + assertThat(names(page)).containsExactly("b", "d"); + } + + @Test + public void withUpdates_withoutPublishedVersions_isEmpty() { + installFive(); + Map unpublished = new HashMap<>(); + unpublished.put(unpublishedItemId, null); + + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, Map.of(), new PageLink(10)).getData()).isEmpty(); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, unpublished, new PageLink(10)).getData()).isEmpty(); + } + +} diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java index f91e722b3f..488cbb9dfa 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.dao.service.timeseries; -import com.datastax.oss.driver.api.core.uuid.Uuids; import lombok.extern.slf4j.Slf4j; import org.assertj.core.data.Offset; import org.junit.After; @@ -11,6 +10,7 @@ import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.id.DeviceId; @@ -31,6 +31,7 @@ import org.thingsboard.server.common.data.kv.ReadTsKvQueryResult; import org.thingsboard.server.common.data.kv.StringDataEntry; import org.thingsboard.server.common.data.kv.TsKvEntry; import org.thingsboard.server.common.data.objects.TelemetryEntityView; +import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.entityview.EntityViewService; import org.thingsboard.server.dao.exception.IncorrectParameterException; import org.thingsboard.server.dao.service.AbstractServiceTest; @@ -63,6 +64,9 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { @Autowired EntityViewService entityViewService; + @Autowired + DeviceService deviceService; + @Value("${database.ts.type}") String databaseTsLatestType; @@ -82,7 +86,7 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { KvEntry booleanKvEntry = new BooleanDataEntry(BOOLEAN_KEY, Boolean.TRUE); protected TenantId tenantId; - protected DeviceId deviceId = new DeviceId(Uuids.timeBased()); + protected DeviceId deviceId; @Before public void before() { @@ -91,6 +95,12 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { Tenant savedTenant = tenantService.saveTenant(tenant); Assert.assertNotNull(savedTenant); tenantId = savedTenant.getId(); + + Device device = new Device(); + device.setTenantId(tenantId); + device.setName("My device"); + device.setType("default"); + deviceId = deviceService.saveDevice(device).getId(); } @After diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidatorTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidatorTest.java index b42309a6f2..6e7872010a 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidatorTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidatorTest.java @@ -8,12 +8,19 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.id.AdminSettingsId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.exception.DataValidationException; import java.util.UUID; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @SpringBootTest(classes = AdminSettingsDataValidator.class) class AdminSettingsDataValidatorTest { @@ -34,4 +41,38 @@ class AdminSettingsDataValidatorTest { verify(validator).validateString("Key", adminSettings.getKey()); } -} \ No newline at end of file + @Test + void whenStoredSettingsBelongToAnotherTenant_thenUpdateIsRejected() { + AdminSettings stored = settings(TenantId.SYS_TENANT_ID); + when(adminSettingsService.findAdminSettingsById(any(), eq(stored.getId()))).thenReturn(stored); + + AdminSettings update = new AdminSettings(stored); + update.setTenantId(tenantId); + + assertThatThrownBy(() -> validator.validateUpdate(tenantId, update)) + .isInstanceOf(DataValidationException.class) + .hasMessageContaining("different tenant"); + } + + @Test + void whenStoredSettingsBelongToSameTenant_thenStoredSettingsReturned() { + AdminSettings stored = settings(tenantId); + when(adminSettingsService.findAdminSettingsById(any(), eq(stored.getId()))).thenReturn(stored); + assertThat(validator.validateUpdate(TenantId.SYS_TENANT_ID, new AdminSettings(stored))).isEqualTo(stored); + + AdminSettings storedSystemSettings = settings(TenantId.SYS_TENANT_ID); + when(adminSettingsService.findAdminSettingsById(any(), eq(storedSystemSettings.getId()))).thenReturn(storedSystemSettings); + AdminSettings update = new AdminSettings(storedSystemSettings); + update.setTenantId(null); + assertThat(validator.validateUpdate(TenantId.SYS_TENANT_ID, update)).isEqualTo(storedSystemSettings); + } + + private AdminSettings settings(TenantId tenantId) { + AdminSettings settings = new AdminSettings(new AdminSettingsId(UUID.randomUUID())); + settings.setTenantId(tenantId); + settings.setKey("general"); + settings.setJsonValue(JacksonUtil.newObjectNode().put("v", 1)); + return settings; + } + +} diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidatorTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidatorTest.java index 0cb12152be..c3163970a0 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidatorTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidatorTest.java @@ -3,36 +3,65 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao.service.validator; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.cf.CalculatedField; import org.thingsboard.server.common.data.cf.CalculatedFieldType; +import org.thingsboard.server.common.data.cf.configuration.Argument; +import org.thingsboard.server.common.data.cf.configuration.ArgumentType; +import org.thingsboard.server.common.data.cf.configuration.ReferencedEntityKey; +import org.thingsboard.server.common.data.cf.configuration.SimpleCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput; import org.thingsboard.server.common.data.id.CalculatedFieldId; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.cf.CalculatedFieldDao; +import org.thingsboard.server.dao.device.DeviceDao; +import org.thingsboard.server.dao.entity.EntityDaoRegistry; import org.thingsboard.server.dao.usagerecord.DefaultApiLimitService; import org.thingsboard.server.exception.DataValidationException; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.UUID; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; @SpringBootTest(classes = CalculatedFieldDataValidator.class) public class CalculatedFieldDataValidatorTest { private final TenantId TENANT_ID = TenantId.fromUUID(UUID.fromString("7b5229e9-166e-41a9-a257-3b1dafad1b04")); + private final TenantId OTHER_TENANT_ID = TenantId.fromUUID(UUID.fromString("2f3d5c1e-7a52-4c8b-9d36-0b0e4f1a6c27")); private final CalculatedFieldId CALCULATED_FIELD_ID = new CalculatedFieldId(UUID.fromString("060fbe45-fbb2-4549-abf3-f72a6be3cb9f")); + private final DeviceId DEVICE_ID = new DeviceId(UUID.fromString("5a1f0e8c-3b44-4f0e-8e2a-91c7d6b3e512")); + private final DeviceId REFERENCED_DEVICE_ID = new DeviceId(UUID.fromString("c8e2b7d4-1f6a-4e93-a5c0-7d2f9b4e8a31")); @MockitoBean private CalculatedFieldDao calculatedFieldDao; @MockitoBean private DefaultApiLimitService apiLimitService; + @MockitoBean + private EntityDaoRegistry entityDaoRegistry; @MockitoSpyBean private CalculatedFieldDataValidator validator; + private final DeviceDao deviceDao = mock(DeviceDao.class); + + @BeforeEach + public void setUp() { + given(entityDaoRegistry.getDao(EntityType.DEVICE)).willReturn(deviceDao); + given(deviceDao.findById(TENANT_ID, DEVICE_ID.getId())).willReturn(getDevice(DEVICE_ID, TENANT_ID)); + } + @Test public void testUpdateNonExistingCalculatedField() { CalculatedField calculatedField = new CalculatedField(CALCULATED_FIELD_ID); @@ -46,4 +75,85 @@ public class CalculatedFieldDataValidatorTest { .hasMessage("Can't update non existing calculated field!"); } + @Test + public void testUpdateCalculatedFieldOfOtherTenant() { + CalculatedField calculatedField = getCalculatedField(TENANT_ID); + calculatedField.setId(CALCULATED_FIELD_ID); + CalculatedField stored = getCalculatedField(TENANT_ID); + stored.setId(CALCULATED_FIELD_ID); + stored.setTenantId(OTHER_TENANT_ID); + + given(calculatedFieldDao.findById(TENANT_ID, CALCULATED_FIELD_ID.getId())).willReturn(stored); + + assertThatThrownBy(() -> validator.validateUpdate(TENANT_ID, calculatedField)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Can't update calculated field tenant id!"); + } + + @Test + public void testValidateCalculatedFieldWithOwnReferences() { + given(deviceDao.findById(TENANT_ID, REFERENCED_DEVICE_ID.getId())).willReturn(getDevice(REFERENCED_DEVICE_ID, TENANT_ID)); + + assertThatCode(() -> validator.validate(getCalculatedField(TENANT_ID, REFERENCED_DEVICE_ID), CalculatedField::getTenantId)) + .doesNotThrowAnyException(); + } + + @Test + public void testValidateCalculatedFieldWithOtherTenantReference() { + assertThatThrownBy(() -> validator.validate(getCalculatedField(OTHER_TENANT_ID), CalculatedField::getTenantId)) + .isInstanceOf(DataValidationException.class); + } + + @Test + public void testValidateCalculatedFieldWithOtherTenantDeviceReference() { + given(deviceDao.findById(TENANT_ID, REFERENCED_DEVICE_ID.getId())).willReturn(getDevice(REFERENCED_DEVICE_ID, OTHER_TENANT_ID)); + + assertThatThrownBy(() -> validator.validate(getCalculatedField(REFERENCED_DEVICE_ID), CalculatedField::getTenantId)) + .isInstanceOf(DataValidationException.class); + } + + @Test + public void testValidateCalculatedFieldWithMissingDeviceReference() { + assertThatThrownBy(() -> validator.validate(getCalculatedField(REFERENCED_DEVICE_ID), CalculatedField::getTenantId)) + .isInstanceOf(DataValidationException.class); + } + + @Test + public void testValidateCalculatedFieldWithOtherTenantTarget() { + given(deviceDao.findById(TENANT_ID, DEVICE_ID.getId())).willReturn(getDevice(DEVICE_ID, OTHER_TENANT_ID)); + + assertThatThrownBy(() -> validator.validate(getCalculatedField(TENANT_ID), CalculatedField::getTenantId)) + .isInstanceOf(DataValidationException.class); + } + + private CalculatedField getCalculatedField(EntityId... refEntityIds) { + SimpleCalculatedFieldConfiguration configuration = new SimpleCalculatedFieldConfiguration(); + Map arguments = new LinkedHashMap<>(); + for (int i = 0; i < refEntityIds.length; i++) { + Argument argument = new Argument(); + argument.setRefEntityId(refEntityIds[i]); + argument.setRefEntityKey(new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null)); + arguments.put("a" + i, argument); + } + configuration.setArguments(arguments); + configuration.setExpression("a0"); + TimeSeriesOutput output = new TimeSeriesOutput(); + output.setName("output"); + configuration.setOutput(output); + + CalculatedField calculatedField = new CalculatedField(); + calculatedField.setTenantId(TENANT_ID); + calculatedField.setEntityId(DEVICE_ID); + calculatedField.setType(CalculatedFieldType.SIMPLE); + calculatedField.setName("Test"); + calculatedField.setConfiguration(configuration); + return calculatedField; + } + + private Device getDevice(DeviceId deviceId, TenantId tenantId) { + Device device = new Device(deviceId); + device.setTenantId(tenantId); + return device; + } + } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidatorTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidatorTest.java index b367e660f8..67c6fbd0d2 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidatorTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidatorTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao.service.validator; import org.junit.jupiter.api.BeforeEach; @@ -7,15 +8,24 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.HasId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.customer.CustomerDao; +import org.thingsboard.server.dao.entity.EntityService; import org.thingsboard.server.dao.entityview.EntityViewDao; import org.thingsboard.server.dao.tenant.TenantService; +import org.thingsboard.server.exception.DataValidationException; +import java.util.Optional; import java.util.UUID; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.willReturn; +import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.verify; @SpringBootTest(classes = EntityViewDataValidator.class) @@ -27,9 +37,12 @@ class EntityViewDataValidatorTest { TenantService tenantService; @MockitoBean CustomerDao customerDao; + @MockitoBean + EntityService entityService; @MockitoSpyBean EntityViewDataValidator validator; TenantId tenantId = TenantId.fromUUID(UUID.fromString("9ef79cdf-37a8-4119-b682-2e7ed4e018da")); + DeviceId deviceId = new DeviceId(UUID.fromString("3c6f2b7e-5a41-4d8e-9f0b-7e2d1c4a8b95")); @BeforeEach void setUp() { @@ -42,10 +55,86 @@ class EntityViewDataValidatorTest { entityView.setName("view"); entityView.setType("default"); entityView.setTenantId(tenantId); + entityView.setEntityId(deviceId); + willReturn(Optional.of(newDevice(tenantId))).given(entityService).fetchEntity(tenantId, deviceId); validator.validateDataImpl(tenantId, entityView); verify(validator).validateString("Entity view name", entityView.getName()); verify(validator).validateString("Entity view type", entityView.getType()); } + @Test + void testValidateEntityViewWithEntityOfSameTenant() { + EntityView entityView = newEntityView(deviceId); + willReturn(Optional.of(newDevice(tenantId))).given(entityService).fetchEntity(tenantId, deviceId); + + assertThatCode(() -> validator.validateDataImpl(tenantId, entityView)).doesNotThrowAnyException(); + } + + @Test + void testValidateEntityViewWithNonExistentEntity() { + EntityView entityView = newEntityView(deviceId); + willReturn(Optional.empty()).given(entityService).fetchEntity(tenantId, deviceId); + + assertThatThrownBy(() -> validator.validateDataImpl(tenantId, entityView)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Entity view is referencing to non-existent entity!"); + } + + @Test + void testValidateEntityViewWithEntityOfOtherTenant() { + EntityView entityView = newEntityView(deviceId); + TenantId otherTenantId = TenantId.fromUUID(UUID.fromString("b1d4e8a2-6c3f-4a7b-8e5d-2f9c0a1b3d47")); + willReturn(Optional.of(newDevice(otherTenantId))).given(entityService).fetchEntity(tenantId, deviceId); + + assertThatThrownBy(() -> validator.validateDataImpl(tenantId, entityView)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Can't assign entity view to entity from different tenant!"); + } + + @Test + void testValidateEntityViewWithEntityOfUnsupportedType() { + EntityView entityView = newEntityView(deviceId); + willThrow(new IllegalArgumentException("Unsupported entity type DEVICE")).given(entityService).fetchEntity(tenantId, deviceId); + + assertThatThrownBy(() -> validator.validateDataImpl(tenantId, entityView)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Entity view is referencing to non-existent entity!"); + } + + @Test + void testValidateEntityViewWithEntityWithoutTenant() { + EntityView entityView = newEntityView(deviceId); + HasId entity = () -> deviceId; + willReturn(Optional.of(entity)).given(entityService).fetchEntity(tenantId, deviceId); + + assertThatThrownBy(() -> validator.validateDataImpl(tenantId, entityView)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Can't assign entity view to entity from different tenant!"); + } + + @Test + void testValidateEntityViewWithoutEntity() { + EntityView entityView = newEntityView(null); + + assertThatThrownBy(() -> validator.validateDataImpl(tenantId, entityView)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Entity view should be assigned to entity!"); + } + + private EntityView newEntityView(DeviceId entityId) { + EntityView entityView = new EntityView(); + entityView.setName("view"); + entityView.setType("default"); + entityView.setTenantId(tenantId); + entityView.setEntityId(entityId); + return entityView; + } + + private Device newDevice(TenantId deviceTenantId) { + Device device = new Device(deviceId); + device.setTenantId(deviceTenantId); + return device; + } + } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/LegacyJsonbColumnsTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/LegacyJsonbColumnsTest.java new file mode 100644 index 0000000000..f44431d3a2 --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/LegacyJsonbColumnsTest.java @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.sql; + +import org.junit.jupiter.api.Test; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.ai.model.AiModelConfig; +import org.thingsboard.server.dao.util.mapping.AiModelConfigConverter; +import org.thingsboard.server.dao.util.mapping.IotHubInstalledItemDescriptorConverter; + +import static org.assertj.core.api.Assertions.assertThat; + +class LegacyJsonbColumnsTest { + + private static final String LEGACY_AI_MODEL_CONFIG = "{\"topP\": 0.3, \"modelId\": \"gpt-4o\", \"provider\": \"OPENAI\", \"modelType\": \"CHAT\", \"maxRetries\": 2, \"temperature\": 0.5, \"providerConfig\": {\"apiKey\": \"test-api-key\", \"baseUrl\": \"https://api.openai.com/v1\"}, \"timeoutSeconds\": 60, \"maxOutputTokens\": 1000, \"presencePenalty\": 0.2, \"frequencyPenalty\": 0.1}"; + private static final String LEGACY_IOT_HUB_DESCRIPTOR = "{\"type\": \"RULE_CHAIN\", \"ruleChainId\": {\"id\": \"4dda2206-0fd7-4c10-aea1-39535f726360\", \"entityType\": \"RULE_CHAIN\"}, \"targetProfileId\": {\"id\": \"4103fb6e-ce28-4115-a0fc-e4492ffe4d9b\", \"entityType\": \"DEVICE_PROFILE\"}}"; + + @Test + void readsLegacyAiModelConfig() { + AiModelConfigConverter converter = new AiModelConfigConverter(); + AiModelConfig config = converter.convertToEntityAttribute(LEGACY_AI_MODEL_CONFIG); + assertThat(JacksonUtil.toJsonNode(converter.convertToDatabaseColumn(config))) + .isEqualTo(JacksonUtil.toJsonNode(LEGACY_AI_MODEL_CONFIG)); + } + + @Test + void readsLegacyIotHubDescriptor() { + IotHubInstalledItemDescriptorConverter converter = new IotHubInstalledItemDescriptorConverter(); + assertThat(JacksonUtil.toJsonNode(converter.convertToDatabaseColumn(converter.convertToEntityAttribute(LEGACY_IOT_HUB_DESCRIPTOR)))) + .isEqualTo(JacksonUtil.toJsonNode(LEGACY_IOT_HUB_DESCRIPTOR)); + } + +} diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceDaoTest.java index 3265b0dc18..3672d91446 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceDaoTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao.sql.device; import com.datastax.oss.driver.api.core.uuid.Uuids; @@ -15,6 +16,7 @@ import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceProfileType; import org.thingsboard.server.common.data.DeviceTransportType; +import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.TenantId; @@ -112,6 +114,21 @@ public class JpaDeviceDaoTest extends AbstractJpaDaoTest { assertThat(device.getVersion()).isEqualTo(3); } + @Test + public void testSaveDevice_presetId_staleVersionRejected() { + Device device = getDevice(tenantId1, customerId1, "preset-id-stale"); + device = saveDevice(tenantId1, device); + deviceIds.add(device.getUuidId()); + + Device stale = new Device(device); + stale.setVersion(device.getVersion()); + device.setName(device.getName() + "x"); + saveDevice(tenantId1, device); + + stale.setName(stale.getName() + "y"); + assertThatThrownBy(() -> saveDevice(tenantId1, stale)).isInstanceOf(EntityVersionMismatchException.class); + } + @Test public void testSaveDevice_versionIncrement_noChanges() { Device device = getDevice(tenantId1, customerId1, "1ewfewf2"); diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserSettingsDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserSettingsDaoTest.java index 15204fac59..81955e5359 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserSettingsDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserSettingsDaoTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao.sql.user; import com.datastax.oss.driver.api.core.uuid.Uuids; @@ -68,8 +69,6 @@ public class JpaUserSettingsDaoTest extends AbstractJpaDaoTest { assertNull(retrievedUserSettings2); } - // If Hibernate fail to bind JSON path please check the hypersistence-utils-hibernate-XX artifact name and version in the dependency management - // Example: java.lang.ClassCastException: class [Ljava.lang.String; cannot be cast to class [B ([Ljava.lang.String; and [B are in module java.base of loader 'bootstrap') @Test public void testFindByTypeAndJsonPath() { UserSettings userSettings = createUserSettings(user.getId()); diff --git a/dao/src/test/java/org/thingsboard/server/dao/util/ImageUtilsTest.java b/dao/src/test/java/org/thingsboard/server/dao/util/ImageUtilsTest.java new file mode 100644 index 0000000000..6f29d64a48 --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/util/ImageUtilsTest.java @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.util; + +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.thingsboard.server.dao.util.ImageUtils.ProcessedImage; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mockStatic; + +class ImageUtilsTest { + + private static final byte[] SVG = "A" + .getBytes(StandardCharsets.UTF_8); + + @Test + void svgThatCannotBeRenderedForLackOfFontsKeepsTheOriginalAsPreview() throws Exception { + try (MockedStatic imageUtils = mockStatic(ImageUtils.class, CALLS_REAL_METHODS)) { + imageUtils.when(() -> ImageUtils.processSvgImage(any(), anyString(), anyInt())) + .thenThrow(new NoClassDefFoundError("Could not initialize class com.github.weisj.jsvg.attributes.font.FontResolver$FontFamiliesCache")); + + ProcessedImage image = ImageUtils.processImage(SVG, "image/svg+xml", 250); + + assertThat(image.getData()).isEqualTo(SVG); + assertThat(image.getPreview().getData()).isNull(); + assertThat(image.getMediaType()).isEqualTo("image/svg+xml"); + } + } + +} diff --git a/edqs/pom.xml b/edqs/pom.xml index 704ca7efc7..5cb4791033 100644 --- a/edqs/pom.xml +++ b/edqs/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard edqs @@ -83,6 +83,11 @@ spring-boot-starter-test test
+ + org.springframework.boot + spring-boot-persistence + test + org.junit.vintage junit-vintage-engine @@ -98,6 +103,14 @@ assertj-core test + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/edqs/src/main/resources/edqs.yml b/edqs/src/main/resources/edqs.yml index 52ccb89920..0effa4e1b2 100644 --- a/edqs/src/main/resources/edqs.yml +++ b/edqs/src/main/resources/edqs.yml @@ -1,6 +1,7 @@ # # SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +# SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 # server: @@ -8,6 +9,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8080}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" # Application info parameters app: diff --git a/edqs/src/test/java/org/thingsboard/server/edqs/repo/AbstractEDQTest.java b/edqs/src/test/java/org/thingsboard/server/edqs/repo/AbstractEDQTest.java index 1c31e9741f..cfd96dba0f 100644 --- a/edqs/src/test/java/org/thingsboard/server/edqs/repo/AbstractEDQTest.java +++ b/edqs/src/test/java/org/thingsboard/server/edqs/repo/AbstractEDQTest.java @@ -7,7 +7,7 @@ import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.persistence.autoconfigure.EntityScan; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; diff --git a/integration/apache-pulsar/pom.xml b/integration/apache-pulsar/pom.xml index 3124532310..68c29c0ad4 100644 --- a/integration/apache-pulsar/pom.xml +++ b/integration/apache-pulsar/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -42,6 +42,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/apache-pulsar/src/main/resources/tb-apache-pulsar-integration.yml b/integration/apache-pulsar/src/main/resources/tb-apache-pulsar-integration.yml index 2d259b7e33..64d23fe77b 100644 --- a/integration/apache-pulsar/src/main/resources/tb-apache-pulsar-integration.yml +++ b/integration/apache-pulsar/src/main/resources/tb-apache-pulsar-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -25,8 +28,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: # Location of the folder to store data files diff --git a/integration/aws/pom.xml b/integration/aws/pom.xml index eae85b500c..907bb0a5a3 100644 --- a/integration/aws/pom.xml +++ b/integration/aws/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -42,6 +42,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/aws/src/main/resources/tb-aws-integration.yml b/integration/aws/src/main/resources/tb-aws-integration.yml index 4e5b715d0b..d4d6a17d66 100644 --- a/integration/aws/src/main/resources/tb-aws-integration.yml +++ b/integration/aws/src/main/resources/tb-aws-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -23,8 +26,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: data_folder_path: "${INTEGRATION_STORAGE_DATA_FOLDER_PATH:./}" diff --git a/integration/azure/pom.xml b/integration/azure/pom.xml index 179359bbc0..8f50f0c2f4 100644 --- a/integration/azure/pom.xml +++ b/integration/azure/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -42,6 +42,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/azure/src/main/resources/tb-azure-integration.yml b/integration/azure/src/main/resources/tb-azure-integration.yml index 4e5b715d0b..d4d6a17d66 100644 --- a/integration/azure/src/main/resources/tb-azure-integration.yml +++ b/integration/azure/src/main/resources/tb-azure-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -23,8 +26,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: data_folder_path: "${INTEGRATION_STORAGE_DATA_FOLDER_PATH:./}" diff --git a/integration/coap/pom.xml b/integration/coap/pom.xml index 82dfd8a93c..7b3a1c14a8 100644 --- a/integration/coap/pom.xml +++ b/integration/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -42,6 +42,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/coap/src/main/resources/tb-coap-integration.yml b/integration/coap/src/main/resources/tb-coap-integration.yml index 560f20b9f7..7ddcd6fce5 100644 --- a/integration/coap/src/main/resources/tb-coap-integration.yml +++ b/integration/coap/src/main/resources/tb-coap-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -25,8 +28,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration main: allow-circular-references: "true" # Spring Boot configuration property that controls whether circular dependencies between beans are allowed. diff --git a/integration/executor/pom.xml b/integration/executor/pom.xml index 50e8a56fce..8c846481dc 100644 --- a/integration/executor/pom.xml +++ b/integration/executor/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -96,7 +96,16 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + + + org.springframework.boot + spring-boot-starter-test + test diff --git a/integration/executor/src/main/java/org/thingsboard/integration/service/api/DefaultIntegrationApiService.java b/integration/executor/src/main/java/org/thingsboard/integration/service/api/DefaultIntegrationApiService.java index 2c740fe561..6dd03d6350 100644 --- a/integration/executor/src/main/java/org/thingsboard/integration/service/api/DefaultIntegrationApiService.java +++ b/integration/executor/src/main/java/org/thingsboard/integration/service/api/DefaultIntegrationApiService.java @@ -67,6 +67,7 @@ import org.thingsboard.server.service.cache.IntegrationExecutorDeviceProfileCach import org.thingsboard.server.service.data.EntityCacheKey; import org.thingsboard.server.service.data.EntityUplinkData; +import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; @@ -148,8 +149,8 @@ public class DefaultIntegrationApiService implements IntegrationApiService { TransportProtos.SessionInfoProto sessionInfo = ProtoUtils.toSessionInfo(integration.getUuidId(), device); onActivity(device.tenantId(), new DeviceId(device.id()), integration, proto); dispatchUplink(data.hasPostTelemetryMsg(), data.hasPostAttributesMsg(), callback, - composite -> process(sessionInfo, data.getPostTelemetryMsg(), composite), - composite -> process(sessionInfo, data.getPostAttributesMsg(), composite)); + composite -> process(sessionInfo, data.getPostTelemetryMsg(), data.getTelemetryTypeCastDisabledKeysList(), composite), + composite -> process(sessionInfo, data.getPostAttributesMsg(), data.getAttributesTypeCastDisabledKeysList(), composite)); } catch (Exception e) { callback.onError(new RuntimeException("Failed to process device uplink data: " + data.getDeviceName(), e)); } @@ -180,8 +181,8 @@ public class DefaultIntegrationApiService implements IntegrationApiService { } try { dispatchUplink(data.hasPostTelemetryMsg(), data.hasPostAttributesMsg(), callback, - composite -> process(asset, data.getPostTelemetryMsg(), integration.getId(), composite), - composite -> process(asset, data.getPostAttributesMsg(), integration.getId(), composite)); + composite -> process(asset, data.getPostTelemetryMsg(), data.getTelemetryTypeCastDisabledKeysList(), integration.getId(), composite), + composite -> process(asset, data.getPostAttributesMsg(), data.getAttributesTypeCastDisabledKeysList(), integration.getId(), composite)); } catch (Exception e) { callback.onError(new RuntimeException("Failed to process asset uplink data: " + data.getAssetName(), e)); } @@ -278,42 +279,42 @@ public class DefaultIntegrationApiService implements IntegrationApiService { producer.send(tpi, new TbProtoQueueMsg<>(messageKey, msg), wrappedCallback); } - private void process(TransportProtos.SessionInfoProto sessionInfo, TransportProtos.PostTelemetryMsg msg, IntegrationCallback callback) { + private void process(TransportProtos.SessionInfoProto sessionInfo, TransportProtos.PostTelemetryMsg msg, Collection typeCastDisabledKeys, IntegrationCallback callback) { TenantId tenantId = TenantId.fromUUID(new UUID(sessionInfo.getTenantIdMSB(), sessionInfo.getTenantIdLSB())); DeviceId deviceId = new DeviceId(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB())); processTelemetry(tenantId, getCustomerId(sessionInfo), sessionInfo.getDeviceName(), sessionInfo.getDeviceType(), - DEVICE_NAME_META, DEVICE_TYPE_META, msg, + DEVICE_NAME_META, DEVICE_TYPE_META, msg, typeCastDisabledKeys, (json, metaData, msgType, cb) -> sendToRuleEngine(tenantId, deviceId, sessionInfo, json, metaData, msgType, cb), callback); } - private void process(TransportProtos.SessionInfoProto sessionInfo, TransportProtos.PostAttributeMsg msg, IntegrationCallback callback) { + private void process(TransportProtos.SessionInfoProto sessionInfo, TransportProtos.PostAttributeMsg msg, Collection typeCastDisabledKeys, IntegrationCallback callback) { TenantId tenantId = TenantId.fromUUID(new UUID(sessionInfo.getTenantIdMSB(), sessionInfo.getTenantIdLSB())); DeviceId deviceId = new DeviceId(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB())); processAttributes(tenantId, getCustomerId(sessionInfo), sessionInfo.getDeviceName(), sessionInfo.getDeviceType(), - DEVICE_NAME_META, DEVICE_TYPE_META, msg, + DEVICE_NAME_META, DEVICE_TYPE_META, msg, typeCastDisabledKeys, (json, metaData, msgType, cb) -> sendToRuleEngine(tenantId, deviceId, sessionInfo, json, metaData, msgType, cb), callback); } - private void process(AssetCacheInfo asset, TransportProtos.PostTelemetryMsg msg, IntegrationId integrationId, IntegrationCallback callback) { + private void process(AssetCacheInfo asset, TransportProtos.PostTelemetryMsg msg, Collection typeCastDisabledKeys, IntegrationId integrationId, IntegrationCallback callback) { processTelemetry(asset.tenantId(), asset.customerId(), asset.name(), asset.type(), - ASSET_NAME_META, ASSET_TYPE_META, msg, + ASSET_NAME_META, ASSET_TYPE_META, msg, typeCastDisabledKeys, (json, metaData, msgType, cb) -> sendToRuleEngine(asset.tenantId(), new AssetId(asset.id()), asset.type(), asset.assetProfileId(), asset.customerId(), json, metaData, msgType, integrationId, cb), callback); } - private void process(AssetCacheInfo asset, TransportProtos.PostAttributeMsg msg, IntegrationId integrationId, IntegrationCallback callback) { + private void process(AssetCacheInfo asset, TransportProtos.PostAttributeMsg msg, Collection typeCastDisabledKeys, IntegrationId integrationId, IntegrationCallback callback) { processAttributes(asset.tenantId(), asset.customerId(), asset.name(), asset.type(), - ASSET_NAME_META, ASSET_TYPE_META, msg, + ASSET_NAME_META, ASSET_TYPE_META, msg, typeCastDisabledKeys, (json, metaData, msgType, cb) -> sendToRuleEngine(asset.tenantId(), new AssetId(asset.id()), asset.type(), asset.assetProfileId(), asset.customerId(), json, metaData, msgType, integrationId, cb), callback); } private void processTelemetry(TenantId tenantId, CustomerId customerId, String entityName, String entityType, - String nameMetaKey, String typeMetaKey, TransportProtos.PostTelemetryMsg msg, + String nameMetaKey, String typeMetaKey, TransportProtos.PostTelemetryMsg msg, Collection typeCastDisabledKeys, TbMsgSender sender, IntegrationCallback callback) { if (msg.getTsKvListCount() == 0) { callback.onSuccess(null); @@ -330,17 +331,19 @@ public class DefaultIntegrationApiService implements IntegrationApiService { metaData.putValue(nameMetaKey, entityName); metaData.putValue(typeMetaKey, entityType); metaData.putValue(TS_META, tsKv.getTs() + ""); + metaData.putTypeCastDisabledKeys(typeCastDisabledKeys); JsonObject json = JsonUtils.getJsonObject(tsKv.getKvList()); sender.send(json, metaData, TbMsgType.POST_TELEMETRY_REQUEST, packCallback); } } private void processAttributes(TenantId tenantId, CustomerId customerId, String entityName, String entityType, String nameMetaKey, String typeMetaKey, - TransportProtos.PostAttributeMsg msg, TbMsgSender sender, IntegrationCallback callback) { + TransportProtos.PostAttributeMsg msg, Collection typeCastDisabledKeys, TbMsgSender sender, IntegrationCallback callback) { JsonObject json = JsonUtils.getJsonObject(msg.getKvList()); TbMsgMetaData metaData = new TbMsgMetaData(); metaData.putValue(nameMetaKey, entityName); metaData.putValue(typeMetaKey, entityType); + metaData.putTypeCastDisabledKeys(typeCastDisabledKeys); sender.send(json, metaData, TbMsgType.POST_ATTRIBUTES_REQUEST, new MsgPackCallback(1, new ApiStatsProxyCallback<>(tenantId, customerId, msg.getKvList().size(), callback))); } diff --git a/integration/executor/src/main/resources/tb-integration-executor.yml b/integration/executor/src/main/resources/tb-integration-executor.yml index 0e7978f9b1..fad781696b 100644 --- a/integration/executor/src/main/resources/tb-integration-executor.yml +++ b/integration/executor/src/main/resources/tb-integration-executor.yml @@ -13,6 +13,8 @@ server: tomcat: # Maximum size of data that could be sent over HTTP form POST request max-http-form-post-size: "${MAX_HTTP_FORM_POST_SIZE:10000000}" # 10Mb + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" # Spring common parameters # Controls Spring Boot circular reference handling and multipart file upload size limits. @@ -332,7 +334,7 @@ queue: pause-between-retries: "${TB_QUEUE_RE_SQ_PROCESSING_STRATEGY_RETRY_PAUSE:5}" # Time in seconds to wait in consumer thread before retries; max-pause-between-retries: "${TB_QUEUE_RE_SQ_PROCESSING_STRATEGY_MAX_RETRY_PAUSE:5}" # Max allowed time in seconds for pause between retries. integration: - # Name of hash function used for consistent hash ring in Cluster Mode. See architecture docs for more details. Valid values - murmur3_32, murmur3_128 or sha256 + # Number of partitions in each integration queue; there is one queue per integration type. Integrations that run on only one executor at a time (MQTT, OPC-UA, Kafka and similar) are distributed across executors by partition, so executors above this number stay idle for those types. When you add executors, set it to at least the number of executors that run the same integration types, and use the same value on the ThingsBoard nodes. partitions: "${TB_QUEUE_INTEGRATION_PARTITIONS:3}" # For high-priority notifications that require minimum latency and processing time notifications_topic: "${TB_QUEUE_INTEGRATION_NOTIFICATIONS_TOPIC:tb_integration_executor.notifications}" diff --git a/integration/executor/src/test/java/org/thingsboard/integration/service/api/DefaultIntegrationApiServiceTest.java b/integration/executor/src/test/java/org/thingsboard/integration/service/api/DefaultIntegrationApiServiceTest.java new file mode 100644 index 0000000000..839ff101fb --- /dev/null +++ b/integration/executor/src/test/java/org/thingsboard/integration/service/api/DefaultIntegrationApiServiceTest.java @@ -0,0 +1,219 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.integration.service.api; + +import com.google.common.util.concurrent.Futures; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.integration.api.IntegrationCallback; +import org.thingsboard.server.common.data.AssetCacheInfo; +import org.thingsboard.server.common.data.AssetProfileCacheInfo; +import org.thingsboard.server.common.data.DeviceCacheInfo; +import org.thingsboard.server.common.data.DeviceProfileCacheInfo; +import org.thingsboard.server.common.data.id.AssetProfileId; +import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.IntegrationId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.integration.Integration; +import org.thingsboard.server.common.data.msg.TbMsgType; +import org.thingsboard.server.common.msg.TbMsg; +import org.thingsboard.server.common.msg.TbMsgMetaData; +import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; +import org.thingsboard.server.common.stats.MessagesStats; +import org.thingsboard.server.common.stats.StatsFactory; +import org.thingsboard.server.common.stats.TbApiUsageReportClient; +import org.thingsboard.server.gen.integration.AssetUplinkDataProto; +import org.thingsboard.server.gen.integration.DeviceUplinkDataProto; +import org.thingsboard.server.gen.integration.IntegrationApiRequestMsg; +import org.thingsboard.server.gen.integration.IntegrationApiResponseMsg; +import org.thingsboard.server.gen.integration.IntegrationInfoProto; +import org.thingsboard.server.gen.integration.ToCoreIntegrationMsg; +import org.thingsboard.server.gen.transport.TransportProtos.KeyValueProto; +import org.thingsboard.server.gen.transport.TransportProtos.KeyValueType; +import org.thingsboard.server.gen.transport.TransportProtos.PostAttributeMsg; +import org.thingsboard.server.gen.transport.TransportProtos.PostTelemetryMsg; +import org.thingsboard.server.gen.transport.TransportProtos.ToRuleEngineMsg; +import org.thingsboard.server.gen.transport.TransportProtos.TsKvListProto; +import org.thingsboard.server.queue.TbQueueCallback; +import org.thingsboard.server.queue.TbQueueProducer; +import org.thingsboard.server.queue.TbQueueRequestTemplate; +import org.thingsboard.server.queue.common.TbProtoQueueMsg; +import org.thingsboard.server.queue.common.TbRuleEngineProducerService; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.provider.TbQueueProducerProvider; +import org.thingsboard.server.service.cache.IntegrationExecutorAssetCache; +import org.thingsboard.server.service.cache.IntegrationExecutorAssetProfileCache; +import org.thingsboard.server.service.cache.IntegrationExecutorDeviceCache; +import org.thingsboard.server.service.cache.IntegrationExecutorDeviceProfileCache; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class DefaultIntegrationApiServiceTest { + + private static final long TIMEOUT_MS = 5000; + + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + private final Integration integration = new Integration(new IntegrationId(UUID.randomUUID())); + + private TbRuleEngineProducerService ruleEngineProducerService; + private IntegrationExecutorDeviceProfileCache deviceProfileCache; + private IntegrationExecutorAssetProfileCache assetProfileCache; + private IntegrationExecutorDeviceCache deviceCache; + private IntegrationExecutorAssetCache assetCache; + private DefaultIntegrationApiService service; + + @BeforeEach + @SuppressWarnings("unchecked") + public void setUp() { + integration.setTenantId(tenantId); + + StatsFactory statsFactory = mock(StatsFactory.class); + when(statsFactory.createMessagesStats(any())).thenReturn(mock(MessagesStats.class)); + PartitionService partitionService = mock(PartitionService.class); + when(partitionService.resolve(any(), any(TenantId.class), any())).thenReturn(new TopicPartitionInfo("tb_core", tenantId, 0, true)); + TbQueueProducerProvider producerProvider = mock(TbQueueProducerProvider.class); + TbQueueProducer> coreProducer = mock(TbQueueProducer.class); + when(producerProvider.getTbCoreIntegrationMsgProducer()).thenReturn(coreProducer); + when(producerProvider.getRuleEngineMsgProducer()).thenReturn(mock(TbQueueProducer.class)); + + ruleEngineProducerService = mock(TbRuleEngineProducerService.class); + doAnswer(invocation -> { + TbQueueCallback callback = invocation.getArgument(3); + callback.onSuccess(null); + return null; + }).when(ruleEngineProducerService).sendToRuleEngine(any(), any(), any(), any()); + + deviceProfileCache = mock(IntegrationExecutorDeviceProfileCache.class); + assetProfileCache = mock(IntegrationExecutorAssetProfileCache.class); + deviceCache = mock(IntegrationExecutorDeviceCache.class); + assetCache = mock(IntegrationExecutorAssetCache.class); + + service = new DefaultIntegrationApiService(statsFactory, partitionService, producerProvider, ruleEngineProducerService, + mock(TbApiUsageReportClient.class), deviceProfileCache, assetProfileCache, deviceCache, assetCache, + (TbQueueRequestTemplate, TbProtoQueueMsg>) mock(TbQueueRequestTemplate.class)); + ReflectionTestUtils.setField(service, "maxCallbackThreads", 1); + service.init(); + } + + @AfterEach + public void tearDown() { + service.destroy(); + } + + @Test + public void deviceUplinkPassesTelemetryAndAttributeTypeCastDisabledKeysToTheirOwnMessages() { + DeviceProfileId deviceProfileId = new DeviceProfileId(UUID.randomUUID()); + when(deviceCache.getEntity(any(), any())).thenReturn(Futures.immediateFuture( + new DeviceCacheInfo(UUID.randomUUID(), tenantId, null, "Device A", "default", deviceProfileId))); + when(deviceProfileCache.getProfile(eq(deviceProfileId.getId()), any())).thenReturn(Futures.immediateFuture( + new DeviceProfileCacheInfo(deviceProfileId.getId(), tenantId, "default", null, "Main"))); + + DeviceUplinkDataProto data = DeviceUplinkDataProto.newBuilder() + .setDeviceName("Device A") + .setDeviceType("default") + .setPostTelemetryMsg(telemetry()) + .setPostAttributesMsg(attributes()) + .addAllTelemetryTypeCastDisabledKeys(List.of("devAddr")) + .addAllAttributesTypeCastDisabledKeys(List.of("joinEui", "firmwareVersion")) + .build(); + IntegrationCallback callback = mock(IntegrationCallback.class); + + service.sendUplinkData(integration, IntegrationInfoProto.getDefaultInstance(), data, callback); + + Map msgs = captureRuleEngineMsgs(); + assertThat(msgs.get(TbMsgType.POST_TELEMETRY_REQUEST).getTypeCastDisabledKeys()).isEqualTo(Set.of("devAddr")); + assertThat(msgs.get(TbMsgType.POST_ATTRIBUTES_REQUEST).getTypeCastDisabledKeys()).isEqualTo(Set.of("joinEui", "firmwareVersion")); + verify(callback, timeout(TIMEOUT_MS)).onSuccess(null); + } + + @Test + public void assetUplinkPassesTelemetryAndAttributeTypeCastDisabledKeysToTheirOwnMessages() { + AssetProfileId assetProfileId = new AssetProfileId(UUID.randomUUID()); + when(assetCache.getEntity(any(), any())).thenReturn(Futures.immediateFuture( + new AssetCacheInfo(UUID.randomUUID(), tenantId, null, "Asset A", "default", assetProfileId))); + when(assetProfileCache.getProfile(eq(assetProfileId.getId()), any())).thenReturn(Futures.immediateFuture( + new AssetProfileCacheInfo(assetProfileId.getId(), tenantId, "default", null, "Main"))); + + AssetUplinkDataProto data = AssetUplinkDataProto.newBuilder() + .setAssetName("Asset A") + .setAssetType("default") + .setPostTelemetryMsg(telemetry()) + .setPostAttributesMsg(attributes()) + .addAllTelemetryTypeCastDisabledKeys(List.of("devAddr")) + .addAllAttributesTypeCastDisabledKeys(List.of("joinEui", "firmwareVersion")) + .build(); + IntegrationCallback callback = mock(IntegrationCallback.class); + + service.sendUplinkData(integration, IntegrationInfoProto.getDefaultInstance(), data, callback); + + Map msgs = captureRuleEngineMsgs(); + assertThat(msgs.get(TbMsgType.POST_TELEMETRY_REQUEST).getTypeCastDisabledKeys()).isEqualTo(Set.of("devAddr")); + assertThat(msgs.get(TbMsgType.POST_ATTRIBUTES_REQUEST).getTypeCastDisabledKeys()).isEqualTo(Set.of("joinEui", "firmwareVersion")); + verify(callback, timeout(TIMEOUT_MS)).onSuccess(null); + } + + @Test + public void uplinkWithoutTypeCastDisabledKeysAddsNoMetadata() { + DeviceProfileId deviceProfileId = new DeviceProfileId(UUID.randomUUID()); + when(deviceCache.getEntity(any(), any())).thenReturn(Futures.immediateFuture( + new DeviceCacheInfo(UUID.randomUUID(), tenantId, null, "Device B", "default", deviceProfileId))); + when(deviceProfileCache.getProfile(eq(deviceProfileId.getId()), any())).thenReturn(Futures.immediateFuture( + new DeviceProfileCacheInfo(deviceProfileId.getId(), tenantId, "default", null, "Main"))); + + DeviceUplinkDataProto data = DeviceUplinkDataProto.newBuilder() + .setDeviceName("Device B") + .setDeviceType("default") + .setPostTelemetryMsg(telemetry()) + .setPostAttributesMsg(attributes()) + .build(); + + service.sendUplinkData(integration, IntegrationInfoProto.getDefaultInstance(), data, mock(IntegrationCallback.class)); + + Map msgs = captureRuleEngineMsgs(); + assertThat(msgs.get(TbMsgType.POST_TELEMETRY_REQUEST).getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isNull(); + assertThat(msgs.get(TbMsgType.POST_ATTRIBUTES_REQUEST).getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isNull(); + } + + private Map captureRuleEngineMsgs() { + ArgumentCaptor captor = ArgumentCaptor.forClass(TbMsg.class); + verify(ruleEngineProducerService, timeout(TIMEOUT_MS).times(2)).sendToRuleEngine(any(), eq(tenantId), captor.capture(), any()); + return captor.getAllValues().stream().collect(Collectors.toMap(TbMsg::getInternalType, Function.identity())); + } + + private static PostTelemetryMsg telemetry() { + return PostTelemetryMsg.newBuilder() + .addTsKvList(TsKvListProto.newBuilder() + .setTs(1000L) + .addKv(stringKv("devAddr", "01020304"))) + .build(); + } + + private static PostAttributeMsg attributes() { + return PostAttributeMsg.newBuilder() + .addKv(stringKv("joinEui", "0000000000000000")) + .addKv(stringKv("firmwareVersion", "1.0")) + .build(); + } + + private static KeyValueProto stringKv(String key, String value) { + return KeyValueProto.newBuilder().setKey(key).setType(KeyValueType.STRING_V).setStringV(value).build(); + } + +} diff --git a/integration/http/pom.xml b/integration/http/pom.xml index 5bc82f903d..4879370975 100644 --- a/integration/http/pom.xml +++ b/integration/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -43,6 +43,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/http/src/main/resources/tb-http-integration.yml b/integration/http/src/main/resources/tb-http-integration.yml index 1ee6dcdab0..682870d675 100644 --- a/integration/http/src/main/resources/tb-http-integration.yml +++ b/integration/http/src/main/resources/tb-http-integration.yml @@ -11,6 +11,8 @@ server: tomcat: # Maximum size of data that could be sent over HTTP form POST request max-http-form-post-size: "${MAX_HTTP_FORM_POST_SIZE:10000000}" # 10Mb + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -31,8 +33,8 @@ spring.mvc.async.request-timeout: "${SPRING_MVC_ASYNC_REQUEST_TIMEOUT:30000}" spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: # Location of the folder to store data files diff --git a/integration/kafka/pom.xml b/integration/kafka/pom.xml index aa56ecf747..b746be4460 100644 --- a/integration/kafka/pom.xml +++ b/integration/kafka/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -42,6 +42,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/kafka/src/main/resources/tb-kafka-integration.yml b/integration/kafka/src/main/resources/tb-kafka-integration.yml index 56140b4b3d..f89fc2428b 100644 --- a/integration/kafka/src/main/resources/tb-kafka-integration.yml +++ b/integration/kafka/src/main/resources/tb-kafka-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -25,8 +28,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: # Location of the folder to store data files diff --git a/integration/mqtt/pom.xml b/integration/mqtt/pom.xml index 83e180e2fa..e4db54d60e 100644 --- a/integration/mqtt/pom.xml +++ b/integration/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -42,6 +42,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/mqtt/src/main/resources/tb-mqtt-integration.yml b/integration/mqtt/src/main/resources/tb-mqtt-integration.yml index 50fcced5ab..7bf1643339 100644 --- a/integration/mqtt/src/main/resources/tb-mqtt-integration.yml +++ b/integration/mqtt/src/main/resources/tb-mqtt-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -23,8 +26,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: data_folder_path: "${INTEGRATION_STORAGE_DATA_FOLDER_PATH:./}" diff --git a/integration/opc-ua/pom.xml b/integration/opc-ua/pom.xml index 4c49affe2f..6767a9e531 100644 --- a/integration/opc-ua/pom.xml +++ b/integration/opc-ua/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -42,6 +42,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/opc-ua/src/main/resources/tb-opc-ua-integration.yml b/integration/opc-ua/src/main/resources/tb-opc-ua-integration.yml index 4e5b715d0b..d4d6a17d66 100644 --- a/integration/opc-ua/src/main/resources/tb-opc-ua-integration.yml +++ b/integration/opc-ua/src/main/resources/tb-opc-ua-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -23,8 +26,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: data_folder_path: "${INTEGRATION_STORAGE_DATA_FOLDER_PATH:./}" diff --git a/integration/pom.xml b/integration/pom.xml index e4df184899..d640754f6a 100644 --- a/integration/pom.xml +++ b/integration/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard integration diff --git a/integration/pubsub/pom.xml b/integration/pubsub/pom.xml index f087359e49..42409d0aef 100644 --- a/integration/pubsub/pom.xml +++ b/integration/pubsub/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -42,6 +42,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/pubsub/src/main/resources/tb-pubsub-integration.yml b/integration/pubsub/src/main/resources/tb-pubsub-integration.yml index 56140b4b3d..f89fc2428b 100644 --- a/integration/pubsub/src/main/resources/tb-pubsub-integration.yml +++ b/integration/pubsub/src/main/resources/tb-pubsub-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -25,8 +28,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: # Location of the folder to store data files diff --git a/integration/rabbitmq/pom.xml b/integration/rabbitmq/pom.xml index 0db3ccdaad..d640a35eca 100644 --- a/integration/rabbitmq/pom.xml +++ b/integration/rabbitmq/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -42,6 +42,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/rabbitmq/src/main/resources/tb-rabbitmq-integration.yml b/integration/rabbitmq/src/main/resources/tb-rabbitmq-integration.yml index 56140b4b3d..f89fc2428b 100644 --- a/integration/rabbitmq/src/main/resources/tb-rabbitmq-integration.yml +++ b/integration/rabbitmq/src/main/resources/tb-rabbitmq-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -25,8 +28,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: # Location of the folder to store data files diff --git a/integration/tcp-udp/pom.xml b/integration/tcp-udp/pom.xml index ce13d16b3a..57991fea99 100644 --- a/integration/tcp-udp/pom.xml +++ b/integration/tcp-udp/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -46,6 +46,14 @@ com.github.ben-manes.caffeine caffeine + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/tcp-udp/src/main/resources/tb-tcp-udp-integration.yml b/integration/tcp-udp/src/main/resources/tb-tcp-udp-integration.yml index 71b0634c0e..f8f55ab190 100644 --- a/integration/tcp-udp/src/main/resources/tb-tcp-udp-integration.yml +++ b/integration/tcp-udp/src/main/resources/tb-tcp-udp-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -23,8 +26,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: data_folder_path: "${INTEGRATION_STORAGE_DATA_FOLDER_PATH:./}" diff --git a/integration/tuya/pom.xml b/integration/tuya/pom.xml index 8e325d9c36..3025160688 100644 --- a/integration/tuya/pom.xml +++ b/integration/tuya/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration @@ -42,6 +42,14 @@ org.thingsboard.common.integration remote-integration-api + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/integration/tuya/src/main/resources/tb-tuya-integration.yml b/integration/tuya/src/main/resources/tb-tuya-integration.yml index 56140b4b3d..f89fc2428b 100644 --- a/integration/tuya/src/main/resources/tb-tuya-integration.yml +++ b/integration/tuya/src/main/resources/tb-tuya-integration.yml @@ -8,6 +8,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8082}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" integration: routingKey: "${INTEGRATION_ROUTING_KEY:PUT_YOUR_ROUTING_KEY_HERE}" @@ -25,8 +28,8 @@ integration: spring: autoconfigure: exclude: - - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration + - org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration storage: # Location of the folder to store data files diff --git a/migrator/pom.xml b/migrator/pom.xml index e0141d2d0d..18331c84a6 100644 --- a/migrator/pom.xml +++ b/migrator/pom.xml @@ -12,7 +12,7 @@ thingsboard org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT migrator @@ -83,17 +83,12 @@ org.testcontainers - postgresql + testcontainers-postgresql test org.testcontainers - junit-jupiter - test - - - software.xdev - testcontainers-junit4-mock + testcontainers-junit-jupiter test diff --git a/migrator/src/main/java/org/thingsboard/migrator/config/CassandraConfig.java b/migrator/src/main/java/org/thingsboard/migrator/config/CassandraConfig.java index fa0709f99d..e09d1005a1 100644 --- a/migrator/src/main/java/org/thingsboard/migrator/config/CassandraConfig.java +++ b/migrator/src/main/java/org/thingsboard/migrator/config/CassandraConfig.java @@ -3,16 +3,16 @@ package org.thingsboard.migrator.config; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration; +import org.springframework.boot.cassandra.autoconfigure.CassandraAutoConfiguration; +import org.springframework.boot.data.cassandra.autoconfigure.DataCassandraAutoConfiguration; import org.springframework.context.annotation.Configuration; /** * Disables Cassandra autoconfiguration if Cassandra export/import is disabled * */ @Configuration -@EnableAutoConfiguration(exclude = {CassandraDataAutoConfiguration.class, CassandraAutoConfiguration.class}) +@EnableAutoConfiguration(exclude = {DataCassandraAutoConfiguration.class, CassandraAutoConfiguration.class}) @ConditionalOnExpression("('${mode}' == 'TENANT_DATA_EXPORT' && ${export.cassandra.enabled} == false) || ('${mode}' == 'TENANT_DATA_IMPORT' and ${import.cassandra.enabled} == false) || ('${mode}' == 'CASSANDRA_LATEST_KV_EXPORT')") public class CassandraConfig { } diff --git a/migrator/src/main/java/org/thingsboard/migrator/utils/CassandraService.java b/migrator/src/main/java/org/thingsboard/migrator/utils/CassandraService.java index de678acd6d..a7493376ee 100644 --- a/migrator/src/main/java/org/thingsboard/migrator/utils/CassandraService.java +++ b/migrator/src/main/java/org/thingsboard/migrator/utils/CassandraService.java @@ -13,11 +13,11 @@ import org.springframework.dao.RecoverableDataAccessException; import org.springframework.dao.TransientDataAccessException; import org.springframework.data.cassandra.core.CassandraTemplate; import org.springframework.data.cassandra.core.cql.ArgumentPreparedStatementBinder; -import org.springframework.data.cassandra.core.cql.CachedPreparedStatementCreator; import org.springframework.data.cassandra.core.cql.CqlOperations; import org.springframework.data.cassandra.core.cql.ResultSetExtractor; import org.springframework.data.cassandra.core.cql.RowMapper; import org.springframework.data.cassandra.core.cql.RowMapperResultSetExtractor; +import org.springframework.data.cassandra.core.cql.SimplePreparedStatementCreator; import org.springframework.data.cassandra.core.cql.SingleColumnRowMapper; import org.springframework.stereotype.Service; @@ -69,7 +69,6 @@ public class CassandraService { return query(query, new RowMapperResultSetExtractor<>(rowMapper), args); } - @SuppressWarnings("deprecation") private T query(String query, ResultSetExtractor resultSetExtractor, Object... args) { int attempt = 0; while (true) { @@ -79,7 +78,7 @@ public class CassandraService { } boolean success = false; try { - T result = cqlOperations.query(new CachedPreparedStatementCreator(query), new ArgumentPreparedStatementBinder(args), resultSetExtractor); + T result = cqlOperations.query(new SimplePreparedStatementCreator(query), new ArgumentPreparedStatementBinder(args), resultSetExtractor); success = true; return result; } finally { diff --git a/monitoring/pom.xml b/monitoring/pom.xml index 45fde8874c..6c264b22b6 100644 --- a/monitoring/pom.xml +++ b/monitoring/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard @@ -51,6 +51,14 @@ org.springframework.boot spring-boot-starter + + org.springframework.boot + spring-boot-restclient + + + org.springframework.boot + spring-boot-jackson2 + org.eclipse.californium diff --git a/monitoring/src/main/java/org/thingsboard/monitoring/client/TbClient.java b/monitoring/src/main/java/org/thingsboard/monitoring/client/TbClient.java index cd9fac70e5..c92c8ba598 100644 --- a/monitoring/src/main/java/org/thingsboard/monitoring/client/TbClient.java +++ b/monitoring/src/main/java/org/thingsboard/monitoring/client/TbClient.java @@ -1,10 +1,11 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.monitoring.client; import jakarta.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.stereotype.Component; import org.thingsboard.rest.client.RestClient; diff --git a/monitoring/src/main/java/org/thingsboard/monitoring/notification/channels/impl/SlackNotificationChannel.java b/monitoring/src/main/java/org/thingsboard/monitoring/notification/channels/impl/SlackNotificationChannel.java index 22a6c64c11..eeab6b7313 100644 --- a/monitoring/src/main/java/org/thingsboard/monitoring/notification/channels/impl/SlackNotificationChannel.java +++ b/monitoring/src/main/java/org/thingsboard/monitoring/notification/channels/impl/SlackNotificationChannel.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.monitoring.notification.channels.impl; import jakarta.annotation.PostConstruct; @@ -7,7 +8,7 @@ import jakarta.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.thingsboard.monitoring.data.notification.Notification; diff --git a/monitoring/src/main/java/org/thingsboard/monitoring/service/integration/impl/HttpIntegrationHealthChecker.java b/monitoring/src/main/java/org/thingsboard/monitoring/service/integration/impl/HttpIntegrationHealthChecker.java index 8e4a2c333d..122645229f 100644 --- a/monitoring/src/main/java/org/thingsboard/monitoring/service/integration/impl/HttpIntegrationHealthChecker.java +++ b/monitoring/src/main/java/org/thingsboard/monitoring/service/integration/impl/HttpIntegrationHealthChecker.java @@ -4,7 +4,7 @@ package org.thingsboard.monitoring.service.integration.impl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; diff --git a/monitoring/src/main/java/org/thingsboard/monitoring/service/transport/impl/HttpTransportHealthChecker.java b/monitoring/src/main/java/org/thingsboard/monitoring/service/transport/impl/HttpTransportHealthChecker.java index 5c5e80ef38..ade7b26f35 100644 --- a/monitoring/src/main/java/org/thingsboard/monitoring/service/transport/impl/HttpTransportHealthChecker.java +++ b/monitoring/src/main/java/org/thingsboard/monitoring/service/transport/impl/HttpTransportHealthChecker.java @@ -1,10 +1,11 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.monitoring.service.transport.impl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; diff --git a/msa/black-box-tests/pom.xml b/msa/black-box-tests/pom.xml index 727e6757d6..d5489e1214 100644 --- a/msa/black-box-tests/pom.xml +++ b/msa/black-box-tests/pom.xml @@ -11,7 +11,7 @@ org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -37,11 +37,6 @@ testcontainers test - - software.xdev - testcontainers-junit4-mock - test - com.microsoft.azure.sdk.iot iot-service-client diff --git a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ContainerTestSuite.java b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ContainerTestSuite.java index c4127f775f..465fb282f8 100644 --- a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ContainerTestSuite.java +++ b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ContainerTestSuite.java @@ -148,7 +148,6 @@ public class ContainerTestSuite { testContainer = new DockerComposeContainerImpl(targetDir, composeFiles) .withPull(false) - .withLocalCompose(true) .withOptions("--compatibility") .withTailChildContainers(!skipTailChildContainers) .withEnv(installTb.getEnv()) diff --git a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/cf/CalculatedFieldCurrentOwnerTest.java b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/cf/CalculatedFieldCurrentOwnerTest.java index 78db4a8307..163b33c1a4 100644 --- a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/cf/CalculatedFieldCurrentOwnerTest.java +++ b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/cf/CalculatedFieldCurrentOwnerTest.java @@ -3,7 +3,7 @@ package org.thingsboard.server.msa.cf; import com.fasterxml.jackson.databind.JsonNode; -import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.RandomStringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; diff --git a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ui/base/AbstractDriverBaseTest.java b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ui/base/AbstractDriverBaseTest.java index 457fae5619..61b06f8980 100644 --- a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ui/base/AbstractDriverBaseTest.java +++ b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ui/base/AbstractDriverBaseTest.java @@ -15,7 +15,6 @@ import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; -import org.openqa.selenium.html5.WebStorage; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; @@ -70,7 +69,6 @@ abstract public class AbstractDriverBaseTest extends AbstractContainerTest { private JavascriptExecutor js; public static final long WAIT_TIMEOUT = TimeUnit.SECONDS.toMillis(10); private final Duration duration = Duration.ofMillis(WAIT_TIMEOUT); - private WebStorage webStorage; @BeforeClass public void startUp() throws MalformedURLException { diff --git a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ui/tests/customerSmoke/SearchCustomerGroupTest.java b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ui/tests/customerSmoke/SearchCustomerGroupTest.java index c6691e5798..afe3e63920 100644 --- a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ui/tests/customerSmoke/SearchCustomerGroupTest.java +++ b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ui/tests/customerSmoke/SearchCustomerGroupTest.java @@ -5,7 +5,7 @@ package org.thingsboard.server.msa.ui.tests.customerSmoke; import io.qameta.allure.Description; import io.qameta.allure.Epic; import io.qameta.allure.Feature; -import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.RandomStringUtils; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; diff --git a/msa/edqs/pom.xml b/msa/edqs/pom.xml index 807df3b0b8..25f611e29c 100644 --- a/msa/edqs/pom.xml +++ b/msa/edqs/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/apache-pulsar/pom.xml b/msa/integration/apache-pulsar/pom.xml index 7dbe26541c..b307f62da3 100644 --- a/msa/integration/apache-pulsar/pom.xml +++ b/msa/integration/apache-pulsar/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/aws/pom.xml b/msa/integration/aws/pom.xml index 8b58f4737e..b78e4cd1e5 100644 --- a/msa/integration/aws/pom.xml +++ b/msa/integration/aws/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/azure/pom.xml b/msa/integration/azure/pom.xml index ea12b52480..417711a02a 100644 --- a/msa/integration/azure/pom.xml +++ b/msa/integration/azure/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/coap/pom.xml b/msa/integration/coap/pom.xml index 1739f56dad..f655762c9a 100644 --- a/msa/integration/coap/pom.xml +++ b/msa/integration/coap/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/executor/pom.xml b/msa/integration/executor/pom.xml index 35b2788aab..875a29157c 100644 --- a/msa/integration/executor/pom.xml +++ b/msa/integration/executor/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/http/pom.xml b/msa/integration/http/pom.xml index 2d65ebbc76..4ac57bf9f2 100644 --- a/msa/integration/http/pom.xml +++ b/msa/integration/http/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/kafka/pom.xml b/msa/integration/kafka/pom.xml index f6d69ddd3b..e994e7bdc9 100644 --- a/msa/integration/kafka/pom.xml +++ b/msa/integration/kafka/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/mqtt/pom.xml b/msa/integration/mqtt/pom.xml index 888396d188..4004336f8c 100644 --- a/msa/integration/mqtt/pom.xml +++ b/msa/integration/mqtt/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/opc-ua/pom.xml b/msa/integration/opc-ua/pom.xml index 1389e7395d..8caf5e9c20 100644 --- a/msa/integration/opc-ua/pom.xml +++ b/msa/integration/opc-ua/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/pom.xml b/msa/integration/pom.xml index 4feae93369..cc9e6f925e 100644 --- a/msa/integration/pom.xml +++ b/msa/integration/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa @@ -54,7 +54,7 @@ ${docker.push-integration-arm-amd-image.phase} - latest,${project.version} + latest,${docker.version.tag} @@ -96,7 +96,7 @@ buildx build -t - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} --platform=linux/amd64,linux/arm64 -o type=registry @@ -117,11 +117,11 @@ - 4.4.1-latest + 4.4.2-latest false ${docker.push-integration-arm-amd-image.phase} - ${sbom.image.latestTag},${project.version},${docker.lts.tag} + ${sbom.image.latestTag},${docker.version.tag},${docker.lts.tag} @@ -164,7 +164,7 @@ buildx build -t - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} --platform=linux/amd64,linux/arm64 -o type=registry diff --git a/msa/integration/pubsub/pom.xml b/msa/integration/pubsub/pom.xml index e00259414f..7d54cc91a6 100644 --- a/msa/integration/pubsub/pom.xml +++ b/msa/integration/pubsub/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/rabbitmq/pom.xml b/msa/integration/rabbitmq/pom.xml index c16bfb0ccd..f4735e59ce 100644 --- a/msa/integration/rabbitmq/pom.xml +++ b/msa/integration/rabbitmq/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/tcp-udp/pom.xml b/msa/integration/tcp-udp/pom.xml index 2ee453c6c4..5123237814 100644 --- a/msa/integration/tcp-udp/pom.xml +++ b/msa/integration/tcp-udp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/tuya/pom.xml b/msa/integration/tuya/pom.xml index 831cadc812..a37d7c5358 100644 --- a/msa/integration/tuya/pom.xml +++ b/msa/integration/tuya/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/js-executor/docker/Dockerfile b/msa/js-executor/docker/Dockerfile index 7e5687f01c..37988c7947 100644 --- a/msa/js-executor/docker/Dockerfile +++ b/msa/js-executor/docker/Dockerfile @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # -FROM thingsboard/node:22.23.4-bookworm-slim +FROM thingsboard/node:22.23.5-bookworm-slim ENV NODE_ENV production ENV DOCKER_MODE true diff --git a/msa/js-executor/package.json b/msa/js-executor/package.json index c9ddd554a5..e5adac41b9 100644 --- a/msa/js-executor/package.json +++ b/msa/js-executor/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-js-executor", "private": true, - "version": "4.4.1", + "version": "4.4.2", "description": "ThingsBoard JavaScript Executor Microservice", "main": "server.ts", "bin": "server.js", @@ -49,5 +49,8 @@ "node_modules/config/**/*.*", "node_modules/@antoniomuso/lz4-napi-*/**/*.node" ] + }, + "resolutions": { + "@yao-pkg/pkg/tar": "^8.0.5" } } diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index 687d7fbc25..79ef36ab88 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -92,7 +92,7 @@ install-node-and-yarn - v22.23.4 + v22.23.5 v1.22.22 @@ -221,7 +221,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -332,7 +332,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/js-executor/yarn.lock b/msa/js-executor/yarn.lock index 3c195e8c38..36290f0732 100644 --- a/msa/js-executor/yarn.lock +++ b/msa/js-executor/yarn.lock @@ -365,13 +365,6 @@ "@hapi/bourne" "^3.0.0" "@hapi/hoek" "^11.0.2" -"@isaacs/fs-minipass@^4.0.0": - version "4.0.1" - resolved "https://registry.yarnpkg.com/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz#2d59ae3ab4b38fb4270bfa23d30f8e2e86c7fe32" - integrity sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w== - dependencies: - minipass "^7.0.4" - "@jridgewell/gen-mapping@^0.3.12": version "0.3.13" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz#6342a19f44347518c93e43b1ac69deb3c4656a1f" @@ -772,11 +765,6 @@ chownr@^1.1.1: resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" integrity sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg== -chownr@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" - integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== - cliui@^7.0.2: version "7.0.4" resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" @@ -1403,18 +1391,6 @@ minimist@^1.2.0, minimist@^1.2.3: resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== -minipass@^7.0.4, minipass@^7.1.2: - version "7.1.3" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.3.tgz#79389b4eb1bb2d003a9bba87d492f2bd37bdc65b" - integrity sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A== - -minizlib@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-3.1.0.tgz#6ad76c3a8f10227c9b51d1c9ac8e30b27f5a251c" - integrity sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw== - dependencies: - minipass "^7.1.2" - mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: version "0.5.3" resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" @@ -1932,16 +1908,10 @@ tar-stream@^3.1.5: fast-fifo "^1.3.2" streamx "^2.28.1" -tar@^7.5.7: - version "7.5.22" - resolved "https://registry.yarnpkg.com/tar/-/tar-7.5.22.tgz#a696f998136e71487dc3f869a85bba2c67971ba9" - integrity sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA== - dependencies: - "@isaacs/fs-minipass" "^4.0.0" - chownr "^3.0.0" - minipass "^7.1.2" - minizlib "^3.1.0" - yallist "^5.0.0" +tar@^7.5.7, tar@^8.0.5: + version "8.1.0" + resolved "https://registry.yarnpkg.com/tar/-/tar-8.1.0.tgz#c5cfb646747f360ece8d47c276c46e7bd499861f" + integrity sha512-0QsCa04wk0hddEWM4hSNMtgewhgvFTW+KzMKJzsSIGO2/snEWyaD9s72p9Is8SXHvbd6sxjInzzT39/yxOWTTw== teex@^1.0.1: version "1.0.1" @@ -2139,11 +2109,6 @@ y18n@^5.0.5: resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== -yallist@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-5.0.0.tgz#00e2de443639ed0d78fd87de0d27469fbcffb533" - integrity sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw== - yargs-parser@^20.2.2: version "20.2.9" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee" diff --git a/msa/migrator/pom.xml b/msa/migrator/pom.xml index bbb29c50f5..045eb14b3e 100644 --- a/msa/migrator/pom.xml +++ b/msa/migrator/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -179,7 +179,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/monitoring/pom.xml b/msa/monitoring/pom.xml index 8154decd5d..195f73e411 100644 --- a/msa/monitoring/pom.xml +++ b/msa/monitoring/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa @@ -138,7 +138,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -185,7 +185,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/pom.xml b/msa/pom.xml index 7dba66bcfd..7ae6583537 100644 --- a/msa/pom.xml +++ b/msa/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard msa @@ -26,6 +26,7 @@ pkg.package.phase (which is "none" here since these modules don't produce packaging). --> package thingsboard + ${project.version} thingsboard/openjdk25:trixie-slim true @@ -157,7 +158,7 @@ ${docker.push-arm-amd-image.phase} - latest,${project.version} + latest,${docker.version.tag} @@ -199,7 +200,7 @@ buildx build -t - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} --platform=linux/amd64,linux/arm64 -o type=registry @@ -220,11 +221,11 @@ - 4.4.1-latest + 4.4.2-latest false ${docker.push-arm-amd-image.phase} - ${sbom.image.latestTag},${project.version},${docker.lts.tag} + ${sbom.image.latestTag},${docker.version.tag},${docker.lts.tag} @@ -267,7 +268,7 @@ buildx build -t - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} --platform=linux/amd64,linux/arm64 -o type=registry diff --git a/msa/report/pom.xml b/msa/report/pom.xml index 806d9f8e71..9fb3296db3 100644 --- a/msa/report/pom.xml +++ b/msa/report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -138,7 +138,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -185,7 +185,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/tb-node/pom.xml b/msa/tb-node/pom.xml index 0b25f1c314..4efbec11e1 100644 --- a/msa/tb-node/pom.xml +++ b/msa/tb-node/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/transport/coap/pom.xml b/msa/transport/coap/pom.xml index 53d1b2aa30..3d2e8590b4 100644 --- a/msa/transport/coap/pom.xml +++ b/msa/transport/coap/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.msa.transport @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/transport/http/pom.xml b/msa/transport/http/pom.xml index 5d0d7b30f2..784358bb9d 100644 --- a/msa/transport/http/pom.xml +++ b/msa/transport/http/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.msa.transport @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/transport/lwm2m/pom.xml b/msa/transport/lwm2m/pom.xml index 6a628aa6e7..b1ae461b1c 100644 --- a/msa/transport/lwm2m/pom.xml +++ b/msa/transport/lwm2m/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.msa.transport @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/transport/mqtt/pom.xml b/msa/transport/mqtt/pom.xml index 83e767470b..b6012e3dab 100644 --- a/msa/transport/mqtt/pom.xml +++ b/msa/transport/mqtt/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.msa.transport @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/transport/pom.xml b/msa/transport/pom.xml index 93c2de38bf..05e68ae535 100644 --- a/msa/transport/pom.xml +++ b/msa/transport/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/snmp/pom.xml b/msa/transport/snmp/pom.xml index 2c223f046f..43e3793e30 100644 --- a/msa/transport/snmp/pom.xml +++ b/msa/transport/snmp/pom.xml @@ -11,7 +11,7 @@ org.thingsboard.msa transport - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT org.thingsboard.msa.transport @@ -138,7 +138,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -185,7 +185,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/vc-executor-docker/pom.xml b/msa/vc-executor-docker/pom.xml index 22f42235ad..d703927a5b 100644 --- a/msa/vc-executor-docker/pom.xml +++ b/msa/vc-executor-docker/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/vc-executor/pom.xml b/msa/vc-executor/pom.xml index 9b54d974a9..6ded68ec01 100644 --- a/msa/vc-executor/pom.xml +++ b/msa/vc-executor/pom.xml @@ -11,7 +11,7 @@ org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -46,7 +46,11 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 io.grpc diff --git a/msa/web-report/chromium.js b/msa/web-report/chromium.js new file mode 100644 index 0000000000..662678c8f6 --- /dev/null +++ b/msa/web-report/chromium.js @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +// The Chromium builds shipped with the packages. They must be the Chromium release that playwright-core is released with, +// which install.js checks, so a Playwright upgrade needs new builds here. The Docker image has the chromium package of +// Debian instead: see docker/Dockerfile. +// +// The Chromium project publishes builds of the main branch only, so these are the builds from where the release was +// branched off, without the fixes made on the release branch later. The Debian package of the image has those fixes. +// +// To update after a Playwright upgrade, for the version that the error of install.js names: +// 1. Find where the release was branched off: chromium_main_branch_position in +// https://chromiumdash.appspot.com/fetch_version?version= +// 2. For Linux_x64 and for Win_x64, take the highest snapshot build that is not above that position. Builds are listed by +// the start of their number, so shorten the start until one appears: +// https://www.googleapis.com/storage/v1/b/chromium-browser-snapshots/o?delimiter=/&fields=prefixes&prefix=Linux_x64/ +// 3. Set the version (the release from the error, ending in .0) and the two paths, and build the module. It fails with +// the SHA-256 of an archive: put it in the sha256 of that platform and build again, until both pass. +// install.js also fails if an unpacked build is not the version set here. +module.exports = { + // The packages: snapshot builds of the open source code, published by the Chromium project. + // exclude: glob patterns of the files that are not packaged + // strip: glob patterns of the executables to strip of their symbols, when GNU strip is installed + snapshot: { + version: '159.0.8154.0', + baseUrl: 'https://commondatastorage.googleapis.com/chromium-browser-snapshots', + // The .pak.info files, 70 MB, are left from the build of the translations; the browser does not read them + linux: { path: 'Linux_x64/1739867/chrome-linux.zip', sha256: 'e3dc14d0c796c4cff0a2e67e1d2d384a5228ab7e6adb4d4822d813772e4b8b4b', + exclude: ['locales/*.pak.info'], + // The Linux builds come with their symbols, 180 MB + strip: ['chrome', 'chrome_crashpad_handler', 'chrome_sandbox', '*.so*'] }, + // interactive_ui_tests.exe is a test program of 348 MB that the service does not need + windows: { path: 'Win_x64/1739762/chrome-win.zip', sha256: '097cc334674de52de3653519d8205bc227c7943f6a6cc0d2a0fc4a8f685284db', + exclude: ['interactive_ui_tests.exe'] } + } +}; diff --git a/msa/web-report/docker/Dockerfile b/msa/web-report/docker/Dockerfile index 9e1d9404e3..f80f704a0e 100644 --- a/msa/web-report/docker/Dockerfile +++ b/msa/web-report/docker/Dockerfile @@ -3,14 +3,15 @@ # SPDX-License-Identifier: BUSL-1.1 # -FROM thingsboard/node:22.23.4-bookworm-slim +FROM thingsboard/node:22.23.5-bookworm-slim ARG TARGETPLATFORM ARG DEBIAN_FRONTEND=noninteractive ENV NODE_ENV production ENV DOCKER_MODE true -ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright +# The browser is the chromium package of Debian, installed below +ENV CHROME_EXECUTABLE=/usr/bin/chromium COPY start-web-report.sh /tmp/ @@ -26,17 +27,13 @@ COPY src/config ./config COPY src/inspectorShim.js src/server.js ./ RUN apt-get update \ - && apt-get install -yq --no-install-recommends fonts-noto-cjk-extra fonts-roboto fonts-noto-color-emoji fonts-unifont libfreetype6 xfonts-scalable fonts-liberation \ - fonts-ipafont-gothic fonts-wqy-zenhei fonts-tlwg-loma-otf fonts-freefont-ttf fontconfig libasound2 libatk-bridge2.0-0 libatk1.0-0 libatspi2.0-0 \ - libcairo2 libcups2 libdbus-1-3 libdrm2 libgbm1 libglib2.0-0 libnspr4 libnss3 libpango-1.0-0 libwayland-client0 libx11-6 libxcb1 libxcomposite1 \ - libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 \ + && apt-get install -yq --no-install-recommends chromium fontconfig fonts-noto-cjk-extra fonts-roboto fonts-noto-color-emoji fonts-unifont \ + xfonts-scalable fonts-liberation fonts-ipafont-gothic fonts-wqy-zenhei fonts-tlwg-loma-otf fonts-freefont-ttf \ && rm -rf /var/lib/apt/lists/* \ && chmod a+x /tmp/*.sh \ && mv /tmp/start-web-report.sh /usr/bin \ && chown -R node:node ${pkg.installFolder} \ - && mkdir /ms-playwright \ - && yarn install --production --non-interactive --network-concurrency 4 --network-timeout 100000 --mutex network && yarn cache clean --all \ - && chmod -R 777 /ms-playwright + && yarn install --production --non-interactive --network-concurrency 4 --network-timeout 100000 --mutex network && yarn cache clean --all USER node diff --git a/msa/web-report/docker/start-web-report.sh b/msa/web-report/docker/start-web-report.sh index 390c77e2d7..6b2a050558 100755 --- a/msa/web-report/docker/start-web-report.sh +++ b/msa/web-report/docker/start-web-report.sh @@ -14,7 +14,5 @@ source "${CONF_FOLDER}/${configfile}" cd ${pkg.installFolder} -export CHROME_EXECUTABLE=$(node -e "console.log(require('playwright-chromium').chromium.executablePath());") - # This will forward this PID 1 to the node.js and forward SIGTERM for graceful shutdown as well exec node server.js diff --git a/msa/web-report/install.js b/msa/web-report/install.js index 842978aaec..64312b6333 100644 --- a/msa/web-report/install.js +++ b/msa/web-report/install.js @@ -1,46 +1,149 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +const fs = require('fs'); const fse = require('fs-extra'); const path = require('path'); -const { execFileSync } = require('child_process'); +const crypto = require('crypto'); +const { execFile, execFileSync } = require('child_process'); +const { promisify } = require('util'); +const { Transform } = require('stream'); +const { pipeline } = require('stream/promises'); +// The helpers that Playwright downloads its browsers with: httpRequest follows HTTPS_PROXY and redirects, extractZip needs no unzip tool +const { httpRequest, extractZip } = require('playwright-core/lib/coreBundle').utils; +const { snapshot } = require('./chromium'); + +const DOWNLOAD_ATTEMPTS = 3; -// Chromium builds packaged with the service, downloaded by the Playwright CLI as if it ran on the target platform. const PLATFORMS = { - linux: { hostPlatform: 'ubuntu24.04-x64', downloadDir: 'chromiumLinux', chromeDir: 'chrome-linux64', binary: 'tb-web-report', pkgOutput: 'thingsboard-web-report-linux' }, - windows: { hostPlatform: 'win64', downloadDir: 'chromiumWin', chromeDir: 'chrome-win64', binary: 'tb-web-report.exe', pkgOutput: 'thingsboard-web-report-win.exe' } + linux: { + ...snapshot.linux, binary: 'tb-web-report', pkgOutput: 'thingsboard-web-report-linux', + // The version is written into the executable + hasVersion: dir => fileContains(path.join(dir, 'chrome'), snapshot.version) + }, + windows: { + ...snapshot.windows, binary: 'tb-web-report.exe', pkgOutput: 'thingsboard-web-report-win.exe', + hasVersion: dir => fse.pathExists(path.join(dir, `${snapshot.version}.manifest`)) + } }; (async() => { - for (const [targetDir, platform] of Object.entries(PLATFORMS)) { - const downloadDir = path.join(projectRoot(), 'target', platform.downloadDir); - installChromium(platform.hostPlatform, downloadDir); - const chromiumDir = path.join(targetPackageDir(targetDir), 'chromium'); - await fse.emptyDir(chromiumDir); - await fse.copy(path.join(downloadDir, chromiumRevisionDir(), platform.chromeDir), chromiumDir); + checkPlaywrightVersion(); + await Promise.all(Object.entries(PLATFORMS).map(async ([targetDir, platform]) => { + await installChromium(platform, path.join(projectRoot(), 'target', 'chromium-' + targetDir), + path.join(targetPackageDir(targetDir), 'chromium')); await fse.move(path.join(projectRoot(), 'target', platform.pkgOutput), path.join(targetPackageDir(targetDir), 'bin', platform.binary), {overwrite: true}); - } + })); })().catch(e => { console.error(e); process.exit(1); }); -function installChromium(hostPlatform, downloadDir) { - execFileSync(process.execPath, [path.join(path.dirname(require.resolve('playwright-core/package.json')), 'cli.js'), 'install', '--no-shell', 'chromium'], { - stdio: 'inherit', - env: { - ...process.env, - PLAYWRIGHT_HOST_PLATFORM_OVERRIDE: hostPlatform, - PLAYWRIGHT_BROWSERS_PATH: downloadDir, - PLAYWRIGHT_SKIP_BROWSER_GC: '1' +function checkPlaywrightVersion() { + const browsers = fse.readJsonSync(path.join(path.dirname(require.resolve('playwright-core/package.json')), 'browsers.json')).browsers; + const chromium = browsers.find(browser => browser.name === 'chromium'); + if (!chromium) { + throw new Error('playwright-core/browsers.json does not list chromium'); + } + // The release is the first three numbers; the last one counts the fixes on its branch and differs between builds + const build = version => version.split('.').slice(0, 3).join('.'); + if (build(chromium.browserVersion) !== build(snapshot.version)) { + throw new Error(`playwright-core expects Chromium ${chromium.browserVersion}, the snapshot build in chromium.js is ${snapshot.version}`); + } +} + +async function installChromium(platform, downloadDir, chromiumDir) { + await fse.emptyDir(downloadDir); + const archive = path.join(downloadDir, 'chromium.zip'); + await download(`${snapshot.baseUrl}/${platform.path}`, archive, platform.sha256); + await extractZip(archive, { dir: downloadDir }); + const unpacked = path.join(downloadDir, path.basename(platform.path, '.zip')); + for await (const excluded of fs.promises.glob(platform.exclude || [], { cwd: unpacked })) { + await fse.remove(path.join(unpacked, excluded)); + } + if (platform.strip) { + await stripExecutables(unpacked, platform.strip); + } + if (!await platform.hasVersion(unpacked)) { + throw new Error(`${platform.path} is not Chromium ${snapshot.version}; check the build number in chromium.js`); + } + await fse.move(unpacked, chromiumDir, { overwrite: true }); + await fse.remove(downloadDir); +} + +// Fails unless the SHA-256 of the downloaded file is the expected one. Tries again when the connection or the server +// fails, but not for an answer such as 404, which would be the same again. +async function download(url, file, sha256) { + let actual; + for (let attempt = 1; actual === undefined; attempt++) { + try { + actual = await downloadOnce(url, file); + } catch (e) { + if (e.statusCode < 500 || attempt === DOWNLOAD_ATTEMPTS) { + throw e; + } + console.warn(`${e.message}; trying again`); } + } + if (actual !== sha256) { + throw new Error(`${url} has SHA-256 ${actual}, expected ${sha256}`); + } +} + +// Writes the file while it is downloaded, and gives its SHA-256 +function downloadOnce(url, file) { + return new Promise((resolve, reject) => { + const fail = (reason, statusCode) => reject(Object.assign(new Error(`Cannot download ${url}: ${reason}`), { statusCode })); + httpRequest({ url, socketTimeout: 60000 }, response => { + if (response.statusCode !== 200) { + response.resume(); + fail(`HTTP ${response.statusCode}`, response.statusCode); + return; + } + const hash = crypto.createHash('sha256'); + const hashing = new Transform({ + transform(chunk, encoding, callback) { + hash.update(chunk); + callback(null, chunk); + } + }); + pipeline(response, hashing, fs.createWriteStream(file)).then(() => resolve(hash.digest('hex')), e => fail(e.message)); + }, e => fail(e.message)); }); } -function chromiumRevisionDir() { - const browsers = fse.readJsonSync(path.join(projectRoot(), 'node_modules', 'playwright-core', 'browsers.json')).browsers; - return 'chromium-' + browsers.find(b => b.name === 'chromium').revision; +// Strips the symbols with GNU strip, which reads the Linux executables on any build machine. Without it, as on macOS +// or where binutils is not installed, the executables are packaged as they are. +async function stripExecutables(dir, patterns) { + if (!hasGnuStrip()) { + console.warn('strip not found, Linux Chromium left unstripped (+~180 MB); install GNU binutils to strip it'); + return; + } + for await (const file of fs.promises.glob(patterns, { cwd: dir })) { + await promisify(execFile)('strip', ['--strip-unneeded', path.join(dir, file)]); + } +} + +function hasGnuStrip() { + try { + return execFileSync('strip', ['--version'], { encoding: 'utf8' }).includes('GNU strip'); + } catch { + return false; + } +} + +async function fileContains(file, text) { + const needle = Buffer.from(text); + let tail = Buffer.alloc(0); + for await (const chunk of fs.createReadStream(file)) { + const data = Buffer.concat([tail, chunk]); + if (data.includes(needle)) { + return true; + } + tail = data.subarray(data.length - needle.length + 1); + } + return false; } function projectRoot() { diff --git a/msa/web-report/package.json b/msa/web-report/package.json index 169548ffc0..21143e2bd8 100644 --- a/msa/web-report/package.json +++ b/msa/web-report/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-web-report", "private": true, - "version": "4.4.1", + "version": "4.4.2", "description": "ThingsBoard Web Reporting Microservice", "main": "server.ts", "bin": "server.js", @@ -18,8 +18,7 @@ "config": "~4.4.2", "express": "~5.3.0", "js-yaml": "^4.3.2", - "playwright-chromium": "~1.64.1", - "playwright-core": "~1.64.1", + "playwright-core": "~1.65.2", "winston": "~3.19.0", "winston-daily-rotate-file": "~5.0.0" }, @@ -45,5 +44,8 @@ "node_modules/playwright-core/lib/server/chromium/appIcon.png", "../../node_modules/playwright-core/lib/webp_codec.wasm" ] + }, + "resolutions": { + "@yao-pkg/pkg/tar": "^8.0.5" } } diff --git a/msa/web-report/playwright-core-1.65.2.tgz b/msa/web-report/playwright-core-1.65.2.tgz new file mode 100644 index 0000000000..f53a0e9a93 Binary files /dev/null and b/msa/web-report/playwright-core-1.65.2.tgz differ diff --git a/msa/web-report/pom.xml b/msa/web-report/pom.xml index 7bba753b18..e76e6e7586 100644 --- a/msa/web-report/pom.xml +++ b/msa/web-report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -88,7 +88,7 @@ install-node-and-yarn - v22.23.4 + v22.23.5 v1.22.22 @@ -238,7 +238,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -321,15 +321,16 @@ application - chrome-for-testing + chromium ${chromium.version} - Chrome for Testing build downloaded by Playwright, used to render reports. - pkg:generic/google/chrome-for-testing@${chromium.version}?os=linux + Chromium snapshot build of the Chromium project, used to render reports. + pkg:generic/chromium/chromium@${chromium.version}?os=linux cpe:2.3:a:google:chrome:${chromium.version}:*:*:*:*:*:*:* + BSD-3-Clause - Google LLC + The Chromium Authors - https://googlechromelabs.github.io/chrome-for-testing/ + https://www.chromium.org ${pkg.linux.dist}/chromium/chrome @@ -340,15 +341,16 @@ application - chrome-for-testing + chromium ${chromium.version} - Chrome for Testing build downloaded by Playwright, used to render reports. - pkg:generic/google/chrome-for-testing@${chromium.version}?os=windows + Chromium snapshot build of the Chromium project, used to render reports. + pkg:generic/chromium/chromium@${chromium.version}?os=windows cpe:2.3:a:google:chrome:${chromium.version}:*:*:*:*:*:*:* + BSD-3-Clause - Google LLC + The Chromium Authors - https://googlechromelabs.github.io/chrome-for-testing/ + https://www.chromium.org ${pkg.win.dist}/chromium/chrome.exe @@ -367,48 +369,6 @@ ${project.build.directory}/sbom/tb-web-report.cdx.json ${pkg.installFolder} - - application - chrome-for-testing - ${chromium.version} - Chrome for Testing build downloaded by Playwright to /ms-playwright, used to render reports. - pkg:generic/google/chrome-for-testing@${chromium.version}?os=linux&arch=@{architecture} - cpe:2.3:a:google:chrome:${chromium.version}:*:*:*:*:*:*:* - - Google LLC - - https://googlechromelabs.github.io/chrome-for-testing/ - - - - - application - chrome-headless-shell - ${chromium-headless-shell.version} - Chrome Headless Shell build downloaded by Playwright to /ms-playwright. - pkg:generic/google/chrome-headless-shell@${chromium-headless-shell.version}?os=linux&arch=@{architecture} - cpe:2.3:a:google:chrome:${chromium-headless-shell.version}:*:*:*:*:*:*:* - - Google LLC - - https://googlechromelabs.github.io/chrome-for-testing/ - - - - - application - playwright-ffmpeg - ${ffmpeg.revision} - FFmpeg build by Playwright (revision ${ffmpeg.revision}), downloaded to /ms-playwright. - pkg:generic/microsoft/playwright-ffmpeg@${ffmpeg.revision}?os=linux&arch=@{architecture} - LGPL-2.1-or-later - - Microsoft Corporation - - https://playwright.dev - - - @@ -482,7 +442,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/web-report/sbom-check.js b/msa/web-report/sbom-check.js index cd4d3f76df..3f2723cea6 100644 --- a/msa/web-report/sbom-check.js +++ b/msa/web-report/sbom-check.js @@ -12,7 +12,7 @@ const BASE_BINARY = /fetched-v(\d+\.\d+\.\d+)-/; (() => { const listed = listedPackages(JSON.parse(fs.readFileSync(SBOM_FILE, 'utf8'))); - const versions = playwrightVersions(); + const versions = { 'chromium.version': require('./chromium').snapshot.version }; for (const [os, log] of Object.entries(PKG_LOGS)) { const output = fs.readFileSync(path.join(TARGET_DIR, log), 'utf8').replace(/\x1b\[[0-9;]*m/g, ''); const baseBinary = BASE_BINARY.exec(output); @@ -74,20 +74,3 @@ function packageDir(file) { } return parts.slice(0, index + (scoped ? 3 : 2)).join(path.sep); } - -function playwrightVersions() { - const browsers = JSON.parse(fs.readFileSync(path.join(path.dirname(require.resolve('playwright-core/package.json')), 'browsers.json'), 'utf8')).browsers; - const browser = name => { - const found = browsers.find(candidate => candidate.name === name); - if (!found) { - throw new Error(`playwright-core/browsers.json does not list ${name}`); - } - return found; - }; - return { - 'chromium.version': browser('chromium').browserVersion, - 'chromium-headless-shell.version': browser('chromium-headless-shell').browserVersion, - 'ffmpeg.revision': browser('ffmpeg').revision - }; -} - diff --git a/msa/web-report/server.ts b/msa/web-report/server.ts index e000c860c4..758f016cb2 100644 --- a/msa/web-report/server.ts +++ b/msa/web-report/server.ts @@ -5,8 +5,7 @@ import express from 'express'; import bodyParser from 'body-parser'; import config from 'config'; import { _logger } from './config/logger'; -import { chromium } from 'playwright-chromium'; -import { Browser, LaunchOptions } from 'playwright-core'; +import { Browser, chromium, LaunchOptions } from 'playwright-core'; import { route } from './api/routes/tbWebReportRoutes'; import { TbWebReportPageQueue } from './api/controllers/tbWebReportPageQueue'; diff --git a/msa/web-report/yarn.lock b/msa/web-report/yarn.lock index 82f160bb5d..be8dd94dc6 100644 --- a/msa/web-report/yarn.lock +++ b/msa/web-report/yarn.lock @@ -235,13 +235,6 @@ resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz#b21affb804cc167c133d95f45b3a1dc1323b9a87" integrity sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g== -"@isaacs/fs-minipass@^4.0.0": - version "4.0.1" - resolved "https://registry.yarnpkg.com/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz#2d59ae3ab4b38fb4270bfa23d30f8e2e86c7fe32" - integrity sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w== - dependencies: - minipass "^7.0.4" - "@jridgewell/gen-mapping@^0.3.12": version "0.3.13" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz#6342a19f44347518c93e43b1ac69deb3c4656a1f" @@ -591,11 +584,6 @@ chownr@^1.1.1: resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" integrity sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg== -chownr@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" - integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== - cliui@^7.0.2: version "7.0.4" resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" @@ -1178,18 +1166,6 @@ minimist@^1.2.0, minimist@^1.2.3: resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== -minipass@^7.0.4, minipass@^7.1.2: - version "7.1.3" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.3.tgz#79389b4eb1bb2d003a9bba87d492f2bd37bdc65b" - integrity sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A== - -minizlib@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-3.1.0.tgz#6ad76c3a8f10227c9b51d1c9ac8e30b27f5a251c" - integrity sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw== - dependencies: - minipass "^7.1.2" - mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: version "0.5.3" resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" @@ -1307,17 +1283,10 @@ picomatch@^4.0.2, picomatch@^4.0.4: resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.7.tgz#6313360034ccb36b3dc61ecbdff78121f90fe21f" integrity sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA== -playwright-chromium@~1.64.1: - version "1.64.1" - resolved "https://registry.yarnpkg.com/playwright-chromium/-/playwright-chromium-1.64.1.tgz#81aec8925514050c0ac5bc08fa231ed189ab0e86" - integrity sha512-lvAzvvIRtbHaeLwl7XoUkhSNuWHKshbrYv2sjqYgLQS4SsTTwgSTlg9BwU5LeGxYkHxBXTnKtNDEQdZSOj/01g== - dependencies: - playwright-core "1.64.1" - -playwright-core@1.64.1, playwright-core@~1.64.1: - version "1.64.1" - resolved "https://registry.yarnpkg.com/playwright-core/-/playwright-core-1.64.1.tgz#ca9ec82d7da6ced1b2326ec59ef097aaa9a29f94" - integrity sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ== +playwright-core@~1.65.2: + version "1.65.2" + resolved "https://registry.yarnpkg.com/playwright-core/-/playwright-core-1.65.2.tgz#10b242db00a3cf9d01d2cc38cd91afb66664be6c" + integrity sha512-aHu9F46Mx5ha9iiB+VLZMUUtex3PBw4am9MHptc0IXaJhz++6YXsH96eEyThwCwMkIUiB8TdZcwXqnb3xKDzmA== postinstall-postinstall@^2.1.0: version "2.1.0" @@ -1714,16 +1683,10 @@ tar-stream@^3.1.5: fast-fifo "^1.3.2" streamx "^2.28.1" -tar@^7.5.7: - version "7.5.22" - resolved "https://registry.yarnpkg.com/tar/-/tar-7.5.22.tgz#a696f998136e71487dc3f869a85bba2c67971ba9" - integrity sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA== - dependencies: - "@isaacs/fs-minipass" "^4.0.0" - chownr "^3.0.0" - minipass "^7.1.2" - minizlib "^3.1.0" - yallist "^5.0.0" +tar@^7.5.7, tar@^8.0.5: + version "8.1.0" + resolved "https://registry.yarnpkg.com/tar/-/tar-8.1.0.tgz#c5cfb646747f360ece8d47c276c46e7bd499861f" + integrity sha512-0QsCa04wk0hddEWM4hSNMtgewhgvFTW+KzMKJzsSIGO2/snEWyaD9s72p9Is8SXHvbd6sxjInzzT39/yxOWTTw== teex@^1.0.1: version "1.0.1" @@ -1916,11 +1879,6 @@ y18n@^5.0.5: resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== -yallist@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-5.0.0.tgz#00e2de443639ed0d78fd87de0d27469fbcffb533" - integrity sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw== - yargs-parser@^20.2.2: version "20.2.9" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee" diff --git a/msa/web-ui/docker/Dockerfile b/msa/web-ui/docker/Dockerfile index 7f316f63ce..6e34dfb6fc 100644 --- a/msa/web-ui/docker/Dockerfile +++ b/msa/web-ui/docker/Dockerfile @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # -FROM thingsboard/node:22.23.4-bookworm-slim +FROM thingsboard/node:22.23.5-bookworm-slim ENV NODE_ENV production ENV DOCKER_MODE true diff --git a/msa/web-ui/negotiator.d.ts b/msa/web-ui/negotiator.d.ts new file mode 100644 index 0000000000..c98d111f40 --- /dev/null +++ b/msa/web-ui/negotiator.d.ts @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 + +// negotiator 1.x ships no types, and @types/negotiator (0.6) lacks the `preferred` option +declare module 'negotiator' { + import { IncomingMessage } from 'http'; + + export default class Negotiator { + constructor(request: IncomingMessage); + encoding(available: string[], options?: { preferred?: string[] }): string | undefined; + } +} diff --git a/msa/web-ui/package.json b/msa/web-ui/package.json index 3053dbe185..9a35e6b4b3 100644 --- a/msa/web-ui/package.json +++ b/msa/web-ui/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-web-ui", "private": true, - "version": "4.4.1", + "version": "4.4.2", "description": "ThingsBoard Web UI Microservice", "main": "server.ts", "bin": "server.js", @@ -14,18 +14,17 @@ "sbom": "node ../../tools/src/main/javascript/yarn-sbom.js target/sbom/tb-web-ui.cdx.json application --all-platforms" }, "dependencies": { - "compression": "^1.8.2", "config": "^4.4.2", "connect-history-api-fallback": "^2.0.0", "express": "^5.3.0", "http-proxy": "^1.18.1", "js-yaml": "^4.3.2", + "negotiator": "^1.1.0", "winston": "^3.19.0", "winston-daily-rotate-file": "^5.0.0" }, "devDependencies": { "@cyclonedx/cyclonedx-library": "10.3.0", - "@types/compression": "^1.8.1", "@types/connect-history-api-fallback": "1.5.4", "@types/express": "~5.0.6", "@types/http-proxy": "^1.17.17", @@ -43,5 +42,8 @@ "assets": [ "node_modules/config/**/*.*" ] + }, + "resolutions": { + "@yao-pkg/pkg/tar": "^8.0.5" } } diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index 02c8d28238..6488e08843 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -71,7 +71,7 @@ install-node-and-yarn - v22.23.4 + v22.23.5 v1.22.22 @@ -227,7 +227,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -330,7 +330,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/web-ui/server.ts b/msa/web-ui/server.ts index 9aa316e78f..59cb9dec9d 100644 --- a/msa/web-ui/server.ts +++ b/msa/web-ui/server.ts @@ -1,14 +1,16 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import express from 'express'; import config from 'config'; import { _logger} from './config/logger'; import path from 'path'; import http, { ServerResponse } from 'http'; import httpProxy from 'http-proxy'; -import compression from 'compression'; +import fs from 'fs'; import historyApiFallback from 'connect-history-api-fallback'; import { Socket } from 'net'; +import Negotiator from 'negotiator'; import { RequestHandler } from 'express'; const logger = _logger('main'); @@ -16,6 +18,18 @@ const logger = _logger('main'); let server: http.Server | null; let connections: Socket[] = []; +// in server preference order; must match the encoders in ui-ngx/compress-build.js +const precompressedEncodings = [ + {encoding: 'br', ext: '.br'}, + {encoding: 'gzip', ext: '.gz'} +]; + +interface PrecompressedVariant { + encoding: string; + ext: string; + files: Set; +} + (async() => { try { logger.info('Starting ThingsBoard Web UI Microservice...'); @@ -115,12 +129,20 @@ let connections: Socket[] = []; } app.use(historyApiFallback()); - if (compressionEnabled) { - app.use(compression()); - } const root = path.join(webDir, 'public'); + // No per-request compression: zlib/brotli fragment native memory that glibc never returns, until OOM + if (compressionEnabled) { + const variants = listPrecompressedFiles(root); + if (variants.some(({files}) => files.size)) { + logger.info('Pre-compressed files: %s', variants.map(({encoding, files}) => `${encoding} ${files.size}`).join(', ')); + } else { + logger.warn('No pre-compressed (.br/.gz) UI files in %s: UI files are served uncompressed', root); + } + app.use(precompressedStatic(root, variants)); + } + const staticServe = express.static(root); const indexHtmlFallback: RequestHandler = (req, res, next) => { @@ -167,6 +189,57 @@ process.on('exit', async (code: number) => { logger.info(`ThingsBoard Web UI Microservice has been stopped. Exit code: ${code}.`); }); +function listPrecompressedFiles(root: string): PrecompressedVariant[] { + const variants = precompressedEncodings.map(encoding => ({...encoding, files: new Set()})); + if (fs.existsSync(root)) { + for (const file of fs.readdirSync(root, {recursive: true, encoding: 'utf8'})) { + const variant = variants.find(({ext}) => file.endsWith(ext)); + variant?.files.add('/' + file.slice(0, -variant.ext.length).split(path.sep).join('/')); + } + } + return variants; +} + +function precompressedStatic(root: string, variants: PrecompressedVariant[]): RequestHandler { + return (req, res, next) => { + if (req.method !== 'GET' && req.method !== 'HEAD') { + return next(); + } + let filePath: string; + try { + filePath = decodeURIComponent(req.path); + } catch { + return next(); + } + const available = variants.filter(({files}) => files.has(filePath)); + if (!available.length) { + return next(); + } + res.vary('Accept-Encoding'); + // highest q wins; on a tie the server's order does, as browsers list gzip before br + const encodings = available.map(({encoding}) => encoding); + const best = new Negotiator(req).encoding([...encodings, 'identity'], {preferred: encodings}); + const variant = available.find(({encoding}) => encoding === best); + if (!variant) { + return next(); + } + res.setHeader('Content-Encoding', variant.encoding); + res.type(path.extname(filePath)); + res.sendFile(filePath + variant.ext, {root}, (err?: NodeJS.ErrnoException & { status?: number }) => { + // the client went away; express.static ignores these too + if (!err || err.code === 'ECONNABORTED' || err.syscall === 'write') { + return; + } + if (res.headersSent) { + return next(err); + } + res.removeHeader('Content-Encoding'); + // the copy was removed after startup: fall through to the original + next(err.status === 404 ? undefined : err); + }); + }; +} + async function exit(status: number) { logger.info('Exiting with status: %d ...', status); if (server) { diff --git a/msa/web-ui/tsconfig.json b/msa/web-ui/tsconfig.json index b633ffc768..2b3cfdf7e5 100644 --- a/msa/web-ui/tsconfig.json +++ b/msa/web-ui/tsconfig.json @@ -9,5 +9,8 @@ "skipLibCheck": true, "strictPropertyInitialization": false }, - "exclude": ["node_modules", "target"] + "exclude": ["node_modules", "target"], + "ts-node": { + "files": true + } } diff --git a/msa/web-ui/yarn.lock b/msa/web-ui/yarn.lock index 70dce9222f..290a600123 100644 --- a/msa/web-ui/yarn.lock +++ b/msa/web-ui/yarn.lock @@ -235,13 +235,6 @@ resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz#b21affb804cc167c133d95f45b3a1dc1323b9a87" integrity sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g== -"@isaacs/fs-minipass@^4.0.0": - version "4.0.1" - resolved "https://registry.yarnpkg.com/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz#2d59ae3ab4b38fb4270bfa23d30f8e2e86c7fe32" - integrity sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w== - dependencies: - minipass "^7.0.4" - "@jridgewell/gen-mapping@^0.3.12": version "0.3.13" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz#6342a19f44347518c93e43b1ac69deb3c4656a1f" @@ -317,14 +310,6 @@ "@types/connect" "*" "@types/node" "*" -"@types/compression@^1.8.1": - version "1.8.1" - resolved "https://registry.yarnpkg.com/@types/compression/-/compression-1.8.1.tgz#57cd1a5c0c585aca56124ab4daef1d254d6f5a7d" - integrity sha512-kCFuWS0ebDbmxs0AXYn6e2r2nrGAb5KwQhknjSPSPgJcGd8+HVSILlUyFhGqML2gk39HcG7D1ydW9/qpYkN00Q== - dependencies: - "@types/express" "*" - "@types/node" "*" - "@types/connect-history-api-fallback@1.5.4": version "1.5.4" resolved "https://registry.yarnpkg.com/@types/connect-history-api-fallback/-/connect-history-api-fallback-1.5.4.tgz#7de71645a103056b48ac3ce07b3520b819c1d5b3" @@ -350,7 +335,7 @@ "@types/range-parser" "*" "@types/send" "*" -"@types/express@*", "@types/express@~5.0.6": +"@types/express@~5.0.6": version "5.0.6" resolved "https://registry.yarnpkg.com/@types/express/-/express-5.0.6.tgz#2d724b2c990dcb8c8444063f3580a903f6d500cc" integrity sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA== @@ -588,7 +573,7 @@ buffer@^5.5.0: base64-js "^1.3.1" ieee754 "^1.1.13" -bytes@3.1.2, bytes@^3.1.2, bytes@~3.1.2: +bytes@^3.1.2, bytes@~3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.2.tgz#8b0beeb98605adf1b128fa4386403c009e0221a5" integrity sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg== @@ -614,11 +599,6 @@ chownr@^1.1.1: resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" integrity sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg== -chownr@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" - integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== - cliui@^7.0.2: version "7.0.4" resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" @@ -672,27 +652,6 @@ commander@^9.4.0: resolved "https://registry.yarnpkg.com/commander/-/commander-9.5.0.tgz#bc08d1eb5cedf7ccb797a96199d41c7bc3e60d30" integrity sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ== -compressible@~2.0.18: - version "2.0.18" - resolved "https://registry.yarnpkg.com/compressible/-/compressible-2.0.18.tgz#af53cca6b070d4c3c0750fbd77286a6d7cc46fba" - integrity sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg== - dependencies: - mime-db ">= 1.43.0 < 2" - -compression@^1.8.2: - version "1.8.2" - resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.2.tgz#781397127ae2da00c0c5f7c76bda5b2a9b32a49f" - integrity sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ== - dependencies: - bytes "3.1.2" - compressible "~2.0.18" - debug "2.6.9" - destroy "1.2.0" - negotiator "~0.6.4" - on-headers "~1.1.0" - safe-buffer "5.2.1" - vary "~1.1.2" - config@^4.4.2: version "4.4.2" resolved "https://registry.yarnpkg.com/config/-/config-4.4.2.tgz#adab67a87fcb5f84edcacb3f159ccdb31ad8b901" @@ -735,13 +694,6 @@ create-require@^1.1.0: resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== -debug@2.6.9: - version "2.6.9" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" - integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== - dependencies: - ms "2.0.0" - debug@^4.3.1, debug@^4.4.0, debug@^4.4.3: version "4.4.3" resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.3.tgz#c6ae432d9bd9662582fce08709b038c58e9e3d6a" @@ -766,11 +718,6 @@ depd@^2.0.0, depd@~2.0.0: resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== -destroy@1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" - integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== - detect-libc@^2.0.0: version "2.1.2" resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.1.2.tgz#689c5dcdc1900ef5583a4cb9f6d7b473742074ad" @@ -1236,7 +1183,7 @@ merge-descriptors@^2.0.0: resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-2.0.0.tgz#ea922f660635a2249ee565e0449f951e6b603808" integrity sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g== -"mime-db@>= 1.43.0 < 2", mime-db@^1.54.0: +mime-db@^1.54.0: version "1.54.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.54.0.tgz#cddb3ee4f9c64530dff640236661d42cb6a314f5" integrity sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ== @@ -1258,18 +1205,6 @@ minimist@^1.2.0, minimist@^1.2.3: resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== -minipass@^7.0.4, minipass@^7.1.2: - version "7.1.3" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.3.tgz#79389b4eb1bb2d003a9bba87d492f2bd37bdc65b" - integrity sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A== - -minizlib@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-3.1.0.tgz#6ad76c3a8f10227c9b51d1c9ac8e30b27f5a251c" - integrity sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw== - dependencies: - minipass "^7.1.2" - mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: version "0.5.3" resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" @@ -1280,11 +1215,6 @@ moment@^2.29.1: resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== -ms@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" - integrity sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A== - ms@^2.1.1, ms@^2.1.3: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" @@ -1303,18 +1233,13 @@ napi-build-utils@^2.0.0: resolved "https://registry.yarnpkg.com/napi-build-utils/-/napi-build-utils-2.0.0.tgz#13c22c0187fcfccce1461844136372a47ddc027e" integrity sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA== -negotiator@^1.0.0: +negotiator@^1.0.0, negotiator@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-1.1.0.tgz#16e003d0db4ac24fd9df168edf871625deeae3df" integrity sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg== dependencies: content-type "^2.1.0" -negotiator@~0.6.4: - version "0.6.4" - resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.4.tgz#777948e2452651c570b712dd01c23e262713fff7" - integrity sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w== - node-abi@^3.3.0: version "3.100.0" resolved "https://registry.yarnpkg.com/node-abi/-/node-abi-3.100.0.tgz#31aa9623841051d14f52415557e18101bc0de7ca" @@ -1353,11 +1278,6 @@ on-finished@^2.4.1: dependencies: ee-first "1.1.1" -on-headers@~1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/on-headers/-/on-headers-1.1.0.tgz#59da4f91c45f5f989c6e4bcedc5a3b0aed70ff65" - integrity sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A== - once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" @@ -1544,7 +1464,7 @@ router@^2.2.0: parseurl "^1.3.3" path-to-regexp "^8.0.0" -safe-buffer@5.2.1, safe-buffer@^5.0.1, safe-buffer@~5.2.0: +safe-buffer@^5.0.1, safe-buffer@~5.2.0: version "5.2.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== @@ -1797,16 +1717,10 @@ tar-stream@^3.1.5: fast-fifo "^1.3.2" streamx "^2.28.1" -tar@^7.5.7: - version "7.5.22" - resolved "https://registry.yarnpkg.com/tar/-/tar-7.5.22.tgz#a696f998136e71487dc3f869a85bba2c67971ba9" - integrity sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA== - dependencies: - "@isaacs/fs-minipass" "^4.0.0" - chownr "^3.0.0" - minipass "^7.1.2" - minizlib "^3.1.0" - yallist "^5.0.0" +tar@^7.5.7, tar@^8.0.5: + version "8.0.5" + resolved "https://registry.yarnpkg.com/tar/-/tar-8.0.5.tgz#1f36231a811830520db3a6af984c55505a930ec3" + integrity sha512-iYroSHv/iVs5Bfy7uXCZVTye64oecqEETP3jvxksDcJlf8E3hreHYyhT+Qu7b+JgniditLaQbk4ZujNAnPEX9w== teex@^1.0.1: version "1.0.1" @@ -1939,7 +1853,7 @@ validate-npm-package-license@^3.0.4: spdx-correct "^3.0.0" spdx-expression-parse "^3.0.0" -vary@^1.1.2, vary@~1.1.2: +vary@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc" integrity sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg== @@ -1999,11 +1913,6 @@ y18n@^5.0.5: resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== -yallist@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-5.0.0.tgz#00e2de443639ed0d78fd87de0d27469fbcffb533" - integrity sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw== - yargs-parser@^20.2.2: version "20.2.9" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee" diff --git a/netty-mqtt/pom.xml b/netty-mqtt/pom.xml index 9fe47daa32..ae51ed9ac1 100644 --- a/netty-mqtt/pom.xml +++ b/netty-mqtt/pom.xml @@ -9,11 +9,11 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard netty-mqtt - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT jar Netty MQTT Client @@ -84,17 +84,12 @@ org.testcontainers - junit-jupiter - test - - - software.xdev - testcontainers-junit4-mock + testcontainers-junit-jupiter test org.testcontainers - hivemq + testcontainers-hivemq test diff --git a/netty-mqtt/src/test/java/org/thingsboard/mqtt/MqttClientTlsTest.java b/netty-mqtt/src/test/java/org/thingsboard/mqtt/MqttClientTlsTest.java new file mode 100644 index 0000000000..f306de52eb --- /dev/null +++ b/netty-mqtt/src/test/java/org/thingsboard/mqtt/MqttClientTlsTest.java @@ -0,0 +1,151 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.mqtt; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.codec.mqtt.MqttConnAckMessage; +import io.netty.handler.codec.mqtt.MqttConnectReturnCode; +import io.netty.handler.codec.mqtt.MqttDecoder; +import io.netty.handler.codec.mqtt.MqttEncoder; +import io.netty.handler.codec.mqtt.MqttMessage; +import io.netty.handler.codec.mqtt.MqttMessageBuilders; +import io.netty.handler.codec.mqtt.MqttMessageType; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.SslHandler; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.Promise; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.thingsboard.common.util.AbstractListeningExecutor; + +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.time.Duration; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +class MqttClientTlsTest { + + private EventLoopGroup serverGroup; + private Channel serverChannel; + private CompletableFuture> serverHandshake; + private AbstractListeningExecutor handlerExecutor; + private MqttClient client; + + @BeforeEach + void setup() throws Exception { + SslContext serverSslContext; + try (InputStream cert = resource("mismatched-host-cert.pem"); InputStream key = resource("mismatched-host-key.pem")) { + serverSslContext = SslContextBuilder.forServer(cert, key).build(); + } + serverHandshake = new CompletableFuture<>(); + serverGroup = new NioEventLoopGroup(1); + serverChannel = new ServerBootstrap() + .group(serverGroup) + .channel(NioServerSocketChannel.class) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) { + SslHandler sslHandler = serverSslContext.newHandler(ch.alloc()); + serverHandshake.complete(sslHandler.handshakeFuture()); + ch.pipeline().addLast(sslHandler, new MqttDecoder(), MqttEncoder.INSTANCE, new ConnAckHandler()); + } + }) + .bind("localhost", 0).sync().channel(); + + handlerExecutor = new AbstractListeningExecutor() { + @Override + protected int getThreadPollSize() { + return 1; + } + }; + handlerExecutor.init(); + } + + @AfterEach + void cleanup() { + if (client != null) { + client.disconnect(); + } + handlerExecutor.destroy(); + serverChannel.close().syncUninterruptibly(); + serverGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).syncUninterruptibly(); + } + + @Test + void connectsOverTlsWhenCertificateNameDoesNotMatchHostAndEndpointIdentificationIsOff() throws Exception { + SslContext clientSslContext; + try (InputStream cert = resource("mismatched-host-cert.pem")) { + clientSslContext = SslContextBuilder.forClient().endpointIdentificationAlgorithm(null).trustManager(cert).build(); + } + + Promise connectFuture = connect(clientSslContext); + + Awaitility.await("waiting for client to connect") + .atMost(Duration.ofSeconds(10)) + .until(connectFuture::isDone); + assertThat(connectFuture.isSuccess()).isTrue(); + assertThat(connectFuture.getNow().getReturnCode()).isEqualTo(MqttConnectReturnCode.CONNECTION_ACCEPTED); + assertThat(client.isConnected()).isTrue(); + } + + @Test + void rejectsCertificateNameMismatchWithNettyDefaultEndpointIdentification() throws Exception { + SslContext clientSslContext; + try (InputStream cert = resource("mismatched-host-cert.pem")) { + clientSslContext = SslContextBuilder.forClient().trustManager(cert).build(); + } + + connect(clientSslContext); + + Future handshake = serverHandshake.get(10, TimeUnit.SECONDS); + Awaitility.await("waiting for server handshake to finish") + .atMost(Duration.ofSeconds(10)) + .until(handshake::isDone); + assertThat(handshake.isSuccess()).isFalse(); + assertThat(client.isConnected()).isFalse(); + } + + private Promise connect(SslContext clientSslContext) { + MqttClientConfig config = new MqttClientConfig(clientSslContext); + config.setOwnerId("Test[Tls]"); + config.setClientId("tls"); + config.setReconnect(false); + client = MqttClient.create(config, null, handlerExecutor); + int port = ((InetSocketAddress) serverChannel.localAddress()).getPort(); + return client.connect("localhost", port); + } + + private static InputStream resource(String name) { + return MqttClientTlsTest.class.getClassLoader().getResourceAsStream(name); + } + + private static class ConnAckHandler extends SimpleChannelInboundHandler { + + @Override + protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) { + if (msg.fixedHeader().messageType() == MqttMessageType.CONNECT) { + MqttConnAckMessage connAck = MqttMessageBuilders.connAck() + .returnCode(MqttConnectReturnCode.CONNECTION_ACCEPTED) + .sessionPresent(false) + .build(); + ctx.writeAndFlush(connAck); + } + } + + } + +} diff --git a/netty-mqtt/src/test/resources/mismatched-host-cert.pem b/netty-mqtt/src/test/resources/mismatched-host-cert.pem new file mode 100644 index 0000000000..98ab8a4e0d --- /dev/null +++ b/netty-mqtt/src/test/resources/mismatched-host-cert.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDJzCCAg+gAwIBAgIUZh0cw6RBfrfnG9H3yz/2MNm6syQwDQYJKoZIhvcNAQEL +BQAwIjEgMB4GA1UEAwwXbWlzbWF0Y2hlZC1ob3N0LmludmFsaWQwIBcNMjYxMDE1 +MDg0NTU3WhgPMjEyNjA5MjEwODQ1NTdaMCIxIDAeBgNVBAMMF21pc21hdGNoZWQt +aG9zdC5pbnZhbGlkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAujvb +w6YNgojtfzCzP7O5UrtcTnnO6dEIPQbMen/lhs5JGvC3GJIJLqtMpsKNu6W7cHaF +ZW9jPTXPytXLJqKjNhL6Czq0tdirGafaYrTxdkBO/GxOyv8AEPZNa94rx46yaLZL +U0iyu6VBCnNip/JDAnaooK1Vn6KGfGKc7Rspg4z7vqF9DCdmtX10nTxf1UpH8ecK +aXj7Q5kbKvRv/V8r6wioY9fv2Tmi9Fb3aD1ZNEQsZmpfd+m8yqiHbg6XBsdT/crQ +etcWxHVTEzYHDN3f4dMqAcNrnmecwwN4dTHUhnqwZZ9VeFc935t37mHQqUlloEql +u1vmgVcnBV0lY5a/rQIDAQABo1MwUTAdBgNVHQ4EFgQUlN4DKYSnyGJiTb8xZSv6 +gm7kiqswHwYDVR0jBBgwFoAUlN4DKYSnyGJiTb8xZSv6gm7kiqswDwYDVR0TAQH/ +BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAYIRGdtrtWvrhltDamBRQJqIMNxxP +cig7GWf7YwM28PjN9VFrWa/DPPKjA4Pmn173dYZvqALdIo5cLCZi22q3jS3oF43w +cpSRudn6rrD5gVSWgzje/daW2V/AxnSc1GqdlWSTBxTpYgTUNRg2Gz4JTftgzvCL +1quZ026DogZ2jwNCM/WdJeIow3E8Iv3Jc3p+l01d8ISsxo++gCDPPUaW1sNeQ3Vh +yCxmADS0T/Jp/ecLJmOgfdgkSkVZycvcRKwMmz8OXhcZL5/7aCNMhs4fp1Rj1WSH +ovhcKoIpJ3mDyMA+1TpTEE5ClvRVYMya0bMSda+Q+H7TOn61l9lOjFqR9A== +-----END CERTIFICATE----- diff --git a/netty-mqtt/src/test/resources/mismatched-host-key.pem b/netty-mqtt/src/test/resources/mismatched-host-key.pem new file mode 100644 index 0000000000..ae347f3934 --- /dev/null +++ b/netty-mqtt/src/test/resources/mismatched-host-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC6O9vDpg2CiO1/ +MLM/s7lSu1xOec7p0Qg9Bsx6f+WGzkka8LcYkgkuq0ymwo27pbtwdoVlb2M9Nc/K +1csmoqM2EvoLOrS12KsZp9pitPF2QE78bE7K/wAQ9k1r3ivHjrJotktTSLK7pUEK +c2Kn8kMCdqigrVWfooZ8YpztGymDjPu+oX0MJ2a1fXSdPF/VSkfx5wppePtDmRsq +9G/9XyvrCKhj1+/ZOaL0VvdoPVk0RCxmal936bzKqIduDpcGx1P9ytB61xbEdVMT +NgcM3d/h0yoBw2ueZ5zDA3h1MdSGerBln1V4Vz3fm3fuYdCpSWWgSqW7W+aBVycF +XSVjlr+tAgMBAAECggEAH1hM1GDB/Fr8kkBJoyqmQgj7789rpooCt3bJ+sJFCQv2 +XPzv7EhEGGFHjPfI8DDkW/ju2dRGITrJ5wtV3oJYMxU9lZ9DZCn8HlzUknF/BJat +VKoMFvmVcsVp4YJq3vMjDyHDith9EL0vNcmW7MqHQcZj+mtCMpShyxSz8ep08cmC +UalzYFfDdsxfyae1BgmUrUQoHhkUXMsOdUY+azTRqbLCF0hc8/RuLtfAjZTjrKy+ +nIVzw2q4DCrL08GSWYqwDwtYGvLLMcpjfoQGQgntrF06eaLn4PIwUWmYEEMRnyZD +KakHL0TgrdwaQcaG/URO9i8JJs7u7MEfaw4LiytJVwKBgQD3QoJQxx/tYJm01eeD +dP/PYLan97JqTqPUN09bbog0jnX4S4xJVgXQ15hSChaOwI+44XrpbP8RMvWHHSRk +miRdVYGuOU6hUZ/8B8dsO9FqyGL5gPBsScx96XTSVeUEvLFi+9jH0I1HwYr4pm9T +Jwd95Lpe9+/g64IpB0ilTUhJswKBgQDA0R2+plDCRirtXu3A5Ek/X6eS6MKrC8kS +Kw/Pp0jCjPDrNKg/E7ZLiDxeP+OerfK8Yy1lzMDiadTcxW9RWM3coqjvPLg622iL +TO/wTZ2ENnxdsWzhU1PyJe0qY+Cyue0VHIigGWR47Qq0OODedHnyuNYvEjxSvLdu +qkCVFfNhHwKBgAImh++f670qy+twuNTB3b+1/aC0XM7j5DTiTkRjT7f1TT1dmtjA +cMiCN4bvI4cWUamv/FuvYQCLSutj638cgBh3t+sGAJMSnKuafbeJRacCGypEXtLy +SV8G+schjB5gbcKIojgKrk/jdQv4lptIiZ4ksSJGUcXJBpbIw278nxZVAoGAAiRQ +iEWgsAfHgkuDqJjgl2ugmOktAGlpGmKQEmZxUHfwVSyIkerOI5in0wQyqxiTkbQo +VPEpU1qJmso2qliqMME9zyqFgWHej22TXL//9/ADAadu5jHexNnXAJmLbXDTSWC/ +w8eEbjNz4vyewtnYYPHcrzksol6mSvxpKz7LLVECgYB7u1UROLePGqZtvwwezO06 +0BnMKBVptULLU5bqCu1nFDlqf76pJupjBoL9P1ZbluPI0EhHK3QmlaE2pyC4z/ha +976FbyZGetl3y/wrxru6zUKKaHS/PFlMwSxwFsnAp+ytplNLUqxmnCdY1ydzEIGr +heiiG7mwv7c03YOk+0C37A== +-----END PRIVATE KEY----- diff --git a/packaging/java/build.gradle b/packaging/java/build.gradle index 348874b4b7..777337d78d 100644 --- a/packaging/java/build.gradle +++ b/packaging/java/build.gradle @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import org.apache.tools.ant.filters.ReplaceTokens +import org.redline_rpm.header.Flags plugins { id "com.netflix.nebula.ospackage" version "12.1.1" @@ -38,6 +39,23 @@ ospackage { into "bin" } + from("${buildDir}/control/launcher") { + rename { String fileName -> + "${pkgName}" + } + filePermissions { + unix('r-x------') // 0500 + } + into "bin" + } + + from("${buildDir}/control/java-env") { + filePermissions { + unix('rw-r--r--') // 0644 + } + into "bin" + } + if("${pkgCopyInstallScripts}".equalsIgnoreCase("true")) { // Copy the install files from("${buildDir}/bin/install/install.sh") { @@ -91,11 +109,18 @@ buildRpm { archiveFileName = "${pkgName}.rpm" - // Support Java 25 (current), plus Java 21 and Java 17 (backward compatibility) for RPM-based distros - // Keep using RPM boolean expression syntax since .or() chaining is for DEB only - requires("(java-17 or java-17-headless or jre-17 or jre-17-headless or " + - "java-21 or java-21-headless or jre-21 or jre-21-headless or " + - "java-25 or java-25-headless or jre-25 or jre-25-headless)") + // The RPM writer overwrites the file in place without truncating it, so a smaller rebuild keeps stale bytes + doFirst { + archiveFile.get().asFile.delete() + } + + // RPM boolean expression syntax, since .or() chaining is for DEB only + requires("(java-${pkgMinJavaVersion} or java-${pkgMinJavaVersion}-headless or jre-${pkgMinJavaVersion} or jre-${pkgMinJavaVersion}-headless)") + requires("shadow-utils", "", Flags.SCRIPT_PRE) + if ("${pkgRequiresFonts}".equalsIgnoreCase("true")) { + requires("fontconfig") + requires("dejavu-sans-fonts") + } from("${buildDir}/conf") { include "${pkgName}.conf" @@ -138,9 +163,14 @@ buildDeb { archiveFileName = "${pkgName}.deb" - requires("openjdk-17-jre").or("java17-runtime").or("oracle-java17-installer").or("openjdk-17-jre-headless") - .or("openjdk-21-jre").or("java21-runtime").or("oracle-java21-installer").or("openjdk-21-jre-headless") - .or("openjdk-25-jre").or("java25-runtime").or("oracle-java25-installer").or("openjdk-25-jre-headless") + requires("openjdk-${pkgMinJavaVersion}-jre").or("java${pkgMinJavaVersion}-runtime").or("oracle-java${pkgMinJavaVersion}-installer").or("openjdk-${pkgMinJavaVersion}-jre-headless") + preDepends("adduser") + if ("${pkgRequiresFonts}".equalsIgnoreCase("true")) { + requires("fontconfig") + requires("fonts-dejavu-core") + // Debian and Ubuntu OpenJDK builds load the system HarfBuzz for text layout but only recommend it + requires("libharfbuzz0b") + } from("${buildDir}/conf") { include "${pkgName}.conf" diff --git a/packaging/java/scripts/control/deb/postinst b/packaging/java/scripts/control/deb/postinst index 6ec2dff6bf..4eeaa1d4c3 100644 --- a/packaging/java/scripts/control/deb/postinst +++ b/packaging/java/scripts/control/deb/postinst @@ -11,6 +11,7 @@ chown -R ${pkg.user}: ${pkg.installFolder} # directory are unaffected. rm -f ${pkg.installFolder}/extensions/rule-node-twilio-sms*.jar +systemctl daemon-reload >/dev/null 2>&1 || : systemctl --no-reload enable ${pkg.name}.service >/dev/null 2>&1 || : exit 0 diff --git a/packaging/java/scripts/control/java-env b/packaging/java/scripts/control/java-env new file mode 100644 index 0000000000..c4f3e1ef55 --- /dev/null +++ b/packaging/java/scripts/control/java-env @@ -0,0 +1,21 @@ +# +# SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +# SPDX-License-Identifier: BUSL-1.1 +# + +if [ -n "$JAVA_HOME" ] && [ -x "$JAVA_HOME/bin/java" ]; then + javaexe="$JAVA_HOME/bin/java" +else + javaexe=java +fi + +require_java() { + local javaVersion javaMajor + javaVersion=$(JAVA_TOOL_OPTIONS= JDK_JAVA_OPTIONS= "$1" -version 2>&1 | sed -n 's/.*version "\([^"]*\)".*/\1/p' | head -n 1) + javaMajor=$(echo "$javaVersion" | sed -e 's/^1\.//' -e 's/^\([0-9]*\).*/\1/') + if [ -z "$javaMajor" ] || [ "$javaMajor" -lt ${pkg.minJavaVersion} ]; then + echo "${pkg.name} requires Java ${pkg.minJavaVersion} or later, but '$1' is ${javaVersion:-not a working Java}." >&2 + echo "Select Java ${pkg.minJavaVersion} or later with 'update-alternatives --config java' (deb) or 'alternatives --config java' (rpm), or set JAVA_HOME in $CONF_FOLDER/${pkg.name}.conf." >&2 + exit 78 + fi +} diff --git a/packaging/java/scripts/control/launcher b/packaging/java/scripts/control/launcher new file mode 100755 index 0000000000..c6cdac7979 --- /dev/null +++ b/packaging/java/scripts/control/launcher @@ -0,0 +1,22 @@ +#!/bin/bash +# +# SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +# SPDX-License-Identifier: BUSL-1.1 +# + +[ -z "$CONF_FOLDER" ] && CONF_FOLDER=${pkg.installFolder}/conf +jarfile=${pkg.installFolder}/bin/${pkg.name}.jar + +[ -r "$CONF_FOLDER/${pkg.name}.conf" ] && source "$CONF_FOLDER/${pkg.name}.conf" + +javaenv=${pkg.installFolder}/bin/java-env +if [ ! -r "$javaenv" ]; then + echo "Cannot read $javaenv; reinstall ${pkg.name}." >&2 + exit 1 +fi +source "$javaenv" + +require_java "$javaexe" + +cd "$(dirname "$jarfile")" || exit 1 +exec "$javaexe" $JAVA_OPTS -jar "$jarfile" $RUN_ARGS "$@" diff --git a/packaging/java/scripts/control/rpm/postinst b/packaging/java/scripts/control/rpm/postinst index 99cac70253..998b2799de 100644 --- a/packaging/java/scripts/control/rpm/postinst +++ b/packaging/java/scripts/control/rpm/postinst @@ -9,6 +9,8 @@ chown -R ${pkg.user}: ${pkg.installFolder} # directory are unaffected. rm -f ${pkg.installFolder}/extensions/rule-node-twilio-sms*.jar +systemctl daemon-reload >/dev/null 2>&1 || : + if [ $1 -eq 1 ] ; then # Initial installation systemctl --no-reload enable ${pkg.name}.service >/dev/null 2>&1 || : diff --git a/packaging/java/scripts/control/template.service b/packaging/java/scripts/control/template.service index f4fa806c32..080ac8cb2d 100644 --- a/packaging/java/scripts/control/template.service +++ b/packaging/java/scripts/control/template.service @@ -4,8 +4,10 @@ After=syslog.target [Service] User=${pkg.user} -ExecStart=${pkg.installFolder}/bin/${pkg.name}.jar +ExecStart=${pkg.installFolder}/bin/${pkg.name} SuccessExitStatus=143 +# The launcher exits with 78 when the selected Java is older than ${pkg.minJavaVersion}; restarting cannot fix that. +RestartPreventExitStatus=78 # Service shall be restarted in 30 seconds when the service process exits, is killed, or a timeout is reached. # Restart parameter default value 'no' diff --git a/packaging/java/scripts/install/install.sh b/packaging/java/scripts/install/install.sh index 5bde590c27..b65bd19dcb 100755 --- a/packaging/java/scripts/install/install.sh +++ b/packaging/java/scripts/install/install.sh @@ -28,9 +28,18 @@ installDir=${pkg.installFolder}/data source "${CONF_FOLDER}/${configfile}" +javaenv=${pkg.installFolder}/bin/java-env +if [ ! -r "$javaenv" ]; then + echo "Cannot read $javaenv; reinstall ${pkg.name}." >&2 + exit 1 +fi +source "$javaenv" + +require_java "$javaexe" + run_user=${pkg.user} -su -s /bin/sh -c "java -cp ${jarfile} $JAVA_OPTS -Dloader.main=org.thingsboard.server.ThingsboardInstallApplication \ +su -s /bin/sh -c "'$javaexe' -cp ${jarfile} $JAVA_OPTS -Dloader.main=org.thingsboard.server.ThingsboardInstallApplication \ -Dinstall.data_dir=${installDir} \ -Dspring.jpa.hibernate.ddl-auto=none \ -Dinstall.upgrade=false \ diff --git a/packaging/java/scripts/install/upgrade.sh b/packaging/java/scripts/install/upgrade.sh index c1b7cbcf7e..ae214332e7 100755 --- a/packaging/java/scripts/install/upgrade.sh +++ b/packaging/java/scripts/install/upgrade.sh @@ -31,6 +31,15 @@ installDir=${pkg.installFolder}/data source "${CONF_FOLDER}/${configfile}" +javaenv=${pkg.installFolder}/bin/java-env +if [ ! -r "$javaenv" ]; then + echo "Cannot read $javaenv; reinstall ${pkg.name}." >&2 + exit 1 +fi +source "$javaenv" + +require_java "$javaexe" + run_user=${pkg.user} # 4.4 folded the twilio rule nodes into the boot jar; the leftover extension jar is an unrelocated @@ -38,7 +47,7 @@ run_user=${pkg.user} # are upgraded without the deb/rpm control scripts. rm -f ${pkg.installFolder}/extensions/rule-node-twilio-sms*.jar -su -s /bin/sh -c "java -cp ${jarfile} $JAVA_OPTS -Dloader.main=org.thingsboard.server.ThingsboardInstallApplication \ +su -s /bin/sh -c "'$javaexe' -cp ${jarfile} $JAVA_OPTS -Dloader.main=org.thingsboard.server.ThingsboardInstallApplication \ -Dinstall.data_dir=${installDir} \ -Dspring.jpa.hibernate.ddl-auto=none \ -Dinstall.upgrade=true \ diff --git a/packaging/java/scripts/windows/install.bat b/packaging/java/scripts/windows/install.bat index 59a3fa15cd..6aed48556c 100644 --- a/packaging/java/scripts/windows/install.bat +++ b/packaging/java/scripts/windows/install.bat @@ -10,14 +10,17 @@ setlocal ENABLEEXTENSIONS @ECHO Detecting Java version installed. :CHECK_JAVA -for /f tokens^=2-5^ delims^=.-_^" %%j in ('java -fullversion 2^>^&1') do set "jver=%%j%%k" +set "jver=" +set "jmajor=0" +for /f tokens^=2^ delims^=.+-_^" %%j in ('java -fullversion 2^>^&1 ^| findstr /c:"full version"') do set "jver=%%j" @ECHO CurrentVersion %jver% -if %jver% NEQ 250 GOTO JAVA_NOT_INSTALLED +set /a jmajor=jver 2>nul +if %jmajor% LSS ${pkg.minJavaVersion} GOTO JAVA_NOT_INSTALLED :JAVA_INSTALLED -@ECHO Java 25 found! +@ECHO Java %jmajor% found! @ECHO Installing thingsboard ... SET BASE=%~dp0 @@ -49,8 +52,8 @@ POPD GOTO END :JAVA_NOT_INSTALLED -@ECHO Java 25 is not installed. Only Java 25 is supported -@ECHO Please go to https://adoptopenjdk.net/index.html and install Java 25. Then retry installation. +@ECHO Java ${pkg.minJavaVersion} or later is not installed. ThingsBoard requires Java ${pkg.minJavaVersion} or later. +@ECHO Please go to https://adoptium.net/ and install Java ${pkg.minJavaVersion}. Then retry installation. PAUSE GOTO END diff --git a/packaging/java/scripts/windows/service.xml b/packaging/java/scripts/windows/service.xml index 3d19b16353..8f0c9632f7 100644 --- a/packaging/java/scripts/windows/service.xml +++ b/packaging/java/scripts/windows/service.xml @@ -18,7 +18,6 @@ -Dinstall.data_dir=%BASE%\data -Xlog:gc*,heap*,age*,safepoint=debug:file=%BASE%\logs\gc.log:time,uptime,level,tags:filecount=10,filesize=10M -XX:+HeapDumpOnOutOfMemoryError - -XX:-UseBiasedLocking -XX:+UseTLAB -XX:+ResizeTLAB -XX:+PerfDisableSharedMem diff --git a/packaging/js/build.gradle b/packaging/js/build.gradle index 4c7d0765e4..c62e144537 100644 --- a/packaging/js/build.gradle +++ b/packaging/js/build.gradle @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +import org.redline_rpm.header.Flags + plugins { id "com.netflix.nebula.ospackage" version "12.1.1" } @@ -71,6 +73,13 @@ buildRpm { archiveFileName = "${pkgName}.rpm" + // The RPM writer overwrites the file in place without truncating it, so a smaller rebuild keeps stale bytes + doFirst { + archiveFile.get().asFile.delete() + } + + requires("shadow-utils", "", Flags.SCRIPT_PRE) + preInstall file("${buildDir}/control/rpm/preinst") postInstall file("${buildDir}/control/rpm/postinst") preUninstall file("${buildDir}/control/rpm/prerm") @@ -101,6 +110,8 @@ buildDeb { archiveFileName = "${pkgName}.deb" + preDepends("adduser") + configurationFile("${pkgInstallFolder}/conf/${pkgName}.conf") configurationFile("${pkgInstallFolder}/conf/custom-environment-variables.yml") configurationFile("${pkgInstallFolder}/conf/default.yml") diff --git a/pom.xml b/pom.xml index 334d0f4696..2dadf56746 100755 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT pom ThingsBoard @@ -73,75 +73,66 @@ module depends on the ZIP artifact, so this flag can be toggled freely without breaking downstream modules. --> false + + false thingsboard + 25 ${project.name} /var/log/${pkg.name} /usr/share/${pkg.name} control - 2.1.10-SNAPSHOT + 2.1.11-SNAPSHOT 4.4.0 - 3.5.15 - - 3.5.13 - 3.18.0 - 4.1.138.Final - 1.62.0 - 10.1.61 - 5.4.3 - 1.5.38 - 2.21.7 - 42.7.14 + 4.1.3 + 4.2.20.Final + 2.0.85.Final 1.11.4 - 5.34.0 - 5.6.4 1.5.7-14 - 2.3.35 - 2.4.0-b180830.0359 - 0.12.5 + 2.10.0 + 42.7.15 + 11.0.29 + 0.13.0 0.10 - 1.0-1 4.2.25 5.0.7 33.7.2-jre - 1.0.1 - 2.16.1 - 1.3.1 - 1.10.0 - 1.26.1 - 10.0.2 + 2.22.0 + 1.14.1 + 1.28.0 + 10.9.1 4.5.14 - 4.0.1 + 4.0.14 2.12.7 4.4.0 1.5.6 0.6.12 + 2.4.0-b180830.0359 3.12.1 2.0.0-M15 - 2.0.1 - 5.6.0 + 5.9.0 3.9.6 - 3.25.5 + 3.25.5 1.76.0 - 1.2.12 - 1.18.46 + 4.0.32 + 1.2.13 + 1.18.48 1.2.5 1.2.5 1.7.1 3.5.0 2.9.3 1.0.0 - 3.5.4 + 3.5.6 3.1.4 3.1.4 3.5.0 - 2.8.8TB - 2.2.30 + 3.1.1TB + 2.2.55 0.8 1.19.0 + 8.18.8 + 5.5.7 + 1.0-1 1.86 2.0.1 1.13.0 @@ -158,7 +149,7 @@ 8.10.1 3.5.3 0.15.12 - 20250517 + 20260719 3.1.2 1.11.4 1.12.701 @@ -176,15 +167,13 @@ 1.6.4 1.6.1 1.11.0 - 4.4 + 4.6.0 1.0.5TB 6.4.5 10.1.3 - 3.7.4 - 4.0.2 + 6.0.0 1.7.5 3.8.0 - 1.18.4 1.16.1 2.43.0 1.24 @@ -192,16 +181,12 @@ 3.42.0 0.27.0 - 2.7.3 1.5.6 5.15.0 - 1.3.0 1.2.7 5.0.0 7.10.1 - 1.21.4 - 1.0.2 1.12 6.1.0 2.27.0 @@ -223,7 +208,6 @@ 9.2.0 1.1.10.10 9.10.0 - 3.1.5.RELEASE 9.13.0 1.5.6 1.0.5 @@ -634,7 +618,6 @@ false ZIP - true true @@ -644,12 +627,6 @@ lombok - - ${pkg.installFolder}/conf - ${pkg.unixLogFolder} - ${pkg.name}.out - ${pkg.name} - @@ -681,6 +658,8 @@ -PpkgUser=${pkg.user} -PpkgInstallFolder=${pkg.installFolder} -PpkgCopyInstallScripts=${pkg.copyInstallScripts} + -PpkgMinJavaVersion=${pkg.minJavaVersion} + -PpkgRequiresFonts=${pkg.requiresFonts} -PpkgLogFolder=${pkg.unixLogFolder} -PskipDeb=${pkg.skip.deb} -PskipRpm=${pkg.skip.rpm} @@ -743,7 +722,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.11.0 + 3.15.0 25 @@ -955,7 +934,7 @@ org.apache.maven.plugins maven-enforcer-plugin - 3.5.0 + 3.6.3 org.codehaus.mojo @@ -965,6 +944,7 @@ org.apache.maven.plugins maven-dependency-plugin + 3.10.0 copy-protoc @@ -1017,7 +997,7 @@ org.codehaus.mojo build-helper-maven-plugin - 1.12 + 3.6.1 add-source @@ -1204,6 +1184,50 @@ com.mycila license-maven-plugin + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-banned-dependencies + + enforce + + + + + + javax.annotation:javax.annotation-api + org.springframework.boot:*:[,4.0.0) + org.springframework:*:[,7.0.0) + org.springframework.security:*:[,7.0.0) + org.springframework.integration:*:[,7.0.0) + tools.jackson*:* + org.testcontainers:postgresql + org.testcontainers:cassandra + org.testcontainers:jdbc + org.testcontainers:junit-jupiter + org.testcontainers:hivemq + io.hypersistence:* + org.glassfish:jakarta.el + com.datastax.oss:java-driver-core + + + + + io.netty:netty-tcnative* + + + + + com.nimbusds:nimbus-jose-jwt + + + + + + + org.apache.maven.plugins maven-clean-plugin @@ -1233,96 +1257,169 @@ - + io.netty - netty-bom + netty-resolver-dns-native-macos ${netty.version} - pom - import + osx-aarch_64 - - - org.apache.tomcat.embed - tomcat-embed-core - ${tomcat.version} + io.netty + netty-transport-native-unix-common + ${netty.version} + linux-aarch_64 - org.apache.tomcat.embed - tomcat-embed-el - ${tomcat.version} + io.netty + netty-transport-native-unix-common + ${netty.version} + linux-riscv64 - org.apache.tomcat.embed - tomcat-embed-websocket - ${tomcat.version} + io.netty + netty-transport-native-unix-common + ${netty.version} + linux-x86_64 - - - org.apache.httpcomponents.core5 - httpcore5 - ${httpcore5.version} + io.netty + netty-transport-native-unix-common + ${netty.version} + osx-x86_64 - org.apache.httpcomponents.core5 - httpcore5-h2 - ${httpcore5.version} + io.netty + netty-transport-native-unix-common + ${netty.version} + osx-aarch_64 - - - ch.qos.logback - logback-core - ${logback.version} + io.netty + netty-transport-native-epoll + ${netty.version} + linux-aarch_64 - ch.qos.logback - logback-classic - ${logback.version} + io.netty + netty-transport-native-epoll + ${netty.version} + linux-riscv64 - - - com.fasterxml.jackson - jackson-bom - ${jackson-bom.version} - pom - import + io.netty + netty-transport-native-epoll + ${netty.version} + linux-x86_64 - - - org.postgresql - postgresql - ${postgresql.version} + io.netty + netty-transport-native-io_uring + ${netty.version} + linux-aarch_64 + + + io.netty + netty-transport-native-io_uring + ${netty.version} + linux-riscv64 + + + io.netty + netty-transport-native-io_uring + ${netty.version} + linux-x86_64 + + + io.netty + netty-transport-native-kqueue + ${netty.version} + osx-aarch_64 + + + io.netty + netty-codec-native-quic + ${netty.version} + linux-x86_64 + + + io.netty + netty-codec-native-quic + ${netty.version} + linux-aarch_64 - - - com.rabbitmq - amqp-client - ${amqp-client.version} + io.netty + netty-codec-native-quic + ${netty.version} + osx-x86_64 - - - org.apache.httpcomponents.client5 - httpclient5 - ${httpclient5.version} + io.netty + netty-codec-native-quic + ${netty.version} + osx-aarch_64 - org.apache.httpcomponents.client5 - httpclient5-cache - ${httpclient5.version} + io.netty + netty-codec-native-quic + ${netty.version} + windows-x86_64 - org.apache.httpcomponents.client5 - httpclient5-fluent - ${httpclient5.version} + io.netty + netty-tcnative + ${netty-tcnative.version} + linux-x86_64 + + + io.netty + netty-tcnative + ${netty-tcnative.version} + linux-x86_64-fedora + + + io.netty + netty-tcnative + ${netty-tcnative.version} + osx-x86_64 + + + io.netty + netty-tcnative + ${netty-tcnative.version} + osx-aarch_64 + + + io.netty + netty-tcnative-boringssl-static + ${netty-tcnative.version} + linux-x86_64 + + + io.netty + netty-tcnative-boringssl-static + ${netty-tcnative.version} + linux-aarch_64 + + + io.netty + netty-tcnative-boringssl-static + ${netty-tcnative.version} + osx-x86_64 + + + io.netty + netty-tcnative-boringssl-static + ${netty-tcnative.version} + osx-aarch_64 + + + io.netty + netty-tcnative-boringssl-static + ${netty-tcnative.version} + windows-x86_64 - com.github.luben @@ -1330,13 +1427,6 @@ ${zstd-jni.version} - - - org.freemarker - freemarker - ${freemarker.version} - - org.apache.pulsar pulsar-bom @@ -1344,15 +1434,6 @@ pom import - - - io.opentelemetry - opentelemetry-bom - ${opentelemetry.version} - pom - import - - at.yawk.lz4 @@ -1372,6 +1453,58 @@ ${wire-schema.version} + + com.google.protobuf + protobuf-bom + ${protobuf.version} + pom + import + + + io.grpc + grpc-bom + ${grpc.version} + pom + import + + + org.apache.groovy + groovy-bom + ${groovy.version} + pom + import + + + + org.conscrypt + conscrypt-openjdk-uber + ${conscrypt.version} + + + + + org.postgresql + postgresql + ${postgresql.version} + + + + + org.apache.tomcat.embed + tomcat-embed-core + ${tomcat.version} + + + org.apache.tomcat.embed + tomcat-embed-el + ${tomcat.version} + + + org.apache.tomcat.embed + tomcat-embed-websocket + ${tomcat.version} + + org.springframework.boot spring-boot-dependencies @@ -1380,14 +1513,37 @@ import - net.bytebuddy - byte-buddy - ${bytebuddy.version} + org.springframework.boot + spring-boot-starter-webmvc + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-jackson + + + + + org.springframework.boot + spring-boot-starter-webclient + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-jackson + + - net.bytebuddy - byte-buddy-agent - ${bytebuddy.version} + org.springframework.boot + spring-boot-starter-websocket + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-jackson + + dev.langchain4j @@ -1745,11 +1901,6 @@ test-jar test - - javax.xml.bind - jaxb-api - ${javax.xml.bind-api.version} - org.springframework.boot spring-boot-starter-test @@ -1762,30 +1913,11 @@ - - - org.springframework.boot - spring-boot-test - ${spring-boot-test.version} - - - org.springframework.boot - spring-boot-test-autoconfigure - ${spring-boot-test.version} - org.apache.kafka kafka-clients ${kafka.version} - - com.github.springtestdbunit - spring-test-dbunit - ${spring-test-dbunit.version} - test - io.jsonwebtoken jjwt @@ -1796,11 +1928,6 @@ antlr ${antlr.version} - - com.sun.mail - jakarta.mail - ${mail.version} - org.apache.curator curator-recipes @@ -1826,29 +1953,20 @@ io.netty netty-resolver-dns-native-macos + ${netty.version} osx-x86_64 io.netty netty-transport-native-kqueue + ${netty.version} osx-x86_64 - - - com.github.stephenc.jcip - jcip-annotations - ${jcip-annotations.version} - io.dropwizard.metrics metrics-jmx ${metrics.version} - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - commons-io commons-io @@ -1859,11 +1977,6 @@ commons-compress ${commons-compress.version} - - commons-logging - commons-logging - ${commons-logging.version} - org.apache.commons commons-csv @@ -1938,6 +2051,11 @@ ${milo.version} test + + javax.xml.bind + jaxb-api + ${javax.xml.bind-api.version} + org.eclipse.californium element-connector @@ -1955,101 +2073,6 @@ guava ${guava.version} - - org.jspecify - jspecify - ${jspecify.version} - - - com.google.protobuf - protobuf-java - ${protobuf.version} - - - com.google.protobuf - protobuf-java-util - ${protobuf.version} - - - io.grpc - grpc-netty-shaded - ${grpc.version} - - - io.grpc - grpc-protobuf - ${grpc.version} - - - io.grpc - grpc-protobuf-lite - ${grpc.version} - - - io.grpc - grpc-rls - ${grpc.version} - - - io.grpc - grpc-util - ${grpc.version} - - - io.grpc - grpc-googleapis - ${grpc.version} - - - io.grpc - grpc-xds - ${grpc.version} - - - io.grpc - grpc-services - ${grpc.version} - - - io.grpc - grpc-context - ${grpc.version} - - - io.grpc - grpc-inprocess - ${grpc.version} - - - io.grpc - grpc-core - ${grpc.version} - - - io.grpc - grpc-grpclb - ${grpc.version} - - - io.grpc - grpc-stub - ${grpc.version} - - - io.grpc - grpc-alts - ${grpc.version} - - - io.grpc - grpc-auth - ${grpc.version} - - - io.grpc - grpc-api - ${grpc.version} - org.thingsboard tbel @@ -2096,12 +2119,6 @@ ${allure-maven.version} test - - org.dbunit - dbunit - ${dbunit.version} - test - org.eclipse.paho org.eclipse.paho.client.mqttv3 @@ -2117,10 +2134,31 @@ curator-x-discovery ${curator.version} + + org.elasticsearch.client + elasticsearch-rest-client + ${elasticsearch-rest-client.version} + + + io.rest-assured + rest-assured + ${rest-assured.version} + + + com.github.stephenc.jcip + jcip-annotations + ${jcip-annotations.version} + org.thingsboard springdoc-openapi-starter-webmvc-ui ${springdoc-swagger.version} + + + org.springframework.boot + spring-boot-jackson + + io.swagger.core.v3 @@ -2211,6 +2249,12 @@ com.google.cloud google-cloud-pubsub ${pubsub.client.version} + + + javax.annotation + javax.annotation-api + + com.google.auth @@ -2226,6 +2270,12 @@ com.google.cloud google-cloud-recaptchaenterprise ${google-recaptcha-enterprise.version} + + + javax.annotation + javax.annotation-api + + com.google.http-client @@ -2349,14 +2399,9 @@ - io.hypersistence - hypersistence-utils-hibernate-63 - ${hypersistence-utils.version} - - - org.glassfish - jakarta.el - ${jakarta.el.version} + org.glassfish.expressly + expressly + ${expressly.version} org.owasp.antisamy @@ -2382,38 +2427,6 @@ snmp4j ${snmp4j.version} - - org.testcontainers - testcontainers - ${testcontainers.version} - test - - - junit - junit - - - - - - software.xdev - testcontainers-junit4-mock - ${testcontainers-junit4-mock.version} - test - - - org.testcontainers - junit-jupiter - ${testcontainers.version} - test - - - junit - junit - - - org.zeroturnaround zt-exec @@ -2475,6 +2488,10 @@ firebase-admin ${firebase-admin.version} + + javax.annotation + javax.annotation-api + commons-logging commons-logging @@ -2543,11 +2560,6 @@ rocksdbjni ${rocksdbjni.version} - - org.thymeleaf - thymeleaf - ${thymeleaf.version} - org.xhtmlrenderer flying-saucer-pdf @@ -2619,6 +2631,14 @@ thingsboard-public-repo https://repo.thingsboard.io/artifactory/libs-release-public + + + thingsboard-repo + https://repo.thingsboard.io/artifactory/libs-release-local + + false + + spring-snapshots Spring Snapshots @@ -2652,7 +2672,7 @@ - thingsboard-repo + thingsboard-public-repo https://repo.thingsboard.io/artifactory/libs-release-public diff --git a/report/pom.xml b/report/pom.xml index 4e99e1b42f..ec121acb46 100644 --- a/report/pom.xml +++ b/report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard report @@ -28,6 +28,7 @@ tb-report ${project.build.directory}/windows true + true ThingsBoard Report Service org.thingsboard.server.report.ThingsboardReportApplication @@ -106,6 +107,14 @@ assertj-core test + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 + diff --git a/report/src/main/resources/tb-report.yml b/report/src/main/resources/tb-report.yml index ad41603ead..959d58752e 100644 --- a/report/src/main/resources/tb-report.yml +++ b/report/src/main/resources/tb-report.yml @@ -10,6 +10,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8081}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" # Application info parameters # Provides metadata about the application build, including the current version string. diff --git a/rest-client/pom.xml b/rest-client/pom.xml index 6ef87dde9b..1e6381f6ab 100644 --- a/rest-client/pom.xml +++ b/rest-client/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard rest-client diff --git a/rest-client/src/main/java/org/thingsboard/rest/client/RestClient.java b/rest-client/src/main/java/org/thingsboard/rest/client/RestClient.java index ad40daa707..38ab8978b5 100644 --- a/rest-client/src/main/java/org/thingsboard/rest/client/RestClient.java +++ b/rest-client/src/main/java/org/thingsboard/rest/client/RestClient.java @@ -24,6 +24,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.support.HttpRequestWrapper; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -325,7 +326,7 @@ public class RestClient implements Closeable { public enum AuthType {JWT, API_KEY} public RestClient(String baseURL) { - this(new RestTemplate(), baseURL); + this(newRestTemplate(), baseURL); } public RestClient(RestTemplate restTemplate, String baseURL) { @@ -338,7 +339,8 @@ public class RestClient implements Closeable { public RestClient(RestTemplate restTemplate, String baseURL, AuthType authType, String token) { this.restTemplate = restTemplate; - this.loginRestTemplate = new RestTemplate(restTemplate.getRequestFactory()); + this.loginRestTemplate = newRestTemplate(); + this.loginRestTemplate.setRequestFactory(restTemplate.getRequestFactory()); this.baseURL = baseURL; this.restTemplate.getInterceptors().add((request, bytes, execution) -> { HttpRequest wrapper = new HttpRequestWrapper(request); @@ -371,13 +373,23 @@ public class RestClient implements Closeable { } public static RestClient withApiKey(String baseURL, String token) { - return withApiKey(new RestTemplate(), baseURL, token); + return withApiKey(newRestTemplate(), baseURL, token); } public static RestClient withApiKey(RestTemplate rt, String baseURL, String token) { return new RestClient(rt, baseURL, AuthType.API_KEY, token); } + // Spring 7 defaults to Jackson 3 when it is on the classpath; Spring 6 already uses Jackson 2 + @SuppressWarnings("removal") + private static RestTemplate newRestTemplate() { + RestTemplate restTemplate = new RestTemplate(); + restTemplate.getMessageConverters().replaceAll(converter -> + converter.getClass().getName().equals("org.springframework.http.converter.json.JacksonJsonHttpMessageConverter") ? + new MappingJackson2HttpMessageConverter() : converter); + return restTemplate; + } + public String getToken() { return mainToken; } @@ -4812,9 +4824,10 @@ public class RestClient implements Closeable { return listToString(list.stream().map(Enum::name).collect(Collectors.toList())); } + @SuppressWarnings("removal") private HttpEntity> createMultipartRequest(String fileName, byte[] fileData, String fileContentType, Map otherParts) { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.set(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE); MultiValueMap fileMap = new LinkedMultiValueMap<>(); fileMap.add(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=file; filename=" + fileName); @@ -5135,6 +5148,7 @@ public class RestClient implements Closeable { return response.getBody(); } + @SuppressWarnings("removal") public CustomMenu saveCustomMenu(CustomMenuInfo customMenuInfo, UUID[] ids, Boolean force) { Map params = new HashMap<>(); if (ids != null && ids.length > 0) { @@ -5144,13 +5158,13 @@ public class RestClient implements Closeable { params.put("force", force); } - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL + "/api/customMenu"); + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseURL + "/api/customMenu"); for (Map.Entry entry : params.entrySet()) { builder.queryParam(entry.getKey(), entry.getValue()); } - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); HttpEntity requestEntity = new HttpEntity<>(customMenuInfo, headers); return restTemplate.postForEntity(builder.toUriString(), requestEntity, CustomMenu.class).getBody(); } diff --git a/rule-engine/pom.xml b/rule-engine/pom.xml index 72c1799c23..e6b22e65a1 100644 --- a/rule-engine/pom.xml +++ b/rule-engine/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard rule-engine diff --git a/rule-engine/rule-engine-api/pom.xml b/rule-engine/rule-engine-api/pom.xml index 2d62e7812a..0dd54d0bbc 100644 --- a/rule-engine/rule-engine-api/pom.xml +++ b/rule-engine/rule-engine-api/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT rule-engine org.thingsboard.rule-engine @@ -88,8 +88,13 @@ provided - com.sun.mail - jakarta.mail + jakarta.mail + jakarta.mail-api + provided + + + org.eclipse.angus + angus-mail provided diff --git a/rule-engine/rule-engine-components/pom.xml b/rule-engine/rule-engine-components/pom.xml index b138ee6b47..56c1f833d6 100644 --- a/rule-engine/rule-engine-components/pom.xml +++ b/rule-engine/rule-engine-components/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT rule-engine org.thingsboard.rule-engine @@ -83,7 +83,11 @@ org.springframework.boot - spring-boot-starter-webflux + spring-boot-starter-webclient + + + org.springframework.boot + spring-boot-jackson2 io.projectreactor.netty @@ -118,8 +122,13 @@ bcpkix-jdk18on - com.sun.mail - jakarta.mail + jakarta.mail + jakarta.mail-api + provided + + + org.eclipse.angus + angus-mail provided diff --git a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/action/TbCopyAttributesToEntityViewNode.java b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/action/TbCopyAttributesToEntityViewNode.java index ba3ba9ae75..0789b6f293 100644 --- a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/action/TbCopyAttributesToEntityViewNode.java +++ b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/action/TbCopyAttributesToEntityViewNode.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.action; import com.google.common.util.concurrent.FutureCallback; @@ -95,7 +96,7 @@ public class TbCopyAttributesToEntityViewNode implements TbNode { .build()); } } else { - List attributes = JsonConverter.convertToAttributes(JsonParser.parseString(msg.getData())).stream() + List attributes = JsonConverter.attributesFromMsg(msg).stream() .filter(attr -> attributeContainsInEntityView(scope, attr.getKey(), entityView)).toList(); ctx.getTelemetryService().saveAttributes(AttributesSaveRequest.builder() .tenantId(ctx.getTenantId()) diff --git a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/CertPemCredentials.java b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/CertPemCredentials.java index 0404c91372..329909e5b2 100644 --- a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/CertPemCredentials.java +++ b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/CertPemCredentials.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.credentials; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -45,7 +46,7 @@ public class CertPemCredentials implements ClientCredentials { @Override public SslContext initSslContext() { try { - SslContextBuilder builder = SslContextBuilder.forClient(); + SslContextBuilder builder = SslContextBuilder.forClient().endpointIdentificationAlgorithm(null); if (StringUtils.hasLength(caCert)) { builder.trustManager(createAndInitTrustManagerFactory()); } diff --git a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/ClientCredentials.java b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/ClientCredentials.java index 8197f57178..7a01398868 100644 --- a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/ClientCredentials.java +++ b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/ClientCredentials.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.credentials; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -23,6 +24,6 @@ public interface ClientCredentials { @JsonIgnore default SslContext initSslContext() throws SSLException{ - return SslContextBuilder.forClient().build(); + return SslContextBuilder.forClient().endpointIdentificationAlgorithm(null).build(); } } diff --git a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mail/TbSendEmailNode.java b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mail/TbSendEmailNode.java index 96cf0cad8e..5e2c1a332c 100644 --- a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mail/TbSendEmailNode.java +++ b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mail/TbSendEmailNode.java @@ -116,6 +116,8 @@ public class TbSendEmailNode extends TbAbstractExternalNode { javaMailProperties.put(MAIL_PROP + protocol + ".timeout", this.config.getTimeout() + ""); javaMailProperties.put(MAIL_PROP + protocol + ".auth", String.valueOf(StringUtils.isNotEmpty(this.config.getUsername()))); javaMailProperties.put(MAIL_PROP + protocol + ".starttls.enable", Boolean.valueOf(this.config.isEnableTls()).toString()); + // Angus Mail checks the server identity unless this is set + javaMailProperties.put(MAIL_PROP + protocol + ".ssl.checkserveridentity", "false"); if (this.config.isEnableTls() && StringUtils.isNoneEmpty(this.config.getTlsVersion())) { javaMailProperties.put(MAIL_PROP + protocol + ".ssl.protocols", this.config.getTlsVersion()); } diff --git a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/azure/AzureIotHubSasCredentials.java b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/azure/AzureIotHubSasCredentials.java index fbbe5f981b..3d62ae13c4 100644 --- a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/azure/AzureIotHubSasCredentials.java +++ b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/mqtt/azure/AzureIotHubSasCredentials.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.mqtt.azure; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -31,6 +32,7 @@ public class AzureIotHubSasCredentials extends CertPemCredentials { caCert = AzureIotHubUtil.getDefaultCaCert(); } return SslContextBuilder.forClient() + .endpointIdentificationAlgorithm(null) .trustManager(createAndInitTrustManagerFactory()) .clientAuth(ClientAuth.REQUIRE) .build(); diff --git a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/profile/DeviceState.java b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/profile/DeviceState.java index 2a1619f36d..9d88a7a17e 100644 --- a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/profile/DeviceState.java +++ b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/profile/DeviceState.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.profile; import com.google.gson.JsonElement; @@ -283,7 +284,7 @@ class DeviceState { private boolean processAttributes(TbContext ctx, TbMsg msg, String scope) throws ExecutionException, InterruptedException { boolean stateChanged = false; - List attributes = JsonConverter.convertToAttributes(JsonParser.parseString(msg.getData())); + List attributes = JsonConverter.attributesFromMsg(msg); if (!attributes.isEmpty()) { SnapshotUpdate update = merge(latestValues, attributes, scope); for (DeviceProfileAlarm alarm : deviceProfile.getAlarmSettings()) { @@ -297,7 +298,7 @@ class DeviceState { } protected boolean processTelemetryRequest(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException { - return processTelemetryUpdate(ctx, msg, JsonParser.parseString(msg.getData())); + return processTelemetryUpdate(ctx, msg, JsonConverter.sortedTelemetryFromMsg(msg, msg.getMetaDataTs())); } protected boolean processTelemetryUpdatedNotification(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException { @@ -306,12 +307,11 @@ class DeviceState { .filter(JsonElement::isJsonObject) .map(e -> e.getAsJsonObject().get("timeseries")) .orElse(msgData); - return processTelemetryUpdate(ctx, msg, telemetryData); + return processTelemetryUpdate(ctx, msg, JsonConverter.convertToSortedTelemetry(telemetryData, msg.getMetaDataTs())); } - private boolean processTelemetryUpdate(TbContext ctx, TbMsg msg, JsonElement telemetryData) throws ExecutionException, InterruptedException { + private boolean processTelemetryUpdate(TbContext ctx, TbMsg msg, Map> tsKvMap) throws ExecutionException, InterruptedException { boolean stateChanged = false; - Map> tsKvMap = JsonConverter.convertToSortedTelemetry(telemetryData, msg.getMetaDataTs()); // iterate over data by ts (ASC order). for (Map.Entry> entry : tsKvMap.entrySet()) { Long ts = entry.getKey(); diff --git a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbHttpClient.java b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbHttpClient.java index 975791f2a7..72b0af7bbe 100644 --- a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbHttpClient.java +++ b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/rest/TbHttpClient.java @@ -48,7 +48,6 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.UUID; @@ -520,7 +519,7 @@ public class TbHttpClient { return ctx.transformMsg(origMsg, metaData, body); } - void headersToMetaData(Map> headers, BiConsumer consumer) { + void headersToMetaData(HttpHeaders headers, BiConsumer consumer) { if (headers == null) { return; } diff --git a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbCalculatedFieldsNode.java b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbCalculatedFieldsNode.java index a6e992e0dd..392e81724c 100644 --- a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbCalculatedFieldsNode.java +++ b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbCalculatedFieldsNode.java @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.telemetry; -import com.google.gson.JsonParser; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.rule.engine.api.EmptyNodeConfiguration; import org.thingsboard.rule.engine.api.RuleNode; @@ -54,7 +54,7 @@ public class TbCalculatedFieldsNode implements TbNode { } private void processPostTelemetryRequest(TbContext ctx, TbMsg msg) { - Map> tsKvMap = JsonConverter.convertToTelemetry(JsonParser.parseString(msg.getData()), System.currentTimeMillis()); + Map> tsKvMap = JsonConverter.telemetryFromMsg(msg, System.currentTimeMillis()); if (tsKvMap.isEmpty()) { ctx.tellSuccess(msg); @@ -84,7 +84,7 @@ public class TbCalculatedFieldsNode implements TbNode { } private void processPostAttributesRequest(TbContext ctx, TbMsg msg) { - List newAttributes = JsonConverter.convertToAttributes(JsonParser.parseString(msg.getData())); + List newAttributes = JsonConverter.attributesFromMsg(msg); if (newAttributes.isEmpty()) { ctx.tellSuccess(msg); return; diff --git a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbMsgAttributesNode.java b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbMsgAttributesNode.java index a66127734a..0b474b1159 100644 --- a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbMsgAttributesNode.java +++ b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbMsgAttributesNode.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.telemetry; import com.fasterxml.jackson.databind.JsonNode; @@ -7,7 +8,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; -import com.google.gson.JsonParser; import org.thingsboard.common.util.DonAsynchron; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.AttributesSaveRequest; @@ -115,8 +115,7 @@ public class TbMsgAttributesNode implements TbNode { ctx.tellFailure(msg, new IllegalArgumentException("Unsupported msg type: " + msg.getType())); return; } - String src = msg.getData(); - List newAttributes = JsonConverter.convertToAttributes(JsonParser.parseString(src)); + List newAttributes = JsonConverter.attributesFromMsg(msg); if (newAttributes.isEmpty()) { ctx.tellSuccess(msg); return; diff --git a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbMsgTimeseriesNode.java b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbMsgTimeseriesNode.java index be78edc6da..6c22aa3cff 100644 --- a/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbMsgTimeseriesNode.java +++ b/rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/telemetry/TbMsgTimeseriesNode.java @@ -5,7 +5,6 @@ package org.thingsboard.rule.engine.telemetry; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.gson.JsonParser; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.RuleNode; import org.thingsboard.rule.engine.api.TbContext; @@ -130,7 +129,7 @@ public class TbMsgTimeseriesNode implements TbNode { } String src = msg.getData(); - Map> tsKvMap = JsonConverter.convertToTelemetry(JsonParser.parseString(src), ts); + Map> tsKvMap = JsonConverter.telemetryFromMsg(msg, ts); if (tsKvMap.isEmpty()) { ctx.tellFailure(msg, new IllegalArgumentException("Msg body is empty: " + src)); return; diff --git a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbCopyAttributesToEntityViewNodeTest.java b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbCopyAttributesToEntityViewNodeTest.java index d35ffb1b3e..c1c426c7f1 100644 --- a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbCopyAttributesToEntityViewNodeTest.java +++ b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/action/TbCopyAttributesToEntityViewNodeTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.action; import com.google.common.util.concurrent.Futures; @@ -22,6 +23,8 @@ import org.thingsboard.rule.engine.api.TbNodeException; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.kv.AttributeKvEntry; +import org.thingsboard.server.common.data.kv.DataType; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EntityViewId; import org.thingsboard.server.common.data.id.TenantId; @@ -38,7 +41,10 @@ import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -268,6 +274,85 @@ public class TbCopyAttributesToEntityViewNodeTest { verifyNoMoreInteractions(ctxMock); } + @Test + public void givenTypeCastDisabledKeysMetadata_whenOnMsg_thenListedNumericStringIsCopiedAsString() { + TbMsgMetaData metaData = new TbMsgMetaData(Map.of(DataConstants.SCOPE, AttributeScope.CLIENT_SCOPE.name())); + metaData.putTypeCastDisabledKeys(Set.of("joinEui")); + + Map entries = copyAttributesToView(TbMsgType.POST_ATTRIBUTES_REQUEST, metaData); + + assertThat(entries.get("joinEui").getDataType()).isEqualTo(DataType.STRING); + assertThat(entries.get("joinEui").getValue()).isEqualTo("0000000000000000"); + assertThat(entries.get("firmwareVersion").getDataType()).isEqualTo(DataType.DOUBLE); + assertThat(entries.get("firmwareVersion").getValue()).isEqualTo(1.0); + } + + @Test + public void givenMetadataWithoutTypeCastDisabledKeys_whenOnMsg_thenNumericStringsAreCast() { + TbMsgMetaData metaData = new TbMsgMetaData(Map.of(DataConstants.SCOPE, AttributeScope.CLIENT_SCOPE.name())); + + Map entries = copyAttributesToView(TbMsgType.POST_ATTRIBUTES_REQUEST, metaData); + + assertThat(entries.get("joinEui").getDataType()).isEqualTo(DataType.LONG); + assertThat(entries.get("joinEui").getValue()).isEqualTo(0L); + assertThat(entries.get("firmwareVersion").getDataType()).isEqualTo(DataType.DOUBLE); + assertThat(entries.get("firmwareVersion").getValue()).isEqualTo(1.0); + } + + @Test + public void givenAttributesUpdatedWithTypeCastDisabledKeys_whenOnMsg_thenListedNumericStringIsCopiedAsString() { + TbMsgMetaData metaData = new TbMsgMetaData(Map.of(DataConstants.SCOPE, AttributeScope.CLIENT_SCOPE.name())); + metaData.putTypeCastDisabledKeys(Set.of("joinEui")); + + Map entries = copyAttributesToView(TbMsgType.ATTRIBUTES_UPDATED, metaData); + + assertThat(entries.get("joinEui").getDataType()).isEqualTo(DataType.STRING); + assertThat(entries.get("joinEui").getValue()).isEqualTo("0000000000000000"); + assertThat(entries.get("firmwareVersion").getDataType()).isEqualTo(DataType.DOUBLE); + } + + @Test + public void givenAttributesUpdatedWithoutTypeCastDisabledKeys_whenOnMsg_thenNumericStringsAreCast() { + TbMsgMetaData metaData = new TbMsgMetaData(Map.of(DataConstants.SCOPE, AttributeScope.CLIENT_SCOPE.name())); + + Map entries = copyAttributesToView(TbMsgType.ATTRIBUTES_UPDATED, metaData); + + assertThat(entries.get("joinEui").getDataType()).isEqualTo(DataType.LONG); + assertThat(entries.get("joinEui").getValue()).isEqualTo(0L); + } + + private Map copyAttributesToView(TbMsgType msgType, TbMsgMetaData metaData) { + AttributesEntityView attributes = new AttributesEntityView(List.of("joinEui", "firmwareVersion"), Collections.emptyList(), Collections.emptyList()); + EntityView entityView = getEntityView(new TelemetryEntityView(Collections.emptyList(), attributes)); + + TbMsg msg = TbMsg.newMsg() + .type(msgType) + .originator(DEVICE_ID) + .copyMetaData(metaData) + .data("{\"joinEui\": \"0000000000000000\", \"firmwareVersion\": \"1.0\"}") + .build(); + + mockEntityViewLookup(entityView); + when(ctxMock.getTelemetryService()).thenReturn(telemetryServiceMock); + doAnswer(invocation -> { + AttributesSaveRequest request = invocation.getArgument(0); + request.getCallback().onSuccess(null); + return null; + }).when(telemetryServiceMock).saveAttributes(any(AttributesSaveRequest.class)); + TbMsg newMsg = TbMsg.newMsg(msg, msg.getQueueName(), msg.getRuleChainId(), msg.getRuleNodeId()); + doAnswer(invocation -> newMsg).when(ctxMock).newMsg(any(), any(String.class), any(), any(), any(), any()); + + node.onMsg(ctxMock, msg); + + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(AttributesSaveRequest.class); + verify(telemetryServiceMock).saveAttributes(requestCaptor.capture()); + AttributesSaveRequest request = requestCaptor.getValue(); + assertThat(request.getEntityId()).isEqualTo(ENTITY_VIEW_ID); + assertThat(request.getScope()).isEqualTo(AttributeScope.CLIENT_SCOPE); + assertThat(request.getEntries().size()).isEqualTo(2); + return request.getEntries().stream().collect(Collectors.toMap(AttributeKvEntry::getKey, Function.identity())); + } + private EntityView getEntityView(TelemetryEntityView attributesEntityView, long startTimeMs, long endTimeMs) { EntityView entityView = new EntityView(ENTITY_VIEW_ID); entityView.setStartTimeMs(startTimeMs); diff --git a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/mail/TbSendEmailNodeTest.java b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/mail/TbSendEmailNodeTest.java new file mode 100644 index 0000000000..fd2e82dfd2 --- /dev/null +++ b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/mail/TbSendEmailNodeTest.java @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.rule.engine.mail; + +import org.junit.jupiter.api.Test; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.TbContext; +import org.thingsboard.rule.engine.api.TbNodeConfiguration; +import org.thingsboard.rule.engine.api.TbNodeException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +class TbSendEmailNodeTest { + + @Test + void serverIdentityCheckIsDisabled() throws TbNodeException { + TbSendEmailNodeConfiguration config = new TbSendEmailNodeConfiguration().defaultConfiguration(); + config.setUseSystemSmtpSettings(false); + config.setSmtpProtocol("smtps"); + config.setSmtpHost("10.0.0.1"); + config.setEnableTls(true); + TbSendEmailNode node = new TbSendEmailNode(); + + node.init(mock(TbContext.class), new TbNodeConfiguration(JacksonUtil.valueToTree(config))); + + JavaMailSenderImpl mailSender = (JavaMailSenderImpl) ReflectionTestUtils.getField(node, "mailSender"); + assertThat(mailSender.getJavaMailProperties()).containsEntry("mail.smtps.ssl.checkserveridentity", "false"); + } + +} diff --git a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/mqtt/TbMqttNodeTest.java b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/mqtt/TbMqttNodeTest.java index b07946ecae..34a79a9395 100644 --- a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/mqtt/TbMqttNodeTest.java +++ b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/mqtt/TbMqttNodeTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.mqtt; import io.netty.buffer.ByteBuf; @@ -172,7 +173,7 @@ public class TbMqttNodeTest extends AbstractRuleNodeUpgradeTest { .usingRecursiveComparison() .ignoringFields("ctx", "ctxLock", "sessionContext.context.ctx", "sessionContext.context.ctxLock", "sslContext") - .isEqualTo(SslContextBuilder.forClient().build()); + .isEqualTo(SslContextBuilder.forClient().endpointIdentificationAlgorithm(null).build()); } @Test diff --git a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/profile/DeviceStateTest.java b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/profile/DeviceStateTest.java index 732147c3cb..0b326c5045 100644 --- a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/profile/DeviceStateTest.java +++ b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/profile/DeviceStateTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.profile; import com.google.common.util.concurrent.Futures; @@ -10,6 +11,7 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.RuleEngineAlarmService; import org.thingsboard.rule.engine.api.TbContext; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.AlarmApiCallResult; @@ -30,14 +32,17 @@ import org.thingsboard.server.common.data.msg.TbMsgType; import org.thingsboard.server.common.data.query.BooleanFilterPredicate; import org.thingsboard.server.common.data.query.EntityKeyValueType; import org.thingsboard.server.common.data.query.FilterPredicateValue; +import org.thingsboard.server.common.data.query.StringFilterPredicate; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; import org.thingsboard.server.dao.attributes.AttributesService; import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.timeseries.TimeseriesService; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.TreeMap; import java.util.UUID; @@ -66,6 +71,10 @@ public class DeviceStateTest { when(attributesService.find(any(), any(), any(AttributeScope.class), anyCollection())).thenReturn(Futures.immediateFuture(Collections.emptyList())); when(ctx.getAttributesService()).thenReturn(attributesService); + TimeseriesService timeseriesService = mock(TimeseriesService.class); + when(timeseriesService.findLatest(any(), any(), anyCollection())).thenReturn(Futures.immediateFuture(Collections.emptyList())); + when(ctx.getTimeseriesService()).thenReturn(timeseriesService); + RuleEngineAlarmService alarmService = mock(RuleEngineAlarmService.class); when(alarmService.findLatestActiveByOriginatorAndType(any(), any(), any())).thenReturn(null); when(alarmService.createAlarm(any())).thenAnswer(invocationOnMock -> { @@ -165,6 +174,113 @@ public class DeviceStateTest { }); } + @Test + public void whenAttributeIsTypeCastDisabledKey_thenStringValueIsEvaluatedAsString() throws Exception { + DeviceProfileAlarm alarmConfig = createAlarmConfigWithStrCondition(AlarmConditionKeyType.ATTRIBUTE, "joinEui", "0000000000000000"); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DeviceState deviceState = createDeviceState(deviceId, alarmConfig); + + TbMsgMetaData metaData = new TbMsgMetaData(); + metaData.putTypeCastDisabledKeys(Set.of("joinEui")); + deviceState.process(ctx, TbMsg.newMsg() + .type(TbMsgType.POST_ATTRIBUTES_REQUEST) + .originator(deviceId) + .copyMetaData(metaData) + .data("{\"joinEui\": \"0000000000000000\"}") + .build()); + + verify(ctx).enqueueForTellNext(any(), eq("Alarm Created")); + } + + @Test + public void whenAttributeIsNotTypeCastDisabledKey_thenNumericStringIsCast() throws Exception { + DeviceProfileAlarm alarmConfig = createAlarmConfigWithStrCondition(AlarmConditionKeyType.ATTRIBUTE, "joinEui", "0000000000000000"); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DeviceState deviceState = createDeviceState(deviceId, alarmConfig); + + // Cast to the long 0, which reads back as "0" and no longer matches. + deviceState.process(ctx, TbMsg.newMsg() + .type(TbMsgType.POST_ATTRIBUTES_REQUEST) + .originator(deviceId) + .copyMetaData(TbMsgMetaData.EMPTY) + .data("{\"joinEui\": \"0000000000000000\"}") + .build()); + + verify(ctx, never()).enqueueForTellNext(any(), anyString()); + } + + @Test + public void whenAttributesUpdatedNotificationListsKey_thenStringValueIsEvaluatedAsString() throws Exception { + DeviceProfileAlarm alarmConfig = createAlarmConfigWithStrCondition(AlarmConditionKeyType.ATTRIBUTE, "joinEui", "0000000000000000"); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DeviceState deviceState = createDeviceState(deviceId, alarmConfig); + + TbMsgMetaData metaData = new TbMsgMetaData(); + metaData.putValue(DataConstants.SCOPE, DataConstants.SHARED_SCOPE); + metaData.putTypeCastDisabledKeys(Set.of("joinEui")); + deviceState.process(ctx, TbMsg.newMsg() + .type(TbMsgType.ATTRIBUTES_UPDATED) + .originator(deviceId) + .copyMetaData(metaData) + .data("{\"joinEui\": \"0000000000000000\"}") + .build()); + + verify(ctx).enqueueForTellNext(any(), eq("Alarm Created")); + } + + @Test + public void whenAttributesUpdatedNotificationDoesNotListKey_thenNumericStringIsCast() throws Exception { + DeviceProfileAlarm alarmConfig = createAlarmConfigWithStrCondition(AlarmConditionKeyType.ATTRIBUTE, "joinEui", "0000000000000000"); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DeviceState deviceState = createDeviceState(deviceId, alarmConfig); + + TbMsgMetaData metaData = new TbMsgMetaData(); + metaData.putValue(DataConstants.SCOPE, DataConstants.SHARED_SCOPE); + deviceState.process(ctx, TbMsg.newMsg() + .type(TbMsgType.ATTRIBUTES_UPDATED) + .originator(deviceId) + .copyMetaData(metaData) + .data("{\"joinEui\": \"0000000000000000\"}") + .build()); + + verify(ctx, never()).enqueueForTellNext(any(), anyString()); + } + + @Test + public void whenTelemetryIsTypeCastDisabledKey_thenStringValueIsEvaluatedAsString() throws Exception { + DeviceProfileAlarm alarmConfig = createAlarmConfigWithStrCondition(AlarmConditionKeyType.TIME_SERIES, "firmwareVersion", "1.10"); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DeviceState deviceState = createDeviceState(deviceId, alarmConfig); + + TbMsgMetaData metaData = new TbMsgMetaData(); + metaData.putTypeCastDisabledKeys(Set.of("firmwareVersion")); + deviceState.process(ctx, TbMsg.newMsg() + .type(TbMsgType.POST_TELEMETRY_REQUEST) + .originator(deviceId) + .copyMetaData(metaData) + .data("{\"firmwareVersion\": \"1.10\", \"fCnt\": \"42\"}") + .build()); + + verify(ctx).enqueueForTellNext(any(), eq("Alarm Created")); + } + + @Test + public void whenTelemetryIsNotTypeCastDisabledKey_thenNumericStringIsCast() throws Exception { + DeviceProfileAlarm alarmConfig = createAlarmConfigWithStrCondition(AlarmConditionKeyType.TIME_SERIES, "firmwareVersion", "1.10"); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DeviceState deviceState = createDeviceState(deviceId, alarmConfig); + + // Cast to the double 1.1, which reads back as "1.1" and no longer matches. + deviceState.process(ctx, TbMsg.newMsg() + .type(TbMsgType.POST_TELEMETRY_REQUEST) + .originator(deviceId) + .copyMetaData(TbMsgMetaData.EMPTY) + .data("{\"firmwareVersion\": \"1.10\"}") + .build()); + + verify(ctx, never()).enqueueForTellNext(any(), anyString()); + } + private DeviceState createDeviceState(DeviceId deviceId, DeviceProfileAlarm... alarmConfigs) { DeviceProfile deviceProfile = new DeviceProfile(); @@ -177,6 +293,17 @@ public class DeviceStateTest { deviceId, profileState, null); } + private DeviceProfileAlarm createAlarmConfigWithStrCondition(AlarmConditionKeyType keyType, String key, String value) { + AlarmConditionFilter condition = new AlarmConditionFilter(); + condition.setKey(new AlarmConditionFilterKey(keyType, key)); + condition.setValueType(EntityKeyValueType.STRING); + StringFilterPredicate predicate = new StringFilterPredicate(); + predicate.setOperation(StringFilterPredicate.StringOperation.EQUAL); + predicate.setValue(new FilterPredicateValue<>(value)); + condition.setPredicate(predicate); + return createAlarmConfig(condition); + } + private DeviceProfileAlarm createAlarmConfigWithBoolAttrCondition(String key, boolean value) { AlarmConditionFilter condition = new AlarmConditionFilter(); @@ -186,7 +313,10 @@ public class DeviceStateTest { predicate.setOperation(BooleanFilterPredicate.BooleanOperation.EQUAL); predicate.setValue(new FilterPredicateValue<>(value)); condition.setPredicate(predicate); + return createAlarmConfig(condition); + } + private DeviceProfileAlarm createAlarmConfig(AlarmConditionFilter condition) { DeviceProfileAlarm alarmConfig = new DeviceProfileAlarm(); alarmConfig.setId("MyAlarmID"); alarmConfig.setAlarmType("MyAlarm"); diff --git a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/rest/TbHttpClientTest.java b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/rest/TbHttpClientTest.java index dd3e77f241..943fd6ea15 100644 --- a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/rest/TbHttpClientTest.java +++ b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/rest/TbHttpClientTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.rest; import io.netty.channel.EventLoopGroup; @@ -14,7 +15,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; -import org.springframework.util.LinkedMultiValueMap; +import org.springframework.http.HttpHeaders; import org.thingsboard.common.util.DirectListeningExecutor; import org.thingsboard.rule.engine.api.TbContext; import org.thingsboard.server.common.data.id.DeviceId; @@ -545,9 +546,9 @@ public class TbHttpClientTest { @Test public void testHeadersToMetaData() { - Map> headers = new LinkedMultiValueMap<>(); - headers.put("Content-Type", List.of("binary")); - headers.put("Set-Cookie", List.of("sap-context=sap-client=075; path=/", "sap-token=sap-client=075; path=/")); + HttpHeaders headers = new HttpHeaders(); + headers.addAll("Content-Type", List.of("binary")); + headers.addAll("Set-Cookie", List.of("sap-context=sap-client=075; path=/", "sap-token=sap-client=075; path=/")); TbMsgMetaData metaData = new TbMsgMetaData(); diff --git a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbCalculatedFieldsNodeTest.java b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbCalculatedFieldsNodeTest.java index 0472d01611..622866feea 100644 --- a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbCalculatedFieldsNodeTest.java +++ b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbCalculatedFieldsNodeTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.rule.engine.telemetry; import org.junit.jupiter.api.BeforeEach; @@ -22,14 +23,18 @@ import org.thingsboard.rule.engine.api.TimeseriesSaveRequest; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.kv.DataType; +import org.thingsboard.server.common.data.kv.KvEntry; import org.thingsboard.server.common.data.msg.TbMsgType; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; import java.util.Map; +import java.util.Set; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.assertArg; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.then; @@ -182,4 +187,47 @@ class TbCalculatedFieldsNodeTest { )); } + @Test + void givenTelemetryMsgWithTypeCastDisabledKeys_whenOnMsg_thenListedKeysAreSavedAsStrings() { + var metadata = new TbMsgMetaData(); + metadata.putTypeCastDisabledKeys(Set.of("devAddr")); + var msg = TbMsg.newMsg() + .type(TbMsgType.POST_TELEMETRY_REQUEST) + .originator(deviceId) + .data("{\"devAddr\": \"01020304\", \"temperature\": \"22.5\"}") + .metaData(metadata) + .build(); + + node.onMsg(ctxMock, msg); + + ArgumentCaptor captor = ArgumentCaptor.forClass(TimeseriesSaveRequest.class); + then(telemetryServiceMock).should().saveTimeseries(captor.capture()); + assertThat(captor.getValue().getEntries()).extracting(KvEntry::getKey, KvEntry::getDataType, KvEntry::getValue).containsExactlyInAnyOrder( + tuple("devAddr", DataType.STRING, "01020304"), + tuple("temperature", DataType.DOUBLE, 22.5)); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void givenAttributesMsg_whenOnMsg_thenTypeCastDisabledKeysKeepStrings(boolean withTypeCastDisabledKeys) { + var metadata = new TbMsgMetaData(Map.of("scope", AttributeScope.CLIENT_SCOPE.name())); + if (withTypeCastDisabledKeys) { + metadata.putTypeCastDisabledKeys(Set.of("joinEui")); + } + var msg = TbMsg.newMsg() + .type(TbMsgType.POST_ATTRIBUTES_REQUEST) + .originator(deviceId) + .data("{\"joinEui\": \"0000000000000000\", \"hardwareVersion\": \"1.0\"}") + .metaData(metadata) + .build(); + + node.onMsg(ctxMock, msg); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AttributesSaveRequest.class); + then(telemetryServiceMock).should().saveAttributes(captor.capture()); + assertThat(captor.getValue().getEntries()).extracting(KvEntry::getKey, KvEntry::getDataType, KvEntry::getValue).containsExactlyInAnyOrder( + withTypeCastDisabledKeys ? tuple("joinEui", DataType.STRING, "0000000000000000") : tuple("joinEui", DataType.LONG, 0L), + tuple("hardwareVersion", DataType.DOUBLE, 1.0)); + } + } diff --git a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbMsgAttributesNodeTest.java b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbMsgAttributesNodeTest.java index d6b2c115a8..de5a7866e6 100644 --- a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbMsgAttributesNodeTest.java +++ b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbMsgAttributesNodeTest.java @@ -9,11 +9,13 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.AbstractRuleNodeUpgradeTest; +import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.rule.engine.api.RuleEngineTelemetryService; import org.thingsboard.rule.engine.api.TbContext; import org.thingsboard.rule.engine.api.TbNode; @@ -26,8 +28,10 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; import org.thingsboard.server.common.data.kv.BooleanDataEntry; +import org.thingsboard.server.common.data.kv.DataType; import org.thingsboard.server.common.data.kv.DoubleDataEntry; import org.thingsboard.server.common.data.kv.JsonDataEntry; +import org.thingsboard.server.common.data.kv.KvEntry; import org.thingsboard.server.common.data.kv.LongDataEntry; import org.thingsboard.server.common.data.kv.StringDataEntry; import org.thingsboard.server.common.data.msg.TbMsgType; @@ -39,12 +43,14 @@ import org.thingsboard.server.exception.DataValidationException; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import java.util.stream.Stream; import static com.google.common.util.concurrent.Futures.immediateFuture; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.assertArg; @@ -466,6 +472,46 @@ class TbMsgAttributesNodeTest extends AbstractRuleNodeUpgradeTest { then(ctxMock).should().tellSuccess(msg); } + @Test + void givenTypeCastDisabledKeysInMetadata_whenOnMsg_thenListedKeysAreSavedAsStrings() throws TbNodeException { + var metadata = new TbMsgMetaData(); + metadata.putTypeCastDisabledKeys(Set.of("joinEui", "hardwareVersion")); + + List entries = saveIntegrationAttributes(metadata); + + assertThat(entries).extracting(KvEntry::getKey, KvEntry::getDataType, KvEntry::getValue).containsExactlyInAnyOrder( + tuple("joinEui", DataType.STRING, "0000000000000000"), + tuple("hardwareVersion", DataType.STRING, "1.0"), + tuple("temperature", DataType.DOUBLE, 22.5)); + } + + @Test + void givenMetadataWithoutTypeCastDisabledKeys_whenOnMsg_thenNumericStringsAreCast() throws TbNodeException { + List entries = saveIntegrationAttributes(new TbMsgMetaData()); + + assertThat(entries).extracting(KvEntry::getKey, KvEntry::getDataType, KvEntry::getValue).containsExactlyInAnyOrder( + tuple("joinEui", DataType.LONG, 0L), + tuple("hardwareVersion", DataType.DOUBLE, 1.0), + tuple("temperature", DataType.DOUBLE, 22.5)); + } + + private List saveIntegrationAttributes(TbMsgMetaData metadata) throws TbNodeException { + config.setUpdateAttributesOnlyOnValueChange(false); + node.init(ctxMock, new TbNodeConfiguration(JacksonUtil.valueToTree(config))); + var msg = TbMsg.newMsg() + .type(TbMsgType.POST_ATTRIBUTES_REQUEST) + .originator(deviceId) + .data("{\"joinEui\": \"0000000000000000\", \"hardwareVersion\": \"1.0\", \"temperature\": \"22.5\"}") + .metaData(metadata) + .build(); + + node.onMsg(ctxMock, msg); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AttributesSaveRequest.class); + then(telemetryServiceMock).should().saveAttributes(captor.capture()); + return captor.getValue().getEntries(); + } + // Notify device backward-compatibility test @ParameterizedTest @MethodSource diff --git a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbMsgTimeseriesNodeTest.java b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbMsgTimeseriesNodeTest.java index 8a7fa59b4c..fa5370e7b6 100644 --- a/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbMsgTimeseriesNodeTest.java +++ b/rule-engine/rule-engine-components/src/test/java/org/thingsboard/rule/engine/telemetry/TbMsgTimeseriesNodeTest.java @@ -29,6 +29,7 @@ import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantProfileId; import org.thingsboard.server.common.data.kv.BasicTsKvEntry; +import org.thingsboard.server.common.data.kv.DataType; import org.thingsboard.server.common.data.kv.DoubleDataEntry; import org.thingsboard.server.common.data.kv.KvEntry; import org.thingsboard.server.common.data.kv.TsKvEntry; @@ -43,12 +44,14 @@ import org.thingsboard.server.exception.DataValidationException; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.assertArg; import static org.mockito.ArgumentMatchers.eq; @@ -606,6 +609,45 @@ public class TbMsgTimeseriesNodeTest extends AbstractRuleNodeUpgradeTest { return node; } + @Test + public void givenTypeCastDisabledKeysInMetadata_whenOnMsg_thenListedKeysAreSavedAsStrings() throws TbNodeException { + var metadata = new TbMsgMetaData(); + metadata.putTypeCastDisabledKeys(Set.of("devAddr", "firmwareVersion")); + + List entries = saveIntegrationTelemetry(metadata); + + assertThat(entries).extracting(KvEntry::getKey, KvEntry::getDataType, KvEntry::getValue).containsExactlyInAnyOrder( + tuple("devAddr", DataType.STRING, "01020304"), + tuple("firmwareVersion", DataType.STRING, "1.01"), + tuple("temperature", DataType.DOUBLE, 22.5)); + } + + @Test + public void givenMetadataWithoutTypeCastDisabledKeys_whenOnMsg_thenNumericStringsAreCast() throws TbNodeException { + List entries = saveIntegrationTelemetry(new TbMsgMetaData()); + + assertThat(entries).extracting(KvEntry::getKey, KvEntry::getDataType, KvEntry::getValue).containsExactlyInAnyOrder( + tuple("devAddr", DataType.LONG, 1020304L), + tuple("firmwareVersion", DataType.DOUBLE, 1.01), + tuple("temperature", DataType.DOUBLE, 22.5)); + } + + private List saveIntegrationTelemetry(TbMsgMetaData metadata) throws TbNodeException { + node.init(ctxMock, new TbNodeConfiguration(JacksonUtil.valueToTree(config))); + TbMsg msg = TbMsg.newMsg() + .type(TbMsgType.POST_TELEMETRY_REQUEST) + .originator(DEVICE_ID) + .copyMetaData(metadata) + .data("{\"devAddr\": \"01020304\", \"firmwareVersion\": \"1.01\", \"temperature\": \"22.5\"}") + .build(); + + node.onMsg(ctxMock, msg); + + ArgumentCaptor captor = ArgumentCaptor.forClass(TimeseriesSaveRequest.class); + verify(telemetryServiceMock).saveTimeseries(captor.capture()); + return captor.getValue().getEntries(); + } + private static Stream givenFromVersionAndConfig_whenUpgrade_thenVerifyHasChangesAndConfig() { return Stream.of( Arguments.of(0, """ diff --git a/tools/pom.xml b/tools/pom.xml index 2acb7b5877..8f8b17ae95 100644 --- a/tools/pom.xml +++ b/tools/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard tools @@ -31,7 +31,11 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 org.eclipse.paho diff --git a/tools/src/main/python/license-headers/README.md b/tools/src/main/python/license-headers/README.md index 6e2b20939e..5aa38f3ac8 100644 --- a/tools/src/main/python/license-headers/README.md +++ b/tools/src/main/python/license-headers/README.md @@ -24,7 +24,25 @@ A file whose path exists in CE is `apache` when its content without the header equals a CE version of it, or a clean merge of its CE versions, and `ce-modified` otherwise. -A file whose path does not exist in CE is `busl`, except when it needs a +A file whose path does not exist in CE but that commits after the CE commits +renamed from a CE file is `ce-modified`. The check follows the Git history of +the file's path back to the commit that added the current file; through a +merge, it follows the side whose version the merge kept. When that commit is a +rename, which Git's rename detection finds in commits other than merges and the +relicensing commit, the check follows the source path the same way from the +parent of the rename. The chain ends at a source that no commit after the CE +commits added and whose path exists in the CE commits merged into the parent of +the rename. Any other source, such as a CE file deleted and restored or a file +a merge added at a path the CE commits merged before the rename did not have, +counts as CE only when, without the header, it is at least 50% similar to the CE +version of its path; otherwise the file needs a decision, and +so does a file whose chain runs through a path that parallel branches added +separately. Git scores a rename with the header included, so each rename in the +chain counts only when the file without the header is at least 50% similar +before and after that rename; a weaker rename needs a decision. Changes made +before or after a rename do not affect its score. + +Any other file whose path does not exist in CE is `busl`, except when it needs a decision: its content is at least 50% similar to a CE file, or CE history once had this path. A `pom.xml` added under a directory that has no files in CE is `busl` even when it resembles a CE `pom.xml`: module identity, dependencies and @@ -36,9 +54,11 @@ packaging define the new artifact. ./check-license-headers.sh ``` -The check needs the full Git history of the clone. It runs Git and Mycila -subprocesses in parallel on all CPUs but one; set `LICENSE_HEADERS_JOBS` to -another number, for example `1` for a sequential run. +The check needs Git 2.43 or later, for `git merge-file --object-id`, and the +full Git history of the clone. It stops at startup on an older Git, such as the +Git that ships with macOS. It runs Git and Mycila subprocesses in parallel on +all CPUs but one; set `LICENSE_HEADERS_JOBS` to another number, for example `1` +for a sequential run. ## Cache diff --git a/tools/src/main/python/license-headers/check_license_headers.py b/tools/src/main/python/license-headers/check_license_headers.py index a01d776e43..3cbfb086f6 100644 --- a/tools/src/main/python/license-headers/check_license_headers.py +++ b/tools/src/main/python/license-headers/check_license_headers.py @@ -69,6 +69,7 @@ BLOCK_CLOSERS = {b"*/", b"-->"} | set(LINE_COMMENT_TOKENS) RESTAMP_LISTING = 40 REPEATED_HEADERS = 3 HEADER_WINDOW = 4096 +SIMILARITY = 50 XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space" JOBS_VARIABLE = "LICENSE_HEADERS_JOBS" CACHE_SIGNATURES_VARIABLE = "LICENSE_HEADERS_CACHE_SIGNATURES" @@ -108,6 +109,9 @@ STRICT_BLOCK = Style("strict_block", tuple(sorted(suffix[1:] for suffix in BLOCK )) +MERGE_FILE_REQUIREMENT = "The license header check needs Git 2.43 or later" + + class Failure(Exception): pass @@ -231,10 +235,26 @@ def merged_ce_bases(repo, head, baseline): def merge_blobs(repo, ours, base, theirs): - result = run(["git", "merge-file", "-p", "--object-id", ours, base, theirs], repo, ok=range(0, 256)) + # 255: merge-file refuses binary blobs + result = run(["git", "merge-file", "-p", "--object-id", ours, base, theirs], repo, ok=(*range(0, 128), 129, 255)) + if result.returncode == 129: + raise unsupported_merge_file(repo) return result.stdout if result.returncode == 0 else None +def merge_file_object_id_supported(): + with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: + git(temporary, "init", "--quiet") + blob = run(["git", "hash-object", "-w", "--stdin"], temporary, data=b"probe\n").stdout.decode().strip() + result = run(["git", "merge-file", "-p", "--object-id", blob, blob, blob], temporary, ok=(0, 129)) + return result.returncode == 0 + + +def unsupported_merge_file(directory): + return Failure(f"git merge-file does not support --object-id. {MERGE_FILE_REQUIREMENT}, " + f"found {git(directory, 'version').decode().strip()}.") + + def tree(repo, revision): result = {} for record in git(repo, "ls-tree", "-r", "-z", "--full-tree", revision).split(b"\0"): @@ -273,14 +293,15 @@ class Change: old: str new: str status: str + source: str def history(repo, revisions, *options): """First-parent changes of every revision in one walk: commits shared by several revisions appear once.""" if not revisions or any(revision.startswith("-") for revision in revisions): raise Failure("history needs revisions that do not start with '-'") - raw = git(repo, "log", "--first-parent", "--diff-merges=first-parent", "--root", "--raw", "--no-abbrev", - "--no-renames", "-z", "--format=%x1e%H", *options, *revisions, "--") + raw = git(repo, "log", "--no-show-signature", "--first-parent", "--diff-merges=first-parent", "--root", "--raw", + "--no-abbrev", "--no-renames", "-z", "--format=%x1e%H", *options, *revisions, "--") return list(parse_history(raw)) @@ -304,7 +325,7 @@ def parse_history(raw): if commit is None: raise Failure("Unexpected Git raw-history record") fields, status, paths = raw_change(token, tokens) - yield Change(commit, paths[0], fields[2].decode(), fields[3].decode(), status) + yield Change(commit, paths[-1], fields[2].decode(), fields[3].decode(), status, paths[0]) elif token: raise Failure(f"Unexpected Git history token: {token[:80]!r}") @@ -767,16 +788,14 @@ def normalized_copies(mycila, source_refs, names, nonempty): destinations = {("head", name) for name in names} & nonempty if not sources or not destinations: return {} - git(mycila.root, "init", "--quiet") - git(mycila.root, "config", "core.autocrlf", "false") - git(mycila.root, "config", "core.attributesFile", "/dev/null") + index_repository(mycila) before = stage(mycila, sources) after = stage(mycila, destinations) raw = git(mycila.root, "diff-tree", "--no-commit-id", "-r", "--raw", "--no-abbrev", "-z", f"-C{COPY_SIMILARITY}%", "--find-copies-harder", "-l0", before, after) keys = {path: key for key, path in mycila.paths.items()} copies = defaultdict(list) - for source, destination, similarity in parse_copies(raw): + for source, destination, similarity in parse_pairs(raw, "C"): source_key, destination_key = keys[source], keys[destination] if source_key not in sources or destination_key not in destinations: raise Failure("Normalized copy escaped the selected CE and HEAD inputs") @@ -785,6 +804,27 @@ def normalized_copies(mycila, source_refs, names, nonempty): return dict(copies) +def normalized_similarity(mycila, source, destination): + before, after = mycila.contents[source], mycila.contents[destination] + if comparison_hash(before) == comparison_hash(after): + return 100 + if not before.strip() or not after.strip(): + return 0 + index_repository(mycila) + trees = [] + for key in (source, destination): + git(mycila.root, "read-tree", "--empty") + trees.append(stage(mycila, [key])) + raw = git(mycila.root, "diff-tree", "--no-commit-id", "-r", "--raw", "--no-abbrev", "-z", "-M1%", "-l0", *trees) + return max((similarity for _, _, similarity in parse_pairs(raw, "R")), default=0) + + +def index_repository(mycila): + git(mycila.root, "init", "--quiet") + git(mycila.root, "config", "core.autocrlf", "false") + git(mycila.root, "config", "core.attributesFile", "/dev/null") + + def staged(content): """What stage() hands to Git: the size filter in front of the copy search measures exactly this.""" return content.replace(b"\r\n", b"\n") @@ -799,13 +839,13 @@ def stage(mycila, keys): return git(mycila.root, "write-tree").decode().strip() -def parse_copies(raw): +def parse_pairs(raw, kind): tokens = iter(raw.split(b"\0")) for token in tokens: token = token.lstrip(b"\n") if token: _, status, paths = raw_change(token, tokens) - if status[0] == "C": + if status[0] == kind: yield paths[0], paths[1], int(status[1:]) @@ -818,6 +858,10 @@ class Evidence: ce_versions: tuple = () identical: dict | None = None copies: tuple = () + renamed_from: tuple = () + renames: tuple = () + rename_origin: str = "ce" + unsupported_path: str | None = None deleted: dict | None = None directory_in_ce: bool = True @@ -848,6 +892,26 @@ def infer(evidence): reason = ("same path in CE, content identical" if "blob" in evidence.identical else "same path in CE, content identical to a clean merge of its CE versions") return verdict(evidence.current, "apache", reason) | versions | {"identicalTo": evidence.identical} + if evidence.renames: + first = evidence.renames[0] + source = first["from"] + renames = list(evidence.renames) + if evidence.rename_origin == "unsupported": + reason = (f"renamed from {source}, but its rename chain passes through {evidence.unsupported_path}, " + "a file type outside the check") + elif evidence.rename_origin == "ambiguous": + reason = f"renamed from {source}, but parallel branches added a file of its rename chain" + elif evidence.rename_origin == "downstream": + reason = (f"renamed from {source} in {first['commit'][:11]}, but that file was added outside CE " + f"and is less than {SIMILARITY}% similar to the CE {source}") + elif (weakest := min(evidence.renames, key=lambda rename: rename["similarity"]))["similarity"] < SIMILARITY: + reason = (f"renamed from CE {source}, but the rename of {weakest['from']} in {weakest['commit'][:11]} " + f"is {weakest['similarity']}% similar without the header, less than {SIMILARITY}%") + else: + return (verdict(evidence.current, "ce-modified", f"renamed from CE {source}") + | {"renamedFrom": list(evidence.renamed_from), "renames": renames}) + return unresolved(reason, None, renameCandidates=list(evidence.renamed_from), renames=renames, + copyCandidates=list(evidence.copies)) if evidence.module_descriptor(): return verdict(evidence.current, NON_CE, "build descriptor of a module that does not exist in CE") if evidence.copies: @@ -873,6 +937,7 @@ class Lineage: bases: tuple trees: dict deleted: dict + renames: dict @classmethod def load(cls, repo, head, bases): @@ -881,17 +946,92 @@ class Lineage: deleted = {} for change in history(repo, list(bases), "--diff-filter=D"): deleted.setdefault(change.path, {"path": change.path, "ref": change.commit + "^1", "blob": change.old}) - return cls(head=head, bases=tuple(bases), trees={base: tree(repo, base) for base in bases}, deleted=deleted) + trees = {base: tree(repo, base) for base in bases} + return cls(head=head, bases=tuple(bases), trees=trees, deleted=deleted, + renames=ce_renames(repo, head, bases, set().union(*trees.values()))) def versions(self, name): return [(base, files[name]) for base, files in self.trees.items() if name in files] -def comparable_ce_files(comparison, names): +@dataclass(frozen=True) +class RenameChain: + hops: tuple + origin: str + + @property + def source(self): + return self.hops[0].source + + +def ce_renames(repo, head, bases, ce_paths): + # The relicensing squash pairs deleted CE files with similar PE files; that is not a rename. + raw = git(repo, "log", "--no-show-signature", "-M", "-l0", "--raw", "--no-abbrev", "-z", "--diff-filter=R", + "--format=%x1e%H", head, "--not", *bases, "--") + hops = {(change.commit, change.path): change for change in parse_history(raw) if change.commit != RELICENSING_COMMIT} + sources = defaultdict(set) + for hop in hops.values(): + sources[hop.path].add(hop.source) + chains = {} + for name in sorted(set(tree(repo, head)) & set(sources) - ce_paths): + if reaches(name, sources, ce_paths): + chain = rename_chain(repo, head, bases, hops, name, ce_paths) + if chain.hops and (chain.origin == "ambiguous" or chain.source in ce_paths): + chains[name] = chain + return chains + + +def reaches(name, sources, targets): + seen, pending = set(), [name] + while pending: + path = pending.pop() + if path in targets: + return True + if path not in seen: + seen.add(path) + pending.extend(sources.get(path, ())) + return False + + +def rename_chain(repo, head, bases, hops, name, ce_paths): + chain, revision = [], head + while True: + added = creations(repo, revision, bases, name) + if not added: + origin = "ce" if in_ce_history(repo, revision, bases, name) else "downstream" + return RenameChain(tuple(reversed(chain)), origin) + if not all(contains(repo, older, added[0]) for older in added[1:]): + renamed = sorted((hops[(commit, name)] for commit in added if (commit, name) in hops), + key=lambda hop: hop.source not in ce_paths) + return RenameChain(tuple(reversed(chain + renamed[:1])), "ambiguous") + hop = hops.get((added[0], name)) + if hop is None: + return RenameChain(tuple(reversed(chain)), "downstream") + chain.append(hop) + name, revision = hop.source, hop.commit + "^" + + +def in_ce_history(repo, revision, bases, path): + ancestors = {ancestor for base in bases for ancestor in + run(["git", "merge-base", "--all", revision, base], repo, ok=(0, 1)).stdout.decode().split()} + return any(run(["git", "cat-file", "-e", f"{ancestor}:{path}"], repo, ok=(0, 1, 128)).returncode == 0 + for ancestor in ancestors) + + +def creations(repo, revision, bases, path): + return git(repo, "--literal-pathspecs", "log", "--no-show-signature", "--no-follow", "--topo-order", "--no-renames", + "--diff-filter=A", "--format=%H", revision, "--not", *bases, "--", path).decode().split() + + +def same_type(names): suffixes = {PurePosixPath(name).suffix for name in names} - {""} extensionless = {PurePosixPath(name).name for name in names if not PurePosixPath(name).suffix} - return {path: oid for path, oid in comparison.items() - if PurePosixPath(path).suffix in suffixes or PurePosixPath(path).name in extensionless} + return lambda path: PurePosixPath(path).suffix in suffixes or PurePosixPath(path).name in extensionless + + +def comparable_ce_files(comparison, names): + comparable = same_type(names) + return {path: oid for path, oid in comparison.items() if comparable(path)} @dataclass(frozen=True) @@ -902,12 +1042,25 @@ class Comparison: normalized: dict copies: dict merges: dict + rename_similarities: dict + source_similarities: dict + unsupported_renames: dict ce_directories: frozenset size_filter: bool | None = None def classify(self, name, curation): key = ("head", name) versions = self.lineage.versions(name) + chain = None if versions else self.lineage.renames.get(name) + renamed_from = tuple({"path": chain.source, "ref": base, "blob": oid} + for base, oid in self.lineage.versions(chain.source)) if chain else () + renames = tuple({"commit": hop.commit, "from": hop.source, "to": hop.path, + "similarity": self.rename_similarities.get(hop)} for hop in chain.hops) if chain else () + origin = chain.origin if chain else "ce" + if name in self.unsupported_renames: + origin = "unsupported" + elif origin == "downstream" and self.source_similarities[name] >= SIMILARITY: + origin = "ce" identical = next(({"path": name, "ref": base, "blob": oid} for base, oid in versions if self.normalized[(name, oid)] == self.normalized[key]), self.merges.get(name)) copies = sorted(self.copies.get(name, []), key=lambda copy: (-copy["similarity"], copy["path"])) @@ -919,6 +1072,10 @@ class Comparison: ce_versions=tuple({"path": name, "ref": base, "blob": oid} for base, oid in versions), identical=identical, copies=tuple(copies), + renamed_from=renamed_from, + renames=renames, + rename_origin=origin, + unsupported_path=self.unsupported_renames.get(name), deleted=self.lineage.deleted.get(name), directory_in_ce=str(PurePosixPath(name).parent) in self.ce_directories, )) @@ -1110,6 +1267,15 @@ def could_shrink_to_copy(raw_size, destinations): def compare(repo, plugin, lineage, contents, cache, in_scope): names = list(contents) new_paths = {name for name in names if not lineage.versions(name)} + supported = same_type(in_scope) + renames, unsupported_renames = {}, {} + for name in new_paths & set(lineage.renames): + chain = lineage.renames[name] + unsupported = next((hop.source for hop in chain.hops if not supported(hop.source)), None) + if unsupported is None: + renames[name] = chain + else: + unsupported_renames[name] = unsupported # Copy sources follow every path in scope that CE lacks, not only the checked ones: with --since they would # otherwise depend on the files a pull request changes and miss copies that a full run finds. Without new paths # nothing is searched for copies, so no CE file needs to be read for it. @@ -1119,14 +1285,20 @@ def compare(repo, plugin, lineage, contents, cache, in_scope): for name in names: if name in files: sources.setdefault((name, files[name]), base) + for source in (chain.source for chain in renames.values()): + if source in files: + sources.setdefault((source, files[source]), base) for key in comparable_ce_files(files, copy_source_types).items(): sources.setdefault(key, base) versions = {(name, oid) for name in names for _, oid in lineage.versions(name)} + versions |= {(chain.source, oid) for chain in renames.values() for _, oid in lineage.versions(chain.source)} + hops = {hop for chain in renames.values() for hop in chain.hops} + hop_blobs = {(path, oid) for hop in hops for path, oid in ((hop.source, hop.old), (hop.path, hop.new))} # Git breaks ties between equally similar copy sources by path. Sources are staged in key order, padded so that # paths sort like ranks: --since, a full run and the size filter all present any two sources in the same order. slots = {("head", name): f"{index:08d}" for index, name in enumerate(sorted(names))} slots |= {key: f"{index:08d}" for index, key in enumerate(sorted(sources))} - bytes_by_id = blobs(repo, [oid for _, oid in sources]) + bytes_by_id = blobs(repo, [oid for _, oid in sources] + [oid for _, oid in hop_blobs]) with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: mycila = Mycila(repo, Path(temporary), plugin) for name, content in contents.items(): @@ -1135,9 +1307,10 @@ def compare(repo, plugin, lineage, contents, cache, in_scope): recognized = mycila.current_headers([("head", name) for name in names]) console.end() console.begin("Comparing against CE") - head_hashes, copy_sources = parallel(lambda job: job(), [ + head_hashes, copy_sources, hop_contents = parallel(lambda job: job(), [ mycila.strip_headers, - lambda: normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in versions})]) + lambda: normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in versions}), + lambda: normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in hop_blobs})]) headers = mycila.header_states(recognized) destinations = {name: mycila.contents[("head", name)] for name in sorted(new_paths) if mycila.contents[("head", name)].strip()} @@ -1145,6 +1318,8 @@ def compare(repo, plugin, lineage, contents, cache, in_scope): copies, searched, size_filter = copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, destinations, copy_sources) normalized |= searched + rename_similarities, source_similarities = rename_scores(repo, plugin, lineage, renames, hops, + hop_contents | copy_sources) merges = clean_merges(repo, plugin, cache, lineage, names, normalized) console.end(f"done ({len(normalized)} file versions, {len(searched)} of {len(sources) - len(versions)} " f"other CE files searched for copies, {cache.hits} from the cache)") @@ -1155,12 +1330,30 @@ def compare(repo, plugin, lineage, contents, cache, in_scope): normalized=normalized, copies=copies, merges=merges, + rename_similarities=rename_similarities, + source_similarities=source_similarities, + unsupported_renames=unsupported_renames, ce_directories=frozenset(str(parent) for files in lineage.trees.values() for path in files for parent in PurePosixPath(path).parents), size_filter=size_filter, ) +def rename_scores(repo, plugin, lineage, renames, hops, normalized_contents): + """Header-free similarity of each rename hop, and of each downstream chain's first source to its CE versions.""" + with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: + staging = Mycila(repo, Path(temporary), plugin) + for key, content in normalized_contents.items(): + staging.add(key, key[0], content) + hop_similarities = {hop: normalized_similarity(staging, (hop.source, hop.old), (hop.path, hop.new)) + for hop in hops} + source_similarities = {name: max((normalized_similarity(staging, (chain.source, chain.hops[0].old), + (chain.source, oid)) + for _, oid in lineage.versions(chain.source)), default=0) + for name, chain in renames.items() if chain.origin == "downstream"} + return hop_similarities, source_similarities + + def copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, destinations, copy_sources): """CE files similar to the paths that CE does not have, normalized only when Git could match them by size; the comparison hashes of the other CE files searched for them; and whether the size filter was used, None when there @@ -1346,12 +1539,15 @@ def describe_mismatch(row): def describe_unresolved(row, ref_names): hint = f" (hint: {row['suggestedHeader']})" if row.get("suggestedHeader") else "" details = [f"has {header_name(row['currentHeader'])}, no expected header yet{hint}"] - evidence = [(f"similar CE file ({candidate['similarity']}%)", candidate) - for candidate in row.get("copyCandidates", [])] + if "renames" in row: + details.append(row["reason"]) + evidence = [("rename source in CE", candidate) for candidate in row.get("renameCandidates", [])] + evidence += [(f"similar CE file ({candidate['similarity']}%)", candidate) + for candidate in row.get("copyCandidates", [])] if "historicalCandidate" in row: evidence.append(("CE history", row["historicalCandidate"])) if not evidence: - return details + [row["reason"]] + return details if "renames" in row else details + [row["reason"]] label, candidate = evidence[0] details.append(f"{label}: {candidate['path']} at {ref_name(candidate['ref'], ref_names)}") others = len(evidence) - 1 @@ -1520,6 +1716,8 @@ def prune_curations(path, rows, orphaned): def check(args): repo = repository_root() + if not merge_file_object_id_supported(): + raise unsupported_merge_file(repo) head = resolve(repo, "HEAD") if args.ce_ref: console.begin(f"Fetching {args.ce_ref} from {args.ce_remote}") diff --git a/tools/src/main/python/license-headers/curations.json b/tools/src/main/python/license-headers/curations.json index 1087d63225..ce7711b735 100644 --- a/tools/src/main/python/license-headers/curations.json +++ b/tools/src/main/python/license-headers/curations.json @@ -11,7 +11,7 @@ "path": "application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java", "header": "ce-modified", "reason": "Retained CE file subsequently deleted on the selected lts-4.2 mainline. PE retains the CE implementation with HTTP client migration, timeout and request-handling changes. Reviewed against last CE path version 3af76140cd7dd2968cdba2875a92eccbbcfc05fe^1 (blob 034ac5148483fda6234c6fae2a46cf601396606a); absence from the selected CE tree does not change origin.", - "contentHash": "sha256:eecfaa3b7a1a6e24f09816fbce577ddad12ce5fc0a0ccb14391982673adc081f" + "contentHash": "sha256:e0bb8888308be0e7cd40e4b5fcc938df2069eb044232c1bbe83c2fc2b294f494" }, { "path": "application/src/main/java/org/thingsboard/server/service/edge/EdgeLicenseService.java", @@ -49,24 +49,6 @@ "reason": "PE-specific service adapter/message SecretEdgeProcessor.java. Reviewed methods bind the common framework to PE integration, scheduler, encryption/secret, group, or customer-parent behavior. This is a new typed PE extension, not a relocation of the candidate CE implementation. Reviewed candidate application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/queue/QueueEdgeProcessor.java at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob 8e5a65b588937e5703ff87f301be023d27ce1808).", "contentHash": "sha256:6f960791993777f636b230e3829422af292370a5b5a113b082dc2d05ee151491" }, - { - "path": "application/src/main/java/org/thingsboard/server/service/install/lts/Migration.java", - "header": "ce-modified", - "reason": "CE interface application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigration.java renamed in 7a926f2c1f2 when the Lts prefix was dropped from migrations, with PE changes on top. Reviewed against CE application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigration.java at 5954190c32f (blob f0cadee1f657ab6d1a0f670f1166ef3140ec4438); a renamed CE file stays CE-derived.", - "contentHash": "sha256:c12598c1c6ccd66fe6cfd7833fe1624d379c937151df7d13bf162212cb7344aa" - }, - { - "path": "application/src/main/java/org/thingsboard/server/service/install/lts/MigrationService.java", - "header": "ce-modified", - "reason": "CE service application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java renamed in 7a926f2c1f2 when the Lts prefix was dropped from migrations, with PE changes on top. Reviewed against CE application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java at 5954190c32f (blob 2f063c3a1a469cb578503bdf548f5e1a4cfb4035); a renamed CE file stays CE-derived.", - "contentHash": "sha256:f72de342ef3308706b866bb311ede8c07c4027a2b413154a4002807561887ed3" - }, - { - "path": "application/src/main/java/org/thingsboard/server/service/install/lts/Version.java", - "header": "ce-modified", - "reason": "CE class application/src/main/java/org/thingsboard/server/service/install/lts/LtsVersion.java renamed in 7a926f2c1f2 when the Lts prefix was dropped from migrations, with PE changes on top. Reviewed against CE application/src/main/java/org/thingsboard/server/service/install/lts/LtsVersion.java at 5954190c32f (blob fa59efcc5a2d50079e495e42c141139fc57f178b); a renamed CE file stays CE-derived.", - "contentHash": "sha256:d7698c48f928583c2ade63ed5f16620677bb6d0a59376d9dbe1fb1ee1457a095" - }, { "path": "application/src/main/java/org/thingsboard/server/service/integration/rpc/IntegrationSessionCaffeineCache.java", "header": "busl", @@ -133,24 +115,6 @@ "reason": "PE WebSocket logs subscription command added in 4005afabb81 as part of the PE agent feature introduced on lts-4.4, which has no counterpart in CE. The candidate CE application/src/main/java/org/thingsboard/server/service/ws/notification/cmd/NotificationsUnsubCmd.java shares only the WebSocket command boilerplate. Reviewed candidate at a0aff29ef42d3636473b017115a9334b48d54d15 (blob 1a7a6119358).", "contentHash": "sha256:fd319f8910fa50f4db8dd30fe3f90e60e34910e1ddc0bb9db390db64f56b27db" }, - { - "path": "application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java", - "header": "ce-modified", - "reason": "CE test application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java renamed in 7a926f2c1f2 when the Lts prefix was dropped from migrations, with PE changes on top. Reviewed against CE application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java at 5954190c32f (blob cf60ec2e4b5fce7a55862805e9bd959c125ce17e); a renamed CE file stays CE-derived.", - "contentHash": "sha256:24cb205ad1c7a7577284aa2fca5b245d60e0c554accfe9f26021a6d60e0807ce" - }, - { - "path": "application/src/test/java/org/thingsboard/server/service/install/lts/MigrationServiceTest.java", - "header": "ce-modified", - "reason": "CE test application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java renamed in 7a926f2c1f2 when the Lts prefix was dropped from migrations, with PE changes on top. Reviewed against CE application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java at 5954190c32f (blob 18ee8b6506742c7bf3e39a8fe0e5d9e9370e5614); a renamed CE file stays CE-derived.", - "contentHash": "sha256:1ba9703bfe4a8fdb30ef11d151c9de62b4f89279ad030738021986db9fd64d8d" - }, - { - "path": "application/src/test/java/org/thingsboard/server/service/install/lts/VersionTest.java", - "header": "ce-modified", - "reason": "CE test application/src/test/java/org/thingsboard/server/service/install/lts/LtsVersionTest.java renamed in 7a926f2c1f2 when the Lts prefix was dropped from migrations, with PE changes on top. Reviewed against CE application/src/test/java/org/thingsboard/server/service/install/lts/LtsVersionTest.java at 5954190c32f (blob f3d280a915e59fb37e93c45e6404b09728a772a8); a renamed CE file stays CE-derived.", - "contentHash": "sha256:6a1b1d2f264dbae3ad420d9eef4466449a50f9f721c7256441a4aab0e4a87037" - }, { "path": "application/src/test/java/org/thingsboard/server/service/install/update/DefaultDataUpdateServiceTest.java", "header": "busl", @@ -457,6 +421,12 @@ "reason": "PE custom menu model interface introduced in 2eb81a2baa9 alongside CustomMenuConfig. The candidate CE DeviceConfiguration.java matches only on Jackson polymorphism annotations, not on the menu model. Reviewed candidate at 317a75614137ab5ddd1aecef1abd4c2fcdcb8710 (blob 6fe689d17c0).", "contentHash": "sha256:da19b1162913a636119fcc953d6366b990d24a6fda8df540497653bb317407b0" }, + { + "path": "common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java", + "header": "ce-modified", + "reason": "Copied from the CE EntitiesLimitIncreaseRequestNotificationInfo and adapted: entityType replaced by tenantName and limitDescription, same structure and template data map. Reviewed against CE common/data/src/main/java/org/thingsboard/server/common/data/notification/info/EntitiesLimitIncreaseRequestNotificationInfo.java at 0cfdad792af2a7ab1e292742134dce19f5293b7e (blob 9595b4414fd87b3740479c730c8c39928d003e7b).", + "contentHash": "sha256:362d939f065b94a46db4258c87598278b4f4db7b6dcf82a0a57dd762a8f09635" + }, { "path": "common/data/src/main/java/org/thingsboard/server/common/data/notification/info/IntegrationLifecycleEventNotificationInfo.java", "header": "busl", @@ -551,7 +521,7 @@ "path": "common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/credentials/CertPemClientCredentials.java", "header": "busl", "reason": "Retained PE MQTT integration client-certificate credentials from the original integration credential family. Similar CE rule-engine credential implementations do not establish CE origin for that earlier PE family; PE supplies its client-certificate configuration. Reviewed CE candidate rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/credentials/CertPemCredentials.java at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob 46d844d2c4aff3d5af24802dfee974f0af416113).", - "contentHash": "sha256:d4ae03b84f499bede7580d21ed131995793ee01d9a5bbd602f48a1a47325e896" + "contentHash": "sha256:abe439078bde5c247ab2d091d2aba5828360276d09dc604d7952ada12dab5e25" }, { "path": "common/queue/src/main/java/org/thingsboard/server/queue/settings/TbQueueIntegrationApiSettings.java", @@ -1099,12 +1069,6 @@ "reason": "New PE file implementing a PE feature. It was written by adapting CE monitoring/src/main/java/org/thingsboard/monitoring/service/transport/impl/CoapTransportHealthChecker.java, which PE still carries at its own path, so this is not a CE file with PE modifications. Adaptation from CE does not make it CE-derived. Maintainer rule (2026-09-09): a file that exists in CE and carries PE changes is modified CE; a file that does not exist in CE and implements a PE feature is PE-only, however closely it resembles a CE file.", "contentHash": "sha256:d052fff33aea9d375bbfa2c1655bc016a7d4232cc1aed77be9534dc23f6068e9" }, - { - "path": "monitoring/src/main/java/org/thingsboard/monitoring/service/integration/impl/HttpIntegrationHealthChecker.java", - "header": "busl", - "reason": "New PE file implementing a PE feature. It was written by adapting CE monitoring/src/main/java/org/thingsboard/monitoring/service/transport/impl/HttpTransportHealthChecker.java, which PE still carries at its own path, so this is not a CE file with PE modifications. Adaptation from CE does not make it CE-derived. Maintainer rule (2026-09-09): a file that exists in CE and carries PE changes is modified CE; a file that does not exist in CE and implements a PE feature is PE-only, however closely it resembles a CE file.", - "contentHash": "sha256:7a4b0c71c3185997d717d3ff197f7734826141bb89347b054dd5277a5979e8da" - }, { "path": "monitoring/src/main/java/org/thingsboard/monitoring/service/integration/impl/MqttIntegrationHealthChecker.java", "header": "busl", @@ -1199,7 +1163,7 @@ "path": "msa/web-report/pom.xml", "header": "busl", "reason": "Build descriptor of the PE-only web-report module; CE has no web-report module. The only CE version is an empty file (blob e69de29bb2d) added by stray commit 2b1c5d92f3a, pushed to fix/maven-node-lts-4.3 after #16417 merged and carried into lts-4.4 via #16419; it never reached CE lts-4.3 and is not the origin of this file.", - "contentHash": "sha256:48ee3956937386c95ebb2b95a4981506203c00ce276aa6003fecfc0ddaf04218" + "contentHash": "sha256:620ece3810c834e5823c845cd98b56c67bf1c6bb39bd8e0c67c075bc0c7b1b53" }, { "path": "report/src/main/conf/logback.xml", @@ -1229,7 +1193,7 @@ "path": "report/src/main/resources/tb-report.yml", "header": "busl", "reason": "Launch, logging or runtime scaffolding for a PE service. Maintainer explicitly resolved this PE module scaffolding as PE-only; matching CE startup/logging conventions do not override that decision. Reviewed similarity candidate edqs/src/main/resources/edqs.yml at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob cad0fcaccc785af0853c77f05d385adb4c102f67).", - "contentHash": "sha256:64e2775735521015bd88c79f68db101ff69f536c681db8239764c434205a0583" + "contentHash": "sha256:af66b4f07cc43e0af1fc0f2f39f9c2b1220c22ed6ecefab56bd3260cceab6b50" }, { "path": "rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/metadata/TbGetCustomerAttributeNodeConfiguration.java", @@ -1237,6 +1201,12 @@ "reason": "Configuration holder for the PE customer-attribute rule node. Reviewed property defaults configure this PE node; common rule-node configuration/clone patterns do not establish derivation from the CE entity-data node. Reviewed candidate rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/metadata/TbGetEntityDataNodeConfiguration.java at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob f68fdf321b69b24e3e15bd2a311e2ccfa86ff890).", "contentHash": "sha256:0b91a00b698884c6654781d43c0debb2e61dcfcb9898811e27dc13baafde2bb0" }, + { + "path": "ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss", + "header": "busl", + "reason": "New AI approval card stylesheet holding only a one-line ':host { display: block; }' rule; it matches CE socialshare-panel.component.scss only because that rule is generic boilerplate, not because anything was copied from it. Reviewed against CE ui-ngx/src/app/shared/components/socialshare-panel.component.scss at 0cfdad792af2a7ab1e292742134dce19f5293b7e (blob 75f4e82b7187d38898ab858dc6a20be6058e9e20).", + "contentHash": "sha256:49fd378740956adca949bca4777b25410d4d9c562716602678360a3aa7f82a91" + }, { "path": "ui-ngx/src/app/modules/home/components/converter/converter-autocomplete.component.scss", "header": "busl", @@ -1435,6 +1405,12 @@ "reason": "New PE file implementing a PE feature. It was written by adapting CE ui-ngx/src/app/modules/home/pages/dashboard/make-dashboard-public-dialog.component.ts, which PE still carries at its own path, so this is not a CE file with PE modifications. Adaptation from CE does not make it CE-derived. Maintainer rule (2026-09-09): a file that exists in CE and carries PE changes is modified CE; a file that does not exist in CE and implements a PE feature is PE-only, however closely it resembles a CE file.", "contentHash": "sha256:07f295f637db24d600798215d33391f4e966954899f644a41b9735f5ed5392db" }, + { + "path": "ui-ngx/src/app/modules/home/pages/home-page/home-page.component.html", + "header": "ce-modified", + "reason": "Renamed from CE home-links.component.html; it keeps the CE embedded tb-dashboard-page for an assigned home dashboard and replaces the links grid with the new Home pages. Reviewed against CE ui-ngx/src/app/modules/home/pages/home-links/home-links.component.html at 0cfdad792af2a7ab1e292742134dce19f5293b7e (blob 3f7184d1828f217480f5e12486f1ff0704d2f7c4).", + "contentHash": "sha256:ab7b00962003c516bce4af3dabc068c37b0d9ee773e960f8607b6a155514f76b" + }, { "path": "ui-ngx/src/app/modules/home/pages/iframe/iframe-view.module.ts", "header": "busl", @@ -1698,12 +1674,6 @@ "header": "busl", "reason": "ID wrapper for a PE-only entity. Maintainer resolved ConverterId and comparable PE-only entity wrappers as PE-authored; extending the common ID type and repeating its annotations/type tag is template use. Reviewed similarity candidate ui-ngx/src/app/shared/models/id/asset-id.ts at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob 86ca874a92346a950b6912d78116f1f7ee6bb654).", "contentHash": "sha256:5427b1c6bf59f9e9372c47717fee96bf94bddeaf65ad920b77647b16539bf5f9" - }, - { - "path": "ui-ngx/src/scss/filter-button.scss", - "header": "ce-modified", - "reason": "Shared filter button styles extracted from the CE device filter component, which now uses this file instead of its own copy; the rules are the CE implementation with the panel class renamed. Reviewed against CE ui-ngx/src/app/modules/home/components/device/device-info-filter.component.scss at 269bc8dc73a4892e93cf61db6a8a41ea377c8636 (blob 4a79c6c9ce599e85209d5a6ee9062b6f713ac0f1).", - "contentHash": "sha256:3b19b678564aa147c087269d91d7996a5c2a58d7ff058afbe6610c5cda56cc0e" } ] } diff --git a/tools/src/main/python/license-headers/test_check_license_headers.py b/tools/src/main/python/license-headers/test_check_license_headers.py index 9989f5b2ec..00532f5ee4 100644 --- a/tools/src/main/python/license-headers/test_check_license_headers.py +++ b/tools/src/main/python/license-headers/test_check_license_headers.py @@ -10,8 +10,11 @@ import json import os import sqlite3 from pathlib import Path +import shutil +import subprocess import tempfile import textwrap +from types import SimpleNamespace import unittest from unittest.mock import patch import xml.etree.ElementTree as ET @@ -35,13 +38,25 @@ def signature(label): def temporary_directory(test): directory = tempfile.TemporaryDirectory() test.addCleanup(directory.cleanup) - return Path(directory.name) + return Path(directory.name).resolve() + + +def rename_sources(lineage): + return {name: chain.source for name, chain in lineage.renames.items()} + + +def rename_origins(lineage): + return {name: (chain.source, chain.origin) for name, chain in lineage.renames.items()} def this_repository(): return Path(p.git(Path(__file__).parent, "rev-parse", "--show-toplevel").decode().strip()) +MERGE_FILE_OBJECT_ID = b"object-id" in subprocess.run(["git", "merge-file", "-h"], capture_output=True).stdout +requires_merge_file_object_id = unittest.skipUnless(MERGE_FILE_OBJECT_ID, p.MERGE_FILE_REQUIREMENT) + + def fixture_plugin(version="0"): return p.Plugin(version, ET.Element("configuration")) @@ -62,11 +77,22 @@ class GitFixture: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text) - def commit(self, message): + def commit(self, message, *options): self("add", ".") - self("commit", "-m", message) + self("commit", *options, "-m", message) return self("rev-parse", "HEAD") + def sign_with_new_ssh_key(self, test): + if shutil.which("ssh-keygen") is None: + test.skipTest("ssh-keygen is not available") + keys = temporary_directory(test) + subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "test", "-f", str(keys / "key")], + check=True, capture_output=True) + (keys / "allowed_signers").write_text("test@example.invalid " + (keys / "key.pub").read_text()) + self("config", "gpg.format", "ssh") + self("config", "user.signingkey", str(keys / "key.pub")) + self("config", "gpg.ssh.allowedSignersFile", str(keys / "allowed_signers")) + class DecisionTests(unittest.TestCase): VERSION = {"path": "a.java", "ref": "b" * 40, "blob": "c" * 40} @@ -110,6 +136,35 @@ class DecisionTests(unittest.TestCase): self.assertEqual(("unresolved", "CE history had this path"), (row["status"], row["reason"])) self.assertEqual(deleted, row["historicalCandidate"]) + def test_every_rename_from_ce_needs_header_less_similarity(self): + version = {"path": "source.java", "ref": "a" * 40, "blob": "c" * 40} + first = {"commit": "d" * 40, "from": "source.java", "to": "middle.java", "similarity": 100} + second = {"commit": "e" * 40, "from": "middle.java", "to": "a.java", "similarity": p.SIMILARITY} + row = self.new(current="ce-modified", renamed_from=(version,), renames=(first, second)) + self.assertEqual(("match", "ce-modified", "renamed from CE source.java"), + (row["status"], row["expectedHeader"], row["reason"])) + self.assertEqual(([version], [first, second]), (row["renamedFrom"], row["renames"])) + weak = second | {"similarity": p.SIMILARITY - 1} + row = self.new(current="ce-modified", renamed_from=(version,), renames=(first, weak), copies=(self.COPY,)) + self.assertEqual(("unresolved", None, None), (row["status"], row["expectedHeader"], row["suggestedHeader"])) + self.assertEqual(([version], [first, weak], [self.COPY]), + (row["renameCandidates"], row["renames"], row["copyCandidates"])) + self.assertEqual(f"renamed from CE source.java, but the rename of middle.java in eeeeeeeeeee " + f"is {p.SIMILARITY - 1}% similar without the header, less than {p.SIMILARITY}%", row["reason"]) + + def test_rename_from_a_file_added_outside_ce_needs_a_decision(self): + version = {"path": "source.java", "ref": "a" * 40, "blob": "c" * 40} + rename = {"commit": "d" * 40, "from": "source.java", "to": "a.java", "similarity": 100} + evidence = dict(current=p.NON_CE, renamed_from=(version,), renames=(rename,)) + row = self.new(**evidence, rename_origin="downstream") + self.assertEqual(("unresolved", None), (row["status"], row["expectedHeader"])) + self.assertEqual("renamed from source.java in ddddddddddd, but that file was added outside CE " + f"and is less than {p.SIMILARITY}% similar to the CE source.java", row["reason"]) + self.assertEqual(([version], [rename]), (row["renameCandidates"], row["renames"])) + row = self.new(**evidence, rename_origin="ambiguous") + self.assertEqual(("unresolved", "renamed from source.java, but parallel branches added a file of its rename chain"), + (row["status"], row["reason"])) + def test_descriptor_of_a_module_absent_in_ce_is_non_ce_despite_similar_ce_descriptors(self): copy = self.COPY | {"path": "transport/mqtt/pom.xml"} descriptor = dict(path="integration/mqtt/pom.xml", copies=(copy,), directory_in_ce=False) @@ -387,6 +442,11 @@ class InputTests(unittest.TestCase): p.split_removed(b"\n\nbody\n", b"\nbody\n")[1]) self.assertEqual(b"/**\n * SPDX\n */\n", p.split_removed(b"/**\n * SPDX\n */\n/**\n * Old\n */\n", b"/**\n * Old\n */\n")[1]) + def test_an_empty_side_is_not_similar(self): + tool = SimpleNamespace(contents={"empty": b"\n", "full": b"content\n"}) + self.assertEqual(0, p.normalized_similarity(tool, "empty", "full")) + self.assertEqual(0, p.normalized_similarity(tool, "full", "empty")) + def test_hash_contracts(self): self.assertEqual(p.comparison_hash(b"a\r\nb\r\n"), p.comparison_hash(b"a\nb\n")) self.assertNotEqual(p.raw_hash(b"a\r\n"), p.raw_hash(b"a\n")) @@ -583,6 +643,186 @@ class GitHistoryTests(unittest.TestCase): self.assertEqual([(removal, git("rev-parse", f"{removal}:Kept.java"))], lineage.versions("Kept.java")) self.assertEqual([], lineage.versions("Gone.java")) + def test_lineage_follows_renames_of_ce_paths_after_the_ce_base(self): + git = GitFixture(temporary_directory(self), "ce") + body = "".join(f"CE line {index}\n" for index in range(20)) + git.write("Base.java", body) + git.write("Other.java", "other " + body) + git.write("Merged.java", "merged " + body) + base = git.commit("CE base") + git("checkout", "-b", "downstream") + git("mv", "Base.java", "Middle.java") + git.commit("rename") + git("mv", "Middle.java", "Final.java") + git.write("Final.java", body + "downstream change\n") + git.commit("rename and change") + git("checkout", "-b", "side") + git("rm", "-q", "Merged.java") + git.commit("side deletion") + git.write("Added.java", "merged " + body) + git.commit("unrelated addition") + git("checkout", "downstream") + git("merge", "--no-ff", "side", "-m", "integrate side") + git("mv", "Other.java", "Squashed.java") + squash = git.commit("relicensing") + head = git("rev-parse", "HEAD") + self.assertEqual({"Final.java": "Base.java", "Squashed.java": "Other.java"}, + rename_sources(p.Lineage.load(git.root, head, [base]))) + with patch.object(p, "RELICENSING_COMMIT", squash): + self.assertEqual({"Final.java": "Base.java"}, rename_sources(p.Lineage.load(git.root, head, [base]))) + + def test_lineage_follows_only_the_file_that_reaches_head(self): + git = GitFixture(temporary_directory(self), "ce") + body = "".join(f"CE line {index}\n" for index in range(20)) + git.write("A.java", body) + git.write("Reused.java", "reused " + body) + base = git.commit("CE base") + git("checkout", "-b", "downstream") + git("mv", "A.java", "B.java") + git.commit("rename") + git("rm", "-q", "B.java") + git.commit("delete") + git.write("B.java", "".join(f"unrelated line {index}\n" for index in range(20))) + git.commit("unrelated file at the renamed path") + git("rm", "-q", "Reused.java") + git.commit("delete a CE path") + git.write("Reused.java", "".join(f"downstream line {index}\n" for index in range(20))) + git.commit("reuse the CE path") + git("mv", "Reused.java", "Moved.java") + git.commit("rename the reused path") + self.assertEqual({"Moved.java": ("Reused.java", "downstream")}, + rename_origins(p.Lineage.load(git.root, git("rev-parse", "HEAD"), [base]))) + + def test_lineage_keeps_a_chain_whose_path_is_reused_after_the_rename(self): + git = GitFixture(temporary_directory(self), "ce") + git.write("A.java", "".join(f"CE line {index}\n" for index in range(20))) + base = git.commit("CE base") + git("checkout", "-b", "downstream") + git("mv", "A.java", "B.java") + first = git.commit("rename") + git("mv", "B.java", "C.java") + second = git.commit("rename again") + git.write("B.java", "".join(f"unrelated line {index}\n" for index in range(20))) + git.commit("new file at the intermediate path") + lineage = p.Lineage.load(git.root, git("rev-parse", "HEAD"), [base]) + self.assertEqual({"C.java": ("A.java", "ce")}, rename_origins(lineage)) + self.assertEqual([first, second], [hop.commit for hop in lineage.renames["C.java"].hops]) + + def test_lineage_links_renames_by_ancestry(self): + for merged_into_mainline in (True, False): + with self.subTest(merged_into_mainline=merged_into_mainline): + git = GitFixture(temporary_directory(self), "ce") + git.write("A.java", "".join(f"CE line {index}\n" for index in range(20))) + base = git.commit("CE base") + git("checkout", "-b", "feature") + git.write("B.java", "".join(f"downstream line {index}\n" for index in range(20))) + git.commit("downstream file") + git("mv", "B.java", "C.java") + git.commit("rename the downstream file") + git("checkout", "-b", "mainline", base) + git("mv", "A.java", "B.java") + git.commit("rename the CE file") + if not merged_into_mainline: + git("checkout", "feature") + git("merge", "--no-ff", "feature" if merged_into_mainline else "mainline", "-m", "merge") + lineage = p.Lineage.load(git.root, git("rev-parse", "HEAD"), [base]) + self.assertEqual({"B.java": ("A.java", "ce")}, rename_origins(lineage)) + + def test_lineage_ignores_log_settings_of_the_user(self): + git = GitFixture(temporary_directory(self), "ce") + git.write("A.java", "".join(f"CE line {index}\n" for index in range(20))) + base = git.commit("CE base") + git("checkout", "-b", "downstream") + git("mv", "A.java", "B.java") + git.sign_with_new_ssh_key(self) + try: + git.commit("rename", "-S") + except p.Failure as e: + self.skipTest(f"git cannot sign with an SSH key: {e}") + git("config", "log.follow", "true") + git("config", "log.showSignature", "true") + self.assertEqual({"B.java": ("A.java", "ce")}, + rename_origins(p.Lineage.load(git.root, git("rev-parse", "HEAD"), [base]))) + + def test_lineage_follows_the_side_of_a_merge_that_kept_the_file(self): + git = GitFixture(temporary_directory(self), "ce") + body = "".join(f"CE line {index}\n" for index in range(20)) + git.write("A.java", body) + base = git.commit("CE base") + git("checkout", "-b", "downstream") + git("mv", "A.java", "B.java") + git.commit("rename") + git("checkout", "-b", "cleanup") + git("rm", "-q", "B.java") + git.commit("delete the renamed file") + git("checkout", "downstream") + git.write("B.java", body + "downstream change\n") + git.commit("change the renamed file") + subprocess.run(["git", "merge", "--no-ff", "cleanup", "-m", "merge"], cwd=git.root, capture_output=True) + git("checkout", "downstream", "--", "B.java") + git.commit("keep the changed file") + self.assertEqual({"B.java": ("A.java", "ce")}, + rename_origins(p.Lineage.load(git.root, git("rev-parse", "HEAD"), [base]))) + + def test_lineage_marks_parallel_creations_of_a_path_as_ambiguous(self): + git = GitFixture(temporary_directory(self), "ce") + git.write("A.java", "".join(f"CE line {index}\n" for index in range(20))) + base = git.commit("CE base") + git("checkout", "-b", "downstream") + git("mv", "A.java", "B.java") + git.commit("rename") + git("checkout", "-b", "side", base) + git.write("X.java", "".join(f"downstream line {index}\n" for index in range(20))) + git.commit("parallel file") + git("mv", "X.java", "B.java") + git.commit("rename the parallel file") + git("checkout", "downstream") + subprocess.run(["git", "merge", "--no-ff", "side", "-m", "merge"], cwd=git.root, capture_output=True) + git.write("B.java", "".join(f"resolved line {index}\n" for index in range(20))) + git.commit("resolve") + self.assertEqual({"B.java": ("A.java", "ambiguous")}, + rename_origins(p.Lineage.load(git.root, git("rev-parse", "HEAD"), [base]))) + + def test_lineage_records_where_a_rename_source_was_added(self): + git = GitFixture(temporary_directory(self), "ce") + body = "".join(f"CE line {index}\n" for index in range(20)) + git.write("Restored.java", body) + base = git.commit("CE base") + git("checkout", "-b", "downstream") + git("rm", "-q", "Restored.java") + deletion = git.commit("delete a CE file") + git("revert", "--no-edit", deletion) + git("mv", "Restored.java", "Moved.java") + git.commit("rename the restored file") + git.write("Util.java", "".join(f"downstream line {index}\n" for index in range(20))) + git.commit("downstream file") + git("mv", "Util.java", "PeUtil.java") + git.commit("rename the downstream file") + git("checkout", "ce") + git.write("Util.java", "".join(f"unrelated CE line {index}\n" for index in range(20))) + later = git.commit("CE file at the old downstream path") + git("checkout", "downstream") + git("merge", "--no-ff", "ce", "-m", "merge CE") + self.assertEqual({"Moved.java": ("Restored.java", "downstream"), "PeUtil.java": ("Util.java", "downstream")}, + rename_origins(p.Lineage.load(git.root, git("rev-parse", "HEAD"), [later]))) + + def test_lineage_keeps_a_rename_whose_path_changed_only_on_another_branch(self): + git = GitFixture(temporary_directory(self), "ce") + git.write("Theme.java", "".join(f"CE line {index}\n" for index in range(20))) + base = git.commit("CE base") + git("checkout", "-b", "downstream") + git("mv", "Theme.java", "Constants.java") + git.commit("rename") + git("checkout", "-b", "side", base) + git.write("Constants.java", "".join(f"unrelated line {index}\n" for index in range(20))) + git.commit("unrelated file") + git("rm", "-q", "Constants.java") + git.commit("revert") + git("checkout", "downstream") + git("merge", "--no-ff", "side", "-m", "integrate side") + self.assertEqual({"Constants.java": "Theme.java"}, + rename_sources(p.Lineage.load(git.root, git("rev-parse", "HEAD"), [base]))) + def test_lineage_walks_shared_history_of_several_bases_once(self): git = GitFixture(temporary_directory(self), "ce") git.write("Shared.java", "deleted before the bases diverged\n") @@ -612,6 +852,7 @@ class GitHistoryTests(unittest.TestCase): with self.assertRaises(p.Failure): p.history(git.root, ["--all"]) + @requires_merge_file_object_id def test_clean_merges_match_each_file_with_its_own_merge_in_any_order(self): git = GitFixture(temporary_directory(self), "ce") for header, name in p.TEMPLATES.items(): @@ -648,6 +889,7 @@ class GitHistoryTests(unittest.TestCase): f"{workers} workers") self.assertEqual({base}, {merge["base"] for merge in merges.values()}) + @requires_merge_file_object_id def test_merge_blobs_returns_only_clean_merges(self): git = GitFixture(temporary_directory(self), "main") git.write("File.java", "one\ntwo\nthree\nfour\nfive\n") @@ -663,6 +905,25 @@ class GitHistoryTests(unittest.TestCase): self.assertEqual(b"ONE\ntwo\nthree\nfour\nFIVE\n", p.merge_blobs(git.root, ours, base, theirs)) self.assertIsNone(p.merge_blobs(git.root, ours, base, blob("uno\ntwo\nthree\nfour\nfive\n"))) + @requires_merge_file_object_id + def test_merge_blobs_does_not_merge_binary_blobs(self): + git = GitFixture(temporary_directory(self), "main") + git.write("File.java", "one\0two\n") + git.commit("base") + base = git("rev-parse", "HEAD:File.java") + git.write("File.java", "ONE\0two\n") + git.commit("change") + self.assertIsNone(p.merge_blobs(git.root, git("rev-parse", "HEAD:File.java"), base, base)) + + def test_merge_blobs_fails_without_object_id_support(self): + usage = subprocess.CompletedProcess([], 129, b"", b"error: unknown option `object-id'") + with (patch.object(p, "run", side_effect=[usage, subprocess.CompletedProcess([], 0, b"git version 2.39.5\n", b"")]), + self.assertRaisesRegex(p.Failure, "needs Git 2.43 or later, found git version 2.39.5")): + p.merge_blobs(Path("."), "a", "b", "c") + + def test_merge_file_probe_detects_object_id_support(self): + self.assertEqual(MERGE_FILE_OBJECT_ID, p.merge_file_object_id_supported()) + def test_ignore_filter_keeps_tracked_and_unignored_files(self): repo = temporary_directory(self) p.git(repo, "init") @@ -741,6 +1002,9 @@ class CheckCommandTests(unittest.TestCase): LINES = "".join(f"line {index}\n" for index in range(10)) def setUp(self): + probe = patch.object(p, "merge_file_object_id_supported", return_value=True) + probe.start() + self.addCleanup(probe.stop) self.repo = temporary_directory(self) self.git = git = GitFixture(self.repo, "master") self.body = "CE source implementation\n" * 20 @@ -785,6 +1049,7 @@ class CheckCommandTests(unittest.TestCase): return {key: recognized((tool.root / tool.paths[key]).read_bytes()) for key in keys} def strip_headers(tool): + self.stripped = set(tool.paths.values()) tool.removed = {key: split(body)[0] for key, body in tool.contents.items()} tool.stacked = set() for key, body in list(tool.contents.items()): @@ -813,6 +1078,7 @@ class CheckCommandTests(unittest.TestCase): def rows(self, report): return {row["path"]: row for row in report["files"]} + @requires_merge_file_object_id def test_relicensed_branch_passes(self): code, report, _ = self.check() self.assertEqual(0, code) @@ -827,6 +1093,7 @@ class CheckCommandTests(unittest.TestCase): self.assertEqual({"path": "Fixed.java", "ref": self.fix, "blob": self.git("rev-parse", f"{self.fix}:Fixed.java")}, rows["Fixed.java"]["identicalTo"]) + @requires_merge_file_object_id def test_fix_restamps_decided_headers_only(self): self.git.write("Base.java", FOREIGN_LINE.decode() + "base implementation\n") self.git.write("New.java", fixture("apache") + "TB feature\n") @@ -853,6 +1120,7 @@ class CheckCommandTests(unittest.TestCase): self.assertEqual([], report["restamped"]) self.assertEqual({"match": 5, "mismatch": 1}, report["summary"]) + @requires_merge_file_object_id def test_ce_evidence_for_new_paths_needs_a_decision(self): self.git.write("Copy.java", fixture(p.NON_CE) + self.body) self.git.write("Deleted.java", fixture(p.NON_CE) + "removed CE source\n") @@ -866,6 +1134,148 @@ class CheckCommandTests(unittest.TestCase): rows["Deleted.java"]["historicalCandidate"]) self.assertIn("Needs a decision (2)\n", output) + @requires_merge_file_object_id + def test_renamed_ce_file_is_ce_modified(self): + self.git("mv", "Source.java", "Moved.java") + self.git.write("Moved.java", fixture("ce-modified") + self.body + "TB change\n") + self.git.commit("rename CE file") + _, report, _ = self.check(scope=[name if name != "Source.java" else "Moved.java" for name in self.scope]) + row = self.rows(report)["Moved.java"] + self.assertEqual(("match", "ce-modified", "renamed from CE Source.java"), + (row["status"], row["expectedHeader"], row["reason"])) + self.assertEqual({"Source.java"}, {version["path"] for version in row["renamedFrom"]}) + + @requires_merge_file_object_id + def test_growth_after_a_rename_from_ce_does_not_matter(self): + self.git("mv", "Source.java", "Moved.java") + self.git.write("Moved.java", fixture("ce-modified") + self.body) + rename = self.git.commit("rename CE file") + growth = "".join(f"TB implementation {index}\n" for index in range(200)) + self.git.write("Moved.java", fixture("ce-modified") + self.body + growth) + self.git.commit("grow the renamed file") + _, report, _ = self.check(scope=[name if name != "Source.java" else "Moved.java" for name in self.scope]) + row = self.rows(report)["Moved.java"] + self.assertEqual(("match", "ce-modified"), (row["status"], row["expectedHeader"])) + self.assertEqual([{"commit": rename, "from": "Source.java", "to": "Moved.java", "similarity": 100}], + row["renames"]) + + def rename_with_a_shared_large_header(self, *moves): + padding = "// " + "shared downstream notice " * 120 + "\n" + self.git.write("Source.java", padding + self.body) + self.git.commit("large header on the CE file") + for source, target in moves[:-1]: + self.git("mv", source, target) + self.git.commit("rename") + source, target = moves[-1] + rewritten = padding + "".join(f"TB implementation {index}\n" for index in range(20)) + self.git("mv", source, target) + self.git.write(target, rewritten) + self.git.commit("rename and rewrite") + return rewritten + + @requires_merge_file_object_id + def test_rename_from_ce_below_the_threshold_needs_a_decision(self): + rewritten = self.rename_with_a_shared_large_header(("Source.java", "Moved.java")) + scope = [name if name != "Source.java" else "Moved.java" for name in self.scope] + for args in ((), ("--fix",)): + code, report, output = self.check(*args, scope=scope) + row = self.rows(report)["Moved.java"] + self.assertEqual((1, "unresolved"), (code, row["status"])) + self.assertEqual({"Source.java"}, {candidate["path"] for candidate in row["renameCandidates"]}) + self.assertLess(row["renames"][0]["similarity"], p.SIMILARITY) + self.assertEqual([], report["restamped"]) + weakest = row["renames"][0] + self.assertIn(f" renamed from CE Source.java, but the rename of Source.java in {weakest['commit'][:11]} " + f"is {weakest['similarity']}% similar without the header, less than {p.SIMILARITY}%\n" + " rename source in CE: Source.java at ", output) + self.assertEqual(rewritten, (self.repo / "Moved.java").read_text()) + + @requires_merge_file_object_id + def test_every_rename_of_a_chain_needs_the_threshold(self): + self.rename_with_a_shared_large_header(("Source.java", "Middle.java"), ("Middle.java", "Final.java")) + _, report, _ = self.check(scope=[name if name != "Source.java" else "Final.java" for name in self.scope]) + row = self.rows(report)["Final.java"] + self.assertEqual("unresolved", row["status"]) + self.assertEqual([("Source.java", "Middle.java"), ("Middle.java", "Final.java")], + [(rename["from"], rename["to"]) for rename in row["renames"]]) + self.assertEqual(100, row["renames"][0]["similarity"]) + self.assertLess(row["renames"][1]["similarity"], p.SIMILARITY) + + @requires_merge_file_object_id + def test_rename_through_a_file_type_outside_the_scope_needs_a_decision(self): + self.git("mv", "Source.java", "Notes.txt") + self.git.commit("rename to an unsupported type") + self.git("mv", "Notes.txt", "Moved.java") + self.git.commit("rename back") + _, report, _ = self.check(scope=[name if name != "Source.java" else "Moved.java" for name in self.scope]) + row = self.rows(report)["Moved.java"] + self.assertEqual("unresolved", row["status"]) + self.assertIn("Notes.txt", row["reason"]) + self.assertEqual([("Source.java", "Notes.txt"), ("Notes.txt", "Moved.java")], + [(rename["from"], rename["to"]) for rename in row["renames"]]) + self.assertFalse([path for path in self.stripped if path.endswith(".txt")]) + + @requires_merge_file_object_id + def test_rename_source_added_outside_ce_needs_ce_content(self): + git = self.git + twin = fixture(p.NON_CE) + self.body + git.write("Twin.java", twin) + git.write("Util.java", fixture(p.NON_CE) + "".join(f"TB utility {index}\n" for index in range(20))) + git.commit("downstream files") + git("mv", "Twin.java", "Middle.java") + git("mv", "Util.java", "PeUtil.java") + git.commit("rename the downstream files") + git.write("Middle.java", fixture(p.NON_CE) + "".join(f"TB rewrite {index}\n" for index in range(20))) + git.commit("rewrite the renamed twin") + git("mv", "Middle.java", "Renamed.java") + git.commit("rename the twin again") + git("checkout", "lts-4.3") + git.write("Twin.java", fixture("apache") + self.body) + git.write("Util.java", fixture("apache") + "".join(f"CE helper {index}\n" for index in range(20))) + git.commit("CE files at the old downstream paths") + git("checkout", "master") + git("merge", "--no-ff", "lts-4.3", "-m", "integrate CE files") + _, report, _ = self.check(scope=self.scope + ["PeUtil.java", "Renamed.java", "Twin.java", "Util.java"]) + rows = self.rows(report) + self.assertEqual(("ce-modified", "renamed from CE Twin.java"), + (rows["Renamed.java"]["expectedHeader"], rows["Renamed.java"]["reason"])) + self.assertEqual("unresolved", rows["PeUtil.java"]["status"]) + self.assertIn("but that file was added outside CE", rows["PeUtil.java"]["reason"]) + + @requires_merge_file_object_id + def test_rename_source_added_by_a_merge_needs_ce_content(self): + git = self.git + git("checkout", "-b", "side") + git.write("Side.java", fixture(p.NON_CE) + "side\n") + git.commit("side") + git("checkout", "master") + git("merge", "--no-ff", "--no-commit", "side") + git.write("Util.java", fixture(p.NON_CE) + "".join(f"TB utility {index}\n" for index in range(20))) + git.commit("merge side, adding a downstream file") + git("mv", "Util.java", "PeUtil.java") + git.commit("rename the downstream file") + git("checkout", "lts-4.3") + git.write("Util.java", fixture("apache") + "".join(f"CE helper {index}\n" for index in range(20))) + git.commit("CE file at the old downstream path") + git("checkout", "master") + git("merge", "--no-ff", "lts-4.3", "-m", "integrate CE") + _, report, _ = self.check(scope=self.scope + ["PeUtil.java", "Side.java", "Util.java"]) + row = self.rows(report)["PeUtil.java"] + self.assertEqual("unresolved", row["status"]) + self.assertIn("but that file was added outside CE", row["reason"]) + + @requires_merge_file_object_id + def test_restored_ce_file_renamed_downstream_is_ce_modified(self): + self.git("rm", "-q", "Source.java") + deletion = self.git.commit("delete a CE file") + self.git("revert", "--no-edit", deletion) + self.git("mv", "Source.java", "Moved.java") + self.git.commit("rename the restored file") + _, report, _ = self.check(scope=[name if name != "Source.java" else "Moved.java" for name in self.scope]) + row = self.rows(report)["Moved.java"] + self.assertEqual(("ce-modified", "renamed from CE Source.java"), (row["expectedHeader"], row["reason"])) + + @requires_merge_file_object_id def test_fix_removes_redundant_and_orphaned_curations(self): self.git.write("Copy.java", fixture(p.NON_CE) + self.body) @@ -899,6 +1309,14 @@ class CheckCommandTests(unittest.TestCase): code, report, _ = self.check("--fix", scope=scope) self.assertEqual((0, []), (code, report["removedCurations"])) + def test_git_without_merge_file_object_id_fails_at_startup(self): + with patch.object(p, "merge_file_object_id_supported", return_value=False): + code, report, output = self.check("--ce-ref", "lts-4.3", "--ce-remote", str(self.repo)) + self.assertEqual((2, None), (code, report)) + self.assertNotIn("Fetching", output) + self.assertIn(f"Error: git merge-file does not support --object-id. {p.MERGE_FILE_REQUIREMENT}, found git version", + output) + def pull_request(self): self.git("checkout", "-q", "-b", "feature") return self.git("rev-parse", "master") @@ -906,6 +1324,7 @@ class CheckCommandTests(unittest.TestCase): def checked(self, report): return sorted(row["path"] for row in report["files"]) + @requires_merge_file_object_id def test_files_changed_during_the_scan_fail_the_check(self): compare = p.compare @@ -959,6 +1378,7 @@ class CheckCommandTests(unittest.TestCase): self.assertEqual(["New.java"], self.checked(report)) self.assertEqual("not in CE, no CE evidence", self.rows(report)["New.java"]["reason"]) + @requires_merge_file_object_id def test_since_checks_every_file_when_new_ce_commits_are_merged(self): self.pull_request() self.git("checkout", "-q", "lts-4.3") @@ -973,6 +1393,7 @@ class CheckCommandTests(unittest.TestCase): self.assertTrue(report["selection"]["full"]) self.assertIn("full check: the CE commits merged into the branch changed", output) + @requires_merge_file_object_id def test_since_checks_every_file_when_the_check_changes(self): self.pull_request() self.git.write(p.TEMPLATES["apache"], "fixture apache, reworded\n") @@ -981,6 +1402,7 @@ class CheckCommandTests(unittest.TestCase): self.assertEqual(sorted(self.scope), self.checked(report)) self.assertEqual(f"the check itself changed ({p.TEMPLATES['apache']})", report["selection"]["reason"]) + @requires_merge_file_object_id def test_since_checks_every_file_when_the_mycila_configuration_changes(self): self.pull_request() _, report, _ = self.check("--since", "master", base_plugin=fixture_plugin("1")) @@ -1000,6 +1422,7 @@ class CheckCommandTests(unittest.TestCase): self.assertEqual(["New.java"], self.checked(report)) self.assertEqual([], report["curationIssues"]) + @requires_merge_file_object_id def test_since_finds_a_copy_of_a_ce_file_with_another_extension_as_a_full_run_does(self): # CE sources of the copy search follow the extensions of every path CE lacks: New.java brings .java in. self.pull_request() @@ -1015,6 +1438,22 @@ class CheckCommandTests(unittest.TestCase): self.assertEqual(("unresolved", ["Source.java"]), (row["status"], [copy["path"] for copy in row["copyCandidates"]])) + @requires_merge_file_object_id + def test_since_resolves_a_rename_of_a_ce_file_to_another_type_in_scope_as_a_full_run_does(self): + self.pull_request() + self.git("mv", "Source.java", "Moved.ts") + self.git.write("Moved.ts", fixture("ce-modified") + self.body) + self.git.commit("rename a CE file into another language") + scope = [name if name != "Source.java" else "Moved.ts" for name in self.scope] + _, full, _ = self.check(scope=scope) + _, since, _ = self.check("--since", "master", scope=scope) + self.assertEqual(["Moved.ts"], self.checked(since)) + for report in (full, since): + row = self.rows(report)["Moved.ts"] + self.assertEqual(("match", "ce-modified", "renamed from CE Source.java"), + (row["status"], row["expectedHeader"], row["reason"])) + + @requires_merge_file_object_id def test_since_checks_every_file_when_the_merge_base_has_no_ce_bases(self): self.pull_request() _, report, output = self.check("--since", "lts-4.3") @@ -1249,6 +1688,7 @@ class CopySearchTests(unittest.TestCase): self.scope = ["d/Delta.java"] self.output = self.repo / "target/report.json" + @requires_merge_file_object_id def test_size_filter_keeps_the_copy_search_result(self): _, filtered, output = self.check() with patch.object(p, "size_filter_holds", return_value=False): @@ -1264,6 +1704,7 @@ class CopySearchTests(unittest.TestCase): self.assertIn("2 of 12 other CE files searched for copies", output) self.assertIn("12 of 12 other CE files searched for copies", unfiltered_output) + @requires_merge_file_object_id def test_since_reports_the_copy_a_full_run_reports_among_equally_similar_sources(self): # TB files beside the new one shift where the checked inputs sit among all inputs of a full run. others = [f"t/Tb{index}.java" for index in range(7)] @@ -1283,6 +1724,7 @@ class CopySearchTests(unittest.TestCase): self.assertEqual("b/Alpha.java", row["copyCandidates"][0]["path"]) self.assertEqual(row, self.rows(since)["d/Delta.java"]) + @requires_merge_file_object_id def test_without_the_size_filter_git_searches_every_ce_file(self): searched = [] copies = p.normalized_copies @@ -1312,6 +1754,7 @@ class CopySearchTests(unittest.TestCase): with patch.object(p, "could_be_copy", stricter): self.assertFalse(self.probe()) + @requires_merge_file_object_id def test_report_marks_the_size_filter_only_when_copies_were_searched(self): _, report, _ = self.check() self.assertEqual({"sizeFilter": True}, report["copySearch"]) @@ -1353,6 +1796,7 @@ class CopySearchTests(unittest.TestCase): self.assertTrue(p.could_be_copy(600, [1000])) self.assertFalse(p.could_be_copy(599, [1000])) + @requires_merge_file_object_id def test_a_file_grown_by_normalizing_fails_the_check(self): def strip_headers(tool): tool.removed, tool.stacked = {key: b"" for key in tool.contents}, set() @@ -1385,6 +1829,7 @@ class CacheTests(unittest.TestCase): def cache(self): return self.repo / p.CACHE_DIRECTORY + @requires_merge_file_object_id def test_a_second_run_takes_ce_inputs_from_the_cache_and_reports_the_same(self): first, second = [], [] _, cold, _ = self.check(normalizer=self.normalizer(first)) @@ -1398,6 +1843,7 @@ class CacheTests(unittest.TestCase): self.assertEqual(databases, {path.name: path.read_bytes() for path in self.cache().glob("*.sqlite")}) self.assertRegex(output, r"[1-9][0-9]* from the cache") + @requires_merge_file_object_id def test_without_the_cache_nothing_is_read_or_written(self): self.check() seen = [] diff --git a/transport/coap/pom.xml b/transport/coap/pom.xml index ebc045575f..16f20f591c 100644 --- a/transport/coap/pom.xml +++ b/transport/coap/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.transport @@ -45,7 +45,11 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 com.sun.winsw diff --git a/transport/http/pom.xml b/transport/http/pom.xml index 23832559e6..95ffc9e3ae 100644 --- a/transport/http/pom.xml +++ b/transport/http/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.transport @@ -52,7 +52,11 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 org.springframework.boot diff --git a/transport/http/src/main/resources/tb-http-transport.yml b/transport/http/src/main/resources/tb-http-transport.yml index be7b99887b..451cd6dbfe 100644 --- a/transport/http/src/main/resources/tb-http-transport.yml +++ b/transport/http/src/main/resources/tb-http-transport.yml @@ -11,6 +11,9 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8081}" + tomcat: + # Maximum number of GET and POST request parameters Tomcat parses per request + max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}" # Server SSL configuration ssl: # Enable/disable SSL support diff --git a/transport/lwm2m/pom.xml b/transport/lwm2m/pom.xml index cc548fde1e..04bc000924 100644 --- a/transport/lwm2m/pom.xml +++ b/transport/lwm2m/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.transport @@ -37,7 +37,11 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 org.thingsboard.common.transport diff --git a/transport/mqtt/pom.xml b/transport/mqtt/pom.xml index cce55aead4..04b3df75c4 100644 --- a/transport/mqtt/pom.xml +++ b/transport/mqtt/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.transport @@ -45,7 +45,11 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 com.sun.winsw diff --git a/transport/pom.xml b/transport/pom.xml index c308306461..63378e6591 100644 --- a/transport/pom.xml +++ b/transport/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard transport diff --git a/transport/snmp/pom.xml b/transport/snmp/pom.xml index 8d7cd799a2..bb7a1ded84 100644 --- a/transport/snmp/pom.xml +++ b/transport/snmp/pom.xml @@ -11,7 +11,7 @@ org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport @@ -47,7 +47,11 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-jackson2 diff --git a/ui-ngx/angular.json b/ui-ngx/angular.json index 4228c68d80..283b19b337 100644 --- a/ui-ngx/angular.json +++ b/ui-ngx/angular.json @@ -72,6 +72,11 @@ "input": "./node_modules/ace-builds/src-noconflict/", "output": "/" }, + { + "glob": "worker-yaml.js", + "input": "./node_modules/ace-builds/src-noconflict/", + "output": "/" + }, { "glob": "worker-tbel.js", "input": "./src/app/shared/models/ace/tbel/", diff --git a/ui-ngx/compress-build.js b/ui-ngx/compress-build.js new file mode 100644 index 0000000000..a81d7f610f --- /dev/null +++ b/ui-ngx/compress-build.js @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 + +// Writes .br and .gz copies of the production build's files, served as-is by the monolith and msa/web-ui. +// Not an esbuild plugin: Angular gives custom plugins only the browser code bundle, not polyfills, +// global styles/scripts or copied assets. + +const os = require('node:os'); + +// zlib runs on the libuv thread pool (4 threads by default), which must be sized before its first use. +// More than 8 threads gains nothing: the largest chunk alone takes ~5 s. +const concurrency = Math.min(os.availableParallelism(), 8); +process.env.UV_THREADPOOL_SIZE = String(concurrency); + +const fs = require('node:fs'); +const path = require('node:path'); +const { promisify } = require('node:util'); +const zlib = require('node:zlib'); + +const gzip = promisify(zlib.gzip); +const brotliCompress = promisify(zlib.brotliCompress); + +const buildDir = path.join(__dirname, 'target', 'generated-resources', 'public'); +// already-compressed formats (png, webp, woff2, ...) are left out +const compressibleExtensions = new Set(['.js', '.mjs', '.css', '.html', '.json', '.svg', '.txt', '.md', '.ttf', '.otf', '.eot']); +const minSize = 10240; + +// brotli quality 11 is only ~2% smaller than 10 but 3x slower; must match precompressedEncodings in msa/web-ui +const encoders = [ + { + ext: '.br', + encode: content => brotliCompress(content, { + params: { + [zlib.constants.BROTLI_PARAM_QUALITY]: 10, + [zlib.constants.BROTLI_PARAM_SIZE_HINT]: content.length + } + }) + }, + { + ext: '.gz', + encode: content => gzip(content, { level: zlib.constants.Z_BEST_COMPRESSION }) + } +]; + +function listFiles(dir) { + return fs.readdirSync(dir, { recursive: true, withFileTypes: true }) + .filter(entry => entry.isFile()) + .map(entry => path.join(entry.parentPath, entry.name)); +} + +async function compress(file, { ext, encode }) { + const content = await fs.promises.readFile(file); + const compressed = await encode(content); + if (compressed.length < content.length) { + await fs.promises.writeFile(file + ext, compressed); + } +} + +async function main() { + // largest first, so the main chunk does not start last + const files = listFiles(buildDir) + .map(file => ({ file, size: fs.statSync(file).size })) + .filter(({ file, size }) => compressibleExtensions.has(path.extname(file).toLowerCase()) && size >= minSize) + .sort((a, b) => b.size - a.size) + .map(({ file }) => file); + const jobs = files.flatMap(file => encoders.map(encoder => () => compress(file, encoder))); + let next = 0; + const worker = async () => { + while (next < jobs.length) { + await jobs[next++](); + } + }; + const start = Date.now(); + await Promise.all(Array.from({ length: concurrency }, worker)); + console.log(`Compressed ${files.length} files (${encoders.map(e => e.ext).join(', ')}) in ${path.relative(__dirname, buildDir)} ` + + `in ${((Date.now() - start) / 1000).toFixed(1)} s on ${concurrency} threads`); +} + +main().catch(error => { + console.error(error); + process.exit(1); +}); diff --git a/ui-ngx/esbuild/tb-esbuild-plugins.ts b/ui-ngx/esbuild/tb-esbuild-plugins.ts index acf7ffcfeb..50f07f8bd5 100644 --- a/ui-ngx/esbuild/tb-esbuild-plugins.ts +++ b/ui-ngx/esbuild/tb-esbuild-plugins.ts @@ -1,10 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-License-Identifier: Apache-2.0 -import type { Plugin, PluginBuild, OutputFile } from 'esbuild'; +import type { Plugin, PluginBuild } from 'esbuild'; import dirTree from 'directory-tree'; import * as packageJson from '../package.json'; -import { gzip } from 'node:zlib'; -import * as path from 'node:path'; const defineTbVariablesPlugin: Plugin = { name: 'tb-define-variables', @@ -36,47 +34,6 @@ const resolveJQueryPlugin: Plugin = { } }; -const compressFileTypes = ['.js', '.css', '.html', '.svg', '.png', '.jpg', '.ttf', '.gif', '.woff', '.woff2', '.eot', '.json']; -const compressThreshold = 10240; - -const compressorPlugin: Plugin = { - name: 'tb-compressor-plugin', - setup(build) { - build.onEnd(async result => { - if (!result.outputFiles || !isProduction()) return; - const outputExt = '.gz'; - const gzippedFiles: OutputFile[] = []; - for (const file of result.outputFiles) { - if (!compressFileTypes.some((ext) => ext === path.extname(file.path))) continue; - if (file.contents.byteLength <= compressThreshold) continue; - const compressedContent = await gzipContent(file.contents); - const compressedFilePath = `${file.path}${outputExt}`; - gzippedFiles.push( - { - path: compressedFilePath, - hash: file.hash, - contents: new Uint8Array(compressedContent), - text: '', - } - ); - } - result.outputFiles.push(...gzippedFiles); - }); - }, -}; - -async function gzipContent(content): Promise { - return new Promise((resolve, reject) => { - gzip(content, (error, result) => { - if (error) { - reject(error); - } else { - resolve(result); - } - }); - }); -} - function isProduction(): boolean { const configurationIndex = process.argv.indexOf('--configuration'); let production = false; @@ -87,4 +44,4 @@ function isProduction(): boolean { return production; } -export default [defineTbVariablesPlugin, resolveJQueryPlugin, compressorPlugin]; +export default [defineTbVariablesPlugin, resolveJQueryPlugin]; diff --git a/ui-ngx/eslint.config.mjs b/ui-ngx/eslint.config.mjs index f003d8cc6d..49c95e6f73 100644 --- a/ui-ngx/eslint.config.mjs +++ b/ui-ngx/eslint.config.mjs @@ -20,16 +20,6 @@ export default tsEslint.config( ], processor: angular.processInlineTemplates, rules: { - "@typescript-eslint/explicit-member-accessibility": [ - "off", - { - accessibility: "explicit" - } - ], - "arrow-parens": [ - "off", - "always" - ], "@angular-eslint/component-selector": [ "error", { @@ -38,7 +28,7 @@ export default tsEslint.config( ] } ], - "id-blacklist": [ + "id-denylist": [ "error", "any", "Number", @@ -49,11 +39,9 @@ export default tsEslint.config( "Undefined", "undefined" ], - "import/order": "off", "@typescript-eslint/member-ordering": "off", "no-underscore-dangle": "off", "@typescript-eslint/naming-convention": "off", - "jsdoc/newline-after-description": 0, "@typescript-eslint/consistent-indexed-object-style": "off", "@typescript-eslint/array-type": "off", "no-extra-boolean-cast": "off", diff --git a/ui-ngx/package.json b/ui-ngx/package.json index 1a7a15c765..afd546805d 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -1,11 +1,12 @@ { "name": "thingsboard", - "version": "4.4.1", + "version": "4.4.2", "scripts": { "ng": "ng", "start": "node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng serve --configuration development --host 0.0.0.0 --open", "build": "ng build", "build:prod": "node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng build --configuration production", + "compress": "node compress-build.js", "build:types": "node generate-types.js", "build:icon-metadata": "node generate-icon-metadata.js", "sbom": "node ../tools/src/main/javascript/yarn-sbom.js target/generated-resources/META-INF/sbom/ui-ngx.cdx.json library", @@ -27,6 +28,8 @@ "@auth0/angular-jwt": "^5.2.0", "@flowjs/flow.js": "^2.14.1", "@flowjs/ngx-flow": "20.0.2", + "@fontsource-variable/roboto": "^5.3.0", + "@fontsource-variable/roboto-mono": "^5.3.0", "@fullcalendar/angular": "^6.1.20", "@fullcalendar/core": "^6.1.20", "@fullcalendar/daygrid": "^6.1.20", @@ -40,6 +43,7 @@ "@mat-datetimepicker/core": "~16.0.1", "@mdi/svg": "^7.4.47", "@messageformat/core": "^3.4.1", + "@messageformat/parser": "^5.2.0", "@ngrx/effects": "^20.1.0", "@ngrx/store": "^20.1.0", "@ngrx/store-devtools": "^20.1.0", @@ -54,21 +58,19 @@ "angular-gridster2": "~20.2.4", "angular2-hotkeys": "^16.0.1", "canvas-gauges": "^2.1.7", - "core-js": "^3.51.0", "dayjs": "1.11.23", + "dompurify": "^3.3.3", "echarts": "https://github.com/thingsboard/echarts/archive/5.5.4-TB.tar.gz", "exceljs-hardened": "~5.1.0", "flag-icons": "7.6.0", "flot": "https://github.com/thingsboard/flot.git#0.9-work", "flot.curvedlines": "https://github.com/MichaelZinsmaier/CurvedLines.git#master", "font-awesome": "^4.7.0", - "html2canvas": "^1.4.1", "hugerte": "~1.0.14", "jquery": "^3.7.1", "jquery-sparkline": "^2.4.0", "jquery.terminal": "^2.48.1", - "js-beautify": "1.15.4", - "json-schema-defaults": "^0.4.0", + "js-beautify": "2.0.3", "jstree": "^3.3.17", "jstree-bootstrap-theme": "^1.0.1", "jszip": "^3.10.2", @@ -79,25 +81,27 @@ "leaflet.gridlayer.googlemutant": "0.15.0", "leaflet.markercluster": "1.5.3", "libphonenumber-js": "^1.13.15", + "lodash": "^4.18.1", "maplibre-gl": "6.15.0", "marked": "~16.4.2", + "modern-screenshot": "^4.7.0", "moment": "^2.31.0", "moment-timezone": "^0.6.5", + "mousetrap": "^1.6.5", "ngx-captcha": "^14.0.0", "ngx-clipboard": "^16.0.0", "ngx-daterangepicker-material": "^6.0.4", "ngx-drag-drop": "^20.0.1", "ngx-flowchart": "https://github.com/thingsboard/ngx-flowchart.git#release/4.1.0", - "ngx-hm-carousel": "^19.0.0", "ngx-markdown": "^20.1.0", "ngx-sharebuttons": "^17.0.0", "ngx-translate-messageformat-compiler": "^7.3.0", "objectpath": "^2.0.0", "photoswipe": "^5.4.4", + "prismjs": "^1.30.0", "qrcode": "^1.5.4", "raphael": "^2.3.0", "rxjs": "~7.8.2", - "schema-inspector": "^2.1.0", "screenfull": "^6.0.2", "sorted-btree": "^1.8.1", "split.js": "^1.6.5", @@ -105,20 +109,16 @@ "tinycolor2": "^1.6.0", "tooltipster": "^4.2.8", "tslib": "^2.8.1", - "typeface-roboto": "^1.1.13", - "typeface-roboto-mono": "^1.1.13", "yaml": "^2.6.1", "zone.js": "~0.15.1" }, "devDependencies": { "@angular-builders/custom-esbuild": "20.0.0", - "@angular-devkit/core": "20.3.41", - "@angular-devkit/schematics": "20.3.41", "@angular/build": "20.3.41", "@angular/cli": "20.3.41", "@angular/compiler-cli": "20.3.34", - "@angular/language-service": "20.3.34", "@cyclonedx/cyclonedx-library": "10.3.0", + "@eslint/js": "9.39.5", "@types/ace-diff": "^2.1.4", "@types/canvas-gauges": "^2.1.8", "@types/flot": "^0.0.36", @@ -141,24 +141,19 @@ "autoprefixer": "^10.6.1", "directory-tree": "^3.6.0", "eslint": "9.39.5", - "eslint-plugin-import": "^2.32.0", - "eslint-plugin-jsdoc": "^62.9.0", - "eslint-plugin-prefer-arrow": "^1.2.3", "eslint-plugin-tailwindcss": "^3.18.3", "normalize-package-data": "8.0.0", "packageurl-js": "2.0.1", "patch-package": "^8.0.1", "postcss": "^8.5.31", - "postinstall-prepare": "^2.0.0", "spdx-expression-parse": "4.0.0", "tailwindcss": "^3.4.19", - "ts-node": "^10.9.2", "typescript": "~5.9.3", "typescript-eslint": "^8.72.0" }, "resolutions": { "esbuild": "0.28.1", "rollup": "4.59.0", - "js-beautify/**/minimatch": "^9.0.7" + "@angular/cli/**/tar": "^8.0.5" } } diff --git a/ui-ngx/patches/ngx-hm-carousel+19.0.0.patch b/ui-ngx/patches/ngx-hm-carousel+19.0.0.patch deleted file mode 100644 index 0dfee707e1..0000000000 --- a/ui-ngx/patches/ngx-hm-carousel+19.0.0.patch +++ /dev/null @@ -1,31 +0,0 @@ -diff --git a/node_modules/ngx-hm-carousel/fesm2022/ngx-hm-carousel.mjs b/node_modules/ngx-hm-carousel/fesm2022/ngx-hm-carousel.mjs -index 117f782..70e49a7 100644 ---- a/node_modules/ngx-hm-carousel/fesm2022/ngx-hm-carousel.mjs -+++ b/node_modules/ngx-hm-carousel/fesm2022/ngx-hm-carousel.mjs -@@ -1,5 +1,5 @@ - import * as i0 from '@angular/core'; --import { Directive, inject, ViewContainerRef, TemplateRef, input, PLATFORM_ID, DestroyRef, Renderer2, NgZone, ChangeDetectorRef, viewChild, ElementRef, contentChildren, contentChild, computed, signal, effect, forwardRef, Component, ChangeDetectionStrategy } from '@angular/core'; -+import { Directive, inject, ViewContainerRef, TemplateRef, input, PLATFORM_ID, DestroyRef, Renderer2, NgZone, ChangeDetectorRef, viewChild, ElementRef, contentChildren, contentChild, computed, signal, effect, forwardRef, Component, ChangeDetectionStrategy, afterNextRender } from '@angular/core'; - import { DOCUMENT, isPlatformBrowser, NgTemplateOutlet, AsyncPipe } from '@angular/common'; - import { toObservable, takeUntilDestroyed } from '@angular/core/rxjs-interop'; - import { NG_VALUE_ACCESSOR } from '@angular/forms'; -@@ -340,7 +340,7 @@ class NgxHmCarouselComponent { - }); - }); - }); -- const effectRef = effect(() => { -+ afterNextRender(() => { - this.rootElm = this.container().nativeElement; - this.containerElm = this.rootElm.children[0]; - this.init(); -@@ -365,10 +365,6 @@ class NgxHmCarouselComponent { - ]) - .pipe(takeUntilDestroyed(this._destroyRef)) - .subscribe(); -- // only exec once -- effectRef.destroy(); -- }, { -- allowSignalWrites: true, - }); - } - ngOnDestroy() { diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index 7758fa08fc..7ca54393be 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard ui-ngx @@ -57,7 +57,7 @@ install-node-and-yarn - v22.23.4 + v22.23.5 v1.22.22 @@ -127,6 +127,15 @@ --mutex network run build:prod + + yarn compress + + yarn + + + run compress + + diff --git a/ui-ngx/src/app/app.component.ts b/ui-ngx/src/app/app.component.ts index b811c7fc2c..9ad8eebeac 100644 --- a/ui-ngx/src/app/app.component.ts +++ b/ui-ngx/src/app/app.component.ts @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import 'hammerjs'; - import { Component } from '@angular/core'; import { environment as env } from '@env/environment'; diff --git a/ui-ngx/src/app/core/auth/auth.actions.ts b/ui-ngx/src/app/core/auth/auth.actions.ts index 328f2e06da..5a1778c63f 100644 --- a/ui-ngx/src/app/core/auth/auth.actions.ts +++ b/ui-ngx/src/app/core/auth/auth.actions.ts @@ -4,7 +4,7 @@ import { Action } from '@ngrx/store'; import { AuthUser, User } from '@shared/models/user.model'; import { AuthPayload } from '@core/auth/auth.models'; -import { UserSettings } from '@shared/models/user-settings.models'; +import { AiTourStep, HomeCardsSettings, UserSettings } from '@shared/models/user-settings.models'; export enum AuthActionTypes { AUTHENTICATED = '[Auth] Authenticated', @@ -16,6 +16,8 @@ export enum AuthActionTypes { UPDATE_HAS_REPOSITORY = '[Auth] Change Has Repository', UPDATE_MOBILE_QR_ENABLED = '[Auth] Update Mobile QR Enabled', UPDATE_OPENED_MENU_SECTION = '[Preferences] Update Opened Menu Section', + UPDATE_AI_TOUR = '[Preferences] Update AI tour', + UPDATE_HOME_CARDS = '[Preferences] Update home cards', PUT_USER_SETTINGS = '[Preferences] Put user settings', DELETE_USER_SETTINGS = '[Preferences] Delete user settings', UPDATE_LICENSE_PARAMS = '[Auth] Update License Parameters', @@ -73,6 +75,18 @@ export class ActionPreferencesUpdateOpenedMenuSection implements Action { constructor(readonly payload: { path: string; opened: boolean }) {} } +export class ActionPreferencesUpdateAiTour implements Action { + readonly type = AuthActionTypes.UPDATE_AI_TOUR; + + constructor(readonly payload: { step: AiTourStep; seen: boolean }) {} +} + +export class ActionPreferencesUpdateHomeCards implements Action { + readonly type = AuthActionTypes.UPDATE_HOME_CARDS; + + constructor(readonly payload: HomeCardsSettings) {} +} + export class ActionPreferencesPutUserSettings implements Action { readonly type = AuthActionTypes.PUT_USER_SETTINGS; @@ -93,5 +107,5 @@ export class ActionUpdateLicenseParams implements Action { export type AuthActions = ActionAuthAuthenticated | ActionAuthUnauthenticated | ActionAuthLoadUser | ActionAuthUpdateUserDetails | ActionAuthUpdateLastPublicDashboardId | ActionAuthUpdateHasRepository | - ActionPreferencesUpdateOpenedMenuSection | ActionPreferencesPutUserSettings | ActionPreferencesDeleteUserSettings | + ActionPreferencesUpdateOpenedMenuSection | ActionPreferencesUpdateAiTour | ActionPreferencesUpdateHomeCards | ActionPreferencesPutUserSettings | ActionPreferencesDeleteUserSettings | ActionAuthUpdateAuthUser | ActionUpdateMobileQrCodeEnabled | ActionUpdateLicenseParams; diff --git a/ui-ngx/src/app/core/auth/auth.effects.ts b/ui-ngx/src/app/core/auth/auth.effects.ts index 1b006fd4f1..49812fc732 100644 --- a/ui-ngx/src/app/core/auth/auth.effects.ts +++ b/ui-ngx/src/app/core/auth/auth.effects.ts @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { Injectable } from '@angular/core'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { select, Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { UserSettingsService } from '@core/http/user-settings.service'; -import { mergeMap, withLatestFrom } from 'rxjs/operators'; +import { concatMap, mergeMap, withLatestFrom } from 'rxjs/operators'; import { AuthActions, AuthActionTypes } from '@core/auth/auth.actions'; import { selectAuthState } from '@core/auth/auth.selectors'; @@ -26,6 +27,22 @@ export class AuthEffects { mergeMap(([action, state]) => this.userSettingsService.putUserSettings({ openedMenuSections: state.userSettings.openedMenuSections })) ), {dispatch: false}); + persistAiTour = createEffect(() => this.actions$.pipe( + ofType( + AuthActionTypes.UPDATE_AI_TOUR, + ), + withLatestFrom(this.store.pipe(select(selectAuthState))), + concatMap(([action, state]) => this.userSettingsService.putUserSettings({ aiTour: state.userSettings.aiTour ?? {} })) + ), {dispatch: false}); + + persistHomeCards = createEffect(() => this.actions$.pipe( + ofType( + AuthActionTypes.UPDATE_HOME_CARDS, + ), + withLatestFrom(this.store.pipe(select(selectAuthState))), + concatMap(([action, state]) => this.userSettingsService.putUserSettings({ homeCards: state.userSettings.homeCards ?? {} })) + ), {dispatch: false}); + putUserSettings = createEffect(() => this.actions$.pipe( ofType( AuthActionTypes.PUT_USER_SETTINGS, diff --git a/ui-ngx/src/app/core/auth/auth.reducer.ts b/ui-ngx/src/app/core/auth/auth.reducer.ts index 8fa0d1d2ac..9643135e4b 100644 --- a/ui-ngx/src/app/core/auth/auth.reducer.ts +++ b/ui-ngx/src/app/core/auth/auth.reducer.ts @@ -97,6 +97,20 @@ export const authReducer = ( userSettings = {...state.userSettings, ...{ openedMenuSections: Array.from(openedMenuSections)}}; return { ...state, ...{ userSettings }}; + case AuthActionTypes.UPDATE_AI_TOUR: + const aiTour = {...state.userSettings.aiTour}; + if (action.payload.seen) { + aiTour[action.payload.step] = Date.now(); + } else { + delete aiTour[action.payload.step]; + } + userSettings = {...state.userSettings, aiTour}; + return { ...state, ...{ userSettings }}; + + case AuthActionTypes.UPDATE_HOME_CARDS: + userSettings = {...state.userSettings, homeCards: {...state.userSettings.homeCards, ...action.payload}}; + return { ...state, ...{ userSettings }}; + case AuthActionTypes.PUT_USER_SETTINGS: userSettings = {...state.userSettings, ...action.payload}; return { ...state, ...{ userSettings }}; diff --git a/ui-ngx/src/app/core/auth/auth.selectors.ts b/ui-ngx/src/app/core/auth/auth.selectors.ts index 399fe27183..a0e9f57483 100644 --- a/ui-ngx/src/app/core/auth/auth.selectors.ts +++ b/ui-ngx/src/app/core/auth/auth.selectors.ts @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { createFeatureSelector, createSelector, select, Store } from '@ngrx/store'; import { AppState } from '../core.state'; import { AuthState } from './auth.models'; import { take } from 'rxjs/operators'; import { AuthUser } from '@shared/models/user.model'; -import { UserSettings } from '@shared/models/user-settings.models'; +import { AiTourStep, UserSettings } from '@shared/models/user-settings.models'; import { getDescendantProp } from '@core/utils'; export const selectAuthState = createFeatureSelector< AuthState>( @@ -69,12 +70,6 @@ export const selectMobileQrEnabled = createSelector( (state: AuthState) => state.mobileQrEnabled ); -export const selectHomeDashboardParams = createSelector( - selectPersistDeviceStateToTelemetry, - selectMobileQrEnabled, - (persistDeviceStateToTelemetry, mobileQrEnabled) => ({persistDeviceStateToTelemetry, mobileQrEnabled}) -); - export const selectUserSettings = createSelector( selectAuthState, (state: AuthState) => state.userSettings @@ -90,6 +85,20 @@ export const selectOpenedMenuSections = createSelector( (state: AuthState) => state.userSettings.openedMenuSections ); +export const selectAiTour = createSelector( + selectAuthState, + (state: AuthState) => state.userSettings?.aiTour ?? {} +); + +export const selectAiTourStepSeen = (step: AiTourStep) => createSelector( + selectAiTour, + aiTour => !!aiTour[step] +); + +export const selectHomeCards = createSelector( + selectAuthState, + (state: AuthState) => state.userSettings?.homeCards ?? {} +); export const getCurrentAuthState = (store: Store): AuthState => { let state: AuthState; diff --git a/ui-ngx/src/app/core/auth/auth.service.ts b/ui-ngx/src/app/core/auth/auth.service.ts index edd852247c..1c4c57431e 100644 --- a/ui-ngx/src/app/core/auth/auth.service.ts +++ b/ui-ngx/src/app/core/auth/auth.service.ts @@ -10,7 +10,7 @@ import { catchError, map, mergeMap, tap } from 'rxjs/operators'; import { setEdqsEnabled, setNullsOrderStrategy } from '@shared/models/page/page-link'; import { LoginRequest, LoginResponse, PublicLoginRequest } from '@shared/models/login.models'; -import { Router, UrlTree } from '@angular/router'; +import { PRIMARY_OUTLET, Router, UrlTree } from '@angular/router'; import { defaultHttpOptions, defaultHttpOptionsFromConfig, RequestConfig } from '../http/http-utils'; import { UserService } from '../http/user.service'; import { Store } from '@ngrx/store'; @@ -281,24 +281,12 @@ export class AuthService { } else if (authState.authUser.authority === Authority.MFA_CONFIGURATION_TOKEN) { result = this.router.parseUrl('login/force-mfa'); } else if (!path || path === 'login' || this.forceDefaultPlace(authState, path, params)) { - if (this.redirectUrl) { - const redirectUrl = this.redirectUrl; - this.redirectUrl = null; + const redirectUrl = this.redirectUrl; + this.redirectUrl = null; + if (redirectUrl && !authState.authUser.isPublic && this.isDeepLink(redirectUrl)) { result = this.router.parseUrl(redirectUrl); } else { - result = this.router.parseUrl('home'); - } - if (authState.authUser.authority === Authority.TENANT_ADMIN || authState.authUser.authority === Authority.CUSTOMER_USER) { - if (this.userHasDefaultDashboard(authState)) { - const dashboardId = authState.userDetails.additionalInfo.defaultDashboardId; - if (authState.forceFullscreen) { - result = this.router.parseUrl(`dashboard/${dashboardId}`); - } else { - result = this.router.parseUrl(`dashboards/${dashboardId}`); - } - } else if (authState.authUser.isPublic && authState.lastPublicDashboardId) { - result = this.router.parseUrl(`dashboard/${authState.lastPublicDashboardId}`); - } + result = this.defaultPlaceUrl(authState); } } } else { @@ -339,6 +327,23 @@ export class AuthService { })); } + private defaultPlaceUrl(authState: AuthState): UrlTree { + if (authState.authUser.authority === Authority.TENANT_ADMIN || authState.authUser.authority === Authority.CUSTOMER_USER) { + if (this.userHasDefaultDashboard(authState)) { + const dashboardId = authState.userDetails.additionalInfo.defaultDashboardId; + return this.router.parseUrl(authState.forceFullscreen ? `dashboard/${dashboardId}` : `dashboards/${dashboardId}`); + } else if (authState.authUser.isPublic && authState.lastPublicDashboardId) { + return this.router.parseUrl(`dashboard/${authState.lastPublicDashboardId}`); + } + } + return this.router.parseUrl('home'); + } + + private isDeepLink(url: string): boolean { + const segments = this.router.parseUrl(url).root.children[PRIMARY_OUTLET]?.segments.map(segment => segment.path) ?? []; + return segments.length > 0 && segments[0] !== 'login' && !(segments.length === 1 && segments[0] === 'home'); + } + private loadUser(doTokenRefresh): Observable { const authUser = getCurrentAuthUser(this.store); if (!authUser) { diff --git a/ui-ngx/src/app/core/http/admin.service.ts b/ui-ngx/src/app/core/http/admin.service.ts index 8f76ee61c7..77591e5d29 100644 --- a/ui-ngx/src/app/core/http/admin.service.ts +++ b/ui-ngx/src/app/core/http/admin.service.ts @@ -10,7 +10,6 @@ import { AutoCommitSettings, FeaturesInfo, JwtSettings, - LicenseUsageInfo, MailConfigTemplate, MailServerSettings, RepositorySettings, @@ -128,10 +127,6 @@ export class AdminService { return this.http.get('/api/admin/featuresInfo', defaultHttpOptionsFromConfig(config)); } - public getLicenseUsageInfo(config?: RequestConfig): Observable { - return this.http.get('/api/admin/licenseUsageInfo', defaultHttpOptionsFromConfig(config)); - } - public getSubscriptionInfo(config?: RequestConfig): Observable { return this.http.get('/api/admin/subscriptionInfo', defaultHttpOptionsFromConfig(config)); } diff --git a/ui-ngx/src/app/core/http/ai-chat.service.ts b/ui-ngx/src/app/core/http/ai-chat.service.ts index 76b343c072..3a91763c7f 100644 --- a/ui-ngx/src/app/core/http/ai-chat.service.ts +++ b/ui-ngx/src/app/core/http/ai-chat.service.ts @@ -7,6 +7,7 @@ import { HttpClient, HttpEventType } from '@angular/common/http'; import { ApprovalResult, ChatConfiguration, + ChatUpdate, ChatEvent, ChatInfo, SendChatMessageRequest, @@ -29,11 +30,15 @@ export class AiChatService { return this.http.get>(`/api/ai/chats`, defaultHttpOptionsFromConfig(config)) } + public listChatStatuses(config?: RequestConfig): Observable> { + return this.http.get>(`/api/ai/chats/status`, defaultHttpOptionsFromConfig(config)); + } + public createChat(chat: ChatConfiguration, config?: RequestConfig): Observable { return this.http.post(`/api/ai/chats`, chat, defaultHttpOptionsFromConfig(config)); } - public updatedChat(chatId: string, chat: ChatConfiguration, config?: RequestConfig): Observable { + public updatedChat(chatId: string, chat: ChatUpdate, config?: RequestConfig): Observable { return this.http.patch(`/api/ai/chats/${chatId}`, chat, defaultHttpOptionsFromConfig(config)); } @@ -45,10 +50,6 @@ export class AiChatService { return this.http.get>(`/api/ai/chats/${chatId}/messages`, defaultHttpOptionsFromConfig(config)) } - public generateDashboard(deviceId: string, timeseriesKeys?: string[], config?: RequestConfig): Observable { - return this.http.post(`/api/ai/devices/${deviceId}/dashboard`, { timeseriesKeys }, defaultHttpOptionsFromConfig(config)); - } - public resolveToolApproval(result: ApprovalResult, config?: RequestConfig): Observable { return this.http.post('/api/ai/tools/resolve-approval', result, defaultHttpOptionsFromConfig(config)) } @@ -57,6 +58,10 @@ export class AiChatService { return this.streamEvents(`/api/ai/chats/${chatId}/messages`, request, config); } + public stopChat(chatId: string, config?: RequestConfig): Observable { + return this.http.post(`/api/ai/chats/${chatId}/stop`, null, defaultHttpOptionsFromConfig(config)); + } + /** * Follows the reply still running in the chat: a 'turnResumed' event, every event of the reply so far, then the * live ones. Completes with no events when nothing is running. @@ -110,6 +115,9 @@ export class AiChatService { const result: Partial = {}; const lines = input.trim().split('\n'); + if (lines.every(line => !line.trim() || line.trim().startsWith(':'))) { + return null; + } for (const line of lines) { const trimmedLine = line.trim(); diff --git a/ui-ngx/src/app/core/http/custom-menu.service.ts b/ui-ngx/src/app/core/http/custom-menu.service.ts index 7c896934e2..92ad715dd6 100644 --- a/ui-ngx/src/app/core/http/custom-menu.service.ts +++ b/ui-ngx/src/app/core/http/custom-menu.service.ts @@ -7,7 +7,8 @@ import { CustomMenu, CustomMenuConfig, CustomMenuDeleteResult, - CustomMenuInfo + CustomMenuInfo, + withCurrentMenuIds } from '@shared/models/custom-menu.models'; import { mergeMap, Observable, of, Subject } from 'rxjs'; import { map, tap } from 'rxjs/operators'; @@ -38,6 +39,7 @@ export class CustomMenuService { public loadCustomMenu(notify = false): Observable { return this.http.get('/api/customMenu') .pipe( + map(customMenuConfig => withCurrentMenuIds(customMenuConfig)), tap((customMenuConfig) => { this.customMenuConfig = customMenuConfig; if (notify) { diff --git a/ui-ngx/src/app/core/http/dashboard.service.ts b/ui-ngx/src/app/core/http/dashboard.service.ts index 15c2501a76..30608a5b75 100644 --- a/ui-ngx/src/app/core/http/dashboard.service.ts +++ b/ui-ngx/src/app/core/http/dashboard.service.ts @@ -60,7 +60,7 @@ export class DashboardService { } public getUserDashboards(userId: string, operation: Operation, - pageLink: PageLink, config?: RequestConfig): Observable> { + pageLink: PageLink, config?: RequestConfig, mobile = false): Observable> { let url = `/api/user/dashboards${pageLink.toQuery()}`; if (userId) { url += `&userId=${userId}`; @@ -68,6 +68,9 @@ export class DashboardService { if (operation) { url += `&operation=${operation}`; } + if (mobile) { + url += `&mobile=true`; + } return this.http.get>(url, defaultHttpOptionsFromConfig(config)); } diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index fa040e8632..b9af2299f2 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -4,7 +4,8 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Store } from '@ngrx/store'; -import { Observable } from 'rxjs'; +import { forkJoin, Observable, of } from 'rxjs'; +import { map } from 'rxjs/operators'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; import { @@ -13,7 +14,7 @@ import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; -import { DevicePackageEntityState, DeviceUpdateRequest, DeviceUpdateResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +import { DevicePackageEntityState, DevicePackageRequest, DevicePackageResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params'; import { InterceptorConfig } from '@core/interceptors/interceptor-config'; @@ -50,6 +51,8 @@ export function iotHubResourceUrl(baseUrl: string, path: string): string { return `${baseUrl}${path.startsWith('/') ? '' : '/'}${path}`; } +const PUBLISHED_VERSIONS_CHUNK_SIZE = 100; + export interface IotHubRequestConfig { ignoreLoading?: boolean; ignoreErrors?: boolean; @@ -177,18 +180,6 @@ export class IotHubApiService { ); } - public registerDeviceInstall( - versionId: string, - descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, - config?: IotHubRequestConfig - ): Observable { - return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}`, - { type: 'DEVICE', ...descriptor }, - { params: this.buildParams(config) } - ); - } - public installItemVersion(versionId: string, config?: IotHubRequestConfig, data?: any): Observable { return this.http.post( `/api/iot-hub/versions/${versionId}/install`, @@ -240,11 +231,7 @@ export class IotHubApiService { public getInstalledItems(pageLink: PageLink, itemTypes?: string | string[], itemId?: string, config?: IotHubRequestConfig): Observable> { - let query = pageLink.toQuery(); - if (itemTypes) { - const types = Array.isArray(itemTypes) ? itemTypes : [itemTypes]; - types.forEach(t => query += `&itemTypes=${t}`); - } + let query = this.installedItemsQuery(pageLink, itemTypes); if (itemId) { query += `&itemId=${itemId}`; } @@ -254,6 +241,16 @@ export class IotHubApiService { ); } + /** Body: published version id by item id; returns items installed in a different version. */ + public getInstalledItemsWithUpdates(pageLink: PageLink, itemTypes: string[] | null, publishedVersionIds: Record, + config?: IotHubRequestConfig): Observable> { + return this.http.post>( + `/api/iot-hub/installedItems/withUpdates${this.installedItemsQuery(pageLink, itemTypes)}`, + publishedVersionIds, + { params: this.buildParams(config) } + ); + } + public getInstalledItemsCount(itemType?: string, config?: IotHubRequestConfig): Observable { let url = '/api/iot-hub/installedItems/count'; if (itemType) { @@ -278,14 +275,23 @@ export class IotHubApiService { } /** Applies a device package update in one transaction: all of it, or nothing. */ - public updateDevicePackage(installedItemId: string, request: DeviceUpdateRequest, config?: IotHubRequestConfig): Observable { - return this.http.post( + public updateDevicePackage(installedItemId: string, request: DevicePackageRequest, config?: IotHubRequestConfig): Observable { + return this.http.post( `/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`, request, { params: this.buildParams(config) } ); } + /** Installs a device package in one transaction: all of its entities and the installed item, or nothing. */ + public installDevicePackage(request: DevicePackageRequest, config?: IotHubRequestConfig): Observable { + return this.http.post( + `/api/iot-hub/device/install`, + request, + { params: this.buildParams(config) } + ); + } + public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable { return this.http.get( `/api/iot-hub/installedItems/${installedItemId}/keptEntities`, @@ -294,11 +300,18 @@ export class IotHubApiService { } public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable { - return this.http.post( + if (!itemIds.length) { + return of([]); + } + const chunks: string[][] = []; + for (let i = 0; i < itemIds.length; i += PUBLISHED_VERSIONS_CHUNK_SIZE) { + chunks.push(itemIds.slice(i, i + PUBLISHED_VERSIONS_CHUNK_SIZE)); + } + return forkJoin(chunks.map(chunk => this.http.post( `${this.baseUrl}/api/versions/publishedVersions`, - itemIds, + chunk, { params: this.buildParams(config) } - ); + ))).pipe(map(results => results.flat())); } public getCreatorProfile(creatorId: string, config?: IotHubRequestConfig): Observable { @@ -308,6 +321,11 @@ export class IotHubApiService { ); } + private installedItemsQuery(pageLink: PageLink, itemTypes?: string | string[] | null): string { + const types = !itemTypes ? [] : Array.isArray(itemTypes) ? itemTypes : [itemTypes]; + return pageLink.toQuery() + types.map(t => `&itemTypes=${t}`).join(''); + } + private buildParams(config?: IotHubRequestConfig): HttpParams { return new InterceptorHttpParams( new InterceptorConfig(config?.ignoreLoading ?? false, config?.ignoreErrors ?? false) diff --git a/ui-ngx/src/app/core/http/notification.service.ts b/ui-ngx/src/app/core/http/notification.service.ts index 42e831e2fd..ecd6ed315e 100644 --- a/ui-ngx/src/app/core/http/notification.service.ts +++ b/ui-ngx/src/app/core/http/notification.service.ts @@ -66,6 +66,10 @@ export class NotificationService { return this.http.post(`/api/notification/sendAddonAccessRequest/${addonType}`, null, defaultHttpOptionsFromConfig(config)); } + public sendAiCreditsLimitIncreaseRequest(limitType: 'TENANT' | 'POOL', config?: RequestConfig): Observable { + return this.http.post(`/api/notification/aiCreditsLimitIncreaseRequest?limitType=${limitType}`, null, defaultHttpOptionsFromConfig(config)); + } + public sendPlanUpgradeRequest(planName: string, config?: RequestConfig): Observable { return this.http.post(`/api/notification/sendPlanUpgradeRequest/${planName}`, null, defaultHttpOptionsFromConfig(config)); } diff --git a/ui-ngx/src/app/core/http/solutions-creator.service.ts b/ui-ngx/src/app/core/http/solutions-creator.service.ts index 2cfc4b2bb2..4cd06c68e3 100644 --- a/ui-ngx/src/app/core/http/solutions-creator.service.ts +++ b/ui-ngx/src/app/core/http/solutions-creator.service.ts @@ -9,8 +9,10 @@ import { SolutionDataKey, SolutionDataValues, SolutionInfo, + SolutionInstallProgress, SolutionInstallResult, - SolutionStep + SolutionStep, + SolutionUpdateRequest } from '@shared/models/solution-creator.models'; @Injectable({ @@ -35,6 +37,10 @@ export class SolutionsCreatorService { return this.http.delete(`/api/ai/solution/${solutionId}/${step}/clear`, defaultHttpOptionsFromConfig(config)); } + public stopSolution(solutionId: string, config?: RequestConfig): Observable { + return this.http.post(`/api/ai/solution/${solutionId}/stop`, null, defaultHttpOptionsFromConfig(config)); + } + public createSolution(solutionId: string, config?: RequestConfig): Observable { return this.http.post(`/api/ai/solution/${solutionId}/create`, '', defaultHttpOptionsFromConfig(config)); } @@ -64,4 +70,12 @@ export class SolutionsCreatorService { public deleteSolution(solutionId: string, config?: RequestConfig): Observable { return this.http.delete(`/api/ai/solution/${solutionId}`, defaultHttpOptionsFromConfig(config)); } + + public updateSolution(solutionId: string, request: SolutionUpdateRequest, config?: RequestConfig): Observable { + return this.http.post(`/api/ai/solution/${solutionId}/update`, request, defaultHttpOptionsFromConfig(config)); + } + + public getInstallProgress(solutionId: string, config?: RequestConfig): Observable { + return this.http.get(`/api/ai/solution/${solutionId}/progress`, defaultHttpOptionsFromConfig(config)); + } } diff --git a/ui-ngx/src/app/core/http/user-permissions.service.ts b/ui-ngx/src/app/core/http/user-permissions.service.ts index 71f952154d..2c93cedd4e 100644 --- a/ui-ngx/src/app/core/http/user-permissions.service.ts +++ b/ui-ngx/src/app/core/http/user-permissions.service.ts @@ -1,9 +1,10 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; -import { tap } from 'rxjs/operators'; +import { distinctUntilChanged, map, tap } from 'rxjs/operators'; import { AllowedPermissionsInfo, groupResourceByGroupType, @@ -19,7 +20,10 @@ import { isArray } from '@core/utils'; import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-utils'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; +import { getCurrentAuthState, selectAuth } from '@core/auth/auth.selectors'; +import { Authority } from '@shared/models/authority.enum'; + +const AI_RESOURCES: Resource[] = [Resource.AI, Resource.AI_MODEL]; @Injectable({ providedIn: 'root' @@ -34,6 +38,11 @@ export class UserPermissionsService { private userPermissions: MergedUserPermissions; private userOwnerId: EntityId; + readonly aiAvailable = toSignal(inject(Store).select(selectAuth).pipe( + map(() => this.isAiAvailable()), + distinctUntilChanged() + ), {initialValue: false}); + constructor( private http: HttpClient, private store: Store @@ -122,15 +131,42 @@ export class UserPermissionsService { } } + public hasGenericPermissionExceptAi(operation: Operation): boolean { + if (!this.userPermissions) { + return false; + } + if (this.hasGenericAllPermission(Resource.ALL, operation)) { + return true; + } + return Object.keys(this.operationsByResource ?? {}) + .filter(resource => resource !== Resource.ALL && !AI_RESOURCES.includes(resource as Resource)) + .every(resource => this.hasEveryOperation(resource as Resource, operation)); + } + + private hasEveryOperation(resource: Resource, operation: Operation): boolean { + const valid = this.operationsByResource[resource] ?? []; + if (operation !== Operation.ALL) { + return !valid.includes(operation) || this.hasGenericResourcePermission(resource, operation); + } + const required = valid.filter(op => op !== Operation.ALL); + return required.length ? required.every(op => this.hasGenericResourcePermission(resource, op)) + : this.hasGenericResourcePermission(resource, Operation.ALL); + } + public isAiEnabled(): boolean { return getCurrentAuthState(this.store).aiEnabled; } + public isAiAvailable(operation: Operation = Operation.ALL): boolean { + const authState = getCurrentAuthState(this.store); + return !!authState?.aiEnabled && authState.authUser?.authority === Authority.TENANT_ADMIN + && this.hasGenericPermission(Resource.AI, operation); + } + private isResourceAllowed(resource: Resource): boolean { return !this.allowedResources || this.allowedResources.indexOf(resource) > -1; } - public hasGenericPermissionByEntityGroupType(operation: Operation, groupType: EntityType): boolean { if (!groupType) { return false; diff --git a/ui-ngx/src/app/core/http/widget.service.ts b/ui-ngx/src/app/core/http/widget.service.ts index 0f25a0b2f0..47f7923b9b 100644 --- a/ui-ngx/src/app/core/http/widget.service.ts +++ b/ui-ngx/src/app/core/http/widget.service.ts @@ -26,10 +26,7 @@ import { filter, map, mergeMap, tap } from 'rxjs/operators'; import { WidgetTypeId } from '@shared/models/id/widget-type-id'; import { NULL_UUID } from '@shared/models/id/has-uuid'; import { ActivationEnd, Router } from '@angular/router'; -import { - BasicWidgetConfigComponent, - IBasicWidgetConfigComponent -} from '@home/components/widget/config/widget-config.component.models'; +import type { BasicWidgetConfigComponent, IBasicWidgetConfigComponent } from '@home/components/widget/config/widget-config.component.models'; import { ResourcesService } from '@core/services/resources.service'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { Operation, Resource } from '@shared/models/security.models'; @@ -301,8 +298,8 @@ export class WidgetService { this.widgetsInfoInMemoryCache.set(widgetInfo.fullFqn, widgetInfo); } - public registerBasicWidgetConfigComponents(module: any) { - Object.assign(this.basicWidgetSettingsComponentsMap, this.resourcesService.extractComponentsFromModule(module, BasicWidgetConfigComponent)); + public registerBasicWidgetConfigComponents(module: any, baseType: typeof BasicWidgetConfigComponent) { + Object.assign(this.basicWidgetSettingsComponentsMap, this.resourcesService.extractComponentsFromModule(module, baseType)); } public getBasicWidgetSettingsComponentBySelector(selector: string): Type { diff --git a/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts b/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts index 23db865351..0ae54e2121 100644 --- a/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts +++ b/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts @@ -1,18 +1,18 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; +import { HttpErrorResponse, HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs/internal/Observable'; import { DOCUMENT, Inject, Injectable } from '@angular/core'; import { AuthService } from '@core/auth/auth.service'; import { Constants } from '@shared/models/constants'; -import { catchError, delay, finalize, mergeMap, switchMap } from 'rxjs/operators'; +import { catchError, delay, finalize, mergeMap, switchMap, tap } from 'rxjs/operators'; import { of, throwError } from 'rxjs'; import { InterceptorConfig } from './interceptor-config'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { ActionLoadFinish, ActionLoadStart } from './load.actions'; -import { ActionNotificationShow } from '@app/core/notification/notification.actions'; +import { ActionNotificationHide, ActionNotificationShow } from '@app/core/notification/notification.actions'; import { DialogService } from '@core/services/dialog.service'; import { TranslateService } from '@ngx-translate/core'; import { parseHttpErrorMessage } from '@core/utils'; @@ -23,6 +23,8 @@ import { isSetupIncompleteError } from '@shared/models/system-setup.models'; const tmpHeaders = {}; +const CONNECTION_ERROR = 'Unable to connect'; + @Injectable() export class GlobalHttpInterceptor implements HttpInterceptor { @@ -31,6 +33,8 @@ export class GlobalHttpInterceptor implements HttpInterceptor { private activeRequests = 0; + private connectionErrorShown = false; + constructor( private store: Store, private dialogService: DialogService, @@ -39,7 +43,9 @@ export class GlobalHttpInterceptor implements HttpInterceptor { private sanitizer: DomSanitizer, private systemSetupService: SystemSetupService, @Inject(DOCUMENT) private document: Document - ) {} + ) { + this.document.defaultView?.addEventListener('online', () => this.connectionRestored()); + } intercept(req: HttpRequest, next: HttpHandler): Observable> { if (req.url.startsWith('/api/')) { @@ -80,6 +86,11 @@ export class GlobalHttpInterceptor implements HttpInterceptor { private handleRequest(req: HttpRequest, next: HttpHandler): Observable> { return next.handle(req).pipe( + tap(event => { + if (event.type === HttpEventType.ResponseHeader || event.type === HttpEventType.Response) { + this.connectionRestored(); + } + }), catchError((err) => { const errorResponse = err as HttpErrorResponse; return this.handleResponseError(req, next, errorResponse); @@ -92,6 +103,9 @@ export class GlobalHttpInterceptor implements HttpInterceptor { const ignoreErrors = config.ignoreErrors; const resendRequest = config.resendRequest; const errorCode = errorResponse.error ? errorResponse.error.errorCode : null; + if (errorResponse.status > 0) { + this.connectionRestored(); + } if (errorResponse.error && errorResponse.error.refreshTokenPending || errorResponse.status === 401 && req.url !== Constants.entryPoints.tokenRefresh) { if (errorResponse.error && errorResponse.error.refreshTokenPending || @@ -122,7 +136,8 @@ export class GlobalHttpInterceptor implements HttpInterceptor { this.handleLock(errorResponse.error); } else if (errorResponse.status === 0 || errorResponse.status === -1) { if (!ignoreErrors) { - this.showError('Unable to connect'); + this.connectionErrorShown = true; + this.showError(CONNECTION_ERROR); } } else if (!(req.url.startsWith('/api/rpc') || req.url.startsWith('/api/plugins/rpc'))) { if (errorResponse.status === 404) { @@ -218,6 +233,13 @@ export class GlobalHttpInterceptor implements HttpInterceptor { } } + private connectionRestored(): void { + if (this.connectionErrorShown) { + this.connectionErrorShown = false; + this.store.dispatch(new ActionNotificationHide({message: CONNECTION_ERROR})); + } + } + private showError(error: string, timeout: number = 0) { setTimeout(() => { this.store.dispatch(new ActionNotificationShow({message: error, type: 'error'})); diff --git a/ui-ngx/src/app/core/local-storage/stored.ts b/ui-ngx/src/app/core/local-storage/stored.ts new file mode 100644 index 0000000000..8638c04710 --- /dev/null +++ b/ui-ngx/src/app/core/local-storage/stored.ts @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +export function readStored(key: string): string | null { + try { + return localStorage.getItem(key); + } catch { + return null; + } +} + +export function writeStored(key: string, value: string | null): void { + try { + if (value === null) { + localStorage.removeItem(key); + } else { + localStorage.setItem(key, value); + } + } catch { + return; + } +} diff --git a/ui-ngx/src/app/core/notification/notification.models.ts b/ui-ngx/src/app/core/notification/notification.models.ts index cd8428cd75..33d870fa23 100644 --- a/ui-ngx/src/app/core/notification/notification.models.ts +++ b/ui-ngx/src/app/core/notification/notification.models.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 export interface NotificationState { notification: NotificationMessage; hideNotification: HideNotification; @@ -19,8 +20,11 @@ export class NotificationMessage { verticalPosition?: NotificationVerticalPosition; panelClass?: string | string[]; modern?: boolean; + actionLabel?: string; + onAction?: () => void; } export class HideNotification { target?: string; + message?: string; } diff --git a/ui-ngx/src/app/core/services/ai-assistant-config.service.ts b/ui-ngx/src/app/core/services/ai-assistant-config.service.ts new file mode 100644 index 0000000000..6f6f32d6f0 --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-assistant-config.service.ts @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Injectable } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { AiAssistantPanelConfig, AiAssistantViewType } from '@shared/models/ai-chat.models'; +import { EntityId } from '@shared/models/id/entity-id'; +import { HeaderActionDescriptor } from '@home/models/entity/entities-table-config.models'; + +@Injectable({ + providedIn: 'root' +}) +export class AiAssistantConfigService { + + private userPermissionsService = inject(UserPermissionsService); + private translate = inject(TranslateService); + + configureAction(onAction: ($event: MouseEvent) => void): HeaderActionDescriptor[] { + return this.userPermissionsService.isAiAvailable() ? [{ + name: this.translate.instant('ai-assistant.configure-with-ai'), + icon: 'mdi:creation', + isEnabled: () => true, + onAction + }] : []; + } + + tableConfig(listView: AiAssistantViewType, entityView?: AiAssistantViewType, listEntityId?: EntityId): AiAssistantPanelConfig | null { + if (!this.userPermissionsService.isAiAvailable()) { + return null; + } + return { + view: {listView, entityView, listEntityId}, + initialPromptPlaceholder: this.translate.instant('ai-assistant.welcome.placeholder') + }; + } +} diff --git a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts index efbd13bed0..4e39d0b71d 100644 --- a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts +++ b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts @@ -1,16 +1,11 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { computed, DestroyRef, inject, Injectable, OnDestroy, signal } from '@angular/core'; -import { Subject } from 'rxjs'; -import { distinctUntilChanged, map } from 'rxjs/operators'; +import { computed, DestroyRef, effect, inject, Injectable, OnDestroy, signal } from '@angular/core'; +import { defer, Observable, Subject } from 'rxjs'; +import { buffer, debounceTime, distinctUntilChanged, filter, finalize, map } from 'rxjs/operators'; +import { NavigationEnd, NavigationStart, Router } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { - AiAssistantPanelConfig, - AiAssistantViewType, - AiChatClientContext, - AiChatView, - ChatInfo -} from '@shared/models/ai-chat.models'; +import { AiAssistantPanelConfig, AiAssistantViewType, AiChatClientContext, aiClientOs, AiChatView, AiPromptMessage } from '@shared/models/ai-chat.models'; import { EntityId } from '@shared/models/id/entity-id'; import { getDefaultTimezone } from '@shared/models/time/time.models'; import { LocalStorageService } from '@core/local-storage/local-storage.service'; @@ -18,12 +13,35 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { selectAuthUser } from '@core/auth/auth.selectors'; +export interface AiCustomizationSaved { + kind: 'MAIL_TEMPLATES' | 'TRANSLATION' | 'MENU' | 'MOBILE_QR_CODE' | 'TWO_FACTOR' | 'PROFILE' | 'ACCOUNT_SECURITY' | 'ACCOUNT_NOTIFICATIONS' | 'MAIL_SERVER'; + locale?: string; + menuId?: string; + deleted?: boolean; +} + @Injectable({ providedIn: 'root' }) export class AiAssistantPanelService implements OnDestroy { - private _open = signal(false); + private _editorDraftProvider: (() => unknown | null) | null = null; + + private static readonly WITHOUT_PANEL = ['/home', '/ai-assistant']; + + private static readonly OPEN_KEY = 'tb-ai-panel-open'; + private static readonly RELOAD_DEBOUNCE_MS = 1000; + private static readonly CHATS_KEY = 'tb-ai-panel-chats'; + + private _open = signal(AiAssistantPanelService.readSession(AiAssistantPanelService.OPEN_KEY) === 'true'); readonly open = this._open.asReadonly(); + private openSync = effect(() => AiAssistantPanelService.writeSession(AiAssistantPanelService.OPEN_KEY, this._open() ? 'true' : null)); + + private _restored = signal(this._open()); + readonly restored = this._restored.asReadonly(); + + private _suppressed = signal(false); + readonly suppressed = this._suppressed.asReadonly(); + private _enabled = signal(false); readonly enabled = this._enabled.asReadonly(); @@ -38,110 +56,200 @@ export class AiAssistantPanelService implements OnDestroy { private _sentClientContextByChat = new Map(); - private _chats = signal(null); - readonly chats = this._chats.asReadonly(); - private _lastChatIdByContext = new Map(); + private _lastChatIdByContext = AiAssistantPanelService.readChats(); private static readonly AUTO_APPROVE_STORAGE_KEY = 'aiAssistantAutoApproveChats'; private localStorage = inject(LocalStorageService); private store = inject(Store); private destroyRef = inject(DestroyRef); + private router = inject(Router); + + private routeWatch = (() => { + this._suppressed.set(AiAssistantPanelService.withoutPanel(this.router.url)); + this.router.events.pipe( + filter((event): event is NavigationStart => event instanceof NavigationStart), + takeUntilDestroyed(this.destroyRef) + ).subscribe(event => { + const suppressed = AiAssistantPanelService.withoutPanel(event.url); + this._suppressed.set(suppressed); + if (suppressed) { + this._open.set(false); + } + }); + this.router.events.pipe( + filter((event): event is NavigationEnd => event instanceof NavigationEnd), + takeUntilDestroyed(this.destroyRef) + ).subscribe(event => { + const suppressed = AiAssistantPanelService.withoutPanel(event.urlAfterRedirects); + this._suppressed.set(suppressed); + if (suppressed && !AiAssistantPanelService.onAiPage(event.urlAfterRedirects)) { + this._composed.set(null); + } + const openHere = this._openOnArrival && !suppressed; + if (!suppressed) { + this._openOnArrival = false; + } + if (openHere) { + this._open.set(true); + } + }); + })(); + + private static readSession(key: string): string | null { + try { + return sessionStorage.getItem(key); + } catch { + return null; + } + } + + private static writeSession(key: string, value: string | null): void { + try { + if (value === null) { + sessionStorage.removeItem(key); + } else { + sessionStorage.setItem(key, value); + } + } catch { + return; + } + } + + private static readChats(): Map { + try { + const stored = JSON.parse(AiAssistantPanelService.readSession(AiAssistantPanelService.CHATS_KEY) ?? '{}'); + return new Map(Object.entries(stored).filter((entry): entry is [string, string] => typeof entry[1] === 'string')); + } catch { + return new Map(); + } + } + + private storeChats(): void { + AiAssistantPanelService.writeSession(AiAssistantPanelService.CHATS_KEY, + this._lastChatIdByContext.size ? JSON.stringify(Object.fromEntries(this._lastChatIdByContext)) : null); + } + + private static onAiPage(url: string): boolean { + const path = (url || '/').split(/[?#]/)[0]; + return path === '/ai-assistant' || path.startsWith('/ai-assistant/'); + } + + private static withoutPanel(url: string): boolean { + const path = (url || '/').split(/[?#]/)[0]; + return path === '/' || AiAssistantPanelService.WITHOUT_PANEL.some(page => path === page || path.startsWith(page + '/')); + } private _autoApproveUserId: string | null = null; - private _autoApproveChats = signal>(new Set()); private _autoApproveUserSync = this.store.select(selectAuthUser).pipe( map(user => user?.userId ?? null), distinctUntilChanged(), takeUntilDestroyed(this.destroyRef) ).subscribe(userId => { + if (this._autoApproveUserId !== null && userId !== this._autoApproveUserId) { + this.resetUserState(); + } this._autoApproveUserId = userId; - this._autoApproveChats.set(this.loadAutoApproveChats(userId)); }); + private resetUserState(): void { + this._open.set(false); + this._sentClientContextByChat.clear(); + this._lastChatIdByContext.clear(); + this._carried = null; + this._handOff = null; + this.storeChats(); + } + private _updatedData$ = new Subject>(); readonly updatedData$ = this._updatedData$.asObservable(); + readonly updatedDataBatches$: Observable> = this.updatedData$.pipe( + buffer(this.updatedData$.pipe(debounceTime(AiAssistantPanelService.RELOAD_DEBOUNCE_MS))), + map(batches => batches.flat()) + ); private _teardownTimer: NodeJS.Timeout; - toggle(): void { - if (!this._enabled()) { - return; - } - this._open.update(open => !open); - } + private static readonly CARRY_MS = 15000; + private _carried: {chatId: string; from: string | null; at: number} | null = null; - setChats(chats: ChatInfo[]): void { - this._chats.set(chats); - this.pruneAutoApproveChats(chats); - } + private static readonly FROM_AI_PAGE = 'ai-assistant-page'; + + private _openOnArrival = false; + + private _handOff: AiPromptMessage | null = null; - addChat(chat: ChatInfo): void { - this._chats.update(list => [chat, ...(list ?? [])]); + handOff(prompt: AiPromptMessage): void { + this._handOff = prompt; } - updateChatTitle(chatId: string, title: string): void { - this._chats.update(list => list?.map(c => c.id === chatId ? {...c, title} : c) ?? null); + takeHandOff(): AiPromptMessage | null { + const prompt = this._handOff; + this._handOff = null; + return prompt; } - removeChat(chatId: string): void { - this._chats.update(list => list?.filter(c => c.id !== chatId) ?? null); - this._sentClientContextByChat.delete(chatId); - for (const [key, id] of this._lastChatIdByContext) { - if (id === chatId) { - this._lastChatIdByContext.delete(key); - } - } - this.setAutoApprove(chatId, false); + carryChat(chatId: string): void { + this._carried = {chatId, from: this.contextKey(), at: Date.now()}; } - isAutoApprove(chatId: string | undefined): boolean { - return !!chatId && this._autoApproveChats().has(chatId); + carryChatToPage(chatId: string): void { + this._carried = {chatId, from: AiAssistantPanelService.FROM_AI_PAGE, at: Date.now()}; + this._openOnArrival = true; } - setAutoApprove(chatId: string, enabled: boolean): void { - this._autoApproveChats.update(chats => { - const next = new Set(chats); - if (enabled) { - next.add(chatId); - } else { - next.delete(chatId); - } - return next; - }); - this.persistAutoApproveChats(); + hasCarriedChat(): boolean { + return !!this._carried; } - private pruneAutoApproveChats(chats: ChatInfo[]): void { - const valid = new Set(chats.map(c => c.id)); - const current = this._autoApproveChats(); - const pruned = new Set([...current].filter(id => valid.has(id))); - if (pruned.size !== current.size) { - this._autoApproveChats.set(pruned); - this.persistAutoApproveChats(); + takeCarriedChat(): string | undefined { + const carried = this._carried; + const key = this.contextKey(); + const fromPage = carried?.from === AiAssistantPanelService.FROM_AI_PAGE; + if (!carried || (key === null && !fromPage) || key === carried.from) { + return undefined; + } + this._carried = null; + if (Date.now() - carried.at > AiAssistantPanelService.CARRY_MS) { + return undefined; + } + if (key !== null) { + this._lastChatIdByContext.set(key, carried.chatId); + this.storeChats(); } + return carried.chatId; } - private autoApproveStorageKey(userId: string | null): string { - return `${AiAssistantPanelService.AUTO_APPROVE_STORAGE_KEY}_${userId ?? 'anonymous'}`; + toggle(): void { + if (this._suppressed() && !this._open()) { + return; + } + this._restored.set(false); + this._open.update(open => !open); } - private loadAutoApproveChats(userId: string | null): Set { - try { - const ids = this.localStorage.getItem(this.autoApproveStorageKey(userId)); - return new Set(Array.isArray(ids) ? ids as string[] : []); - } catch { - return new Set(); + forgetChat(chatId: string): void { + this._sentClientContextByChat.delete(chatId); + for (const [key, id] of this._lastChatIdByContext) { + if (id === chatId) { + this._lastChatIdByContext.delete(key); + } } + this.storeChats(); } - private persistAutoApproveChats(): void { + takeStoredAutoApproveChats(): string[] { + const key = `${AiAssistantPanelService.AUTO_APPROVE_STORAGE_KEY}_${this._autoApproveUserId ?? 'anonymous'}`; try { - this.localStorage.setItem(this.autoApproveStorageKey(this._autoApproveUserId), [...this._autoApproveChats()]); + const ids = this.localStorage.getItem(key); + if (ids !== null) { + this.localStorage.removeItem(key); + } + return Array.isArray(ids) ? ids as string[] : []; } catch { - // ignore storage write errors (e.g. private mode quota) + return []; } } @@ -159,6 +267,7 @@ export class AiAssistantPanelService implements OnDestroy { case AiAssistantViewType.ALARM_RULE: case AiAssistantViewType.ALARM_RULE_LIST: case AiAssistantViewType.ALARM_LIST: + case AiAssistantViewType.ALARM: return 'ALARM_RULE'; case AiAssistantViewType.CALCULATED_FIELD: case AiAssistantViewType.CALCULATED_FIELD_LIST: @@ -169,17 +278,87 @@ export class AiAssistantPanelService implements OnDestroy { case AiAssistantViewType.DEVICE_GROUP: case AiAssistantViewType.DEVICE_GROUP_LIST: return 'DEVICE_GROUP'; + case AiAssistantViewType.ASSET: + case AiAssistantViewType.ASSET_LIST: + return 'ASSET'; + case AiAssistantViewType.ASSET_GROUP: + case AiAssistantViewType.ASSET_GROUP_LIST: + return 'ASSET_GROUP'; + case AiAssistantViewType.ENTITY_VIEW: + case AiAssistantViewType.ENTITY_VIEW_LIST: + return 'ENTITY_VIEW'; + case AiAssistantViewType.ENTITY_VIEW_GROUP: + case AiAssistantViewType.ENTITY_VIEW_GROUP_LIST: + return 'ENTITY_VIEW_GROUP'; + case AiAssistantViewType.DASHBOARD_GROUP: + case AiAssistantViewType.DASHBOARD_GROUP_LIST: + return 'DASHBOARD_GROUP'; + case AiAssistantViewType.DEVICE_PROFILE: + case AiAssistantViewType.DEVICE_PROFILE_LIST: + return 'DEVICE_PROFILE'; + case AiAssistantViewType.ASSET_PROFILE: + case AiAssistantViewType.ASSET_PROFILE_LIST: + return 'ASSET_PROFILE'; + case AiAssistantViewType.CUSTOMER: + case AiAssistantViewType.CUSTOMER_LIST: + return 'CUSTOMER'; + case AiAssistantViewType.USER: + case AiAssistantViewType.USER_LIST: + return 'USER'; + case AiAssistantViewType.RULE_CHAIN: + case AiAssistantViewType.RULE_CHAIN_LIST: + return 'RULE_CHAIN'; + case AiAssistantViewType.INTEGRATION: + case AiAssistantViewType.INTEGRATION_LIST: + return 'INTEGRATION'; + case AiAssistantViewType.CONVERTER: + case AiAssistantViewType.CONVERTER_LIST: + return 'CONVERTER'; case AiAssistantViewType.NOTIFICATION_INBOX: case AiAssistantViewType.SENT_NOTIFICATION_LIST: case AiAssistantViewType.NOTIFICATION_TEMPLATE_LIST: case AiAssistantViewType.NOTIFICATION_RECIPIENT_LIST: case AiAssistantViewType.NOTIFICATION_RULE_LIST: + case AiAssistantViewType.NOTIFICATION_TEMPLATE: + case AiAssistantViewType.NOTIFICATION_RULE: + case AiAssistantViewType.NOTIFICATION_RECIPIENT: return 'NOTIFICATION'; default: return view.type; } }); + private static readonly STARTED_KEY = 'tb-ai-panel-started'; + private static readonly STARTED_MAX = 20; + + private _startedByContext = signal>(AiAssistantPanelService.readStarted()); + + private static readStarted(): Record { + try { + const stored = JSON.parse(AiAssistantPanelService.readSession(AiAssistantPanelService.STARTED_KEY) ?? '{}'); + return stored && typeof stored === 'object' ? stored : {}; + } catch { + return {}; + } + } + + noteStartedHere(chatId: string): void { + const key = this.contextKey(); + if (!key) { + return; + } + this._startedByContext.update(started => { + const next = {...started, [key]: [chatId, ...(started[key] ?? []).filter(id => id !== chatId)].slice(0, AiAssistantPanelService.STARTED_MAX)}; + AiAssistantPanelService.writeSession(AiAssistantPanelService.STARTED_KEY, JSON.stringify(next)); + return next; + }); + } + + chatsStartedHere(): string[] { + const key = this.contextKey(); + return key ? this._startedByContext()[key] ?? [] : []; + } + setLastChatId(id: string | undefined): void { const key = this.contextKey(); if (!key) { @@ -190,6 +369,7 @@ export class AiAssistantPanelService implements OnDestroy { } else { this._lastChatIdByContext.delete(key); } + this.storeChats(); } lastChatIdForContext(): string | undefined { @@ -198,13 +378,36 @@ export class AiAssistantPanelService implements OnDestroy { } close(): void { + this._restored.set(false); this._open.set(false); } openPanel(): void { + if (this._suppressed()) { + return; + } + this._restored.set(false); this._open.set(true); } + private _composed = signal(null); + readonly composed = this._composed.asReadonly(); + + compose(text: string): void { + this._composed.set(text); + if (!this._suppressed()) { + this.openPanel(); + } else if (!AiAssistantPanelService.onAiPage(this.router.url)) { + this.router.navigateByUrl('/ai-assistant'); + } + } + + takeComposed(): string | null { + const composed = this._composed(); + this._composed.set(null); + return composed; + } + setEnabled(enabled: boolean): void { this._enabled.set(enabled); if (enabled) { @@ -212,6 +415,17 @@ export class AiAssistantPanelService implements OnDestroy { } } + private _viewName = signal(null); + readonly viewName = this._viewName.asReadonly(); + + setViewName(name: string | null): void { + if (this._focus) { + this._focus.previousName = name?.trim() || null; + return; + } + this._viewName.set(name?.trim() || null); + } + setConfig(config: AiAssistantPanelConfig | null): void { this._config.set(config); } @@ -220,12 +434,39 @@ export class AiAssistantPanelService implements OnDestroy { this._detailsOpen.set(open); } + private _focus: {context: AiChatClientContext; previous: AiChatClientContext; previousName: string | null} | null = null; + setClientContext(ctx: AiChatClientContext | null): void { + if (this._focus && ctx) { + this._focus.previous = ctx; + return; + } + this._focus = null; this._clientContext.set(ctx); } setClientContextForView(view: AiChatView): void { - this.setClientContext({view, timeZone: getDefaultTimezone()}); + this.setClientContext({view, timeZone: getDefaultTimezone(), os: aiClientOs()}); + } + + focusWhile(view: AiChatView, name: string | null | undefined, until: Observable): Observable { + return defer(() => { + const previous = this._clientContext(); + if (!previous || !view.entityId?.id) { + return until; + } + const focus = {context: {view, timeZone: getDefaultTimezone(), os: aiClientOs()}, previous, previousName: this._viewName()}; + this._focus = focus; + this._clientContext.set(focus.context); + this._viewName.set(name?.trim() || null); + return until.pipe(finalize(() => { + if (this._focus === focus) { + this._focus = null; + this._clientContext.set(focus.previous); + this._viewName.set(focus.previousName); + } + })); + }); } getSentClientContext(chatId: string): AiChatClientContext | undefined { @@ -240,19 +481,70 @@ export class AiAssistantPanelService implements OnDestroy { this._updatedData$.complete(); } + private _whiteLabelingSaved$ = new Subject<'GENERAL' | 'LOGIN'>(); + readonly whiteLabelingSaved$ = this._whiteLabelingSaved$.asObservable(); + + emitWhiteLabelingSaved(target: 'GENERAL' | 'LOGIN'): void { + this._whiteLabelingSaved$.next(target); + } + + private _customizationSaved$ = new Subject(); + readonly customizationSaved$ = this._customizationSaved$.asObservable(); + + customizationReload$(kind: AiCustomizationSaved['kind'], clean: () => boolean = () => true): Observable { + return this.customizationSaved$.pipe(filter(event => event.kind === kind && clean())); + } + + emitCustomizationSaved(event: AiCustomizationSaved): void { + this._customizationSaved$.next(event); + } + + setEditorDraftProvider(provider: (() => unknown | null) | null): void { + this._editorDraftProvider = provider; + } + + editorDraft(): unknown | null { + try { + return this._editorDraftProvider ? this._editorDraftProvider() : null; + } catch (e) { + return null; + } + } + + private readonly _keptEdits = signal<{kind: 'dashboard' | 'entity'; reload: () => void} | null>(null); + readonly keptEdits = this._keptEdits.asReadonly(); + + keepEdits(kind: 'dashboard' | 'entity', reload: () => void): void { + this._keptEdits.set({kind, reload}); + } + + clearKeptEdits(kind?: 'dashboard' | 'entity'): void { + if (!kind || this._keptEdits()?.kind === kind) { + this._keptEdits.set(null); + } + } + + reloadKeptEdits(): void { + const kept = this._keptEdits(); + this._keptEdits.set(null); + kept?.reload(); + } + emitUpdatedData(affectedEntities: Array): void { this._updatedData$.next(affectedEntities); } teardown(): void { + this._keptEdits.set(null); + this._editorDraftProvider = null; this._enabled.set(false); this._detailsOpen.set(false); + this._focus = null; this._clientContext.set(null); + this._viewName.set(null); this._sentClientContextByChat.clear(); - this._chats.set(null); this._teardownTimer = setTimeout(() => { this._config.set(null); - this._open.set(false); }); } } diff --git a/ui-ngx/src/app/core/services/ai-chats.service.ts b/ui-ngx/src/app/core/services/ai-chats.service.ts new file mode 100644 index 0000000000..e57a2ea93a --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-chats.service.ts @@ -0,0 +1,353 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { computed, DestroyRef, effect, inject, Injectable, Injector, signal, untracked, WritableSignal } from '@angular/core'; +import { interval, Observable, of } from 'rxjs'; +import { distinctUntilChanged, filter, map, skip, switchMap, tap } from 'rxjs/operators'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { selectAuthUser } from '@core/auth/auth.selectors'; +import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { TranslateService } from '@ngx-translate/core'; +import { AiChatService } from '@core/http/ai-chat.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { DialogService } from '@core/services/dialog.service'; +import { AnswerFeedback, ChatConfiguration, ChatInfo, ChatLevel } from '@shared/models/ai-chat.models'; + +@Injectable({ providedIn: 'root' }) +export class AiChatsService { + + private aiChat = inject(AiChatService); + private panelService = inject(AiAssistantPanelService); + private dialog = inject(DialogService); + private translate = inject(TranslateService); + private destroyRef = inject(DestroyRef); + private injector = inject(Injector); + + private _chats = signal([]); + readonly chats = this._chats.asReadonly(); + + private _loaded = signal(false); + readonly loaded = this._loaded.asReadonly(); + + private _replying = signal>(new Set()); + readonly replying = this._replying.asReadonly(); + + private _waiting = signal>(new Set()); + + private _open = signal>(new Set()); + + private _failed = signal>(new Map()); + + private static readonly STATUS_POLL_MS = 15000; + + private _statuses = signal([]); + + private _statusResolved = signal(false); + + readonly statusChats = computed(() => this._loaded() ? this._chats() : this._statuses()); + + readonly statusResolved = computed(() => this._loaded() || this._statusResolved()); + + private watching = false; + + private polling = false; + + private generation = 0; + + private store = inject(Store); + + private userPermissions = inject(UserPermissionsService); + + private userWatch = this.store.select(selectAuthUser).pipe( + map(user => user?.userId ?? null), + distinctUntilChanged(), + skip(1), + takeUntilDestroyed(this.destroyRef) + ).subscribe(userId => this.reset(userId)); + + private reset(userId: string | null): void { + this.generation++; + this.polling = false; + this.ensuring = false; + this._chats.set([]); + this._loaded.set(false); + this._replying.set(new Set()); + this._waiting.set(new Set()); + this._open.set(new Set()); + this._failed.set(new Map()); + this._statuses.set([]); + this._statusResolved.set(false); + if (userId && this.watching) { + this.pollStatus(); + } + } + + private aiAvailable(): boolean { + return this.userPermissions.isAiAvailable(); + } + + watchStatus(): void { + if (this.watching) { + return; + } + this.watching = true; + this.pollStatus(); + let wasOpen = untracked(this.panelService.open); + const panelWatch = effect(() => { + const open = this.panelService.open(); + if (wasOpen && !open) { + this.pollStatus(); + } + wasOpen = open; + }, {injector: this.injector}); + const poll = interval(AiChatsService.STATUS_POLL_MS).subscribe(() => { + if (!untracked(this.panelService.open) && document.visibilityState === 'visible' + && untracked(this.statusChats).some(chat => this.levelOf(chat) === 'running')) { + this.pollStatus(); + } + }); + this.destroyRef.onDestroy(() => { + panelWatch.destroy(); + poll.unsubscribe(); + }); + } + + private pollStatus(): void { + if (this.polling || !this.aiAvailable()) { + return; + } + this.polling = true; + const generation = this.generation; + this.aiChat.listChatStatuses({ignoreLoading: true, ignoreErrors: true}).pipe( + filter(() => generation === this.generation) + ).subscribe({ + next: statuses => { + this.polling = false; + this._statuses.set(statuses); + this._statusResolved.set(true); + if (untracked(this._loaded)) { + const byId = new Map(statuses.map(chat => [chat.id, chat])); + this._chats.update(list => list.map(chat => { + const live = byId.get(chat.id); + return live?.status === chat.status && live?.statusReason === chat.statusReason && (!live || live.updatedTime === chat.updatedTime) + ? chat : {...chat, status: live?.status, statusReason: live?.statusReason, updatedTime: live?.updatedTime ?? chat.updatedTime}; + })); + } + }, + error: () => { + if (generation === this.generation) { + this.polling = false; + this._statusResolved.set(true); + } + } + }); + } + + levelOf(chat: ChatInfo, ignoreOpen = false): ChatLevel | null { + if (this._waiting().has(chat.id)) { + return 'needs'; + } + if (this._replying().has(chat.id)) { + return 'running'; + } + if (this._failed().has(chat.id)) { + return 'error'; + } + if (!ignoreOpen && this._open().has(chat.id)) { + return chat.status === 'FAILED' ? 'error' : null; + } + return chat.status === 'NEEDS_YOU' ? 'needs' : chat.status === 'NO_DATA' ? 'nodata' : chat.status === 'RUNNING' ? 'running' : chat.status === 'FAILED' ? 'error' : null; + } + + needsAttention(chat: ChatInfo): boolean { + const level = this.levelOf(chat); + return level === 'needs' || level === 'error'; + } + + tipOf(chat: ChatInfo): string { + const level = this.levelOf(chat); + if (!level) { + return ''; + } + const reason = level === 'error' ? this._failed().get(chat.id) ?? chat.statusReason : undefined; + return reason || this.translate.instant('ai-assistant.status-tip-' + level); + } + + setFailed(chatId: string | undefined, reason: string): void { + if (chatId) { + this._failed.update(map => new Map(map).set(chatId, reason)); + } + } + + clearFailure(chatId: string | undefined): void { + if (!chatId) { + return; + } + if (untracked(this._failed).has(chatId)) { + this._failed.update(map => { + const next = new Map(map); + next.delete(chatId); + return next; + }); + } + if (untracked(this._chats).some(chat => chat.id === chatId && chat.status === 'FAILED')) { + this._chats.update(list => list.map(chat => chat.id === chatId && chat.status === 'FAILED' + ? {...chat, status: undefined, statusReason: undefined} : chat)); + } + } + + setWaiting(chatId: string | undefined, waiting: boolean): void { + this.toggle(this._waiting, chatId, waiting); + } + + setOpen(chatId: string | undefined, open: boolean): void { + this.toggle(this._open, chatId, open); + } + + refresh(): Observable { + const generation = this.generation; + return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe( + tap(chats => { + if (generation === this.generation) { + this._chats.set(chats); + } + }) + ); + } + + private ensuring = false; + + ensureLoaded(): void { + if (this._loaded() || this.ensuring) { + return; + } + this.ensuring = true; + const generation = this.generation; + const done = () => { + if (generation === this.generation) { + this.ensuring = false; + } + }; + this.load().subscribe({error: done, complete: done}); + } + + load(): Observable { + const generation = this.generation; + return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe( + filter(() => generation === this.generation), + tap({ + next: chats => { + this._chats.set(chats); + this._loaded.set(true); + this.moveStoredAutoApprove(chats); + }, + error: () => this._loaded.set(true) + }) + ); + } + + find(chatId: string | undefined): ChatInfo | undefined { + return chatId ? this._chats().find(chat => chat.id === chatId) : undefined; + } + + create(title: string, autoApprove = false): Observable { + const request: ChatConfiguration = autoApprove ? {title, autoApprove} : {title}; + return this.aiChat.createChat(request, {ignoreLoading: true, ignoreErrors: true}).pipe( + map(id => ({id, title, createdTime: Date.now(), autoApprove} as ChatInfo)), + tap(chat => { + this._chats.update(list => [chat, ...list]); + }) + ); + } + + rename(chatId: string, title: string): Observable { + return this.aiChat.updatedChat(chatId, {title}, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this.setTitle(chatId, title)) + ); + } + + sendFeedback(chatId: string, feedback: AnswerFeedback): Observable { + return this.aiChat.updatedChat(chatId, {feedback}, {ignoreLoading: true}); + } + + isAutoApprove(chatId: string | undefined): boolean { + return !!this.find(chatId)?.autoApprove; + } + + setAutoApprove(chatId: string, autoApprove: boolean): Observable { + const before = this.isAutoApprove(chatId); + this.applyAutoApprove(chatId, autoApprove); + return this.aiChat.updatedChat(chatId, {autoApprove}, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap({error: () => this.applyAutoApprove(chatId, before)}) + ); + } + + private applyAutoApprove(chatId: string, autoApprove: boolean): void { + this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, autoApprove} : chat)); + } + + private moveStoredAutoApprove(chats: ChatInfo[]): void { + const stored = new Set(this.panelService.takeStoredAutoApproveChats()); + chats.filter(chat => stored.has(chat.id) && !chat.autoApprove) + .forEach(chat => this.setAutoApprove(chat.id, true).subscribe({error: () => {}})); + } + + setPinned(chatId: string, pinned: boolean): Observable { + return this.aiChat.updatedChat(chatId, {pinned}, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, pinned, pinnedTime: pinned ? Date.now() : undefined} : chat))) + ); + } + + setTitle(chatId: string, title: string): void { + this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, title} : chat)); + } + + discard(chatId: string): Observable { + return this.aiChat.deleteChat(chatId, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => { + this._chats.update(list => list.filter(c => c.id !== chatId)); + this.panelService.forgetChat(chatId); + }) + ); + } + + confirmAndDelete(chat: ChatInfo): Observable { + const title = chat.title || this.translate.instant('ai-assistant.new-chat'); + return this.dialog.confirm( + this.translate.instant('ai-assistant.delete-chat-title', {name: title}), + this.translate.instant('ai-assistant.delete-chat-text'), + this.translate.instant('action.no'), + this.translate.instant('ai-assistant.delete-chat-confirm') + ).pipe( + switchMap(confirmed => confirmed + ? this.aiChat.deleteChat(chat.id, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => { + this._chats.update(list => list.filter(c => c.id !== chat.id)); + this.panelService.forgetChat(chat.id); + }), + map(() => true) + ) + : of(false)) + ); + } + + setReplying(chatId: string | undefined, replying: boolean): void { + this.toggle(this._replying, chatId, replying); + } + + private toggle(target: WritableSignal>, chatId: string | undefined, on: boolean): void { + if (!chatId || untracked(target).has(chatId) === on) { + return; + } + target.update(set => { + const next = new Set(set); + if (on) { + next.add(chatId); + } else { + next.delete(chatId); + } + return next; + }); + } +} diff --git a/ui-ngx/src/app/core/services/ai-slash.service.ts b/ui-ngx/src/app/core/services/ai-slash.service.ts new file mode 100644 index 0000000000..4d74aa93a1 --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-slash.service.ts @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Injectable, NgZone } from '@angular/core'; +import { MatDialog } from '@angular/material/dialog'; + +export interface AiSlashComposer { + field(): HTMLTextAreaElement | undefined; + focusEnd(): void; +} + +export interface AiSlashOpener { + canOpen(): boolean; + open(): void; +} + +@Injectable({ + providedIn: 'root' +}) +export class AiSlashService { + + private zone = inject(NgZone); + private dialog = inject(MatDialog); + private composers = new Set(); + private opener: AiSlashOpener | null = null; + private listening = false; + + addComposer(composer: AiSlashComposer): () => void { + this.listen(); + this.composers.add(composer); + return () => this.composers.delete(composer); + } + + setOpener(opener: AiSlashOpener): () => void { + this.listen(); + this.opener = opener; + return () => { + if (this.opener === opener) { + this.opener = null; + } + }; + } + + private listen(): void { + if (this.listening) { + return; + } + this.listening = true; + this.zone.runOutsideAngular(() => document.addEventListener('keydown', event => this.onKeydown(event))); + } + + private onKeydown(event: KeyboardEvent): void { + if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented || this.dialog.openDialogs.length + || (event.target as HTMLElement)?.closest?.('input, textarea, select, [contenteditable], [role="combobox"], [role="listbox"], [role="menu"], [role="menuitem"]') + || document.querySelector('.cdk-overlay-container .mat-mdc-select-panel, .cdk-overlay-container .mat-mdc-menu-panel, .cdk-overlay-container .mat-mdc-autocomplete-panel')) { + return; + } + const visible = Array.from(this.composers) + .filter(composer => { + const field = composer.field(); + return !!field?.offsetParent && !field.closest('tb-ai-assistant-panel:not(.open)'); + }) + .sort((a, b) => a.field().compareDocumentPosition(b.field()) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1); + const last = visible[visible.length - 1]; + if (last) { + event.preventDefault(); + this.zone.run(() => last.focusEnd()); + return; + } + if (this.opener?.canOpen()) { + event.preventDefault(); + this.zone.run(() => this.opener.open()); + } + } +} diff --git a/ui-ngx/src/app/core/services/ai-solutions.service.ts b/ui-ngx/src/app/core/services/ai-solutions.service.ts new file mode 100644 index 0000000000..a426eed1c4 --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-solutions.service.ts @@ -0,0 +1,286 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { computed, DestroyRef, inject, Injectable, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { selectAuthUser } from '@core/auth/auth.selectors'; +import { EMPTY, Observable, of, Subscription, timer } from 'rxjs'; +import { catchError, distinctUntilChanged, filter, finalize, map, skip, switchMap, takeWhile, tap } from 'rxjs/operators'; +import { TranslateService } from '@ngx-translate/core'; +import { ChatLevel } from '@shared/models/ai-chat.models'; +import { SolutionsCreatorService } from '@core/http/solutions-creator.service'; +import { DialogService } from '@core/services/dialog.service'; +import { + SolutionCreatorInfo, + SolutionInfo, + SolutionInstallProgress, + SolutionStep, + SolutionUpdateRequest +} from '@shared/models/solution-creator.models'; + +const SOLUTIONS_POLL_MS = 5000; + +@Injectable({providedIn: 'root'}) +export class AiSolutionsService { + + private following: Subscription | null = null; + + private _solutions = signal([]); + readonly solutions = this._solutions.asReadonly(); + + private _loaded = signal(false); + readonly loaded = this._loaded.asReadonly(); + + private _running = signal>(new Set()); + readonly running = this._running.asReadonly(); + private _failed = signal>(new Map()); + private _needs = signal>(new Set()); + + private api = inject(SolutionsCreatorService); + private dialog = inject(DialogService); + private translate = inject(TranslateService); + + private generation = 0; + + private userWatch = inject(Store).select(selectAuthUser).pipe( + map(user => user?.userId ?? null), + distinctUntilChanged(), + skip(1), + takeUntilDestroyed(inject(DestroyRef)) + ).subscribe(() => this.reset()); + + private reset(): void { + this.generation++; + this.ensuring = false; + this.following?.unsubscribe(); + this.following = null; + this._solutions.set([]); + this._loaded.set(false); + this._running.set(new Set()); + this._failed.set(new Map()); + } + + private ensuring = false; + + ensureLoaded(): void { + if (this._loaded() || this.ensuring) { + return; + } + this.ensuring = true; + const generation = this.generation; + const done = () => { + if (generation === this.generation) { + this.ensuring = false; + } + }; + this.load().subscribe({error: done, complete: done}); + } + + load(): Observable { + const generation = this.generation; + return this.api.getSolutions({ignoreLoading: true, ignoreErrors: true}).pipe( + filter(() => generation === this.generation), + tap({ + next: solutions => { + this._solutions.set(solutions); + this._loaded.set(true); + this.followRunning(); + }, + error: () => this._loaded.set(true) + }) + ); + } + + keepRunning(solutionId: string | undefined): void { + if (!solutionId) { + return; + } + this.update(solutionId, {status: 'RUNNING', statusReason: undefined}); + this.followRunning(); + } + + followRunning(): void { + if (this.following) { + return; + } + this.following = timer(SOLUTIONS_POLL_MS, SOLUTIONS_POLL_MS).pipe( + takeWhile(() => this._solutions().some(solution => solution.status === 'RUNNING' && !this._running().has(solution.id))), + switchMap(() => this.load().pipe(catchError(() => EMPTY))), + finalize(() => this.following = null) + ).subscribe(); + } + + setNeeds(solutionId: string | undefined, needs: boolean): void { + if (!solutionId || this._needs().has(solutionId) === needs) { + return; + } + if (needs && !['FAILED', 'RUNNING'].includes(this.find(solutionId)?.status)) { + this.update(solutionId, {status: 'NEEDS_YOU', statusReason: undefined}); + } + this._needs.update(set => { + const next = new Set(set); + if (needs) { + next.add(solutionId); + } else { + next.delete(solutionId); + } + return next; + }); + } + + setRunning(solutionId: string | undefined, running: boolean): void { + if (!solutionId || this._running().has(solutionId) === running) { + return; + } + if (running && this.find(solutionId)?.status !== 'RUNNING') { + this.update(solutionId, {status: undefined, statusReason: undefined}); + } + this._running.update(set => { + const next = new Set(set); + if (running) { + next.add(solutionId); + } else { + next.delete(solutionId); + } + return next; + }); + if (!running && this.find(solutionId)?.status === 'RUNNING') { + this.followRunning(); + } + } + + isRunning(solutionId: string): boolean { + return this._running().has(solutionId); + } + + setFailed(solutionId: string | undefined, reason: string | null): void { + if (!solutionId || this._failed().get(solutionId) === (reason ?? undefined)) { + return; + } + this._failed.update(map => { + const next = new Map(map); + if (reason) { + next.set(solutionId, reason); + } else { + next.delete(solutionId); + } + return next; + }); + } + + levelOf(solution: SolutionInfo, open = false): ChatLevel | null { + if (this._running().has(solution.id)) { + return 'running'; + } + if (this._failed().has(solution.id)) { + return 'error'; + } + if (open) { + return solution.status === 'FAILED' ? 'error' : this._needs().has(solution.id) ? 'needs' : null; + } + return solution.status === 'NEEDS_YOU' ? 'needs' : solution.status === 'RUNNING' ? 'running' : solution.status === 'FAILED' ? 'error' : null; + } + + needsAttention(solution: SolutionInfo): boolean { + const level = this.levelOf(solution); + if (this._needs().has(solution.id)) { + return level === 'error'; + } + return level === 'needs' || level === 'error'; + } + + readonly attention = computed(() => this._solutions().filter(solution => this.needsAttention(solution))); + + tipOf(solution: SolutionInfo, open = false): string { + const level = this.levelOf(solution, open); + if (!level) { + return ''; + } + const reason = level === 'error' ? this._failed().get(solution.id) ?? solution.statusReason : undefined; + return reason || this.translate.instant('ai-assistant.status-tip-' + level); + } + + find(solutionId: string | undefined): SolutionInfo | undefined { + return solutionId ? this._solutions().find(solution => solution.id === solutionId) : undefined; + } + + titleOf(solution: SolutionInfo): string { + return solution.solutionTitle || this.translate.instant('solution-creator.new-solution'); + } + + upsert(info: SolutionCreatorInfo): void { + const solution: SolutionInfo = { + id: info.id, + createdTime: info.createdTime, + updatedTime: this.find(info.id)?.updatedTime ?? info.createdTime, + solutionTitle: info.data?.solutionTitle || info.data?.aiSolutionTitle || this.find(info.id)?.solutionTitle || '', + built: !!info.metadata?.built, + installed: !!info.metadata?.installed + }; + this._solutions.update(list => list.some(item => item.id === solution.id) + ? list.map(item => item.id === solution.id ? {...item, ...solution, createdTime: item.createdTime ?? solution.createdTime} : item) + : [solution, ...list]); + } + + update(solutionId: string, fields: Partial): void { + this._solutions.update(list => list.map(item => item.id === solutionId ? {...item, ...fields} : item)); + } + + rename(solution: SolutionInfo, title: string): Observable { + return this.api.updateSolutionData(solution.id, 'solutionTitle', JSON.stringify(title), {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this.update(solution.id, {solutionTitle: title})) + ); + } + + setPinned(solution: SolutionInfo, pinned: boolean): Observable { + return this.api.updateSolution(solution.id, {pinned}, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this.update(solution.id, {pinned})) + ); + } + + sendFeedback(solutionId: string, step: SolutionStep, feedback: SolutionUpdateRequest['feedback']): Observable { + return this.api.updateSolution(solutionId, {step, feedback}, {ignoreLoading: true}); + } + + installProgress(solutionId: string): Observable { + return this.api.getInstallProgress(solutionId, {ignoreLoading: true, ignoreErrors: true}); + } + + confirmAndUninstall(solution: SolutionInfo): Observable { + return this.dialog.confirm( + this.translate.instant('solution-creator.uninstall-solution-dialog-title', {name: this.titleOf(solution)}), + this.translate.instant('solution-creator.uninstall-solution-dialog-text'), + this.translate.instant('action.no'), + this.translate.instant('solution-creator.uninstall-solution-dialog-confirm') + ).pipe( + switchMap(confirmed => confirmed + ? this.api.uninstallSolution(solution.id, {ignoreErrors: true}).pipe( + tap(() => this.update(solution.id, {installed: false})) + ) + : of(null)) + ); + } + + discard(solutionId: string): Observable { + return this.api.deleteSolution(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this._solutions.update(list => list.filter(item => item.id !== solutionId))) + ); + } + + confirmAndDelete(solution: SolutionInfo): Observable { + return this.dialog.confirm( + this.translate.instant('solution-creator.delete-solution-title', {name: this.titleOf(solution)}), + this.translate.instant('solution-creator.delete-solution-text'), + this.translate.instant('action.no'), + this.translate.instant('solution-creator.delete-solution-confirm') + ).pipe( + switchMap(confirmed => confirmed + ? this.api.deleteSolution(solution.id, {ignoreErrors: true}).pipe( + tap(() => this._solutions.update(list => list.filter(item => item.id !== solution.id))), + map(() => true) + ) + : of(false)) + ); + } +} diff --git a/ui-ngx/src/app/core/services/dashboard-utils.service.ts b/ui-ngx/src/app/core/services/dashboard-utils.service.ts index a121cddf28..ffa249754c 100644 --- a/ui-ngx/src/app/core/services/dashboard-utils.service.ts +++ b/ui-ngx/src/app/core/services/dashboard-utils.service.ts @@ -65,7 +65,7 @@ import { BackgroundType, colorBackground, isBackgroundSettings } from '@shared/m import { MediaBreakpoints } from '@shared/models/constants'; import { TranslateService } from '@ngx-translate/core'; import { DashboardPageLayout } from '@home/components/dashboard-page/dashboard-page.models'; -import { maxGridsterCol, maxGridsterRow } from '@home/models/dashboard-component.models'; +import { maxGridsterCol, maxGridsterRow } from '@shared/models/dashboard.models'; import { findWidgetModelDefinition, widgetHasTimewindow, diff --git a/ui-ngx/src/app/core/services/home.service.ts b/ui-ngx/src/app/core/services/home.service.ts index f90ee379df..82a35e4fca 100644 --- a/ui-ngx/src/app/core/services/home.service.ts +++ b/ui-ngx/src/app/core/services/home.service.ts @@ -1,10 +1,11 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { EventEmitter, Injectable } from '@angular/core'; import { ActiveComponentService } from '@core/services/active-component.service'; import { BehaviorSubject, Observable, shareReplay, Subject } from 'rxjs'; import { distinctUntilChanged } from 'rxjs/operators'; -import { RouterTabsComponent } from '@home/components/router-tabs.component'; +import type { RouterTabsComponent } from '@home/components/router-tabs.component'; import { isDefinedAndNotNull } from '@core/utils'; import { PageComponent } from '@shared/components/page.component'; @@ -43,7 +44,7 @@ export class HomeService { private activeComponentChanged(activeComponent: any) { this.hideMainToolbarSubject.next(false); let hideLoadingBar = false; - if (activeComponent && activeComponent instanceof RouterTabsComponent + if (activeComponent && (activeComponent as RouterTabsComponent).isRouterTabsComponent && isDefinedAndNotNull(activeComponent.activatedRoute?.snapshot?.data?.showMainLoadingBar)) { hideLoadingBar = !activeComponent.activatedRoute.snapshot.data.showMainLoadingBar; } else if (activeComponent && activeComponent instanceof PageComponent diff --git a/ui-ngx/src/app/core/services/menu.models.ts b/ui-ngx/src/app/core/services/menu.models.ts index 85316cf568..e035b89a13 100644 --- a/ui-ngx/src/app/core/services/menu.models.ts +++ b/ui-ngx/src/app/core/services/menu.models.ts @@ -145,7 +145,6 @@ export enum MenuId { dashboard_all = 'dashboard_all', dashboard_groups = 'dashboard_groups', dashboard_shared = 'dashboard_shared', - ai_solution_creator = 'ai_solution_creator', device_all = 'device_all', device_groups = 'device_groups', device_shared = 'device_shared', @@ -178,6 +177,7 @@ export enum MenuId { secrets = 'secrets', ai_models = 'ai_models', iot_hub = 'iot_hub', + ai_assistant = 'ai_assistant', reporting = 'reporting', report_templates = 'report_templates', report_scheduling = 'report_scheduling', @@ -1117,18 +1117,6 @@ export const menuSectionMap = new Map([ rootOnly: true } ], - [ - MenuId.ai_solution_creator, - { - id: MenuId.ai_solution_creator, - name: 'solution-creator.ai-solution-creator', - type: 'link', - path: '/ai-solution-creator', - icon: 'mdi:creation', - outlinedIcon: 'mdi:creation-outline', - isNew: true, - } - ], [ MenuId.device_all, { @@ -1551,6 +1539,18 @@ export const menuSectionMap = new Map([ outlinedIcon: 'mdi:hub-outline', isNew: true } + ], + [ + MenuId.ai_assistant, + { + id: MenuId.ai_assistant, + name: 'ai-assistant.ai-assistant', + type: 'link', + path: '/ai-assistant', + icon: 'auto_awesome', + outlinedIcon: 'mdi:creation-outline', + isNew: true + } ] ]); @@ -1576,16 +1576,13 @@ const menuFilters = new Map([ MenuId.dashboard_shared, (_authState, userPermissionsService) => userPermissionsService.hasSharedReadGroupsPermission(EntityType.DASHBOARD) ], - [ - MenuId.ai_solution_creator, (authState, userPermissionsService) => - authState.aiEnabled && - authState.authUser.authority === Authority.TENANT_ADMIN && - userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) - ], [ MenuId.iot_hub, (authState, userPermissionsService) => authState.authUser.authority === Authority.TENANT_ADMIN && - userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL) + userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL) + ], + [ + MenuId.ai_assistant, (_authState, userPermissionsService) => userPermissionsService.isAiAvailable() ], [ MenuId.device_all, (_authState, userPermissionsService) => @@ -2007,8 +2004,8 @@ export const defaultUserMenuMap = new Map([ Authority.TENANT_ADMIN, [ {id: MenuId.home}, + {id: MenuId.ai_assistant}, {id: MenuId.iot_hub}, - {id: MenuId.ai_solution_creator}, { id: MenuId.monitor, pages: [ diff --git a/ui-ngx/src/app/core/services/tour.service.ts b/ui-ngx/src/app/core/services/tour.service.ts new file mode 100644 index 0000000000..5d59332a92 --- /dev/null +++ b/ui-ngx/src/app/core/services/tour.service.ts @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { createNgModule, inject, Injectable, Injector, signal, untracked } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { MatDialog } from '@angular/material/dialog'; +import { AppState } from '@core/core.state'; +import { getCurrentUserSettings } from '@core/auth/auth.selectors'; +import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { AiTourStep } from '@shared/models/user-settings.models'; +import { AiChatsService } from '@core/services/ai-chats.service'; + +export interface TourLauncherApi { + welcome(): void; + assistantTour(): Promise; +} + +const OFFER_DELAY_MS = 1200; + +@Injectable({providedIn: 'root'}) +export class TourService { + + readonly active = signal(false); + + private store = inject(Store); + private injector = inject(Injector); + private userPermissions = inject(UserPermissionsService); + private chats = inject(AiChatsService); + private dialog = inject(MatDialog); + + private launcher: Promise | null = null; + + private offered = false; + + aiAvailable(): boolean { + return this.userPermissions.aiAvailable(); + } + + offerWelcome(): void { + if (this.offered || !this.aiAvailable() || this.seen(AiTourStep.WELCOME)) { + return; + } + this.offered = true; + this.chats.watchStatus(); + setTimeout(() => { + if (this.active() || this.seen(AiTourStep.WELCOME) || this.dialog.openDialogs.length + || untracked(this.chats.statusChats).some(chat => this.chats.levelOf(chat) === 'running')) { + this.offered = false; + return; + } + this.load().then(launcher => launcher.welcome()); + }, OFFER_DELAY_MS); + } + + playAssistantTour(): void { + if (this.aiAvailable() && !this.active()) { + this.load().then(launcher => launcher.assistantTour()); + } + } + + private seen(step: AiTourStep): boolean { + return !!getCurrentUserSettings(this.store)?.aiTour?.[step]; + } + + private load(): Promise { + if (!this.launcher) { + this.launcher = import('@modules/tour/tour.module').then(m => createNgModule(m.TourModule, this.injector).injector.get(m.TourLauncher)); + this.launcher.catch(() => this.launcher = null); + } + return this.launcher; + } +} diff --git a/ui-ngx/src/app/core/utils.ts b/ui-ngx/src/app/core/utils.ts index 5b134a2b56..8840b63513 100644 --- a/ui-ngx/src/app/core/utils.ts +++ b/ui-ngx/src/app/core/utils.ts @@ -1283,3 +1283,19 @@ export const objectRequired = (): ValidatorFn => { return null; }; } + +export function escapeHtml(value: string): string { + return value.replace(/[&<>]/g, ch => ch === '&' ? '&' : ch === '<' ? '<' : '>'); +} + +export function escapeHtmlAttr(value: string): string { + return value.replace(/[&<>"']/g, ch => { + switch (ch) { + case '&': return '&'; + case '<': return '<'; + case '>': return '>'; + case '"': return '"'; + default: return '''; + } + }); +} diff --git a/ui-ngx/src/app/modules/common/lazy-modules-map.ts b/ui-ngx/src/app/modules/common/lazy-modules-map.ts new file mode 100644 index 0000000000..ce46d971b3 --- /dev/null +++ b/ui-ngx/src/app/modules/common/lazy-modules-map.ts @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { defer, map, Observable, shareReplay, switchMap } from 'rxjs'; +import { IModulesMap } from '@modules/common/modules-map.models'; + +class LazyModulesMap implements IModulesMap { + + private modulesMap$: Observable = defer(() => import('@modules/common/modules-map')).pipe( + switchMap(module => module.modulesMap.init().pipe(map(() => module.modulesMap))), + shareReplay(1) + ); + + init(): Observable { + return this.modulesMap$; + } +} + +export const lazyModulesMap = new LazyModulesMap(); diff --git a/ui-ngx/src/app/modules/common/modules-map.ts b/ui-ngx/src/app/modules/common/modules-map.ts index da47be2020..494a534b2d 100644 --- a/ui-ngx/src/app/modules/common/modules-map.ts +++ b/ui-ngx/src/app/modules/common/modules-map.ts @@ -71,7 +71,7 @@ import * as momentPlugin from '@fullcalendar/moment'; import * as interactionPlugin from '@fullcalendar/interaction'; import * as FullCalendar from '@fullcalendar/angular'; import * as CanvasGauges from 'canvas-gauges'; -import * as NgxHmCarousel from 'ngx-hm-carousel'; +import * as NgxHmCarousel from '@shared/components/carousel/carousel.component'; import * as TbCore from '@core/public-api'; import * as TbShared from '@shared/public-api'; diff --git a/ui-ngx/src/app/modules/home/components/agent/_agent-shared.scss b/ui-ngx/src/app/modules/home/components/agent/_agent-shared.scss index c44b7923e8..3daf483b7f 100644 --- a/ui-ngx/src/app/modules/home/components/agent/_agent-shared.scss +++ b/ui-ngx/src/app/modules/home/components/agent/_agent-shared.scss @@ -93,10 +93,11 @@ $agent-type-generic-fg: #6a1b9a; display: flex; align-items: center; justify-content: space-between; + gap: 16px; padding: 4px 0; font-size: 13px; - .label { color: $agent-text-secondary; } - .value { color: $agent-text-primary; font-weight: 500; } + .label { flex: none; color: $agent-text-secondary; } + .value { min-width: 0; color: $agent-text-primary; font-weight: 500; text-align: right; overflow-wrap: anywhere; } } } diff --git a/ui-ngx/src/app/modules/home/components/agent/agent-deploy-status.component.scss b/ui-ngx/src/app/modules/home/components/agent/agent-deploy-status.component.scss index 231d0ac663..d4c26d1fe8 100644 --- a/ui-ngx/src/app/modules/home/components/agent/agent-deploy-status.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/agent-deploy-status.component.scss @@ -21,6 +21,12 @@ border: 1px solid $agent-divider-light; border-radius: 10px; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03); + + @media #{$mat-lt-sm} { + flex-wrap: wrap; + gap: 12px 16px; + padding: 16px; + } } .tb-deploy-card-icon { @@ -33,11 +39,22 @@ justify-content: center; background: color-mix(in srgb, var(--tb-primary-500) 14%, transparent); + @media #{$mat-lt-sm} { + width: 44px; + height: 44px; + } + mat-icon { color: var(--tb-primary-600, var(--tb-primary-500)); font-size: 32px; width: 32px; height: 32px; + + @media #{$mat-lt-sm} { + font-size: 24px; + width: 24px; + height: 24px; + } } } @@ -58,6 +75,10 @@ font-size: 20px; font-weight: 600; color: $agent-text-primary; + + @media #{$mat-lt-sm} { + font-size: 17px; + } } .tb-deploy-card-desc { @@ -85,6 +106,13 @@ align-items: flex-end; gap: 6px; flex-shrink: 0; + + @media #{$mat-lt-sm} { + flex-direction: row; + flex-wrap: wrap; + align-items: center; + width: 100%; + } } .tb-deploy-pill { @@ -181,6 +209,10 @@ transition: border-color 0.15s, box-shadow 0.15s, transform 0.15s; text-align: left; + @media #{$mat-lt-sm} { + padding: 16px; + } + &:hover { border-color: color-mix(in srgb, var(--tb-primary-500) 40%, transparent); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); diff --git a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.scss b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.scss index 891f4f85a5..426cfa045e 100644 --- a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.scss @@ -8,7 +8,7 @@ tb-agent-compose-diff { .diff-viewer { position: relative; overflow: hidden; - height: clamp(220px, calc(85vh - 280px), 520px); + height: clamp(220px, calc(75vh - 240px), 520px); width: 100%; .acediff__wrap { @@ -32,7 +32,7 @@ tb-agent-compose-diff { .ace_editor { font-family: $agent-mono-font !important; } - .ace_gutter { width: 44px !important; background: #f5f5f5; color: rgba(0, 0, 0, 0.42); } + .ace_gutter { width: 44px !important; background: $agent-surface-soft; color: $agent-ink-42; } .ace_gutter-layer { width: 44px !important; } .acediff__right .ace_gutter { diff --git a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.ts b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.ts index 216ceb2e4e..c5495ca4a2 100644 --- a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.ts @@ -221,15 +221,20 @@ export class AgentComposeDiffComponent implements AfterViewInit, OnChanges, OnDe requestAnimationFrame(() => this.whenReady(cb, frames - 1)); } - private scheduleRebuild(): void { + private scheduleRebuild(frames = 60): void { if (this.rebuildHandle != null || this.destroyed) { return; } this.rebuildHandle = requestAnimationFrame(() => { this.rebuildHandle = null; - if (!this.destroyed) { - this.build(); + if (this.destroyed) { + return; } + if (this.differ && !this.ready && frames > 0) { + this.scheduleRebuild(frames - 1); + return; + } + this.build(); }); } diff --git a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-editor.component.scss b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-editor.component.scss index a4c87845ac..38a3946a9a 100644 --- a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-editor.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-editor.component.scss @@ -8,7 +8,7 @@ tb-agent-compose-editor { .yaml-editor { width: 100%; box-sizing: border-box; padding: 12px 14px; border: 1px solid $agent-divider; border-radius: 4px; - background: $agent-surface-muted; color: #1f2328; + background: $agent-surface-muted; color: $agent-editor-fg; font-family: $agent-mono-font; font-size: 12px; line-height: 1.55; letter-spacing: 0; tab-size: 2; -moz-tab-size: 2; @@ -16,7 +16,7 @@ tb-agent-compose-editor { .yaml-editor-ace { padding: 0; - height: clamp(220px, calc(85vh - 280px), 520px); + height: clamp(220px, calc(75vh - 240px), 520px); overflow: hidden; overscroll-behavior: contain; .ace_editor { @@ -28,6 +28,6 @@ tb-agent-compose-editor { .ace_content { overscroll-behavior: contain; } - .ace_gutter { background: #f5f5f5; color: rgba(0, 0, 0, 0.42); } + .ace_gutter { background: $agent-surface-soft; color: $agent-ink-42; } } } diff --git a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.html b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.html index 88855e5893..99b0e1a1c5 100644 --- a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.html @@ -4,18 +4,17 @@ SPDX-License-Identifier: BUSL-1.1 --> - -
-

{{ titleKey | translate }}

-
+ +

{{ titleKey | translate }}

+
-
- -
- +
+ @@ -98,16 +97,6 @@ }
- - @@ -146,16 +135,30 @@ edge.auto-provision-no-script
} - - - +
+ @if (selectedIndex === 0) { +
+ +
+ + } +
+ + @if (selectedIndex > 0) { + + } +
+
diff --git a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.scss b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.scss index c3f58c4989..ffe68e19c0 100644 --- a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.scss @@ -2,14 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 @use '../wizard/agent-wizard' as *; -@include wizard-chrome; - -:host { - display: block; - width: min(800px, 95vw); - min-width: 0; - max-width: 95vw; -} +@include wizard-stepper-dialog(800px); .select-form { display: block; diff --git a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.ts b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.ts index a833397836..395f72bb99 100644 --- a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.ts @@ -58,6 +58,7 @@ export class AgentAutoProvisionDialogComponent searchText = ''; loading = false; + selectedIndex = 0; @ViewChild('stepper', { static: false }) stepper: MatStepper; @ViewChild(MatAutocompleteTrigger) private autocompleteTrigger: MatAutocompleteTrigger; @@ -221,7 +222,7 @@ export class AgentAutoProvisionDialogComponent return this.dialog.open( AgentProfileAssignProfileDialogComponent, { disableClose: true, - panelClass: ['tb-dialog'], + panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-wide-dialog'], data: { selectedIds, lockedAppType: this.appType } } ).afterClosed(); diff --git a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.service.ts b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.service.ts index 4283ec6f50..30ab9e23c9 100644 --- a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.service.ts +++ b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.service.ts @@ -20,7 +20,7 @@ export class AgentAutoProvisionDialogService { return this.dialog.open( AgentAutoProvisionDialogComponent, { disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-agent-wizard-dialog'], + panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-wide-dialog'], data: { appType } } ).afterClosed(); diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/_agent-wizard.scss b/ui-ngx/src/app/modules/home/components/agent/wizard/_agent-wizard.scss index 689721caf0..85e0b73a8a 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/_agent-wizard.scss +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/_agent-wizard.scss @@ -4,96 +4,76 @@ @forward '../agent-shared'; @use '../agent-shared' as *; -@mixin wizard-chrome { +@mixin wizard-dialog($width) { :host { - display: block; - width: min(1280px, 95vw); - min-width: 0; - max-width: 95vw; + height: 100%; + width: $width; + max-width: 100%; + display: grid; + grid-template-rows: min-content minmax(0, 1fr) min-content; + grid-template-columns: minmax(0, 1fr); } - .tb-install-wizard-toolbar { - display: flex; align-items: center; gap: 8px; - padding: 0 16px; - min-height: 56px; - .tb-install-wizard-toolbar-content { - flex: 1; min-width: 0; - display: flex; flex-direction: row; align-items: center; gap: 8px; - h2 { font-size: 20px; font-weight: 400; margin: 0; color: inherit; } - span { font-size: 20px; font-weight: 400; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + :host-context(.mat-mdc-dialog-container) { + @media #{$mat-gt-xs} { + max-height: calc(100vh - 32px); } - } - .tb-install-wizard-body.tb-install-wizard-embedded { - max-height: none !important; - overflow-y: visible !important; - padding: 8px 0 !important; - } + .mat-mdc-dialog-content { + overscroll-behavior: contain; - .tb-install-wizard-body { - // No vertical padding: the sticky stepper header sits flush at the top and the - // sticky footer flush at the bottom, with the content carrying its own spacing. - padding: 0 24px !important; - // Cap the dialog body to the viewport. Allow vertical scroll so tall step - // content (e.g. update/upgrade step 2 with config sections + summary card + - // info box + footer) can reach its buttons. The ace editors inside are - // clamped so they don't contribute unbounded height, and .acediff__wrap has - // its own overflow killed — so the only outer scrollbar that appears here - // is a legitimate chrome scroll when the step content genuinely overflows. - max-height: 85vh; - overflow-y: auto; - // Contain horizontal overscroll so two-finger trackpad swipes inside the - // ace editors / diff panes don't bubble up to the browser's back/forward - // page navigation. Also block vertical bounce from escaping the dialog. - overscroll-behavior: contain; + @media #{$mat-gt-xs} { + max-height: 75vh; + } + } } +} - :host ::ng-deep .mat-horizontal-stepper-wrapper { - margin-top: 0; - } +@mixin wizard-stepper-dialog($width) { + @include wizard-dialog($width); - :host ::ng-deep .mat-horizontal-stepper-header-container { - margin-top: 0; - // Keep the step indicators (1)…(N) pinned at the top while content scrolls. - position: sticky; - top: 0; - z-index: 5; - background: #fff; + :host { + .dialog-actions-row { + padding: 8px; + } } - :host ::ng-deep .mat-horizontal-stepper-header { - padding: 0 12px; - } + :host-context(.mat-mdc-dialog-container) { + .mat-mdc-dialog-content { + padding: 0; + scrollbar-gutter: stable; + } - :host ::ng-deep .mat-horizontal-content-container { - padding: 12px 0; - // Material defaults this to `overflow: hidden`, which makes it a scroll - // container and anchors the sticky `.step-footer` here (content height, so it - // never sticks). `clip` still clips the sliding steps but is NOT a scroll - // container, so the footer anchors to the scrolling `.tb-install-wizard-body`. - overflow: clip; - max-width: 100%; + .mat-mdc-dialog-actions { + padding: 0; + } } - :host-context(.tb-fullscreen-dialog .mat-mdc-dialog-container) { - max-width: 100%; + :host ::ng-deep { + .mat-horizontal-stepper-header-container { + position: sticky; + top: 0; + z-index: 5; + background: #fff; + } - .tb-install-wizard-body { - max-width: 100%; - overflow-x: hidden; + .mat-horizontal-content-container, + .mat-vertical-content { + padding-top: 4px; } - } - :host ::ng-deep .mat-step-header { - // Kill the hover/focus background — navigation works, but no visual fill. - &:hover, - &.cdk-program-focused, - &.cdk-mouse-focused, - &.cdk-focused { - background-color: transparent !important; + .mat-step-header { + &:hover, + &.cdk-program-focused, + &.cdk-mouse-focused, + &.cdk-focused { + background-color: transparent !important; + } } } +} +@mixin wizard-steps-locked { :host ::ng-deep .tb-steps-locked .mat-step-header[aria-selected="false"] { pointer-events: none; cursor: default; @@ -107,22 +87,6 @@ color: $agent-text-hint !important; } } - - .step-footer { - display: flex; align-items: center; justify-content: flex-end; gap: 8px; - padding: 12px 0; border-top: 1px solid $agent-divider-light; margin-top: 16px; - button mat-icon { font-size: 18px; width: 18px; height: 18px; } - } - - // Pin the footer to the bottom of the scrolling body so its action buttons stay - // visible while tall step content scrolls. Skipped in embedded mode, where the - // body doesn't scroll (the host dialog does) and a sticky footer would misbehave. - .tb-install-wizard-body:not(.tb-install-wizard-embedded) .step-footer { - position: sticky; - bottom: 0; - z-index: 15; - background: #fff; - } } @mixin wizard-step-basics { @@ -165,27 +129,27 @@ transition: border-color 0.2s, background 0.2s; &:hover { border-color: var(--tb-primary-400); background: color-mix(in srgb, var(--tb-primary-500) 4%, transparent); } &.selected { border-color: var(--tb-primary-500); background: color-mix(in srgb, var(--tb-primary-500) 8%, transparent); } - &.locked-out, &:disabled { opacity: 0.35; cursor: not-allowed; pointer-events: none; } + &.locked-out, &:disabled { + cursor: not-allowed; pointer-events: none; + mat-icon, h4 { opacity: 0.35; } + } mat-icon { font-size: 36px; width: 36px; height: 36px; color: var(--tb-primary-500); margin-bottom: 8px; } h4 { font-size: 16px; font-weight: 500; margin: 0 0 4px; } p { font-size: 13px; color: $agent-text-secondary; margin: 0; } - } -} -@mixin wizard-yaml-editor { - // Defensive: also contain overscroll on the editor hosts themselves, so even - // if a swipe lands directly on an ace editor (not on the body), it won't be - // interpreted as page navigation. - .diff-viewer, - .yaml-editor-ace { - overscroll-behavior: contain; - ::ng-deep .ace_editor, - ::ng-deep .ace_scroller, - ::ng-deep .ace_content { - overscroll-behavior: contain; + @media #{$mat-lt-sm} { + display: grid; + grid-template-columns: 32px minmax(0, 1fr); + column-gap: 12px; + align-items: center; + padding: 12px 16px; + text-align: left; + mat-icon { grid-row: span 2; font-size: 32px; width: 32px; height: 32px; margin: 0; } } } +} +@mixin wizard-yaml-editor { .tb-compose-panel { box-shadow: none !important; border: 1px solid $agent-divider; @@ -195,33 +159,6 @@ } } - .yaml-editor { - width: 100%; box-sizing: border-box; padding: 12px 14px; - border: 1px solid $agent-divider; border-radius: 4px; - background: $agent-surface-muted; color: $agent-editor-fg; - font-family: $agent-mono-font; - font-size: 12px; line-height: 1.55; letter-spacing: 0; - tab-size: 2; -moz-tab-size: 2; - resize: vertical; - &:focus { - outline: none; border-color: var(--tb-primary-400); - box-shadow: 0 0 0 3px color-mix(in srgb, var(--tb-primary-400) 15%, transparent); - } - } - - // Ace-backed single editor (install mode and detail view) sits in the same - // .yaml-editor box but needs padding removed and a fixed height for ace layout. - .yaml-editor-ace { - padding: 0; - height: clamp(220px, calc(85vh - 280px), 520px); - overflow: hidden; - ::ng-deep .ace_editor { - font-family: $agent-mono-font !important; - background: transparent; - } - ::ng-deep .ace_gutter { background: $agent-surface-soft; color: $agent-ink-42; } - } - .pull-images { display: block; margin-top: 12px; } // Compact, content-width toggle (Material defaults the group to full width). @@ -280,6 +217,8 @@ .diff-header { flex: 1 1 50%; box-sizing: border-box; padding: 8px 12px; font-size: 12px; font-weight: 500; letter-spacing: 0.3px; + min-width: 0; overflow-wrap: anywhere; + @media #{$mat-lt-sm} { padding: 6px 8px; font-size: 11px; } & + .diff-header { border-left: 1px solid $agent-divider; padding-right: 36px; } &.added { background: $agent-success-surface; color: $agent-color-success-dark; } &.removed { background: #fce4ec; color: $agent-color-error-dark; } @@ -347,102 +286,6 @@ } } - .diff-viewer { - position: relative; - overflow: hidden; - // Fit within the wizard body (which no longer scrolls). Chrome above/below - // the editor (toolbar + stepper header + name field + footer + padding) is - // roughly 280px; the clamp floors at 220px so very short viewports still - // show a usable editor and cap at 520px on large displays. - height: clamp(220px, calc(85vh - 280px), 520px); - width: 100%; - - // ace-diff ships with `.acediff__wrap { overflow: auto }`. That creates an - // extra scrollbar wrapping the two editors + center gutter — the outer - // scrollbar the user sees. Force it hidden; each ace editor has its own - // internal scrollbar for the YAML content and that's the only one we want. - ::ng-deep .acediff__wrap { - overflow: hidden !important; - } - border: 1px solid $agent-divider; - border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; - background: $agent-surface-muted; - - // ace-diff overrides: narrow center gutter, unified monospace styling, tight gutters. - // flex: 0 0 60px is ace-diff's default — must override flex-basis, not just width, - // otherwise the element stays 60px and its grey background leaks around the arrows. - ::ng-deep .acediff__gutter { - flex: 0 0 40px !important; - width: 40px !important; - background: #ffffff !important; - border-left: 1px solid $agent-divider-light !important; - border-right: 1px solid $agent-divider-light !important; - overflow: visible !important; - contain: layout paint style; - will-change: transform; - svg { width: 40px !important; background: transparent !important; } - } - ::ng-deep .ace_editor { - font-family: $agent-mono-font !important; - } - ::ng-deep .ace_gutter { width: 44px !important; background: $agent-surface-soft; color: $agent-ink-42; } - ::ng-deep .ace_gutter-layer { width: 44px !important; } - - // Flip the right pane's gutter to the right edge. Ace lays out .ace_gutter - // and .ace_scroller with absolute positioning (gutter: left 0; scroller: left - // ). Overriding both moves the line numbers against the outer - // edge of the right pane, mirroring the left pane — numbers end up hugging - // both outside edges, with code meeting in the middle at the copy arrows. - ::ng-deep .acediff__right .ace_gutter { - left: auto !important; - right: 0 !important; - border-left: 1px solid $agent-divider-light; - } - ::ng-deep .acediff__right .ace_scroller { - left: 0 !important; - right: 44px !important; - } - ::ng-deep .acediff__right .ace_scrollbar-v { - right: 44px !important; - } - - // Hide the LEFT pane's vertical scrollbar — it overlaps the center gutter and - // covers ace-diff's copy-arrow circles. ace-diff keeps both editors scroll- - // synced internally, and the right pane still shows its own scrollbar, so - // vertical scrolling remains available via mouse wheel / right-side thumb. - ::ng-deep .acediff__left .ace_scrollbar, - ::ng-deep .acediff__left .ace_scrollbar-v { - display: none !important; - width: 0 !important; - } - // Pull the left pane's scroller flush to its right edge so no blank strip - // remains where the scrollbar used to sit. - ::ng-deep .acediff__left .ace_scroller { - right: 0 !important; - } - // Raise the entire center gutter above the panes so nothing from either - // editor can occlude the copy-arrow SVGs. - ::ng-deep .acediff__gutter { - z-index: 10; - } - ::ng-deep .acediff__gutter svg, - ::ng-deep .acediff__copy { - z-index: 11; - position: relative; - } - // The connector SVG paints over the copy arrows and swallows clicks. - // Make the whole gutter SVG click-through so the copy arrow
s stay hit-testable. - ::ng-deep .acediff__gutter svg { pointer-events: none !important; } - ::ng-deep .acediff__copy, - ::ng-deep .acediff__copy--left, - ::ng-deep .acediff__copy--right, - ::ng-deep .acediff__copy--left div, - ::ng-deep .acediff__copy--right div { - pointer-events: auto !important; - z-index: 12 !important; - } - } - .diff-hint { font-size: 12px; color: $agent-text-secondary; margin: 6px 0 0; } diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.html b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.html index 8714ed94dc..de4faf9639 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.html +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.html @@ -5,30 +5,33 @@ --> @if (!embedded) { - + @if (showBack) { - } -
-

{{ 'agent.app-install-title' | translate }}@if (agent) { - : - }

- @if (agent) { - - {{ 'agent.app-install-on-agent' | translate: { name: agent?.name } }} - - } -
+

{{ 'agent.app-install-title' | translate }}@if (agent) {: {{ 'agent.app-install-on-agent' | translate: { name: agent?.name } }}}

+
-
} +@if (embedded) { + + +} @else { +
+ +
+
+ +
+} -
+ @if (checkingManaged) {
@@ -37,7 +40,7 @@ } @if (!checkingManaged && managedApp) { -
+
-
} @if (selectAgent && !embedded && !checkingManaged && !managedApp) { -
+
info_outline agent.deploy-via-agent-desc
@@ -64,284 +61,292 @@ @if (!checkingManaged && !managedApp) { - @if (selectAgent) { - -

agent.deploy-intro

- - - -
- } - @if (!lockedType) { - -

agent.app-install-pick-type

-
- @for (card of typeCards; track card.type) { - - } -
- @if (loadingTemplate) { -
- - agent.app-install-loading-template -
+ @for (step of steps; track step) { + @switch (step) { + @case ('agent') { + +

agent.deploy-intro

+ + +
} - @if (loadError) { -
- error_outline - {{ loadError }} -
+ @case ('type') { + +

agent.app-install-pick-type

+
+ @for (card of typeCards; track card.type) { + + } +
+ @if (loadingTemplate) { +
+ + agent.app-install-loading-template +
+ } + @if (loadError) { +
+ error_outline + {{ loadError }} +
+ } +
} - -
- } - -
- - {{ 'agent.app-install-from-profile' | translate }} - {{ 'agent.app-install-custom-config' | translate }} - -
- - agent.app-install-name - - - @if (canHaveRelatedEntity) { - - - } - @if (useProfile) { - - agent.app-install-select-profile - - @if (profileSelectFormGroup.get('profile').value) { - - } - @if (!profileSelectFormGroup.get('profile').value && canCreateAppProfile) { - - } - - @if (filteredProfiles | async; as profiles) { - @for (p of profiles; track trackKey(p)) { - - {{ p.name }} - @if (isVirtualProfile(p)) { - {{ 'agent.app-install-virtual-profile-badge' | translate }} - } - @if (!isVirtualProfile(p) && p.templateVersion) { - {{ profileTemplateLabel(p) }} + @case ('config') { + +
+ + {{ 'agent.app-install-from-profile' | translate }} + {{ 'agent.app-install-custom-config' | translate }} + +
+ + agent.app-install-name + + + @if (canHaveRelatedEntity) { + + + } + @if (useProfile && typesWithoutTemplates.has(selectedType)) { +
+ warning_amber + agent.app-no-templates +
+ } + @if (useProfile) { + + agent.app-install-select-profile + + @if (profileSelectFormGroup.get('profile').value) { + + } + @if (!profileSelectFormGroup.get('profile').value && canCreateProfileForType) { + + } + + @if (filteredProfiles | async; as profiles) { + @for (p of profiles; track trackKey(p)) { + + {{ p.name }} + @if (isVirtualProfile(p)) { + {{ 'agent.app-install-virtual-profile-badge' | translate }} + } + @if (!isVirtualProfile(p) && p.templateVersion) { + {{ profileTemplateLabel(p) }} + } + + } + @if (!profiles.length) { + +
+ agent.app-install-no-profiles +
+
+ } } -
+
+
+ } + @if (loadingProfiles) { +
+ + agent.app-install-loading-template +
+ } + + @if (useProfile && selectedProfile && !isVirtualProfile(selectedProfile)) { +
+ +
+ } + @if (useProfile && selectedProfile) { + + + agent.app-install-yaml + + + + + + } + @if (mergeError) { +
+ error_outline + {{ mergeError }} +
+ } + @if (!useProfile && !template && loadError) { +
+ error_outline + {{ loadError }} +
+ } @else if (!useProfile) { + @if (composeTypeKeys.length > 1) { + + agent.app-compose-template-select + + @for (key of composeTypeKeys; track key) { + + {{ composeTypeLabel(key) }} + + } + + } - @if (!profiles.length) { - -
- agent.app-install-no-profiles -
-
+ @if (relatedEntityId) { +
+ info_outline + agent.app-compose-creds-overridden-hint +
} +
+
agent.app-install-diff-template
+
agent.app-install-diff-editable
+ +
+ +

agent.app-install-diff-hint

} - - - } - @if (loadingProfiles) { -
- - agent.app-install-loading-template -
- } - - @if (useProfile && selectedProfile && !isVirtualProfile(selectedProfile)) { -
- -
- } - @if (useProfile && selectedProfile) { - - - agent.app-install-yaml - - - - - - } - @if (!useProfile) { - @if (composeTypeKeys.length > 1) { - - agent.app-compose-template-select - - @for (key of composeTypeKeys; track key) { - - {{ composeTypeLabel(key) }} - +
+ } + @case ('summary') { + +
+
+ agent.app-name + {{ appName }} +
+
+ agent.app-type + {{ selectedType }} +
+ @if (template) { +
+ agent.app-template + {{ template.appType }} {{ template.currentVersion }} +
+ } + @if (useProfile && selectedProfile) { +
+ agent.app-install-select-profile + {{ selectedProfile.name }} +
} - - + @if (agent) { +
+ agent.agents + {{ agent.name }} +
+ } +
+
+ info_outline + agent.app-install-confirm-info +
+
} - @if (relatedEntityId) { -
- info_outline - agent.app-compose-creds-overridden-hint -
+ @case ('deploy') { + + + + } -
-
agent.app-install-diff-template
-
agent.app-install-diff-editable
- -
- -

agent.app-install-diff-hint

} - - - -
-
- agent.app-name - {{ appName }} -
-
- agent.app-type - {{ selectedType }} -
- @if (template) { -
- agent.app-template - {{ template.appType }} {{ template.currentVersion }} -
- } - @if (useProfile && selectedProfile) { -
- agent.app-install-select-profile - {{ selectedProfile.name }} -
- } - @if (agent) { -
- agent.agents - {{ agent.name }} -
- } -
-
- info_outline - agent.app-install-confirm-info -
- -
- @if (selectAgent) { - - - - - }
} -
+ + + + @if (!checkingManaged && !managedApp && (canGoBack() || showNext())) { +
+ @if (canGoBack()) { + + } + + @if (showNext()) { + + } +
+ @if (!embedded || canInstall()) { + + } + } + @if (!embedded || canInstall()) { +
+ @if (!embedded) { + + } + @if (canInstall()) { + + } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.scss b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.scss index 1af432721a..95d4951c34 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.scss @@ -2,10 +2,18 @@ // SPDX-License-Identifier: BUSL-1.1 @use 'agent-wizard' as *; -@include wizard-chrome; +@include wizard-stepper-dialog(1280px); @include wizard-step-basics; @include wizard-type-cards; @include wizard-yaml-editor; @include wizard-diff; @include wizard-summary; @include agent-virtual-profile-badge; +@include wizard-steps-locked; + +:host(.tb-embedded) { + display: block; + width: auto; + height: auto; + max-height: none; +} diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.ts b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.ts index e505901685..ece77cd194 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.ts @@ -6,8 +6,8 @@ import { Router } from '@angular/router'; import { MatDialog } from '@angular/material/dialog'; import { MatStepper, StepperOrientation } from '@angular/material/stepper'; import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; -import { BehaviorSubject, combineLatest, forkJoin, Observable, of } from 'rxjs'; -import { catchError, map, share, startWith } from 'rxjs/operators'; +import { BehaviorSubject, combineLatest, EMPTY, forkJoin, Observable, of, Subscription } from 'rxjs'; +import { catchError, map, share, shareReplay, startWith, switchMap, take } from 'rxjs/operators'; import { PageComponent } from '@shared/components/page.component'; import { TranslateService } from '@ngx-translate/core'; import { AgentService } from '@core/http/agent.service'; @@ -38,22 +38,28 @@ import { buildVirtualAppProfiles, VIRTUAL_APP_TYPES } from '@home/pages/agent/util/virtual-app-profiles'; -import { - AgentAppProfileWizardComponent, - AgentAppProfileWizardData -} from '@home/pages/agent/wizard/agent-app-profile-wizard.component'; +import { openAgentAppProfileWizard } from '@home/pages/agent/wizard/agent-app-profile-wizard-dialog'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { Operation, Resource } from '@shared/models/security.models'; import { AgentAppWizardLoaderService } from '@home/pages/agent/wizard/agent-app-wizard-loader.service'; import { AgentAppWizardSubmitService } from '@home/pages/agent/wizard/agent-app-wizard-submit.service'; -import { AgentAppUpgradeResult, AgentAppWizardFinish, AgentTypeCard } from '@home/pages/agent/wizard/agent-app-wizard.models'; +import { + AGENT_APP_INSTALL_STEP_LABELS, + AgentAppInstallStepKey, + AgentAppUpgradeResult, + AgentAppWizardFinish, + AgentTypeCard +} from '@home/pages/agent/wizard/agent-app-wizard.models'; import { EdgeTemplateCompatibilityService } from '@home/pages/agent/util/edge-template-compatibility.service'; @Component({ selector: 'tb-agent-app-install-flow', templateUrl: './agent-app-install-flow.component.html', styleUrls: ['./agent-app-install-flow.component.scss'], - standalone: false + standalone: false, + host: { + '[class.tb-embedded]': 'embedded' + } }) export class AgentAppInstallFlowComponent extends PageComponent implements OnInit { @@ -82,6 +88,9 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni @ViewChild('stepper', { static: false }) stepper: MatStepper; + readonly stepLabels = AGENT_APP_INSTALL_STEP_LABELS; + steps: AgentAppInstallStepKey[] = []; + selectedIndex = 0; bindings: StepBinding[] = []; @@ -101,6 +110,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni composeTypeKeys: string[] = []; loadingTemplate = false; loadError = ''; + mergeError = ''; private advanceAfterTypeSelect = false; appName = ''; @@ -112,6 +122,13 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni useProfile = true; selectedProfile: AgentAppProfile | null = null; loadingProfiles = false; + typesWithoutTemplates = new Set(); + // No templates and no existing profiles: nothing can be installed for the type. + unavailableTypes = new Set(); + detectingTypes = true; + private typeAvailability$: Observable; + private typeLoadSubscription: Subscription | null = null; + private mergeSubscription: Subscription | null = null; profileSelectFormGroup: UntypedFormGroup; filteredProfiles: Observable; @@ -153,6 +170,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni private pendingCustomCompose: string | null = null; readonly canCreateAppProfile: boolean; + private readonly canReadAppProfiles: boolean; constructor(private router: Router, private translate: TranslateService, @@ -166,6 +184,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni private destroyRef: DestroyRef) { super(); this.canCreateAppProfile = this.userPermissionsService.hasGenericPermission(Resource.AGENT_APP_PROFILE, Operation.CREATE); + this.canReadAppProfiles = this.userPermissionsService.hasGenericPermission(Resource.AGENT_APP_PROFILE, Operation.READ); this.profileSelectFormGroup = this.fb.group({ profile: [null] }); const text$ = this.profileSelectFormGroup.get('profile').valueChanges.pipe( startWith(this.profileSelectFormGroup.get('profile').value), @@ -197,6 +216,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni } ngOnInit() { + this.steps = this.buildSteps(); this.relatedEntityId = this.lockedRelatedEntity || null; if (this.selectAgent && this.lockedRelatedEntity?.id && this.lockedRelatedEntity?.entityType) { this.checkingManaged = true; @@ -217,22 +237,57 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni } }); } - this.loader.prewarmTemplates(this.typeCards.map(card => card.type)); + const types = this.lockedType ? [this.lockedType] : this.typeCards.map(card => card.type); + this.detectTypeAvailability(types); + this.loader.prewarmTemplates(types, this.destroyRef); if (this.lockedType) { this.selectType(this.lockedType); } } + private detectTypeAvailability(types: AgentApplicationType[]) { + this.typeAvailability$ = forkJoin(types.map(type => forkJoin([ + this.loader.loadTemplatesByType(type).pipe(catchError(() => of(null))), + this.canReadAppProfiles ? this.loader.loadProfiles(type).pipe(catchError(() => of(null))) : of([]) + ]))).pipe( + map(results => { + results.forEach(([templates, profiles], index) => { + if (templates && !this.edgeTemplateCompatibility.filterTemplates(templates).length) { + this.typesWithoutTemplates.add(types[index]); + if (profiles && !this.edgeTemplateCompatibility.filterProfiles(profiles).length) { + this.unavailableTypes.add(types[index]); + } + } + }); + }), + shareReplay({ bufferSize: 1, refCount: true }) + ); + this.typeAvailability$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => { + this.detectingTypes = false; + }); + } + + isTypeDisabled(type: AgentApplicationType): boolean { + return this.detectingTypes || this.unavailableTypes.has(type); + } + + get canCreateProfileForType(): boolean { + return this.canCreateAppProfile && !this.typesWithoutTemplates.has(this.selectedType); + } + selectType(type: AgentApplicationType) { if (this.selectedType === type) { return; } this.selectedType = type; + this.typeLoadSubscription?.unsubscribe(); + this.mergeSubscription?.unsubscribe(); this.template = null; this.composeType = null; this.composeTypeKeys = []; this.composeYaml = ''; this.mergedApp = null; + this.loadingTemplate = false; this.selectedProfile = null; this.profileSelectFormGroup.get('profile').patchValue(null, { emitEvent: false }); this.availableProfiles = []; @@ -241,6 +296,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni this.pendingCustomCompose = null; this.appName = this.defaultAppName(type); this.loadError = ''; + this.mergeError = ''; this.advanceAfterTypeSelect = !this.lockedType; if (this.useProfile) { @@ -266,12 +322,16 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni this.savedProfile = this.selectedProfile; } this.useProfile = value; + this.typeLoadSubscription?.unsubscribe(); + this.mergeSubscription?.unsubscribe(); this.selectedProfile = null; this.profileSelectFormGroup.get('profile').patchValue(null, { emitEvent: false }); this.template = null; this.composeYaml = ''; this.mergedApp = null; + this.loadingTemplate = false; this.loadError = ''; + this.mergeError = ''; this.credentialValues = {}; if (this.selectedType) { if (value) { @@ -322,6 +382,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni selectProfile(profile: AgentAppProfile) { if (!profile) { return; } this.selectedProfile = profile; + this.mergeSubscription?.unsubscribe(); this.profileSelectFormGroup.get('profile').patchValue(profile, { emitEvent: false }); this.composeYaml = dumpCompose(profile); this.initCredentialValues(); @@ -351,12 +412,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni const appType = this.selectedType || this.lockedType; if (!appType) { return; } const presetName = this.relatedEntityName ? `${this.relatedEntityName} profile` : undefined; - this.dialog.open( - AgentAppProfileWizardComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-agent-wizard-dialog'], - data: { lockedAppType: appType, presetName } - }).afterClosed().subscribe(saved => { + openAgentAppProfileWizard(this.dialog, { lockedAppType: appType, presetName }).subscribe(saved => { if (saved) { this.availableProfiles = [ ...this.availableProfiles.filter(p => !(isVirtualAppProfile(p) && p.templateVersion === saved.templateVersion)), @@ -370,12 +426,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni openEditProfile() { if (!this.selectedProfile || isVirtualAppProfile(this.selectedProfile)) { return; } - this.dialog.open( - AgentAppProfileWizardComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-agent-wizard-dialog'], - data: { profile: this.selectedProfile } - }).afterClosed().subscribe(saved => { + openAgentAppProfileWizard(this.dialog, { profile: this.selectedProfile }).subscribe(saved => { if (saved) { this.availableProfiles = this.availableProfiles.map(p => p.id?.id === saved.id?.id ? saved : p); this.cacheRealProfiles(saved.appType); @@ -413,7 +464,9 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni const draft = buildRelatedMergeDraft( this.agentId, this.selectedType!, this.appName, tpl, this.composeYaml, dockerComposeConfig(this.mergedApp)?.compose); - this.loader.merge( + this.mergeError = ''; + this.mergeSubscription?.unsubscribe(); + this.mergeSubscription = this.loader.merge( tpl.currentVersion, tpl.appType, draft, this.useProfile ? undefined : (this.composeType || undefined), this.relatedEntityId || undefined, undefined, true ).subscribe({ @@ -430,7 +483,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni } }, error: () => { - this.loadError = this.translate.instant('agent.app-install-merge-failed'); + this.mergeError = this.translate.instant('agent.app-install-merge-failed'); } }); } @@ -454,6 +507,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni private clearProfileSelection() { this.selectedProfile = null; + this.mergeSubscription?.unsubscribe(); this.composeYaml = ''; this.credentialValues = {}; this.template = null; @@ -463,14 +517,16 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni private loadProfilesForType(type: AgentApplicationType) { this.loadingProfiles = true; - const templates$: Observable = VIRTUAL_APP_TYPES.includes(type) && this.canCreateAppProfile + const templates$: Observable = this.canCreateAppProfile ? this.loader.loadTemplatesByType(type).pipe(catchError(() => of([]))) : of([]); - forkJoin([this.loader.loadProfiles(type), templates$]).subscribe({ + const profiles$: Observable = this.canReadAppProfiles ? this.loader.loadProfiles(type) : of([]); + this.typeLoadSubscription = forkJoin([profiles$, templates$]).subscribe({ next: ([allProfiles, allTemplates]) => { const profiles = this.edgeTemplateCompatibility.filterProfiles(allProfiles); const templates = this.edgeTemplateCompatibility.filterTemplates(allTemplates); - this.availableProfiles = [...profiles, ...buildVirtualAppProfiles(templates, allProfiles)]; + const virtualProfiles = VIRTUAL_APP_TYPES.includes(type) ? buildVirtualAppProfiles(templates, allProfiles) : []; + this.availableProfiles = [...profiles, ...virtualProfiles]; this.loadingProfiles = false; this.advanceFromTypeStep(); }, @@ -483,7 +539,18 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni private loadTemplateForType(type: AgentApplicationType) { this.loadingTemplate = true; - this.loader.loadTemplate(type).subscribe({ + this.typeLoadSubscription = this.typeAvailability$.pipe( + take(1), + switchMap(() => { + if (this.typesWithoutTemplates.has(type)) { + this.loadingTemplate = false; + this.loadError = this.translate.instant('agent.app-no-templates'); + return EMPTY; + } + return this.loader.loadTemplate(type); + }), + takeUntilDestroyed(this.destroyRef) + ).subscribe({ next: tpl => this.applyTemplate(tpl), error: () => { this.loadError = this.translate.instant('agent.app-install-template-failed'); @@ -528,7 +595,9 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni private runMergeForPreview(tpl: AgentAppTemplate) { const draft = buildInstallMergeDraft(this.agentId, this.selectedType!, this.appName, tpl); - this.loader.merge(tpl.currentVersion, tpl.appType, draft, this.composeType || undefined, this.relatedEntityId || undefined, undefined, true).subscribe({ + this.mergeError = ''; + this.mergeSubscription?.unsubscribe(); + this.mergeSubscription = this.loader.merge(tpl.currentVersion, tpl.appType, draft, this.composeType || undefined, this.relatedEntityId || undefined, undefined, true).subscribe({ next: merged => { this.mergedApp = merged; if (!this.useProfile) { @@ -541,7 +610,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni } }, error: () => { - this.loadError = this.translate.instant('agent.app-install-merge-failed'); + this.mergeError = this.translate.instant('agent.app-install-merge-failed'); } }); } @@ -609,6 +678,9 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni } canSubmit(): boolean { + if (this.mergeError) { + return false; + } if (this.relatedEntityRequired && !this.relatedEntityId?.id) { return false; } @@ -659,4 +731,55 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni cancel() { this.cancelled.emit(null); } + + currentStep(): AgentAppInstallStepKey | undefined { + return this.steps[this.selectedIndex]; + } + + canGoBack(): boolean { + return this.selectedIndex > 0 && !this.installedApplication; + } + + canInstall(): boolean { + return !this.checkingManaged && !this.managedApp && !this.installedApplication; + } + + showNext(): boolean { + const hasNext = this.selectedIndex < this.steps.length - 1; + return hasNext && (this.currentStep() !== 'summary' || !!this.installedApplication); + } + + canGoNext(): boolean { + switch (this.currentStep()) { + case 'agent': + return this.canProceedFromAgent(); + case 'type': + return this.canProceedFromType(); + case 'config': + return this.canSubmit(); + case 'summary': + return !!this.installedApplication; + default: + return false; + } + } + + nextStepLabel(): string { + return this.stepLabels[this.steps[this.selectedIndex + 1]] ?? ''; + } + + private buildSteps(): AgentAppInstallStepKey[] { + const keys: AgentAppInstallStepKey[] = []; + if (this.selectAgent) { + keys.push('agent'); + } + if (!this.lockedType) { + keys.push('type'); + } + keys.push('config', 'summary'); + if (this.selectAgent) { + keys.push('deploy'); + } + return keys; + } } diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard-dialog.ts b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard-dialog.ts new file mode 100644 index 0000000000..c4d6a400fd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard-dialog.ts @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { MatDialog } from '@angular/material/dialog'; +import { Observable } from 'rxjs'; +import { + AgentAppInstallWizardComponent, + AgentAppInstallWizardData, + AgentAppInstallWizardResult +} from '@home/components/agent/wizard/agent-app-install-wizard.component'; + +export function openAgentAppInstallWizard( + dialog: MatDialog, + data: AgentAppInstallWizardData +): Observable { + return dialog.open( + AgentAppInstallWizardComponent, { + disableClose: false, + panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-wide-dialog'], + data + } + ).afterClosed(); +} diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.scss b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.scss deleted file mode 100644 index d662554d66..0000000000 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.scss +++ /dev/null @@ -1,5 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -@use 'agent-wizard' as *; - -@include wizard-chrome; diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.ts b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.ts index 6b74694329..2a95ed1705 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.ts @@ -47,7 +47,6 @@ export { isAgentAppUpgradeResult } from '@home/pages/agent/wizard/agent-app-wiza @Component({ selector: 'tb-agent-app-install-wizard', templateUrl: './agent-app-install-wizard.component.html', - styleUrls: ['./agent-app-install-wizard.component.scss'], standalone: false, providers: [AgentAppWizardLoaderService, AgentAppWizardSubmitService] }) diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.html b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.html index 46c50b18b7..6f42c808d0 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.html +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.html @@ -5,36 +5,28 @@ --> @if (!embedded) { - + @if (showBack) { - } -
-

{{ 'agent.app-update-wizard-title' | translate }}@if (existingApplication) { - : - }

- @if (existingApplication) { - - {{ 'agent.app-update-on-app' | translate: { name: existingApplication?.name } }} - - } -
+

{{ 'agent.app-update-wizard-title' | translate }}@if (existingApplication) {: {{ 'agent.app-update-on-app' | translate: { name: existingApplication?.name } }}}

+
-
} - -
+
- + agent.app-install-name @@ -124,13 +116,6 @@

agent.app-update-compare-hint

} - -
@@ -171,18 +156,33 @@ info_outline agent.app-install-confirm-info
- -
+
+
+ @if (selectedIndex > 0) { + + } + + @if (selectedIndex === 0) { + + } +
+ +
+ + +
+
diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.scss b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.scss index 29da806e40..a5d3ab398a 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.scss @@ -2,7 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 @use 'agent-wizard' as *; -@include wizard-chrome; +@include wizard-stepper-dialog(1280px); @include wizard-step-basics; @include wizard-config-section; @include wizard-diff; diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.ts b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.ts index 83dc7275e8..481316fb06 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.ts @@ -23,10 +23,7 @@ import { buildStepInputs, createStepBinding, StepBinding } from '@home/pages/age import { buildUpdateApplication } from '@home/pages/agent/util/agent-app-payloads'; import { buildUpdateMergeDraft } from '@home/pages/agent/util/agent-app-compose-preview'; import { composeTemplateKeys, composeTypeLabelKey, dumpCompose, pickComposeType } from '@home/pages/agent/util/agent-compose-yaml'; -import { - AgentAppProfileWizardComponent, - AgentAppProfileWizardData -} from '@home/pages/agent/wizard/agent-app-profile-wizard.component'; +import { openAgentAppProfileWizard } from '@home/pages/agent/wizard/agent-app-profile-wizard-dialog'; import { AgentAppWizardLoaderService } from '@home/pages/agent/wizard/agent-app-wizard-loader.service'; import { AgentAppWizardSubmitService } from '@home/pages/agent/wizard/agent-app-wizard-submit.service'; import { AgentAppUpgradeResult, AgentAppWizardFinish } from '@home/pages/agent/wizard/agent-app-wizard.models'; @@ -52,6 +49,8 @@ export class AgentAppUpdateFlowComponent extends PageComponent implements OnInit @Output() cancelled = new EventEmitter(); @Output() back = new EventEmitter(); + selectedIndex = 0; + bindings: StepBinding[] = []; proposedYaml = ''; @@ -237,12 +236,7 @@ export class AgentAppUpdateFlowComponent extends PageComponent implements OnInit openEditProfile() { if (!this.profileForCompare) { return; } - this.dialog.open( - AgentAppProfileWizardComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-agent-wizard-dialog'], - data: { profile: this.profileForCompare } - }).afterClosed().subscribe(saved => { + openAgentAppProfileWizard(this.dialog, { profile: this.profileForCompare }).subscribe(saved => { if (saved) { this.profileForCompare = saved; this.refreshFutureCompare(); diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.html b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.html index aba02480fa..bf7cfeb2e2 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.html +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.html @@ -5,30 +5,21 @@ --> @if (!embedded) { - + @if (showBack) { - } -
-

{{ 'agent.app-upgrade-title' | translate }}@if (existingApplication) { - : - }

- @if (existingApplication) { - - {{ 'agent.app-upgrade-heading' | translate: { name: existingApplication?.name, from: fromVersion || '—', to: toVersion || '—' } }} - - } -
+

{{ 'agent.app-upgrade-title' | translate }}@if (existingApplication) {: {{ 'agent.app-upgrade-heading' | translate: { name: existingApplication?.name, from: fromVersion || '—', to: toVersion || '—' } }}}

+
-
} - -
+
@if (loadingTemplate || loadingProfile) {
@@ -45,143 +36,154 @@ @if (!(loadingTemplate || loadingProfile || loadError)) { - @if (showProfileUpgradeStep) { - - @if (loadingProfile) { -
- - agent.app-upgrade-profile-loading -
+ @for (step of steps; track step) { + @switch (step) { + @case ('profile') { + + @if (loadingProfile) { +
+ + agent.app-upgrade-profile-loading +
+ } + @if (!loadingProfile && profileLoadError) { +
+ error_outline + {{ profileLoadError }} +
+ } + @if (!loadingProfile && !profileLoadError && profile && template) { +
+
+ agent.app-upgrade-profile-name + {{ profile.name }} +
+
+ agent.app-upgrade-summary-versions + {{ fromVersion || '—' }} → {{ toVersion || '—' }} +
+
+

agent.app-upgrade-profile-hint

+
+
+ {{ 'agent.app-upgrade-template-new' | translate: { version: toVersion || '—' } }} +
+
agent.app-upgrade-profile-current
+ @if (profileUpgraded) { +
+ lock + agent.app-diff-read-only +
+ } + +
+ +

agent.app-upgrade-diff-hint

+ } +
} - @if (!loadingProfile && profileLoadError) { -
- error_outline - {{ profileLoadError }} -
+ @case ('config') { + + @if (canHaveRelatedEntity && isProfileBoundUpgrade) { + + + } + + @if (!isProfileBoundUpgrade) { +
+
+ {{ 'agent.app-upgrade-template-new' | translate: { version: toVersion || '—' } }} +
+
agent.app-upgrade-current
+ +
+ +

agent.app-upgrade-diff-hint

+ } +
} - @if (!loadingProfile && !profileLoadError && profile && template) { -
-
- agent.app-upgrade-profile-name - {{ profile.name }} -
-
- agent.app-upgrade-summary-versions - {{ fromVersion || '—' }} → {{ toVersion || '—' }} + @case ('summary') { + +
+
+ agent.app-name + {{ appName }} +
+
+ agent.app-upgrade-summary-versions + {{ fromVersion || '—' }} → {{ toVersion || '—' }} +
+ @if (hasBackupVolumeInput) { +
+ agent.app-upgrade-summary-volumes-label + + {{ 'agent.app-upgrade-summary-volumes' | translate: { count: selectedBackupVolumeCount } }} + +
+ }
-
-

agent.app-upgrade-profile-hint

-
-
- {{ 'agent.app-upgrade-template-new' | translate: { version: toVersion || '—' } }} +
+ info_outline + agent.app-upgrade-rollback-info
-
agent.app-upgrade-profile-current
- @if (profileUpgraded) { -
- lock - agent.app-diff-read-only -
- } - -
- -

agent.app-upgrade-diff-hint

+ } - - - } - - @if (canHaveRelatedEntity && isProfileBoundUpgrade) { - - - } - - @if (!isProfileBoundUpgrade) { -
-
- {{ 'agent.app-upgrade-template-new' | translate: { version: toVersion || '—' } }} -
-
agent.app-upgrade-current
- -
- -

agent.app-upgrade-diff-hint

} - -
- -
-
- agent.app-name - {{ appName }} -
-
- agent.app-upgrade-summary-versions - {{ fromVersion || '—' }} → {{ toVersion || '—' }} -
- @if (hasBackupVolumeInput) { -
- agent.app-upgrade-summary-volumes-label - - {{ 'agent.app-upgrade-summary-volumes' | translate: { count: selectedBackupVolumeCount } }} - -
- } -
-
- info_outline - agent.app-upgrade-rollback-info -
- -
+ } }
+
+ @if (canGoBack() || showNext()) { +
+ @if (canGoBack()) { + + } + + @if (showNext()) { + + } +
+ + } +
+ + @if (currentStep() === 'profile' && !profileUpgraded) { + + } @else { + + } +
+
diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.scss b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.scss index fcbe6cb001..d3ab782e2b 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.scss @@ -2,7 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 @use 'agent-wizard' as *; -@include wizard-chrome; +@include wizard-stepper-dialog(1280px); @include wizard-step-basics; @include wizard-diff; @include wizard-summary; diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.ts b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.ts index 12a0e21ae7..133567985a 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.ts @@ -29,7 +29,12 @@ import { ActionNotificationShow } from '@core/notification/notification.actions' import * as YAML from 'yaml'; import { AgentAppWizardLoaderService } from '@home/pages/agent/wizard/agent-app-wizard-loader.service'; import { AgentAppWizardSubmitService } from '@home/pages/agent/wizard/agent-app-wizard-submit.service'; -import { AgentAppUpgradeResult, AgentAppWizardFinish } from '@home/pages/agent/wizard/agent-app-wizard.models'; +import { + AGENT_APP_UPGRADE_STEP_LABELS, + AgentAppUpgradeResult, + AgentAppUpgradeStepKey, + AgentAppWizardFinish +} from '@home/pages/agent/wizard/agent-app-wizard.models'; @Component({ selector: 'tb-agent-app-upgrade-flow', @@ -65,10 +70,11 @@ export class AgentAppUpgradeFlowComponent extends PageComponent implements OnIni profileLoadError = ''; profileUpgrading = false; profileUpgraded = false; - showProfileUpgradeStep = false; - @ViewChild('stepper', { static: false }) stepper: MatStepper; + readonly stepLabels = AGENT_APP_UPGRADE_STEP_LABELS; + steps: AgentAppUpgradeStepKey[] = ['config', 'summary']; + selectedIndex = 0; bindings: StepBinding[] = []; @@ -210,7 +216,7 @@ export class AgentAppUpgradeFlowComponent extends PageComponent implements OnIni private maybeInitProfileDiff() { if (!this.needsProfileUpgrade || !this.template || !this.profile || this.profileMergeRequested) { return; } this.profileMergeRequested = true; - this.showProfileUpgradeStep = true; + this.steps = ['profile', 'config', 'summary']; const profileComposeType = dockerComposeConfig(this.profile)?.composeType || undefined; this.profileProposedYaml = dumpRawTemplateCompose(this.template, profileComposeType); const draft = { ...this.profile, templateVersion: this.template.currentVersion } as AgentAppProfile; @@ -354,4 +360,25 @@ export class AgentAppUpgradeFlowComponent extends PageComponent implements OnIni // the caller refresh even when the user backs out before the app upgrade. this.cancelled.emit(this.profileUpgraded ? { profileOnly: true } : null); } + + currentStep(): AgentAppUpgradeStepKey | undefined { + return this.loadingTemplate || this.loadingProfile || this.loadError ? undefined : this.steps[this.selectedIndex]; + } + + canGoBack(): boolean { + return this.selectedIndex > 0 && this.steps[this.selectedIndex - 1] !== 'profile'; + } + + showNext(): boolean { + const step = this.currentStep(); + return step === 'config' || (step === 'profile' && this.profileUpgraded); + } + + canGoNext(): boolean { + return this.currentStep() === 'profile' ? this.profileUpgraded : this.canSubmit(); + } + + nextStepLabel(): string { + return this.stepLabels[this.steps[this.selectedIndex + 1]] ?? ''; + } } diff --git a/ui-ngx/src/app/modules/home/components/ai/_ai-breakpoints.scss b/ui-ngx/src/app/modules/home/components/ai/_ai-breakpoints.scss new file mode 100644 index 0000000000..fae4946635 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/_ai-breakpoints.scss @@ -0,0 +1,7 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +// Widths at which the AI chat drops secondary text. The chat head's narrow width used by the +// component code is AI_NARROW_HEAD_WIDTH in ai-breakpoints.ts. +$ai-head-status-hidden-below: 400px; +$ai-composer-auto-label-max: 400px; diff --git a/ui-ngx/src/app/modules/home/components/ai/_ai-code-blocks.scss b/ui-ngx/src/app/modules/home/components/ai/_ai-code-blocks.scss new file mode 100644 index 0000000000..5596a7f727 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/_ai-code-blocks.scss @@ -0,0 +1,506 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@mixin ai-code-blocks { + div.code-wrapper { + margin-top: 14px; + } + + .tb-codeblock { + position: relative; + min-width: 0; + font-size: 14px; + line-height: 20px; + border-radius: 10px; + background: var(--tb-code-bg); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.05); + + &.folded { + .tb-code { + display: none; + } + + .tb-codeblock-head { + border-bottom-color: transparent; + } + } + + &:not(.labeled) .tb-code { + padding-right: 44px; + } + + &.labeled .tb-code { + border-radius: 0 0 10px 10px; + } + + &:is([data-lang="python"], [data-lang="js"], [data-lang="c"], [data-lang="json"], [data-lang="yaml"]) .tb-code { + overflow-x: auto; + scrollbar-width: thin; + scrollbar-color: rgba(255, 255, 255, 0.2) transparent; + + &, code { + white-space: pre; + overflow-wrap: normal; + } + } + + &.wrap .tb-code { + &, code { + white-space: pre-wrap; + overflow-wrap: anywhere; + } + } + } + + .tb-codeblock-head { + display: flex; + align-items: center; + gap: 8px; + height: 36px; + box-sizing: border-box; + padding: 0 4px 0 12px; + border-bottom: 1px solid var(--tb-code-line); + font-family: var(--tb-font); + font-size: 12px; + line-height: 16px; + letter-spacing: .2px; + font-weight: 500; + color: var(--tb-code-head-fg); + + .mat-icon { + flex: none; + color: rgba(255, 255, 255, 0.42); + } + + > .tb-codeblock-label { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 12px; + line-height: 16px; + letter-spacing: .2px; + color: var(--tb-code-head-fg); + } + } + + .tb-codetabs { + flex: 1; + display: flex; + align-self: stretch; + gap: 2px; + min-width: 0; + margin-left: -4px; + overflow-x: auto; + scrollbar-width: none; + } + + .tb-codetab { + position: relative; + height: 100%; + padding: 0 8px; + border: 0; + border-radius: 6px 6px 0 0; + background: none; + font: 500 12px/16px var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; + color: rgba(255, 255, 255, 0.62); + cursor: pointer; + + &:hover { + color: rgba(255, 255, 255, 0.85); + } + + &[aria-selected="true"] { + color: #fff; + + &::after { + content: ''; + position: absolute; + left: 8px; + right: 8px; + bottom: -1px; + height: 2px; + border-radius: 2px 2px 0 0; + background: var(--hl-cmd); + } + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300, #7fb5ff); + outline-offset: -4px; + } + } + + .tb-codefold { + flex: 1; + min-width: 0; + display: flex; + align-items: center; + gap: 8px; + height: 100%; + margin-left: -6px; + padding: 0 6px; + border: 0; + border-radius: 6px; + background: none; + color: inherit; + font: inherit; + letter-spacing: inherit; + text-align: left; + cursor: pointer; + + &:hover { + background: rgba(255, 255, 255, 0.05); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: -2px; + } + + .tb-codeblock-label { + flex: none; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .tb-codeblock-size { + flex: none; + color: rgba(255, 255, 255, 0.55); + font-weight: 400; + white-space: nowrap; + } + + .tb-codefold-tg { + margin-left: auto; + transition: transform .2s ease; + } + } + + .tb-codeblock:not(.folded) .tb-codefold-tg { + transform: rotate(180deg); + } + + .tb-codecopy { + position: relative; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + margin: 0; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + color: rgba(255, 255, 255, 0.72); + font: inherit; + letter-spacing: normal; + cursor: pointer; + outline: none; + + &:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; + } + + &[aria-pressed="true"] { + background: rgba(255, 255, 255, 0.12); + color: #fff; + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: 1px; + } + + &.floating { + position: absolute; + top: 8px; + right: 8px; + } + + &::after { + content: attr(data-tip); + position: absolute; + right: 0; + bottom: calc(100% + 6px); + padding: 3px 8px; + border-radius: 5px; + background: #10181d; + color: #fff; + font: 500 11px/16px var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; + box-shadow: 0 2px 8px rgba(16, 24, 40, 0.3); + opacity: 0; + pointer-events: none; + transition: opacity .12s ease; + } + + &.copied::after { + content: attr(data-copied); + } + + &:hover::after, &:focus-visible::after, &.copied::after { + opacity: 1; + } + } + + .tb-codecopy > .mat-icon { + transition: opacity .15s ease, transform .15s cubic-bezier(.2, 0, 0, 1); + } + + .tb-codecopy > .mat-icon.tb-copy-ok { + position: absolute; + inset: 0; + margin: auto; + opacity: 0; + transform: scale(.5); + color: var(--ai-dark-accent); + } + + .tb-codecopy.copied > .mat-icon:not(.tb-copy-ok) { + opacity: 0; + transform: scale(.5); + } + + .tb-codecopy.copied > .mat-icon.tb-copy-ok { + opacity: 1; + transform: scale(1); + } + + .tb-codecopy.labelled { + width: auto; + gap: 5px; + padding: 0 8px 0 6px; + + &::after { + display: none; + } + } + + .tb-codeblock.value { + display: flex; + align-items: center; + gap: 8px; + min-height: 36px; + box-sizing: border-box; + padding: 0 4px 0 12px; + color: var(--tb-code-fg); + font: 500 12px/16px var(--tb-font); + letter-spacing: .2px; + + .tb-codeblock-label { + flex: none; + min-width: 84px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: rgba(255, 255, 255, 0.62); + } + + > code.tb-value { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + padding: 0; + border: 0; + border-radius: 0; + background: none; + font: 13px/20px var(--tb-mono); + letter-spacing: 0; + color: var(--tb-code-fg); + } + } + + .tb-cmdrow { + display: flex; + align-items: center; + gap: 10px; + min-height: 40px; + box-sizing: border-box; + padding: 6px 6px 6px 12px; + border-radius: 8px; + background: var(--tb-code-bg); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.05); + + .tb-cmd-p { + flex: none; + font: 500 13px/20px var(--tb-mono); + color: #7d8c96; + } + + > code.tb-cmd-t { + flex: 1; + min-width: 0; + overflow-x: auto; + scrollbar-width: none; + white-space: nowrap; + padding: 0; + border: 0; + border-radius: 0; + background: none; + font: 400 13px/20px var(--tb-mono); + color: #e8eef2; + -webkit-font-smoothing: antialiased; + } + + .tb-codecopy.tb-cmd-copy { + color: #b4bec6; + } + } + + pre.tb-code, pre.tb-code[class*=language-] { + margin: 0; + padding: 12px 16px 14px; + border: 0; + border-radius: 10px; + background: none; + box-shadow: none; + font-family: var(--tb-mono); + font-size: var(--chat-code); + line-height: var(--chat-code-lh); + color: var(--tb-code-fg); + white-space: pre-wrap; + overflow-wrap: anywhere; + -webkit-font-smoothing: antialiased; + + code, code[class*=language-] { + display: block; + white-space: inherit; + overflow-wrap: inherit; + padding: 0; + border: 0; + border-radius: 0; + background: none; + font: inherit; + color: inherit; + text-shadow: none; + } + } + + .tb-line { + display: block; + min-height: 20px; + + &.add, &.del { + margin: 0 -16px; + padding: 0 16px; + } + + &.add { + background: rgba(143, 227, 211, 0.12); + color: var(--hl-cmd); + } + + &.del { + background: rgba(255, 157, 146, 0.12); + color: var(--hl-err); + } + } + + .tb-codeblock.shell .tb-line { + padding-left: 24px; + text-indent: -24px; + + &.cont { + padding-left: 40px; + } + } + + pre.tb-code div.tb-cmd { + font: inherit; + letter-spacing: inherit; + color: inherit; + } + + .tb-cmd { + position: relative; + margin: 0 -8px; + padding: 2px 36px 2px 8px; + border-radius: 6px; + + & + .tb-cmd { + margin-top: 4px; + } + + &:hover, &:focus-within { + background: rgba(255, 255, 255, 0.05); + + .tb-cmdcopy { + opacity: 1; + } + } + } + + .tb-codecopy.tb-cmdcopy { + position: absolute; + top: 0; + right: 4px; + width: 24px; + height: 24px; + opacity: 0; + text-indent: 0; + + &.copied { + opacity: 1; + } + } + + @media (hover: none) { + .tb-codecopy.tb-cmdcopy { + opacity: .6; + } + } + + .hl-cmd, .hl-ok { + color: var(--hl-cmd); + } + + .hl-flag { + color: var(--hl-flag); + } + + .hl-str, .hl-warn { + color: var(--hl-str); + } + + .hl-num, .hl-kw { + color: var(--hl-num); + } + + .hl-key, .hl-var { + color: var(--hl-key); + } + + .hl-com, .hl-op { + color: var(--hl-com); + } + + .hl-err { + color: var(--hl-err); + } + + .hl-val { + color: var(--tb-code-fg); + } + + .hl-fn { + color: var(--hl-fn); + } + + .hl-bool { + color: var(--hl-bool); + } + + .hl-lvl { + color: var(--hl-lvl); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss b/ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss new file mode 100644 index 0000000000..894eeaad97 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@mixin ai-icon-button($color: var(--tb-ink-54), $icon: 19px, $tap: true, $relative: true) { + @if $relative { + position: relative; + } + flex: none; + width: 32px; + height: 32px; + @if $tap { + min-width: var(--chat-tap); + min-height: var(--chat-tap); + } + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: $color; + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: background-color .15s ease, color .15s ease; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + .mat-icon { + font-size: $icon; + width: $icon; + height: $icon; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html new file mode 100644 index 0000000000..fd61708266 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html @@ -0,0 +1,258 @@ + +@if (hood()) { +

{{ 'ai-assistant.detail.asked-for' | translate }}{{ hood() }}

+} +@for (block of view().blocks; track $index) { + @switch (block.type) { + @case ('hub') { +
+ @for (rec of shown(hub(), 'hub'); track rec.key) { + + } + @if (hub().length > LIST_SHOWN) { + + } +
+ } + @case ('records') { + @if (block.label) { +
{{ say(block.label) }}
+ } +
+ @for (row of shown(block.rows, 'records' + $index); track $index) { +
+ + @if (recordUrl(row); as url) { + {{ row.name }} + } @else { + {{ row.name }} + } + @if (row.status) { + {{ 'ai-assistant.detail.alarm-meta' | translate:{ + severity: ('alarm.severity-' + (row.severity || 'indeterminate').toLowerCase()) | translate, + status: ('ai-assistant.detail.alarm-status.' + row.status) | translate, + since: row.since || '—'} }} + } @else if (row.meta) { + {{ row.meta }} + } +
+ } + @if (block.rows.length > LIST_SHOWN) { + + } +
+ @if (more(block); as rest) { +
{{ 'ai-assistant.detail.more' | translate:{count: rest} }}
+ } + } + @case ('values') { + @if (block.entity) { +

{{ entityName(block.entity) }}

+ } @else if (block.label) { +
{{ say(block.label) }}
+ } +
+ @for (row of block.rows; track $index) { +
{{ row.key }}
+
{{ row.value }}
+ } +
+ } + @case ('series') { + @if (block.entity) { +

{{ entityName(block.entity) }}

+ } + + + + + + + + + + + @for (row of block.rows; track row.key) { + + + + + + + } + +
{{ 'ai-assistant.detail.history-key' | translate }}{{ 'ai-assistant.detail.history-curve' | translate }}{{ 'ai-assistant.detail.history-last' | translate }}{{ 'ai-assistant.detail.history-range' | translate }}
{{ row.key }} + + {{ row.lastText ?? number(row.last) }}{{ row.changes !== undefined + ? ('ai-assistant.detail.history-changes' | translate: {count: row.changes}) + : ('ai-assistant.detail.history-span' | translate: {min: number(row.min), max: number(row.max)}) }}
+ } + @case ('keys') { + @if (block.label) { +
{{ say(block.label) }}
+ } +
+ @for (key of block.keys; track $index) { + {{ key }} + } +
+ } + @case ('facts') { + @if (changeRows(block.rows); as changes) { + @if (changes.length) { +
+ @for (change of changes; track $index) { +
+
{{ label(change) }}
+ @if (change.images; as pair) { +
+ @if (pair.current) { + + } @else { + + } + + {{ 'ai-assistant.review.changes-to' | translate }} + @if (pair.value) { + + } @else { + + } +
+ } @else { +
+ {{ change.was }} + + {{ 'ai-assistant.review.changes-to' | translate }} + {{ factValue(change) }} +
+ } +
+ } +
+ } + } + @if (plainRows(block.rows).length) { +
+ @for (fact of plainRows(block.rows); track $index) { +
{{ label(fact) }}
+
+ @if (fact.images; as pair) { + + @if (pair.current) { + + + } + @if (pair.value) { + + } @else { + {{ 'ai-assistant.review.not-set' | translate }} + } + + } @else if (fact.chip; as chip) { + + @if (chip.image) { + + } @else if (chip.icon) { + + } + {{ factValue(fact) }} + + } @else if (factLink(fact); as url) { + {{ factValue(fact) }} + } @else if (fact.secret && !revealed().has(view().hood?.key + $index)) { + {{ masked(factValue(fact)) }} + + } @else { + {{ factValue(fact) }} + } +
+ } +
+ } + } + @case ('list') { + @if (block.label) { +
{{ say(block.label) }}
+ } +
    + @for (row of block.rows; track $index) { +
  • {{ rowText(row) }}
  • + } +
+ } + @case ('commands') { +
+ } + @case ('code') { + @if (block.title) { +
{{ ('ai-assistant.action.' + block.title) | translate }}
+ } +
{{ block.text }}
+ } + @case ('links') { + + } + @case ('markdown') { +
+ +
+ } + @case ('images') { +
+ @for (image of block.rows; track image.url) { +
+ + @if (image.label) { +
{{ say(image.label) }}
+ } +
+ } +
+ } + @case ('warning') { +
{{ 'ai-assistant.detail.heads-up' | translate }}@if (block.label) {{{ say(block.label) }} }@for (row of block.rows; track $index) {{{ rowText(row) }}@if (!$last) {; }}
+ } + @case ('found') { +

{{ say(block.text) }}

+ } + @case ('note') { +

{{ say(block.text) }}

+ } + @case ('text') { +

{{ block.text }}

+ } + @case ('json') { +
{{ ('ai-assistant.action.' + block.label) | translate }}
+
{{ block.text }}
+ } + } +} + + + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts new file mode 100644 index 0000000000..a810676ce5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts @@ -0,0 +1,293 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiTrueMinus } from '@home/components/ai/ai-text'; +import { afterRenderEffect, ChangeDetectionStrategy, Component, computed, DestroyRef, effect, ElementRef, inject, input, signal, untracked } from '@angular/core'; +import { ClipboardService } from 'ngx-clipboard'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { TranslateService } from '@ngx-translate/core'; +import { forkJoin, of } from 'rxjs'; +import { catchError, map } from 'rxjs/operators'; +import { EntityType, baseDetailsPageByEntityType } from '@shared/models/entity-type.models'; +import { EntityService } from '@core/http/entity.service'; +import { IotHubApiService } from '@core/http/iot-hub-api.service'; +import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; +import { AiRecordView } from '@home/components/ai/ai-record.models'; +import { getEntityDetailsPageURL } from '@core/utils'; +import { aiEntityKind, aiJoinWords, aiThingWord, isAiWordList } from '@home/components/ai/ai-action.models'; +import { codeTabsBlock, decorateCodeBlocks } from '@home/components/ai/ai-code-block'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { + AiDetailBlock, + AiDetailEntity, + AiDetailFact, + AiDetailNames, + AiDetailRecord, + AiDetailText, + AiDetailView +} from '@home/components/ai/ai-action-detail.models'; + +const FETCHED = new Set([ + EntityType.DEVICE, EntityType.ASSET, EntityType.DASHBOARD, EntityType.CUSTOMER, EntityType.USER, EntityType.DEVICE_PROFILE, + EntityType.ASSET_PROFILE, EntityType.ENTITY_VIEW, EntityType.EDGE, EntityType.RULE_CHAIN +]); + +const MAX_HUB = 50; + +const PROTOCOL_KEY = 'tb-ai-code-protocol'; + +@Component({ + selector: 'tb-ai-action-detail', + templateUrl: './ai-action-detail.component.html', + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'k-detail' + } +}) +export class AiActionDetailComponent { + + view = input.required(); + + names = input(new Map()); + + private translate = inject(TranslateService); + private entityService = inject(EntityService); + private iotHubApi = inject(IotHubApiService); + private recordLoader = inject(AiRecordLoaderService); + private destroyRef = inject(DestroyRef); + private host = inject(ElementRef); + private clipboard = inject(ClipboardService); + + private fetched = signal>(new Map()); + + private hubItems = signal>(new Map()); + + revealed = signal>(new Set()); + + readonly LIST_SHOWN = 8; + + private opened = signal>(new Set()); + + isOpen(key: string): boolean { + return this.opened().has(key); + } + + toggleMore(key: string): void { + const next = new Set(this.opened()); + if (!next.delete(key)) { + next.add(key); + } + this.opened.set(next); + } + + shown(rows: T[], key: string): T[] { + return this.isOpen(key) ? rows : rows.slice(0, this.LIST_SHOWN); + } + + hood = computed(() => { + const hood = this.view().hood; + this.fetched(); + return hood ? this.say(hood) : ''; + }); + + hub = computed(() => { + const block = this.view().blocks.find(item => item.type === 'hub'); + const items = this.hubItems(); + if (block?.type !== 'hub') { + return []; + } + return block.rows.map(row => { + const item = items.get(row.id); + if (item) { + const view = this.recordLoader.hubView(item); + return {...view, description: row.description ?? view.description}; + } + return { + key: `HUB:${row.id}`, entityType: 'SOLUTION_TEMPLATE', alarmRule: false, name: row.name, meta: '', + url: `/iot-hub/version/${row.id}`, description: row.description, + hub: {type: '', creator: row.vendor} + }; + }); + }); + + constructor() { + effect(() => { + const view = this.view(); + untracked(() => { + this.resolveNames(view); + this.loadHub(view); + }); + }); + afterRenderEffect(() => { + const view = this.view(); + const copy = (text: string) => this.clipboard.copyFromContent(text); + decorateCodeBlocks(this.host.nativeElement, this.translate, copy); + this.host.nativeElement.querySelectorAll('.k-codetabs-slot:empty').forEach((slot: HTMLElement) => { + const block = view.blocks[Number(slot.dataset.block)]; + if (block?.type === 'commands' && block.rows.length) { + const remembered = this.rememberedTab(); + const initial = Math.max(block.rows.findIndex(row => row.label === remembered), 0); + slot.append(codeTabsBlock(block.rows, 'bash', this.translate, copy, initial, tab => this.rememberTab(tab.label))); + } + }); + }); + } + + say(text: AiDetailText): string { + const params: Record = {}; + for (const [key, value] of Object.entries(text.params ?? {})) { + params[key] = isAiWordList(value) ? aiJoinWords(this.translate, value) + : typeof value === 'object' ? this.entityText(value) : typeof value === 'string' && value.startsWith('ai-assistant.') ? this.translate.instant(value) : value; + } + return this.translate.instant(text.key, params); + } + + codeLabel(label: string): string { + return label.startsWith('ai-assistant.') ? this.translate.instant(label) : label; + } + + label(fact: AiDetailFact): string { + return fact.raw ? fact.label : this.translate.instant(fact.label); + } + + rowText(row: string | AiDetailText): string { + return typeof row === 'string' ? row : this.say(row); + } + + factValue(fact: AiDetailFact): string { + if (fact.say) { + return this.say(fact.say); + } + if (fact.entity) { + return this.nameOf(fact.entity) ?? fact.entity.id ?? '—'; + } + return fact.value && (fact.chip || fact.value.startsWith('ai-assistant.')) ? this.translate.instant(fact.value) : fact.value ?? ''; + } + + factLink(fact: AiDetailFact): string | null { + return fact.entity ? this.urlOf(fact.entity.id, fact.entity.entityType) : null; + } + + masked(value: string): string { + return value.length <= 6 ? '••••••' : '••••••••' + value.slice(-4); + } + + reveal(key: string): void { + this.revealed.update(set => new Set(set).add(key)); + } + + recordUrl(record: AiDetailRecord): string | null { + if (record.entityType === EntityType.ENTITY_GROUP) { + const base = record.id && record.groupType ? baseDetailsPageByEntityType.get(record.groupType as EntityType) : undefined; + return base ? `${base.replace(/\/all$/, '/groups')}/${record.id}` : null; + } + return this.urlOf(record.id, record.entityType); + } + + kind(entityType: string, groupType?: string) { + return entityType === 'IMAGE' ? {icon: 'image', palette: 'view'} : aiEntityKind(entityType, entityType === 'ALARM_RULE', groupType); + } + + more(block: AiDetailBlock): number { + return block.type === 'records' && block.total ? Math.max(block.total - block.rows.length, 0) : 0; + } + + time(ts: number): string { + return new Date(ts).toLocaleString([], {dateStyle: 'short', timeStyle: 'short'}); + } + + number(value?: number): string { + if (value === undefined) { + return ''; + } + return aiTrueMinus(Number.isInteger(value) ? String(value) : String(Math.round(value * 100) / 100)); + } + + private rememberedTab(): string | null { + return readStored(PROTOCOL_KEY); + } + + private rememberTab(label: string): void { + writeStored(PROTOCOL_KEY, label); + } + + changeRows(rows: AiDetailFact[]): AiDetailFact[] { + return rows.filter(row => row.change); + } + + plainRows(rows: AiDetailFact[]): AiDetailFact[] { + return rows.filter(row => !row.change); + } + + entityName(entity: AiDetailEntity): string { + return this.nameOf(entity) ?? this.translate.instant('ai-assistant.detail.this', {what: this.typeWord(entity.entityType)}); + } + + private entityText(entity: AiDetailEntity): string { + const name = this.nameOf(entity); + if (name) { + return name; + } + return this.translate.instant('ai-assistant.detail.this', {what: this.typeWord(entity.entityType)}); + } + + private typeWord(entityType?: string): string { + return aiThingWord(this.translate, entityType, 'ai-assistant.detail.thing.entity'); + } + + private nameOf(entity: AiDetailEntity): string | undefined { + return entity.name ?? (entity.id ? this.names().get(entity.id)?.name ?? this.fetched().get(entity.id) : undefined); + } + + private urlOf(id?: string, entityType?: string): string | null { + return id && entityType && FETCHED.has(entityType) ? getEntityDetailsPageURL(id, entityType as EntityType) || null : null; + } + + private resolveNames(view: AiDetailView): void { + const wanted = new Map(); + const want = (entity?: AiDetailEntity) => { + if (entity?.id && !entity.name && entity.entityType && FETCHED.has(entity.entityType) && !this.names().has(entity.id) && !this.fetched().has(entity.id)) { + wanted.set(entity.id, entity.entityType); + } + }; + Object.values(view.hood?.params ?? {}).forEach(value => typeof value === 'object' && !isAiWordList(value) && want(value)); + view.blocks.forEach(block => { + if (block.type === 'facts') { + block.rows.forEach(fact => want(fact.entity)); + } else if (block.type === 'values' || block.type === 'series') { + want(block.entity); + } + }); + if (!wanted.size) { + return; + } + const config = {ignoreLoading: true, ignoreErrors: true}; + forkJoin([...wanted].map(([id, type]) => this.entityService.getEntity(type as EntityType, id, config).pipe( + map(found => [id, (found as {name?: string; title?: string})?.name ?? (found as {title?: string})?.title] as [string, string]), + catchError(() => of([id, undefined] as [string, string])) + ))).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(found => { + const next = new Map(this.fetched()); + found.filter(([, name]) => !!name).forEach(([id, name]) => next.set(id, name)); + this.fetched.set(next); + }); + } + + private loadHub(view: AiDetailView): void { + const block = view.blocks.find(item => item.type === 'hub'); + if (block?.type !== 'hub' || !this.iotHubApi.baseUrl) { + return; + } + const ids = block.rows.slice(0, MAX_HUB).map(row => row.id).filter(id => !this.hubItems().has(id)); + if (!ids.length) { + return; + } + const config = {ignoreLoading: true, ignoreErrors: true}; + forkJoin(ids.map(id => this.iotHubApi.getVersionInfo(id, config).pipe(catchError(() => of(null))))).pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(items => { + const next = new Map(this.hubItems()); + items.filter(Boolean).forEach(item => next.set(item.id, item)); + this.hubItems.set(next); + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts new file mode 100644 index 0000000000..0180665132 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts @@ -0,0 +1,2393 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiTrueMinus } from '@home/components/ai/ai-text'; +import { AiAction } from '@shared/models/ai-chat.models'; +import { aiPartTitle, aiPartWord, AiWordList, aiWordList, alarmUpdateAction, widgetParts } from '@home/components/ai/ai-action.models'; +import { IntegrationType, integrationTypeInfoMap } from '@shared/models/integration.models'; +import { ConverterType, converterTypeTranslationMap } from '@shared/models/converter.models'; + +const WIDGET_PART_LANGS: Record = {html: 'html', css: 'css', js: 'javascript'}; + +const SCADA_SYMBOL_PART_LANGS: Record = {svg: 'html', functions: 'javascript'}; + +export interface AiDetailEntity { + id?: string; + entityType?: string; + name?: string; +} + +export type AiDetailParam = string | number | AiDetailEntity | AiWordList; + +export interface AiDetailText { + key: string; + params?: Record; +} + +export interface AiDetailRecord { + entityType: string; + groupType?: string; + id?: string; + name: string; + meta?: string; + severity?: string; + status?: string; + since?: string; +} + +export interface AiDetailHubItem { + id: string; + name: string; + vendor?: string; + description?: string; +} + +export interface AiDetailValue { + key: string; + value: string; + time?: number; +} + +export interface AiDetailSeries { + key: string; + points: number; + min?: number; + max?: number; + last?: number; + lastText?: string; + changes?: number; + from: number; + to: number; + path: string; + dot: number; +} + +export interface AiDetailFact { + label: string; + raw?: boolean; + value?: string; + say?: AiDetailText; + entity?: AiDetailEntity; + mono?: boolean; + secret?: boolean; + images?: {current?: string; value?: string}; + chip?: {icon?: string; image?: string}; + change?: boolean; + was?: string; + long?: boolean; +} + +export interface AiDetailCommand { + label: string; + text: string; +} + +export interface AiDetailLink { + title: string; + url: string; + from: string; + snippet?: string; +} + +export type AiDetailBlock = + | {type: 'records'; label?: AiDetailText; rows: AiDetailRecord[]; total?: number} + | {type: 'hub'; rows: AiDetailHubItem[]} + | {type: 'values'; label?: AiDetailText; entity?: AiDetailEntity; rows: AiDetailValue[]} + | {type: 'series'; entity?: AiDetailEntity; rows: AiDetailSeries[]} + | {type: 'keys'; label?: AiDetailText; keys: string[]} + | {type: 'facts'; rows: AiDetailFact[]} + | {type: 'list'; label?: AiDetailText; rows: Array} + | {type: 'commands'; rows: AiDetailCommand[]} + | {type: 'links'; rows: AiDetailLink[]} + | {type: 'markdown'; text: string} + | {type: 'code'; label: string; text: string; lang?: string; title?: string} + | {type: 'note'; text: AiDetailText} + | {type: 'found'; text: AiDetailText} + | {type: 'text'; text: string} + | {type: 'json'; label: string; text: string} + | {type: 'images'; rows: AiDetailImage[]} + | {type: 'warning'; label?: AiDetailText; rows: Array}; + +export interface AiDetailImage { + label?: AiDetailText; + url: string; +} + +export interface AiDetailView { + hood?: AiDetailText; + blocks: AiDetailBlock[]; +} + +export type AiDetailNames = ReadonlyMap; + +export interface AiStepView { + askedFor?: AiDetailText; + blocks: AiDetailBlock[]; + under: AiDetailBlock[]; +} + +const ASKED_FOR: Record = { + 'search-named': 'named', 'search-typed': 'typed', 'search-text': 'text', 'search-related-from': 'related-from', + 'search-related-to': 'related-to', 'read-attributes-scope': 'attributes-scope', + 'search-alarms': 'alarms', 'search-alarms-on': 'alarms-on', 'search-alarms-filter-on': 'alarms-filter-on', 'search-alarms-window': 'alarms-window', + 'search-alarms-filter-window': 'alarms-filter-window', 'search-alarms-on-window': 'alarms-on-window', 'search-alarms-filter-on-window': 'alarms-filter-on-window', + 'read-history': 'history', 'read-history-keys': 'history-keys', 'read-latest-keys': 'latest-keys', 'iot-hub-query': 'query', + 'search-web': 'query', 'read-widget-parts': 'widget' +}; + +export function aiStepView(action: AiAction, names: AiDetailNames): AiStepView { + const view = aiActionDetailView(action, names); + const hood = view.hood?.key.slice(K.length); + const asked = hood ? ASKED_FOR[hood] : undefined; + const askedFor = asked ? {key: K + 'asked.' + asked, params: view.hood.params} : undefined; + const under: AiDetailBlock[] = []; + const blocks: AiDetailBlock[] = []; + for (const block of view.blocks) { + if (block.type === 'list' && block.label?.key === K + 'widget-warnings') { + under.push({type: 'warning', label: block.label, rows: block.rows}); + } else { + blocks.push(block); + } + } + return {askedFor, blocks, under}; +} + +const K = 'ai-assistant.detail.'; + +const ALARM_FILTER_WORDS = new Set(['ACTIVE', 'CLEARED', 'ACK', 'UNACK', 'CRITICAL', 'MAJOR', 'MINOR', 'WARNING', 'INDETERMINATE']); + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +const OK_ID = /^OK:\s*([0-9a-z_-]+)/i; + +const MAX_ROWS = 20; + +const SCOPES: Record = { + SERVER_SCOPE: 'server', + SHARED_SCOPE: 'shared', + CLIENT_SCOPE: 'client' +}; + +const SEARCHED: Record = { + DEVICE: 'devices', + ASSET: 'assets', + ENTITY_VIEW: 'entity-views', + EDGE: 'edges', + CUSTOMER: 'customers', + USER: 'users', + DASHBOARD: 'dashboards', + TENANT: 'tenants', + DEVICE_PROFILE: 'device-profiles', + ASSET_PROFILE: 'asset-profiles', + ENTITY_GROUP: 'groups' +}; + +const FILTER_TYPES: Record = { + deviceType: 'DEVICE', + assetType: 'ASSET', + entityViewType: 'ENTITY_VIEW', + edgeType: 'EDGE', + gateway: 'DEVICE', + alarm: 'ALARM', + alarmRule: 'ALARM_RULE', + calculatedField: 'CALCULATED_FIELD', + notificationTarget: 'NOTIFICATION_TARGET', + notificationTemplate: 'NOTIFICATION_TEMPLATE', + notificationRule: 'NOTIFICATION_RULE', + image: 'IMAGE', + entityGroupName: 'ENTITY_GROUP' +}; + +const FILTER_WORDS: Record = { + gateway: 'gateways', + alarm: 'alarms', + alarmRule: 'alarm-rules', + calculatedField: 'calculated-fields', + notificationTarget: 'notification-targets', + notificationTemplate: 'notification-templates', + notificationRule: 'notification-rules', + image: 'images' +}; + +const DELETE_TYPES: Record = { + DASHBOARD_WIDGET: 'DASHBOARD_WIDGET', + DASHBOARD_STATE: 'DASHBOARD_STATE', + DASHBOARD_ENTITY_ALIAS: 'DASHBOARD_ENTITY_ALIAS', + DASHBOARD_FILTER: 'DASHBOARD_FILTER' +}; + +type Values = Record; + +export function aiParse(value: unknown): unknown { + if (typeof value !== 'string') { + return value ?? undefined; + } + const text = value.trim(); + if (!text.startsWith('{') && !text.startsWith('[')) { + return value; + } + try { + return JSON.parse(text); + } catch { + return value; + } +} + +const isObject = (value: unknown): value is Values => !!value && typeof value === 'object' && !Array.isArray(value); + +const str = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined; + +const idOf = (value: unknown): string | undefined => typeof value === 'string' ? value : isObject(value) ? str(value.id) : undefined; + +const okId = (result: unknown): string | undefined => typeof result === 'string' ? OK_ID.exec(result.trim())?.[1] : undefined; + + +export function aiValueText(value: unknown): string { + if (value === null || value === undefined) { + return '—'; + } + if (typeof value === 'number') { + return aiTrueMinus(Number.isInteger(value) ? String(value) : String(Math.round(value * 1000) / 1000)); + } + if (typeof value === 'string') { + const parsed = aiParse(value); + return parsed !== value ? aiValueText(parsed) : aiTrueMinus(value.length > 120 ? value.slice(0, 120) + '…' : value); + } + if (typeof value === 'boolean') { + return String(value); + } + const json = JSON.stringify(value); + return json.length > 120 ? json.slice(0, 120) + '…' : json; +} + +const ACRONYMS: ReadonlySet = new Set(['fqn', 'id', 'url', 'uri', 'ip', 'api', 'mqtt', 'mqtts', 'http', 'https', 'coap', 'coaps', + 'lwm2m', 'snmp', 'ota', 'json', 'tls', 'ssl', 'rpc', 'tbel', 'js', 'ttn', 'tti', 'sms', 'eui', 'oid', 'qos', 'cf']); + +export const aiHumanize = (key: string): string => { + const words = key.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim().toLowerCase(); + if (!words) { + return key; + } + const cased = words.split(' ').map(word => ACRONYMS.has(word) ? word.toUpperCase() : word).join(' '); + return cased.charAt(0).toUpperCase() + cased.slice(1); +}; + +function entity(id: unknown, entityType: unknown, names: AiDetailNames): AiDetailEntity { + const key = idOf(id); + const type = str(entityType) ?? (isObject(id) ? str(id.entityType) : undefined); + const known = key ? names.get(key) : undefined; + return {id: key, entityType: type ?? known?.entityType, name: known?.name}; +} + +function galleryImage(value: unknown): string | undefined { + const url = str(value); + return url && /^(tb-image;)?\/api\/images\//.test(url) ? url : undefined; +} + +function images(rows: {label?: AiDetailText; value: unknown}[]): AiDetailBlock[] { + const found: AiDetailImage[] = rows.map(row => ({label: row.label, url: galleryImage(row.value)})).filter(row => !!row.url); + return found.length ? [{type: 'images', rows: found}] : []; +} + +function text(key: string, params?: Record): AiDetailText { + return {key: K + key, params}; +} + +function scadaSymbolPicture(values: Values): AiDetailBlock[] { + const link = str(values.link); + return link && link.startsWith('tb-image;') ? [{type: 'images', rows: [{url: link}]}] : []; +} + +function scadaSymbolOverviewBlocks(overview: Values): AiDetailBlock[] { + const rows = facts(overview, ['link', 'note', 'tags', 'behavior', 'properties', 'problems', 'searchTags', 'description']); + const behaviors = Array.isArray(overview.behavior) + ? overview.behavior.filter(isObject).map(item => [item.name || item.id, item.default].filter(Boolean).join(' — ')) : []; + const problems = Array.isArray(overview.problems) ? overview.problems.map(item => String(item)) : []; + return [...scadaSymbolPicture(overview), ...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...(behaviors.length ? [{type: 'list' as const, label: text('scada-symbol-behaviors'), rows: behaviors.slice(0, MAX_ROWS)}] : []), + ...(problems.length ? [{type: 'list' as const, label: text('scada-symbol-problems'), rows: problems.slice(0, MAX_ROWS)}] : [])]; +} + +const CODE_KEYS = new Set(['script', 'decoder', 'encoder', 'tbelDecoder', 'tbelEncoder', 'jsDecoder', 'jsEncoder']); + +const CONVERTER_ICONS: Record = {UPLINK: 'call_received', DOWNLINK: 'call_made'}; + +function converterTypeFact(type: unknown, label = K + 'fact.type'): AiDetailFact[] { + const key = converterTypeTranslationMap.get(type as ConverterType); + return key ? [{label, value: key, chip: {icon: CONVERTER_ICONS[type as string]}}] : []; +} + +function integrationTypeFact(type: unknown): AiDetailFact[] { + const info = integrationTypeInfoMap.get(type as IntegrationType); + return info ? [{label: K + 'fact.integration-type', value: info.name, chip: {image: info.icon}}] : []; +} + +function typedFact(key: string, value: unknown): AiDetailFact[] { + if (key === 'integrationType') { + return integrationTypeFact(value); + } + if (key === 'type' || key === 'converterType') { + return converterTypeFact(value); + } + return []; +} + +function codeBlocks(values: Values): AiDetailBlock[] { + return Object.entries(values).filter(([key, value]) => CODE_KEYS.has(key) && str(value)) + .map(([, value]) => ({type: 'code', title: 'script', label: 'TBEL', lang: 'tbel', text: (value as string).replace(/\n+$/, '')})); +} + +function messageBlock(label: string, value: unknown): AiDetailBlock[] { + if (isObject(value) || Array.isArray(value)) { + return [{type: 'json', label, text: JSON.stringify(value, null, 2)}]; + } + const text = str(value); + if (!text) { + return []; + } + const parsed = /^[[{]/.test(text) ? aiParse(text) : undefined; + return isObject(parsed) || Array.isArray(parsed) ? [{type: 'json', label, text: JSON.stringify(parsed, null, 2)}] : [{type: 'json', label, text}]; +} + +function converterBlocks(values: Values, result: unknown): AiDetailBlock[] { + const rows = [...converterTypeFact(values.type), ...integrationTypeFact(values.integrationType), + ...facts(values, ['type', 'integrationType', 'payload', 'metadata', 'integrationMetadata', ...CODE_KEYS])]; + const outcome = isObject(result) ? result : {}; + return [ + ...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...codeBlocks(values), + ...messageBlock('payload', values.payload), + ...messageBlock('metadata', values.metadata), + ...messageBlock('error', outcome.error), + ...messageBlock('output', outcome.output), + ...messageBlock('result', outcome.result) + ]; +} + +function facts(values: Values, skip: string[] = [], names?: AiDetailNames): AiDetailFact[] { + const rows: AiDetailFact[] = []; + for (const [key, value] of Object.entries(values)) { + if (skip.includes(key) || value === null || value === undefined || value === '') { + continue; + } + const typed = typedFact(key, value); + if (typed.length) { + rows.push(...typed); + continue; + } + if (names && /Id$/.test(key) && (typeof value === 'string' || isObject(value)) && idOf(value)) { + const ref = entity(value, isObject(value) ? value.entityType : undefined, names); + rows.push(ref.name ? {label: aiHumanize(key.replace(/Id$/, '')), raw: true, entity: ref} : {label: aiHumanize(key), raw: true, value: idOf(value), mono: true}); + continue; + } + if (Array.isArray(value) && value.every(item => typeof item !== 'object')) { + rows.push({label: aiHumanize(key), raw: true, value: value.map(aiValueText).join(', ')}); + } else if (typeof value === 'object') { + rows.push({label: aiHumanize(key), raw: true, value: aiValueText(value), mono: true}); + } else { + rows.push({label: aiHumanize(key), raw: true, value: aiValueText(value)}); + } + } + return rows; +} + +function flat(value: unknown, depth = 0): boolean { + if (!isObject(value)) { + return false; + } + return Object.values(value).every(item => item === null || typeof item !== 'object' + || (depth < 1 && (isObject(item) ? flat(item, depth + 1) : (item as unknown[]).every(entry => typeof entry !== 'object')))); +} + +function json(label: string, value: unknown): AiDetailBlock[] { + if (value === undefined || value === null || value === '') { + return []; + } + if (typeof value === 'string') { + return [{type: 'text', text: value}]; + } + return [{type: 'json', label, text: JSON.stringify(value, null, 2)}]; +} + +function generic(value: unknown, label: string, skip: string[] = [], names?: AiDetailNames): AiDetailBlock[] { + if (typeof value === 'string') { + const trimmed = value.trim().replace(/^OK:\s*/i, ''); + return !trimmed || /^OK\.?$/i.test(trimmed) || UUID.test(trimmed) ? [] : [{type: 'text', text: trimmed}]; + } + if (isObject(value) && Object.keys(value).length <= 16 && flat(value)) { + const rows = facts(value, skip, names); + return rows.length ? [{type: 'facts', rows}] : []; + } + return json(label, value); +} + +function timeOf(ts: unknown): number | undefined { + const value = typeof ts === 'string' ? Number(ts) : ts; + return typeof value === 'number' && Number.isFinite(value) && value > 1e11 ? value : undefined; +} + +function sparkPath(values: number[], times: number[]): {path: string; dot: number} { + const width = 300; + const height = 60; + const pad = 6; + const from = times[0]; + const span = times[times.length - 1] - from || 1; + const min = Math.min(...values); + const range = Math.max(...values) - min || 1; + const y = (value: number) => height - pad - (value - min) / range * (height - 2 * pad); + const path = values.map((value, index) => + `${index ? 'L' : 'M'}${((times[index] - from) / span * width).toFixed(1)} ${y(value).toFixed(1)}`).join(''); + return {path, dot: Math.round(y(values[values.length - 1]) / height * 100)}; +} + +function series(key: string, points: Array<[number, number]>): AiDetailSeries { + const sorted = [...points].sort((a, b) => a[0] - b[0]); + const values = sorted.map(point => point[1]); + const times = sorted.map(point => point[0]); + return {key, points: sorted.length, min: Math.min(...values), max: Math.max(...values), last: values[values.length - 1], + from: times[0], to: times[times.length - 1], ...sparkPath(values, times)}; +} + +function changesSeries(key: string, points: Array<[number, unknown]>): AiDetailSeries { + const sorted = [...points].sort((a, b) => a[0] - b[0]); + const words = sorted.map(point => aiValueText(point[1])); + const levels = [...new Set(words)]; + const changes = words.filter((word, index) => index && word !== words[index - 1]).length; + const times = sorted.map(point => point[0]); + return {key, points: sorted.length, lastText: words[words.length - 1], changes, from: times[0], to: times[times.length - 1], + ...sparkPath(words.map(word => levels.indexOf(word)), times)}; +} + +function telemetry(result: Values, entityOf?: (id: string) => AiDetailEntity): AiDetailBlock[] { + const ids = Object.keys(result); + if (entityOf && ids.length && ids.every(id => UUID.test(id) && isObject(result[id]))) { + return ids.flatMap(id => telemetry(result[id] as Values).map(block => + block.type === 'values' || block.type === 'series' ? {...block, entity: entityOf(id)} : block)); + } + const latest: AiDetailValue[] = []; + const history: AiDetailSeries[] = []; + const other: AiDetailValue[] = []; + const add = (key: string, points: Array<[number, unknown]>) => { + const numbers = points.map(([ts, value]) => [ts, typeof value === 'boolean' ? NaN : Number(value)] as [number, number]); + if (points.length > 1 && numbers.every(([, value]) => Number.isFinite(value))) { + history.push(series(key, numbers)); + } else if (points.length > 1) { + history.push(changesSeries(key, points)); + } else if (points.length) { + latest.push({key, value: aiValueText(points[0][1]), time: points[0][0]}); + } + }; + for (const [key, data] of Object.entries(result)) { + if (isObject(data) && 'value' in data) { + latest.push({key, value: aiValueText(data.value), time: timeOf(data.ts)}); + continue; + } + if (Array.isArray(data) && data.every(point => isObject(point) && 'ts' in point)) { + add(key, data.map(point => [timeOf(point.ts), point.value] as [number, unknown]).filter(([ts]) => !!ts)); + continue; + } + if (!isObject(data)) { + other.push({key, value: aiValueText(data)}); + continue; + } + const entries = Object.entries(data).filter(([ts]) => timeOf(ts)); + if (entries.length) { + add(key, entries.map(([ts, value]) => [timeOf(ts), value] as [number, unknown])); + } else { + other.push({key, value: aiValueText(data)}); + } + } + const blocks: AiDetailBlock[] = []; + if (history.length) { + blocks.push({type: 'series', rows: history}); + } + if (latest.length || other.length) { + blocks.push({type: 'values', rows: [...latest, ...other]}); + } + return blocks; +} + +function searchSections(result: unknown): Array<{entityType?: string; page: Values}> { + if (isObject(result)) { + return [{page: result}]; + } + if (typeof result !== 'string') { + return []; + } + const sections: Array<{entityType?: string; page: Values}> = []; + const pattern = /(?:^|\n\n)([A-Z_]+) entities[^\n]*:\n(\{[\s\S]*?\})(?=\n\n[A-Z_]+ entities|$)/g; + let match: RegExpExecArray | null; + while ((match = pattern.exec(result)) !== null) { + const page = aiParse(match[2]); + if (isObject(page)) { + sections.push({entityType: match[1], page}); + } + } + return sections; +} + +function searchType(values: Values): string | undefined { + const filter = isObject(values.entityFilter) ? values.entityFilter : {}; + return FILTER_TYPES[values.filterType] ?? str(filter.entityType) ?? str(filter.singleEntity?.entityType) ?? str(filter.groupType && 'ENTITY_GROUP'); +} + + +function recordOf(row: Values, entityType: string): AiDetailRecord | null { + if (entityType === 'ALARM') { + const alarmName = str(row.type) ?? str(row.name); + return alarmName ? {entityType, id: idOf(row.id), name: alarmName, severity: str(row.severity)?.toUpperCase(), status: str(row.status)?.toUpperCase(), + since: timeOf(row.startTs) ? dateText(timeOf(row.startTs)) : undefined} : null; + } + const name = str(row.name) ?? str(row.title) ?? str(row.email) ?? str(row.label); + if (!name) { + return null; + } + const meta = [row.label && row.label !== name ? row.label : undefined, entityType === 'ALARM_RULE' ? undefined : row.type, row.email && row.email !== name ? row.email : undefined] + .filter(value => typeof value === 'string' && value.trim()).join(' · '); + return {entityType: entityType === 'ALARM_RULE' ? 'ALARM_RULE' : entityType, id: idOf(row.id), name, meta: meta || undefined}; +} + +function withoutCommonMeta(rows: AiDetailRecord[]): AiDetailRecord[] { + if (rows.length < 2) { + return rows; + } + const counts = new Map(); + rows.forEach(row => row.meta && counts.set(row.meta, (counts.get(row.meta) ?? 0) + 1)); + const common = [...counts].find(([, count]) => count > rows.length / 2)?.[0]; + return common ? rows.map(row => row.meta === common ? {...row, meta: undefined} : row) : rows; +} + +function searchEntities(values: Values, result: unknown, names: AiDetailNames): AiDetailView { + const filter = isObject(values.entityFilter) ? values.entityFilter : {}; + const type = searchType(values); + const what = FILTER_WORDS[values.filterType] ?? (type && SEARCHED[type]) ?? (values.filterType === 'entityType' && !filter.entityType ? 'devices-assets' : 'entities'); + const params: Record = {what: K + 'what.' + what}; + let key = 'search'; + if (values.filterType === 'singleEntity' && filter.singleEntity) { + key = 'search-one'; + params.entity = entity(filter.singleEntity.id, filter.singleEntity.entityType, names); + } else if (values.filterType === 'relationsQuery' && filter.rootEntity) { + key = filter.direction === 'TO' ? 'search-related-to' : 'search-related-from'; + params.entity = entity(filter.rootEntity.id, filter.rootEntity.entityType, names); + } else if (str(filter.nameFilter)) { + key = 'search-named'; + params.name = filter.nameFilter.replace(/%/g, ''); + } else if (Array.isArray(filter.types) && filter.types.length) { + key = 'search-typed'; + params.types = filter.types.join(', '); + } else if (str(values.pageLink?.textSearch)) { + key = 'search-text'; + params.text = values.pageLink.textSearch; + } else if (values.filterType === 'alarm') { + const words = [...(Array.isArray(filter.severityList) ? filter.severityList : []), ...(Array.isArray(filter.statusList) ? filter.statusList : [])] + .map(word => str(word)?.toUpperCase()).filter(word => !!word && ALARM_FILTER_WORDS.has(word)).map(word => K + 'alarm-filter.' + word); + const one = Array.isArray(filter.originatorIds) && filter.originatorIds.length === 1; + const window = timeOf(filter.startTs) ? `${dateText(timeOf(filter.startTs))} – ${endText(filter.endTs)}` : undefined; + const parts = [words.length ? 'filter' : '', one ? 'on' : '', window ? 'window' : ''].filter(Boolean); + if (parts.length) { + key = parts.length === 1 && parts[0] === 'filter' ? 'search-alarms' : 'search-alarms-' + parts.join('-'); + params.filter = {words, commas: true}; + params.entity = one ? entity(filter.originatorIds[0], filter.originatorType, names) : ''; + params.window = window ?? ''; + } + } + const sections = searchSections(result); + if (!sections.length) { + return {hood: text(key, params), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + for (const section of sections) { + const entityType = section.entityType ?? type ?? 'DEVICE'; + const data: unknown[] = Array.isArray(section.page.data) ? section.page.data : []; + if (!data.length) { + if (sections.length === 1) { + blocks.push({type: 'found', text: text(entityType === 'ALARM' ? 'no-alarms' : 'nothing-found')}); + } + continue; + } + const groupType = entityType === 'ENTITY_GROUP' ? str(filter.groupType)?.toUpperCase() : undefined; + const rows = withoutCommonMeta(data.filter(isObject).map(row => recordOf(row, entityType)).filter(Boolean).slice(0, MAX_ROWS) + .map(row => groupType ? {...row, groupType} : row)); + const total = typeof section.page.totalElements === 'number' ? section.page.totalElements : data.length; + blocks.push(rows.length + ? {type: 'records', label: sections.length > 1 ? text('what-found.' + (SEARCHED[entityType] ?? 'entities')) : undefined, rows, total} + : {type: 'json', label: 'result', text: JSON.stringify(data, null, 2)}); + } + return {hood: text(key, params), blocks}; +} + +function relations(result: unknown): AiDetailBlock[] { + if (!isObject(result)) { + return generic(result, 'result'); + } + const blocks: AiDetailBlock[] = []; + for (const direction of ['from', 'to']) { + const byType = result[direction]; + if (!isObject(byType)) { + continue; + } + for (const [relationType, group] of Object.entries(byType)) { + const related: unknown[] = Array.isArray(group?.relatedEntities) ? group.relatedEntities : []; + const rows = related.filter(isObject).map(item => ({ + entityType: str(item.entityType) ?? 'DEVICE', + id: idOf(item.entityId ?? item.id), + name: str(item.name) ?? idOf(item.entityId ?? item.id) ?? '—' + })); + if (rows.length) { + blocks.push({type: 'records', label: text('relation-' + direction, {type: relationType}), rows}); + } + } + } + return blocks.length ? blocks : generic(result, 'result'); +} + +function attributes(result: unknown, label: 'values' | 'keys'): AiDetailBlock[] { + if (!isObject(result)) { + return generic(result, 'result'); + } + const blocks: AiDetailBlock[] = []; + for (const [scope, data] of Object.entries(result)) { + const scopeLabel = text('scope.' + (SCOPES[scope] ?? 'other')); + if (Array.isArray(data) && data.length) { + blocks.push({type: 'keys', label: scopeLabel, keys: data.map(String)}); + } else if (isObject(data) && Object.keys(data).length) { + blocks.push({ + type: 'values', label: scopeLabel, rows: Object.entries(data).map(([key, item]) => isObject(item) && 'value' in item + ? {key, value: aiValueText(item.value), time: timeOf(item.ts)} : {key, value: aiValueText(item)}) + }); + } + } + return blocks.length ? blocks : [{type: 'note', text: text(label === 'keys' ? 'no-attribute-keys' : 'no-attributes')}]; +} + +const PROTOCOLS: Record = { + coap: 'CoAP', + coaps: 'CoAPS', + lwm2m: 'LwM2M', + docker: 'Docker', + windows: 'Windows', + linux: 'Linux', + macos: 'macOS' +}; + +function commands(value: unknown, prefix: string[] = [], rows: AiDetailCommand[] = []): AiDetailCommand[] { + if (typeof value === 'string') { + rows.push({label: prefix.map(part => PROTOCOLS[part.toLowerCase()] ?? (part.length <= 5 ? part.toUpperCase() : aiHumanize(part))) + .filter((part, index, all) => all.indexOf(part) === index).join(' · '), text: value}); + } else if (isObject(value)) { + Object.entries(value).forEach(([key, item]) => commands(item, [...prefix, key], rows)); + } + return rows; +} + +function webResults(result: unknown): AiDetailBlock[] { + if (typeof result !== 'string' || !/^1\. /.test(result.trim())) { + return generic(result, 'result'); + } + const rows: AiDetailLink[] = []; + for (const chunk of result.trim().split(/\n\n(?=\d+\. )/)) { + const [head, url, ...rest] = chunk.split('\n'); + const title = head?.replace(/^\d+\.\s*/, '').trim(); + if (!title || !/^https?:\/\//.test(url ?? '')) { + continue; + } + let from = url; + try { + from = new URL(url).hostname.replace(/^www\./, ''); + } catch { + } + rows.push({title, url: url.trim(), from, snippet: rest.join(' ').trim() || undefined}); + } + return rows.length ? [{type: 'links', rows}] : generic(result, 'result'); +} + +function aliasFilter(filter: unknown, names: AiDetailNames): AiDetailFact[] { + if (!isObject(filter)) { + return []; + } + const rows: AiDetailFact[] = [{label: K + 'fact.resolves', value: aiHumanize(String(filter.type ?? ''))}]; + if (Array.isArray(filter.entityList)) { + const list = filter.entityList.map((id: unknown) => names.get(String(id))?.name ?? String(id)); + rows.push({label: K + 'fact.entities', value: list.join(', ')}); + } + for (const key of ['deviceTypes', 'assetTypes', 'entityViewTypes', 'deviceType', 'assetType', 'entityType', 'entityNameFilter', 'relationType', 'direction']) { + if (filter[key] !== undefined && filter[key] !== '') { + rows.push({label: aiHumanize(key), raw: true, value: Array.isArray(filter[key]) ? filter[key].join(', ') : aiValueText(filter[key])}); + } + } + const single = filter.singleEntity ?? filter.defaultStateEntity ?? filter.rootEntity; + if (isObject(single)) { + rows.push({label: K + 'fact.entity', entity: entity(single.id, single.entityType, names)}); + } + rows.push({label: K + 'fact.multiple', value: filter.resolveMultiple ? K + 'yes' : K + 'no'}); + return rows; +} + +function reportTemplateOverview(result: Values): AiDetailBlock[] { + const blocks: AiDetailBlock[] = []; + const settings = isObject(result.settings) ? result.settings : {}; + const page = isObject(settings.page) ? settings.page : null; + const rows: AiDetailFact[] = [{label: K + 'fact.format', value: [str(result.format), result.templateType === 'SUB_REPORT' ? text('sub-report') : null].filter(Boolean).join(' · ')}]; + if (page) { + rows.push({label: K + 'fact.page', value: [page.size, aiHumanize(String(page.orientation ?? ''))].filter(Boolean).join(' · ')}); + } + if (str(settings.fileName)) { + rows.push({label: K + 'fact.file-name', value: settings.fileName, mono: true}); + } + const sections = ['header', 'footer'].filter(section => isObject(settings[section]) && settings[section].enabled); + if (page) { + rows.push({label: K + 'fact.header-footer', value: sections.length ? sections.map(section => aiHumanize(section)).join(', ') : '—'}); + } + blocks.push({type: 'facts', rows}); + const components = isObject(result.components) ? Object.entries(result.components) : []; + blocks.push({ + type: 'list', label: text('report-components'), + rows: components.length ? components.slice(0, MAX_ROWS).map(([path, line]) => { + const item = isObject(line) ? line : {}; + return [path, aiHumanize(String(item.type ?? '')), str(item.is), str(item.alias)].filter(Boolean).join(' · '); + }) : ['—'] + }); + const aliases = (Array.isArray(result.entityAliases) ? result.entityAliases : []).filter(isObject); + if (aliases.length) { + blocks.push({type: 'list', label: text('aliases'), rows: aliases.map(alias => [str(alias.name) ?? alias.id, alias.filter?.type ? aiHumanize(alias.filter.type) : null].filter(Boolean).join(' · '))}); + } + const filters = (Array.isArray(result.filters) ? result.filters : []).filter(isObject); + if (filters.length) { + blocks.push({type: 'list', label: text('filters'), rows: filters.map(item => String(item.name ?? item.id))}); + } + const problems = (Array.isArray(result.problems) ? result.problems : []).map(String); + if (problems.length) { + blocks.push({type: 'list', label: text('report-problems'), rows: problems}); + } + return blocks; +} + +function reportComponentFacts(component: Values): AiDetailFact[] { + const rows: AiDetailFact[] = [{label: K + 'fact.component', value: aiHumanize(String(component.type ?? ''))}]; + rows.push({label: K + 'fact.path', value: String(component.path ?? '—'), mono: true}); + const config = isObject(component.config) ? component.config : {}; + const title = str(config.title) ?? str(config.text); + if (title) { + rows.push({label: K + 'fact.title', value: title}); + } + if (str(component.entityAlias) || str(component.entityAliasId)) { + rows.push(str(component.entityAlias) ? {label: K + 'fact.alias', value: component.entityAlias} + : {label: K + 'fact.alias', value: component.entityAliasId, mono: true}); + } + const entries = [config.keys, config.columns, config.series, config.latestColumns].filter(Array.isArray).flat(); + const keys = entries.map((item: any) => typeof item === 'string' ? item : item?.key).filter(Boolean); + if (str(config.key)) { + keys.push(config.key); + } + if (keys.length) { + rows.push({label: K + 'fact.keys', value: [...new Set(keys)].join(', '), mono: true}); + } + const history = isObject(config.timewindow) && isObject(config.timewindow.history) ? config.timewindow.history : null; + if (history) { + const window = history.interval ?? history.last ?? (isObject(history.range) ? `${history.range.from} – ${history.range.to}` : null); + const aggregation = isObject(config.timewindow.aggregation) && config.timewindow.aggregation.type && config.timewindow.aggregation.type !== 'NONE' + ? `${config.timewindow.aggregation.type}${config.timewindow.aggregation.grouping ? ' per ' + config.timewindow.aggregation.grouping : ''}` : null; + rows.push({label: K + 'fact.time-window', value: [window ? aiHumanize(String(window)) : null, aggregation].filter(Boolean).join(' · ')}); + } + if (typeof config.height === 'number') { + rows.push({label: K + 'fact.height', value: `${config.height} px`}); + } + return rows; +} + +function widgetFacts(widget: Values, names: AiDetailNames): AiDetailFact[] { + const rows: AiDetailFact[] = []; + if (str(widget.title)) { + rows.push({label: K + 'fact.title', value: widget.title}); + } + if (str(widget.widgetType)) { + rows.push({label: K + 'fact.widget-type', value: aiHumanize(widget.widgetType)}); + } + if (str(widget.stateId)) { + rows.push({label: K + 'fact.state', value: widget.stateId, mono: true}); + } + if (str(widget.entityAliasId)) { + const alias = names.get(widget.entityAliasId)?.name; + rows.push(alias ? {label: K + 'fact.alias', value: alias} : {label: K + 'fact.alias', value: widget.entityAliasId, mono: true}); + } + const config = isObject(widget.widgetConfig) ? widget.widgetConfig : {}; + const keys = (Array.isArray(config.keys) ? config.keys : []).map((item: any) => typeof item === 'string' ? item : item?.key).filter(Boolean); + ['latitudeKey', 'longitudeKey', 'valueKey', 'key'].forEach(field => str(config[field]) && keys.push(config[field])); + if (keys.length) { + rows.push({label: K + 'fact.keys', value: [...new Set(keys)].join(', '), mono: true}); + } + if (widget.sizeX && widget.sizeY) { + rows.push({label: K + 'fact.size', say: widget.col !== undefined + ? text('widget-size-at', {width: widget.sizeX, height: widget.sizeY, col: widget.col, row: widget.row ?? 0}) + : text('widget-size', {width: widget.sizeX, height: widget.sizeY})}); + } + return rows; +} + +function widgetRecords(widgets: unknown, result: unknown): AiDetailRecord[] { + const ids = typeof result === 'string' ? [...result.matchAll(/widgets\[(\d+)\][^:]*:\s*([0-9a-f-]{36})/g)] : []; + return (Array.isArray(widgets) ? widgets : []).filter(isObject).map((widget, index) => ({ + entityType: 'DASHBOARD_WIDGET', + id: ids.find(match => Number(match[1]) === index)?.[2], + name: str(widget.title) ?? aiHumanize(String(widget.widgetType ?? 'widget')), + meta: [widget.widgetType ? aiHumanize(widget.widgetType) : undefined, widget.stateId, + widget.sizeX && widget.sizeY ? `${widget.sizeX} × ${widget.sizeY}` : undefined].filter(Boolean).join(' · ') + })); +} + +function dashboardOverview(result: unknown, names: AiDetailNames): AiDetailBlock[] { + if (!isObject(result) || !Array.isArray(result.states)) { + return generic(result, 'result'); + } + const blocks: AiDetailBlock[] = []; + const rows: AiDetailFact[] = []; + if (str(result.theme)) { + rows.push({label: K + 'fact.theme', value: aiHumanize(result.theme)}); + } + const window = result.timewindow?.realtime?.last ?? result.timewindow?.realtime?.timewindowMs; + if (window) { + rows.push({label: K + 'fact.time-window', value: String(window)}); + } + if (rows.length) { + blocks.push({type: 'facts', rows}); + } + blocks.push({ + type: 'list', label: text('states'), rows: result.states.filter(isObject).map(state => { + const widgets = Array.isArray(state.widgets) ? state.widgets.length : 0; + return [str(state.name) ?? state.id, state.root ? '★' : '', `${widgets} widget${widgets === 1 ? '' : 's'}`, state.layout].filter(Boolean).join(' · '); + }) + }); + const aliases = (Array.isArray(result.aliases) ? result.aliases : []).filter(isObject); + if (aliases.length) { + blocks.push({type: 'list', label: text('aliases'), rows: aliases.map(alias => [alias.alias ?? alias.name ?? alias.id, alias.filter?.type ? aiHumanize(alias.filter.type) : alias.type].filter(Boolean).join(' · '))}); + } + const filters = (Array.isArray(result.filters) ? result.filters : []).filter(isObject); + if (filters.length) { + blocks.push({type: 'list', label: text('filters'), rows: filters.map(item => String(item.filter ?? item.name ?? item.id))}); + } + return blocks; +} + +function partialString(source: string, key: string): string | undefined { + const start = source.indexOf(`"${key}":"`); + if (start < 0) { + return undefined; + } + let body = source.slice(start + key.length + 4); + const end = /(?:^|[^\\])(?:\\\\)*"/.exec(body); + body = end ? body.slice(0, end.index + end[0].length - 1) : body.replace(/…$/, '').replace(/\\(u[0-9a-fA-F]{0,3})?$/, ''); + try { + return JSON.parse(`"${body}"`); + } catch { + return undefined; + } +} + +function htmlPage(result: unknown): AiDetailBlock[] { + if (typeof result === 'string' && result.trim().startsWith('{')) { + const html = partialString(result, 'html'); + if (html) { + return [{type: 'code', label: 'HTML', text: html}, {type: 'note', text: text('cut-short')}]; + } + } + const content = isObject(result) ? (isObject(result.content) ? result.content : result) : undefined; + if (!content || (!str(content.html) && !str(content.css) && !str(content.js))) { + return generic(result, 'result'); + } + return (['html', 'css', 'js'] as const).filter(part => str(content[part])).map(part => ({type: 'code', label: part.toUpperCase(), text: content[part]})); +} + +function savedObject(values: Values, nested?: string): Values { + const raw = nested ? values[nested] : values; + const parsed = aiParse(raw); + return isObject(parsed) ? parsed : values; +} + +function savedFacts(saved: Values, names: AiDetailNames): AiDetailFact[] { + const rows: AiDetailFact[] = []; + const config = isObject(aiParse(saved.configuration)) ? aiParse(saved.configuration) as Values : {}; + if (str(config.type)) { + rows.push({label: K + 'fact.type', value: aiHumanize(config.type)}); + } + if (saved.entityId) { + rows.push({label: K + 'fact.on', entity: entity(saved.entityId, saved.entityId?.entityType, names)}); + } + if (isObject(config.arguments) && Object.keys(config.arguments).length) { + rows.push({label: K + 'fact.arguments', value: Object.entries(config.arguments) + .map(([name, arg]: [string, any]) => arg?.refEntityKey?.key && arg.refEntityKey.key !== name ? `${name} = ${arg.refEntityKey.key}` : name).join(', '), mono: true}); + } + if (str(config.expression)) { + rows.push({label: K + 'fact.expression', value: config.expression, mono: true}); + } + if (isObject(config.output) && str(config.output.name)) { + rows.push({label: K + 'fact.output', value: config.output.name, mono: true}); + } + if (isObject(config.createRules)) { + rows.push({label: K + 'fact.severities', value: Object.keys(config.createRules).map(aiHumanize).join(', ')}); + } + if (config.clearRule) { + rows.push({label: K + 'fact.clears', value: K + 'yes'}); + } + for (const key of ['label', 'description', 'notificationType', 'triggerType', 'recipientsConfig', 'templateId']) { + if (saved[key] !== undefined && saved[key] !== null && saved[key] !== '') { + rows.push(...facts({[key]: saved[key]}, [], names)); + } + } + if (!rows.length) { + rows.push(...facts(saved, ['id', 'name', 'title', 'configuration', 'additionalInfo', 'tenantId', 'version', 'createdTime'], names)); + } + return rows; +} + +function changes(values: Values, skip: string[], names: AiDetailNames): AiDetailBlock[] { + const rows: AiDetailFact[] = []; + for (const [key, value] of Object.entries(values)) { + if (skip.includes(key) || value === undefined) { + continue; + } + if (key === 'widgetConfig' && isObject(value)) { + const shown = widgetFacts({widgetConfig: value}, names); + rows.push(...(shown.length ? shown : [{label: K + 'fact.settings', value: Object.keys(value).join(', '), mono: true}])); + } else if (key === 'filter') { + rows.push(...aliasFilter(value, names)); + } else if (key === 'entityAliasId') { + rows.push(...widgetFacts({entityAliasId: value}, names)); + } else { + rows.push(...facts({[key]: value}, [], names)); + } + } + return rows.length ? [{type: 'facts', rows}] : []; +} + +const MODEL_TEXT_FIELDS: ReadonlySet = new Set(['note']); + +function withoutModelText(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(withoutModelText); + } + if (!isObject(value)) { + return value; + } + return Object.fromEntries(Object.entries(value).filter(([key]) => !MODEL_TEXT_FIELDS.has(key)) + .map(([key, item]) => [key, withoutModelText(item)])); +} + +export function aiActionDetailView(action: AiAction, names: AiDetailNames): AiDetailView { + const values: Values = isObject(aiParse(action.arguments)) ? aiParse(action.arguments) as Values : {}; + const result = withoutModelText(aiParse(action.result)); + const failed = action.status === 'FAILURE'; + const view = describe(action.tool, values, result, names); + if (failed) { + const reason = typeof action.result === 'string' ? action.result.trim() : ''; + return {hood: view.hood, blocks: reason.includes('\n') ? [{type: 'text', text: reason}] : []}; + } + return view; +} + +function accessBlocks(report: unknown): AiDetailBlock[] { + if (!isObject(report)) { + return []; + } + const hidden = Array.isArray(report.notVisibleToCustomer) ? report.notVisibleToCustomer.filter(isObject) : []; + const blocks: AiDetailBlock[] = [{type: 'facts', rows: [ + ...(str(report.dashboard) ? [{label: K + 'fact.dashboard', value: report.dashboard}] : []), + {label: K + 'fact.entities-checked', value: String(report.entitiesChecked ?? 0)} + ]}]; + if (hidden.length) { + blocks.push({type: 'records', label: text('not-visible', {count: hidden.length}), rows: hidden.map(item => ({ + entityType: str(item.entityType) ?? 'DEVICE', id: str(item.id), name: str(item.name) ?? '—', + meta: [str(item.owner), ...(Array.isArray(item.groups) ? item.groups.filter(str) : [])].filter(Boolean).join(' · ') || undefined + }))}); + } else { + blocks.push({type: 'note', text: text('all-visible')}); + } + if (Array.isArray(report.aliasesResolvedOnlyOnTheDashboard) && report.aliasesResolvedOnlyOnTheDashboard.length) { + blocks.push({type: 'note', text: text('state-aliases', {aliases: report.aliasesResolvedOnlyOnTheDashboard.filter(str).join(', ')})}); + } + if (str(report.truncated)) { + blocks.push({type: 'note', text: text('access-truncated')}); + } + return blocks; +} + +function grantMeta(grant: Values): string | undefined { + return [str(grant.role), str(grant.appliesTo) ?? [str(grant.userGroup), str(grant.userGroupOwner)].filter(Boolean).join(' · ')] + .filter(Boolean).join(' · ') || undefined; +} + +function groupRows(groups: unknown): AiDetailRecord[] { + return (Array.isArray(groups) ? groups.filter(isObject) : []).map(group => ({ + entityType: 'ENTITY_GROUP', groupType: 'USER', id: str(group.id), name: str(group.name) ?? '—', + meta: (Array.isArray(group.grants) ? group.grants.filter(isObject) : []).map(grantMeta).filter(Boolean).join('; ') || undefined + })); +} + +function readAccess(target: string | undefined, result: unknown): AiDetailBlock[] { + if (!isObject(result)) { + return generic(result, 'result'); + } + const blocks: AiDetailBlock[] = []; + const fact = (key: string, value: unknown) => str(value) ? [{label: K + 'fact.' + key, value: String(value)}] : []; + switch (target) { + case 'USER': + blocks.push({type: 'facts', rows: [...fact('email', result.email), ...fact('owner', result.owner)]}); + blocks.push({type: 'records', label: text('user-groups'), rows: groupRows(result.userGroups)}); + break; + case 'USER_GROUP': + blocks.push({type: 'facts', rows: [...fact('owner', result.owner), ...fact('members', String(result.memberCount ?? ''))]}); + blocks.push({type: 'records', label: text('grants'), rows: (Array.isArray(result.grants) ? result.grants.filter(isObject) : []) + .map(grant => ({entityType: 'ROLE', name: str(grant.role) ?? '—', meta: str(grant.appliesTo)}))}); + blocks.push({type: 'records', label: text('members'), rows: (Array.isArray(result.members) ? result.members.filter(isObject) : []) + .map(member => ({entityType: 'USER', id: str(member.id), name: str(member.email) ?? '—'}))}); + break; + case 'ENTITY_GROUP': + blocks.push({type: 'facts', rows: [...fact('type', result.type), ...fact('owner', result.owner)]}); + blocks.push({type: 'records', label: text('shared-with'), rows: (Array.isArray(result.sharedWith) ? result.sharedWith.filter(isObject) : []) + .map(grant => ({entityType: 'ENTITY_GROUP', name: str(grant.userGroup) ?? '—', meta: [str(grant.userGroupOwner), str(grant.role)].filter(Boolean).join(' · ') || undefined}))}); + break; + case 'CUSTOMER': + blocks.push({type: 'records', label: text('user-groups'), rows: groupRows(result.userGroups)}); + break; + case 'ROLES': + blocks.push({type: 'records', label: text('roles'), rows: (Array.isArray(result.roles) ? result.roles.filter(isObject) : []).map(role => ({ + entityType: 'ROLE', id: str(role.id), name: str(role.name) ?? '—', + meta: [str(role.type), permissionsText(role.permissions)].filter(Boolean).join(' · ') || undefined + }))}); + break; + default: + return generic(result, 'result'); + } + return blocks.filter(block => block.type !== 'records' || block.rows.length); +} + +function permissionsText(permissions: unknown): string | undefined { + if (Array.isArray(permissions)) { + return permissions.filter(str).join(', '); + } + if (isObject(permissions)) { + return Object.entries(permissions).map(([resource, operations]) => + resource + ': ' + (Array.isArray(operations) ? operations.join(', ') : '')).join('; '); + } + return undefined; +} + +function sentNotification(result: unknown): AiDetailBlock[] { + if (!isObject(result) || !str(result.requestId)) { + return generic(result, 'result'); + } + const rows: AiDetailFact[] = []; + if (str(result.status)) { + rows.push({label: K + 'fact.status', value: K + 'notification-status.' + String(result.status).toLowerCase()}); + } + if (str(result.sendsAt)) { + rows.push({label: K + 'fact.sends-at', value: dateText(result.sendsAt)}); + } + if (str(result.usersTargetName)) { + rows.push({label: K + 'fact.recipients', value: result.usersTargetName}); + } + if (isObject(result.sent)) { + rows.push({label: K + 'fact.delivered', + value: Object.entries(result.sent).map(([method, count]) => `${aiHumanize(method)} ${count}`).join(', ')}); + } + if (isObject(result.errors)) { + Object.entries(result.errors).filter(([, byRecipient]) => isObject(byRecipient)).forEach(([method, byRecipient]) => + Object.entries(byRecipient as Record).forEach(([recipient, error]) => + rows.push({label: aiHumanize(method), raw: true, value: `${recipient}: ${aiValueText(error)}`}))); + } + if (str(result.error)) { + rows.push({label: K + 'fact.error', value: result.error}); + } + return rows.length ? [{type: 'facts', rows}] : []; +} + +function createdUser(user: unknown): AiDetailBlock[] { + if (!isObject(user)) { + return []; + } + const activation = isObject(user.activation) ? user.activation : null; + const rows: AiDetailFact[] = []; + if (str(user.email)) { + rows.push({label: K + 'fact.email', value: user.email}); + } + if (Array.isArray(user.userGroups) && user.userGroups.length) { + rows.push({label: K + 'fact.user-groups', value: user.userGroups.filter(str).join(', ')}); + } + if (activation?.emailSent) { + rows.push({label: K + 'fact.activation', value: K + 'activation-email'}); + } else if (str(activation?.link)) { + rows.push({label: K + 'fact.activation-link', value: activation.link, mono: true}); + } + return rows.length ? [{type: 'facts', rows}] : []; +} + +function describe(tool: string, values: Values, result: unknown, names: AiDetailNames): AiDetailView { + const of = (id: unknown, type?: unknown) => entity(id, type, names); + const target = of(values.entityId, values.entityType); + const dashboard = of(values.dashboardId, 'DASHBOARD'); + switch (tool) { + case 'send_notification': + return {blocks: sentNotification(result)}; + case 'check_dashboard_access': + return {hood: text('check-dashboard-access', {dashboard, customer: of(values.customerId, 'CUSTOMER')}), blocks: accessBlocks(result)}; + case 'change_owner': + case 'share_entity_group': { + const outcome = isObject(result) && str(result.result) ? [{type: 'text' as const, text: result.result.replace(/^OK:\s*/i, '')}] : generic(result, 'result'); + const reports = isObject(result) ? (Array.isArray(result.dashboardAccess) ? result.dashboardAccess : result.dashboardAccess ? [result.dashboardAccess] : []) : []; + return {blocks: [...outcome, ...reports.flatMap(accessBlocks)]}; + } + case 'save_entity_group': + case 'grant_role': + case 'update_group_members': + return {blocks: []}; + case 'save_role': { + const permissions = permissionsText(values.permissions); + return {blocks: permissions ? [{type: 'facts', rows: [{label: K + 'fact.permissions', value: permissions}]}] : []}; + } + case 'read_access': + return {blocks: readAccess(str(values.target)?.toUpperCase(), result)}; + case 'save_user': + return {blocks: isObject(result) && str(result.userId) ? createdUser(result) : generic(result, 'result')}; + case 'save_customer': + return {blocks: isObject(result) && str(result.customerId) ? [...createdUser(result.user), + ...(str(result.userError) ? [{type: 'note' as const, text: text('user-error', {reason: result.userError})}] : [])] : generic(result, 'result')}; + case 'search_iot_hub_devices': { + const data = isObject(result) && Array.isArray(result.data) ? result.data.filter(isObject) : null; + const rows: AiDetailHubItem[] = (data ?? []).filter(item => str(item.id)).map(item => ({ + id: item.id, name: str(item.model) ?? str(item.name) ?? item.id, vendor: str(item.vendor), description: str(item.description) + })); + return { + hood: text('iot-hub-query', {query: str(values.query) ?? '*'}), + blocks: data ? (rows.length ? [{type: 'hub', rows}] : [{type: 'note', text: text('nothing-found')}]) : generic(result, 'result') + }; + } + case 'search_iot_hub': + case 'list_installed_iot_hub_items': { + const data = isObject(result) && Array.isArray(result.data) ? result.data.filter(isObject) : null; + const rows: AiDetailHubItem[] = (data ?? []).filter(item => str(item.versionId)).map(item => ({ + id: item.versionId, name: str(item.name) ?? item.versionId, vendor: str(item.creator), description: str(item.description) + })); + const hood = tool === 'search_iot_hub' + ? (str(values.query) ? text('iot-hub-query', {query: str(values.query)}) : text('iot-hub-browse')) + : text('iot-hub-installed'); + return {hood, blocks: data ? (rows.length ? [{type: 'hub', rows}] : [{type: 'note', text: text('nothing-found')}]) : generic(result, 'result')}; + } + case 'read_iot_hub_item': { + const item = isObject(result) && str(result.versionId) ? result : null; + return { + hood: text('iot-hub-read', {name: str(item?.name) ?? '…'}), + blocks: item ? [{type: 'hub', rows: [{id: item.versionId, name: str(item.name) ?? item.versionId, vendor: str(item.creator), + description: str(item.description)}]}] : generic(result, 'result') + }; + } + case 'read_iot_hub_device': + case 'install_iot_hub_device': { + const item = isObject(result) && (str(result.name) ?? str(result.installed)) ? result : null; + const name = str(item?.name) ?? str(item?.installed); + return { + hood: text(tool === 'install_iot_hub_device' ? 'iot-hub-install' : 'iot-hub-read', {name: name ?? '…'}), + blocks: item && str(values.versionId) ? [{type: 'hub', rows: [{id: values.versionId, name, vendor: str(item.vendor), + description: str(item.description)}]}] : generic(result, 'result') + }; + } + case 'search_entities': + return searchEntities(values, result, names); + case 'read_entity': { + const read = isObject(result) ? result : null; + if (!read) { + return {hood: text('read-entity', {entity: target}), blocks: generic(result, 'result')}; + } + const record: AiDetailRecord = {entityType: target.entityType ?? 'DEVICE', id: target.id, name: str(read.name) ?? str(read.title) ?? target.name ?? '—', + meta: [read.label && read.label !== read.name ? read.label : undefined, read.deviceProfileName ?? read.assetProfileName ?? read.type].filter(Boolean).join(' · ') || undefined}; + const configured = isObject(aiParse(read.configuration)); + const rows = [ + ...(configured ? savedFacts(read, names) : []), + ...facts(read, ['id', 'name', 'title', 'label', 'createdTime', 'deviceProfileName', 'assetProfileName', 'tenantId', 'type', 'additionalInfo', + 'debugSettings', 'configuration', 'version', 'configurationVersion', ...(configured ? ['entityId', 'description'] : [])], names) + ]; + if (read.createdTime) { + rows.push({label: K + 'fact.created', value: dateText(read.createdTime)}); + } + return {hood: text('read-entity', {entity: {...target, name: record.name}}), blocks: [{type: 'records', rows: [record]}, ...(rows.length ? [{type: 'facts', rows} as AiDetailBlock] : [])]}; + } + case 'read_entity_relations': + return {hood: text('read-relations', {entity: target}), blocks: relations(result)}; + case 'read_timeseries': { + const keys = Array.isArray(values.keys) ? values.keys.join(', ') : ''; + const ids = Array.isArray(values.entityIds) ? values.entityIds.map(idOf).filter(Boolean) : []; + const subject: AiDetailParam = ids.length > 1 + ? {words: ids.map(id => names.get(id)?.name).every(Boolean) ? ids.map(id => names.get(id).name) : ['ai-assistant.detail.several'], commas: true} + : ids.length ? of(ids[0], values.entityType) : target; + const hood = values.mode === 'HISTORY' || values.startTime + ? text(keys ? 'read-history-keys' : 'read-history', {entity: subject, keys, from: dateText(values.startTime), to: endText(values.endTime)}) + : text(keys ? 'read-latest-keys' : 'read-latest', {entity: subject, keys}); + const blocks = isObject(result) ? telemetry(result, id => of(id, values.entityType)) : generic(result, 'result'); + return {hood, blocks: isObject(result) && !Object.keys(result).length ? [{type: 'note', text: text('no-data')}] : blocks}; + } + case 'read_timeseries_keys': { + const data = isObject(result) ? (isObject(result.timeseries) ? result.timeseries : result) : null; + let blocks: AiDetailBlock[]; + if (Array.isArray(data)) { + blocks = [{type: 'keys', keys: data.map(String)}]; + } else if (data && Object.keys(data).length) { + blocks = telemetry(data); + } else { + blocks = data ? [{type: 'note', text: text('no-data')}] : generic(result, 'result'); + } + return {hood: text('read-keys', {entity: target}), blocks}; + } + case 'read_attributes': + return {hood: text(values.scope ? 'read-attributes-scope' : 'read-attributes', {entity: target, scope: K + 'scope.' + (SCOPES[values.scope] ?? 'other')}), blocks: attributes(result, 'values')}; + case 'discover_attribute_keys': + return {hood: text('discover-attribute-keys', {entity: of(values.profileId, values.profileType)}), blocks: attributes(result, 'keys')}; + case 'save_attributes': { + const saved = aiParse(values.attributes); + const rows = isObject(saved) ? Object.entries(saved).map(([key, value]) => ({key, value: aiValueText(value)})) : []; + return { + hood: text('save-attributes.' + (SCOPES[values.scope] ?? 'other'), {entity: target, count: rows.length}), + blocks: rows.length ? [{type: 'values', rows}, ...generic(result, 'result')] : generic(result, 'result') + }; + } + case 'delete_attributes': { + const keys = Array.isArray(values.keys) ? values.keys.map(String) : []; + return {hood: text('delete-attributes', {entity: target, scope: K + 'scope.' + (SCOPES[values.scope] ?? 'other')}), blocks: [...(keys.length ? [{type: 'keys', keys} as AiDetailBlock] : []), ...generic(result, 'result')]}; + } + case 'read_device_credentials': { + const device = of(values.deviceId, 'DEVICE'); + if (!isObject(result)) { + return {hood: text('read-credentials', {entity: device}), blocks: generic(result, 'result')}; + } + const rows: AiDetailFact[] = []; + if (str(result.credentialsType)) { + rows.push({label: K + 'fact.type', value: aiHumanize(result.credentialsType)}); + } + for (const key of ['accessToken', 'credentialsId', 'clientId', 'userName', 'password', 'credentialsValue']) { + if (str(result[key])) { + rows.push({label: aiHumanize(key), raw: true, value: result[key], mono: true, secret: /token|password|value|credentialsId/i.test(key)}); + } + } + return {hood: text('read-credentials', {entity: device}), blocks: [{type: 'facts', rows}]}; + } + case 'read_transport_endpoints': { + if (!isObject(result)) { + return {hood: text('read-endpoints'), blocks: generic(result, 'result')}; + } + const rows: AiDetailFact[] = Object.entries(isObject(result.transports) ? result.transports : {}) + .map(([name, endpoint]: [string, any]) => ({label: name.toUpperCase(), raw: true, value: [endpoint?.host, endpoint?.port].filter(Boolean).join(':'), mono: true})); + if (Array.isArray(result.disabled) && result.disabled.length) { + rows.push({label: K + 'fact.disabled', value: result.disabled.map((name: string) => name.toUpperCase()).join(', ')}); + } + return {hood: text('read-endpoints'), blocks: [{type: 'facts', rows}]}; + } + case 'read_device_connect_commands': { + const rows = commands(result); + return {hood: text('read-connect-commands', {entity: of(values.deviceId, 'DEVICE')}), blocks: rows.length ? [{type: 'commands', rows}] : generic(result, 'result')}; + } + case 'research_device_connectivity': + return { + hood: text(str(values.question) ? 'research-question' : 'research', {device: str(values.device) ?? '—', question: str(values.question) ?? ''}), + blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result.trim()}] : generic(result, 'result') + }; + case 'search_web': + return {hood: text('search-web', {query: str(values.query) ?? '—'}), blocks: webResults(result)}; + case 'fetch_web_page': + return { + hood: text('fetch-page', {url: str(values.url) ?? '—'}), + blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result.trim()}] : generic(result, 'result') + }; + case 'create_dashboard': + return {hood: text('create-dashboard', {name: str(values.title) ?? '—'}), blocks: []}; + case 'generate_device_dashboard': { + const keys = Array.isArray(values.keys) ? values.keys.map(String) : []; + return {hood: text('generate-device-dashboard', {entity: of(values.deviceId, 'DEVICE')}), blocks: keys.length ? [{type: 'keys', keys}] : []}; + } + case 'update_dashboard': + return {hood: text('update-dashboard', {entity: dashboard}), blocks: changes(values, ['dashboardId'], names)}; + case 'read_dashboard_overview': + return {hood: text('read-dashboard', {entity: dashboard}), blocks: dashboardOverview(result, names)}; + case 'add_dashboard_state': { + const id = okId(result); + return {hood: text('add-state', {name: str(values.name) ?? '—', entity: dashboard}), blocks: id ? [{type: 'facts', rows: [{label: K + 'fact.state-id', value: id, mono: true}]}] : generic(result, 'result')}; + } + case 'update_dashboard_state': + return {hood: text('update-state', {state: str(values.stateId) ?? '—', entity: dashboard}), blocks: changes(values, ['dashboardId', 'stateId'], names)}; + case 'add_dashboard_entity_alias': + case 'update_dashboard_entity_alias': + return { + hood: text(tool === 'add_dashboard_entity_alias' ? 'add-alias' : 'update-alias', {name: str(values.alias) ?? names.get(values.aliasId)?.name ?? '—', entity: dashboard}), + blocks: [{type: 'facts', rows: aliasFilter(values.filter, names)}] + }; + case 'read_dashboard_entity_alias': { + const read = isObject(result) ? result : null; + return { + hood: text('read-alias', {name: str(read?.alias) ?? names.get(values.aliasId)?.name ?? '—'}), + blocks: read ? [{type: 'facts', rows: aliasFilter(read.filter, names)}] : generic(result, 'result') + }; + } + case 'add_dashboard_filter': + case 'update_dashboard_filter': + case 'read_dashboard_filter': { + const name = str(values.filter) ?? str(values.name) ?? (isObject(result) ? str(result.filter) ?? str(result.name) : undefined) ?? '—'; + const shown = tool === 'read_dashboard_filter' ? generic(result, 'result', ['id'], names) : changes(values, ['dashboardId', 'filterId'], names); + return {hood: text(tool.replace(/_dashboard_filter$/, '-filter'), {name, entity: dashboard}), blocks: shown}; + } + case 'add_dashboard_widgets': { + const rows = widgetRecords(values.widgets, result); + return {hood: text(rows.length === 1 ? 'add-widget' : 'add-widgets', {count: rows.length, entity: dashboard}), blocks: rows.length ? [{type: 'records', rows}] : generic(result, 'result')}; + } + case 'add_scada_connectors': { + const rows = (Array.isArray(values.lines) ? values.lines : []).filter(isObject) + .map((line, index) => `${str(line.name) ?? 'Line ' + (index + 1)} · ${isObject(line.from) && isObject(line.to) + ? `${names.get(str(line.from.widgetId) ?? '')?.name ?? str(line.from.widgetId) ?? '—'} ${str(line.from.side) ?? ''} → ` + + `${names.get(str(line.to.widgetId) ?? '')?.name ?? str(line.to.widgetId) ?? '—'} ${str(line.to.side) ?? ''}` + : `${Array.isArray(line.points) ? line.points.length : 0} points`}` + (isObject(line.flow) ? ' · flow' : '')); + return {hood: text('add-scada-connectors', {count: rows.length, entity: dashboard}), blocks: rows.length ? [{type: 'list', rows}] : generic(result, 'result')}; + } + case 'update_dashboard_widget': + return { + hood: text('update-widget', {name: str(values.title) ?? names.get(values.widgetId)?.name ?? '—', entity: dashboard}), + blocks: changes(values, ['dashboardId', 'widgetId'], names) + }; + case 'read_dashboard_widget': { + const read = isObject(result) ? result : null; + return { + hood: text('read-widget', {name: str(read?.title) ?? names.get(values.widgetId)?.name ?? '—'}), + blocks: read ? [{type: 'facts', rows: widgetFacts(read, names)}] : generic(result, 'result') + }; + } + case 'place_dashboard_widgets': { + const rows = (Array.isArray(values.placements) ? values.placements : []).filter(isObject) + .map(place => text('widget-placed', {name: names.get(place.widgetId)?.name ?? place.widgetId, width: place.sizeX, height: place.sizeY, + col: place.col, row: place.row})); + return {hood: text('place-widgets', {count: rows.length, entity: dashboard}), blocks: rows.length ? [{type: 'list', rows}] : generic(result, 'result')}; + } + case 'set_dashboard_html_page': { + const brief = isObject(values.brief) ? values.brief : {}; + const rows: AiDetailFact[] = []; + for (const key of ['description', 'design', 'embeds', 'aliases']) { + const value = brief[key]; + if (value !== undefined && value !== '' && !(Array.isArray(value) && !value.length)) { + rows.push({label: K + 'fact.' + key, value: Array.isArray(value) ? value.join(', ') : String(value)}); + } + } + return {hood: text('set-html-page', {state: str(values.stateId) ?? 'default', entity: dashboard}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_dashboard_html_page': + return {hood: text('read-html-page', {state: str(values.stateId) ?? 'default', entity: dashboard}), blocks: htmlPage(result)}; + case 'delete': { + if (values.targetType === 'IMAGE') { + const key = String(values.targetId ?? '').split('/').pop() || '—'; + return {hood: text('delete', {entity: {entityType: 'IMAGE', name: key}}), blocks: generic(result, 'result')}; + } + const type = DELETE_TYPES[values.targetType] ?? values.targetType; + return {hood: text('delete', {entity: of(values.targetId, type)}), blocks: generic(result, 'result')}; + } + case 'save_device': { + const saved = savedObject(values); + const rows: AiDetailFact[] = []; + if (str(saved.label) && saved.label !== saved.name) { + rows.push({label: K + 'fact.label', value: saved.label}); + } + const profile = saved.profileId ?? saved.deviceProfileId; + if (profile) { + rows.push({label: K + 'fact.profile', entity: of(profile, 'DEVICE_PROFILE')}); + } + if (saved.customerId) { + rows.push({label: K + 'fact.customer', entity: of(saved.customerId, 'CUSTOMER')}); + } + if (saved.additionalInfo?.gateway) { + rows.push({label: K + 'fact.gateway', value: K + 'yes'}); + } + return {hood: text(hasId(saved) ? 'update-device' : 'create-device', {name: str(saved.name) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_calculated_field': + case 'save_alarm_rule': + case 'save_notification_target': + case 'save_notification_template': + case 'save_notification_rule': { + const nested = {save_alarm_rule: 'alarmRule', save_notification_target: 'target', save_notification_template: 'template', save_notification_rule: 'rule'}[tool]; + const saved = savedObject(values, nested); + const kind = tool.replace(/^save_/, '').replace(/_/g, '-'); + return {hood: text('save', {what: K + 'kind.' + kind, name: str(saved.name) ?? str(saved.title) ?? '—'}), blocks: [{type: 'facts', rows: savedFacts(saved, names)}]}; + } + case 'save_asset': + case 'save_entity_view': + case 'save_asset_profile': + case 'save_secret': + case 'save_ai_model': + case 'save_resource': { + const kind = tool.replace(/^save_/, '').replace(/_/g, '-'); + const saved = isObject(result) ? result : {}; + const name = str(values.name) ?? str(values.title) ?? str(saved.name) ?? str(saved.title) ?? '—'; + const rows: AiDetailFact[] = []; + if (str(saved.reference)) { + rows.push({label: K + 'fact.reference', value: saved.reference, mono: true}); + } + if (str(saved.link)) { + rows.push({label: K + 'fact.link', value: saved.link, mono: true}); + } + if (saved.tested === true) { + rows.push({label: K + 'fact.tested', value: K + 'yes'}); + } + const pictures = images([{value: values.image}]); + return {hood: text('save', {what: K + 'kind.' + kind, name}), blocks: rows.length ? [{type: 'facts', rows}, ...pictures] : [...generic(result, 'result'), ...pictures]}; + } + case 'save_relations': { + if (!isObject(result)) { + return {hood: text('save-relations'), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + for (const [field, label] of [['added', 'relations-added'], ['removed', 'relations-removed']] as const) { + const rows = Array.isArray(result[field]) ? result[field].map(String) : []; + if (rows.length) { + blocks.push({type: 'list', label: text(label), rows: rows.slice(0, MAX_ROWS)}); + } + } + const failed = Array.isArray(result.failed) ? result.failed.filter(isObject) : []; + if (failed.length) { + blocks.push({type: 'list', label: text('relations-failed'), rows: failed.slice(0, MAX_ROWS).map(row => `${row.relation}: ${row.error}`)}); + } + return {hood: text('save-relations'), blocks}; + } + case 'read_gateway_status': { + if (!isObject(result)) { + return {hood: text('read-gateway-status'), blocks: generic(result, 'result')}; + } + const rows: AiDetailFact[] = [{label: K + 'fact.status', value: K + (result.online ? 'gateway-online' : 'gateway-offline')}]; + if (str(result.version)) { + rows.push({label: K + 'fact.version', value: result.version}); + } + if (str(result.lastConnect)) { + rows.push({label: K + 'fact.last-connect', value: dateText(result.lastConnect)}); + } + const blocks: AiDetailBlock[] = [{type: 'facts', rows}]; + const connectors = Array.isArray(result.connectors) ? result.connectors.filter(isObject) : []; + if (connectors.length) { + blocks.push({type: 'list', label: text('gateway-connectors'), rows: connectors.map(connector => [ + `${connector.name} (${connector.type})`, connector.active ? '●' : '○', + connector.applied === true ? '✓' : connector.applied === false ? '…' : undefined, str(connector.problem) + ].filter(Boolean).join(' '))}); + } + for (const [key, lines] of Object.entries(isObject(result.logs) ? result.logs : {})) { + if (Array.isArray(lines) && lines.length) { + blocks.push({type: 'code', label: key, text: lines.map(String).join('\n')}); + } + } + return {hood: text('read-gateway-status', {name: str(result.name) ?? '—'}), blocks}; + } + case 'read_white_labeling': + return {hood: text('read-white-labeling'), blocks: json('settings', result)}; + case 'read_website_brand': { + const site = str(isObject(result) ? result.url : undefined) ?? str(values.url) ?? '—'; + if (!isObject(result)) { + return {hood: text('read-website-brand', {site}), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + if (str(result.pageNotRead)) { + blocks.push({type: 'note', text: text('website-not-read')}); + } + const colors = [str(result.themeColor) ? `${result.themeColor} · theme-color` : undefined, + ...(Array.isArray(result.iconColors) ? result.iconColors.filter(isObject).map(color => `${color.color} · icon ${color.percent}%`) : []), + ...Object.entries(isObject(result.colorVariables) ? result.colorVariables : {}).map(([name, color]) => `${color} · ${name}`), + ...(Array.isArray(result.colors) ? result.colors.filter(isObject).map(color => `${color.color} · ×${color.uses}`) : [])] + .filter(Boolean).slice(0, MAX_ROWS); + if (colors.length) { + blocks.push({type: 'list', label: text('website-colors'), rows: colors}); + } + const logos = (Array.isArray(result.logos) ? result.logos.filter(isObject) : []) + .map(logo => str(logo.url) ?? ` · ${logo.source}`).slice(0, MAX_ROWS); + if (logos.length) { + blocks.push({type: 'list', label: text('website-logos'), rows: logos}); + } + return {hood: text('read-website-brand', {site}), blocks}; + } + case 'save_white_labeling': { + const {target, reset, ...changes} = values; + if (reset) { + return {hood: text(target === 'LOGIN' ? 'reset-white-labeling-login' : 'reset-white-labeling'), blocks: []}; + } + return {hood: text(target === 'LOGIN' ? 'save-white-labeling-login' : 'save-white-labeling'), blocks: [{type: 'facts', rows: facts(changes)}, + ...images([{label: text('image-logo'), value: values.logoImage}, {label: text('image-collapsed-logo'), value: values.collapsedLogoImage}, + {label: text('image-favicon'), value: values.favicon}])]}; + } + case 'read_mail_templates': { + if (!isObject(result)) { + return {hood: text('read-mail-templates'), blocks: generic(result, 'result')}; + } + const note: AiDetailBlock[] = [{type: 'note', text: text(result.useSystemTemplates ? 'mail-system-in-use' : 'mail-own-in-use')}]; + if (str(result.template)) { + const blocks: AiDetailBlock[] = [...note, {type: 'facts', rows: [{label: K + 'fact.subject', value: str(result.subject) ?? '—', raw: true}]}]; + if (str(result.body)) { + blocks.push({type: 'code', label: 'HTML', text: result.body}); + } + return {hood: text('read-mail-template', {template: result.template}), blocks}; + } + const rows = (Array.isArray(result.templates) ? result.templates.filter(isObject) : []).map(item => `${item.template} · ${item.subject ?? '—'}`); + return {hood: text('read-mail-templates'), blocks: [...note, ...(rows.length ? [{type: 'list', rows} as AiDetailBlock] : [])]}; + } + case 'save_mail_template': { + if (values.useSystemTemplates) { + return {hood: text('mail-use-system'), blocks: []}; + } + const blocks: AiDetailBlock[] = []; + if (str(values.subject)) { + blocks.push({type: 'facts', rows: [{label: K + 'fact.subject', value: values.subject, raw: true}]}); + } + const replace = Array.isArray(values.replace) ? values.replace.filter(isObject) : []; + if (replace.length) { + blocks.push({type: 'list', label: text('mail-replaced'), rows: replace.map(item => `${item.from} → ${item.to}`)}); + } + if (str(values.body)) { + blocks.push({type: 'code', label: 'HTML', text: values.body}); + } + return {hood: str(values.template) ? text('save-mail-template', {template: values.template}) : text('save-mail-templates'), blocks}; + } + case 'read_custom_translation': { + const locale = str(isObject(result) ? result.locale : undefined) ?? str(values.locale) ?? '—'; + if (!isObject(result)) { + return {hood: text('read-custom-translation', {locale}), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + const matches = (Array.isArray(result.matches) ? result.matches.filter(isObject) : []).slice(0, MAX_ROWS) + .map(match => `${match.key} · ${match.text}${match.customized ? ' ✎' : ''}`); + if (matches.length) { + blocks.push({type: 'list', label: text('translation-matches'), rows: matches}); + } + const customized = Object.entries(isObject(result.customized) ? result.customized : {}).slice(0, MAX_ROWS) + .map(([key, value]) => `${key} · ${value}`); + if (customized.length) { + blocks.push({type: 'list', label: text('translation-customized'), rows: customized}); + } + return {hood: text('read-custom-translation', {locale}), blocks}; + } + case 'save_custom_translation': { + const blocks: AiDetailBlock[] = []; + const set = (Array.isArray(values.set) ? values.set.filter(isObject) : []).map(item => `${item.key} → ${item.text}`); + if (set.length) { + blocks.push({type: 'list', label: text('translation-set'), rows: set.slice(0, MAX_ROWS)}); + } + const removed = Array.isArray(values.remove) ? values.remove.map(String) : []; + if (removed.length) { + blocks.push({type: 'list', label: text('translation-removed'), rows: removed.slice(0, MAX_ROWS)}); + } + return {hood: text('save-custom-translation', {locale: str(values.locale) ?? '—'}), blocks}; + } + case 'read_mobile_center': { + if (!isObject(result)) { + return {hood: text('read-mobile-center'), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + const apps = (Array.isArray(result.apps) ? result.apps.filter(isObject) : []).slice(0, MAX_ROWS) + .map(app => [app.pkgName, app.platformType, aiHumanize(String(app.status)), str(app.versionInfo?.latestVersion)].filter(Boolean).join(' · ')); + if (apps.length) { + blocks.push({type: 'list', label: text('mobile-apps'), rows: apps}); + } else if (Array.isArray(result.apps)) { + blocks.push({type: 'note', text: text('no-mobile-apps')}); + } + if (Array.isArray(result.bundles) && !result.bundles.length) { + blocks.push({type: 'note', text: text('no-mobile-bundles')}); + } + for (const bundle of (Array.isArray(result.bundles) ? result.bundles.filter(isObject) : []).slice(0, MAX_ROWS)) { + const pages = (Array.isArray(bundle.menu) ? bundle.menu.filter(isObject) : []) + .map(page => `${str(page.label) ?? page.id}${page.hidden ? ' ⊘' : ''}`); + blocks.push({type: 'list', label: text('mobile-bundle-menu', {name: str(bundle.title) ?? '—'}), rows: pages}); + } + if (isObject(result.qrCode)) { + blocks.push(...json('qr-code', result.qrCode)); + } + return {hood: text('read-mobile-center'), blocks}; + } + case 'save_mobile_app': { + const rows = facts(values, ['appId']); + return {hood: str(values.appId) ? text('save-mobile-app') : text('register-mobile-app', {name: str(values.pkgName) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_mobile_bundle': { + const changes = (Array.isArray(values.changes) ? values.changes.filter(isObject) : []) + .map(change => [aiHumanize(String(change.action)), str(change.page) ?? str(change.label), str(change.page) && str(change.label) ? '→ ' + change.label : undefined, + str(change.dashboardId) ?? str(change.url) ?? str(change.path)].filter(Boolean).join(' ')); + const blocks: AiDetailBlock[] = []; + const rows = facts(values, ['bundleId', 'changes']); + if (rows.length) { + blocks.push({type: 'facts', rows}); + } + if (changes.length) { + blocks.push({type: 'list', label: text('menu-changes'), rows: changes.slice(0, MAX_ROWS)}); + } + return {hood: str(values.bundleId) ? text('save-mobile-bundle') : text('create-mobile-bundle', {name: str(values.title) ?? '—'}), blocks}; + } + case 'read_scheduler_events': { + if (!isObject(result)) { + return {hood: text('read-scheduler-events'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.events)) { + const rows = result.events.filter(isObject).slice(0, MAX_ROWS) + .map(event => [event.name, event.schedule, event.enabled === false ? '⏸' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-scheduler-events'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-scheduler-events')}]}; + } + return {hood: text('read-scheduler-event', {name: str(result.name) ?? '—'}), blocks: json('event', result)}; + } + case 'read_mail_server': + return {hood: text('read-mail-server'), blocks: json('mail-server', result)}; + case 'save_mail_server': { + const rows = facts(values); + return {hood: text('save-mail-server'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_my_account': + return {hood: text('read-my-account'), blocks: json('account', result)}; + case 'save_my_profile': { + const rows = facts(values); + return {hood: text('save-my-profile'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_my_two_factor': { + const rows = facts(values); + return {hood: text('save-my-two-factor'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'update_api_key': { + const rows = facts(values, ['apiKeyId']); + return {hood: values.delete === true ? text('delete-api-key') : text('update-api-key'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_oauth2_domain': { + const rows = facts(values, ['domainId']); + return {hood: text('save-oauth2-domain'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_two_factor_settings': { + const rows = facts(values); + return {hood: text('save-two-factor-settings'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'create_report_template': + case 'update_report_template': { + const rows = facts(values, ['templateId']); + return {hood: tool === 'create_report_template' ? text('create-report-template', {name: str(values.name) ?? '—'}) : text('update-report-template'), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_report_template': { + if (!isObject(result)) { + return {hood: text(str(values.path) ? 'read-report-component' : 'read-report-template', {path: str(values.path) ?? '—', name: '—'}), blocks: generic(result, 'result')}; + } + if (str(values.path)) { + return {hood: text('read-report-component', {path: str(result.path) ?? str(values.path), name: str(result.template) ?? '—'}), + blocks: [{type: 'facts', rows: reportComponentFacts(result)}]}; + } + return {hood: text('read-report-template', {name: str(result.name) ?? '—'}), blocks: reportTemplateOverview(result)}; + } + case 'add_report_components': { + const rows = (Array.isArray(values.components) ? values.components.filter(isObject) : []).slice(0, MAX_ROWS).map(component => { + const config = isObject(component.config) ? component.config : {}; + const title = str(config.title) ?? str(config.text); + return [str(component.in), aiHumanize(String(component.type)), title].filter(Boolean).join(' · '); + }); + return {hood: text('add-report-components'), blocks: rows.length ? [{type: 'list', rows}] : []}; + } + case 'update_report_component': { + const rows = facts(isObject(values.config) ? values.config as Values : {}); + return {hood: text('update-report-component', {path: str(values.path) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'move_report_component': + return {hood: text('move-report-component', {path: str(values.path) ?? '—', target: str(values.in) ?? '—'}), blocks: []}; + case 'save_report_entity_alias': + case 'save_report_filter': { + const rows = facts(values, ['templateId', 'aliasId', 'filterId']); + return {hood: text(tool === 'save_report_filter' ? 'save-report-filter' : 'save-report-alias', {name: str(values.name) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'test_report_template': { + if (!isObject(result)) { + return {hood: text('test-report-template'), blocks: generic(result, 'result')}; + } + const errors = (Array.isArray(result.errors) ? result.errors.filter(isObject) : []) + .map(error => [error.page !== undefined ? `p. ${error.page}` : error.row !== undefined ? `row ${error.row}` : undefined, str(error.message)] + .filter(Boolean).join(' · ')); + const pdf = result.pages !== undefined; + const count = Number(pdf ? result.pages : result.rows ?? 0); + const size = text((pdf ? 'report-pages' : 'report-rows') + (errors.length ? '' : '-clean'), {count}); + return {hood: text('test-report-template'), + blocks: [{type: 'note', text: size}, + ...(errors.length ? [{type: 'list' as const, label: text('report-errors'), rows: errors.slice(0, MAX_ROWS)}] : [])]}; + } + case 'read_reports': { + if (!isObject(result)) { + return {hood: text('read-reports'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.templates)) { + const rows = result.templates.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.name, item.format, item.templateType === 'SUB_REPORT' ? 'Sub-report' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-report-templates'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-report-templates')}]}; + } + if (Array.isArray(result.scheduledReports)) { + const rows = result.scheduledReports.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.name, item.template, item.schedule, item.enabled === false ? '⏸' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-scheduled-reports'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-scheduled-reports')}]}; + } + if (Array.isArray(result.reports)) { + const rows = result.reports.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.file, item.template, item.generated].filter(Boolean).join(' · ')); + return {hood: text('read-generated-reports'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-generated-reports')}]}; + } + if (isObject(result.file)) { + return {hood: text('attach-report', {name: str(result.file.name) ?? '—'}), blocks: []}; + } + const rows = facts(result, ['eventId', 'templateId', 'rawSchedule', 'recipients', 'notificationTemplate', 'name']); + const recipients = Array.isArray(result.recipients) ? result.recipients.filter(isObject).map(item => str(item.name)).filter(Boolean) : []; + if (recipients.length) { + rows.push({label: aiHumanize('recipients'), raw: true, value: recipients.join(', ')}); + } + return {hood: text('read-scheduled-report', {name: str(result.name) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_scheduled_report': { + const rows = facts(values, ['eventId', 'templateId', 'userId', 'recipientIds', 'notificationTemplateId']); + return {hood: str(values.eventId) ? text('save-scheduled-report') : text('create-scheduled-report', {name: str(values.name) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'generate_report': { + const raw = typeof result === 'string' && /^OK: [^\n]*\n/.test(result) ? aiParse(result.slice(result.indexOf('\n') + 1)) : result; + if (!isObject(raw)) { + return {hood: text('generate-report'), blocks: generic(raw, 'result')}; + } + const name = isObject(raw.file) ? str(raw.file.name) : str(raw.file); + const rows: AiDetailFact[] = []; + if (name) { + rows.push({label: aiHumanize('file'), raw: true, value: name}); + } + if (str(raw.sentTo)) { + rows.push({label: aiHumanize('sent to'), raw: true, value: str(raw.sentTo)}); + } + return {hood: text('generate-report'), blocks: rows.length ? [{type: 'facts', rows}] : [{type: 'note', text: text('report-still-running')}]}; + } + case 'read_widgets': { + if (!isObject(result)) { + return {hood: text('read-widgets'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.widgets) && str(result.title)) { + const rows = result.widgets.filter(isObject).slice(0, MAX_ROWS).map(item => [item.name, item.type].filter(Boolean).join(' · ')); + return {hood: text('read-widgets-bundle', {name: str(result.title)}), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-widgets')}]}; + } + if (Array.isArray(result.widgets)) { + const rows = result.widgets.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.name, item.type, item.system ? 'system' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-widgets'), blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-widgets')}]}; + } + const rows = (Array.isArray(result.bundles) ? result.bundles.filter(isObject) : []).slice(0, MAX_ROWS) + .map(item => [item.title, item.system ? 'system' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-widgets-bundles'), blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-widgets-bundles')}]}; + } + case 'read_scada_symbols': { + const rows = (isObject(result) && Array.isArray(result.symbols) ? result.symbols.filter(isObject) : []).slice(0, MAX_ROWS) + .map(item => [item.title, item.family === 'hp' ? 'HP' : item.family, item.size, item.system ? 'system' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-scada-symbols'), blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-scada-symbols')}]}; + } + case 'read_scada_symbol': { + if (!isObject(result)) { + const raw = typeof result === 'string' ? result : ''; + const name = /^SCADA symbol '([^']*)'/.exec(raw)?.[1] ?? '—'; + const parts = widgetParts(values).filter(part => part !== 'all'); + const sections = raw.split(/\n\n=== ([A-Za-z]+) ===\n/); + const blocks: AiDetailBlock[] = []; + for (let i = 1; i + 1 < sections.length; i += 2) { + const overview = sections[i] === 'overview' ? aiParse(sections[i + 1]) : undefined; + if (isObject(overview)) { + blocks.push(...scadaSymbolOverviewBlocks(overview)); + } else if (sections[i + 1].trim()) { + blocks.push({type: 'code', label: aiPartTitle(sections[i]), text: sections[i + 1], + lang: SCADA_SYMBOL_PART_LANGS[sections[i]] ?? 'json'}); + } + } + return {hood: text('read-scada-symbol-parts', {name, parts: aiWordList(parts.map(aiPartWord), true)}), blocks}; + } + return {hood: text('read-scada-symbol', {name: str(result.title) ?? '—'}), blocks: scadaSymbolOverviewBlocks(result)}; + } + case 'build_scada_symbol': + case 'create_scada_symbol': + case 'update_scada_symbol': { + const raw = typeof result === 'string' && result.startsWith('OK: ') ? aiParse(result.slice(4)) : result; + const name = (isObject(raw) ? str(raw.title) : undefined) ?? str(values.title) ?? '—'; + const hood = tool === 'create_scada_symbol' ? text('copy-scada-symbol', {name}) + : tool === 'update_scada_symbol' ? text('change-scada-symbol', {name}) + : str(values.symbol) ? text('update-scada-symbol', {name}) : text('create-scada-symbol', {name}); + if (!isObject(raw)) { + return {hood, blocks: generic(raw, 'result')}; + } + const warnings = Array.isArray(raw.warnings) ? raw.warnings.map(item => String(item)) : []; + const rows = facts(raw, ['warnings', 'link']); + return {hood, blocks: [...scadaSymbolPicture(raw), ...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...(warnings.length ? [{type: 'list' as const, label: text('widget-warnings'), rows: warnings.slice(0, MAX_ROWS)}] : [])]}; + } + case 'read_widget': { + if (!isObject(result)) { + const raw = typeof result === 'string' ? result : ''; + const name = /^Widget '([^']*)'/.exec(raw)?.[1] ?? '—'; + const parts = widgetParts(values).filter(part => part !== 'all'); + const sections = raw.split(/\n\n=== ([A-Za-z]+) ===\n/); + const blocks: AiDetailBlock[] = []; + for (let i = 1; i + 1 < sections.length; i += 2) { + if (sections[i + 1].trim()) { + blocks.push({type: 'code', label: aiPartTitle(sections[i]), text: sections[i + 1], + lang: WIDGET_PART_LANGS[sections[i]] ?? 'json'}); + } + } + return {hood: text('read-widget-parts', {name, parts: aiWordList(parts.map(aiPartWord), true)}), blocks}; + } + const rows = facts(result, ['id', 'name', 'typeParameters', 'functions', 'problems', 'lines', 'settingsForm', 'dataKeySettingsForm', + 'latestDataKeySettingsForm', 'defaultConfig', 'resources', 'note', 'builtIn', 'description', 'image', 'tags']); + const problems = Array.isArray(result.problems) ? result.problems.map(item => String(item)) : []; + return {hood: text('read-widget-type', {name: str(result.name) ?? '—'}), + blocks: [...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...(problems.length ? [{type: 'list' as const, label: text('widget-problems'), rows: problems.slice(0, MAX_ROWS)}] : [])]}; + } + case 'create_widget': + case 'build_widget': + case 'update_widget': { + const raw = typeof result === 'string' && /^OK: [^\n]*\n/.test(result) ? aiParse(result.slice(result.indexOf('\n') + 1)) : result; + const edits = Array.isArray(values.edits) ? values.edits.length : 0; + const hood = tool === 'create_widget' || (tool === 'build_widget' && !values.widgetTypeId) ? text('create-widget', {name: str(values.name) ?? '—'}) + : edits ? text('update-widget-edits', {count: edits}) : text('update-widget-type'); + if (!isObject(raw)) { + return {hood, blocks: generic(raw, 'result')}; + } + const warnings = Array.isArray(raw.warnings) ? raw.warnings.map(item => String(item)) : []; + const rows = facts(raw, ['typeParameters', 'warnings', 'note', 'next', 'id', 'name', 'fqn', 'type']); + return {hood, blocks: [...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...(warnings.length ? [{type: 'list' as const, label: text('widget-warnings'), rows: warnings.slice(0, MAX_ROWS)}] : [])]}; + } + case 'create_scada_symbol_widget': { + const raw = typeof result === 'string' && result.startsWith('OK: ') ? aiParse(result.slice(4)) : result; + const name = (isObject(raw) ? str(raw.name) : undefined) ?? str(values.name) ?? '—'; + if (!isObject(raw)) { + return {hood: text('create-scada-symbol-widget', {name}), blocks: generic(raw, 'result')}; + } + const rows = facts(raw, ['widgetTypeId']); + return {hood: text('create-scada-symbol-widget', {name}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'check_scada_symbol': { + if (!isObject(result)) { + return {hood: text('check-scada-symbol'), blocks: generic(result, 'result')}; + } + const errors = Array.isArray(result.errors) ? result.errors.map(item => String(item)) : []; + const outcome = errors.length ? text('widget-check-errors', {count: errors.length}) + : result.result === 'rendered without errors' ? text('scada-symbol-check-clean') : text('scada-symbol-check-not-rendered'); + return {hood: text('check-scada-symbol'), blocks: [{type: 'note', text: outcome}, + ...(errors.length ? [{type: 'list' as const, label: text('widget-errors'), rows: errors.slice(0, MAX_ROWS)}] : [])]}; + } + case 'check_widget': { + if (!isObject(result)) { + return {hood: text('check-widget'), blocks: generic(result, 'result')}; + } + const errors = Array.isArray(result.errors) ? result.errors.map(item => String(item)) : []; + const consoleErrors = Array.isArray(result.consoleErrors) ? result.consoleErrors.map(item => String(item)) : []; + const outcome = errors.length ? text('widget-check-errors', {count: errors.length}) + : result.result === 'ran without errors' ? text('widget-check-clean') : text('widget-check-not-run'); + return {hood: text('check-widget'), blocks: [{type: 'note', text: outcome}, + ...(errors.length ? [{type: 'list' as const, label: text('widget-errors'), rows: errors.slice(0, MAX_ROWS)}] : []), + ...(consoleErrors.length ? [{type: 'list' as const, label: text('widget-console'), rows: consoleErrors.slice(0, MAX_ROWS)}] : [])]}; + } + case 'save_widgets_bundle': { + const raw = typeof result === 'string' && /^OK: [^\n]*\n/.test(result) ? aiParse(result.slice(result.indexOf('\n') + 1)) : result; + const hood = str(values.bundleId) ? text('save-widgets-bundle') : text('create-widgets-bundle', {name: str(values.title) ?? '—'}); + if (!isObject(raw)) { + return {hood, blocks: generic(raw, 'result')}; + } + const rows = Array.isArray(raw.widgets) ? raw.widgets.map(item => String(item)).slice(0, MAX_ROWS) : []; + return {hood, blocks: rows.length ? [{type: 'list', label: text('widgets'), rows}] : [{type: 'note', text: text('no-widgets')}]}; + } + case 'save_scheduler_event': { + const rows = facts(values, ['eventId']); + return {hood: str(values.eventId) ? text('save-scheduler-event') : text('create-scheduler-event', {name: str(values.name) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_mobile_qr_code': { + const rows = facts(values); + return {hood: text('save-mobile-qr-code'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_security_settings': + return {hood: text('read-security-settings'), blocks: json('settings', result)}; + case 'read_custom_menus': { + if (!isObject(result)) { + return {hood: text('read-custom-menus'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.menus)) { + const rows = result.menus.filter(isObject).slice(0, MAX_ROWS).map(menu => `${menu.name} · ${aiHumanize(String(menu.scope))} · ${aiHumanize(String(menu.assigneeType))}`); + return {hood: text('read-custom-menus'), blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('nothing-found')}]}; + } + const rows: string[] = []; + const walk = (items: unknown, depth: number) => { + for (const item of Array.isArray(items) ? items.filter(isObject) : []) { + rows.push(`${' '.repeat(depth)}${str(item.custom) ?? str(item.name) ?? item.id}${item.hidden ? ' ⊘' : ''}`); + walk(item.pages, depth + 1); + } + }; + walk(result.items, 0); + return {hood: text('read-custom-menu', {name: str(result.name) ?? '—'}), blocks: rows.length ? [{type: 'list', rows: rows.slice(0, 80)}] : []}; + } + case 'save_custom_menu': { + const changes = (Array.isArray(values.changes) ? values.changes.filter(isObject) : []) + .map(change => [aiHumanize(String(change.action)), str(change.item) ?? str(change.name), str(change.item) && str(change.name) ? '→ ' + change.name : undefined, + str(change.url) ?? str(change.dashboardId)].filter(Boolean).join(' ')); + const blocks: AiDetailBlock[] = []; + const rows = facts(values, ['menuId', 'changes']); + if (rows.length) { + blocks.push({type: 'facts', rows}); + } + if (changes.length) { + blocks.push({type: 'list', label: text('menu-changes'), rows: changes.slice(0, MAX_ROWS)}); + } + return {hood: str(values.menuId) ? text('save-custom-menu') : text('create-custom-menu', {name: str(values.name) ?? '—'}), blocks}; + } + case 'read_edges': { + if (!isObject(result)) { + return {hood: text('read-edges'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.edges)) { + const counts: AiDetailFact[] = Object.entries(isObject(result.connection) ? result.connection : {}) + .map(([state, count]) => ({label: aiHumanize(state), raw: true, value: String(count)})); + const rows = result.edges.filter(isObject).slice(0, MAX_ROWS) + .map(edge => [edge.name, edge.connection, str(edge.version)].filter(Boolean).join(' · ')); + const blocks: AiDetailBlock[] = counts.length ? [{type: 'facts', rows: counts}] : []; + if (rows.length) { + blocks.push({type: 'list', rows}); + } + return {hood: text('read-edges'), blocks}; + } + const rows = facts(result, ['id', 'assigned', 'missingRuleChains']); + const blocks: AiDetailBlock[] = rows.length ? [{type: 'facts', rows}] : []; + const assigned = isObject(result.assigned) ? result.assigned : {}; + const lines: string[] = []; + for (const [kind, items] of Object.entries(assigned)) { + if (Array.isArray(items) && items.length) { + lines.push(`${aiHumanize(kind)}: ${items.filter(isObject).map(item => item.name).join(', ')}`); + } else if (isObject(items)) { + for (const [groupType, groups] of Object.entries(items)) { + if (Array.isArray(groups) && groups.length) { + lines.push(`${aiHumanize(groupType)}: ${groups.filter(isObject).map(group => group.name).join(', ')}`); + } + } + } + } + if (lines.length) { + blocks.push({type: 'list', label: text('edge-assigned'), rows: lines.slice(0, MAX_ROWS)}); + } + return {hood: text('read-edge', {name: str(result.name) ?? '—'}), blocks}; + } + case 'read_edge_events': { + if (!isObject(result)) { + return {hood: text('read-edge-events'), blocks: generic(result, 'result')}; + } + const counts: AiDetailFact[] = Object.entries(isObject(result.counts) ? result.counts : {}) + .map(([state, count]) => ({label: aiHumanize(state), raw: true, value: String(count)})); + const rows = (Array.isArray(result.downlinks) ? result.downlinks.filter(isObject) : []).slice(0, MAX_ROWS) + .map(event => [event.status, event.type, event.action, str(event.time) ? dateText(event.time) : undefined] + .filter(Boolean).join(' · ')); + const blocks: AiDetailBlock[] = counts.length ? [{type: 'facts', rows: counts}] : []; + if (rows.length) { + blocks.push({type: 'list', rows}); + } + return {hood: text('read-edge-events'), blocks}; + } + case 'read_edge_instructions': + return {hood: text(values.upgrade ? 'read-edge-upgrade-instructions' : 'read-edge-install-instructions'), + blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result}] : []}; + case 'read_ota': { + if (!isObject(result)) { + return {hood: text('read-ota'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.packages)) { + const rows = result.packages.filter(isObject).slice(0, MAX_ROWS) + .map(pkg => `${pkg.title} ${pkg.version} · ${pkg.type} · ${pkg.source}`); + return {hood: text('read-ota-packages'), blocks: rows.length ? [{type: 'list', rows}] : []}; + } + const states = isObject(result.states) ? result.states : {}; + const facts: AiDetailFact[] = Object.entries(states).map(([state, count]) => ({label: aiHumanize(state), raw: true, value: String(count)})); + const rows = (Array.isArray(result.list) ? result.list.filter(isObject) : []).slice(0, MAX_ROWS) + .map(device => [device.name, device.state, str(device.current), str(device.target) ? '→ ' + device.target : undefined].filter(Boolean).join(' · ')); + const blocks: AiDetailBlock[] = facts.length ? [{type: 'facts', rows: facts}] : []; + if (rows.length) { + blocks.push({type: 'list', rows}); + } + return {hood: text('read-ota', {count: Number(result.devices) || 0}), blocks}; + } + case 'save_edge': + return {hood: text(str(values.edgeId) ? 'update-edge' : 'create-edge', {name: str(values.name) ?? '—'}), blocks: generic(result, 'result')}; + case 'assign_to_edge': { + const done = isObject(result) && Array.isArray(result.done) ? result.done.map(String) : []; + const failed = isObject(result) && Array.isArray(result.failed) ? result.failed.filter(isObject) : []; + const blocks: AiDetailBlock[] = []; + if (done.length) { + blocks.push({type: 'list', label: text('alarms-done'), rows: done.slice(0, MAX_ROWS)}); + } + if (failed.length) { + blocks.push({type: 'list', label: text('alarms-failed'), rows: failed.slice(0, MAX_ROWS).map(row => `${row.item}: ${row.error}`)}); + } + if (isObject(result) && result.missingRuleChains) { + blocks.push({type: 'list', label: text('edge-missing-rule-chains'), rows: [typeof result.missingRuleChains === 'string' + ? result.missingRuleChains : JSON.stringify(result.missingRuleChains)]}); + } + return {hood: text('assign-to-edge'), blocks: blocks.length ? blocks : generic(result, 'result')}; + } + case 'read_agents': { + if (!isObject(result)) { + return {hood: text('read-agents'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.agents)) { + const rows = result.agents.filter(isObject).slice(0, MAX_ROWS) + .map(agent => [agent.name, agent.online ? '●' : '○', str(agent.version), str(agent.profile)].filter(Boolean).join(' · ')); + return {hood: text('read-agents'), blocks: rows.length ? [{type: 'list', rows}] : []}; + } + const blocks: AiDetailBlock[] = []; + const apps = Array.isArray(result.applications) ? result.applications.filter(isObject) : []; + if (apps.length) { + blocks.push({type: 'list', label: text('agent-applications'), rows: apps.slice(0, MAX_ROWS) + .map(app => [app.name, app.appType, str(app.version), str(app.upgradeTo) ? '→ ' + app.upgradeTo : undefined].filter(Boolean).join(' · '))}); + } + const units = Array.isArray(result.units) ? result.units.filter(isObject) : []; + if (units.length) { + blocks.push({type: 'list', label: text('agent-units'), rows: units.slice(0, MAX_ROWS) + .map(unit => [unit.type, unit.name, str(unit.state)].filter(Boolean).join(' · '))}); + } + const ops = Array.isArray(result.recentOperations) ? result.recentOperations.filter(isObject) : []; + if (ops.length) { + blocks.push({type: 'list', label: text('agent-operations'), rows: ops.slice(0, MAX_ROWS) + .map(op => [op.action, str(op.application), op.status, str(op.error)].filter(Boolean).join(' · '))}); + } + return {hood: text('read-agent', {name: str(result.name) ?? '—'}), blocks}; + } + case 'read_agent_instructions': + return {hood: text('read-agent-instructions'), blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result}] : []}; + case 'read_agent_profiles': { + if (!isObject(result)) { + return {hood: text('read-agent-profiles'), blocks: generic(result, 'result')}; + } + const list = (key: string) => Array.isArray(result[key]) ? (result[key] as unknown[]).filter(isObject) : []; + const rows = [...list('agentProfiles').map(profile => [profile.name, profile.provisionType, profile.default ? '★' : undefined]), + ...list('appProfiles').map(profile => [profile.name, profile.appType, str(profile.templateVersion)])] + .slice(0, MAX_ROWS).map(row => row.filter(Boolean).map(String).join(' · ')); + if (Array.isArray(result.versions)) { + rows.push(...result.versions.map(String).slice(0, MAX_ROWS)); + } + return {hood: text('read-agent-profiles'), blocks: rows.length ? [{type: 'list', rows}] : generic(result, 'result')}; + } + case 'save_agent': + return {hood: text(str(values.agentId) ? 'update-agent' : 'create-agent', {name: str(values.name) ?? '—'}), blocks: generic(result, 'result')}; + case 'install_agent_application': + case 'run_agent_operation': + case 'save_agent_profile': + case 'save_agent_app_profile': + case 'run_agent_bulk_action': + return {hood: text(tool.replace(/_/g, '-')), blocks: generic(result, 'result')}; + case 'wait_agent_operation': { + if (!isObject(result)) { + return {hood: text('wait-agent-operation'), blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result}] : []}; + } + const rows = facts(result, ['operationId']); + return {hood: text('wait-agent-operation'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_rule_chain_templates': { + if (!isObject(result)) { + return {hood: text('read-rule-chain-templates'), blocks: generic(result, 'result')}; + } + const templates = Array.isArray(result.templates) ? result.templates.filter(isObject) : []; + if (templates.length || !str(result.name)) { + const blocks: AiDetailBlock[] = []; + const roots = templates.filter(template => template.edgeTemplateRoot).map(template => String(template.name)); + const auto = templates.filter(template => template.autoAssignToNewEdges).map(template => String(template.name)); + if (roots.length) { + blocks.push({type: 'list', label: text('rule-chain-template-root'), rows: roots}); + } + if (auto.length) { + blocks.push({type: 'list', label: text('rule-chain-template-auto'), rows: auto.slice(0, MAX_ROWS)}); + } + const rows = templates.slice(0, MAX_ROWS).map(template => String(template.name)); + if (rows.length) { + blocks.push({type: 'list', rows}); + } + return {hood: text('read-rule-chain-templates'), blocks}; + } + const blocks: AiDetailBlock[] = []; + const edges = Array.isArray(result.assignedToEdges) ? result.assignedToEdges.map(String) : []; + if (edges.length) { + blocks.push({type: 'list', label: text('rule-chain-template-edges'), rows: edges.slice(0, MAX_ROWS)}); + } + const nodes = Array.isArray(result.nodes) ? result.nodes.map(String) : []; + if (nodes.length) { + blocks.push({type: 'list', label: text('rule-chain-template-nodes'), rows: nodes.slice(0, MAX_ROWS)}); + } + return {hood: text('read-rule-chain-template', {name: str(result.name) ?? '—'}), blocks}; + } + case 'set_rule_chain_template': + return {hood: text('set-rule-chain-template'), blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result}] : []}; + case 'sync_edge': + return {hood: text('sync-edge'), blocks: []}; + case 'save_ota_package': + return {hood: text('save-ota-package', {name: [str(values.title), str(values.version)].filter(Boolean).join(' ') || '—'}), blocks: generic(result, 'result')}; + case 'assign_ota_package': { + const updated = isObject(result) && Array.isArray(result.updated) ? result.updated.map(String) : []; + const failed = isObject(result) && Array.isArray(result.failed) ? result.failed.filter(isObject) : []; + const blocks: AiDetailBlock[] = []; + if (updated.length) { + blocks.push({type: 'list', label: text('alarms-done'), rows: updated.slice(0, MAX_ROWS)}); + } + if (failed.length) { + blocks.push({type: 'list', label: text('alarms-failed'), rows: failed.slice(0, MAX_ROWS).map(row => `${row.target}: ${row.error}`)}); + } + return {hood: text(values.clear ? 'clear-ota-package' : 'assign-ota-package'), blocks: blocks.length ? blocks : generic(result, 'result')}; + } + case 'read_versions': { + const versions = isObject(result) && Array.isArray(result.versions) ? result.versions.filter(isObject) : undefined; + if (!versions) { + return {hood: text('read-versions'), blocks: generic(result, 'result')}; + } + const rows = versions.slice(0, MAX_ROWS).map(version => [str(version.name), str(version.author), + str(version.time) ? dateText(version.time) : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-versions'), blocks: rows.length ? [{type: 'list', rows}] : []}; + } + case 'commit_version': { + const saved = isObject(result) ? result : {}; + const rows: AiDetailFact[] = []; + if (str(saved.versionId)) { + rows.push({label: K + 'fact.version', value: saved.versionId, mono: true}); + } + if (str(saved.branch)) { + rows.push({label: K + 'fact.branch', value: saved.branch}); + } + for (const field of ['added', 'modified', 'removed']) { + if (typeof saved[field] === 'number') { + rows.push({label: K + 'fact.' + field, value: String(saved[field])}); + } + } + return {hood: text('commit-version', {name: str(values.name) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : generic(result, 'result')}; + } + case 'restore_version': { + const types = isObject(result) && Array.isArray(result.result) ? result.result.filter(isObject) : undefined; + const rows = (types ?? []).map(type => `${type.entityType}: +${type.created} · ~${type.updated} · −${type.deleted}`); + return {hood: text('restore-version', {version: String(values.versionId ?? '').slice(0, 8)}), blocks: types ? [{type: 'list', rows}] : generic(result, 'result')}; + } + case 'read_platform_settings': + return {hood: text('read-platform-settings'), blocks: json('settings', result)}; + case 'save_platform_settings': + return {hood: text('save-platform-settings'), blocks: json('settings', result)}; + case 'update_alarms': { + const action = alarmUpdateAction(values.action); + const count = Array.isArray(values.alarmIds) ? values.alarmIds.length : 0; + if (!isObject(result)) { + return {hood: text('update-alarms.' + action, {count}), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + const done = Array.isArray(result.done) ? result.done.map(String) : []; + const skipped = Array.isArray(result.skipped) ? result.skipped.map(String) : []; + const failed = Array.isArray(result.failed) ? result.failed.filter(isObject) : []; + if (done.length) { + blocks.push({type: 'list', label: text('alarms-done'), rows: done.slice(0, MAX_ROWS)}); + } + if (skipped.length) { + blocks.push({type: 'list', label: text('alarms-skipped'), rows: skipped.slice(0, MAX_ROWS)}); + } + if (failed.length) { + blocks.push({type: 'list', label: text('alarms-failed'), rows: failed.slice(0, MAX_ROWS).map(row => `${row.alarm}: ${row.error}`)}); + } + if (str(values.comment)) { + blocks.push({type: 'facts', rows: [{label: K + 'fact.comment', value: values.comment}]}); + } + return {hood: text('update-alarms.' + action, {count}), blocks}; + } + case 'read_api_usage': + return {hood: text('read-api-usage'), blocks: apiUsageBlocks(result)}; + case 'read_audit_logs': + return {hood: values.entityId ? text('read-audit-logs-of', {entity: target}) : text('read-audit-logs'), blocks: auditLogBlocks(result)}; + case 'read_tasks': + return {hood: text('read-tasks'), blocks: taskBlocks(result)}; + case 'save_image': { + const saved = isObject(result) ? result : {}; + const rows: AiDetailFact[] = str(saved.link) ? [{label: K + 'fact.link', value: saved.link, mono: true}] : []; + return {hood: text('save-image', {name: str(saved.title) ?? str(values.title) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}, ...images([{value: saved.link}])] : generic(result, 'result')}; + } + case 'test_converter': + return {blocks: converterBlocks(values, result)}; + case 'save_converter': + return {blocks: [...converterBlocks(values, undefined), ...generic(result, 'result', [], names)]}; + case 'reprocess_calculated_field': + return {hood: text('reprocess', {entity: of(values.calculatedFieldId, 'CALCULATED_FIELD'), from: dateText(values.startTime ?? values.startTs), to: endText(values.endTime ?? values.endTs)}), blocks: generic(result, 'result')}; + } + const request = Object.keys(values).length ? (flat(values) ? [{type: 'facts', rows: facts(values, [...CODE_KEYS], names)} as AiDetailBlock, ...codeBlocks(values)] : json('request', values)) : []; + return {blocks: [...request, ...generic(result, 'result', [], names)]}; +} + +const USAGE_LIMIT = (limit: unknown): string => limit === 'unlimited' || limit === undefined ? '∞' : aiValueText(limit); + +function apiUsageBlocks(result: unknown): AiDetailBlock[] { + if (!isObject(result)) { + return generic(result, 'result'); + } + const rows: AiDetailFact[] = []; + const warned: string[] = []; + for (const [name, entry] of Object.entries(isObject(result.entities) ? result.entities : {})) { + if (isObject(entry)) { + rows.push({label: K + 'usage.' + name, value: `${aiValueText(entry.count)} / ${USAGE_LIMIT(entry.limit)}`}); + } + } + for (const entry of Array.isArray(result.monthly) ? result.monthly : []) { + if (isObject(entry) && str(entry.name)) { + rows.push({label: K + 'usage.' + entry.name, value: `${aiValueText(entry.count)} / ${USAGE_LIMIT(entry.limit)}`}); + if (entry.state === 'WARNING' || entry.state === 'DISABLED') { + warned.push(entry.name); + } + } + } + const blocks: AiDetailBlock[] = rows.length ? [{type: 'facts', rows}] : []; + if (warned.length) { + blocks.push({type: 'note', text: text('usage.limited', {count: warned.length})}); + } + return blocks; +} + +function auditLogBlocks(result: unknown): AiDetailBlock[] { + const logs = isObject(result) && Array.isArray(result.logs) ? result.logs.filter(isObject) : undefined; + if (!logs) { + return generic(result, 'result'); + } + const rows: AiDetailRecord[] = logs.slice(0, MAX_ROWS).map(log => { + const target = isObject(log.entity) ? log.entity : {}; + const when = str(log.time) ? dateText(log.time) : undefined; + const meta = [str(log.action) ? aiHumanize(log.action) : undefined, str(log.user), when, log.status === 'FAILURE' ? '✕' : undefined] + .filter(Boolean).join(' · '); + return {entityType: str(target.type) ?? 'USER', id: str(target.id), name: str(target.name) ?? str(target.type) ?? '—', meta}; + }); + return [{type: 'records', rows, total: logs.length}]; +} + +function taskBlocks(result: unknown): AiDetailBlock[] { + const tasks = isObject(result) && Array.isArray(result.tasks) ? result.tasks.filter(isObject) : undefined; + if (!tasks) { + return generic(result, 'result'); + } + const rows: AiDetailRecord[] = tasks.slice(0, MAX_ROWS).map(task => { + const target = isObject(task.entity) ? task.entity : {}; + const progress = isObject(task.progress) ? task.progress : undefined; + const done = progress ? `${aiValueText(progress.successful)}${progress.total !== undefined ? ' / ' + aiValueText(progress.total) : ''}` : undefined; + const meta = [str(task.status) ? aiHumanize(task.status) : undefined, done, str(task.error)].filter(Boolean).join(' · '); + return {entityType: str(target.type) ?? 'CALCULATED_FIELD', id: str(target.id), name: str(target.name) ?? (str(task.type) ? aiHumanize(task.type) : '—'), meta}; + }); + return [{type: 'records', rows, total: tasks.length}]; +} + +function hasId(saved: Values): boolean { + return !!idOf(saved.id); +} + +function endText(value: unknown): string { + const shown = dateText(value); + return shown === '—' ? K + 'now' : shown; +} + +export function aiDateText(date: Date, locale?: string): string { + const now = new Date(); + const today = now.toDateString() === date.toDateString(); + const options: Intl.DateTimeFormatOptions = today ? {hour: 'numeric', minute: '2-digit'} + : date.getFullYear() === now.getFullYear() ? {day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit'} + : {day: 'numeric', month: 'short', year: 'numeric', hour: 'numeric', minute: '2-digit'}; + return new Intl.DateTimeFormat(locale || undefined, options).format(date); +} + +function dateText(value: unknown): string { + const parsed = typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : value; + const date = typeof parsed === 'number' ? new Date(parsed) : typeof parsed === 'string' ? new Date(parsed) : null; + return date && !isNaN(date.getTime()) ? aiDateText(date) : '—'; +} + +const NAMES_CACHE = new Map>(); + +const MAX_CACHED = 500; + +export function aiDetailNames(messages: Array<{from: string; data?: any; references?: Array<{id: string; name: string; entityType: string}>}>, + previous?: AiDetailNames): AiDetailNames { + const names = new Map(); + for (const message of messages) { + let found: Map; + if (message.from === 'ACTION' && message.data?.executionId) { + const key = message.data.executionId + ':' + message.data.status; + found = NAMES_CACHE.get(key); + if (!found) { + found = namesOf(message); + if (NAMES_CACHE.size >= MAX_CACHED) { + NAMES_CACHE.delete(NAMES_CACHE.keys().next().value); + } + NAMES_CACHE.set(key, found); + } + } else if (message.references?.length) { + found = namesOf(message); + } else { + continue; + } + found.forEach((value, id) => !names.has(id) && names.set(id, value)); + } + if (previous && previous.size === names.size && [...names].every(([id, value]) => { + const old = previous.get(id); + return old && old.name === value.name && old.entityType === value.entityType; + })) { + return previous; + } + return names; +} + +function namesOf(message: {from: string; data?: any; references?: Array<{id: string; name: string; entityType: string}>}): Map { + const names = new Map(); + const put = (id: unknown, name: unknown, entityType?: unknown) => { + const key = idOf(id); + const label = str(name); + if (key && label && !names.has(key)) { + names.set(key, {id: key, name: label, entityType: str(entityType) ?? (isObject(id) ? str(id.entityType) : undefined)}); + } + }; + const walk = (value: unknown, entityType: string | undefined, depth: number) => { + if (depth > 6 || !value || typeof value !== 'object') { + return; + } + if (Array.isArray(value)) { + value.forEach(item => walk(item, entityType, depth + 1)); + return; + } + const object = value as Values; + const id = object.entityId ?? object.id; + if (idOf(id) && UUID.test(idOf(id))) { + put(id, object.name ?? object.title ?? object.alias, object.entityType ?? entityType); + } + Object.values(object).forEach(item => walk(item, undefined, depth + 1)); + }; + message.references?.forEach(reference => put(reference.id, reference.name, reference.entityType)); + if (message.from === 'ACTION' && message.data) { + const action = message.data as AiAction; + const values: Values = isObject(aiParse(action.arguments)) ? aiParse(action.arguments) as Values : {}; + const result = aiParse(action.result); + const created = okId(result); + switch (action.tool) { + case 'create_dashboard': + put(created, values.title, 'DASHBOARD'); + break; + case 'generate_device_dashboard': + put(created, undefined, 'DASHBOARD'); + break; + case 'save_device': + put(created ?? savedObject(values).id, savedObject(values).name, 'DEVICE'); + break; + case 'add_dashboard_entity_alias': + put(created, values.alias, 'DASHBOARD_ENTITY_ALIAS'); + break; + case 'add_dashboard_widgets': + widgetRecords(values.widgets, result).forEach(row => put(row.id, row.name, 'DASHBOARD_WIDGET')); + break; + case 'read_entity': + if (isObject(result)) { + put(result.id ?? values.entityId, result.name ?? result.title, values.entityType); + } + break; + case 'search_entities': + for (const section of searchSections(result)) { + walk(section.page.data, section.entityType ?? searchType(values), 0); + } + return names; + } + walk(result, undefined, 0); + } + return names; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html new file mode 100644 index 0000000000..f944b1445f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html @@ -0,0 +1,85 @@ + +@switch (action().status) { + @case ('RUNNING') { + + @if (action().progress) { +
    + @for (stage of action().stages ?? []; track $index) { +
  • {{ stage }}
  • + } +
  • {{ action().progress }}
  • +
+ } + } + @case ('STOPPED') { + + } + @default { +
+ @switch (mark()) { + @case ('fail') { + + } + @case ('web') { + + } + @case ('auto') { + check + } + @default { + + } + } + @let parts = lineParts(); + {{ parts.head }}@if (parts.chip; as chip) {}{{ parts.middle }}{{ parts.tail }}@if (parts.chipLast; as chip) {}@if (hasDetails()) {} +
+
+ @if (failure() !== null || arrival()?.readings?.length || listing() || detail().under.length) { +
+ @if (failure(); as why) { +
+

{{ why }}

+ +
+ } + @if (arrival()?.readings?.length) { +
+ @for (reading of arrival().readings; track reading.key) { + {{ reading.key }}{{ reading.value }} + } +
+ } + @if (listing(); as hub) { +
+ +
+ } + @if (detail().under.length) { + + } +
+ } + @if (hasDetails() && open()) { +
+ @if (grouped()) { + @for (member of groupViews(); track member.id) { +

{{ member.words }}

+ + } + } @else { + + } + @if (took(); as time) { +

{{ time }}

+ } +
+ } +
+ } +} +@if (chip.link) {{{ chip.name }}} @else {{{ chip.name }}} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss new file mode 100644 index 0000000000..9c2ad20d60 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss @@ -0,0 +1,207 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + font-family: var(--tb-mono); + font-size: 15px; + letter-spacing: var(--chat-text-ls); +} + +.k-out { + display: flex; + align-items: flex-start; + gap: 8px; + margin-top: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); + + &.opens { + cursor: pointer; + } + + .k-mark { + flex: none; + display: inline-flex; + justify-content: center; + width: 20px; + height: 22px; + font-size: 22px; + line-height: 22px; + margin-top: 0; + color: var(--tb-ok); + + &.fail { + color: var(--tb-crit); + } + + &.auto { + position: relative; + + > .mat-icon { + display: inline-flex; + justify-content: center; + width: 20px; + height: 22px; + font-size: 22px; + line-height: 22px; + overflow: visible; + color: inherit; + } + } + } + + .k-mark-bolt { + position: absolute; + right: -5px; + bottom: -2px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 11px; + height: 11px; + border-radius: 50%; + background: var(--tb-surface); + box-shadow: 0 0 0 1.5px var(--tb-surface); + color: var(--tb-ok); + + > .mat-icon { + width: 11px; + height: 11px; + font-size: 11px; + line-height: 11px; + } + } + + .k-say { + flex: 1; + min-width: 0; + overflow-wrap: anywhere; + color: var(--tb-ink-76); + } + + .k-keep { + white-space: nowrap; + } + + code.k-ent .k-ent-t { + display: inline-block; + max-width: 180px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + vertical-align: top; + } + + &.opens:hover .k-chev { + color: var(--tb-ink); + } +} + +.k-chev { + display: inline-flex; + align-items: center; + justify-content: center; + margin: 0 0 0 4px; + padding: 0; + border: 0; + border-radius: 4px; + background: none; + color: var(--tb-ink-38); + vertical-align: -2px; + cursor: pointer; + transition: color var(--motion-base, 150ms) var(--ease-standard, ease); + + svg { + display: block; + transition: transform var(--motion-base, 150ms) var(--ease-standard, ease); + } + + &[aria-expanded="true"] svg { + transform: rotate(90deg); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.k-stepcol { + margin: 0 0 0 9px; + padding-left: 18px; + border-left: 1px solid transparent; + font-family: var(--tb-font); + + &.open { + border-left-color: var(--tb-line); + } +} + +.k-under { + display: grid; + gap: 8px; + justify-items: start; + margin-top: 6px; + + > * { + margin: 0; + max-width: 100%; + } +} + +.k-det { + margin: 6px 0 4px; + max-width: 100%; + + > * + * { + margin-top: 8px; + } +} + +.k-took { + margin: 0; + font-family: var(--tb-mono); + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-text-secondary); + font-variant-numeric: tabular-nums; +} + +.k-arrived { + display: flex; + flex-wrap: wrap; + gap: 4px 14px; + margin: 0; + font-size: var(--chat-line, 14px); + line-height: 22px; + + .k-reading { + display: inline-flex; + align-items: baseline; + gap: 6px; + } + + code { + padding: 0 6px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font: 13px/18px var(--tb-mono); + color: var(--tb-ink); + } + + b { + font: 600 13px/18px var(--tb-mono); + color: var(--tb-ink); + } +} + +.k-group-h { + margin: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + color: var(--tb-ink); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts new file mode 100644 index 0000000000..57d8e87421 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts @@ -0,0 +1,287 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { of } from 'rxjs'; +import { catchError, distinctUntilChanged, switchMap } from 'rxjs/operators'; +import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; +import { AiRecordView } from '@home/components/ai/ai-record.models'; +import { EntityId } from '@shared/models/id/entity-id'; +import { TranslateService } from '@ngx-translate/core'; +import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models'; +import { AiDetailFact, AiDetailNames, aiParse, aiStepView } from '@home/components/ai/ai-action-detail.models'; +import { aiFold, aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; +import { + AiAction, + aiConnectionCheckOf, + aiEntityKind, + aiActionDuration, + aiActionText, + aiActionWords, + HUB_INSTALL_TOOLS +} from '@home/components/ai/ai-action.models'; + +@Component({ + selector: 'tb-ai-action-line', + templateUrl: './ai-action-line.component.html', + styleUrls: ['./ai-action-line.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + '[class.run]': 'action().status === "RUNNING"', + '[class.fail]': 'action().status === "FAILURE"', + '[class.stopped]': 'action().status === "STOPPED"' + } +}) +export class AiActionLineComponent { + + action = input.required(); + + private translate = inject(TranslateService); + + private loader = inject(AiRecordLoaderService); + + hubVersionId = computed(() => { + const action = this.action(); + const id = HUB_INSTALL_TOOLS.has(action.tool) && action.status !== 'RUNNING' ? (action.arguments as {versionId?: unknown})?.versionId : null; + return typeof id === 'string' && id ? id : null; + }); + + private groupId = computed(() => { + const affected = this.action().status === 'SUCCESS' ? this.action().affectedEntities ?? [] : []; + const entity = this.action().tool === 'update_group_members' ? affected.find(item => item.entityType === EntityType.ENTITY_GROUP) : affected[0]; + return entity?.entityType === EntityType.ENTITY_GROUP ? entity.id : null; + }); + + private groupView = toSignal(toObservable(this.groupId).pipe( + distinctUntilChanged(), + switchMap(id => id ? this.loader.entity({entityType: EntityType.ENTITY_GROUP, id} as EntityId).pipe(catchError(() => of(null))) : of(null)) + ), {initialValue: null as AiRecordView | null}); + + listing = toSignal(toObservable(this.hubVersionId).pipe( + distinctUntilChanged(), + switchMap(id => id ? this.loader.hub(id).pipe(catchError(() => of(null))) : of(null)) + ), {initialValue: null as AiRecordView | null}); + + words = computed(() => aiActionWords(this.action().tool, this.action().arguments)); + + more = input(0); + + group = input([]); + + grouped = computed(() => this.group().length > 1); + + groupViews = computed(() => this.grouped() ? this.group().map(action => ({ + id: action.executionId, + words: aiActionText(this.translate, aiActionWords(action.tool, action.arguments), 'done'), + view: aiStepView(action, this.names()) + })) : []); + + outcomeText = input(); + + autoApproved = input(false); + + linkEntity = input(true); + + outcomeChip = computed(() => { + if (this.grouped()) { + return null; + } + const affected = this.action().affectedEntities ?? []; + const entity = this.action().tool === 'update_group_members' + ? affected.find(item => item.entityType === EntityType.ENTITY_GROUP) ?? affected[0] + : affected[0]; + const text = this.outcome(); + const match = entity && this.action().status === 'SUCCESS' ? /(?:^|\s)'(.{1,120}?)'(?=$|[\s.,:;!?)])/.exec(text) : null; + if (!match) { + return null; + } + const start = match.index + match[0].indexOf('\''); + const alarmRule = entity.entityType === EntityType.CALCULATED_FIELD && this.isAlarmRule(); + const kind = aiEntityKind(entity.entityType, alarmRule); + const base = alarmRule ? '/alarms/alarm-rules' : baseDetailsPageByEntityType.get(entity.entityType as EntityType); + const groupUrl = entity.entityType === EntityType.ENTITY_GROUP ? this.groupView()?.url : undefined; + return { + before: text.slice(0, start), + name: match[1], + after: text.slice(match.index + match[0].length), + icon: kind.icon, + palette: kind.palette, + link: this.linkEntity() ? (groupUrl ?? (base ? `${base}/${entity.id}` : null)) : null + }; + }); + + private isAlarmRule(): boolean { + const action = this.action(); + if (action.tool === 'save_alarm_rule') { + return true; + } + const result = aiParse(action.result) as {type?: unknown} | null; + return action.tool === 'install_iot_hub_item' && result?.type === 'ALARM_RULE'; + } + + readonly runWords = computed(() => aiActionText(this.translate, this.words(), 'run')); + + running = computed(() => this.more() > 0 + ? this.translate.instant('ai-assistant.work.more', {words: this.runWords(), count: this.more()}) + : this.action().progress ? `${this.runWords()} · ${this.action().progress}` : this.runWords()); + + outcome = computed(() => { + const group = this.group(); + if (group.length < 2) { + return this.outcomeWords(); + } + const words = this.outcomeWords(); + const said = (action: AiAction) => JSON.stringify(aiActionWords(action.tool, action.arguments)); + return group.every(action => said(action) === said(group[0])) + ? this.translate.instant('ai-assistant.action.times', {words, count: group.length}) + : this.translate.instant('ai-assistant.work.more', {words, count: group.length - 1}); + }); + + arrival = computed(() => { + const action = this.action(); + const values = aiParse(action.arguments) as {waitSeconds?: unknown} | null; + if (action.tool !== 'check_connection' || action.status !== 'SUCCESS' || !(Number(values?.waitSeconds) > 0)) { + return null; + } + const check = aiConnectionCheckOf(action.result); + if (!check?.dataArriving) { + return null; + } + const time = new Date(action.startedAt + (action.durationMs ?? 0)).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}); + if (check.gateway) { + return {text: this.translate.instant('ai-assistant.hand-over.gateway-connected', {name: check.name, time}), readings: []}; + } + return { + text: this.translate.instant('ai-assistant.hand-over.' + (!check.keyCount ? 'arrived-message' : check.keyCount === 1 ? 'arrived-key' : 'arrived-keys') + + (check.name ? '-from' : ''), {name: check.name, time, count: check.keyCount}), + readings: check.readings + }; + }); + + private outcomeWords(): string { + const action = this.action(); + if (this.outcomeText()) { + return this.outcomeText(); + } + if (this.arrival()) { + return this.arrival().text; + } + if (action.status === 'FAILURE') { + return this.translate.instant('ai-assistant.action.failed', {words: this.lowerFirst(this.runWords())}); + } + const words = this.words(); + return aiActionText(this.translate, words, 'done'); + } + + names = input(new Map()); + + facts = input([]); + + detail = computed(() => { + const view = aiStepView(this.action(), this.names()); + const facts = this.facts(); + const stages = this.action().stages ?? []; + const done = this.action().status === 'SUCCESS' && this.action().progress ? [...stages, this.action().progress] : stages; + const labelOf = (fact: AiDetailFact) => (fact.raw ? fact.label : this.translate.instant(fact.label) as string).trim().toLowerCase(); + const changed = new Set(facts.filter(fact => fact.change).map(labelOf)); + const own = changed.size ? view.blocks.map(block => block.type === 'facts' ? {...block, rows: block.rows.filter(fact => !changed.has(labelOf(fact)))} : block) + .filter(block => block.type !== 'facts' || block.rows.length) : view.blocks; + const blocks = [...(done.length ? [{type: 'list' as const, label: {key: 'ai-assistant.detail.stages'}, rows: done}] : []), + ...own, ...(facts.length ? [{type: 'facts' as const, rows: facts}] : [])]; + return {...view, blocks}; + }); + + failure = computed(() => { + const action = this.action(); + if (action.status !== 'FAILURE') { + return null; + } + const reason = this.reason(action.result); + const unchanged = this.translate.instant('ai-assistant.failed.nothing-changed'); + return reason ? `${/[.!?…]$/.test(reason) ? reason : reason + '.'} ${unchanged}` : unchanged; + }); + + took = computed(() => { + const group = this.group(); + const ms = group.length > 1 + ? Math.max(...group.map(action => action.startedAt + (action.durationMs ?? 0))) - Math.min(...group.map(action => action.startedAt)) + : this.action().durationMs; + if (this.action().status === 'FAILURE') { + return ''; + } + if (ms == null) { + return this.autoApproved() ? this.translate.instant('ai-assistant.action.done-auto') : ''; + } + const time = aiActionDuration(this.translate, ms); + return this.translate.instant(this.autoApproved() ? 'ai-assistant.action.took-auto' : 'ai-assistant.action.took', {time}); + }); + + hasDetails = computed(() => this.grouped() || !!this.detail().askedFor || !!this.detail().blocks.length || !!this.took()); + + private host = inject(ElementRef); + + panelId = 'k-det-' + Math.random().toString(36).slice(2, 10); + + private key = computed(() => 'action:' + this.action().executionId); + + private fold = aiFold(() => this.key()); + + open = this.fold.open; + + mark = computed<'check' | 'fail' | 'web' | 'auto'>(() => { + if (this.action().status === 'FAILURE') { + return 'fail'; + } + if (this.action().tool === 'search_web') { + return 'web'; + } + return this.autoApproved() ? 'auto' : 'check'; + }); + + lineParts = computed(() => { + const chip = this.outcomeChip(); + const split = (text: string) => { + const trimmed = text.trimEnd(); + const cut = trimmed.lastIndexOf(' ') + 1; + return {start: trimmed.slice(0, cut), last: trimmed.slice(cut)}; + }; + if (!chip) { + const {start, last} = split(this.outcome()); + return {head: start, chip: null, middle: '', tail: last, chipLast: null}; + } + if (!chip.after.trim()) { + return {head: chip.before, chip: null, middle: '', tail: '', chipLast: chip}; + } + const {start, last} = split(chip.after); + return {head: chip.before, chip, middle: start, tail: last, chipLast: null}; + }); + + toggle(event?: Event): void { + event?.stopPropagation(); + if (this.fold.toggle()) { + setTimeout(() => aiRevealOpened(this.host.nativeElement)); + } + } + + lineClicked(event: MouseEvent): void { + if (!this.hasDetails() || (event.target as HTMLElement).closest('a, button, input')) { + return; + } + this.toggle(); + } + + + private reason(result?: string): string | undefined { + const text = result?.trim(); + if (!text || text.startsWith('{') || text.startsWith('[')) { + return undefined; + } + const line = text.split('\n')[0].trim(); + return line.length > 300 ? line.slice(0, 300) + '…' : line; + } + + private lowerFirst(words: string): string { + return words ? words.charAt(0).toLocaleLowerCase() + words.slice(1) : words; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts new file mode 100644 index 0000000000..06f4f75667 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -0,0 +1,930 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { SEVERITY_MARK } from '@home/components/ai/ai-text'; +import { aiQuestionKind } from '@home/components/ai/ai-question.models'; +import { AiQuestion } from '@shared/models/solution-creator.models'; +import { TranslateService } from '@ngx-translate/core'; +import type { AiAction } from '@shared/models/ai-chat.models'; + +export type { AiAction, AiActionStatus } from '@shared/models/ai-chat.models'; + +export type AiSpinKind = 'think' | 'gen' | 'install' | 'listen' | 'stop'; + +export interface AiActionWords { + key: string; + params?: Record; + kind: AiSpinKind; +} + +export type AiWorkMoment = 'reading-request' | 'going-through-results' | 'applying-change' | 'reading-what-to-change'; + +export interface AiWorkState { + moment: AiWorkMoment; + since: number; + headline?: string; +} +const HIDDEN_TOOLS = new Set(['read_current_time']); + +const TOOL_WORDS: Record = { + create_solution: 'create-solution', + install_solution: 'install-solution', + read_entity: 'read-entity', + read_timeseries_keys: 'read-telemetry-keys', + read_attributes: 'read-attributes', + discover_attribute_keys: 'discover-attribute-keys', + save_attributes: 'save-attributes', + delete_attributes: 'delete-attributes', + read_entity_relations: 'read-relations', + read_device_credentials: 'read-credentials', + save_device_credentials: 'save-credentials', + test_converter: 'test-converter', + read_converter_library: 'read-converter-library', + create_dashboard: 'create-dashboard', + generate_device_dashboard: 'generate-device-dashboard', + update_dashboard: 'update-dashboard', + add_dashboard_state: 'add-dashboard-state', + update_dashboard_state: 'update-dashboard-state', + add_dashboard_entity_alias: 'add-entity-alias', + update_dashboard_entity_alias: 'update-entity-alias', + read_dashboard_entity_alias: 'read-entity-alias', + add_dashboard_filter: 'add-dashboard-filter', + update_dashboard_filter: 'update-dashboard-filter', + read_dashboard_filter: 'read-dashboard-filter', + read_dashboard_overview: 'read-dashboard', + update_dashboard_widget: 'update-widget', + place_dashboard_widgets: 'place-widgets', + read_dashboard_widget: 'read-widget', + read_dashboard_html_page: 'read-dashboard-page', + search_iot_hub_devices: 'search-iot-hub', + search_iot_hub: 'search-iot-hub', + read_iot_hub_item: 'read-iot-hub-item', + read_iot_hub_device: 'read-iot-hub-device', + list_installed_iot_hub_items: 'list-installed-iot-hub-items', + install_iot_hub_item: 'install-iot-hub-item', + install_iot_hub_device: 'install-iot-hub-device', + update_group_members: 'update-group-members', + change_owner: 'change-owner', + share_entity_group: 'share-group', + grant_role: 'grant-role', + read_access: 'read-access', + check_dashboard_access: 'check-dashboard-access', + read_transport_endpoints: 'read-connection-settings', + read_api_usage: 'read-api-usage', + read_audit_logs: 'read-audit-logs', + read_tasks: 'read-tasks', + save_image: 'save-image', + read_platform_settings: 'read-platform-settings', + save_relations: 'save-relations', + read_versions: 'read-versions', + read_gateway_status: 'read-gateway-status', + read_ota: 'read-ota', + read_edges: 'read-edges', + read_edge_events: 'read-edge-events', + read_edge_instructions: 'read-edge-instructions', + save_edge: 'save-edge', + assign_to_edge: 'assign-to-edge', + sync_edge: 'sync-edge', + read_rule_chain_templates: 'read-rule-chain-templates', + set_rule_chain_template: 'set-rule-chain-template', + read_agents: 'read-agents', + read_agent_instructions: 'read-agent-instructions', + save_agent: 'save-agent', + install_agent_application: 'install-agent-application', + run_agent_operation: 'run-agent-operation', + read_agent_profiles: 'read-agent-profiles', + save_agent_profile: 'save-agent-profile', + save_agent_app_profile: 'save-agent-app-profile', + run_agent_bulk_action: 'run-agent-bulk-action', + wait_agent_operation: 'wait-agent-operation', + read_white_labeling: 'read-white-labeling', + read_website_brand: 'read-website-brand', + save_white_labeling: 'save-white-labeling', + read_mail_templates: 'read-mail-templates', + save_mail_template: 'save-mail-template', + read_custom_translation: 'read-custom-translation', + save_custom_translation: 'save-custom-translation', + read_custom_menus: 'read-custom-menus', + read_security_settings: 'read-security-settings', + read_mobile_center: 'read-mobile-center', + save_mobile_app: 'save-mobile-app', + save_mobile_bundle: 'save-mobile-bundle', + save_mobile_qr_code: 'save-mobile-qr-code', + read_scheduler_events: 'read-scheduler-events', + save_scheduler_event: 'save-scheduler-event', + create_report_template: 'create-report-template', + update_report_template: 'update-report-template', + add_report_components: 'add-report-components', + update_report_component: 'update-report-component', + move_report_component: 'move-report-component', + save_report_entity_alias: 'save-report-alias', + save_report_filter: 'save-report-filter', + test_report_template: 'test-report-template', + read_reports: 'read-reports', + save_scheduled_report: 'save-scheduled-report', + generate_report: 'generate-report', + read_widgets: 'read-widgets', + read_widget: 'read-widget-type', + create_widget: 'create-widget', + build_widget: 'build-widget', + update_widget: 'update-widget-type', + check_widget: 'check-widget', + save_widgets_bundle: 'save-widgets-bundle', + read_scada_symbols: 'read-scada-symbols', + build_scada_symbol: 'build-scada-symbol', + create_scada_symbol: 'copy-scada-symbol', + update_scada_symbol: 'update-scada-symbol', + check_scada_symbol: 'check-scada-symbol', + create_scada_symbol_widget: 'create-scada-symbol-widget', + save_two_factor_settings: 'save-two-factor-settings', + save_oauth2_domain: 'save-oauth2-domain', + read_my_account: 'read-my-account', + save_my_profile: 'save-my-profile', + save_my_two_factor: 'save-my-two-factor', + update_api_key: 'update-api-key', + read_mail_server: 'read-mail-server', + save_mail_server: 'save-mail-server', + save_custom_menu: 'save-custom-menu', + save_ota_package: 'save-ota-package', + assign_ota_package: 'assign-ota-package', + save_platform_settings: 'save-platform-settings', + read_device_connect_commands: 'read-connect-commands', + read_billing: 'read-billing', + search_web: 'search-web', + send_notification: 'send-notification', + read_notifications: 'read-notifications', + mark_notifications_read: 'mark-notifications-read', + save_notification_settings: 'save-notification-settings', + save_notification_preferences: 'save-notification-preferences' +}; + +const GENERATING_TOOLS: Record = { + set_dashboard_html_page: 'lay-out-dashboard', + reprocess_calculated_field: 'recalculate-history', + commit_version: 'commit-version', + restore_version: 'restore-version', + research_device_connectivity: 'research-device' +}; + +const SAVED_KINDS: Record = { + save_device: ['device', ''], + save_calculated_field: ['calculated-field', ''], + save_alarm_rule: ['alarm-rule', 'alarmRule'], + save_notification_target: ['notification-target', 'target'], + save_notification_template: ['notification-template', 'template'], + save_notification_rule: ['notification-rule', 'rule'], + save_customer: ['customer', ''], + save_user: ['user', ''], + save_entity_group: ['entity-group', ''], + save_role: ['role', ''], + save_entity_view: ['entity-view', ''], + save_asset: ['asset', ''], + save_asset_profile: ['asset-profile', ''], + save_device_profile: ['device-profile', ''], + save_converter: ['converter', ''], + save_integration: ['integration', ''], + save_secret: ['secret', ''], + save_ai_model: ['ai-model', ''], + save_resource: ['resource', ''] +}; + +const SEARCHED_TYPES: Record = { + DEVICE: 'search-devices', + ASSET: 'search-assets', + DASHBOARD: 'search-dashboards', + CUSTOMER: 'search-customers', + USER: 'search-users', + ENTITY_VIEW: 'search-entity-views', + EDGE: 'search-edges', + TENANT: 'search-tenants', + DEVICE_PROFILE: 'search-device-profiles', + ASSET_PROFILE: 'search-asset-profiles', + ENTITY_GROUP: 'search-groups' +}; + +const SEARCHED_FILTERS: Record = { + gateway: 'search-gateways', + alarm: 'search-alarms', + alarmRule: 'search-alarm-rules', + calculatedField: 'search-calculated-fields', + notificationTarget: 'search-notification-targets', + notificationTemplate: 'search-notification-templates', + notificationRule: 'search-notification-rules', + image: 'search-images' +}; + +const DELETED_TARGETS: Record = { + CALCULATED_FIELD: 'delete-calculated-field', + ALARM_RULE: 'delete-alarm-rule', + NOTIFICATION_RULE: 'delete-notification-rule', + NOTIFICATION_TARGET: 'delete-notification-target', + NOTIFICATION_TEMPLATE: 'delete-notification-template', + NOTIFICATION_REQUEST: 'delete-sent-notification', + NOTIFICATION: 'delete-inbox-notification', + DASHBOARD: 'delete-dashboard', + DASHBOARD_WIDGET: 'delete-widget', + DASHBOARD_STATE: 'delete-dashboard-state', + DASHBOARD_ENTITY_ALIAS: 'delete-entity-alias', + DASHBOARD_FILTER: 'delete-dashboard-filter', + DEVICE: 'delete-device', + CUSTOMER: 'delete-customer', + USER: 'delete-user', + ENTITY_GROUP: 'delete-entity-group', + ROLE: 'delete-role', + GROUP_PERMISSION: 'delete-grant', + ALARM: 'delete-alarm', + ASSET: 'delete-asset', + OTA_PACKAGE: 'delete-ota-package', + EDGE: 'delete-edge', + AGENT: 'delete-agent', + AGENT_PROFILE: 'delete-agent-profile', + AGENT_APP_PROFILE: 'delete-agent-app-profile', + IMAGE: 'delete-image', + ENTITY_VIEW: 'delete-entity-view', + ASSET_PROFILE: 'delete-asset-profile', + DEVICE_PROFILE: 'delete-device-profile', + INTEGRATION: 'delete-integration', + CONVERTER: 'delete-converter', + SECRET: 'delete-secret', + AI_MODEL: 'delete-ai-model', + RESOURCE: 'delete-resource', + CUSTOM_MENU: 'delete-custom-menu', + MOBILE_APP: 'delete-mobile-app', + MOBILE_BUNDLE: 'delete-mobile-bundle', + SCHEDULER_EVENT: 'delete-scheduler-event', + REPORT_TEMPLATE: 'delete-report-template', + REPORT_COMPONENT: 'delete-report-component', + REPORT_ENTITY_ALIAS: 'delete-report-alias', + REPORT_FILTER: 'delete-report-filter', + REPORT: 'delete-report', + WIDGET_TYPE: 'delete-widget-type', + WIDGETS_BUNDLE: 'delete-widgets-bundle' +}; + +const ACTION_PREFIX = 'ai-assistant.action.'; + +export const isHiddenAiAction = (tool: string): boolean => HIDDEN_TOOLS.has(tool); + +const READ_VERBS = /^(read|search|discover|fetch|list|check_dashboard_access|research)_/; + +const NEVER_GROUPED: ReadonlySet = new Set(['read_device_credentials', 'read_device_connect_commands', 'check_connection', + 'research_device_connectivity', 'read_iot_hub_device']); + +export function aiGroupableRead(action: AiAction): boolean { + if (action.status !== 'SUCCESS' || NEVER_GROUPED.has(action.tool)) { + return false; + } + return action.readOnly ?? READ_VERBS.test(action.tool + '_'); +} + +export const SUGGEST_PROMPTS_TOOL = 'suggest_next_prompts'; + +export const ASK_USER_TOOL = 'ask_user'; + +export const PROPOSE_PLAN_TOOL = 'propose_plan'; + +export const CITE_SOURCES_TOOL = 'cite_sources'; + +export const HUB_INSTALL_TOOLS: ReadonlySet = new Set(['install_iot_hub_item', 'install_iot_hub_device']); + +export interface AiSource { + url: string; + title: string; + from: string; + quote?: string; + icon: string; + external: boolean; +} + +const humanize = (segment: string): string => { + const words = decodeURIComponent(segment).replace(/\.[a-z]+$/i, '').replace(/[-_]+/g, ' ').trim(); + return words ? words.charAt(0).toUpperCase() + words.slice(1) : ''; +}; + +export function aiSourcesOf(args: unknown): AiSource[] { + const sources = (args as {sources?: unknown})?.sources; + if (!Array.isArray(sources)) { + return []; + } + return sources.flatMap(source => { + if (typeof source?.url !== 'string' || typeof source?.title !== 'string') { + return []; + } + let url: URL; + try { + url = new URL(source.url); + } catch { + return []; + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') { + return []; + } + const host = url.hostname.replace(/^www\./, ''); + const product = host === 'thingsboard.io' || host.endsWith('.thingsboard.io') || host.endsWith('thingsboard.cloud'); + const path = url.pathname.split('/').filter(segment => segment.length > 2).slice(0, 2).map(humanize).filter(Boolean); + return [{ + url: url.href, + title: source.title.trim(), + from: [host, ...path].join(' › '), + quote: typeof source.quote === 'string' && source.quote.trim() ? source.quote.trim() : undefined, + icon: !product ? 'public' : /pricing/i.test(url.pathname) ? 'sell' : 'menu_book', + external: !product + }]; + }).slice(0, 3); +} + +export const UPDATE_PLAN_TOOL = 'update_plan'; + +export const HAND_OVER_TOOL = 'hand_over'; + +export const CHECK_CONNECTION_TOOL = 'check_connection'; + +const KIT_CARD_TOOLS = new Set([SUGGEST_PROMPTS_TOOL, ASK_USER_TOOL, PROPOSE_PLAN_TOOL, UPDATE_PLAN_TOOL, 'write_file', 'create_file', CITE_SOURCES_TOOL, 'show_records', + HAND_OVER_TOOL]); + +export interface AiHandOverValue { + label: string; + value: string; + secret: boolean; + icon: string; +} + +export interface AiHandOverStep { + title: string; + detail?: string; + markdown?: string; + values: AiHandOverValue[]; + file?: string; + done: boolean; +} + +export interface AiHandOverOption { + id: string; + label: string; + icon?: string; + text: string; + steps?: AiHandOverStep[]; +} + +export interface AiHandOver { + title: string; + text?: string; + choice?: {question: string; icon: string; value: string; options: AiHandOverOption[]}; + steps: AiHandOverStep[]; + waitFor?: 'message' | 'uplink' | 'gateway'; + intervalSeconds?: number; + test?: AiHandOverTest; + paste?: {label: string; icon: string; intro: string}; +} + +export interface AiHandOverTest { + hint?: string; + commands: {os: 'macos' | 'windows' | 'linux'; command: string}[]; + sample?: Record; + accessToken?: string; +} + +function handOverTestOf(value: any): AiHandOverTest | undefined { + const commands = (Array.isArray(value?.commands) ? value.commands : []) + .filter(item => ['macos', 'windows', 'linux'].includes(item?.os) && text(item?.command)) + .slice(0, 3) + .map(item => ({os: item.os, command: item.command.trim()})); + if (!commands.length) { + return undefined; + } + let sample: Record | undefined; + try { + const parsed = typeof value.sample === 'string' ? JSON.parse(value.sample) : value.sample; + sample = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined; + } catch { + sample = undefined; + } + const accessToken = text(value.accessToken); + return {hint: text(value.hint), commands, ...(sample && accessToken ? {sample, accessToken} : {})}; +} + +const text = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined; + +const ICON_NAME = /^[a-z0-9_]{2,40}$/; + +const iconOf = (value: unknown, fallback: string): string => typeof value === 'string' && ICON_NAME.test(value) ? value : fallback; + +export function aiHandOverOf(args: unknown): AiHandOver | null { + const values = (args ?? {}) as Record; + const title = text(values.title); + if (!title) { + return null; + } + const steps = handOverStepsOf(values.steps); + const options: AiHandOverOption[] = (Array.isArray(values.choice?.options) ? values.choice.options : []) + .filter(option => text(option?.id) && text(option?.label)) + .slice(0, 4) + .map(option => ({id: text(option.id), label: text(option.label), icon: typeof option.icon === 'string' && ICON_NAME.test(option.icon) ? option.icon : undefined, + text: text(option.text) ?? '', steps: handOverStepsOf(option.steps)})); + const choice = options.length >= 2 ? { + question: text(values.choice.question) ?? '', + icon: iconOf(values.choice.icon, 'tune'), + value: options.some(option => option.id === values.choice.value) ? values.choice.value : options[0].id, + options + } : undefined; + const waitFor = ['message', 'uplink', 'gateway'].includes(values.waitFor) ? values.waitFor : undefined; + const interval = Number(values.intervalSeconds); + return {title, text: text(values.text), choice, steps, waitFor, + intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined, + test: handOverTestOf(values.test), paste: handOverPasteOf(values.paste)}; +} + +function handOverPasteOf(value: any): AiHandOver['paste'] { + const label = text(value?.label); + const intro = text(value?.intro); + return label && intro ? {label, intro, icon: iconOf(value.icon, 'terminal')} : undefined; +} + +function handOverStepsOf(list: unknown): AiHandOverStep[] { + return (Array.isArray(list) ? list : []) + .filter(step => text(step?.title)) + .slice(0, 6) + .map(step => ({ + title: text(step.title), + detail: text(step.detail), + markdown: text(step.markdown), + file: text(step.file), + done: step.done === true, + values: (Array.isArray(step.values) ? step.values : []) + .filter(value => text(value?.label) && typeof value?.value === 'string' && value.value) + .slice(0, 4) + .map(value => ({label: text(value.label), value: value.value, secret: value.secret === true, + icon: iconOf(value.icon, value.secret === true ? 'key' : /^https?:\/\//.test(value.value) ? 'link' : 'label')})) + })); +} + +export interface AiConnectionCheck { + dataArriving: boolean; + failedStep?: string; + name?: string; + note?: string; + readings: {key: string; value: string}[]; + keyCount: number; + gateway: boolean; +} + +export function aiConnectionCheckOf(result: unknown): AiConnectionCheck | null { + let values: any = result; + if (typeof result === 'string') { + try { + values = JSON.parse(result); + } catch { + return null; + } + } + if (!values || typeof values !== 'object' || !values.steps) { + return null; + } + const readings: {key: string; value: string}[] = []; + const add = (telemetry: unknown) => Object.entries(telemetry && typeof telemetry === 'object' ? telemetry : {}) + .map(([key, item]) => ({key, value: String((item as any)?.value ?? '')})) + .filter(reading => !/^\s*[{[]/.test(reading.value)) + .forEach(reading => readings.push(reading)); + const gateway = values.gateway === true; + if (!gateway) { + add(values.telemetry); + } + (Array.isArray(values.devices) ? values.devices : []).forEach(device => add(device?.telemetry)); + return {dataArriving: values.steps.dataArriving === true, failedStep: text(values.failedStep), name: text(values.name), + note: text(values.note), readings: readings.slice(0, 6), keyCount: new Set(readings.map(reading => reading.key)).size, gateway}; +} + +export const isKitCardTool = (tool: string): boolean => KIT_CARD_TOOLS.has(tool); + +const PLAN_NEEDS = new Set(['device', 'account', 'computer', 'phone']); + +export interface AiPlanStep { + text: string; + by: 'agent' | 'user'; + needs?: string; + optional?: boolean; + makes?: {type: string; name: string}[]; +} + +export interface AiPlanProgress { + done: number[]; + now?: number; + skipped: number[]; +} + +export type AiPlanMark = 'todo' | 'now' | 'done' | 'off'; + +export interface AiPlanStatus { + marks: AiPlanMark[]; + done: number; + counted: number; + now: number; + finished: boolean; +} + +export function aiPlanStatus(steps: AiPlanStep[], progress: AiPlanProgress | null): AiPlanStatus { + const marks = steps.map((_, index): AiPlanMark => { + const number = index + 1; + if (progress?.done.includes(number)) { + return 'done'; + } + if (progress?.skipped.includes(number)) { + return 'off'; + } + return progress?.now === number ? 'now' : 'todo'; + }); + return { + marks, + done: marks.filter(mark => mark === 'done').length, + counted: marks.filter(mark => mark !== 'off').length, + now: progress?.now ?? marks.findIndex(mark => mark !== 'done' && mark !== 'off') + 1, + finished: !!progress && marks.every(mark => mark === 'done' || mark === 'off') + }; +} + +export function aiPlanOf(args: unknown): AiPlanStep[] { + const steps = (args as {steps?: unknown})?.steps; + if (!Array.isArray(steps)) { + return []; + } + return steps + .filter(step => typeof step?.text === 'string' && step.text.trim()) + .slice(0, 8) + .map(step => ({ + text: step.text.trim(), + by: step.by === 'user' ? 'user' : 'agent', + needs: step.by === 'user' && PLAN_NEEDS.has(step.needs) ? step.needs : undefined, + optional: step.optional === true, + makes: Array.isArray(step.makes) + ? step.makes.filter(made => typeof made?.type === 'string' && typeof made?.name === 'string' && made.name.trim()).slice(0, 4) + : [] + })); +} + +export function aiPlanProgressOf(args: unknown): AiPlanProgress { + const values = (args ?? {}) as {done?: unknown; now?: unknown; skipped?: unknown}; + const numbers = (list: unknown): number[] => Array.isArray(list) ? list.filter(item => Number.isInteger(item) && item > 0) : []; + return { + done: numbers(values.done), + now: Number.isInteger(values.now) && (values.now as number) > 0 ? values.now as number : undefined, + skipped: numbers(values.skipped) + }; +} + +export type AiSeverityWord = (severity: string) => string; + +const PLAIN_SEVERITY_WORD: AiSeverityWord = severity => severity.charAt(0) + severity.slice(1).toLowerCase(); + +export function aiQuestionsOf(args: unknown, word: AiSeverityWord = PLAIN_SEVERITY_WORD): AiQuestion[] { + const questions = (args as {questions?: unknown})?.questions; + if (!Array.isArray(questions)) { + return []; + } + return questions + .filter(question => typeof question?.question === 'string' && question.question.trim()) + .slice(0, 3) + .map((question, index) => ({ + id: typeof question.id === 'string' && question.id ? question.id : 'q' + index, + question: aiSeverityWords(question.question.trim(), word), + parts: aiSeverityParts(question.question.trim()), + why: typeof question.why === 'string' ? aiSeverityWords(question.why, word) : undefined, + options: (Array.isArray(question.options) ? question.options : []) + .filter(option => typeof option?.label === 'string' && option.label.trim()) + .slice(0, 6) + .map(option => ({label: aiSeverityWords(option.label.trim(), word), hint: typeof option.hint === 'string' ? aiSeverityWords(option.hint, word) : undefined})), + recommended: Array.isArray(question.recommended) ? question.recommended.filter(label => typeof label === 'string') : undefined, + multiple: question.multiple === true, + secret: question.secret === true && !(Array.isArray(question.options) && question.options.length), + color: question.color === true && question.multiple !== true, + other: aiQuestionOther(question.other), + number: aiQuestionNumber(question.number), + date: question.date === true && question.multiple !== true && Array.isArray(question.options) && question.options.length > 0 + } as AiQuestion)) + .map(question => ({...question, kind: aiQuestionKind(question)})); +} + +const SEVERITY_MARKS = new RegExp(SEVERITY_MARK.source, 'g'); + +export function aiSeverityWords(text: string, word: AiSeverityWord = PLAIN_SEVERITY_WORD): string { + return text.replace(SEVERITY_MARKS, (_, severity: string) => word(severity)); +} + +function aiSeverityParts(text: string): Array<{text?: string; severity?: string}> | undefined { + if (!new RegExp(SEVERITY_MARKS.source).test(text)) { + return undefined; + } + return text.split(new RegExp(SEVERITY_MARKS.source)).map((part, index) => index % 2 ? {severity: part} : {text: part}).filter(part => part.severity || part.text); +} + +function aiQuestionOther(other: any): AiQuestion['other'] { + const label = typeof other?.label === 'string' && other.label.trim() ? other.label.trim() : undefined; + const placeholder = typeof other?.placeholder === 'string' && other.placeholder.trim() ? other.placeholder.trim() : undefined; + return label || placeholder ? {label, placeholder} : undefined; +} + +function aiQuestionNumber(number: any): AiQuestion['number'] { + if (!number || typeof number !== 'object') { + return undefined; + } + const finite = (value: unknown) => typeof value === 'number' && isFinite(value) ? value : undefined; + const size = number.size === 'short' || number.size === 'medium' ? number.size : 'long'; + return {suggested: finite(number.suggested), unit: typeof number.unit === 'string' && number.unit.trim() ? number.unit.trim() : undefined, + step: finite(number.step), size}; +} + +const MAX_PROMPTS = 4; + +const PROMPT_ICONS: Record = {domain: 'mdi:cube-outline', rule: 'mdi:bell-cog', functions: 'mdi:function-variant'}; + +export interface AiPrompt { + text: string; + icon?: string; +} + +export function aiTurnPrompts(messages: Array<{from: string; data?: any}>): AiPrompt[] { + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i]; + if (message.from === 'USER') { + return []; + } + if (message.from === 'ACTION' && message.data?.tool === SUGGEST_PROMPTS_TOOL) { + return aiPromptsOf(message.data.arguments); + } + } + return []; +} + +export function aiPromptsOf(args: unknown): AiPrompt[] { + const prompts = (args as {prompts?: unknown})?.prompts; + if (!Array.isArray(prompts)) { + return []; + } + return prompts + .filter(prompt => typeof prompt?.text === 'string' && prompt.text.trim()) + .map(prompt => ({text: prompt.text.trim(), icon: typeof prompt.icon === 'string' && /^[a-z0-9_]+$/.test(prompt.icon) ? PROMPT_ICONS[prompt.icon] ?? prompt.icon : undefined})) + .slice(0, MAX_PROMPTS); +} + +const ALARM_UPDATE_ACTIONS = ['acknowledge', 'assign', 'clear', 'comment', 'unassign']; + +export const alarmUpdateAction = (action: unknown): string => { + const name = String(action ?? '').toLowerCase(); + return ALARM_UPDATE_ACTIONS.includes(name) ? name : 'other'; +}; + +const PART_WORDS = new Set(['html', 'css', 'js', 'resources', 'settingsForm', 'dataKeySettingsForm', 'latestDataKeySettingsForm', + 'defaultConfig', 'svg', 'metadata', 'functions', 'behavior', 'properties']); + +export interface AiWordList { + words: string[]; + commas?: boolean; +} + +export const aiPartWord = (part: string): string => PART_WORDS.has(part) ? 'ai-assistant.part.' + part : part; + +export const aiPartTitle = (part: string): string => PART_WORDS.has(part) ? 'ai-assistant.part-title.' + part : part.charAt(0).toUpperCase() + part.slice(1); + +export const aiWordList = (words: string[], commas = false): AiWordList => commas ? {words, commas} : {words}; + +export const isAiWordList = (value: unknown): value is AiWordList => !!value && typeof value === 'object' && Array.isArray((value as AiWordList).words); + +export function aiJoinWords(translate: TranslateService, list: AiWordList): string { + const said = list.words.map(word => word.startsWith('ai-assistant.') ? translate.instant(word) as string : word); + if (said.length < 2) { + return said.join(''); + } + const more = (first: string, rest: string) => translate.instant('ai-assistant.list.more', {first, rest}) as string; + const last = list.commas ? more(said[said.length - 2], said[said.length - 1]) + : translate.instant('ai-assistant.list.pair', {first: said[said.length - 2], second: said[said.length - 1]}) as string; + return said.slice(0, -2).reduceRight((rest, first) => more(first, rest), last); +} + +const THING_KEYS: Record = { + DASHBOARD_WIDGET: 'widget', + DASHBOARD_STATE: 'state', + DASHBOARD_ENTITY_ALIAS: 'alias', + DASHBOARD_FILTER: 'filter' +}; + +export function aiThingWord(translate: TranslateService, entityType: string | undefined, fallback: string): string { + if (!entityType) { + return translate.instant(fallback); + } + const key = 'ai-assistant.detail.thing.' + (THING_KEYS[entityType] ?? entityType.toLowerCase().replace(/_/g, '-')); + const word: string = translate.instant(key); + return word !== key ? word : translate.instant(fallback); +} + +export function aiActionText(translate: TranslateService, words: AiActionWords, phase: 'run' | 'done'): string { + const params: Record = {}; + for (const [key, value] of Object.entries(words.params ?? {})) { + params[key] = isAiWordList(value) ? aiJoinWords(translate, value) : value; + } + return translate.instant(words.key + '.' + phase, params); +} + +export function widgetParts(values: Record): string[] { + const parts = Array.isArray(values.sections) ? values.sections.map(String) : []; + return parts.length ? parts : typeof values.section === 'string' ? [values.section] : ['overview']; +} + +export function aiActionWords(tool: string, args: unknown): AiActionWords { + const values = (args && typeof args === 'object' ? args : {}) as Record; + if (GENERATING_TOOLS[tool]) { + return {key: ACTION_PREFIX + GENERATING_TOOLS[tool], kind: 'gen'}; + } + if (SAVED_KINDS[tool]) { + const [kind, nested] = SAVED_KINDS[tool]; + return {key: ACTION_PREFIX + (hasId(nested ? values[nested] : values) ? 'update-' : 'create-') + kind, kind: 'think'}; + } + switch (tool) { + case 'add_dashboard_widgets': + return {key: ACTION_PREFIX + (Array.isArray(values.widgets) && values.widgets.length === 1 ? 'add-widget' : 'add-widgets'), kind: 'think'}; + case 'add_scada_connectors': + return {key: ACTION_PREFIX + 'add-scada-connectors', kind: 'think'}; + case 'read_widget': { + const parts = widgetParts(values).filter(part => part !== 'overview'); + return parts.length && !parts.includes('all') + ? {key: ACTION_PREFIX + 'read-widget-parts', params: {parts: aiWordList(parts.map(aiPartWord))}, kind: 'think'} + : {key: ACTION_PREFIX + 'read-widget-type', kind: 'think'}; + } + case 'read_scada_symbol': { + const parts = widgetParts(values).filter(part => part !== 'overview'); + return parts.length && !parts.includes('all') + ? {key: ACTION_PREFIX + 'read-scada-symbol-parts', params: {parts: aiWordList(parts.map(aiPartWord))}, kind: 'think'} + : {key: ACTION_PREFIX + 'read-scada-symbol', kind: 'think'}; + } + case 'read_report_template': + return {key: ACTION_PREFIX + (typeof values.path === 'string' && values.path ? 'read-report-component' : 'read-report-template'), kind: 'think'}; + case 'search_entities': + return {key: ACTION_PREFIX + searchedWords(values), kind: 'think'}; + case 'update_alarms': + return {key: ACTION_PREFIX + 'update-alarms.' + alarmUpdateAction(values.action), kind: 'think'}; + case 'read_timeseries': + return {key: ACTION_PREFIX + telemetryWords(values), kind: 'think'}; + case 'delete': + return {key: ACTION_PREFIX + (DELETED_TARGETS[values.targetType] ?? 'delete-other'), kind: 'think'}; + case 'check_connection': + return {key: ACTION_PREFIX + (Number(values.waitSeconds) > 0 ? 'wait-for-data' : 'check-connection'), kind: 'think'}; + case 'fetch_web_page': { + const site = siteOf(values.url); + return site ? {key: ACTION_PREFIX + 'read-site', params: {site}, kind: 'think'} : {key: ACTION_PREFIX + 'read-page', kind: 'think'}; + } + } + return {key: ACTION_PREFIX + (TOOL_WORDS[tool] ?? 'other'), kind: 'think'}; +} + +export function aiActionDuration(translate: TranslateService, ms: number): string { + if (ms < 1000) { + return translate.instant('ai-assistant.duration.seconds', {seconds: Math.max(Math.round(ms / 100), 1) / 10}); + } + const seconds = Math.round(ms / 1000); + if (seconds < 60) { + return translate.instant('ai-assistant.duration.seconds', {seconds}); + } + const rest = seconds % 60; + return rest ? translate.instant('ai-assistant.duration.minutes-seconds', {minutes: Math.floor(seconds / 60), seconds: rest}) + : translate.instant('ai-assistant.duration.minutes', {minutes: seconds / 60}); +} + +export function aiWorkClock(ms: number): string { + const seconds = Math.round(ms / 1000); + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; +} + +function hasId(value: unknown): boolean { + let object = value; + if (typeof value === 'string') { + try { + object = JSON.parse(value); + } catch { + return false; + } + } + const id = (object as {id?: unknown})?.id; + return !!id && (typeof id === 'string' || typeof (id as {id?: unknown}).id === 'string'); +} + +function searchedWords(values: Record): string { + const filter = values.entityFilter ?? values; + if (typeof filter?.filterType === 'string' && SEARCHED_FILTERS[filter.filterType]) { + return SEARCHED_FILTERS[filter.filterType]; + } + if (filter?.statusList || filter?.severityList || filter?.typeList || filter?.searchPropagatedAlarms !== undefined) { + return 'search-alarms'; + } + const types = new Set(); + const add = (type: unknown) => typeof type === 'string' && types.add(type); + add(filter?.entityType); + add(filter?.singleEntity?.entityType); + if (filter?.deviceType || filter?.deviceTypes || filter?.filterType === 'deviceType') { + types.add('DEVICE'); + } + if (filter?.assetType || filter?.assetTypes || filter?.filterType === 'assetType') { + types.add('ASSET'); + } + (filter?.filters ?? []).forEach((relationFilter: any) => (relationFilter?.entityTypes ?? []).forEach(add)); + if (types.size === 1) { + return SEARCHED_TYPES[[...types][0]] ?? 'search-tenant'; + } + return 'search-tenant'; +} + +function telemetryWords(values: Record): string { + switch (values.mode) { + case 'LATEST': + return 'read-latest-values'; + case 'KEYS': + return 'read-telemetry-keys'; + default: + return values.mode ? 'read-history' : 'read-latest-values'; + } +} + +function siteOf(url: unknown): string | undefined { + if (typeof url !== 'string') { + return undefined; + } + try { + return new URL(url).hostname.replace(/^www\./, '') || undefined; + } catch { + return undefined; + } +} + +export type AiEntityPalette = 'device' | 'path' | 'chain' | 'rule' | 'view' | 'people' | 'solution' | 'none'; + +export interface AiEntityKind { + icon: string; + palette: AiEntityPalette; +} + +const ENTITY_KINDS: Record = { + DEVICE: {icon: 'memory', palette: 'device'}, + GATEWAY: {icon: 'lan', palette: 'device'}, + ENTITY_VIEW: {icon: 'view_quilt', palette: 'device'}, + EDGE: {icon: 'router', palette: 'device'}, + DEVICE_PROFILE: {icon: 'mdi:alpha-d-box', palette: 'device'}, + ASSET: {icon: 'mdi:cube-outline', palette: 'device'}, + ASSET_PROFILE: {icon: 'mdi:alpha-a-box', palette: 'device'}, + AGENT: {icon: 'settings_applications', palette: 'device'}, + AGENT_APPLICATION: {icon: 'apps', palette: 'device'}, + AGENT_PROFILE: {icon: 'group_work', palette: 'device'}, + AGENT_APP_PROFILE: {icon: 'description', palette: 'device'}, + OTA_PACKAGE: {icon: 'system_update_alt', palette: 'device'}, + INTEGRATION: {icon: 'input', palette: 'path'}, + CONVERTER: {icon: 'transform', palette: 'path'}, + CALCULATED_FIELD: {icon: 'mdi:function-variant', palette: 'path'}, + RULE_CHAIN: {icon: 'settings_ethernet', palette: 'chain'}, + EDGE_RULE_CHAIN: {icon: 'settings_ethernet', palette: 'chain'}, + SCHEDULER_EVENT: {icon: 'schedule', palette: 'chain'}, + ALARM_RULE: {icon: 'mdi:bell-cog', palette: 'rule'}, + ALARM: {icon: 'notification_important', palette: 'rule'}, + NOTIFICATION_RULE: {icon: 'mdi:message-cog', palette: 'rule'}, + DASHBOARD: {icon: 'dashboard', palette: 'view'}, + DASHBOARD_WIDGET: {icon: 'widgets', palette: 'view'}, + WIDGET_TYPE: {icon: 'widgets', palette: 'view'}, + WIDGETS_BUNDLE: {icon: 'now_widgets', palette: 'view'}, + DASHBOARD_STATE: {icon: 'layers', palette: 'view'}, + DASHBOARD_ENTITY_ALIAS: {icon: 'label', palette: 'view'}, + DASHBOARD_FILTER: {icon: 'filter_list', palette: 'view'}, + REPORT_TEMPLATE: {icon: 'edit_document', palette: 'view'}, + REPORT_COMPONENT: {icon: 'view_agenda', palette: 'view'}, + REPORT_ENTITY_ALIAS: {icon: 'label', palette: 'view'}, + REPORT_FILTER: {icon: 'filter_list', palette: 'view'}, + SCHEDULED_REPORT: {icon: 'mdi:file-clock', palette: 'view'}, + REPORT: {icon: 'summarize', palette: 'view'}, + MAIL_TEMPLATE: {icon: 'drafts', palette: 'view'}, + NOTIFICATION_TEMPLATE: {icon: 'mdi:message-draw', palette: 'view'}, + CUSTOM_TRANSLATION: {icon: 'translate', palette: 'view'}, + CUSTOM_MENU: {icon: 'menu', palette: 'view'}, + MOBILE_APP: {icon: 'smartphone', palette: 'view'}, + MOBILE_BUNDLE: {icon: 'phonelink_setup', palette: 'view'}, + MOBILE_QR_CODE: {icon: 'qr_code', palette: 'view'}, + IMAGE: {icon: 'image', palette: 'view'}, + SCADA_SYMBOL: {icon: 'view_in_ar', palette: 'view'}, + CUSTOMER: {icon: 'supervisor_account', palette: 'people'}, + USER: {icon: 'account_circle', palette: 'people'}, + TENANT: {icon: 'business', palette: 'people'}, + MY_PROFILE: {icon: 'account_circle', palette: 'people'}, + NOTIFICATION_TARGET: {icon: 'contacts', palette: 'people'}, + ROLE: {icon: 'badge', palette: 'people'}, + GROUP_PERMISSION: {icon: 'verified_user', palette: 'people'}, + SOLUTION_TEMPLATE: {icon: 'dashboard_customize', palette: 'solution'}, + IOT_HUB: {icon: 'hub', palette: 'solution'}, + MAIL_SERVER: {icon: 'mail', palette: 'none'}, + TWO_FACTOR_SETTINGS: {icon: 'mdi:two-factor-authentication', palette: 'none'}, + MY_TWO_FACTOR: {icon: 'mdi:two-factor-authentication', palette: 'none'}, + DOMAIN: {icon: 'language', palette: 'none'}, + API_KEY: {icon: 'vpn_key', palette: 'none'}, + TB_RESOURCE: {icon: 'mdi:rhombus-split', palette: 'none'}, + SECRET: {icon: 'lock', palette: 'none'}, + ENTITY_GROUP: {icon: 'folder', palette: 'none'} +}; + +export function aiEntityKind(entityType: string, alarmRule = false, groupType?: string | null): AiEntityKind { + if (entityType === 'ENTITY_GROUP') { + return {icon: 'folder', palette: (groupType && ENTITY_KINDS[groupType]?.palette) || 'none'}; + } + return ENTITY_KINDS[alarmRule ? 'ALARM_RULE' : entityType] ?? {icon: 'category', palette: 'none'}; +} + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html index ce8881931c..5f60cad9e6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html @@ -4,47 +4,102 @@ SPDX-License-Identifier: BUSL-1.1 --> -@switch (state) { - @case ('pending') { -
{{ data.title ?? ('ai-assistant.action-approval-required' | translate) }}
-
{{ data.message }}
-
- - -
- +@if (handedOver) { + +} @else { +
+
{{ headText }}
+ @if (listing; as hub) { + + } @else if (review) { + } - @case ('executing') { -
- - {{ data.executing ?? ('ai-assistant.processing' | translate) }} -
+ @if (state === 'pending' || state === 'waiting') { + @if (!review) { +

{{ data.message }}

+ } + @if (facts.length) { +
+ @for (fact of facts; track $index) { +
@if (fact.labelCode) { {{ fact.label }} } @else { {{ fact.label }} }
+
@if (fact.chip; as chip) { @if (chip.image) { } @else if (chip.icon) { }{{ fact.value }} } @else if (fact.image) { } @else if (fact.valueCode) { {{ fact.value }} } @else { {{ fact.value }} }
+ } +
+ } + @for (block of codeBlocks; track $index) { + @if (block.current !== undefined) { +
{{ block.current }}
+ } +
{{ block.value }}
+ } + @if (changes.length) { +
+ @for (change of changes; track $index) { +
+
@if (change.labelCode) { {{ change.label }} } @else { {{ change.label }} }
+
+ @if (change.currentImage) { } @else { {{ change.current }} } + + {{ 'ai-assistant.review.changes-to' | translate }} + @if (change.image) { } @else { {{ change.value }} } +
+
+ } + @if (unchanged.length && showUnchanged) { + + } +
+ @if (unchanged.length) { + + } + } @else if (unchanged.length) { +
+ +
+ } +
+ + +
+ @if (denying) { +
+ +
+ } + } @else if (state === 'denied') { +

{{ 'ai-assistant.review.denied-text' | translate }}

} - @case ('approved') { -
- {{ resultIcon }} - {{ completedExecution?.message || ('ai-assistant.approved' | translate) }} -
- } - @case ('denied') { -
- {{ resultIcon }} - {{ completedExecution?.message || ('ai-assistant.denied' | translate) }} -
- } - @case ('error') { -
- {{ resultIcon }} - {{ completedExecution?.message || ('ai-assistant.error' | translate) }} -
+ @if (data.time) { + } +
} + +
+ @for (same of unchanged; track $index) { +
+
@if (same.labelCode) { {{ same.label }} } @else { {{ same.label }} }
+
{{ same.value }}
+
+ } +
+
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss index 41b1e862cf..829dc96e3c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss @@ -2,82 +2,4 @@ // SPDX-License-Identifier: BUSL-1.1 :host { display: block; - border: 1px solid rgba(0, 0, 0, 0.12); - border-radius: 12px; - padding: 16px; - - &.executing { - color: rgba(0, 0, 0, 0.76); - } - - &.approved { - color: #198038; - background-color: rgba(25, 128, 56, 0.06); - } - - &.denied { - color: rgba(0, 0, 0, 0.54); - background-color: rgba(0, 0, 0, 0.06); - } - - &.error { - color: var(--tb-crit); - background-color: color-mix(in srgb, var(--tb-crit) 8%, transparent); - } - - .approval-title { - margin-bottom: 8px; - font-weight: 500; - font-size: 16px; - line-height: 24px; - letter-spacing: 0.25px; - } - - .approval-content { - font-size: 14px; - line-height: 20px; - margin-bottom: 16px; - color: rgba(0, 0, 0, 0.54); - letter-spacing: 0.25px; - } - - .approval-actions { - display: flex; - gap: 8px; - justify-content: flex-end; - - .approved { - flex: 1; - --mat-button-filled-label-text-color: #FFF; - --mat-button-filled-container-color: #198038; - } - - .danger { - flex: 1; - --mat-button-filled-label-text-color: #FFF; - --mat-button-filled-container-color: #d32f2f; - } - - .denied { - flex: 1; - --mat-button-outlined-label-text-color: #FF5722; - } - } - - .approve-all { - width: 100%; - margin-top: 8px; - --mat-button-text-label-text-color: rgba(0, 0, 0, 0.54); - --mat-button-text-container-height: 32px; - } - - .approval-result { - display: flex; - align-items: center; - gap: 8px; - font-size: 16px; - font-weight: 500; - line-height: 24px; - letter-spacing: 0.25px; - } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts index fe6b67e07b..b8d19aa09f 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts @@ -1,99 +1,543 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { + AfterViewChecked, + ChangeDetectionStrategy, ChangeDetectorRef, Component, + ElementRef, EventEmitter, - HostBinding, inject, Input, OnChanges, Output, - SimpleChanges + SimpleChanges, + ViewChild } from '@angular/core'; +import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; +import { TranslateService } from '@ngx-translate/core'; +import { ClipboardService } from 'ngx-clipboard'; +import { IntegrationType, integrationTypeInfoMap } from '@shared/models/integration.models'; +import { ConverterType, converterTypeTranslationMap } from '@shared/models/converter.models'; +import { decorateCodeBlocks } from '@home/components/ai/ai-code-block'; import { + AiApprovalReview, + AiReviewField, ApprovalResult, ToolApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; +import { AiAction, HUB_INSTALL_TOOLS } from '@home/components/ai/ai-action.models'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { MailTemplate, mailTemplateTranslations } from '@shared/models/settings.models'; -export type ApprovalCardState = 'pending' | 'executing' | 'approved' | 'denied' | 'error'; +export type ApprovalCardState = 'pending' | 'waiting' | 'approved' | 'auto' | 'denied'; + +import { AiDetailFact } from '@home/components/ai/ai-action-detail.models'; +import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; +import { AiRecordView } from '@home/components/ai/ai-record.models'; + +export interface AiReviewRow { + label: string; + labelCode: boolean; + valueCode: boolean; + current?: string; + value: string; + image?: boolean; + currentImage?: boolean; + code?: boolean; + lang?: string; + chip?: {icon?: string; image?: string}; +} + +const MAX_FIELDS = 5; + +const DETAIL_TOKENS = new Set(['server-attributes', 'shared-attributes']); + +const ATTRIBUTE_TOOLS = new Set(['save_attributes', 'delete_attributes']); + +const VALUE_TOKENS: Record = { + undo: ['none'], + defaultDashboard: ['none'], + homeDashboard: ['none'], + clears: ['yes', 'no'], + edgeTemplateRoot: ['yes'], + autoAssign: ['yes', 'no'], + removeVolumes: ['yes', 'no'], + default: ['yes'], + operation: ['restart', 'update', 'upgrade', 'delete', 'cancel', 'upgrade agent'] +}; + +const CODE_FIELDS = new Set(['arguments', 'expression', 'output']); + +const HEAD_VERBS = new Set(['create', 'update', 'delete', 'install', 'acknowledge', 'clear', 'assign', 'unassign']); +const REVIEW_VERBS = new Set(['install', 'restart', 'update', 'upgrade', 'upgrade-agent', 'delete', 'cancel', 'sync', 'acknowledge', 'clear', 'assign', 'unassign']); + +const IMAGE_FIELDS = new Set(['widget-image', 'scada-symbol', 'dashboard-image']); + +const BLOCK_FIELDS = new Set(['script']); + +const DETAILED_TOOLS = new Set(['save_converter']); + +const JSON_BLOCK_AT = 80; + +function prettyJson(value: string | undefined | null): string | null { + const trimmed = value?.trim() ?? ''; + if (trimmed.length < JSON_BLOCK_AT || !/^[[{]/.test(trimmed)) { + return null; + } + try { + const parsed = JSON.parse(trimmed); + return parsed && typeof parsed === 'object' ? JSON.stringify(parsed, null, 2) : null; + } catch { + return null; + } +} + +const DIFF_CONTEXT = 2; + +function withoutTs(text: string): string { + try { + const parsed = JSON.parse(text); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && 'ts' in parsed) { + const rest = {...parsed}; + delete rest.ts; + return JSON.stringify(rest, null, 2); + } + } catch { + } + return text; +} + +function lineDiff(before: string, after: string): string { + const a = before.split('\n'); + const b = after.split('\n'); + const table: number[][] = Array.from({length: a.length + 1}, () => new Array(b.length + 1).fill(0)); + for (let i = a.length - 1; i >= 0; i--) { + for (let j = b.length - 1; j >= 0; j--) { + table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]); + } + } + const rows: {mark: ' ' | '-' | '+'; text: string}[] = []; + let i = 0; + let j = 0; + while (i < a.length || j < b.length) { + if (i < a.length && j < b.length && a[i] === b[j]) { + rows.push({mark: ' ', text: a[i++]}); + j++; + } else if (i < a.length && (j >= b.length || table[i + 1][j] >= table[i][j + 1])) { + rows.push({mark: '-', text: a[i++]}); + } else { + rows.push({mark: '+', text: b[j++]}); + } + } + const keep = rows.map((row, index) => row.mark !== ' ' + || rows.slice(Math.max(0, index - DIFF_CONTEXT), index + DIFF_CONTEXT + 1).some(near => near.mark !== ' ')); + const out: string[] = []; + rows.forEach((row, index) => { + if (keep[index]) { + out.push(row.mark + ' ' + row.text); + } else if (keep[index - 1] || index === 0) { + out.push(' …'); + } + }); + return out.join('\n'); +} + +const isBlock = (field: AiReviewField): boolean => BLOCK_FIELDS.has(field.id) || !!prettyJson(field.value) || !!prettyJson(field.current); + +const CONVERTER_ICONS: Record = {UPLINK: 'call_received', DOWNLINK: 'call_made'}; + +const IMAGE_VALUE = /^(tb-image;|\/api\/images\/|data:image\/)/; + +const LONG_CHANGE_AT = 36; +const COMMON_VALUES = new Set(['on', 'off', 'automatic', 'set', 'not set', 'default']); +const OWN_TYPE_LABELS = new Set(['ALARM_RULE', 'DASHBOARD_WIDGET', 'DASHBOARD_STATE', 'DASHBOARD_ENTITY_ALIAS', 'DASHBOARD_FILTER', 'NOTIFICATION', 'NOTIFICATION_SETTINGS', 'NOTIFICATION_PREFERENCES', 'IMAGE', 'PLATFORM_SETTINGS', 'RELATION', 'VERSION', 'WHITE_LABELING', 'MAIL_TEMPLATE', 'CUSTOM_TRANSLATION', 'CUSTOM_MENU', 'MOBILE_APP', 'MOBILE_BUNDLE', 'MOBILE_QR_CODE', 'TWO_FACTOR_SETTINGS', 'MY_PROFILE', 'MY_TWO_FACTOR', 'MAIL_SERVER', 'REPORT_COMPONENT', 'REPORT_ENTITY_ALIAS', 'REPORT_FILTER', 'SCHEDULED_REPORT', 'SCADA_SYMBOL']); + +const PROFILE_TYPES = new Set([EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE]); + +function aiApproveLabel(data: ToolExecutionRequested): string { + const review = data?.review; + const versionId = HUB_INSTALL_TOOLS.has(data?.tool) ? (data.arguments as {versionId?: unknown})?.versionId : null; + if (typeof versionId === 'string' && versionId) { + return 'ai-assistant.record.install'; + } + if (review?.verb && REVIEW_VERBS.has(review.verb)) { + return 'ai-assistant.review.verb.' + review.verb; + } + if (data?.destructive) { + return 'ai-assistant.review.delete'; + } + switch (review?.change) { + case 'CREATE': + return 'ai-assistant.review.create'; + case 'UPDATE': + return 'ai-assistant.review.update'; + default: + return 'ai-assistant.approve'; + } +} + +function aiReviewTypeLabel(translate: TranslateService, entityType: string): string { + if (OWN_TYPE_LABELS.has(entityType)) { + return translate.instant('ai-assistant.review.type.' + entityType); + } + const translation = entityTypeTranslations.get(entityType as EntityType)?.type; + return translation ? translate.instant(translation) : entityType; +} + +function aiChangeHead(translate: TranslateService, data: ToolExecutionRequested): string | null { + const review = data?.review; + const label = aiApproveLabel(data); + if (!review?.entityType || label === 'ai-assistant.approve') { + return null; + } + const verb = label.split('.').pop(); + if (!HEAD_VERBS.has(verb)) { + return translate.instant(label); + } + if (DETAIL_TOKENS.has(review.detail) || ATTRIBUTE_TOOLS.has(data.tool)) { + const kind = DETAIL_TOKENS.has(review.detail) ? translate.instant('ai-assistant.review.detail.' + review.detail) + : translate.instant('ai-assistant.review.kind.attributes'); + return translate.instant('ai-assistant.review.head-change.' + verb, {kind}); + } + const type = review.detail === 'alarm-rule' ? 'ALARM_RULE' : review.entityType; + const key = 'ai-assistant.review.kind.' + type; + const phrase = translate.instant(key); + const kind = phrase !== key ? phrase : aiReviewTypeLabel(translate, type); + return translate.instant('ai-assistant.review.head-change.' + verb, {kind}); +} + +export function aiReviewHead(translate: TranslateService, data: ToolExecutionRequested): string { + return aiChangeHead(translate, data) ?? translate.instant('ai-assistant.review.head.pending'); +} @Component({ + changeDetection: ChangeDetectionStrategy.OnPush, selector: 'tb-ai-approval-card', templateUrl: './ai-approval-card.component.html', styleUrls: ['./ai-approval-card.component.scss'], standalone: false }) -export class AiApprovalCardComponent implements OnChanges { +export class AiApprovalCardComponent implements OnChanges, AfterViewChecked { @Input() data: ToolExecutionRequested; @Input() completedExecution: ToolExecutionResult | null = null; + @Input() durationMs?: number; + @Input() autoApprove = false; + @Input() answered = false; + + @Input() busy = false; + + @ViewChild('denyInput') denyInput: ElementRef; + @Output() approvalAction = new EventEmitter(); - @HostBinding('class') state: ApprovalCardState = 'pending'; + @Output() answerLater = new EventEmitter(); + + denying = false; + + showUnchanged = false; + + state: ApprovalCardState = 'pending'; + + handedOver: AiAction | null = null; + + handedFacts: AiDetailFact[] = []; + + private autoApproved = false; private readonly cd = inject(ChangeDetectorRef); + private readonly translate = inject(TranslateService); + private readonly clipboard = inject(ClipboardService); + private readonly host = inject(ElementRef); + + private readonly loader = inject(AiRecordLoaderService); + + listing: AiRecordView | null = null; + + private listingId: string | null = null; + + ngAfterViewChecked(): void { + decorateCodeBlocks(this.host.nativeElement, this.translate, text => this.clipboard.copyFromContent(text)); + } ngOnChanges(changes: SimpleChanges): void { - if (this.autoApprove && this.state === 'pending' && !this.completedExecution) { - this.approve(); + this.loadListing(); + if ((this.data?.autoApproved || this.autoApprove) && this.state === 'pending' && !this.completedExecution) { + this.autoApproved = true; + this.denying = false; + this.state = 'auto'; + } + if (this.answered && this.state === 'pending' && !this.completedExecution) { + this.denying = false; + this.state = 'denied'; + } + if (changes.durationMs && this.handedOver && !changes.completedExecution) { + this.handedOver = {...this.handedOver, durationMs: this.durationMs}; } if (changes.completedExecution && this.completedExecution?.executionId === this.data.executionId) { const result = this.completedExecution; - if (result.approvalStatus === ToolApprovalResult.DENIED || result.approvalStatus === ToolApprovalResult.TIMEOUT) { + if (result.approvalStatus === ToolApprovalResult.TIMEOUT) { + this.state = 'waiting'; + } else if (result.approvalStatus === ToolApprovalResult.DENIED) { this.state = 'denied'; - } else if (result.approvalStatus === ToolApprovalResult.APPROVED && result.executionStatus === 'SUCCESS') { - this.state = 'approved'; } else { - this.state = 'error'; + this.autoApproved = this.autoApproved || !!this.data?.autoApproved; + this.state = this.autoApproved ? 'auto' : 'approved'; + this.handedOver = { + executionId: result.executionId, + tool: this.data.tool ?? '', + arguments: this.data.arguments, + result: result.result, + status: result.executionStatus, + startedAt: this.data.time ?? Date.now(), + durationMs: this.durationMs ?? result.durationMs, + affectedEntities: result.affectedEntities ?? [] + }; + this.handedFacts = DETAILED_TOOLS.has(this.data.tool ?? '') ? [] : this.reviewFacts(); } this.cd.detectChanges(); } } - get isDestructive(): boolean { - return this.data.destructive; + get review(): AiApprovalReview | undefined { + return this.data.review; } - get approveIcon(): string { - return this.data.icon || (this.isDestructive ? 'delete' : 'check'); + get isDestructive(): boolean { + return this.data.destructive; } - get resultIcon(): string { - if (this.completedExecution?.icon) { - return this.completedExecution.icon; - } + get headIcon(): string { switch (this.state) { case 'approved': - return this.approveIcon; + return 'check_circle'; + case 'auto': + return 'bolt'; case 'denied': return 'block'; default: - return 'error_outline'; + return 'rate_review'; } } - approve(): void { - this.emitApproval(); + get headText(): string { + if (this.state === 'pending' || this.state === 'waiting') { + return this.changeHead() ?? this.translate.instant('ai-assistant.review.head.pending'); + } + return this.translate.instant('ai-assistant.review.head.' + this.state); + } + + private changeHead(): string | null { + return aiChangeHead(this.translate, this.data); + } + + + get outcomeText(): string { + const result = this.completedExecution; + const failed = result?.executionStatus !== 'SUCCESS'; + return result?.message || this.translate.instant(failed ? 'ai-assistant.error' : 'ai-assistant.approved'); + } + + get planned(): boolean { + return this.review?.change === 'CREATE'; + } + + get hubVersionId(): string | null { + const id = HUB_INSTALL_TOOLS.has(this.data?.tool) ? (this.data.arguments as {versionId?: unknown})?.versionId : null; + return typeof id === 'string' && id ? id : null; + } + + get approveLabel(): string { + return aiApproveLabel(this.data); + } + + + get recordName(): string { + const name = this.review?.name; + if (this.review?.entityType === 'WHITE_LABELING' && (name === 'GENERAL' || name === 'LOGIN')) { + return this.translate.instant('ai-assistant.review.white-labeling-target.' + name); + } + const template = this.review?.entityType === 'MAIL_TEMPLATE' && name ? mailTemplateTranslations.get(name as MailTemplate) : undefined; + return template ? this.translate.instant(template) : name; + } + + get alarmRule(): boolean { + return this.review?.detail === 'alarm-rule'; + } + + get meta(): string { + const review = this.review; + if (!review) { + return ''; + } + const parts = [this.alarmRule ? this.translate.instant('ai-assistant.review.type.ALARM_RULE') : this.typeLabel(review.entityType)]; + if (review.detail && !this.alarmRule) { + const integration = review.entityType === 'INTEGRATION' ? integrationTypeInfoMap.get(review.detail as IntegrationType) : undefined; + parts.push(DETAIL_TOKENS.has(review.detail) ? this.translate.instant('ai-assistant.review.detail.' + review.detail) + : integration ? this.translate.instant(integration.name) : review.detail); + } + if (review.target) { + parts.push(this.translate.instant(PROFILE_TYPES.has(review.entityType) ? 'ai-assistant.record.on-profile' : 'ai-assistant.record.on', + {name: review.target})); + } + return parts.join(' · '); + } + + get facts(): AiReviewRow[] { + const rows = [...this.rows('FACT', field => !isBlock(field)).slice(0, MAX_FIELDS), + ...this.rows('CHANGE', field => !isBlock(field) && (field.current === undefined || field.current === null))]; + if (this.listing && this.review?.target) { + rows.push({label: this.translate.instant('ai-assistant.record.set-up-on'), labelCode: false, valueCode: false, value: this.review.target}); + } + return rows; + } + + get codeBlocks(): AiReviewRow[] { + return [...this.rows('FACT', field => isBlock(field)), + ...this.rows('CHANGE', field => isBlock(field)).map(row => row.current === undefined ? row + : {...row, value: row.lang === 'json' ? lineDiff(withoutTs(row.current), withoutTs(row.value)) : lineDiff(row.current, row.value), + current: undefined, lang: 'diff'})]; + } + + private reviewFacts(): AiDetailFact[] { + return [ + ...this.rows('FACT', field => !isBlock(field)).map(row => row.image ? {label: row.label, raw: true, images: {value: row.value}} + : {label: row.label, raw: true, value: row.value, mono: row.valueCode, chip: row.chip}), + ...this.rows('CHANGE', field => !isBlock(field)).map(row => row.image || row.currentImage + ? {label: row.label, raw: true, change: true, images: {current: row.currentImage ? row.current : undefined, value: row.image ? row.value : undefined}} + : {label: row.label, raw: true, change: true, was: row.current ?? '—', value: row.value, mono: row.valueCode, long: this.isLongChange(row)}) + ]; + } + + isLongChange(change: AiReviewRow): boolean { + return !change.image && !change.currentImage && (change.current?.length ?? 0) + (change.value?.length ?? 0) > LONG_CHANGE_AT; } - approveAll(): void { - this.emitApproval(true); + get changes(): AiReviewRow[] { + return this.rows('CHANGE', field => !isBlock(field) && field.current !== undefined && field.current !== null); + } + + get unchanged(): AiReviewRow[] { + return this.rows('UNCHANGED'); + } + + get recordClosed(): boolean { + return this.state === 'pending' || this.state === 'denied' || this.state === 'waiting'; + } + + toggleUnchanged(): void { + this.showUnchanged = !this.showUnchanged; + if (this.showUnchanged) { + aiRevealOpened(this.host.nativeElement); + } + } + + approve(): void { + const later = this.state === 'waiting'; + this.state = this.autoApproved ? 'auto' : 'approved'; + this.denying = false; + (later ? this.answerLater : this.approvalAction).emit({executionId: this.data.executionId, approved: true}); } deny(): void { - this.state = 'executing'; - this.approvalAction.emit({executionId: this.data.executionId, approved: false}); + if (this.denying) { + this.sendDeny(this.denyInput?.nativeElement.value ?? ''); + return; + } + this.denying = true; + setTimeout(() => this.denyInput?.nativeElement.focus()); + } + + sendDeny(words: string): void { + const reason = words.trim(); + const later = this.state === 'waiting'; + this.denying = false; + this.state = 'denied'; + (later ? this.answerLater : this.approvalAction).emit(reason + ? {executionId: this.data.executionId, approved: false, reason} + : {executionId: this.data.executionId, approved: false}); + } + + closeDeny(): void { + this.denying = false; + } + + private loadListing(): void { + const id = this.hubVersionId; + if (!id || id === this.listingId) { + return; + } + this.listingId = id; + this.loader.hub(id).subscribe({ + next: listing => { + this.listing = listing; + this.cd.markForCheck(); + }, + error: () => { + this.listing = null; + this.cd.markForCheck(); + } + }); } - private emitApproval(autoApprove = false): void { - this.state = 'executing'; - this.approvalAction.emit({executionId: this.data.executionId, approved: true, autoApprove}); + private rows(kind: AiReviewField['kind'], include: (field: AiReviewField) => boolean = () => true): AiReviewRow[] { + return (this.review?.fields ?? []).filter(field => field.kind === kind && include(field)).map(field => ({ + label: field.name ?? this.translate.instant('ai-assistant.review.field.' + field.id), + labelCode: !!field.name, + valueCode: CODE_FIELDS.has(field.id) && field.value !== undefined && field.value !== null, + current: kind !== 'CHANGE' || (isBlock(field) && (field.current === undefined || field.current === null)) ? undefined + : prettyJson(field.current) ?? this.value(field, field.current), + value: prettyJson(field.value) ?? this.value(field, field.value), + image: IMAGE_FIELDS.has(field.id) && IMAGE_VALUE.test(field.value ?? ''), + currentImage: IMAGE_FIELDS.has(field.id) && IMAGE_VALUE.test(field.current ?? ''), + code: isBlock(field), + lang: BLOCK_FIELDS.has(field.id) ? 'tbel' : 'json', + chip: this.chip(field) + })); } + + private chip(field: AiReviewField): {icon?: string; image?: string} | undefined { + if (field.id === 'integrationType') { + const info = integrationTypeInfoMap.get(field.value as IntegrationType); + return info ? {image: info.icon} : undefined; + } + if (field.id === 'type' && converterTypeTranslationMap.has(field.value as ConverterType)) { + return {icon: CONVERTER_ICONS[field.value]}; + } + return undefined; + } + + private value(field: AiReviewField, value: string | undefined): string { + if (value === undefined || value === null) { + return this.translate.instant('ai-assistant.review.not-set'); + } + if (field.id === 'when' && !isNaN(Date.parse(value))) { + return new Date(value).toLocaleString(); + } + if (field.id === 'integrationType' && integrationTypeInfoMap.has(value as IntegrationType)) { + return this.translate.instant(integrationTypeInfoMap.get(value as IntegrationType).name); + } + if (field.id === 'type' && converterTypeTranslationMap.has(value as ConverterType)) { + return this.translate.instant(converterTypeTranslationMap.get(value as ConverterType)); + } + if (field.id && VALUE_TOKENS[field.id]?.includes(value)) { + return this.translate.instant(`ai-assistant.review.value.${field.id}-${value.replace(/ /g, '-')}`); + } + if (COMMON_VALUES.has(value)) { + return this.translate.instant(`ai-assistant.review.value.${value.replace(/ /g, '-')}`); + } + return value; + } + + private typeLabel(entityType: string): string { + return aiReviewTypeLabel(this.translate, entityType); + } + } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html new file mode 100644 index 0000000000..11489f55ee --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html @@ -0,0 +1,23 @@ + + +
+ + +
+
+ +
+ diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.ts new file mode 100644 index 0000000000..c44118f7a4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.ts @@ -0,0 +1,160 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AfterViewInit, Component, DestroyRef, ElementRef, EventEmitter, inject, input, Output, signal, ViewChild } from '@angular/core'; + +const PANE_MIN = 360; +const CHAT_MIN = 340; +const WIDTH_KEY = 'tbSolutionPaneWidth'; +const ESCAPE_OWNERS = ['mat-mdc-dialog-container', 'mat-mdc-menu-panel', 'mat-mdc-select-panel', 'mat-mdc-autocomplete-panel'] + .map(owner => '.cdk-overlay-container .' + owner).join(', '); + +@Component({ + selector: 'tb-ai-artifact-pane', + templateUrl: './ai-artifact-pane.component.html', + standalone: false, + host: { + class: 'art-pane', + '[class.scrolled]': 'scrolled()', + '[class.more]': 'more()', + '[style.flex-basis]': 'width() ? width() + "px" : null', + '(keydown.escape)': 'onEscape($event)', + '(document:keydown.escape)': 'onDocumentEscape($event)' + } +}) +export class AiArtifactPaneComponent implements AfterViewInit { + + dark = input(false); + + @Output() closed = new EventEmitter(); + + @ViewChild('body', {static: true}) body: ElementRef; + + width = signal(AiArtifactPaneComponent.storedWidth()); + scrolled = signal(false); + more = signal(false); + + private host = inject(ElementRef); + private destroyRef = inject(DestroyRef); + + ngAfterViewInit(): void { + setTimeout(() => this.refreshEdges(), 50); + const columns = (this.host.nativeElement as HTMLElement).parentElement; + columns?.addEventListener('keydown', this.onColumnsEscape); + this.destroyRef.onDestroy(() => columns?.removeEventListener('keydown', this.onColumnsEscape)); + } + + refreshEdges(): void { + const body = this.body?.nativeElement; + if (body) { + this.scrolled.set(body.scrollTop > 0); + this.more.set(body.scrollTop + body.clientHeight < body.scrollHeight - 1); + } + } + + onEscape(event: Event): void { + if (event.defaultPrevented) { + return; + } + event.stopPropagation(); + this.closed.emit(); + } + + onDocumentEscape(event: KeyboardEvent): void { + if (event.target === document.body || event.target === document.documentElement) { + this.closeOnEscape(event); + } + } + + private onColumnsEscape = (event: KeyboardEvent): void => { + if (event.key === 'Escape' && !(this.host.nativeElement as HTMLElement).contains(event.target as Node)) { + this.closeOnEscape(event); + } + }; + + private closeOnEscape(event: KeyboardEvent): void { + if (event.defaultPrevented || document.querySelector(ESCAPE_OWNERS)) { + return; + } + this.closed.emit(); + } + + startResize(event: PointerEvent): void { + event.preventDefault(); + const edge = event.target as HTMLElement; + const pane = this.host.nativeElement as HTMLElement; + const cols = pane.parentElement; + if (!cols) { + return; + } + const startX = event.clientX; + const startWidth = pane.getBoundingClientRect().width; + const max = cols.getBoundingClientRect().width - CHAT_MIN; + edge.setPointerCapture(event.pointerId); + edge.classList.add('held'); + let closing = false; + const move = (e: PointerEvent) => { + const width = startWidth + (startX - e.clientX); + closing = width < PANE_MIN - 72; + pane.classList.toggle('closing', closing); + this.width.set(Math.round(Math.min(max, Math.max(PANE_MIN, width)))); + }; + const up = () => { + edge.removeEventListener('pointermove', move); + edge.removeEventListener('pointerup', up); + edge.removeEventListener('pointercancel', up); + edge.classList.remove('held'); + pane.classList.remove('closing'); + if (closing) { + this.width.set(startWidth); + this.closed.emit(); + } else { + this.storeWidth(); + } + }; + edge.addEventListener('pointermove', move); + edge.addEventListener('pointerup', up); + edge.addEventListener('pointercancel', up); + } + + resetWidth(): void { + this.width.set(null); + this.storeWidth(); + } + + onEdgeKey(event: KeyboardEvent): void { + if (event.key === 'Enter') { + this.resetWidth(); + return; + } + const pane = this.host.nativeElement as HTMLElement; + const cols = pane.parentElement; + if (!cols) { + return; + } + const max = cols.getBoundingClientRect().width - CHAT_MIN; + let width: number; + if (event.key === 'Home') { + width = max; + } else if (event.key === 'End') { + width = PANE_MIN; + } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { + const step = event.shiftKey ? 64 : 16; + width = pane.getBoundingClientRect().width + (event.key === 'ArrowLeft' ? step : -step); + } else { + return; + } + event.preventDefault(); + this.width.set(Math.round(Math.min(max, Math.max(PANE_MIN, width)))); + this.storeWidth(); + } + + private static storedWidth(): number | null { + return Number(readStored(WIDTH_KEY)) || null; + } + + private storeWidth(): void { + const width = this.width(); + writeStored(WIDTH_KEY, width ? String(width) : null); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts new file mode 100644 index 0000000000..0b2439f73e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts @@ -0,0 +1,256 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + ElementRef, + inject, + Renderer2, + signal, + untracked, + viewChild, + ViewContainerRef +} from '@angular/core'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; +import { NavigationEnd, NavigationStart, Router } from '@angular/router'; +import { filter } from 'rxjs/operators'; +import { TranslateService } from '@ngx-translate/core'; +import { AiChatsService } from '@core/services/ai-chats.service'; +import { ChatLevel } from '@shared/models/ai-chat.models'; +import { MatDialog } from '@angular/material/dialog'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthState, selectAiTourStepSeen } from '@core/auth/auth.selectors'; +import { ActionPreferencesUpdateAiTour } from '@core/auth/auth.actions'; +import { AiTourStep } from '@shared/models/user-settings.models'; +import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { escapeTourText, TourPopupRef, TourPopupService } from '@shared/components/tour/tour-popup.service'; +import { TourService } from '@core/services/tour.service'; +import { AiAssistantContextService } from '@home/components/ai/ai-assistant-context.service'; +import { AiSlashService } from '@core/services/ai-slash.service'; +import { AiMarkCue } from '@home/components/ai/ai-mark.component'; + +const INTRO_DELAY_MS = 900; + +const intro: { owner: AiAssistantButtonComponent | null } = {owner: null}; + +@Component({ + selector: 'tb-ai-assistant-button', + template: ` + @if (available() && !panelService.open() && !panelService.suppressed()) { + @let status = cue(); + + +
+
+ {{ status ? ('ai-assistant.ai-assistant-cue' | translate: {cue: status.tip}) : ('ai-assistant.ai-assistant' | translate) }} + / +
+
+
+ } + `, + styles: [` + :host { + display: contents; + } + `], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiAssistantButtonComponent { + + panelService = inject(AiAssistantPanelService); + + private store = inject(Store); + + private readonly authState = getCurrentAuthState(this.store); + + readonly available = inject(UserPermissionsService).aiAvailable; + + private dialog = inject(MatDialog); + + private chats = inject(AiChatsService); + + private translate = inject(TranslateService); + + private context = inject(AiAssistantContextService); + + private tourPopup = inject(TourPopupService); + + private tourService = inject(TourService); + + private renderer = inject(Renderer2); + + private viewContainerRef = inject(ViewContainerRef); + + private buttonRef = viewChild('aiButton', {read: ElementRef}); + + private introSeen = toSignal(this.store.select(selectAiTourStepSeen(AiTourStep.AI_BUTTON)), {initialValue: true}); + + private welcomeSeen = toSignal(this.store.select(selectAiTourStepSeen(AiTourStep.WELCOME)), {initialValue: false}); + + readonly introOpen = signal(false); + + private introPopup: TourPopupRef | null = null; + + private introTimer: ReturnType | null = null; + + readonly cue = computed<{level: ChatLevel; tip: string} | null>(() => { + const chats = this.chats.statusChats(); + const titleOf = (title: string) => title || this.translate.instant('ai-assistant.new-chat'); + const attention = chats.filter(chat => this.chats.needsAttention(chat)); + if (attention.length) { + const level: AiMarkCue = attention.some(chat => this.chats.levelOf(chat) === 'needs') ? 'needs' : 'error'; + return { + level, + tip: attention.length === 1 + ? this.translate.instant('ai-assistant.waiting-one-tip', {title: titleOf(attention[0].title), status: this.chats.tipOf(attention[0])}) + : this.translate.instant('ai-assistant.waiting-many', {count: attention.length}) + }; + } + const running = chats.filter(chat => this.chats.levelOf(chat) === 'running'); + if (running.length) { + return { + level: 'running', + tip: running.length === 1 + ? this.translate.instant('ai-assistant.running-one-tip', {title: titleOf(running[0].title)}) + : this.translate.instant('ai-assistant.running-many', {count: running.length}) + }; + } + return null; + }); + + readonly markCue = computed(() => { + const level = this.cue()?.level; + return level === 'needs' || level === 'error' ? level : null; + }); + + private introWanted = computed(() => this.available() && this.welcomeSeen() && !this.tourService.active() && !this.introSeen() && this.cue()?.level !== 'running' && !this.panelService.open() + && !this.panelService.suppressed() && !!this.buttonRef()); + + private introEffect = effect(() => { + const wanted = this.introWanted(); + untracked(() => { + this.clearIntroTimer(); + if (wanted && !this.introOpen()) { + this.introTimer = setTimeout(() => this.showIntro(), INTRO_DELAY_MS); + } else if (!wanted && this.introOpen()) { + this.hideIntro(); + } + }); + }); + + private statusWatch = effect(() => { + if (this.available()) { + untracked(() => this.chats.watchStatus()); + } + }); + + constructor() { + inject(Router).events.pipe( + filter(event => event instanceof NavigationStart || event instanceof NavigationEnd), + takeUntilDestroyed() + ).subscribe(event => { + this.clearIntroTimer(); + if (event instanceof NavigationStart) { + this.hideIntro(); + } else if (this.introWanted()) { + this.introTimer = setTimeout(() => this.showIntro(), INTRO_DELAY_MS); + } + }); + const removeOpener = inject(AiSlashService).setOpener({ + canOpen: () => this.available() && !this.panelService.open() && !this.panelService.suppressed(), + open: () => this.openChat() + }); + inject(DestroyRef).onDestroy(() => { + removeOpener(); + this.clearIntroTimer(); + this.hideIntro(); + }); + } + + toggle($event: Event): void { + $event.stopPropagation(); + this.openChat(); + } + + private openChat(): void { + if (this.introOpen()) { + this.closeIntro(); + } + this.panelService.openPanel(); + } + + private showIntro(): void { + this.introTimer = null; + const trigger: HTMLElement | undefined = this.buttonRef()?.nativeElement; + if (!this.introWanted() || !trigger || intro.owner || this.dialog.openDialogs.length || !this.visible(trigger)) { + return; + } + intro.owner = this; + const welcome = this.context.welcome(); + const example = welcome.examples[0]?.label?.trim(); + const lead = this.translate.instant(`ai-assistant.intro.lead-${welcome.place}${example ? '-example' : ''}`, {example}); + const keys = matchMedia('(hover: hover) and (pointer: fine)').matches ? ' ' + this.translate.instant('ai-assistant.intro.keys') : ''; + this.introOpen.set(true); + this.introPopup = this.tourPopup.show({ + target: trigger, + hostView: this.viewContainerRef, + renderer: this.renderer, + placement: ['bottomRight', 'bottom', 'bottomLeft'], + title: welcome.title || this.translate.instant('ai-assistant.panel-title'), + text: escapeTourText(lead) + keys, + skipLabel: this.translate.instant('ai-assistant.intro.got-it'), + nextLabel: this.translate.instant('ai-assistant.intro.open-chat'), + onSkip: () => this.closeIntro(), + onClose: () => this.closeIntro(), + onNext: () => this.openChat(), + onHidden: () => { + if (this.introOpen()) { + this.introPopup = null; + this.hideIntro(); + } + } + }); + } + + private closeIntro(): void { + this.hideIntro(); + if (!this.introSeen()) { + this.store.dispatch(new ActionPreferencesUpdateAiTour({step: AiTourStep.AI_BUTTON, seen: true})); + } + } + + private hideIntro(): void { + if (intro.owner === this) { + intro.owner = null; + } + this.introOpen.set(false); + const popup = this.introPopup; + this.introPopup = null; + popup?.close(); + } + + private clearIntroTimer(): void { + if (this.introTimer) { + clearTimeout(this.introTimer); + this.introTimer = null; + } + } + + private visible(element: HTMLElement): boolean { + const rect = element.getBoundingClientRect(); + return rect.width > 0 && rect.height > 0 && (element.checkVisibility?.({visibilityProperty: true}) ?? element.offsetParent !== null); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts new file mode 100644 index 0000000000..cd8cdc97b8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { computed, inject, Injectable } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { NavigationEnd, Router } from '@angular/router'; +import { TranslateService } from '@ngx-translate/core'; +import { filter, map, startWith } from 'rxjs/operators'; +import { aiClientOs, aiPageView, AiChatClientContext } from '@shared/models/ai-chat.models'; +import { getDefaultTimezone } from '@shared/models/time/time.models'; +import { BreadCrumb } from '@shared/components/breadcrumb'; +import { BreadcrumbService } from '@core/services/breadcrumb.service'; +import { UtilsService } from '@core/services/utils.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { aiWelcome } from '@home/components/ai/ai-welcome.models'; + +@Injectable({providedIn: 'root'}) +export class AiAssistantContextService { + + private panelService = inject(AiAssistantPanelService); + private translate = inject(TranslateService); + private utils = inject(UtilsService); + private router = inject(Router); + + private pageTitle = toSignal(inject(BreadcrumbService).breadcrumbs$.pipe( + map(crumbs => crumbs.map(crumb => this.crumbLabel(crumb)).filter(label => !!label).join(' › ')) + ), {initialValue: ''}); + + readonly pagePath = toSignal(this.router.events.pipe( + filter((event): event is NavigationEnd => event instanceof NavigationEnd), + map(event => event.urlAfterRedirects), + startWith(this.router.url), + map(url => (url || '/').split(/[?#]/)[0]) + ), {initialValue: '/'}); + + readonly clientContext = computed(() => { + const context = this.panelService.clientContext(); + if (context) { + const name = this.panelService.viewName(); + return context.view?.entityId && name && !context.view.title ? {...context, view: {...context.view, title: name}} : context; + } + const title = this.pageTitle(); + const path = this.pagePath(); + const type = aiPageView(path); + return title || path !== '/' ? {view: {type, title, path}, timeZone: getDefaultTimezone(), os: aiClientOs()} : undefined; + }); + + readonly welcome = computed(() => aiWelcome(this.clientContext()?.view, this.panelService.viewName(), this.panelService.config(), + this.translate)); + + private crumbLabel(crumb: BreadCrumb): string { + try { + return crumb.labelFunction ? crumb.labelFunction() : crumb.customTranslate ? this.utils.customTranslation(crumb.label, crumb.label) + : this.translate.instant(crumb.label); + } catch { + return ''; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html index 2e848e106f..346fc7deb5 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html @@ -4,105 +4,29 @@ SPDX-License-Identifier: BUSL-1.1 --> -
-
- - - - @for (group of groupedChats(); track group.label) { -
{{ group.label | translate }}
- @for (chat of group.chats; track chat.id) { - - } - } @empty { -
{{ 'ai-assistant.no-chats' | translate }}
- } -
-
-
- - - - - - - - -
-
-
- @if (messages().length) { -
-
- - -
- } @else { -
-
-
- - - -
-
ai-assistant.main-title
-
{{ subTitle() }}
-
-
-
- } - @if (!messages().length && promptExamples().length) { -
- @for (example of promptExamples(); track example.message) { - - } -
- } -
- - + +
+ +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss index 0e5550eb38..4bf26c3c6b 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss @@ -3,223 +3,97 @@ @import '../../../../../scss/constants'; :host { - width: 480px; - overflow: hidden; - transform: translateX(100%); - transition: transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1); position: absolute; top: 0; right: 0; bottom: 0; + z-index: 20; + width: var(--tb-ai-panel-w, 364px); display: flex; flex-direction: column; - z-index: 20; + background: var(--tb-surface, #fff); + transform: translateX(100%); + transition: transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1), box-shadow 400ms ease; - &.open { - transform: translateX(0); + &.suppressed { + visibility: hidden; + transition: none; } - .image-main-color { - color: var(--tb-primary-500); + &.restored { + transition: none; } - .ai-assistant-container { - background: #fff; - margin: 16px 16px 16px 0; - box-shadow: 0 0 0 0 rgba(0, 0, 0, 0.2), 0 0 0 0 rgba(0, 0, 0, 0.14), 0 0 0 0 rgba(0, 0, 0, 0.12); - border: solid 1px #e0e0e0; - border-radius: 4px; - display: flex; - flex-direction: column; - // :host is a flex column, so fill its height via flex (which subtracts the card margins) - // instead of height:100% (which ignores margins and overflows the host, clipping the input). - flex: 1; - min-height: 0; - width: 464px; - overflow: hidden; + &.open { + transform: translateX(0); + box-shadow: -1px 0 0 rgba(16, 24, 40, 0.06), -12px 0 32px rgba(16, 24, 40, 0.06); + } - &.fill { - margin: 0; - width: 480px; + .tb-ai-grip { + position: absolute; + top: 0; + bottom: 0; + left: -4px; + z-index: 6; + width: 8px; + cursor: ew-resize; + touch-action: none; + + &::after { + content: ''; + position: absolute; + top: 50%; + left: 2px; + width: 4px; + height: 36px; + margin-top: -18px; + border-radius: 2px; + background: var(--tb-ink-38); + opacity: 0; + transition: opacity .12s ease; } - &.details-open { - padding: 16px 16px 16px 0; + &:hover::after, &:focus-visible::after { + opacity: 1; } - } - - .ai-assistant-composer { - flex: none; - } - .ai-assistant-header { - display: flex; - align-items: center; - justify-content: space-between; - padding: 12px; - white-space: nowrap; + &:focus-visible { + outline: 0; + } - .chat-selector { - font-size: 16px; - min-width: 0; - max-width: 280px; - --mat-button-text-with-icon-horizontal-padding: 12px; - --mat-button-text-label-text-weight: 400; - flex: 1; + @media (max-width: 1100px) { + display: none; } } - .ai-assistant-content { - width: 100%; - height: 100%; - display: flex; + .ai-assistant-container { overflow: hidden; flex: 1; - padding: 0 24px 16px; - gap: 16px; + min-height: 0; + display: flex; flex-direction: column; - - .chat-messages-container { - position: relative; - display: flex; - flex: 1 1 0; - min-height: 0; - width: calc(100% + 24px); - } - - .ai-chat-messages { - padding-right: 20px; - scrollbar-gutter: stable; - } - - .example-chips { - display: flex; - flex-wrap: wrap; - justify-content: center; - gap: 8px; - width: 100%; - --mat-button-outlined-label-text-color: rgba(0, 0, 0, 0.76); - --mat-button-outlined-container-height: 32px; - --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.16); - --mat-button-outlined-container-shape: 20px; - - .example-chip { - background-color: #fff; - opacity: 0; - animation: exampleChipFadeIn 220ms ease-out forwards; - - &:nth-child(2) { - animation-delay: 60ms; - } - - @media (prefers-reduced-motion: reduce) { - opacity: 1; - animation: none; - } - } - } - - @keyframes exampleChipFadeIn { - from { - opacity: 0; - transform: translateY(6px); - } - to { - opacity: 1; - transform: translateY(0); - } - } } - // <= 1279px: slide-in overlay above the content (which no longer reserves space here), - // keeping the 480px card size of the normal display mode. - @media #{$mat-lt-lg} { - - .ai-assistant-container { - width: 480px; - margin: 0; - - &.fill { - width: 480px; - } - } - - .ai-assistant-content { - min-width: 0; - } + .ai-assistant-chat { + flex: 1; + min-height: 0; } - // <= 599px: full-screen panel, the card fills the whole width. - @media #{$mat-xs} { - width: 100%; + @media (max-width: 1100px) { + top: auto; + left: 0; + width: auto; + height: clamp(min(340px, 70vh), 50vh, 600px); + transform: translateY(100%); - .ai-assistant-container { - margin: 0; - width: auto; - - &.fill { - width: auto; - } - - &.details-open { - padding: 8px; - } + &.open { + transform: translateY(0); + box-shadow: 0 -1px 0 rgba(16, 24, 40, 0.06), 0 -12px 32px rgba(16, 24, 40, 0.08); } } } -:host::ng-deep { - .ai-assistant-header { - .chat-selector { - .mdc-button__label { - width: 100%; - text-align: start; - text-overflow: ellipsis; - overflow: hidden; - } - } - } -} - -::ng-deep { - .ai-chat-list-menu.mat-mdc-menu-panel { - min-width: var(--chat-menu-dynamic-width); - max-height: 65vh; - - .chat-group-label { - padding: 8px 16px; - font-size: 14px; - color: rgba(0, 0, 0, 0.76); - font-weight: 500; - } - - .mat-mdc-menu-item.chat-item { - padding-left: 32px; - min-height: 32px; - --mat-menu-item-label-text-size: 14px; - --mat-menu-item-label-text-line-height: 20px; - padding-top: 4px; - padding-bottom: 4px; - - &.selected { - --mat-menu-item-label-text-color: var(--tb-primary-500); - background-color: rgba(0,0,0,0.04); - } - } - - .chat-group-empty { - padding: 16px; - text-align: center; - color: rgba(0, 0, 0, 0.54); - font-size: 14px; - line-height: 20px; - } - } - - .ai-chat-action-menu { - .delete { - --mat-menu-item-icon-color: #FF5722; - --mat-menu-item-label-text-color: #FF5722; - } - } +:host(.closing) > :not(.tb-ai-grip) { + opacity: .4; + transition: opacity .2s ease; } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts index fb7dadc790..5d3d56b737 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts @@ -1,55 +1,13 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { - Component, - computed, - DestroyRef, - effect, - ElementRef, - inject, - OnInit, - SecurityContext, - signal, - untracked, - ViewChild -} from '@angular/core'; -import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; -import { EMPTY, Observable, of, Subject, throwError, timer } from 'rxjs'; -import { catchError, concatMap, finalize, retry, switchMap, takeUntil, tap } from 'rxjs/operators'; -import { HttpErrorResponse } from '@angular/common/http'; -import { AiChatService } from '@core/http/ai-chat.service'; -import { - AiAssistantPromptExample, - AiChatClientContext, - AiPromptMessage, - ApprovalResult, - ChatEvent, - ChatInfo, - ChatTitleGeneratedEvent, - SendChatMessageRequest, - ToolExecutionRequestedEvent, - ToolExecutionResult -} from '@shared/models/ai-chat.models'; -import { DialogService } from '@core/services/dialog.service'; -import { TranslateService } from '@ngx-translate/core'; -import { MatDialog } from '@angular/material/dialog'; -import { AiRenameDialogComponent, AiRenameDialogData } from '@home/components/ai/ai-rename-dialog.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { ActionNotificationShow } from '@core/notification/notification.actions'; -import { DAY, WEEK } from '@shared/models/time/time.models'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { isEqual, isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { AI_TOOLTIP_PROVIDERS } from '@home/components/ai/ai-tooltip'; +import { Component, computed, effect, ElementRef, inject, NgZone, signal, untracked, ViewChild } from '@angular/core'; +import { MatTooltip } from '@angular/material/tooltip'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; -import { DomSanitizer } from '@angular/platform-browser'; -import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; -import { MatButton } from '@angular/material/button'; -import { EntityId } from '@shared/models/id/entity-id'; - -export interface ChatGroup { - label: string; - chats: ChatInfo[]; -} +import { AiChatsService } from '@core/services/ai-chats.service'; +import { AiChatComponent } from '@home/components/ai/ai-chat.component'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AiAssistantContextService } from '@home/components/ai/ai-assistant-context.service'; @Component({ selector: 'tb-ai-assistant-panel', @@ -58,499 +16,332 @@ export interface ChatGroup { standalone: false, host: { '[class.open]': 'isOpen', + '[class.suppressed]': 'panelService.suppressed()', + '[class.restored]': 'panelService.restored()', '[attr.inert]': 'isOpen ? null : ""', - '(transitionend)': 'onSlideEnd($event)' - } + '[class.split]': 'split()', + '(transitionend)': 'onSlideEnd($event)', + '(window:resize)': 'fit()', + '(click)': 'onClick($event)', + '(keydown.escape)': '$event.stopPropagation()' + }, + providers: AI_TOOLTIP_PROVIDERS }) -export class AiAssistantPanelComponent implements OnInit { +export class AiAssistantPanelComponent { panelService = inject(AiAssistantPanelService); - @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; + @ViewChild(AiChatComponent) chat: AiChatComponent; - get isOpen() { return this.panelService.open(); } + @ViewChild('gripTip', {read: MatTooltip}) gripTip: MatTooltip; - slideDone = signal(false); + private zone = inject(NgZone); - loading = signal(false); + private static readonly PAGE_REFLOW_MS = 50; - isCreatingNew = signal(false); + private static readonly COMPOSE_DELAY_MS = 60; - messages = signal([]); + private static readonly CLOSE_PAST = 72; - completedExecutions = signal>({}); + resizing = signal(false); - chatId = signal(undefined); + get isOpen() { return this.panelService.open(); } - subTitle = computed(() => { - return this.panelService.config()?.subTitle ?? this.translate.instant('ai-assistant.sub-title'); - }); + readonly defaultWidth = 364; - activePlaceholder = computed(() => { - const config = this.panelService.config(); - if (this.messages().length) { - return config?.followUpPromptPlaceholder ?? this.translate.instant('ai-assistant.follow-up-prompt-placeholder'); - } - return config?.initialPromptPlaceholder ?? ''; - }); + readonly minWidth = 320; - promptExamples = computed(() => this.panelService.config()?.promptExamples ?? []); + readonly maxWidth = 480; - autoApprove = computed(() => this.panelService.isAutoApprove(this.chatId())); + private static readonly SPLIT_MAX = 880; + private static readonly SPLIT_MIN = 540; + private static readonly PAGE_MIN = 560; + private static readonly SHEET_MAX_WINDOW = 1100; - selectedChatTitle = computed(() => { - const id = this.chatId(); - if (!id) return null; - return (this.panelService.chats() ?? []).find(c => c.id === id)?.title ?? null; - }); + width = signal(this.defaultWidth); - groupedChats = computed(() => { - const chats = this.panelService.chats() ?? []; - if (!chats.length) return []; - - const now = new Date(); - const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); - const yesterday = today - DAY; - const lastWeek = today - WEEK; - - const groups: ChatGroup[] = [ - {label: 'ai-assistant.today', chats: []}, - {label: 'ai-assistant.yesterday', chats: []}, - {label: 'ai-assistant.last-7-days', chats: []}, - {label: 'ai-assistant.older', chats: []} - ]; - - for (const chat of chats) { - if (chat.createdTime >= today) { - groups[0].chats.push(chat); - } else if (chat.createdTime >= yesterday) { - groups[1].chats.push(chat); - } else if (chat.createdTime >= lastWeek) { - groups[2].chats.push(chat); - } else { - groups[3].chats.push(chat); - } - } + room = signal(0); - return groups.filter(g => g.chats.length > 0); + splitWidth = computed(() => { + const room = this.room(); + return Math.min(AiAssistantPanelComponent.SPLIT_MAX, Math.floor(room / 2), room - AiAssistantPanelComponent.PAGE_MIN); }); - private aiChat = inject(AiChatService); - private dialog = inject(DialogService); - private translate = inject(TranslateService); - private matDialog = inject(MatDialog); - private store = inject(Store); - private destroyRef = inject(DestroyRef); - private sanitizer = inject(DomSanitizer); - private elementRef = inject(ElementRef); + splitAvailable = computed(() => this.room() > 0 && window.innerWidth > AiAssistantPanelComponent.SHEET_MAX_WINDOW + && this.splitWidth() >= AiAssistantPanelComponent.SPLIT_MIN); - private loadChat$ = new Subject(); - private cancelMessage$ = new Subject(); - private sessionAffectedEntities: EntityId[] = []; - private messageCancelled = false; - private resumeOnOpen = false; + split = computed(() => this.width() > this.maxWidth); - private static readonly RESUME_ATTEMPTS = 4; - private static readonly RESUME_DELAY_MS = 2000; + private wanted = this.defaultWidth; - private openEffect = effect(() => { - if (this.panelService.open()) { - this.dropChatFromOtherContext(); - this.loadChats(); - const chatId = untracked(() => this.chatId()); - if (this.resumeOnOpen && chatId) { - this.resumeOnOpen = false; - this.loadChat$.next(chatId); - } - } else { - this.slideDone.set(false); - this.suspendOnClose(); - } - }); + private panelWidth = this.defaultWidth; - private lastContextKey: string | null = null; + chatId = signal(undefined); - // Realign the open chat when the context changes in place while the panel stays open - // (e.g. switching between dashboards). List/entity toggles collapse to the same key, so they - // do not trigger this. Guarded on a non-null key to avoid reacting to teardown clearing context. - private contextSwitchEffect = effect(() => { - const key = this.panelService.contextKey(); - if (this.panelService.open() && this.lastContextKey !== null && key !== null && key !== this.lastContextKey) { - this.reset(); - this.loadChats(); - } - this.lastContextKey = key; - }); + private context = inject(AiAssistantContextService); - ngOnInit() { - this.loadChat$.pipe( - switchMap(id => this.aiChat.getChatMessages(id, {ignoreLoading: true, ignoreErrors: true}).pipe( - catchError(err => { - this.messages.set([]); - this.completedExecutions.set({}); - setTimeout(() => this.showErrorMessage(err), 0); - return EMPTY; - }) - )), - takeUntilDestroyed(this.destroyRef) - ).subscribe(messages => { - this.showHistory(messages); - this.resumeTurn(this.chatId()); - }); - } + clientContext = this.context.clientContext; - close(): void { - this.panelService.close(); - } + welcome = this.context.welcome; - // Credit subscription and focus wait for the slide so they do not stutter it. - onSlideEnd(event: TransitionEvent): void { - if (event.target !== this.elementRef.nativeElement || event.propertyName !== 'transform' || !this.isOpen) { - return; - } - this.slideDone.set(true); - this.promptInput?.focus(); - } + private chats = inject(AiChatsService); + private elementRef = inject(ElementRef); - onApprovalAction(event: ApprovalResult): void { - const chatId = this.chatId(); - if (event.autoApprove && chatId) { - this.panelService.setAutoApprove(chatId, true); - } - this.aiChat.resolveToolApproval( - {executionId: event.executionId, approved: event.approved}, - {ignoreLoading: true, ignoreErrors: true} - ).subscribe(); - } + private static readonly WIDTH_KEY = 'tbAiPanelWidth'; - setMenuWidth(triggerEl: MatButton): void { - const width = triggerEl._elementRef.nativeElement.offsetWidth; - document.documentElement.style.setProperty('--chat-menu-dynamic-width', `${width}px`); - } + private static readonly APPLIED_WIDTH_KEY = 'tb-ai-panel-applied-width'; - selectChat(chat: ChatInfo): void { - this.messageCancelled = true; - this.cancelMessage$.next(); - this.isCreatingNew.set(false); - this.chatId.set(chat.id); - this.panelService.setLastChatId(chat.id); - this.loadChat$.next(chat.id); - } + private lastContextKey: string | null = null; - useExample(example: AiAssistantPromptExample): void { - this.promptInput?.setValue(example.message); - } + private dockedEffect = effect(onCleanup => { + const docked = this.panelService.open() && !this.panelService.suppressed(); + document.documentElement.classList.toggle('tb-ai-docked', docked); + onCleanup(() => document.documentElement.classList.remove('tb-ai-docked')); + }); - sendMsgFromUser(prompt: AiPromptMessage): void { - const userMessage: ChatMessage = prompt.resources.length - ? {from: 'USER', content: prompt.message, resources: prompt.resources} - : {from: 'USER', content: prompt.message}; - this.messages.update(list => [...list, userMessage]); - this.sendMessage(prompt).subscribe({ - error: (err) => { - if (this.isConnectionLost(err) && this.chatId()) { - this.showErrorToast(this.translate.instant('ai-assistant.connection-lost')); - this.resumeTurn(this.chatId(), true); - return; - } - this.messages.update(list => list.filter(message => message !== userMessage)); - setTimeout(() => { - this.showErrorMessage(err); - }, 0); - }, - complete: () => { - if (!this.messageCancelled && this.sessionAffectedEntities.length) { - this.panelService.emitUpdatedData(this.sessionAffectedEntities); - } + private wasOpen = false; + + private openEffect = effect(() => { + const open = this.panelService.open(); + const composed = this.panelService.composed(); + untracked(() => { + const opened = open && !this.wasOpen; + this.wasOpen = open; + if (!open) { + return; + } + if (composed) { + this.startComposed(this.panelService.takeComposed(), opened); + } else if (opened) { + this.restoreChat(); } }); - } + }); - reset(createNew?: boolean): void { - this.cancelActiveMessage(); - this.isCreatingNew.set(!!createNew); + private startComposed(text: string, opened: boolean): void { + this.chat?.keepDraftForCompose(); this.chatId.set(undefined); - this.messages.set([]); - } - - private cancelActiveMessage(): void { - this.messageCancelled = true; - this.cancelMessage$.next(); - this.stopLoadingState(); - this.promptInput?.reset(); - } - - // Keeps the open chat so reopening shows it right away. A reply interrupted by closing keeps running on the - // server, so reopening reloads the chat and follows that reply. - private suspendOnClose(): void { - this.resumeOnOpen = this.loading(); - this.cancelActiveMessage(); - } - - private dropChatFromOtherContext(): void { - const chatId = this.chatId(); - if (chatId && chatId !== this.panelService.lastChatIdForContext()) { - this.reset(); + if (opened) { + this.chats.load().subscribe(); } + setTimeout(() => this.chat?.composeText(text), AiAssistantPanelComponent.COMPOSE_DELAY_MS); } - renameChat(): void { - const chatId = this.chatId(); - if (!chatId) return; - this.matDialog.open(AiRenameDialogComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - data: { - title: this.translate.instant('ai-assistant.rename-chat-title'), - value: this.selectedChatTitle() || this.translate.instant('ai-assistant.new-chat') - } - }).afterClosed().subscribe(newTitle => { - if (newTitle && newTitle !== this.selectedChatTitle()) { - this.aiChat.updatedChat(chatId, {title: newTitle}, {ignoreLoading: true, ignoreErrors: true}).subscribe({ - next: () => { - this.panelService.updateChatTitle(chatId, newTitle); - }, - error: (err) => { - this.showErrorMessage(err); - } - }); - } - }); - } - - deleteChat(): void { - const chatId = this.chatId(); - if (!chatId) return; - const chatTitle = this.selectedChatTitle() || this.translate.instant('ai-assistant.new-chat'); - this.dialog.confirm( - this.translate.instant('ai-assistant.delete-chat-title', {name: chatTitle}), - this.translate.instant('ai-assistant.delete-chat-text'), - this.translate.instant('action.no'), - this.translate.instant('ai-assistant.delete-chat-confirm') - ).subscribe(value => { - if (value) { - this.aiChat.deleteChat(chatId, {ignoreLoading: true, ignoreErrors: true}).subscribe(() => { - this.panelService.removeChat(chatId); - this.reset(); - }); + private restoreChat(): void { + const carried = this.panelService.hasCarriedChat(); + if (!carried) { + this.dropChatFromOtherContext(); + } + this.chats.load().subscribe(() => { + if (carried) { + const chatId = this.panelService.takeCarriedChat(); + if (chatId && this.chats.find(chatId)) { + this.chatId.set(chatId); + return; + } } + this.selectLastChat(); }); } - private loadChats(): void { - const chats = this.panelService.chats(); - if (chats !== null) { - this.selectLastChat(chats); - return; + private contextSwitchEffect = effect(() => { + const key = this.panelService.contextKey(); + if (this.panelService.open() && this.lastContextKey !== null && key !== null && key !== this.lastContextKey) { + untracked(() => { + const carried = this.panelService.takeCarriedChat(); + if (carried && carried === this.chatId()) { + return; + } + this.chatId.set(undefined); + this.selectLastChat(); + }); } - this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).subscribe(chats => { - this.panelService.setChats(chats); - this.selectLastChat(chats); - }); - } + this.lastContextKey = key; + }); - private selectLastChat(chats: ChatInfo[]): void { - if (!this.chatId() && !this.isCreatingNew()) { - const lastId = this.panelService.lastChatIdForContext(); - const lastChat = lastId ? chats.find(c => c.id === lastId) : null; - if (lastChat) { - this.selectChat(lastChat); - } + constructor() { + let stored = 0; + stored = Number(readStored(AiAssistantPanelComponent.WIDTH_KEY)) || 0; + this.wanted = stored || this.defaultWidth; + this.panelWidth = Math.min(this.wanted, this.maxWidth); + let applied = 0; + try { + applied = Number(sessionStorage.getItem(AiAssistantPanelComponent.APPLIED_WIDTH_KEY)) || 0; + } catch { + applied = 0; + } + if (applied) { + this.width.set(applied); + document.documentElement.style.setProperty('--tb-ai-panel-w', applied + 'px'); } + setTimeout(() => this.fit()); } - private sendMessage(prompt: AiPromptMessage): Observable { - this.initLoadingState(); - this.sessionAffectedEntities = []; - this.messageCancelled = false; + fit(): void { + this.room.set(this.elementRef.nativeElement.parentElement?.clientWidth ?? window.innerWidth); + this.show(this.wanted); + } - const startOrContinue$ = this.chatId() - ? of(null) - : this.aiChat.createChat({title: 'New chat'}, {ignoreLoading: true, ignoreErrors: true}).pipe( - tap(chatId => { - this.isCreatingNew.set(false); - this.chatId.set(chatId); - this.panelService.setLastChatId(chatId); - this.panelService.addChat({id: chatId, title: 'New chat', createdTime: Date.now()}); - }) - ); - - const request: SendChatMessageRequest = { - message: prompt.message, - clientContext: this.resolveClientContextToSend() - }; - if (prompt.resources.length) { - request.resources = prompt.resources.map(resource => resource.id); + toggleSplit(): void { + if (this.split()) { + this.setWidth(this.panelWidth, true); + } else if (this.splitAvailable()) { + this.panelWidth = this.width(); + this.setWidth(this.splitWidth(), true); } + } - return startOrContinue$.pipe( - switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})), - tap(() => { - if (request.clientContext) { - this.panelService.markClientContextSent(this.chatId(), request.clientContext); - } - }), - takeUntil(this.cancelMessage$), - concatMap(chatMsg => this.handleChatEvent(chatMsg)), - finalize(() => this.stopLoadingState()) - ); + private widest(): number { + return this.splitAvailable() ? this.splitWidth() : Math.min(this.maxWidth, Math.max(this.minWidth, Math.round(this.room() / 2) || this.maxWidth)); } - private resolveClientContextToSend(): AiChatClientContext | undefined { - const currentContext = this.panelService.clientContext(); - if (!currentContext) { - return undefined; + private show(width: number): number { + const value = Math.round(Math.min(this.widest(), Math.max(this.minWidth, width))); + this.width.set(value); + document.documentElement.style.setProperty('--tb-ai-panel-w', value + 'px'); + try { + sessionStorage.setItem(AiAssistantPanelComponent.APPLIED_WIDTH_KEY, String(value)); + } catch { + return value; } - const chatId = this.chatId(); - const alreadySent = chatId ? this.panelService.getSentClientContext(chatId) : undefined; - return (!chatId || !isEqual(currentContext, alreadySent)) ? currentContext : undefined; + return value; } - private showHistory(messages: ChatMessage[]): void { - const completed: Record = {}; - for (const message of messages) { - if (message.from === 'APPROVAL' && (message as ApprovalChatMessage).result) { - const result = (message as ApprovalChatMessage).result; - completed[result.executionId] = result; + setWidth(width: number, keep = false): void { + this.room.set(this.elementRef.nativeElement.parentElement?.clientWidth ?? window.innerWidth); + const value = this.show(width); + if (keep) { + this.wanted = value; + if (value <= this.maxWidth) { + this.panelWidth = value; } + writeStored(AiAssistantPanelComponent.WIDTH_KEY, value === this.defaultWidth ? null : String(value)); } - this.completedExecutions.set(completed); - this.messages.set(messages); } - // Follows the reply still running in the chat, if any: after a reload, a reopened panel or a lost connection. - // The server replays the whole reply, so what the history already shows of it is dropped first. - private resumeTurn(chatId: string, afterConnectionLoss = false): void { - if (!chatId) { - return; + onGripKey(event: KeyboardEvent): void { + if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { + event.preventDefault(); + this.setWidth(this.width() + (event.key === 'ArrowLeft' ? 16 : -16), true); + } else if (event.key === 'Home' || event.key === 'End') { + event.preventDefault(); + this.setWidth(event.key === 'Home' ? this.widest() : this.minWidth, true); } - let resumed = false; - this.messageCancelled = false; - this.sessionAffectedEntities = []; - const attempt$ = timer(afterConnectionLoss ? AiAssistantPanelComponent.RESUME_DELAY_MS : 0).pipe( - tap(() => { - if (afterConnectionLoss) { - this.initLoadingState(); - } - }), - switchMap(() => this.aiChat.resumeChat(chatId, {ignoreLoading: true, ignoreErrors: true})) - ); - attempt$.pipe( - retry({ - count: afterConnectionLoss ? AiAssistantPanelComponent.RESUME_ATTEMPTS : 0, - delay: (error, attempt) => this.isConnectionLost(error) - ? timer(attempt * AiAssistantPanelComponent.RESUME_DELAY_MS) - : throwError(() => error) - }), - takeUntil(this.cancelMessage$), - concatMap(event => { - if (event.event === 'turnResumed') { - resumed = true; - this.initLoadingState(); - this.dropRunningReply(); - return of(event); - } - return this.handleChatEvent(event); - }), - finalize(() => { - if (resumed || afterConnectionLoss) { - this.stopLoadingState(); - } - }) - ).subscribe({ - error: () => { - if (afterConnectionLoss) { - this.showErrorToast(this.translate.instant('ai-assistant.reconnect-failed')); - } - }, - complete: () => { - if (this.messageCancelled || this.chatId() !== chatId) { - return; - } - if (this.sessionAffectedEntities.length) { - this.panelService.emitUpdatedData(this.sessionAffectedEntities); - } - if (resumed || afterConnectionLoss) { - this.aiChat.getChatMessages(chatId, {ignoreLoading: true, ignoreErrors: true}) - .pipe(takeUntil(this.cancelMessage$)) - .subscribe(messages => this.showHistory(messages)); - } - } - }); } - private dropRunningReply(): void { - this.messages.update(list => { - const lastUser = list.map(message => message.from).lastIndexOf('USER'); - return lastUser >= 0 ? list.slice(0, lastUser + 1) : list; - }); - } - - private isConnectionLost(error: any): boolean { - return error instanceof HttpErrorResponse && error.status === 0; - } - - private handleChatEvent(chatMsg: ChatEvent): Observable { - switch (chatMsg.event) { - case 'assistantMessage': - this.messages.update(list => [...list, {from: 'AI', content: chatMsg.data.message}]); - return of(chatMsg); - case 'toolExecutionRequested': - return this.handleToolApproval(chatMsg); - case 'toolExecutionResult': - this.completedExecutions.update(map => ({...map, [chatMsg.data.executionId]: chatMsg.data})); - if (chatMsg.data.affectedEntities?.length) { - this.sessionAffectedEntities.push(...chatMsg.data.affectedEntities); + startResize(event: PointerEvent): void { + event.preventDefault(); + this.gripTip?.hide(0); + this.resizing.set(true); + const grip = event.target as HTMLElement; + const host = this.elementRef.nativeElement as HTMLElement; + const root = document.documentElement; + const startX = event.clientX; + const startWidth = this.width(); + this.room.set(host.parentElement?.clientWidth ?? window.innerWidth); + const widest = this.widest(); + let current = startWidth; + let closing = false; + let frame = 0; + let pageTimer: ReturnType | undefined; + let pageAt = 0; + const reflowPage = () => { + pageTimer = undefined; + pageAt = performance.now(); + root.style.setProperty('--tb-ai-panel-w', current + 'px'); + }; + const paint = () => { + frame = 0; + host.style.width = current + 'px'; + if (!pageTimer) { + pageTimer = setTimeout(reflowPage, Math.max(0, AiAssistantPanelComponent.PAGE_REFLOW_MS - (performance.now() - pageAt))); + } + }; + grip.setPointerCapture(event.pointerId); + document.body.classList.add('tb-ai-resizing'); + this.zone.runOutsideAngular(() => { + const move = (e: PointerEvent) => { + const wanted = startWidth + (startX - e.clientX); + const past = wanted < this.minWidth - AiAssistantPanelComponent.CLOSE_PAST; + if (past !== closing) { + closing = past; + host.classList.toggle('closing', past); } - return of(chatMsg); - case 'chatTitleGenerated': - this.handleChatTitleGenerated(chatMsg); - return of(chatMsg); - default: - if (chatMsg.event === 'error') { - this.showErrorToast(this.sanitizer.sanitize(SecurityContext.HTML, chatMsg.data?.message) ?? chatMsg.data?.message); + current = Math.round(Math.min(widest, Math.max(this.minWidth, wanted))); + if (!frame) { + frame = requestAnimationFrame(paint); } - return of(chatMsg); - } + }; + const up = () => { + grip.removeEventListener('pointermove', move); + grip.removeEventListener('pointerup', up); + grip.removeEventListener('pointercancel', up); + cancelAnimationFrame(frame); + clearTimeout(pageTimer); + document.body.classList.remove('tb-ai-resizing'); + host.classList.remove('closing'); + host.style.width = ''; + this.zone.run(() => { + this.resizing.set(false); + if (closing) { + this.setWidth(startWidth); + this.close(); + return; + } + this.setWidth(current, current !== startWidth); + }); + }; + grip.addEventListener('pointermove', move); + grip.addEventListener('pointerup', up); + grip.addEventListener('pointercancel', up); + }); } - private handleChatTitleGenerated(chatMsg: ChatTitleGeneratedEvent): void { - const chatId = this.chatId(); - const title = chatMsg.data.title; - if (!chatId || !title) return; - this.panelService.updateChatTitle(chatId, title); + close(): void { + this.panelService.close(); } - private handleToolApproval(chatMsg: ToolExecutionRequestedEvent): Observable { - if (!chatMsg.data.needsApproval) { - return of(chatMsg); + onClick(event: MouseEvent): void { + const chatId = this.chatId(); + const link = (event.target as HTMLElement | null)?.closest?.('a[href]') as HTMLAnchorElement | null; + if (!chatId || !link || link.target === '_blank' || link.origin !== window.location.origin + || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { + return; } - this.messages.update(list => [...list, {from: 'APPROVAL', data: chatMsg.data}]); - return of(chatMsg); + this.panelService.carryChat(chatId); } - private initLoadingState(): void { - this.loading.set(true); + onChatId(chatId: string | undefined): void { + this.chatId.set(chatId); + this.panelService.setLastChatId(chatId); } - private stopLoadingState(): void { - this.loading.set(false); + onSlideEnd(event: TransitionEvent): void { + if (event.target !== this.elementRef.nativeElement || event.propertyName !== 'transform' || !this.isOpen) { + return; + } + this.chat?.focus(); } - showErrorMessage(error: any): void { - const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; - const message = parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message; - this.showErrorToast(message); + private dropChatFromOtherContext(): void { + const chatId = this.chatId(); + if (chatId && chatId !== this.panelService.lastChatIdForContext()) { + this.chatId.set(undefined); + } } - private showErrorToast(message: string): void { - this.store.dispatch(new ActionNotificationShow({ - message, - target: 'aiAssistant', - modern: true, - type: 'error', - verticalPosition: 'bottom', - horizontalPosition: 'center' - })); + private selectLastChat(): void { + if (this.chatId()) { + return; + } + const carried = this.panelService.takeCarriedChat(); + if (carried && this.chats.find(carried)) { + this.chatId.set(carried); + return; + } + const lastId = this.panelService.lastChatIdForContext(); + if (lastId && this.chats.find(lastId)) { + this.chatId.set(lastId); + } } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html index e81e8a2cf7..2b89549dd6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html @@ -5,12 +5,23 @@ --> -

{{ data.resource.name }}

+

{{ title }}

- + @if (data.downloadPng) { + + + + + + } @else { + + }
+ + {{ fileName(item.resource.name).base }}{{ fileName(item.resource.name).ext }} + @if (!item.image && item.extension) { {{ item.extension }} · }{{ factOf(item) ?? (item.resource.size | fileSize) }} + + }
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss index 9da645eb8a..0d9b0dcfcd 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss @@ -2,100 +2,84 @@ // SPDX-License-Identifier: BUSL-1.1 :host { display: block; - max-width: 100%; - - .attachments { - display: flex; - flex-wrap: wrap; - gap: 8px; - justify-content: inherit; - } - - .attachment { - position: relative; - display: flex; - align-items: center; - border-radius: 10px; - border: 1px solid rgba(0, 0, 0, 0.12); - background: #fff; - overflow: hidden; - flex: none; - cursor: pointer; - - &:hover { - border-color: var(--tb-primary-500); - } +} - &.image { - width: 64px; - height: 64px; - justify-content: center; - background: rgba(0, 0, 0, 0.04); +.k-files { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 6px; + font-size: 14px; + line-height: 20px; + color: var(--tb-ink); +} - img { - width: 100%; - height: 100%; - object-fit: cover; - } +.k-file { + display: flex; + align-items: center; + gap: 10px; + max-width: 100%; + min-width: 0; + padding: 6px 10px 6px 8px; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + font: 400 13.5px/20px var(--tb-font); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); + text-align: left; + cursor: pointer; - .placeholder { - color: rgba(0, 0, 0, 0.38); - } - } + &:hover { + border-color: rgba(0, 0, 0, 0.2); + } - &.file { - gap: 8px; - height: 48px; - max-width: 220px; - padding: 0 12px 0 8px; + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } - .file-icon { - display: flex; - align-items: center; - justify-content: center; - flex: none; - width: 32px; - height: 32px; - border-radius: 8px; - color: var(--tb-primary-500); - position: relative; + > .mat-icon { + flex: none; + color: var(--tb-ink-54); + } +} - &:before { - content: ""; - position: absolute; - inset: 0; - border-radius: inherit; - background: var(--tb-primary-500); - opacity: 0.1; - } +.k-file-pic { + flex: none; + width: 32px; + height: 32px; + overflow: hidden; + border-radius: 6px; + background: linear-gradient(135deg, #cfd8dc, #90a4ae); + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.06); - mat-icon { - font-size: 20px; - width: 20px; - height: 20px; - } - } + img { + display: block; + width: 100%; + height: 100%; + object-fit: cover; + } +} - .file-meta { - display: flex; - flex-direction: column; - min-width: 0; - line-height: 16px; +.k-file-text { + display: flex; + flex-direction: column; + min-width: 0; - .file-name { - font-size: 13px; - color: rgba(0, 0, 0, 0.87); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - } + b { + max-width: 240px; + overflow: hidden; + font-size: 13.5px; + line-height: 18px; + font-weight: 500; + text-overflow: ellipsis; + white-space: nowrap; + } - .file-info { - font-size: 11px; - color: rgba(0, 0, 0, 0.54); - white-space: nowrap; - } - } - } + small { + font-size: 12px; + line-height: 16px; + color: var(--tb-ink-76); } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts index 86db1c6232..7ceb5185ef 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts @@ -1,12 +1,14 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +import { aiFileName } from '@home/components/ai/ai-file.models'; import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { Observable } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { AiResourceInfo, isAiImageResource } from '@shared/models/ai-chat.models'; import { AiResourceService } from '@core/http/ai-resource.service'; -import { aiAttachmentExtension, aiAttachmentKind } from '@home/components/ai/ai-attachment.models'; +import { aiAttachmentExtension, aiAttachmentKind, aiResourceFact } from '@home/components/ai/ai-attachment.models'; +import { TranslateService } from '@ngx-translate/core'; import { AiAttachmentPreviewDialogComponent, AiAttachmentPreviewDialogData @@ -28,14 +30,21 @@ interface AiAttachmentItem { }) export class AiAttachmentsComponent implements OnChanges { + readonly fileName = aiFileName; + @Input() resources: AiResourceInfo[]; @Output() resourceError = new EventEmitter(); shown: AiAttachmentItem[] = []; + factOf(item: AiAttachmentItem): string | null { + return item.image ? null : aiResourceFact(item.resource.facts, this.translateService); + } + constructor(private aiResourceService: AiResourceService, - private dialog: MatDialog) { + private dialog: MatDialog, + private translateService: TranslateService) { } ngOnChanges(changes: SimpleChanges): void { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-breakpoints.ts b/ui-ngx/src/app/modules/home/components/ai/ai-breakpoints.ts new file mode 100644 index 0000000000..25163607eb --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-breakpoints.ts @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +// The chat head is narrow below this width (px); the CSS breakpoints of the AI chat are in _ai-breakpoints.scss. +export const AI_NARROW_HEAD_WIDTH = 500; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts new file mode 100644 index 0000000000..fa7b749311 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, input, output } from '@angular/core'; + +export interface AiCardAction { + id: string; + label: string; + icon?: string; + quiet?: boolean; + compose?: string; + pressed?: boolean; + tip?: string; +} + +@Component({ + selector: 'tb-ai-card-actions', + template: ` + @for (action of actions(); track action.id) { + + } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'k-chips', + 'role': 'group' + } +}) +export class AiCardActionsComponent { + + actions = input.required(); + + act = output(); + + compose = output(); + + press(action: AiCardAction): void { + if (action.compose) { + this.compose.emit(action.compose); + } else { + this.act.emit(action.id); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html index 7fd251f846..59a674dcf7 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html @@ -5,47 +5,339 @@ --> @for (msg of messages; track $index) { - @if (msg.from === 'USER') { + @if (dayLines[$index]; as day) { + + } + @if (msg.from === 'USER' && (msg.answers?.length || answersAt[$index])) { + + } @else if (msg.from === 'USER') { + @if (msg.startedFrom) { + + }
- @if (msg.resources?.length) { - - } - @if (msg.content) { -
{{ msg.content }}
+
+ @if (quotes[$index]; as quoted) { + + + {{ fileName(quoted.name).base }}{{ fileName(quoted.name).ext }}{{ (quoted.from === quoted.to ? 'ai-assistant.file.line' : 'ai-assistant.file.lines-range') | translate: {from: quoted.from, to: quoted.to} }} + + } + @if (quotes[$index] ? quotes[$index].message : msg.content; as words) { +
{{ words }}
+ @if (isFolded($index, words)) { + + } + } + @if (msg.resources?.length) { + + } +
+
+ @if (msg.content) { + + + + + } + @if (msg.time) { + + } +
+
+ } @else if (msg.from === 'ACTION' && files[$index] && inCard.has(files[$index].name)) { + } @else if (msg.from === 'ACTION' && files[$index]; as file) { +
+ +
+ } @else if (msg.from === 'ACTION' && madeFiles[$index]?.preview === 'image') { + @let pic = madeFiles[$index]; +
+ +
+ } @else if (msg.from === 'ACTION' && madeFiles[$index]; as made) { +
+
+ + +
+
+ } @else if (msg.from === 'ACTION' && plans[$index]; as plan) { +
+ +
+ } @else if (msg.from === 'ACTION' && handOvers[$index]; as card) { +
+ +
+ @if (waitAfterCard[$index] !== undefined && messages[waitAfterCard[$index]]; as moved) { + @if (moved.from === 'ACTION' && !waitsInCards.has(waitAfterCard[$index])) { +
+ +
} + } + } @else if (msg.from === 'ACTION' && asking?.index === $index) { +
+
+ } @else if (msg.from === 'ACTION') { + @if (isListedAction(msg, $index) && !groupedAway.has($index) && (msg.data.status !== 'RUNNING' || $index === runningLead)) { +
+ + @if ($index === retryIndex) { +
+ } +
+
+ } } @else { -
+ @if ($index === offerIndex) { +
+
+ + {{ 'ai-assistant.offer.text' | translate }} + +
+
+ } +
@if (msg.from === 'APPROVAL') { + [answered]="!!denyReasons[getApprovalData(msg).executionId]" + [busy]="loading" + (approvalAction)="approval($event)" + (answerLater)="answerLater.emit($event)"> - } @else if (msg.status === 'INCOMPLETE') { -
- warning_amber - {{ msg.content }} -
+ } @else if (msg.status === 'RETRIED' || msg.status === 'RESUMED') { +

{{ (msg.status === 'RETRIED' ? 'ai-assistant.failed.tried-again' : 'ai-assistant.failed.resumed') | translate: {time: clockText(msg.time)} }}

+ } @else if (msg.status === 'INCOMPLETE' || msg.status === 'STOPPED') { + @if (msg.status === 'INCOMPLETE') { +
+

{{ 'ai-assistant.failed.headline' | translate }} {{ failText($index, msg) }}

+ @if ($last && !loading && retry.observed) { +
+ } +
+ } @else { +

{{ stoppedText($index, msg.content) }}

+ } + @if (summaries[$index]; as entities) { + + } + @if (msg.status === 'STOPPED' && $last && !loading) { + @if (msg.chips?.length) { + + } @else { + + } + } } @else { - +
+ @if (msg.done) { + + } +
+ @if (msg.lead) { +

{{ msg.lead }}

+ } + @for (key of [decorationKey(msg)]; track key) { + + } + @let madeHere = made[$index] ?? []; + @for (shown of records[$index] ?? []; track $index) { + + } + @if (summaries[$index]; as entities) { + + } + @if (msg.entities?.length) { + + } + @if (msg.hint; as hint) { +
+ + {{ hint.lead }} {{ hint.text }} +
+ } +
+
+ @if (msg.note) { +

{{ msg.note }}

+ } + @if (sources[$index]; as cited) { +
+ @for (source of cited; track source.url) { +
+
+ + + +
+ @if (source.quote) { +
{{ source.quote }}
+ } +
+ } +
+ } + @if (!msg.streaming) { +
+ @if (msg.time) { + + } + + + @if (feedback) { + + + + } + +
+ } + @if (prompts?.index === $index) { +
+ @for (option of prompts.items; track $index) { + + } +
+ } + @if (msg.chips?.length) { + + } + @if (reportingIndex === $index) { +
+
{{ 'ai-assistant.feedback.what-went-wrong' | translate }}
+
+ @for (problem of problems; track problem) { + + } +
+ +

{{ 'ai-assistant.feedback.sent-with' | translate }}

+
+ + +
+
+ } }
+ @if (msg.from === 'APPROVAL' && denyReasonOf(msg); as reason) { +
+
{{ reason }}
+
+ } } } -@if (loading && !waitApproval) { -
- @if (loadingLongTime) { - +@if (dock && dockVisible) { +
+
+ + @if (dock.kind === 'hand' && dock.state !== 'stopped') {{{ 'ai-assistant.plan.you' | translate }}}{{ dock.text }} + @if (dock.count) { + {{ dock.count }} + } + @if (dock.kind === 'hand' && dock.state === 'listen' && dock.canTest) { + + } + @if (dock.kind === 'hand' && dock.state === 'stopped' && !loading) { + + } + +
+
+} +@if (loading && !waitApproval && !actionRunning && !streaming) { +
+ @if (work) { + } @else { - - - +
{{ 'ai-assistant.thinking' | translate }}
}
} + + + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index c9b42e734e..5583c127d2 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -1,94 +1,316 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +@use './ai-code-blocks' as *; + :host { display: flex; flex-direction: column; - gap: 24px; + gap: var(--chat-turn-gap); overflow: auto; + font-family: var(--tb-font); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); width: 100%; margin-top: 8px; flex: 1 1 auto; - .image-main-color { - color: var(--tb-primary-500); - } - .user { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; - .user-attachments { - max-width: 80%; + .turn { + display: grid; + justify-items: end; + gap: 6px; + max-width: 85%; + font-size: 14px; + line-height: 20px; - ::ng-deep .attachments { - justify-content: flex-end; + tb-ai-attachments { + margin-top: 8px; + } - .attachment.image { - width: 120px; - height: 90px; - } + @container k-chat (max-width: 599px) { + max-width: 88%; + } + + .msg { + max-width: none; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); } } + .msg .words { + display: block; + white-space: pre-line; + } + + .msg.folded .words { + display: block; + max-height: calc(6 * var(--chat-text-lh)); + overflow: hidden; + mask-image: linear-gradient(to bottom, #000 calc(100% - var(--chat-text-lh)), transparent); + } + + .show-all { + margin: 0; + } + .msg { - max-width: 80%; - padding: 10px 18px; - border-radius: 12px 12px 0 12px; - position: relative; + max-width: 85%; + padding: 12px 16px; + border-radius: 16px 16px 4px 16px; + background: var(--ai-person); overflow: hidden; - white-space: pre-line; - word-break: break-word; - line-height: 24px; - color: rgba(0, 0, 0, 0.76); + overflow-wrap: anywhere; - &:before { - display: block; - height: auto; - content: ""; - position: absolute; - inset: 0; - background: var(--tb-primary-500); - opacity: 0.1; - pointer-events: none; + @container k-chat (max-width: 599px) { + max-width: 88%; + padding: 10px 14px; } + color: var(--tb-ink); + } + } + + .msg-foot { + display: flex; + align-items: center; + gap: 2px; + min-height: 24px; + margin-top: 0; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--k-faint); + font-variant-numeric: tabular-nums; + + &.agent-foot { + margin-top: 0; + } + + time { + margin-right: 6px; + } + } + + .foot-tools { + display: inline-flex; + align-items: center; + gap: 2px; + opacity: 0; + transition: opacity .12s ease; + + &.show { + opacity: 1; + } + + @media (prefers-reduced-motion: reduce) { + transition: none; } } - .incomplete { - padding: 10px 14px; + .user-foot { + justify-content: flex-end; + + time { + order: 2; + } + } + + .k-day { + display: flex; + align-items: center; + gap: 12px; + font-size: 12px; + line-height: 16px; + letter-spacing: .25px; + color: var(--tb-ink-54); + + &::before, &::after { + content: ''; + flex: 1 1 0%; + height: 1px; + background: var(--tb-line); + } + } + + .user:hover .foot-tools, .user:focus-within .foot-tools, + .ai:hover .foot-tools, .ai:focus-within .foot-tools { + opacity: 1; + } + + .foot-tool { + font-size: 12px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + color: var(--tb-ink-54); + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.05); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + &.done { + color: var(--tb-ok); + } + + &[aria-pressed="true"] { + color: var(--ai-selected); + } + + &.muted:not([aria-pressed="true"]) { + color: var(--tb-ink-38); + } + + &:disabled { + cursor: default; + background: none; + } + } + + .k-report { + display: grid; + gap: 10px; + max-width: 560px; + margin-top: 8px; + padding: 14px 16px; + border: 1px solid var(--tb-line); border-radius: 12px; - line-height: 20px; - color: rgba(0, 0, 0, 0.76); - background: rgba(255, 152, 0, 0.08); + background: var(--tb-surface); + + .k-report-t { + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink); + } + + .k-chips { + gap: 6px; + } - .incomplete-icon { - flex: none; - color: #FF9800; - font-size: 20px; - width: 20px; - height: 20px; + .k-report-note { + margin: 0; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-faint); } + + .k-actions { + margin-top: 0; + } + } + + .agent { + display: block; + + .agent-body { + min-width: 0; + } + + &.done { + display: flex; + align-items: flex-start; + gap: 8px; + + > .done-mark { + flex: none; + margin-top: 2px; + font-size: 20px; + width: 20px; + height: 20px; + line-height: 20px; + color: var(--tb-ok-text); + } + + > .agent-body { + flex: 1; + } + } + + .lead { + margin: 0 0 14px; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + font-weight: 500; + color: var(--tb-ink); + } + } + + .agent-card { + display: block; + margin-top: 12px; + } + + .agent-hint { + margin: 12px 0 4px; + } + + .agent-chips { + margin-top: 8px; + } + + .agent-note { + margin: 14px 0 4px; + letter-spacing: .25px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--k-grey); + } + + .stop-note { + margin: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); + } + + .ai.action + .ai.action { + margin-top: calc(6px - var(--chat-turn-gap)); } .generating { + gap: 10px; + + .work { + flex: 1; + min-width: 0; + } + + .tb-ai-mark { + --m: var(--chat-mark); + } + + font-size: var(--chat-line); + line-height: var(--chat-line-lh); transition: all 0.3s ease-in-out; .glow-container { color: transparent; overflow: hidden; position: relative; - background: linear-gradient(90deg, #3D3D3D -40.76%, #808080 -23.64%, #3D3D3D -6.52%); + background: linear-gradient(90deg, var(--tb-ink-76) -40.76%, var(--tb-ink-38) -23.64%, var(--tb-ink-76) -6.52%); background-clip: text; animation: fadeInScale 0.3s ease-in-out forwards; opacity: 0; transform: scale(0.95); - &.ng-leave { - animation: fadeOutScale 0.3s ease-in-out forwards; - } - &:before { content: ""; display: block; @@ -99,7 +321,7 @@ height: 100%; flex-shrink: 0; opacity: 0.5; - background: #FFF; + background: var(--tb-surface); filter: blur(2px); transform: skewX(-25deg); animation: glow-move 3s ease-in-out infinite; @@ -121,26 +343,300 @@ } - &::ng-deep { - .tb-markdown-view { - h2 { - font-size: 28px; + .user .msg-foot time { + margin: 0 0 0 6px; + } + + &::ng-deep .ai .agent-body:has(> .lead) .tb-markdown-view [class*="tb-markdown-view-"] ol { + padding-left: 20px; + + li + li { + margin-top: 6px; + } + } + + &::ng-deep .ai .agent-body .tb-markdown-view { + font-family: var(--tb-font); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); + + [class*="tb-markdown-view-"] { + > p, > div, > ul, > ol, > table, > pre, > h1, > h2, > h3, > h4, > h5, > h6, > div.code-wrapper { + padding-left: 0; + padding-right: 0; + margin-left: 0; } - h3 { - font-size: 24px; + p, div, li { + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); } - h4 { - font-size: 20px; + p { + margin: 0; + } + + > * + *, > * + p { + margin-top: 14px; + } + + h1, h2, h3, h4, h5, h6 { + padding: 0; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + font-weight: 500; + color: var(--tb-ink); + } + + ul, ol { + margin: 0; + padding-left: 24px; + padding-right: 0; + color: var(--tb-ink); + } + + > p + ul, > p + ol { + margin-top: 6px; } - h5, h6 { - font-size: 18px; + li { + padding-bottom: 0; + + & + li { + margin-top: 4px; + } + + &::marker { + color: var(--tb-text-muted); + } + } + + strong, b { + font-weight: 500; + } + + code:not([class*=language-]):not(.k-ent):not(pre code) { + display: inline-block; + white-space: nowrap; + padding: var(--chat-chip-pad, 1px) 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: var(--chat-chip-mono, 14px); + line-height: var(--chat-chip-lh, 18px); + color: var(--tb-ink); + } + + a.tb-chiplink { + font-weight: 400; + color: var(--tb-ink); + } + + code.k-ent { + display: inline-block; + max-width: 100%; + box-sizing: border-box; + padding: var(--chat-chip-pad, 1px) 7px; + border-radius: 5px; + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--tb-line); + font: 400 var(--chat-chip, 14px)/var(--chat-chip-lh, 18px) var(--tb-font); + color: var(--tb-ink); + white-space: nowrap; } - a { + a.tb-chiplink > code.k-ent { + padding-right: 2px; + } + + a.tb-chiplink:hover > code.k-ent, a.tb-chiplink:focus-visible > code.k-ent { + box-shadow: inset 0 0 0 1px var(--tb-ink-38); + } + + .k-ext-tail { + white-space: nowrap; + } + + .k-ext-tail > .k-ext { + display: inline-block; + width: 13px; + height: 13px; + margin-left: 1px; + font-size: 13px; + line-height: 13px; + vertical-align: -1px; + opacity: .82; + text-decoration: none; + } + + a:not(.tb-chiplink) { + font-weight: 400; + color: var(--ai-link); + text-decoration: none; + border-bottom: 1px solid transparent; word-break: break-word; + + &:hover { + color: var(--ai-link-strong); + text-decoration: none; + border-bottom-color: currentColor; + } + } + + > table { + display: block; + width: fit-content; + max-width: 100%; + box-sizing: border-box; + overflow-x: auto; + scrollbar-width: thin; + margin: 14px 0 0; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + border-collapse: separate; + border-spacing: 0; + table-layout: auto; + font-size: 14px; + line-height: 20px; + font-variant-numeric: tabular-nums; + + > thead { + background: none; + + > tr > th { + padding: 8px 20px 8px 0; + font-size: 12.5px; + line-height: 16px; + font-weight: 500; + color: var(--tb-text-secondary); + border: 0; + border-bottom: 1px solid var(--tb-line); + text-align: left; + white-space: nowrap; + } + } + + > tbody > tr > td { + padding: 7px 20px 7px 0; + font-size: 14px; + line-height: 20px; + color: var(--tb-ink); + border: 0; + border-bottom: 1px solid rgba(0, 0, 0, 0.06); + vertical-align: top; + white-space: nowrap; + } + + > tbody > tr:last-child > td { + border-bottom: 0; + } + + th:first-child, td:first-child { + padding-left: 12px; + } + + th:last-child, td:last-child { + padding-right: 12px; + } + + td.long { + white-space: normal; + min-width: 16em; + } + + th[align="right"], td[align="right"] { + text-align: right; + } + + th[align="center"], td[align="center"] { + text-align: center; + } + + td code.k-ent { + padding: 0; + background: none; + box-shadow: none; + font-weight: 400; + } + + td:first-child code.k-ent { + font-weight: 500; + } + + td .tb-chip-go { + display: none; + } + + td a.tb-chiplink > code.k-ent { + padding: 0; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: color-mix(in srgb, currentColor 28%, transparent); + transition: text-decoration-color .12s ease; + } + + td a.tb-chiplink:hover > code.k-ent, td a.tb-chiplink:focus-visible > code.k-ent { + box-shadow: none; + text-decoration-color: currentColor; + } + + @container k-col (max-width: 480px) { + th:first-child, td:first-child { + position: sticky; + left: 0; + z-index: 1; + padding-left: 8px; + padding-right: 10px; + background: var(--tb-surface); + border-right: 1px solid var(--tb-line); + white-space: normal; + } + + th:nth-child(2), td:nth-child(2) { + padding-left: 12px; + } + + th:last-child, td:last-child { + padding-right: 8px; + } + + td:first-child > .k-md-lead { + display: inline-block; + width: max-content; + max-width: 172px; + vertical-align: top; + } + } + } + + @include ai-code-blocks; + } + } + + &::ng-deep tb-ai-action-detail { + @include ai-code-blocks; + } + + &::ng-deep tb-ai-hand-over { + @include ai-code-blocks; + } + + &::ng-deep tb-ai-approval-card { + @include ai-code-blocks; + + .k-review-code { + margin-top: 10px; + + .tb-code { + max-height: 320px; + overflow-y: auto; + scrollbar-width: thin; } } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts index 7818491ccc..9540bfc852 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts @@ -1,47 +1,521 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Component, ElementRef, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; -import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; -import { ApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; +import { aiClockText, aiLocale } from '@home/components/ai/ai-text'; +import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostListener, inject, Input, OnChanges, OnDestroy, Output, SimpleChanges } from '@angular/core'; +import { ActionChatMessage, AiQuestion, AiQuestionAnswer, ApprovalChatMessage, ChatMessage, GeneralChatMessage } from '@shared/models/solution-creator.models'; +import { ClipboardService } from 'ngx-clipboard'; +import { Observable, of } from 'rxjs'; +import { catchError, shareReplay } from 'rxjs/operators'; +import { TranslateService } from '@ngx-translate/core'; +import { + ANSWER_PROBLEMS, + AnswerProblem, + AnswerRating, + ApprovalResult, + aiQuoteOf, + ToolExecutionRequested, + ToolApprovalResult, + ToolExecutionResult +} from '@shared/models/ai-chat.models'; +import { + aiConnectionCheckOf, + AiHandOver, + aiHandOverOf, + AiHandOverStep, + aiPlanOf, + AiPlanProgress, + aiPlanProgressOf, + AiPlanStep, + AiPrompt, + aiPromptsOf, + aiQuestionsOf, + AiSource, + aiSourcesOf, + AiWorkState, + ASK_USER_TOOL, + CHECK_CONNECTION_TOOL, + CITE_SOURCES_TOOL, + HAND_OVER_TOOL, + AiAction, + aiGroupableRead, + isHiddenAiAction, + isKitCardTool, + aiPlanStatus, + PROPOSE_PLAN_TOOL, + SUGGEST_PROMPTS_TOOL, + UPDATE_PLAN_TOOL +} from '@home/components/ai/ai-action.models'; +import { AiPlanRun } from '@home/components/ai/ai-plan.component'; +import { aiRecordKey, AiShownRecords, aiShownRecordsOf, SHOW_RECORDS_TOOL } from '@home/components/ai/ai-record.models'; +import { AiCardAction } from '@home/components/ai/ai-card-actions.component'; +import { decorateSections } from '@home/components/ai/ai-disclosure.component'; +import { AiFile, aiFileMark, aiFileName, aiFileOf, AiMadeFile, aiMadeFileOf, FILE_MAKING_TOOLS, WRITE_FILE_TOOL } from '@home/components/ai/ai-file.models'; +import { MatDialog } from '@angular/material/dialog'; +import { AiResourceService } from '@core/http/ai-resource.service'; +import { + AiAttachmentPreviewDialogComponent, + AiAttachmentPreviewDialogData +} from '@home/components/ai/ai-attachment-preview-dialog.component'; +import { aiAnswersOf, aiAnswersPrompt } from '@home/components/ai/ai-question.component'; +import { EntityId } from '@shared/models/id/entity-id'; + +export interface AnswerRatingEvent { + index: number; + rating: AnswerRating; +} + +export interface AnswerReportEvent { + index: number; + problem: AnswerProblem; + comment?: string; +} +import { aiFenceMeta, announceCopied, decorateCodeBlocks, decorateTables, fileLanguage } from '@home/components/ai/ai-code-block'; +import { AiHandOverWait } from '@home/components/ai/ai-hand-over.component'; +import { aiDetailNames, AiDetailNames } from '@home/components/ai/ai-action-detail.models'; +import { decorateFileChips, decorateHints, decorateLinks, decorateReferences, decorateSeverities, decorateValues } from '@home/components/ai/ai-references'; +import { AlarmSeverity, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { Router } from '@angular/router'; + +const SOLUTION_STEP_TOOLS = ['create_solution', 'install_solution']; + +interface AiDockRow { + kind: 'hand' | 'plan'; + index: number; + text: string; + state: 'listen' | 'stopped' | 'run' | 'idle'; + count?: string; + canTest?: boolean; +} @Component({ + changeDetection: ChangeDetectionStrategy.OnPush, selector: 'tb-ai-chat-messages', templateUrl: './ai-chat-messages.component.html', styleUrls: ['./ai-chat-messages.component.scss'], standalone: false }) -export class AiChatMessagesComponent implements OnChanges { +export class AiChatMessagesComponent implements OnChanges, OnDestroy { @Input() messages: ChatMessage[] = []; @Input() loading = false; - @Input() loadingLongTime = false; @Input() additionalStyles: string[]; @Input() completedExecutions: Record = {}; + + @Input() toolDurations: Record = {}; @Input() autoApprove = false; + @Input() scrollContainer: HTMLElement; + @Input() initialScroll: 'lastUserMessage' | 'bottom' = 'lastUserMessage'; + @Input() denyReasons: Record = {}; + @Input() work: AiWorkState | undefined; + @Input() feedback = false; + @Input() shownFile: string | null = null; + + latestFiles = new Map(); + + readonly fileMark = aiFileMark; + + readonly fileName = aiFileName; + + shownFileName(): string | null { + return this.shownFile ? Object.values(this.files).find(file => file.executionId === this.shownFile)?.name ?? null : null; + } + @Input() ghostFirst = false; + + detailNames: AiDetailNames = new Map(); + @Output() rate = new EventEmitter(); + @Output() chip = new EventEmitter(); + @Output() report = new EventEmitter(); @Output() approvalAction = new EventEmitter(); + @Output() answerLater = new EventEmitter(); + @Output() editMessage = new EventEmitter(); + @Output() resume = new EventEmitter(); + @Output() dockShown = new EventEmitter(); + @Output() listen = new EventEmitter(); + @Input() slotTaken = false; + testRequests: Record = {}; + + private readonly severityWord = (severity: string): string => this.translate.instant('alarm.severity-' + severity.toLowerCase()); + dock: AiDockRow | null = null; + private madeUrls = new Map>(); + dockVisible = false; + dockBelow = false; + private dockScroller: HTMLElement | null = null; + private readonly placeDockOnScroll = () => this.placeDock(); + @Output() retry = new EventEmitter(); + @Output() autoApproveRest = new EventEmitter(); + @Output() runPlan = new EventEmitter<{run: AiPlanRun; steps: AiPlanStep[]}>(); + @Output() changePlan = new EventEmitter(); + @Output() openFile = new EventEmitter(); + @Output() prompt = new EventEmitter(); + @Output() stopRun = new EventEmitter(); + + @Output() compose = new EventEmitter(); + @Output() answer = new EventEmitter<{message: string; secrets?: Record}>(); @Output() resourceError = new EventEmitter(); waitApproval = false; - constructor(private elementRef: ElementRef) {} + actionRunning = false; + + runningLead = -1; + + readGroups: Record = {}; + + groupedAway = new Set(); + + runningCount = 0; + + summaries: Record = {}; + prompts: {index: number; items: AiPrompt[]} | null = null; + asking: {index: number; questions: AiQuestion[]} | null = null; + retryIndex = -1; + stoppedSteps: Record = {}; + answersAt: Record = {}; + offerIndex = -1; + streaming = false; + files: Record = {}; + madeFiles: Record = {}; + inCard = new Set(); + private handledMadeFiles = new Set(); + quotes: Record = {}; + sources: Record = {}; + + records: Record = {}; + + made: Record = {}; + plans: Record = {}; + handOvers: Record = {}; + waitsInCards = new Set(); + private movedWaits = new Set(); + waitAfterCard: Record = {}; + + private keptAsking = new Set(); + + dayLines: Record = {}; + + private unfolded = new Set(); + + private dayTimer: ReturnType; + + private static readonly PIN_TO_BOTTOM_MS = 1500; + private static readonly COPIED_MS = 1500; + private static readonly FOLD_LINES = 6; + private static readonly FOLD_CHARS = 600; + + private releaseBottom: () => void; + private releaseAsk: () => void; + + lastAnswerIndex = -1; + + readonly problems = ANSWER_PROBLEMS; + + reportingIndex = -1; + + reportProblem: AnswerProblem | null = null; + + copiedIndex = -1; + + private cd = inject(ChangeDetectorRef); + + private copiedTimeout: ReturnType; + + constructor(private elementRef: ElementRef, + private clipboard: ClipboardService, + private translate: TranslateService, + private router: Router, + private dialog: MatDialog, + private aiResourceService: AiResourceService) {} + + madeUrl(file: AiMadeFile): Observable { + let url = this.madeUrls.get(file.executionId); + if (!url) { + url = this.aiResourceService.getUrl(file.resource.id).pipe(catchError(() => of(null)), shareReplay(1)); + this.madeUrls.set(file.executionId, url); + } + return url; + } + + openMadeFile(file: AiMadeFile): void { + if (file.preview === 'image') { + this.dialog.open(AiAttachmentPreviewDialogComponent, { + panelClass: ['tb-dialog', 'tb-ai-attachment-preview-dialog'], + maxWidth: '92vw', + data: {resource: file.resource} + }); + } else { + this.downloadMadeFile(file); + } + } + + private downloadRequestedFiles(): void { + for (const file of Object.values(this.madeFiles)) { + if (this.handledMadeFiles.has(file.executionId)) { + continue; + } + this.handledMadeFiles.add(file.executionId); + if (file.download && this.loading) { + this.downloadMadeFile(file); + } + } + } + + downloadMadeFile(file: AiMadeFile): void { + this.aiResourceService.download(file.resource).subscribe({ + error: error => this.resourceError.emit(error) + }); + } + + copyText(text: string, index: number): void { + if (this.clipboard.copyFromContent(text)) { + this.copiedIndex = index; + announceCopied(this.translate.instant('ai-assistant.copied')); + clearTimeout(this.copiedTimeout); + this.copiedTimeout = setTimeout(() => { + this.copiedIndex = -1; + this.cd.markForCheck(); + }, AiChatMessagesComponent.COPIED_MS); + } + } + + decorationKey(message: ChatMessage): string { + const general = message as GeneralChatMessage; + return `${general.references?.length ?? 0}:${general.severities?.length ?? 0}:${general.readings?.length ?? 0}`; + } + + decorateCode(answer: HTMLElement, message?: ChatMessage): void { + decorateCodeBlocks(answer, this.translate, text => this.clipboard.copyFromContent(text)); + decorateTables(answer); + decorateSections(answer, this.sectionScope(message)); + decorateReferences(answer, (message as GeneralChatMessage)?.references); + decorateLinks(answer, this.translate.instant('ai-assistant.opens-new-tab')); + decorateHints(answer); + decorateValues(answer, (message as GeneralChatMessage)?.readings); + decorateFileChips(answer, this.latestFiles, this.shownFileName()); + decorateSeverities(answer, (message as GeneralChatMessage)?.severities, + severity => this.translate.instant(alarmSeverityTranslations.get(severity as AlarmSeverity) ?? severity)); + } + + private sectionScope(message?: ChatMessage): string { + const general = message as GeneralChatMessage; + return String(general?.time ?? ''); + } + + @HostListener('click', ['$event']) + openInApp(event: MouseEvent): void { + if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { + return; + } + const chip = (event.target as HTMLElement)?.closest('.agent .art-chip[data-file]'); + const chipFile = chip ? this.latestFiles.get(chip.dataset.file) : undefined; + if (chipFile) { + event.preventDefault(); + this.openFile.emit(chipFile); + return; + } + const link = (event.target as HTMLElement)?.closest('.agent a[href]') as HTMLAnchorElement | null; + if (!link || link.target === '_blank' || link.origin !== location.origin) { + return; + } + event.preventDefault(); + this.router.navigateByUrl(link.pathname + link.search + link.hash); + } + + isFolded(index: number, content: string): boolean { + return !this.unfolded.has(index) && (content.split('\n').length > AiChatMessagesComponent.FOLD_LINES || content.length > AiChatMessagesComponent.FOLD_CHARS); + } + + unfold(index: number): void { + this.unfolded.add(index); + } + + withoutDoneMark(content: string): string { + return (content ?? '').replace(/^\s*(✅|🛠️|🛠|🤔|💡|🛑)\s*/u, ''); + } + + copyAnswer(answer: HTMLElement, index: number): void { + const text = (answer.querySelector('tb-markdown') ?? answer).innerText.trim(); + if (this.clipboard.copyFromContent(text)) { + this.copiedIndex = index; + announceCopied(this.translate.instant('ai-assistant.copied')); + clearTimeout(this.copiedTimeout); + this.copiedTimeout = setTimeout(() => { + this.copiedIndex = -1; + this.cd.markForCheck(); + }, AiChatMessagesComponent.COPIED_MS); + } + } + + toggleRating(index: number, current: string | undefined, rating: 'UP' | 'DOWN'): void { + this.rate.emit({index, rating: current === rating ? 'NONE' : rating}); + } + + openReport(index: number): void { + this.reportingIndex = index; + this.reportProblem = null; + setTimeout(() => this.revealReport()); + } + + private revealReport(): void { + this.reveal(this.elementRef.nativeElement.querySelector('.k-report')); + } + + private keepAskInView(): void { + const ask = this.elementRef.nativeElement.querySelector('.ai.ask'); + if (!ask) { + return; + } + this.releaseAsk?.(); + const scroller = this.scroller; + const show = () => this.reveal(ask, 'auto'); + const observer = new ResizeObserver(show); + observer.observe(this.elementRef.nativeElement); + const release = () => { + observer.disconnect(); + clearTimeout(timeout); + scroller.removeEventListener('wheel', release); + scroller.removeEventListener('touchstart', release); + scroller.removeEventListener('keydown', release); + scroller.removeEventListener('pointerdown', release); + this.releaseAsk = undefined; + }; + const timeout = setTimeout(release, AiChatMessagesComponent.PIN_TO_BOTTOM_MS); + scroller.addEventListener('wheel', release, {passive: true}); + scroller.addEventListener('touchstart', release, {passive: true}); + scroller.addEventListener('keydown', release); + scroller.addEventListener('pointerdown', release, {passive: true}); + this.releaseAsk = release; + this.reveal(ask); + } + + private reveal(report: HTMLElement | null, behavior: ScrollBehavior = 'smooth'): void { + const scroller = report?.closest('.ai-chat-body') ?? (report ? this.scroller : null); + if (!report || !scroller) { + return; + } + const composer = scroller.querySelector('.ai-chat-composer'); + const cover = composer?.querySelector('.k-pill') ?? composer; + const limit = Math.min(scroller.getBoundingClientRect().bottom, cover?.getBoundingClientRect().top ?? Infinity) - 12; + const rect = report.getBoundingClientRect(); + const top = scroller.getBoundingClientRect().top + 12; + const overflow = Math.min(rect.bottom - limit, rect.top - top); + if (overflow > 0) { + scroller.scrollBy({top: overflow, behavior: this.motion(behavior)}); + } + } + + closeReport(): void { + this.reportingIndex = -1; + this.reportProblem = null; + } + + sendReport(index: number, comment: string): void { + if (!this.reportProblem) { + return; + } + const words = comment.trim(); + this.report.emit(words ? {index, problem: this.reportProblem, comment: words} : {index, problem: this.reportProblem}); + this.closeReport(); + } + + fullTime(time: number): string { + const zone = Intl.DateTimeFormat().resolvedOptions().timeZone; + const text = new Intl.DateTimeFormat(undefined, { + weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' + }).format(time); + return zone ? `${text} (${zone})` : text; + } getApprovalData(msg: ApprovalChatMessage): ToolExecutionRequested { return msg.data; } + denyReasonOf(msg: ApprovalChatMessage): string | undefined { + return this.completedExecutions[msg.data.executionId]?.reason ?? this.denyReasons[msg.data.executionId]; + } + getCompletedExecution(msg: ApprovalChatMessage): ToolExecutionResult | undefined { return this.completedExecutions[msg.data.executionId]; } ngOnChanges(changes: SimpleChanges): void { - if (changes.loadingLongTime?.currentValue) { - if (this.isNearBottom()) { - setTimeout(() => this.scrollToBottom('smooth'), 0); + if (changes.loading && !changes.loading.firstChange && changes.loading.previousValue && !changes.loading.currentValue + && !changes.messages?.firstChange && this.isNearBottom()) { + setTimeout(() => this.followTurnEnd(), 0); + } + if (changes.slotTaken && !changes.slotTaken.firstChange) { + setTimeout(() => this.placeDock()); + } + if (changes.messages) { + this.refreshDayLines(); + this.detailNames = aiDetailNames(this.messages as Array<{from: string; data?: any; references?: Array<{id: string; name: string; entityType: string}>}>, this.detailNames); + } + if (changes.messages || changes.completedExecutions || changes.loading || changes.autoApprove || changes.denyReasons) { + this.offerIndex = this.findOffer(); + } + if (changes.shownFile) { + const shown = this.shownFileName(); + this.elementRef.nativeElement.querySelectorAll('.art-chip[data-file]').forEach((chip: HTMLElement) => { + chip.classList.toggle('on', chip.dataset.file === shown); + chip.setAttribute('aria-pressed', String(chip.dataset.file === shown)); + }); + } + if (changes.messages || changes.completedExecutions || changes.loading) { + this.summaries = this.findSummaries(); + this.prompts = this.findPrompts(); + const asked = this.asking?.index; + this.asking = this.findAsking(); + if (this.asking && this.asking.index !== asked && !changes.messages?.firstChange) { + setTimeout(() => this.keepAskInView()); } + this.plans = this.findPlans(); + this.handOvers = this.findHandOvers(); + this.dock = this.findDock(); + this.followDock(); + this.files = this.findFiles(); + this.latestFiles = new Map(Object.values(this.files).map(file => [file.name, file])); + this.madeFiles = this.findMadeFiles(); + this.inCard = this.placeFiles(); + this.downloadRequestedFiles(); + this.quotes = this.findQuotes(); + this.sources = this.findSources(); + this.records = this.findRecords(); + this.made = {}; + Object.entries(this.records).forEach(([index, shown]) => { + const entities = this.summaries[Number(index)]; + if (!entities?.length) { + return; + } + const keys = new Set(shown.flatMap(item => item.refs.map(aiRecordKey))); + this.made[Number(index)] = entities.map(entity => `${entity.entityType}:${entity.id}`); + const rest = entities.filter(entity => !keys.has(`${entity.entityType}:${entity.id}`)); + if (rest.length) { + this.summaries[Number(index)] = rest; + } else { + delete this.summaries[Number(index)]; + } + }); + this.answersAt = this.findAnswers(); + this.retryIndex = this.findRetry(); + this.stoppedSteps = this.findStoppedSteps(); } if (changes.messages) { + this.lastAnswerIndex = this.findLastAnswerIndex(); + const tail = this.messages[this.messages.length - 1]; + this.streaming = tail?.from === 'AI' && !!tail.streaming; + const running = this.messages.map((message, index) => message.from === 'ACTION' && message.data.status === 'RUNNING' ? index : -1) + .filter(index => index >= 0); + this.actionRunning = running.length > 0; + this.runningLead = running.length ? running[0] : -1; + this.runningCount = running.length; + this.findReadGroups(); + const last = this.messages[this.messages.length - 1]; + this.waitApproval = last?.from === 'APPROVAL' && !this.autoApprove && !this.isAnswered(last as ApprovalChatMessage); if (changes.messages.firstChange) { - setTimeout(() => this.scrollToLastUserMessage(), 0); + if (this.initialScroll === 'bottom') { + this.pinToBottom(); + } else { + setTimeout(() => this.scrollToLastUserMessage(), 0); + } return; } const wasNearBottom = this.isNearBottom(); @@ -49,12 +523,10 @@ export class AiChatMessagesComponent implements OnChanges { const prevLastMsg = prevMsgs?.[prevMsgs.length - 1]; const msgs = changes.messages.currentValue as ChatMessage[]; const lastMsg = msgs[msgs.length - 1]; - // In auto-approve we are not blocked on the user, so the assistant keeps working: the - // thinking indicator must stay visible (waitApproval false) and the view must follow the - // stream of auto-generated cards down to the bottom. - this.waitApproval = lastMsg?.from === 'APPROVAL' && !this.autoApprove; if (this.autoApprove) { - setTimeout(() => this.scrollToBottom('auto'), 0); + if (wasNearBottom) { + setTimeout(() => this.scrollToBottom('auto'), 0); + } } else if (lastMsg?.from === 'USER') { setTimeout(() => this.scrollToBottom('smooth'), 0); } else if (lastMsg?.from === 'AI') { @@ -63,6 +535,14 @@ export class AiChatMessagesComponent implements OnChanges { } else if (wasNearBottom) { setTimeout(() => this.scrollToLastAiMessage(), 0); } + } else if (lastMsg?.from === 'ACTION') { + if (wasNearBottom) { + setTimeout(() => this.scrollToBottom('smooth'), 0); + } + } else if (lastMsg?.from === 'APPROVAL' && this.waitApproval) { + if (wasNearBottom) { + setTimeout(() => this.revealLastApproval(), 0); + } } else if (lastMsg?.from === 'APPROVAL') { if (prevLastMsg?.from === 'USER') { setTimeout(() => this.scrollToLastUserMessage(), 0); @@ -73,28 +553,696 @@ export class AiChatMessagesComponent implements OnChanges { } } + keepAsking(): void { + this.keptAsking.add(this.turnStart(this.offerIndex)); + this.offerIndex = -1; + } + + private findOffer(): number { + const last = this.messages.length - 1; + const pending = this.messages[last]; + if (this.autoApprove || pending?.from !== 'APPROVAL' || !pending.data.needsApproval || pending.data.autoApproved + || this.approvalResult(pending) || this.denyReasons[pending.data.executionId]) { + return -1; + } + const start = this.turnStart(last); + if (this.keptAsking.has(start)) { + return -1; + } + const approvedBefore = this.messages.slice(start + 1, last).some(message => message.from === 'APPROVAL' + && !message.data.autoApproved && this.approvalResult(message)?.approvalStatus === ToolApprovalResult.APPROVED); + return approvedBefore ? last : -1; + } + + private approvalResult(message: ApprovalChatMessage): ToolExecutionResult | undefined { + return this.completedExecutions[message.data.executionId] ?? message.result; + } + + private turnStart(index: number): number { + for (let i = index; i >= 0; i--) { + if (this.messages[i].from === 'USER') { + return i; + } + } + return -1; + } + + private answeredApprovals = new Set(); + + private isAnswered(message: ApprovalChatMessage): boolean { + const executionId = message.data?.executionId; + return !!message.result || this.answeredApprovals.has(executionId) || !!this.completedExecutions?.[executionId]; + } + approval($event: ApprovalResult) { + this.answeredApprovals.add($event.executionId); this.waitApproval = false; this.approvalAction.emit($event); } + private refreshDayLines(): void { + const lines: Record = {}; + let previous: string | undefined; + let first = true; + this.messages.forEach((message, index) => { + const time = (message as {time?: number}).time; + if (!time) { + return; + } + const day = new Date(time).toDateString(); + if (!first && day !== previous) { + lines[index] = this.dayLabel(time); + } + previous = day; + first = false; + }); + this.dayLines = lines; + clearTimeout(this.dayTimer); + const midnight = new Date(); + midnight.setHours(24, 0, 1, 0); + this.dayTimer = setTimeout(() => this.refreshDayLines(), midnight.getTime() - Date.now()); + } + + private dayLabel(time: number): string { + const date = new Date(time); + const today = new Date(); + today.setHours(0, 0, 0, 0); + const day = new Date(date); + day.setHours(0, 0, 0, 0); + const days = Math.round((today.getTime() - day.getTime()) / 86_400_000); + if (days === 0) { + return this.translate.instant('ai-assistant.today'); + } + if (days === 1) { + return this.translate.instant('ai-assistant.yesterday'); + } + const options: Intl.DateTimeFormatOptions = days > 1 && days <= 6 + ? {weekday: 'long', day: 'numeric', month: 'long'} + : date.getFullYear() === today.getFullYear() ? {day: 'numeric', month: 'long'} : {day: 'numeric', month: 'long', year: 'numeric'}; + return new Intl.DateTimeFormat(aiLocale(this.translate.currentLang), options).format(date).replace(',', ''); + } + + private findSummaries(): Record { + const summaries: Record = {}; + let entities: EntityId[] = []; + let seen = new Set(); + let lastAi = -1; + const close = (finished: boolean) => { + if (finished && lastAi >= 0 && entities.length) { + summaries[lastAi] = entities; + } + entities = []; + seen = new Set(); + lastAi = -1; + }; + const add = (ids?: EntityId[]) => (ids ?? []).forEach(id => { + const key = `${id.entityType}:${id.id}`; + if (!seen.has(key)) { + seen.add(key); + entities.push(id); + } + }); + this.messages.forEach((message, index) => { + switch (message.from) { + case 'USER': + close(true); + break; + case 'APPROVAL': + add((this.completedExecutions[message.data.executionId] ?? message.result)?.affectedEntities); + break; + case 'ACTION': + if (!SOLUTION_STEP_TOOLS.includes(message.data.tool)) { + add(message.data.affectedEntities); + } + break; + case 'AI': + lastAi = index; + break; + } + }); + close(!this.loading); + return summaries; + } + + private findReadGroups(): void { + const groups: Record = {}; + const away = new Set(); + const turns: number[][] = [[]]; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + turns.push([]); + } + turns[turns.length - 1].push(index); + }); + for (const turn of turns) { + const answered = turn.some(index => this.messages[index].from === 'AI' && !(this.messages[index] as GeneralChatMessage).streaming + && turn.indexOf(index) === turn.length - 1); + let lead = -1; + for (const index of turn) { + const message = this.messages[index]; + const action = message.from === 'ACTION' ? (message as ActionChatMessage).data : null; + if (action && isHiddenAiAction(action.tool)) { + continue; + } + if (action && this.isListedAction(message, index) && aiGroupableRead(action)) { + if (lead >= 0) { + groups[lead].push(action); + away.add(index); + } else { + lead = index; + groups[lead] = [action]; + } + continue; + } + if (!answered || message.from === 'USER' || message.from === 'AI') { + lead = -1; + } + } + } + Object.keys(groups).forEach(key => { + if (groups[Number(key)].length < 2) { + delete groups[Number(key)]; + } + }); + this.readGroups = groups; + this.groupedAway = away; + } + + isListedAction(message: ChatMessage, index = -1): boolean { + return message.from === 'ACTION' && !isKitCardTool(message.data.tool) && !isHiddenAiAction(message.data.tool) + && !(index >= 0 && (this.waitsInCards.has(index) || this.movedWaits.has(index))); + } + + answerQuestions(answers: AiQuestionAnswer[]): void { + this.answer.emit(aiAnswersPrompt(answers)); + } + + failText(index: number, message: GeneralChatMessage): string { + let steps = false; + for (let i = index - 1; i >= 0 && this.messages[i].from !== 'USER'; i--) { + if (this.messages[i].from === 'APPROVAL' || (this.messages[i].from === 'ACTION' && this.isListedAction(this.messages[i] as ActionChatMessage))) { + steps = true; + break; + } + } + const reason = message.failure?.reason; + const words = reason === 'TIMED_OUT' || reason === 'MODEL_ERROR' || reason === 'CREDITS_USED_UP' ? [this.translate.instant('ai-assistant.failed.reason.' + reason)] : []; + words.push(this.translate.instant(steps ? 'ai-assistant.failed.steps-done' : 'ai-assistant.failed.nothing-changed')); + return words.join(' '); + } + + clockText(time?: number): string { + return aiClockText(time, this.translate.currentLang); + } + + stoppedText(index: number, content: string): string { + const steps = this.stoppedSteps[index]; + if (steps === undefined) { + return content; + } + return steps ? this.translate.instant('ai-assistant.stopped-after', {count: steps}) : this.translate.instant('ai-assistant.stopped-before'); + } + + private findRetry(): number { + if (this.loading) { + return -1; + } + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (message.from === 'USER' || (message as GeneralChatMessage).status === 'INCOMPLETE' || !this.retry.observed) { + return -1; + } + if (message.from === 'ACTION' && this.isListedAction(message)) { + return message.data.status === 'FAILURE' ? i : -1; + } + } + return -1; + } + + private findStoppedSteps(): Record { + const steps: Record = {}; + let done = 0; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + done = 0; + } else if (message.from === 'ACTION' && this.isListedAction(message) && message.data.status === 'SUCCESS') { + done++; + } else if (message.from === 'APPROVAL' && (this.completedExecutions[message.data.executionId] ?? message.result)?.executionStatus === 'SUCCESS') { + done++; + } else if ((message as GeneralChatMessage).status === 'STOPPED') { + steps[index] = done; + } + }); + return steps; + } + + private findAsking(): {index: number; questions: AiQuestion[]} | null { + if (this.loading) { + return null; + } + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (message.from === 'USER') { + return null; + } + if (message.from === 'ACTION' && message.data.tool === ASK_USER_TOOL) { + const questions = aiQuestionsOf(message.data.arguments, this.severityWord); + return questions.length ? {index: i, questions} : null; + } + } + return null; + } + + private findRecords(): Record { + const records: Record = {}; + let answer = -1; + let pending: AiShownRecords[] = []; + const place = () => { + if (pending.length && answer >= 0) { + records[answer] = [...(records[answer] ?? []), ...pending]; + pending = []; + } + }; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + place(); + answer = -1; + pending = []; + } else if (message.from === 'AI' && !message.status) { + answer = index; + place(); + } else if (message.from === 'ACTION' && message.data.tool === SHOW_RECORDS_TOOL && message.data.status !== 'FAILURE') { + const shown = aiShownRecordsOf(message.data.arguments); + if (shown) { + pending.push(shown); + } + place(); + } + }); + return records; + } + + offerActions(): AiCardAction[] { + return [ + {id: 'approve-rest', icon: 'bolt', label: this.translate.instant('ai-assistant.offer.approve-rest')}, + {id: 'keep-asking', quiet: true, label: this.translate.instant('ai-assistant.offer.keep-asking')} + ]; + } + + offerAct(id: string): void { + if (id === 'approve-rest') { + this.autoApproveRest.emit(); + } else { + this.keepAsking(); + } + } + + listenAgain(): void { + this.listen.emit(); + } + + resumeActions(): AiCardAction[] { + return [{id: 'resume', icon: 'play_arrow', label: this.translate.instant('ai-assistant.resume')}]; + } + + chipActions(chips: Array<{id: string; label: string; icon?: string}>): AiCardAction[] { + return chips.map(option => ({id: option.id, label: option.label, icon: option.icon})); + } + + private findSources(): Record { + const sources: Record = {}; + let answer = -1; + let pending: AiSource[] = []; + const place = () => { + if (pending.length && answer >= 0) { + sources[answer] = [...(sources[answer] ?? []), ...pending]; + pending = []; + } + }; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + place(); + answer = -1; + pending = []; + } else if (message.from === 'AI' && !message.status) { + answer = index; + place(); + } else if (message.from === 'ACTION' && message.data.tool === CITE_SOURCES_TOOL && message.data.status !== 'FAILURE') { + pending.push(...aiSourcesOf(message.data.arguments)); + place(); + } + }); + return sources; + } + + private findQuotes(): Record { + const quotes: Record = {}; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + const found = aiQuoteOf(message.content); + if (found) { + quotes[index] = {name: found.quote.name, icon: fileLanguage(found.quote.name).icon, from: found.quote.from, to: found.quote.to, message: found.message}; + } + } + }); + return quotes; + } + + private findFiles(): Record { + const files: Record = {}; + this.messages.forEach((message, index) => { + if (message.from === 'ACTION' && message.data.tool === WRITE_FILE_TOOL) { + const file = aiFileOf(message.data.executionId, message.data.arguments, !!message.data.edited); + if (file) { + files[index] = file; + } + } + }); + return files; + } + + private placeFiles(): Set { + const placed = new Set(); + const names = [...this.latestFiles.keys()]; + const mentions = (step: AiHandOverStep, name: string) => [step.title, step.detail, step.markdown].some(part => part?.includes(name)); + Object.values(this.handOvers).forEach(card => { + const groups = [card.handOver.steps, ...(card.handOver.choice?.options.map(option => option.steps ?? []) ?? [])]; + groups.forEach(steps => { + steps.filter(step => step.file && !this.latestFiles.has(step.file)).forEach(step => step.file = undefined); + names.filter(name => !steps.some(step => step.file === name)).forEach(name => { + const last = [...steps].reverse().find(step => !step.file && mentions(step, name)); + if (last) { + last.file = name; + } + }); + steps.filter(step => step.file).forEach(step => placed.add(step.file)); + }); + }); + return placed; + } + + private findMadeFiles(): Record { + const files: Record = {}; + this.messages.forEach((message, index) => { + if (message.from === 'ACTION' && FILE_MAKING_TOOLS.has(message.data.tool) && message.data.status === 'SUCCESS') { + const file = aiMadeFileOf(message.data.executionId, message.data.result); + if (file) { + files[index] = file; + } + } + }); + return files; + } + + private findHandOvers(): Record { + const cards: Record = {}; + const waits = new Set(); + let current = -1; + let early = -1; + const moved = new Set(); + const after: Record = {}; + const waitOf = (message: ActionChatMessage, index: number): AiHandOverWait => { + const running = message.data.status === 'RUNNING' && this.loading; + if (running) { + waits.add(index); + } + return {running, startedAt: message.data.startedAt, progress: message.data.progress, + endedAt: message.data.durationMs != null ? message.data.startedAt + message.data.durationMs : undefined, + check: running ? null : aiConnectionCheckOf(message.data.result)}; + }; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + if (current >= 0 && (!cards[current].handOver.waitFor || cards[current].wait?.check?.dataArriving)) { + current = -1; + } + early = -1; + return; + } + if (message.from !== 'ACTION') { + return; + } + if (message.data.tool === HAND_OVER_TOOL) { + const handOver = aiHandOverOf(message.data.arguments); + if (handOver) { + cards[index] = {handOver, wait: null}; + current = index; + if (early >= 0 && handOver.waitFor) { + cards[index].wait = waitOf(this.messages[early] as ActionChatMessage, early); + moved.add(early); + after[index] = early; + early = -1; + } + } + } else if (message.data.tool === CHECK_CONNECTION_TOOL + && Number((message.data.arguments as {waitSeconds?: unknown})?.waitSeconds) > 0) { + if (current >= 0 && cards[current].handOver.waitFor) { + cards[current].wait = waitOf(message, index); + } else if (current < 0) { + early = index; + } + } + }); + this.waitsInCards = waits; + this.movedWaits = moved; + this.waitAfterCard = after; + return cards; + } + + private findPlans(): Record { + const plans: Record = {}; + let current = -1; + this.messages.forEach((message, index) => { + if (message.from !== 'ACTION') { + return; + } + if (message.data.tool === PROPOSE_PLAN_TOOL) { + const steps = aiPlanOf(message.data.arguments); + if (steps.length) { + if (current >= 0 && plans[current].progress && !this.planFinished(plans[current])) { + plans[current].replacedAfter = plans[current].progress.done.length; + } + plans[index] = {steps, progress: null, gate: false, replacedAfter: null}; + current = index; + } + } else if (message.data.tool === UPDATE_PLAN_TOOL && current >= 0) { + plans[current].progress = aiPlanProgressOf(message.data.arguments); + } + }); + if (current >= 0 && !this.loading && !plans[current].progress + && !this.messages.slice(current + 1).some(message => message.from === 'USER')) { + plans[current].gate = true; + } + return plans; + } + + private planFinished(plan: {steps: AiPlanStep[]; progress: AiPlanProgress | null}): boolean { + return aiPlanStatus(plan.steps, plan.progress).finished; + } + + private findAnswers(): Record { + const answers: Record = {}; + let questions: AiQuestion[] = []; + this.messages.forEach((message, index) => { + if (message.from === 'ACTION' && message.data.tool === ASK_USER_TOOL) { + questions = aiQuestionsOf(message.data.arguments, this.severityWord); + } else if (message.from === 'USER') { + const found = questions.length ? aiAnswersOf(message.content, questions) : null; + if (found) { + answers[index] = found; + } + questions = []; + } + }); + return answers; + } + + private findPrompts(): {index: number; items: AiPrompt[]} | null { + if (this.loading) { + return null; + } + let items: AiPrompt[] = []; + let answer = -1; + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (message.from === 'USER') { + break; + } + if (message.from === 'ACTION' && message.data.tool === SUGGEST_PROMPTS_TOOL && !items.length) { + items = aiPromptsOf(message.data.arguments); + } + if (message.from === 'AI' && !message.status && answer < 0) { + answer = i; + } + } + const shown = this.ghostFirst ? items.slice(1) : items; + return shown.length && answer >= 0 ? {index: answer, items: shown} : null; + } + + private findLastAnswerIndex(): number { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (message.from === 'AI' && !message.status) { + return i; + } + } + return -1; + } + + dockClicked(event: MouseEvent): void { + if (!(event.target as HTMLElement).closest('a, button')) { + this.toDockCard(); + } + } + + toDockCard(): void { + const card = this.dock ? this.elementRef.nativeElement.querySelector(`[data-dock="${this.dock.index}"]`) : null; + card?.scrollIntoView({block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth'}); + } + + dockTest(): void { + const id = this.dock ? (this.messages[this.dock.index] as ActionChatMessage)?.data.executionId : null; + if (id) { + this.testRequests = {...this.testRequests, [id]: (this.testRequests[id] ?? 0) + 1}; + } + } + + private findDock(): AiDockRow | null { + const lastUser = this.messages.map(message => message.from).lastIndexOf('USER'); + const handIndex = Object.keys(this.handOvers).map(Number).pop(); + const card = handIndex !== undefined ? this.handOvers[handIndex] : undefined; + if (card?.handOver.waitFor && card.wait && !card.wait.check?.dataArriving && (card.wait.running || handIndex > lastUser)) { + return {kind: 'hand', index: handIndex, text: card.handOver.title, state: card.wait.running ? 'listen' : 'stopped', + canTest: !!card.handOver.test?.sample && card.handOver.waitFor === 'message'}; + } + const planIndex = Object.keys(this.plans).map(Number).pop(); + const plan = planIndex !== undefined ? this.plans[planIndex] : undefined; + if (!plan?.progress || plan.replacedAfter !== null || this.planFinished(plan)) { + return null; + } + const status = aiPlanStatus(plan.steps, plan.progress); + const step = plan.steps[Math.max(0, status.now - 1)]; + return {kind: 'plan', index: planIndex, text: step?.text.replace(/`/g, '') ?? '', state: this.loading ? 'run' : 'idle', + count: this.translate.instant('ai-assistant.plan.done-of', {done: status.done, count: status.counted})}; + } + + private followDock(): void { + const scroller = this.scroller; + if (scroller !== this.dockScroller) { + this.dockScroller?.removeEventListener('scroll', this.placeDockOnScroll); + scroller.addEventListener('scroll', this.placeDockOnScroll, {passive: true}); + this.dockScroller = scroller; + } + setTimeout(() => this.placeDock()); + } + + private placeDock(): void { + let visible = false; + let below = this.dockBelow; + if (this.dock && !this.slotTaken) { + const card = this.elementRef.nativeElement.querySelector(`[data-dock="${this.dock.index}"]`); + if (card) { + const box = this.scroller.getBoundingClientRect(); + const rect = card.getBoundingClientRect(); + visible = Math.min(rect.bottom, box.bottom) - Math.max(rect.top, box.top) <= 40; + below = rect.top >= box.bottom - 40; + } + } + if (below !== this.dockBelow) { + this.dockBelow = below; + this.cd.markForCheck(); + } + if (visible !== this.dockVisible) { + this.dockVisible = visible; + this.dockShown.emit(visible); + this.cd.markForCheck(); + } + } + + ngOnDestroy(): void { + this.dockScroller?.removeEventListener('scroll', this.placeDockOnScroll); + clearTimeout(this.copiedTimeout); + clearTimeout(this.dayTimer); + this.releaseBottom?.(); + this.releaseAsk?.(); + } + + private pinToBottom(place?: () => void): void { + this.releaseBottom?.(); + const scroller = this.scroller; + const stick = place ?? (() => scroller.scrollTop = scroller.scrollHeight); + const observer = new ResizeObserver(stick); + observer.observe(this.elementRef.nativeElement); + const release = () => { + observer.disconnect(); + clearTimeout(timeout); + scroller.removeEventListener('wheel', release); + scroller.removeEventListener('touchstart', release); + scroller.removeEventListener('keydown', release); + scroller.removeEventListener('pointerdown', release); + this.releaseBottom = undefined; + }; + const timeout = setTimeout(release, AiChatMessagesComponent.PIN_TO_BOTTOM_MS); + scroller.addEventListener('wheel', release, {passive: true}); + scroller.addEventListener('touchstart', release, {passive: true}); + scroller.addEventListener('keydown', release); + scroller.addEventListener('pointerdown', release, {passive: true}); + this.releaseBottom = release; + stick(); + } + + private followTurnEnd(): void { + const scroller = this.scroller; + const answers = this.elementRef.nativeElement.querySelectorAll('.ai'); + const answer = answers[answers.length - 1] as HTMLElement | undefined; + this.pinToBottom(() => { + let target = scroller.scrollHeight - scroller.clientHeight; + if (answer?.isConnected) { + const top = answer.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop - 8; + target = Math.min(target, top); + } + if (target > scroller.scrollTop) { + scroller.scrollTop = target; + } + }); + } + scrollToBottom(behavior: ScrollBehavior = 'smooth'): void { - const el = this.elementRef.nativeElement; - el.scrollTo({top: el.scrollHeight, behavior}); + const el = this.scroller; + el.scrollTo({top: el.scrollHeight, behavior: this.motion(behavior)}); } - scrollToLastUserMessage(): void { - const userMessages = this.elementRef.nativeElement.querySelectorAll('.user'); - if (userMessages.length) { - userMessages[userMessages.length - 1].scrollIntoView({block: 'start', behavior: 'smooth'}); + private revealLastApproval(): void { + const cards = this.elementRef.nativeElement.querySelectorAll('tb-ai-approval-card'); + const card = cards[cards.length - 1] as HTMLElement | undefined; + if (!card) { + return; } + const scroller = this.scroller; + this.pinToBottom(() => { + scroller.scrollTop = scroller.scrollHeight; + const top = card.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + if (top < 0) { + scroller.scrollTop += top - 8; + } + }); + } + + scrollToLastUserMessage(): void { + this.scrollToStart(this.elementRef.nativeElement.querySelectorAll('.user')); } private scrollToLastAiMessage(): void { - const aiMessages = this.elementRef.nativeElement.querySelectorAll('.ai'); - if (aiMessages.length) { - aiMessages[aiMessages.length - 1].scrollIntoView({block: 'start', behavior: 'smooth'}); + this.scrollToStart(this.elementRef.nativeElement.querySelectorAll('.ai')); + } + + private scrollToStart(messages: NodeListOf): void { + const message = messages[messages.length - 1]; + const scroller = this.scroller; + if (!message || !scroller) { + return; } + const top = scroller.scrollTop + message.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + scroller.scrollTo({top, behavior: this.motion('smooth')}); } parseResult(msg: string): string { @@ -115,12 +1263,20 @@ export class AiChatMessagesComponent implements OnChanges { '```'; } } else { - return msg; + return aiFenceMeta(msg); } } + private motion(behavior: ScrollBehavior): ScrollBehavior { + return behavior === 'smooth' && matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : behavior; + } + + private get scroller(): HTMLElement { + return this.scrollContainer ?? this.elementRef.nativeElement; + } + private isNearBottom(threshold = 150): boolean { - const el = this.elementRef.nativeElement; + const el = this.scroller; return el.scrollHeight - el.scrollTop - el.clientHeight <= threshold; } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-session.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-session.ts new file mode 100644 index 0000000000..320c3a2842 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-session.ts @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { WritableSignal } from '@angular/core'; +import { Observable } from 'rxjs'; +import { AnswerRatingEvent, AnswerReportEvent } from '@home/components/ai/ai-chat-messages.component'; +import { AnswerFeedback, AnswerRating } from '@shared/models/ai-chat.models'; + +const END_IN_VIEW = 160; + +export interface AiLogScrollState { + scrolled: WritableSignal; + atEnd: WritableSignal; + newTurns: WritableSignal; +} + +export function aiTrackLogScroll(area: HTMLElement, state: AiLogScrollState, reachedEnd: () => void): void { + const scrolled = area.scrollTop > 0; + if (scrolled !== state.scrolled()) { + state.scrolled.set(scrolled); + } + const atEnd = area.scrollHeight - area.scrollTop - area.clientHeight < END_IN_VIEW; + if (atEnd !== state.atEnd()) { + state.atEnd.set(atEnd); + } + if (atEnd) { + state.newTurns.set(0); + reachedEnd(); + } +} + +export interface AiAnswerFeedback { + patch: (patch: {rating?: Exclude; reported?: boolean}) => void; + send: (feedback: Omit) => Observable; + failed: () => void; +} + +export function aiRateAnswer(event: AnswerRatingEvent, before: Exclude | undefined, feedback: AiAnswerFeedback): void { + feedback.patch({rating: event.rating === 'NONE' ? undefined : event.rating}); + feedback.send({rating: event.rating}).subscribe({ + error: () => { + feedback.patch({rating: before}); + feedback.failed(); + } + }); +} + +export function aiReportAnswer(event: AnswerReportEvent, feedback: AiAnswerFeedback, reported: () => void): void { + feedback.patch({reported: true}); + feedback.send({problem: event.problem, comment: event.comment}).subscribe({ + next: () => reported(), + error: () => { + feedback.patch({reported: false}); + feedback.failed(); + } + }); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html new file mode 100644 index 0000000000..35bd1082fd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html @@ -0,0 +1,46 @@ + +@if (title(); as name) { + @if (renaming()) { + + + + + + } @else { + + + @if (renamable()) { + + } + + @if (level(); as current) { + + + {{ ('ai-assistant.status-' + current) | translate }} + + } + } +} @else { + {{ placeholder() }} +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.scss new file mode 100644 index 0000000000..e1f96644e4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.scss @@ -0,0 +1,151 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './ai-icon-button' as *; +@use './ai-breakpoints' as *; +:host { + display: contents; +} + +.ai-chat-name-wrap { + position: relative; + padding-right: 28px; + display: inline-flex; + align-items: center; + flex: 0 1 auto; + min-width: 0; + + &:hover .ai-chat-name-pen, &:focus-within .ai-chat-name-pen { + opacity: 1; + } +} + +.ai-chat-name { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + white-space: nowrap; + padding: 0; + border: 0; + background: none; + font: 500 15px/20px var(--tb-font); + letter-spacing: normal; + text-align: left; + color: var(--tb-ink); + cursor: default; + + &.clipped { + mask-image: linear-gradient(90deg, #000 calc(100% - 44px), transparent calc(100% - 8px)); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + border-radius: 4px; + } +} + +.ai-chat-name-pen { + position: absolute; + right: 0; + width: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--tb-ink-60); + display: inline-flex; + align-items: center; + justify-content: center; + opacity: 0; + cursor: pointer; + transition: opacity .12s ease; + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + } + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + opacity: 1; + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.ai-chat-renaming { + display: inline-flex; + align-items: center; + gap: 2px; + flex: 1; + min-width: 0; + max-width: 480px; +} + +.ai-chat-name.compact { + font-size: var(--chat-line); + line-height: 18px; +} + +.ai-chat-status { + flex: none; + margin-left: auto; + display: inline-flex; + align-items: center; + gap: 6px; + font: 400 12.5px/20px var(--tb-font); + color: var(--tb-ink-54); + white-space: nowrap; + + &.error { + color: var(--tb-crit); + } + + .tb-ai-status-mark { + width: 10px; + height: 10px; + + &.running::before { + width: 8px; + height: 8px; + border-width: 1.5px; + } + } +} + +.ai-chat-rename { + flex: 1; + min-width: 0; + height: 28px; + box-sizing: border-box; + padding: 0; + border: 0; + border-bottom: 1.5px solid var(--tb-primary-500); + border-radius: 0; + outline: 0; + background: none; + font: 500 15px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); +} + + +.ai-chat-name-wrap.static { + padding-right: 0; +} + +.ai-ib { + @include ai-icon-button; +} + +@container k-head (max-width: #{$ai-head-status-hidden-below - 1px}) { + .ai-chat-status > span:last-child { + display: none; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.ts new file mode 100644 index 0000000000..63e562cb2a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.ts @@ -0,0 +1,89 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { afterNextRender, Component, DestroyRef, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { ChatLevel } from '@shared/models/ai-chat.models'; + +@Component({ + selector: 'tb-ai-chat-title', + templateUrl: './ai-chat-title.component.html', + styleUrls: ['./ai-chat-title.component.scss'], + standalone: false +}) +export class AiChatTitleComponent { + + title = input(null); + placeholder = input(''); + level = input(null); + statusTip = input(''); + renamable = input(true); + compact = input(false); + + @Output() renamed = new EventEmitter(); + + private host = inject>(ElementRef); + + renaming = signal(false); + nameClipped = signal(false); + + constructor() { + const head = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => this.measure()) : null; + afterNextRender(() => { + const parent = this.host.nativeElement.parentElement; + if (parent) { + head?.observe(parent); + } + this.measure(); + }); + effect(() => { + this.title(); + this.renaming(); + setTimeout(() => this.measure()); + }); + inject(DestroyRef).onDestroy(() => head?.disconnect()); + } + + measure(): void { + const name = this.host.nativeElement.querySelector('.ai-chat-name'); + this.nameClipped.set(!!name && name.scrollWidth > name.clientWidth + 1); + } + + startRename(): void { + if (!this.title() || !this.renamable()) { + return; + } + this.renaming.set(true); + setTimeout(() => { + const field = this.host.nativeElement.querySelector('.ai-chat-rename'); + field?.focus(); + field?.select(); + }); + } + + cancelRename(): void { + this.renaming.set(false); + } + + onRenameKeydown(event: KeyboardEvent): void { + if (event.isComposing) { + return; + } + if (event.key === 'Enter') { + event.preventDefault(); + this.finishRename((event.target as HTMLInputElement).value); + } else if (event.key === 'Escape') { + event.stopPropagation(); + this.renaming.set(false); + } + } + + finishRename(value: string): void { + if (!this.renaming()) { + return; + } + this.renaming.set(false); + const title = value.trim(); + if (title && title !== this.title()) { + this.renamed.emit(title); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html new file mode 100644 index 0000000000..0b0ccb7268 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -0,0 +1,508 @@ + +
+
+
+ + @if (variant() === 'panel') { + + } + +
+ @if (chatFiles().length && !titleRef?.renaming()) { + + } + @if (variant() === 'panel') { + @if (!titleRef?.renaming()) { + @if (chat()) { + + } + + @if (fullscreen() || !headNarrow()) { + + } + @if (!fullscreen()) { + + } + } + } @else if (chat() && !titleRef?.renaming()) { + + } + + @if (showGetStarted()) { + + } + @if (fullscreenEnabled()) { + + } +
+
+
+
+ @if (messages().length || loading()) { + + + } @else if (historyLoading()) { +
+ + {{ 'ai-assistant.loading-chat' | translate }} +
+ } @else if (!chatId() && docked()) { +
+ +

{{ startTitle() || ('ai-assistant.panel-title' | translate) }}

+

{{ startLine() || ('ai-assistant.panel-line' | translate) }}

+ @if (prompts().length) { +
+ @for (example of prompts(); track example.message) { + + } +
+ } +
+ } @else if (!chatId()) { +
+ + @if (variant() === 'panel') { +

{{ startTitle() || ('ai-assistant.panel-title' | translate) }}

+

{{ startLine() || ('ai-assistant.panel-line' | translate) }}

+ } @else { +

{{ (showGetStarted() ? 'ai-assistant.get-started.heading' : 'ai-assistant.what-to-work-on') | translate }}

+ } +
+ } +
+ @if (pill(); as current) { + + } + @if (creditsOut(); as limitType) { + + } @else if (limitOut(); as platformLimit) { + + } @else if (notice(); as current) { +
+ {{ current.text }} +
+ } @else if (keptEdits(); as kept) { +
+ {{ ('ai-assistant.kept-edits.' + kept.kind) | translate }} + + +
+ } + + +
+ @if (variant() === 'panel' && !docked() && !chatId() && !messages().length && !loading() && prompts().length) { +
+
+ @for (example of prompts(); track example.message) { + + } +
+
+ } + @if (showGetStarted() && !messages().length && !loading()) { +
+
+

{{ 'ai-assistant.get-started.examples' | translate }}

+

{{ 'ai-assistant.get-started.examples-hint' | translate }}

+
+
+ @for (example of examples; track example.key) { + + } +
+
+
+ +
+

{{ 'ai-assistant.cli.band.heading' | translate }}

+

{{ 'ai-assistant.cli.band.line' | translate }}

+
+ +
+ } + @if (variant() === 'page' && !showGetStarted() && !chatId() && !messages().length && !loading()) { +
+

{{ 'ai-assistant.start-a-task' | translate }}

+
+ @for (task of tasks; track task) { + + } +
+
+ } + @if (variant() === 'page' && !showGetStarted() && !chatId() && !messages().length && !loading()) { + + } +
+
+@if (shownFile(); as file) { + @if (fileOpen()) { + +

+ + {{ fileName(file.name).base }}{{ fileName(file.name).ext }} +

+
+ @if (!file.previewed) { +
+ @if (!fileBody()?.editing()) { + + } + + +
+ } +
+ + {{ fileCopied() ? ('ai-assistant.copied' | translate) : '' }} + @if (file.image) { + + } @else { + + } +
+
+ + + @if (fileMarks(); as marks) { +
+ + {{ (marks.from === marks.to ? 'ai-assistant.file.line' : 'ai-assistant.file.lines-range') | translate: {from: marks.from, to: marks.to} }} + {{ 'ai-assistant.file.marked' | translate }} + + + + + +
+ } @else { +
+ + @if (fileBody()?.editing()) { + @if (fileBody()?.dirty()) { + {{ 'ai-assistant.file.unsaved' | translate }} + } @else { + {{ 'ai-assistant.file.editing' | translate }} + } + @if (fileBody()?.caret(); as caret) { + + {{ 'ai-assistant.file.position' | translate: {line: caret.line, col: caret.col} }}@if (caret.selected) { ({{ 'ai-assistant.file.selected' | translate: {count: caret.selected} }})} + } + } @else if (fileBody()?.saved()) { + {{ 'ai-assistant.file.saved' | translate }} + } @else { + {{ 'ai-assistant.file.lines' | translate: {count: file.lines} }} + + {{ file.size }} + @if (file.edited) { + + {{ 'ai-assistant.file.edited-in-chat' | translate }} + } + } + + + @if (fileBody()?.editing()) { + @if (fileBody()?.dirty()) { + + + } @else { + + } + } @else if (chatId()) { + + } + +
+ } +
+
+ + + + + + @if (!fileBody()?.editing()) { + + } +
+ + {{ 'ai-assistant.file.theme' | translate }} +
+ + +
+
+
+ } +} +
+ + + @if (!fullscreen() && headNarrow()) { + + } + @if (docked() && (split() || splitAvailable())) { + + } + @if (chat()) { + + + + } + @for (group of otherChats(); track group.label) { +
{{ group.label | translate }}
+ @for (other of group.chats; track other.id) { + + } + } + +
+ + + + + + + + +
{{ 'ai-assistant.file.files-in-chat' | translate: {count: chatFiles().length} }}
+ @for (entry of chatFiles(); track entry.file.name) { + @if (unlisting() === entry.file.name) { +
+ + {{ 'ai-assistant.file.unlist-ask' | translate }} + {{ fileName(entry.file.name).base }}{{ fileName(entry.file.name).ext }} + + +
+ } @else { +
+ + +
+ } + } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss new file mode 100644 index 0000000000..928d69fb9d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss @@ -0,0 +1,793 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './ai-icon-button' as *; +:host { + position: relative; + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; + background: var(--tb-surface); + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); +} + +:host(.tb-fullscreen) { + margin: 0 !important; + border-radius: 0 !important; + box-shadow: none !important; +} + +.ai-chat-head { + position: relative; + container: k-head / inline-size; + flex: none; + display: flex; + align-items: center; + gap: 8px; + height: 48px; + box-sizing: border-box; + padding: 0 8px 0 16px; + border-bottom: 1px solid rgba(0, 0, 0, 0.06); + + @media (max-width: 599px) { + padding: 0 4px 0 8px; + } +} + +.ai-chat-head::after { + content: ''; + position: absolute; + left: 0; + right: 0; + top: 100%; + z-index: 3; + height: 12px; + background: linear-gradient(to bottom, color-mix(in srgb, var(--tb-ink) 9%, transparent), transparent); + opacity: 0; + transition: opacity .15s ease; + pointer-events: none; +} + +.ai-chat-head.scrolled::after { + opacity: 1; +} + +:host(.v-panel) .ai-chat-head { + height: 56px; + gap: 10px; + padding: 0 8px 0 12px; + border-bottom-color: rgba(0, 0, 0, 0.08); +} + +tb-ai-chat-title:has(.ai-chat-status) + .ai-chat-actions { + margin-left: 0; +} + +.ai-chat-actions { + flex: none; + margin-left: auto; + display: flex; + align-items: center; + gap: 2px; +} + +:host ::ng-deep .ai-ib { + @include ai-icon-button; + + &.more .mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + } +} + +:host(.v-panel) ::ng-deep .ai-ib { + width: 28px; + height: 28px; +} + +.ai-chat-body { + position: relative; + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + align-items: center; + overflow-x: hidden; + overflow-y: auto; + padding: 20px 20px 0; + container: k-chat / inline-size; + + &.empty { + justify-content: flex-start; + padding-top: 64px; + padding-bottom: 24px; + } +} + +:host(.v-panel) .ai-chat-body { + padding: 12px 12px 0; + + &.empty { + padding-top: 0; + padding-bottom: 0; + } +} + +.ai-chat-log { + flex: 1 0 auto; + width: 100%; + max-width: 760px; + margin: 4px 0 24px; + overflow: visible; + + @container k-chat (min-width: 900px) { + max-width: 712px; + } +} + +.k-newchat, .k-prompts { + .prompts { + align-self: stretch; + display: flex; + flex-direction: column; + border-top: 1px solid var(--tb-line); + } + + .prompt { + display: flex; + align-items: center; + gap: 12px; + min-height: 44px; + padding: 0 8px; + border: 0; + border-bottom: 1px solid var(--tb-line); + background: none; + font: 400 14px/20px var(--tb-font); + color: var(--tb-ink); + text-align: left; + cursor: pointer; + transition: background .12s ease; + + > .mat-icon { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + color: var(--tb-ink-54); + } + + > span { + flex: 1; + min-width: 0; + } + + .go { + font-size: 16px; + width: 16px; + height: 16px; + color: var(--tb-ink); + opacity: 0; + transform: translateY(2px); + transition: opacity .12s ease, transform .12s ease; + } + + &:hover, &:focus-visible { + background: rgba(0, 0, 0, .035); + outline: none; + + .go { + opacity: .7; + transform: none; + } + } + } +} + +.k-newchat { + flex: 1 0 auto; + align-self: stretch; + margin: auto 0; + padding: 24px 6px 12px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + + h3 { + margin: 14px 0 4px; + font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); + letter-spacing: 0; + color: var(--tb-ink); + } + + p { + margin: 0 0 20px; + max-width: 300px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-54); + } +} + +.ai-chat-start { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + text-align: center; +} + +.ai-chat-start-title { + margin: 0; + font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); + letter-spacing: 0; + color: var(--tb-ink); +} + +.ai-chat-composer { + position: sticky; + bottom: 0; + z-index: 1; + flex: none; + width: 100%; + max-width: 760px; + padding: 12px 0 14px; + background: linear-gradient(color-mix(in srgb, var(--tb-surface) 0%, transparent), var(--tb-surface) 40%); +} + +.ai-chat-body:not(.empty) .ai-chat-composer ::ng-deep .composer-field:not(:focus-within) { + border-color: var(--tb-line); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06), 0 10px 28px rgba(16, 24, 40, 0.10); +} + +.ai-sec { + width: 100%; + max-width: 680px; + margin-top: 16px; + text-align: left; +} + +.ai-sec-head h2 { + margin: 0; + font: 500 14px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-text-secondary); +} + +.ai-tasks { + margin-top: 8px; + border-radius: 12px; + background: var(--tb-surface); + box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.03), 0 1px 2px rgba(16, 24, 40, 0.06), 0 2px 10px rgba(16, 24, 40, 0.06); +} + +.ai-task { + display: grid; + grid-template-columns: minmax(0, 1fr) auto 20px; + align-items: center; + gap: 12px; + width: 100%; + min-height: 44px; + padding: 0 10px 0 16px; + border: 0; + background: none; + font: 400 14px/20px var(--tb-font); + letter-spacing: normal; + text-align: left; + color: var(--tb-ink); + cursor: pointer; + transition: background-color .12s ease; + + & + .ai-task { + border-top: 1px solid rgba(0, 0, 0, 0.06); + } + + &:first-child { + border-radius: 12px 12px 0 0; + } + + &:last-child { + border-radius: 0 0 12px 12px; + } + + &:hover { + background: rgba(0, 0, 0, 0.03); + + .mat-icon { + color: var(--tb-ink); + transform: translateX(2px); + } + } + + &:focus-visible { + outline: 0; + box-shadow: inset 0 0 0 2px var(--ai-focus); + } + + b { + min-width: 0; + overflow: hidden; + font-weight: 400; + text-overflow: ellipsis; + white-space: nowrap; + } + + small { + max-width: 280px; + overflow: hidden; + font-size: 12.5px; + line-height: 18px; + color: var(--tb-ink-76); + text-overflow: ellipsis; + white-space: nowrap; + + @media (max-width: 599px) { + display: none; + } + } + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + color: var(--tb-ink-38); + transition: transform .15s ease, color .15s ease; + } + + @media (prefers-reduced-motion: reduce) { + transition: none; + + .mat-icon { + transition: none; + } + } +} + +.ai-chat-body.empty .ai-chat-composer { + position: static; + max-width: 680px; + padding-top: 20px; + background: none; +} + +@media (max-width: 599px) { + .ai-chat-body { + padding: 16px 16px 0; + } +} + +:host(.v-panel) .ai-chat-composer, +:host(.v-panel) .ai-chat-body.empty .ai-chat-composer { + position: sticky; + width: auto; + max-width: none; + align-self: stretch; + margin: 0 -12px; + padding: 0; + background: var(--tb-surface); +} + +.ai-chat-start-line { + margin: -4px 0 0; + max-width: 420px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-54); +} + +.ai-chat-col { + position: relative; + flex: 1 1 0; + min-width: 0; + min-height: 0; + display: flex; + flex-direction: column; +} + +.art-cols.with-pane:not(.narrow) .ai-chat-col { + min-width: var(--chat-col-min, 340px); +} + +:host ::ng-deep .ai-ib.art-files-btn { + width: auto; + gap: 4px; + padding: 0 9px 0 8px; + border-radius: 10px; + color: var(--tb-ink-76); + + &:hover { + color: var(--tb-ink); + } + + &.shown, &[aria-expanded="true"] { + color: var(--ai-action); + } + + &[aria-expanded="true"] { + background: color-mix(in srgb, var(--ai-action) 10%, transparent); + } +} + +:host(.v-panel.split) .ai-chat-body { + padding: 20px 20px 0; +} + +:host(.v-panel.split) .ai-chat-log { + max-width: 712px; +} + +:host(.v-panel.split) .ai-chat-composer, +:host(.v-panel.split) .ai-chat-body.empty .ai-chat-composer { + width: 100%; + max-width: 760px; + align-self: center; + margin: 0; + padding: 12px 0 14px; + background: linear-gradient(color-mix(in srgb, var(--tb-surface) 0%, transparent), var(--tb-surface) 40%); +} + +:host(.v-panel.split) .k-newchat { + width: 100%; + max-width: 712px; + margin-left: auto; + margin-right: auto; +} + + +@container k-col (min-width: 481px) { + :host(.v-panel:not(.split)) { + .ai-chat-body { + padding: 20px 24px 0; + } + + .ai-chat-log { + max-width: var(--chat-read-log); + margin-bottom: 64px; + } + + .ai-chat-composer, .ai-chat-body.empty .ai-chat-composer { + margin: 0 -24px; + padding: 0 24px 16px; + background: var(--tb-surface); + pointer-events: none; + + > * { + pointer-events: auto; + } + + > tb-ai-prompt-input { + max-width: var(--chat-read); + margin: 0 auto; + } + } + + .ai-chat-body:not(.empty) .ai-chat-composer { + margin-top: -32px; + padding-top: 32px; + background: linear-gradient(180deg, color-mix(in srgb, var(--tb-surface) 0%, transparent), var(--tb-surface) 32px); + } + } +} + +.ai-sol-card { + display: grid; + grid-template-columns: 44px minmax(0, 1fr) auto; + align-items: center; + column-gap: 14px; + width: 100%; + max-width: 680px; + margin-top: 24px; + padding: 14px 16px 14px 14px; + border: 0; + border-radius: 12px; + background: var(--tb-surface); + text-align: left; + font: inherit; + cursor: pointer; + box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.03), 0 1px 2px rgba(16, 24, 40, 0.06), 0 2px 10px rgba(16, 24, 40, 0.06); + transition: box-shadow .15s ease; + + &:hover { + box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.05), 0 2px 4px rgba(16, 24, 40, 0.06), 0 8px 24px rgba(16, 24, 40, 0.10); + + .ai-sol-card-go .mat-icon { + transform: translateX(2px); + } + } + + &:focus-visible { + outline: 0; + box-shadow: 0 0 0 2px var(--ai-focus); + } +} + +.ai-sol-card-mark { + --ai-mark-fill: radial-gradient(80% 80% at 16% 10%, color-mix(in srgb, var(--tb-surface) 16%, transparent), transparent 62%), + linear-gradient(135deg in oklab, + color-mix(in oklab, var(--ai-light-teal) 34%, var(--tb-ink)) 0%, + color-mix(in oklab, var(--ai-light-aqua) 32%, var(--tb-ink)) 36%, + color-mix(in oklab, var(--ai-light-lilac) 36%, var(--tb-ink)) 68%, + color-mix(in oklab, var(--ai-light-peach) 34%, var(--tb-ink)) 100%); + --ai-mark-edge: 0 4px 12px color-mix(in oklab, var(--tb-ink) 18%, transparent); + --ai-mark-ink: var(--ai-on-action); + --ai-mark-ink-fill: linear-gradient(var(--ai-on-action), var(--ai-on-action)); +} + +.ai-sol-card-text { + display: grid; + gap: 2px; + min-width: 0; + + b { + font: 500 var(--chat-text)/var(--chat-text-lh) var(--tb-font); + color: var(--tb-ink); + } + + small { + font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink-54); + } +} + +.ai-sol-card-go { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 0 4px; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--ai-link); + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + transition: transform .12s cubic-bezier(.2, 0, 0, 1); + } +} + +@media (max-width: 599px) { + .ai-sol-card-go-t { + display: none; + } +} + +.ai-sec-lg { + margin-top: 32px; + + .ai-sec-head h2 { + font: 500 16px/22px var(--tb-font); + color: var(--tb-ink); + } + + .ai-sec-head p { + margin: 2px 0 0; + font: 400 14px/20px var(--tb-font); + color: var(--tb-ink-60); + } +} + +.k-pcards { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-auto-rows: 1fr; + gap: 10px; + margin-top: 14px; +} + +.k-pcard { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 12px; + padding: 16px; + border: 1px solid rgba(0, 0, 0, 0.08); + border-radius: 12px; + background: var(--tb-surface); + text-align: left; + font: inherit; + cursor: pointer; + transition: border-color .15s ease; + + &:hover { + border-color: rgba(0, 0, 0, 0.18); + + .k-pcard-tile::before { + background-position: 100% 100%; + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } +} + +.k-pcard-tile { + position: relative; + isolation: isolate; + overflow: hidden; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 40px; + height: 40px; + border-radius: 11px; + background: var(--tb-surface); + color: var(--tb-ink); + box-shadow: var(--ai-mark-edge); + + &::before { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + background: var(--ai-mark-fill); + background-size: 240% 240%; + background-position: 0% 0%; + transition: background-position 1.2s cubic-bezier(.4, 0, .2, 1); + } + + .mat-icon { + font-size: 22px; + width: 22px; + height: 22px; + } +} + +.k-pcard-body { + display: grid; + gap: 4px; + min-width: 0; + + b { + font: 500 15px/21px var(--tb-font); + color: var(--tb-ink); + } + + span { + font: 400 13.5px/19px var(--tb-font); + color: var(--tb-ink-76); + } +} + +@container k-col (max-width: 560px) { + .k-pcards { + grid-template-columns: minmax(0, 1fr); + } +} + +.ai-tour-link { + display: inline-flex; + align-items: center; + gap: 6px; + margin: 0 4px 0 0; + padding: 4px 10px; + border: 0; + border-radius: 16px; + background: none; + white-space: nowrap; + cursor: pointer; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--ai-link); + + &:hover { + background: var(--ai-selected-wash); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +.ai-cli-band { + display: grid; + grid-template-columns: 40px minmax(0, 1fr) auto; + column-gap: 14px; + align-items: center; + width: 100%; + max-width: 680px; + box-sizing: border-box; + margin-top: 32px; + padding: 14px 14px 14px 16px; + border-radius: 14px; + text-align: left; + color: var(--tb-ink); + background: linear-gradient(160deg, color-mix(in srgb, var(--ai-dark-accent-pale) 62%, var(--tb-surface)), color-mix(in srgb, var(--ai-dark-accent-pale) 34%, var(--tb-surface))); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ai-dark-accent-soft) 40%, transparent); + + @media (max-width: 599px) { + grid-template-columns: 40px minmax(0, 1fr); + row-gap: 12px; + } +} + +.ai-cli-band-tile { + width: 40px; + height: 40px; + border-radius: 38%; + display: inline-flex; + align-items: center; + justify-content: center; + background: var(--ai-dark); + color: var(--ai-dark-accent); + + .mat-icon { + font-size: 22px; + width: 22px; + height: 22px; + } +} + +.ai-cli-band-text { + display: grid; + gap: 2px; + min-width: 0; + + h2 { + margin: 0; + font: 500 var(--chat-text)/var(--chat-text-lh) var(--tb-font); + color: var(--tb-ink); + } + + p { + margin: 0; + font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink-54); + } +} + +.ai-cli-band-btn { + display: inline-flex; + align-items: center; + gap: 6px; + height: 36px; + padding: 0 12px 0 16px; + border: 0; + border-radius: 10px; + background: var(--ai-dark); + color: var(--ai-on-dark); + font: 500 var(--chat-line)/1 var(--tb-font); + letter-spacing: normal; + white-space: nowrap; + cursor: pointer; + transition: background-color .15s cubic-bezier(.2, 0, 0, 1); + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + transition: transform .15s cubic-bezier(.2, 0, 0, 1); + } + + &:hover { + background: color-mix(in srgb, var(--ai-dark) 86%, var(--ai-on-dark)); + + .mat-icon { + transform: translateX(2px); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } + + @media (max-width: 599px) { + grid-column: 1 / -1; + justify-content: center; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts new file mode 100644 index 0000000000..7e914f5760 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -0,0 +1,1769 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { escapeHtml } from '@core/utils'; +import { AI_TOOLTIP_PROVIDERS } from '@home/components/ai/ai-tooltip'; +import { AI_NARROW_HEAD_WIDTH } from '@home/components/ai/ai-breakpoints'; +import { aiCreditsLimitOf, AiCreditsLimitType } from '@home/components/ai/ai-credits.models'; +import { aiClientOs, aiPageView, isAiTitledView } from '@shared/models/ai-chat.models'; +import { getDefaultTimezone } from '@shared/models/time/time.models'; +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + ElementRef, + inject, + input, + model, + OnDestroy, + OnInit, + output, + signal, + untracked, + ViewChild, + viewChild +} from '@angular/core'; +import { Router } from '@angular/router'; +import { DomSanitizer } from '@angular/platform-browser'; +import { TranslateService } from '@ngx-translate/core'; +import { Store } from '@ngrx/store'; +import { HttpErrorResponse } from '@angular/common/http'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { EMPTY, Observable, of, Subject, throwError, timer } from 'rxjs'; +import { catchError, concatMap, finalize, retry, switchMap, takeUntil, tap } from 'rxjs/operators'; +import { AppState } from '@core/core.state'; +import { AiChatService } from '@core/http/ai-chat.service'; +import { AiChatsService } from '@core/services/ai-chats.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { AiWidgetCheckService } from '@home/components/ai/ai-widget-check.service'; +import { aiParse } from '@home/components/ai/ai-action-detail.models'; +import { WhiteLabelingService } from '@core/http/white-labeling.service'; +import { CustomMenuService } from '@core/http/custom-menu.service'; +import { UserService } from '@core/http/user.service'; +import { UnitService } from '@core/services/unit.service'; +import { AuthService } from '@core/auth/auth.service'; +import { ActionAuthUpdateUserDetails } from '@core/auth/auth.actions'; +import { ActionSettingsChangeLanguage } from '@core/settings/settings.actions'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { environment as env } from '@env/environment'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { aiChatNameOf } from '@home/components/ai/ai-text'; +import { ActionChatMessage, AiStartedFrom, ApprovalChatMessage, ChatMessage, GeneralChatMessage } from '@shared/models/solution-creator.models'; +import { + AiAssistantPromptExample, + AiChatClientContext, + AiPlatformLimit, + AiLinesQuote, + AiNotice, + AiPromptMessage, + aiQuoteText, + ChatInfo, + ChatLevel, + ApprovalResult, + ChatEvent, + SendChatMessageRequest, + ToolApprovalResult, + AiAction, + ToolExecutionRequestedEvent, + ToolExecutionResult, + ToolFinished, + ToolStarted +} from '@shared/models/ai-chat.models'; +import { aiActionText, aiActionWords, aiQuestionsOf, AiPlanStep, AiSpinKind, AiWorkMoment, AiWorkState, aiTurnPrompts, isHiddenAiAction, isKitCardTool, ASK_USER_TOOL, HAND_OVER_TOOL } from '@home/components/ai/ai-action.models'; +import { aiHandOverProgress } from '@home/components/ai/ai-hand-over.component'; +import { AiPlanRun } from '@home/components/ai/ai-plan.component'; +import { AiFile, aiFileMark, aiFileName, aiFileOf, downloadAiFile, downloadAiFileAsPng, WRITE_FILE_TOOL } from '@home/components/ai/ai-file.models'; +import { AiFileBodyComponent, AiFileMarks, AiFileSaver } from '@home/components/ai/ai-file-body.component'; +import { ClipboardService } from 'ngx-clipboard'; +import { AiChatMessagesComponent, AnswerRatingEvent, AnswerReportEvent } from '@home/components/ai/ai-chat-messages.component'; +import { EntityId } from '@shared/models/id/entity-id'; +import { EntityType } from '@shared/models/entity-type.models'; +import { AiAssistantViewType, AiRunAgain } from '@shared/models/ai-chat.models'; +import { aiReviewHead } from '@home/components/ai/ai-approval-card.component'; +import { AiChatTitleComponent } from '@home/components/ai/ai-chat-title.component'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AiAnswerFeedback, aiRateAnswer, aiReportAnswer, aiTrackLogScroll } from '@home/components/ai/ai-chat-session'; +import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; + +const PROGRESS_TOOLS = new Set(['wait_agent_operation']); + +export type AiChatVariant = 'page' | 'panel'; + +interface AiGetStartedExample { + key: string; + icon: string; + file?: boolean; +} + +interface AiRefusal { + undo: () => void; + rerun?: boolean; +} + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-ai-chat', + templateUrl: './ai-chat.component.html', + styleUrls: ['./ai-chat.component.scss'], + standalone: false, + host: { + 'data-ai': '', + 'class': 'tb-ai-chat', + '[class.split]': 'split() && docked()', + '[class.v-page]': '!docked()', + '[class.v-panel]': 'docked()' + }, + providers: AI_TOOLTIP_PROVIDERS +}) +export class AiChatComponent implements OnInit, OnDestroy { + + private static readonly RESUME_ATTEMPTS = 4; + private static readonly RESUME_DELAY_MS = 2000; + private static readonly NOTICE_MS = 6000; + private static readonly MENU_CHATS = 4; + + private static readonly NEW_CHAT_TITLE = 'New chat'; + + @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; + @ViewChild(AiChatTitleComponent) titleRef: AiChatTitleComponent; + + chatId = model(undefined); + + variant = input('page'); + + clientContext = input(undefined); + + toastTarget = input('aiChat'); + + fullscreenEnabled = input(true); + + prompts = input([]); + + startTitle = input(); + + startLine = input(); + + startPlaceholder = input(); + + startSuggestion = input(null); + + closed = output(); + + split = input(false); + + splitAvailable = input(false); + + splitToggle = output(); + + newSolution = output(); + + openCli = output(); + + getStarted = input(false); + + takeTour = output(); + + showGetStarted = computed(() => this.variant() === 'page' && this.getStarted() && !this.chatId()); + + readonly examples: AiGetStartedExample[] = [ + {key: 'mqtt', icon: 'memory'}, + {key: 'things-stack', icon: 'input'}, + {key: 'modbus', icon: 'lan'}, + {key: 'datasheet', icon: 'attach_file', file: true} + ]; + + otherChats = computed<{label: string; chats: ChatInfo[]}[]>(() => { + const others = this.chats.chats() + .filter(chat => chat.id !== this.chatId()) + .sort((a, b) => (b.updatedTime ?? b.createdTime) - (a.updatedTime ?? a.createdTime)); + const startedHere = new Set(this.panelService.chatsStartedHere()); + const here = others.filter(chat => startedHere.has(chat.id)).slice(0, AiChatComponent.MENU_CHATS - 1); + const recent = others.filter(chat => !startedHere.has(chat.id)).slice(0, Math.max(1, AiChatComponent.MENU_CHATS - here.length)); + return [ + ...(here.length ? [{label: 'ai-assistant.on-this-page', chats: here}] : []), + ...(recent.length ? [{label: 'ai-assistant.recent-chats', chats: recent}] : []) + ]; + }); + + headNarrow = signal(false); + + shownTitle = computed(() => { + const title = this.chat()?.title; + if (title && title !== AiChatComponent.NEW_CHAT_TITLE) { + return title; + } + const first = this.messages().find(message => message.from === 'USER') as GeneralChatMessage | undefined; + return typeof first?.content === 'string' && first.content.trim() ? aiChatNameOf(first.content) : title; + }); + + fullscreen = signal(false); + + docked = computed(() => this.variant() === 'panel' && !this.fullscreen()); + + readonly markdownStyles = [ + '.tb-markdown-view p, .tb-markdown-view h2, .tb-markdown-view h3, .tb-markdown-view h4, .tb-markdown-view h5, ' + + '.tb-markdown-view h6, .tb-markdown-view div.code-wrapper {padding-left: 0 !important;} ' + + '.tb-markdown-view ol, .tb-markdown-view ul {padding-left: 24px; padding-inline-start: 24px; padding-right: 0;}' + ]; + + messages = signal([]); + + loading = signal(false); + + historyLoading = signal(false); + + completedExecutions = signal>({}); + toolDurations = signal>({}); + + chat = computed(() => { + const id = this.chatId(); + return id ? this.chats.chats().find(chat => chat.id === id) : undefined; + }); + + newChatAutoApprove = signal(false); + + private static readonly FILE_WRAP_KEY = 'tbAiFileWrap'; + + private static readonly UNLISTED_KEY = 'tbAiUnlistedFiles:'; + + shownFile = signal(null); + + fileOpen = signal(false); + + private fileChat: string | undefined; + + fileWrap = signal(AiChatComponent.storedFileWrap()); + + fileCopied = signal(false); + + fileTheme = signal<'dark' | 'light'>(AiChatComponent.stored('tbAiFileTheme') === 'light' ? 'light' : 'dark'); + + fileWhitespace = signal(AiChatComponent.stored('tbAiFileWhitespace') === 'true'); + + fileMarks = signal(null); + + composerQuote = signal(null); + + fileBody = viewChild(AiFileBodyComponent); + + private composerBox = viewChild>('composer'); + + private composerHeight = effect(onCleanup => { + const box = this.composerBox()?.nativeElement; + const body = box?.parentElement; + if (!box || !body || typeof ResizeObserver === 'undefined') { + return; + } + const observer = new ResizeObserver(() => { + const field = box.querySelector('.composer-field') ?? box; + body.style.setProperty('--k-composer-h', Math.round(box.getBoundingClientRect().bottom - field.getBoundingClientRect().top) + 'px'); + }); + observer.observe(box); + onCleanup(() => observer.disconnect()); + }); + + private chatArea = viewChild>('chatArea'); + + private chatLog = viewChild(AiChatMessagesComponent, {read: ElementRef}); + + private composer = viewChild>('composer'); + + private logSizeEffect = effect(onCleanup => { + const area = this.chatArea()?.nativeElement; + const log = this.chatLog()?.nativeElement; + const composer = this.composer()?.nativeElement; + if (!area) { + return; + } + let composerHeight = composer?.offsetHeight ?? 0; + const observer = new ResizeObserver(() => { + const height = composer?.offsetHeight ?? 0; + if (height > composerHeight && untracked(this.atEnd)) { + area.scrollTop = area.scrollHeight; + } + composerHeight = height; + this.onLogScroll(area); + }); + observer.observe(area); + if (log) { + observer.observe(log); + } + if (composer) { + observer.observe(composer); + } + onCleanup(() => observer.disconnect()); + }); + + unlisted = signal>(new Set()); + + unlisting = signal(null); + + chatFiles = computed(() => { + const files = new Map(); + this.messages().forEach(message => { + if (message.from === 'ACTION' && message.data.tool === WRITE_FILE_TOOL) { + const file = aiFileOf(message.data.executionId, message.data.arguments, !!message.data.edited); + if (file) { + files.set(file.name, {file, running: message.data.status === 'RUNNING'}); + } + } + }); + const hidden = this.unlisted(); + return [...files.values()].filter(entry => !hidden.has(entry.file.name)); + }); + + readonly fileMark = aiFileMark; + + readonly fileName = aiFileName; + + readonly fileSaver: AiFileSaver = content => this.saveFile(content); + + private static stored(key: string): string | null { + return readStored(key); + } + + private static store(key: string, value: string): void { + writeStored(key, value); + } + + fileDark(file: AiFile): boolean { + return this.fileCode(file) && this.fileTheme() === 'dark'; + } + + fileCode(file: AiFile): boolean { + return !file.previewed || !!this.fileBody()?.editing(); + } + + setFileTheme(theme: 'dark' | 'light'): void { + this.fileTheme.set(theme); + AiChatComponent.store('tbAiFileTheme', theme); + } + + toggleFileWhitespace(): void { + this.fileWhitespace.update(value => !value); + AiChatComponent.store('tbAiFileWhitespace', String(this.fileWhitespace())); + } + + markedText(file: AiFile): string { + const marks = this.fileMarks(); + return marks ? file.content.replace(/\n$/, '').split('\n').slice(marks.from - 1, marks.to).join('\n') : ''; + } + + copyMarked(file: AiFile): void { + this.clipboard.copyFromContent(this.markedText(file)); + } + + askAboutMarks(file: AiFile): void { + const marks = this.fileMarks(); + if (!marks) { + return; + } + this.composerQuote.set({name: file.name, icon: file.icon, lang: file.lang === 'text' ? '' : file.lang, from: marks.from, to: marks.to, + text: this.markedText(file)}); + this.fileMarks.set(null); + if (this.docked()) { + this.fileOpen.set(false); + } + setTimeout(() => this.promptInput?.focus()); + } + + private fileCopiedTimer: ReturnType; + + private static storedFileWrap(): boolean { + return readStored(AiChatComponent.FILE_WRAP_KEY) === 'true'; + } + + autoApprove = computed(() => this.chatId() ? !!this.chat()?.autoApprove : this.newChatAutoApprove()); + + denyReasons = signal>({}); + + stopping = signal(false); + + work = signal(undefined); + + readonly tasks = ['connect-device', 'build-dashboard', 'set-up-alarm']; + + scrolled = signal(false); + + private atEnd = signal(true); + + private newTurns = signal(0); + + notice = signal(null); + + creditsOut = signal(null); + + limitOut = signal(null); + + private freshChatId: string | null = null; + + private noticeTimer: ReturnType; + + private seenMessages = 0; + + pill = computed<{mode: 'work' | 'new' | 'card'; kind: AiSpinKind; label: string; count: number} | null>(() => { + if (this.atEnd()) { + return null; + } + const waiting = this.waitingApproval(); + if (waiting) { + return {mode: 'card', kind: 'think', label: aiReviewHead(this.translate, waiting.data), count: 0}; + } + if (this.awaitingAnswer()) { + return {mode: 'card', kind: 'think', label: this.translate.instant('ai-assistant.question.needs-answer'), count: 0}; + } + if (this.loading() && !this.waitingApproval()) { + const running = this.messages().filter((message): message is ActionChatMessage => + message.from === 'ACTION' && message.data.status === 'RUNNING'); + if (running.length) { + const words = aiActionWords(running[0].data.tool, running[0].data.arguments); + return {mode: 'work', kind: words.kind, label: aiActionText(this.translate, words, 'run'), count: 0}; + } + const work = this.work(); + return {mode: 'work', kind: 'think', label: work ? this.translate.instant('ai-assistant.work.' + work.moment) : '', count: 0}; + } + const count = this.newTurns(); + return count ? {mode: 'new', kind: 'think', label: this.translate.instant('ai-assistant.new-count', {count}), count} : null; + }); + + private answeredApprovals = signal>(new Set()); + + dockShown = signal(false); + + waitingApproval = computed(() => { + if (this.autoApprove()) { + return undefined; + } + const completed = this.completedExecutions(); + const answered = this.answeredApprovals(); + return this.messages() + .filter((message): message is ApprovalChatMessage => message.from === 'APPROVAL') + .find(message => !completed[message.data.executionId] && !answered.has(message.data.executionId) && message.data.needsApproval); + }); + + private awaitingAnswer = computed(() => { + if (this.loading()) { + return false; + } + const messages = this.messages(); + const completed = this.completedExecutions(); + const answered = this.answeredApprovals(); + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i]; + if (message.from === 'USER') { + return false; + } + if (message.from === 'ACTION' && message.data.tool === ASK_USER_TOOL) { + return aiQuestionsOf(message.data.arguments).length > 0; + } + if (message.from === 'APPROVAL' && completed[message.data.executionId]?.approvalStatus === ToolApprovalResult.TIMEOUT + && !answered.has(message.data.executionId)) { + return true; + } + } + return false; + }); + + suggestion = computed(() => { + if (this.loading() || this.waitingApproval()) { + return null; + } + if (!this.messages().length) { + if (this.chatId()) { + return null; + } + return this.docked() ? this.startSuggestion() + : this.translate.instant(this.showGetStarted() ? 'ai-assistant.get-started.suggestion' : 'ai-assistant.start-suggestion'); + } + return aiTurnPrompts(this.messages())[0]?.text ?? null; + }); + + placeholder = computed(() => !this.waitingApproval() && !this.messages().length && this.startPlaceholder() + ? this.startPlaceholder() + : this.translate.instant(this.waitingApproval() + ? 'ai-assistant.deny-placeholder' + : this.messages().length + ? 'ai-assistant.follow-up-prompt-placeholder' + : 'ai-assistant.prompt-placeholder')); + + private aiChat = inject(AiChatService); + private chats = inject(AiChatsService); + private panelService = inject(AiAssistantPanelService); + + readonly keptEdits = this.panelService.keptEdits; + + reloadKeptEdits(): void { + this.panelService.reloadKeptEdits(); + } + + dismissKeptEdits(): void { + this.panelService.clearKeptEdits(); + } + private whiteLabelingService = inject(WhiteLabelingService); + private customMenuService = inject(CustomMenuService); + private translate = inject(TranslateService); + private clipboard = inject(ClipboardService); + private store = inject(Store); + private userService = inject(UserService); + private unitService = inject(UnitService); + private authService = inject(AuthService); + private sanitizer = inject(DomSanitizer); + private destroyRef = inject(DestroyRef); + private host = inject>(ElementRef); + private router = inject(Router); + private widgetCheck = inject(AiWidgetCheckService); + + readonly hostElement = this.host.nativeElement; + + private loadChat$ = new Subject(); + private cancelMessage$ = new Subject(); + private messageCancelled = false; + private shownChatId: string | undefined; + private replyingChatId: string | undefined; + private appliedEffects = new Set(); + private logScrollBottom: number | undefined; + + private newTurnsEffect = effect(() => { + this.messages(); + untracked(() => this.countNewTurns()); + }); + + private readonly keptDrafts = new Map(); + + private composing = false; + + private chatIdEffect = effect(() => { + const chatId = this.chatId() ?? null; + untracked(() => { + const draft = this.keptDrafts.get(chatId); + if (draft !== undefined && !(chatId === null && this.composing)) { + this.keptDrafts.delete(chatId); + setTimeout(() => this.promptInput?.setValue(draft)); + } + if (this.fileChat !== chatId) { + this.shownFile.set(null); + this.fileOpen.set(false); + } + this.unlisting.set(null); + this.newChatAutoApprove.set(false); + this.unlisted.set(new Set(AiChatComponent.storedList(chatId ? AiChatComponent.UNLISTED_KEY + chatId : null))); + this.show(chatId); + }); + }); + + level = computed(() => { + const chat = this.chat(); + return chat ? this.chats.levelOf(chat) : null; + }); + + statusTip = computed(() => { + const chat = this.chat(); + return chat ? this.chats.tipOf(chat) : ''; + }); + + private openChatEffect = effect(onCleanup => { + const chatId = this.chatId(); + untracked(() => this.chats.setOpen(chatId, true)); + onCleanup(() => untracked(() => this.chats.setOpen(chatId, false))); + }); + + private waitingEffect = effect(onCleanup => { + const chatId = this.chatId(); + const waiting = !!this.waitingApproval() || this.awaitingAnswer(); + untracked(() => this.chats.setWaiting(chatId, waiting)); + onCleanup(() => untracked(() => this.chats.setWaiting(chatId, false))); + }); + + private deletedChatEffect = effect(() => { + const chatId = this.chatId(); + if (chatId && this.chats.loaded() && !this.chats.find(chatId)) { + untracked(() => this.chatId.set(undefined)); + } + }); + + ngOnInit(): void { + if (typeof ResizeObserver !== 'undefined') { + const head = new ResizeObserver(() => { + const width = this.hostElement.querySelector('.ai-chat-head')?.clientWidth ?? 0; + this.headNarrow.set(width > 0 && width < AI_NARROW_HEAD_WIDTH); + }); + head.observe(this.hostElement); + this.destroyRef.onDestroy(() => head.disconnect()); + } + this.loadChat$.pipe( + switchMap(id => this.aiChat.getChatMessages(id, {ignoreLoading: true, ignoreErrors: true}).pipe( + catchError(err => { + this.historyLoading.set(false); + this.showErrorMessage(err); + return EMPTY; + }) + )), + takeUntilDestroyed(this.destroyRef) + ).subscribe(messages => { + this.historyLoading.set(false); + this.showHistory(messages); + this.resumeTurn(this.chatId()); + }); + } + + ngOnDestroy(): void { + this.cancelActiveMessage(); + } + + toggleFullscreen(): void { + const log = this.host.nativeElement.querySelector('.ai-chat-body'); + this.logScrollBottom = log ? log.scrollHeight - log.clientHeight - log.scrollTop : undefined; + this.fullscreen.set(!this.fullscreen()); + } + + onFullscreenChanged(fullscreen: boolean): void { + this.fullscreen.set(fullscreen); + const scrollBottom = this.logScrollBottom; + if (scrollBottom !== undefined) { + setTimeout(() => { + const log = this.host.nativeElement.querySelector('.ai-chat-body'); + if (log) { + log.scrollTop = log.scrollHeight - log.clientHeight - scrollBottom; + } + }); + } + } + + focus(): void { + this.promptInput?.focus(); + } + + levelOf(chat: ChatInfo): ChatLevel | null { + return this.chats.levelOf(chat); + } + + newChat(): void { + this.chatId.set(undefined); + setTimeout(() => this.focus()); + } + + keepDraftForCompose(): void { + const chatId = this.chatId() ?? null; + const draft = this.promptInput?.message.value ?? ''; + if (draft.trim()) { + this.keptDrafts.set(chatId, draft); + } else { + this.keptDrafts.delete(chatId); + } + this.composing = true; + } + + composeText(text: string): void { + this.composing = false; + this.promptInput?.setValue(text); + setTimeout(() => this.focus()); + } + + ask(message: string, secrets?: Record): void { + this.sendMsgFromUser(secrets ? {message, resources: [], secrets} : {message, resources: []}); + } + + showFile(file: AiFile): void { + this.shownFile.set(file); + this.fileChat = this.chatId(); + this.fileMarks.set(null); + this.fileOpen.set(true); + } + + isShownFile(file: AiFile): boolean { + return this.fileOpen() && this.shownFile()?.name === file.name; + } + + askUnlist(file: AiFile, event: Event): void { + event.preventDefault(); + event.stopPropagation(); + this.unlisting.set(file.name); + setTimeout(() => document.querySelector('.art-list-confirm .art-list-no')?.focus()); + } + + keepListed(event: Event): void { + event.stopPropagation(); + this.unlisting.set(null); + } + + unlist(file: AiFile, event: Event): void { + event.stopPropagation(); + const chatId = this.chatId(); + const next = new Set(this.unlisted()).add(file.name); + this.unlisted.set(next); + this.unlisting.set(null); + if (chatId) { + AiChatComponent.store(AiChatComponent.UNLISTED_KEY + chatId, JSON.stringify([...next])); + } + this.showToast(this.translate.instant('ai-assistant.file.unlisted', {name: escapeHtml(file.name)}), 'success'); + } + + onFileDiscarded(file: AiFile): void { + this.showToast(this.translate.instant('ai-assistant.file.discarded', {name: escapeHtml(file.name)}), 'success'); + } + + private saveFile(content: string): Promise { + const chatId = this.chatId(); + const file = this.shownFile(); + if (!chatId || !file) { + return Promise.resolve(false); + } + return new Promise(resolve => this.aiChat.updatedChat(chatId, {fileEdit: {executionId: file.executionId, content}}, {ignoreLoading: true, ignoreErrors: true}) + .subscribe({ + next: () => { + this.messages.update(messages => messages.map(message => message.from === 'ACTION' && message.data.executionId === file.executionId + ? {...message, data: {...message.data, arguments: {...(message.data.arguments as object), content}, edited: true}} : message)); + const saved = aiFileOf(file.executionId, {name: file.name, content, summary: file.summary}, true); + if (saved) { + this.shownFile.set(saved); + } + resolve(true); + }, + error: err => { + this.showErrorMessage(err); + resolve(false); + } + })); + } + + private static storedList(key: string | null): string[] { + if (!key) { + return []; + } + try { + const value = JSON.parse(localStorage.getItem(key) ?? '[]'); + return Array.isArray(value) ? value.filter(item => typeof item === 'string') : []; + } catch { + return []; + } + } + + toggleFileWrap(): void { + this.fileWrap.update(wrap => !wrap); + writeStored(AiChatComponent.FILE_WRAP_KEY, String(this.fileWrap())); + } + + copyFile(file: AiFile): void { + if (this.clipboard.copyFromContent(file.content)) { + this.fileCopied.set(true); + clearTimeout(this.fileCopiedTimer); + this.fileCopiedTimer = setTimeout(() => this.fileCopied.set(false), 1500); + } + } + + downloadFile(file: AiFile): void { + downloadAiFile(file); + } + + downloadFileAsPng(file: AiFile): void { + downloadAiFileAsPng(file).catch(() => this.store.dispatch(new ActionNotificationShow({ + message: this.translate.instant('ai-assistant.file.png-failed'), + type: 'error', + modern: true, + verticalPosition: 'bottom', + horizontalPosition: 'center' + }))); + } + + runPlan(event: {run: AiPlanRun; steps: AiPlanStep[]}): void { + if (event.run.auto && !this.autoApprove()) { + this.setAutoApprove(true); + } + const left = event.run.skipped.map(number => this.translate.instant('ai-assistant.plan.leave-out', + {number, text: event.steps[number - 1]?.text ?? ''})); + this.ask([this.translate.instant('ai-assistant.plan.run-prompt'), ...left].join('\n')); + } + + changePlan(): void { + this.ask(this.translate.instant('ai-assistant.plan.change-ask')); + } + + openAllChats(): void { + this.router.navigate(['/ai-assistant']); + this.closed.emit(); + } + + startRename(): void { + this.titleRef?.startRename(); + } + + rename(title: string): void { + const chat = this.chat(); + if (chat) { + this.chats.rename(chat.id, title).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + togglePinned(): void { + const chat = this.chat(); + if (chat) { + this.chats.setPinned(chat.id, !chat.pinned).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + deleteChat(): void { + const chat = this.chat(); + if (chat) { + this.chats.confirmAndDelete(chat).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + setAutoApprove(enabled: boolean): void { + const chatId = this.chatId(); + if (chatId) { + this.chats.setAutoApprove(chatId, enabled).subscribe({error: err => this.showErrorMessage(err)}); + } else { + this.newChatAutoApprove.set(enabled); + } + } + + stop(): void { + const chatId = this.chatId(); + if (!chatId || !this.loading() || this.stopping()) { + return; + } + this.stopping.set(true); + this.aiChat.stopChat(chatId, {ignoreLoading: true, ignoreErrors: true}).subscribe({ + error: err => { + this.stopping.set(false); + this.showErrorMessage(err); + } + }); + } + + onApprovalAction(event: ApprovalResult): void { + const chatId = this.chatId(); + if (event.autoApprove && chatId) { + this.chats.setAutoApprove(chatId, true).subscribe({error: err => this.showErrorMessage(err)}); + } + this.answeredApprovals.update(set => new Set(set).add(event.executionId)); + this.setWork(event.approved ? 'applying-change' : event.reason ? 'reading-what-to-change' : 'going-through-results'); + if (event.reason) { + this.denyReasons.update(reasons => ({...reasons, [event.executionId]: event.reason})); + } + const result: ApprovalResult = {executionId: event.executionId, approved: event.approved}; + if (event.reason) { + result.reason = event.reason; + } + this.aiChat.resolveToolApproval(result, {ignoreLoading: true, ignoreErrors: true}).subscribe(); + } + + startExample(example: AiGetStartedExample): void { + this.promptInput?.setValue(this.translate.instant('ai-assistant.get-started.example.' + example.key + '.prompt')); + if (example.file) { + this.promptInput?.openFilePicker(); + } + } + + startTask(task: string): void { + this.promptInput?.setValue(this.translate.instant('ai-assistant.task.' + task + '.prompt')); + } + + onRate(event: AnswerRatingEvent): void { + const answer = this.answerAt(event.index); + if (answer) { + aiRateAnswer(event, answer.rating, this.answerFeedback(answer)); + } + } + + onReport(event: AnswerReportEvent): void { + const answer = this.answerAt(event.index); + if (answer) { + aiReportAnswer(event, this.answerFeedback(answer), () => this.showToast(this.translate.instant('ai-assistant.feedback.thanks'), 'success')); + } + } + + private answerFeedback(answer: GeneralChatMessage): AiAnswerFeedback { + return { + patch: patch => this.patchAnswer(answer, patch), + send: feedback => this.chats.sendFeedback(this.chatId(), {answer: answer.content, ...feedback}), + failed: () => this.showErrorToast(this.translate.instant('ai-assistant.feedback.failed')) + }; + } + + private answerAt(index: number): GeneralChatMessage | null { + const message = this.messages()[index]; + return this.chatId() && message?.from === 'AI' && message.content ? message : null; + } + + private patchAnswer(answer: GeneralChatMessage, patch: Partial): void { + this.messages.update(list => list.map(message => message === answer || (message.from === 'AI' && message.content === answer.content + && message.time === answer.time) ? {...message, ...patch} as GeneralChatMessage : message)); + } + + answerLater(event: ApprovalResult): void { + if (event.reason) { + this.denyReasons.update(reasons => ({...reasons, [event.executionId]: event.reason})); + } + this.answeredApprovals.update(set => new Set(set).add(event.executionId)); + if (!this.runAgain(event.approved ? 'approve' : 'deny', event.executionId, event.reason)) { + this.reopenCard(event.executionId); + } + } + + private reopenCard(executionId: string): void { + this.answeredApprovals.update(set => { + const next = new Set(set); + next.delete(executionId); + return next; + }); + this.denyReasons.update(({[executionId]: _, ...rest}) => rest); + this.completedExecutions.update(map => map[executionId] ? {...map, [executionId]: {...map[executionId]}} : map); + } + + sendMsgFromUser(prompt: AiPromptMessage): void { + if (prompt.quote) { + prompt = {message: aiQuoteText(prompt.quote, prompt.message), resources: prompt.resources}; + this.composerQuote.set(null); + } + const waiting = this.waitingApproval(); + if (waiting) { + if (prompt.message.trim()) { + this.onApprovalAction({executionId: waiting.data.executionId, approved: false, reason: prompt.message.trim()}); + } + return; + } + const userMessage: GeneralChatMessage = prompt.resources.length + ? {from: 'USER', content: prompt.message, resources: prompt.resources, time: Date.now()} + : {from: 'USER', content: prompt.message, time: Date.now()}; + const startedFrom = this.messages().length ? undefined : this.startingPage(); + if (startedFrom) { + userMessage.startedFrom = startedFrom; + } + this.clearPassingNotice(); + this.messages.update(list => [...list, userMessage]); + if (this.loading() && this.chatId()) { + this.sendWhileWorking(prompt, userMessage); + return; + } + const closed = this.closeWaitingCards(); + this.sendMessage(prompt, undefined, {undo: () => { + this.reopenWaitingCards(closed); + this.restoreLastPrompt(); + }}).subscribe({ + error: err => { + if (this.isConnectionLost(err) && this.chatId()) { + this.setNotice('warn', 'wifi_off', 'connection-lost'); + this.resumeTurn(this.chatId(), true); + return; + } + this.reopenWaitingCards(closed); + this.onSendFailed(err, userMessage); + } + }); + } + + private startingPage(): AiStartedFrom | undefined { + const view = this.clientContext()?.view; + if (!view?.type || this.variant() !== 'panel') { + return undefined; + } + if (view.entityId) { + return {type: view.type, entityId: view.entityId}; + } + if (isAiTitledView(view.type)) { + return view.title || view.path ? {type: view.type, title: view.title, path: view.path} : undefined; + } + return view.type.endsWith('_LIST') || view.type === 'NOTIFICATION_INBOX' ? {type: view.type} : undefined; + } + + private show(chatId: string | undefined): void { + if (chatId === this.shownChatId) { + return; + } + this.cancelActiveMessage(); + this.titleRef?.cancelRename(); + this.shownChatId = chatId; + this.resetLogPosition(0); + this.messages.set([]); + this.limitOut.set(null); + this.completedExecutions.set({}); + this.toolDurations.set({}); + this.denyReasons.set({}); + this.answeredApprovals.set(new Set()); + this.historyLoading.set(!!chatId); + if (chatId) { + this.loadChat$.next(chatId); + } else { + setTimeout(() => this.promptInput?.focus()); + } + } + + resume(): void { + this.runAgain('resume'); + } + + runAgain(again: AiRunAgain, executionId?: string, reason?: string): boolean { + if (this.loading() || !this.chatId() || this.waitingApproval()) { + return false; + } + const failed = again === 'retry' ? this.messages().filter(message => (message as GeneralChatMessage).status === 'INCOMPLETE') : []; + const marker: GeneralChatMessage | null = again === 'retry' || again === 'resume' + ? {from: 'AI', content: '', status: again === 'retry' ? 'RETRIED' : 'RESUMED', time: Date.now()} : null; + const closed = again === 'retry' || again === 'resume' ? this.closeWaitingCards() : []; + const undo = () => { + this.messages.update(list => [...list.filter(message => message !== marker), ...failed]); + this.reopenWaitingCards(closed); + if (executionId) { + this.reopenCard(executionId); + } + }; + this.clearPassingNotice(); + this.messages.update(list => [...list.filter(message => !failed.includes(message)), ...(marker ? [marker] : [])]); + this.sendMessage({message: '', resources: []}, {again, executionId, reason}, {undo, rerun: true}).subscribe({ + error: err => { + if (this.isConnectionLost(err) && this.chatId()) { + this.setNotice('warn', 'wifi_off', 'connection-lost'); + this.resumeTurn(this.chatId(), true); + return; + } + undo(); + const limitType = aiCreditsLimitOf(err); + if (limitType) { + this.creditsOut.set(limitType); + } else { + setTimeout(() => this.showErrorMessage(err), 0); + } + } + }); + return true; + } + + private sendWhileWorking(prompt: AiPromptMessage, userMessage: ChatMessage): void { + const chatId = this.chatId(); + let ownTurn = false; + this.aiChat.sendChatMessage(chatId, this.chatRequest(prompt), {ignoreLoading: true, ignoreErrors: true}).pipe( + takeUntil(this.cancelMessage$), + concatMap(event => { + if (event.event === 'messageQueued') { + return of(event); + } + if (!ownTurn && !this.loading()) { + ownTurn = true; + this.chats.clearFailure(chatId); + this.startLoading(); + } + return this.handleChatEvent(event, {undo: () => this.restoreMessage(userMessage)}); + }), + finalize(() => { + if (ownTurn) { + this.stopLoading(); + } + }) + ).subscribe({ + error: err => this.onSendFailed(err, userMessage) + }); + } + + private discardFreshChat(): void { + const chatId = this.freshChatId; + this.freshChatId = null; + if (!chatId || chatId !== this.chatId()) { + return; + } + this.chats.discard(chatId).subscribe(); + this.shownChatId = undefined; + this.chatId.set(undefined); + } + + private onSendFailed(err: any, userMessage: ChatMessage): void { + const limitType = aiCreditsLimitOf(err); + if (limitType) { + this.restoreLastPrompt(); + this.discardFreshChat(); + this.creditsOut.set(limitType); + return; + } + this.messages.update(list => list.filter(message => message !== userMessage)); + setTimeout(() => this.showErrorMessage(err), 0); + } + + private chatRequest(prompt: AiPromptMessage): SendChatMessageRequest { + const request: SendChatMessageRequest = {message: prompt.message}; + if (prompt.resources.length) { + request.resources = prompt.resources.map(resource => resource.id); + } + const context = this.clientContext(); + request.clientContext = context ? {...context, os: context.os ?? aiClientOs()} + : {timeZone: getDefaultTimezone(), os: aiClientOs()} as AiChatClientContext; + const card = [...this.messages()].reverse().find((message): message is ActionChatMessage => + message.from === 'ACTION' && message.data.tool === HAND_OVER_TOOL); + const progress = card ? aiHandOverProgress(card.data.executionId) : null; + if (progress?.ticks.length) { + request.clientContext.handOver = {title: progress.title, ticked: progress.ticked, steps: progress.steps}; + } + if (prompt.secrets) { + request.secrets = prompt.secrets; + } + const editorDraft = this.panelService.editorDraft(); + if (editorDraft) { + request.editorDraft = editorDraft; + } + return request; + } + + private sendMessage(prompt: AiPromptMessage, again?: {again: AiRunAgain; executionId?: string; reason?: string}, + refused?: AiRefusal): Observable { + this.messageCancelled = false; + const startOrContinue$ = this.chatId() + ? of(null) + : this.chats.create(AiChatComponent.NEW_CHAT_TITLE, this.newChatAutoApprove()).pipe( + tap(chat => { + if (this.variant() === 'panel') { + this.panelService.noteStartedHere(chat.id); + } + this.freshChatId = chat.id; + this.shownChatId = chat.id; + this.chatId.set(chat.id); + }) + ); + const request = this.chatRequest(prompt); + this.limitOut.set(null); + if (again) { + request.again = again.again; + if (again.executionId) { + request.executionId = again.executionId; + } + if (again.reason) { + request.reason = again.reason; + } + } + this.setWork('reading-request', true); + this.loading.set(true); + return startOrContinue$.pipe( + tap(() => { + this.chats.clearFailure(this.chatId()); + this.startLoading(); + }), + switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})), + takeUntil(this.cancelMessage$), + concatMap(event => this.handleChatEvent(event, refused)), + finalize(() => this.stopLoading()) + ); + } + + private resumeTurn(chatId: string, afterConnectionLoss = false): void { + if (!chatId) { + return; + } + let resumed = false; + this.messageCancelled = false; + const attempt$ = timer(afterConnectionLoss ? AiChatComponent.RESUME_DELAY_MS : 0).pipe( + tap(() => { + if (afterConnectionLoss) { + this.startLoading(); + } + }), + switchMap(() => this.aiChat.resumeChat(chatId, {ignoreLoading: true, ignoreErrors: true})) + ); + attempt$.pipe( + retry({ + count: afterConnectionLoss ? AiChatComponent.RESUME_ATTEMPTS : 0, + delay: (error, attempt) => this.isConnectionLost(error) + ? timer(attempt * AiChatComponent.RESUME_DELAY_MS) + : throwError(() => error) + }), + takeUntil(this.cancelMessage$), + concatMap(event => { + if (event.event === 'turnResumed') { + resumed = true; + if (afterConnectionLoss) { + this.setNotice('info', 'wifi', 'connected-again', AiChatComponent.NOTICE_MS); + } + this.startLoading(); + this.dropRunningReply(); + return of(event); + } + return this.handleChatEvent(event); + }), + finalize(() => { + if (resumed || afterConnectionLoss) { + this.stopLoading(); + } + }) + ).subscribe({ + error: () => { + if (afterConnectionLoss) { + this.setNotice('warn', 'wifi_off', 'reconnect-failed'); + } + }, + complete: () => { + if (this.messageCancelled || this.chatId() !== chatId) { + return; + } + if (afterConnectionLoss && !resumed) { + this.setNotice('info', 'wifi', 'connected-again', AiChatComponent.NOTICE_MS); + } + if (resumed || afterConnectionLoss) { + this.aiChat.getChatMessages(chatId, {ignoreLoading: true, ignoreErrors: true}) + .pipe(takeUntil(this.cancelMessage$)) + .subscribe(messages => this.showHistory(messages)); + } + } + }); + } + + private handleChatEvent(event: ChatEvent, refused?: AiRefusal): Observable { + if (event.event && event.event !== 'error' && event.event !== 'chatTitleGenerated') { + this.freshChatId = null; + } + switch (event.event) { + case 'assistantDelta': + this.appendDelta(event.data.text); + break; + case 'thinking': { + if (event.data?.headline && !event.data.tool && this.showProgress(event.data.headline)) { + break; + } + const headline = this.thinkingHeadline(event.data); + if (headline) { + this.work.update(work => ({...(work ?? {moment: 'going-through-results' as AiWorkMoment, since: Date.now()}), headline})); + } + break; + } + case 'assistantMessage': + this.messages.update(list => [...this.withoutStreaming(list), { + from: 'AI', content: event.data.message, time: Date.now(), + ...(event.data.references?.length ? {references: event.data.references} : {}), + ...(event.data.severities?.length ? {severities: event.data.severities} : {}), + ...(event.data.readings?.length ? {readings: event.data.readings} : {}) + }]); + break; + case 'toolExecutionRequested': + this.handleToolApproval(event); + break; + case 'toolExecutionResult': { + const replayed = this.completedExecutions()[event.data.executionId]?.approvalStatus === event.data.approvalStatus; + this.completedExecutions.update(map => ({...map, [event.data.executionId]: event.data})); + if (event.data.executionStatus === 'SUCCESS' && !replayed) { + const call = this.messages().find(message => (message.from === 'APPROVAL' || message.from === 'ACTION') + && message.data.executionId === event.data.executionId); + if (call?.from === 'APPROVAL' || call?.from === 'ACTION') { + this.applySideEffects(event.data.executionId, call.data.tool, call.data.arguments); + this.openCreatedReportTemplate(call.data.tool, event.data.affectedEntities); + this.openCreatedDashboard(call.data.tool, event.data.affectedEntities); + this.openCreatedWidget(call.data.tool, event.data.affectedEntities); + this.openCreatedScadaSymbol(call.data.tool, call.data.arguments, event.data.result); + this.leaveDeletedScadaSymbol(call.data.tool, call.data.arguments); + } + } + if (event.data.affectedEntities?.length && !replayed) { + this.emitUpdated(event.data.affectedEntities); + } + break; + } + case 'toolStarted': + this.work.update(work => work?.headline ? {moment: work.moment, since: work.since} : work); + this.startAction(event.data); + this.runClientTool(event.data); + break; + case 'toolFinished': + this.finishAction(event.data); + break; + case 'limitReached': + this.limitOut.set(event.data); + break; + case 'turnStopped': + this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: this.translate.instant('ai-assistant.stopped'), status: 'STOPPED', time: Date.now()}]); + break; + case 'chatTitleGenerated': + if (this.chatId() && event.data.title) { + this.chats.setTitle(this.chatId(), event.data.title); + } + break; + default: + if (event.event === 'error' && event.data?.code === 'CREDITS_USED_UP' && this.ranSteps()) { + this.creditsOut.set('POOL'); + this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: '', status: 'INCOMPLETE', + failure: {reason: 'CREDITS_USED_UP'}, time: Date.now()}]); + } else if (event.event === 'error' && event.data?.code) { + if (refused) { + refused.undo(); + } else { + this.restoreLastPrompt(); + } + if (event.data.code === 'CREDITS_USED_UP') { + if (!refused?.rerun) { + this.discardFreshChat(); + } + this.creditsOut.set('POOL'); + } else { + this.setNotice('warn', 'hourglass_top', 'rate-limited'); + } + } else if (event.event === 'error') { + const message = event.data?.message || this.translate.instant('ai-assistant.run-failed'); + this.chats.setFailed(this.chatId(), message); + const failure = {reason: event.data?.reason}; + this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: message, status: 'INCOMPLETE', failure, time: Date.now()}]); + } + } + return of(event); + } + + onLogScroll(area: HTMLElement): void { + aiTrackLogScroll(area, {scrolled: this.scrolled, atEnd: this.atEnd, newTurns: this.newTurns}, () => this.seenMessages = this.messages().length); + } + + goToEnd(area: HTMLElement): void { + const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; + area.scrollTo({top: area.scrollHeight, behavior: reduce ? 'auto' : 'smooth'}); + } + + private countNewTurns(): void { + const total = this.messages().length; + if (this.atEnd() || total <= this.seenMessages) { + this.seenMessages = total; + return; + } + const added = total - this.seenMessages; + this.seenMessages = total; + if (added) { + this.newTurns.update(count => count + added); + } + } + + private runClientTool(started: ToolStarted): void { + if (started.tool === 'check_scada_symbol') { + const values = (typeof started.arguments === 'string' ? aiParse(started.arguments) : started.arguments) as {symbol?: string} | undefined; + if (values?.symbol) { + this.widgetCheck.checkScadaSymbol(values.symbol).subscribe(reason => + this.aiChat.resolveToolApproval({executionId: started.executionId, approved: true, reason}, {ignoreLoading: true, ignoreErrors: true}).subscribe()); + } + return; + } + if (started.tool !== 'check_widget') { + return; + } + const args = typeof started.arguments === 'string' ? this.parseArguments(started.arguments) : started.arguments as {widgetTypeId?: string}; + if (!args?.widgetTypeId) { + return; + } + this.widgetCheck.check(args.widgetTypeId).subscribe(reason => + this.aiChat.resolveToolApproval({executionId: started.executionId, approved: true, reason}, {ignoreLoading: true, ignoreErrors: true}).subscribe()); + } + + private parseArguments(text: string): {widgetTypeId?: string} { + try { + return JSON.parse(text); + } catch (e) { + return null; + } + } + + private startAction(started: ToolStarted): void { + if (isHiddenAiAction(started.tool) || this.isApprovalExecution(started.executionId) + || this.messages().some(message => message.from === 'ACTION' && message.data.executionId === started.executionId)) { + return; + } + const action: AiAction = { + executionId: started.executionId, + tool: started.tool, + arguments: started.arguments, + status: isKitCardTool(started.tool) ? 'SUCCESS' : 'RUNNING', + startedAt: started.startedAt ?? Date.now(), + ...(started.readOnly ? {readOnly: true} : {}) + }; + this.messages.update(list => [...list, {from: 'ACTION', data: action}]); + } + + private openCreatedReportTemplate(tool: string | undefined, affected: EntityId[] | undefined): void { + const chatId = this.chatId(); + const created = affected?.find(entity => entity.entityType === EntityType.REPORT_TEMPLATE); + if (tool !== 'create_report_template' || !created || !chatId + || this.panelService.clientContext()?.view?.type !== AiAssistantViewType.REPORT_TEMPLATE_LIST) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/reporting/templates', created.id]); + } + + private showProgress(progress: string): boolean { + const running = [...this.messages()].reverse() + .find(message => message.from === 'ACTION' && message.data.status === 'RUNNING' && PROGRESS_TOOLS.has(message.data.tool)); + if (running?.from !== 'ACTION') { + return false; + } + const executionId = running.data.executionId; + this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.executionId === executionId + ? {from: 'ACTION', data: {...message.data, progress, stages: message.data.progress && message.data.progress !== progress + ? [...(message.data.stages ?? []), message.data.progress] : message.data.stages}} : message)); + return true; + } + + private thinkingHeadline(data: {headline?: string; tool?: string; arguments?: unknown} | undefined): string | undefined { + return data?.tool ? aiActionText(this.translate, aiActionWords(data.tool, data.arguments), 'run') : undefined; + } + + private openCreatedDashboard(tool: string | undefined, affected: EntityId[] | undefined): void { + const chatId = this.chatId(); + const created = affected?.find(entity => entity.entityType === EntityType.DASHBOARD); + const view = this.panelService.clientContext()?.view?.type ?? aiPageView((this.router.url || '/').split(/[?#]/)[0]); + if (tool !== 'create_dashboard' || !created || !chatId + || (view !== AiAssistantViewType.DASHBOARD_LIST && view !== AiAssistantViewType.DASHBOARD_GROUP_LIST)) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/dashboards', created.id]); + } + + private openCreatedWidget(tool: string | undefined, affected: EntityId[] | undefined): void { + const chatId = this.chatId(); + const created = affected?.find(entity => entity.entityType === EntityType.WIDGET_TYPE); + const view = this.panelService.clientContext()?.view?.type; + if ((tool !== 'create_widget' && tool !== 'build_widget') || !created || !chatId + || (view !== AiAssistantViewType.WIDGET_TYPE_LIST && view !== AiAssistantViewType.NEW_WIDGET_TYPE)) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/resources/widgets-library/widget-types', created.id]); + } + + private openCreatedScadaSymbol(tool: string | undefined, args: unknown, result: string | undefined): void { + const chatId = this.chatId(); + const view = this.panelService.clientContext()?.view?.type ?? aiPageView((this.router.url || '/').split(/[?#]/)[0]); + const values = (aiParse(args) ?? {}) as {symbol?: string}; + if ((tool !== 'build_scada_symbol' && tool !== 'create_scada_symbol') || values.symbol || !chatId || !result?.startsWith('OK: ') + || (view !== AiAssistantViewType.SCADA_SYMBOL_LIST && view !== AiAssistantViewType.SCADA_SYMBOL)) { + return; + } + const link = (aiParse(result.slice(4)) as {link?: string} | undefined)?.link; + const path = /^tb-image;\/api\/images\/((?:system|tenant)\/[^/?#]+)$/.exec(link ?? '')?.[1]; + if (!path) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/resources/scada-symbols', ...path.split('/')]); + } + + private leaveDeletedScadaSymbol(tool: string | undefined, args: unknown): void { + const chatId = this.chatId(); + const values = (aiParse(args) ?? {}) as {targetType?: string; targetId?: string}; + const shown = /^\/resources\/scada-symbols\/tenant\/([^/?#]+)/.exec(this.router.url || '')?.[1]; + if (tool !== 'delete' || values.targetType !== 'IMAGE' || !chatId || !shown) { + return; + } + const deleted = (values.targetId ?? '').trim().replace(/^tb-image;/, '').split('/').pop(); + if (deleted !== decodeURIComponent(shown)) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/resources/scada-symbols']); + } + + private emitUpdated(entities: EntityId[]): void { + if (entities.length) { + this.panelService.emitUpdatedData(entities); + } + } + + private applySideEffects(executionId: string, tool: string | undefined, args: unknown): void { + if (!tool || this.appliedEffects.has(executionId)) { + return; + } + const values = (aiParse(args) ?? {}) as {target?: string; locale?: string; menuId?: string; targetType?: string; targetId?: string}; + switch (tool) { + case 'save_white_labeling': { + const target = values.target === 'LOGIN' ? 'LOGIN' : 'GENERAL'; + if (target === 'GENERAL') { + this.whiteLabelingService.loadUserWhiteLabelingParams().subscribe(); + } + this.panelService.emitWhiteLabelingSaved(target); + break; + } + case 'save_mail_template': + this.panelService.emitCustomizationSaved({kind: 'MAIL_TEMPLATES'}); + break; + case 'save_custom_translation': + if (values.locale && (values.locale === this.translate.currentLang || values.locale === this.translate.getDefaultLang())) { + this.translate.currentLoader.getTranslation(values.locale).subscribe(translation => + this.translate.setTranslation(values.locale, translation, true)); + } + this.panelService.emitCustomizationSaved({kind: 'TRANSLATION', locale: values.locale}); + break; + case 'save_mobile_qr_code': + this.panelService.emitCustomizationSaved({kind: 'MOBILE_QR_CODE'}); + break; + case 'save_two_factor_settings': + this.panelService.emitCustomizationSaved({kind: 'TWO_FACTOR'}); + break; + case 'save_my_profile': + this.applyOwnProfile(); + break; + case 'save_mail_server': + this.panelService.emitCustomizationSaved({kind: 'MAIL_SERVER'}); + break; + case 'save_notification_preferences': + this.panelService.emitCustomizationSaved({kind: 'ACCOUNT_NOTIFICATIONS'}); + break; + case 'save_my_two_factor': + case 'update_api_key': + this.panelService.emitCustomizationSaved({kind: 'ACCOUNT_SECURITY'}); + break; + case 'save_custom_menu': + case 'delete': + if (tool === 'delete' && values.targetType !== 'CUSTOM_MENU') { + return; + } + this.customMenuService.loadCustomMenu(true).subscribe(); + this.panelService.emitCustomizationSaved({kind: 'MENU', menuId: values.menuId ?? values.targetId, deleted: tool === 'delete'}); + break; + default: + return; + } + this.appliedEffects.add(executionId); + } + + private applyOwnProfile(): void { + const userId = getCurrentAuthUser(this.store)?.userId; + if (!userId) { + return; + } + this.userService.getUser(userId, {ignoreLoading: true}).subscribe(user => { + this.store.dispatch(new ActionAuthUpdateUserDetails({userDetails: { + additionalInfo: {...user.additionalInfo}, + authority: user.authority, + createdTime: user.createdTime, + tenantId: user.tenantId, + customerId: user.customerId, + email: user.email, + phone: user.phone, + firstName: user.firstName, + id: user.id, + lastName: user.lastName, + customMenuId: user.customMenuId + }})); + this.store.dispatch(new ActionSettingsChangeLanguage({userLang: user.additionalInfo?.lang || env.defaultLang, reload: false, ignoredLoad: false})); + this.unitService.setUnitSystem(user.additionalInfo?.unitSystem); + this.authService.refreshJwtToken(false); + this.panelService.emitCustomizationSaved({kind: 'PROFILE'}); + }); + } + + private finishAction(finished: ToolFinished): void { + this.toolDurations.update(map => ({...map, [finished.executionId]: finished.durationMs})); + const known = this.messages().find(message => message.from === 'ACTION' && message.data.executionId === finished.executionId); + if (known?.from === 'ACTION' && known.data.status !== 'RUNNING' && (known.data.result !== undefined || !isKitCardTool(known.data.tool))) { + return; + } + if (finished.status === 'SUCCESS') { + const started = this.messages().find(message => message.from === 'ACTION' && message.data.executionId === finished.executionId); + if (started?.from === 'ACTION') { + this.applySideEffects(finished.executionId, started.data.tool, started.data.arguments); + } + } + if (finished.affectedEntities?.length) { + this.emitUpdated(finished.affectedEntities); + } + this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.executionId === finished.executionId + ? {from: 'ACTION', data: {...message.data, status: finished.status, durationMs: finished.durationMs, result: finished.result, + affectedEntities: finished.affectedEntities}} + : message)); + const prompts = this.messages().some(message => message.from === 'ACTION' && message.data.executionId === finished.executionId + && isKitCardTool(message.data.tool)); + if (!prompts && !this.messages().some(message => message.from === 'ACTION' && message.data.status === 'RUNNING')) { + this.setWork('going-through-results', true); + } + } + + private isApprovalExecution(executionId: string): boolean { + return this.messages().some(message => message.from === 'APPROVAL' && message.data.executionId === executionId); + } + + private stopRunningActions(): void { + if (this.messages().some(message => message.from === 'ACTION' && message.data.status === 'RUNNING')) { + this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.status === 'RUNNING' + ? {from: 'ACTION', data: {...message.data, status: 'STOPPED', durationMs: Date.now() - message.data.startedAt}} + : message)); + } + } + + private setWork(moment: AiWorkMoment, restart = false): void { + if (restart || this.work()?.moment !== moment) { + this.work.set({moment, since: Date.now()}); + } + } + + private closeWaitingCards(): string[] { + const map = this.completedExecutions(); + const waiting = Object.keys(map).filter(id => map[id]?.approvalStatus === ToolApprovalResult.TIMEOUT); + if (waiting.length) { + this.completedExecutions.set({...map, ...Object.fromEntries(waiting.map(id => [id, {...map[id], approvalStatus: ToolApprovalResult.DENIED}]))}); + } + return waiting; + } + + private reopenWaitingCards(ids: string[]): void { + if (!ids.length) { + return; + } + this.completedExecutions.update(map => ({...map, ...Object.fromEntries(ids.filter(id => map[id]) + .map(id => [id, {...map[id], approvalStatus: ToolApprovalResult.TIMEOUT}]))})); + } + + private handleToolApproval(event: ToolExecutionRequestedEvent): void { + if (!event.data.needsApproval) { + return; + } + const id = event.data.executionId; + if (this.messages().some(message => message.from === 'APPROVAL' && message.data.executionId === id)) { + if (this.completedExecutions()[id]?.approvalStatus !== ToolApprovalResult.TIMEOUT) { + return; + } + this.completedExecutions.update(map => { + const {[id]: _, ...rest} = map; + return rest; + }); + this.messages.update(list => list.map(message => message.from === 'APPROVAL' && message.data.executionId === id + ? {from: 'APPROVAL', data: event.data} : message)); + return; + } + this.messages.update(list => [...list, {from: 'APPROVAL', data: event.data}]); + } + + private showHistory(messages: ChatMessage[]): void { + const completed: Record = {}; + for (const message of messages) { + const result = message.from === 'APPROVAL' ? (message as ApprovalChatMessage).result : undefined; + if (result) { + completed[result.executionId] = result; + } + } + this.completedExecutions.set(completed); + this.resetLogPosition(messages.length); + this.messages.set(messages); + } + + private resetLogPosition(seen: number): void { + this.atEnd.set(true); + this.scrolled.set(false); + this.newTurns.set(0); + this.seenMessages = seen; + } + + private appendDelta(text: string): void { + const last = this.messages()[this.messages().length - 1]; + if (last?.from === 'AI' && last.streaming) { + this.messages.update(list => [...list.slice(0, -1), {...last, content: last.content + text}]); + return; + } + this.work.set(undefined); + this.messages.update(list => [...list, {from: 'AI', content: text, streaming: true, time: Date.now()}]); + } + + private withoutStreaming(list: ChatMessage[]): ChatMessage[] { + const last = list[list.length - 1]; + return last?.from === 'AI' && last.streaming ? list.slice(0, -1) : list; + } + + private endStreaming(list: ChatMessage[]): ChatMessage[] { + const last = list[list.length - 1]; + return last?.from === 'AI' && last.streaming ? [...list.slice(0, -1), {...last, streaming: false}] : list; + } + + private dropRunningReply(): void { + this.messages.update(list => { + const lastUser = list.map(message => message.from).lastIndexOf('USER'); + return lastUser >= 0 ? list.slice(0, lastUser + 1) : list; + }); + } + + private cancelActiveMessage(): void { + this.messageCancelled = true; + this.cancelMessage$.next(); + this.stopLoading(); + this.promptInput?.reset(); + } + + private startLoading(): void { + this.loading.set(true); + this.setWork('reading-request'); + this.chats.setReplying(this.replyingChatId, false); + this.replyingChatId = this.chatId(); + this.chats.setReplying(this.replyingChatId, true); + } + + private stopLoading(): void { + if (this.loading()) { + this.chats.refresh().subscribe({error: () => {}}); + } + this.loading.set(false); + this.stopping.set(false); + this.work.set(undefined); + this.stopRunningActions(); + this.chats.setReplying(this.replyingChatId, false); + this.replyingChatId = undefined; + } + + private isConnectionLost(error: any): boolean { + return error instanceof HttpErrorResponse && error.status === 0; + } + + private showErrorMessage(error: any): void { + const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; + this.showErrorToast(parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message); + } + + private setNotice(kind: AiNotice['kind'], icon: string, key: string, hideAfter?: number): void { + clearTimeout(this.noticeTimer); + const notice: AiNotice = {kind, icon, text: this.translate.instant('ai-assistant.notice.' + key)}; + this.notice.set(notice); + if (hideAfter) { + this.noticeTimer = setTimeout(() => { + if (this.notice() === notice) { + this.notice.set(null); + } + }, hideAfter); + } + } + + private clearPassingNotice(): void { + if (this.notice()?.kind !== 'block') { + clearTimeout(this.noticeTimer); + this.notice.set(null); + } + } + + private ranSteps(): boolean { + const messages = this.messages(); + const last = messages.map(message => message.from).lastIndexOf('USER'); + return messages.slice(last + 1).some(message => message.from === 'ACTION' || message.from === 'APPROVAL'); + } + + private restoreMessage(userMessage: ChatMessage): void { + const content = (userMessage as GeneralChatMessage).content; + this.messages.update(list => list.filter(message => message !== userMessage)); + if (content) { + setTimeout(() => this.promptInput?.setValue(content)); + } + } + + private restoreLastPrompt(): void { + const messages = this.messages(); + const last = messages.map(message => message.from).lastIndexOf('USER'); + if (last < 0) { + return; + } + const content = (messages[last] as GeneralChatMessage).content; + this.messages.set(messages.slice(0, last)); + if (content) { + setTimeout(() => this.promptInput?.setValue(content)); + } + } + + private showErrorToast(message: string): void { + this.showToast(message, 'error'); + } + + private showToast(message: string, type: 'error' | 'success'): void { + this.store.dispatch(new ActionNotificationShow({ + message, + target: this.toastTarget(), + modern: true, + type, + verticalPosition: 'bottom', + horizontalPosition: 'center' + })); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts new file mode 100644 index 0000000000..1ba63ff0d7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts @@ -0,0 +1,939 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { TranslateService } from '@ngx-translate/core'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; + +export interface CodeLanguage { + lang: string; + label: string; + icon: string; +} + +const FOLD_LINES = 10; +const LONG_LINE = 72; +const COPIED_MS = 1500; +const SIDEWAYS = ['python', 'js', 'c', 'json', 'yaml']; + +const LANGUAGES: Record = { + bash: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + sh: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + shell: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + zsh: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + console: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + powershell: {lang: 'powershell', label: 'PowerShell', icon: 'terminal'}, + ps1: {lang: 'powershell', label: 'PowerShell', icon: 'terminal'}, + json: {lang: 'json', label: 'JSON', icon: 'data_object'}, + yaml: {lang: 'yaml', label: 'YAML', icon: 'description'}, + yml: {lang: 'yaml', label: 'YAML', icon: 'description'}, + log: {lang: 'log', label: 'Log', icon: 'notes'}, + diff: {lang: 'diff', label: 'Diff', icon: 'difference'}, + patch: {lang: 'diff', label: 'Diff', icon: 'difference'}, + js: {lang: 'js', label: 'JavaScript', icon: 'code'}, + javascript: {lang: 'js', label: 'JavaScript', icon: 'code'}, + ts: {lang: 'js', label: 'TypeScript', icon: 'code'}, + typescript: {lang: 'js', label: 'TypeScript', icon: 'code'}, + tbel: {lang: 'js', label: 'TBEL', icon: 'code'}, + python: {lang: 'python', label: 'Python', icon: 'code'}, + py: {lang: 'python', label: 'Python', icon: 'code'}, + c: {lang: 'c', label: 'C', icon: 'code'}, + cpp: {lang: 'c', label: 'C++', icon: 'code'}, + arduino: {lang: 'c', label: 'Arduino', icon: 'code'}, + java: {lang: 'c', label: 'Java', icon: 'code'}, + sql: {lang: 'text', label: 'SQL', icon: 'code'}, + xml: {lang: 'markup', label: 'XML', icon: 'code'}, + html: {lang: 'markup', label: 'HTML', icon: 'code'}, + svg: {lang: 'markup', label: 'SVG', icon: 'image'}, + css: {lang: 'css', label: 'CSS', icon: 'code'} +}; + +const FILE_LANGUAGES: Record = { + ino: {lang: 'c', label: 'Arduino', icon: 'code'}, + h: {lang: 'c', label: 'C', icon: 'code'}, + hpp: {lang: 'c', label: 'C++', icon: 'code'}, + md: {lang: 'text', label: 'Markdown', icon: 'article'}, + markdown: {lang: 'text', label: 'Markdown', icon: 'article'}, + txt: {lang: 'text', label: 'Text', icon: 'notes'}, + csv: {lang: 'text', label: 'CSV', icon: 'table_chart'}, + toml: {lang: 'text', label: 'TOML', icon: 'description'}, + ini: {lang: 'text', label: 'INI', icon: 'description'}, + conf: {lang: 'text', label: 'Config', icon: 'description'}, + env: {lang: 'shell', label: 'Env', icon: 'description'} +}; + +const LABEL_KEYS: Record = {Terminal: 'terminal', Log: 'log', Diff: 'diff', Text: 'text', Config: 'config'}; + +function shownLabel(label: string, translate: TranslateService): string { + return LABEL_KEYS[label] ? translate.instant('ai-assistant.code.label.' + LABEL_KEYS[label]) : label; +} + +export function fileLanguage(name: string): CodeLanguage { + const ext = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : ''; + return FILE_LANGUAGES[ext] ?? LANGUAGES[ext] ?? {lang: 'text', label: ext ? ext.toUpperCase() : 'Text', icon: 'description'}; +} + +export function decorateCodeBlocks(root: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { + readFenceMeta(root); + mergeTabs(root, translate, copy); + root.querySelectorAll('pre').forEach(pre => { + if (!pre.closest('.tb-codeblock')) { + decorate(pre, translate, copy); + } + }); +} + +const FENCE_META = '\u2063tb:'; +const OS_TABS: Record = {macos: 'macos', mac: 'macos', windows: 'windows', linux: 'linux'}; + +export function aiFenceMeta(markdown: string): string { + let open: string | null = null; + return (markdown ?? '').split('\n').map(line => { + const fence = /^(\s*)(`{3,}|~{3,})(.*)$/.exec(line); + if (!fence) { + return line; + } + if (open) { + if (fence[2].startsWith(open) && !fence[3].trim()) { + open = null; + } + return line; + } + open = fence[2]; + const info = fence[3].trim(); + const tab = /(?:^|\s)tab=(.+)$/.exec(info)?.[1]?.trim(); + const words = info.replace(/(?:^|\s)tab=.+$/, '').trim().split(/\s+/).filter(Boolean); + const fileOf = (word: string) => /^[\w.-]+\.\w+$/.test(word ?? '') ? word : null; + const file = words.length > 1 ? fileOf(words[1]) : fileOf(words[0]); + if (!file && !tab) { + return line; + } + const lang = words.length > 1 || !file ? (words[0] ?? '') : fileLanguage(file).lang; + const meta = JSON.stringify({...(file ? {file} : {}), ...(tab ? {tab} : {})}); + return fence[1] + fence[2] + lang + '\n' + FENCE_META + encodeURIComponent(meta); + }).join('\n'); +} + +function readFenceMeta(root: HTMLElement): void { + root.querySelectorAll('pre > code').forEach(code => { + const text = code.textContent ?? ''; + if (!text.startsWith(FENCE_META)) { + return; + } + const end = text.indexOf('\n'); + let meta: {file?: string; tab?: string} = {}; + try { + meta = JSON.parse(decodeURIComponent(text.slice(FENCE_META.length, end < 0 ? text.length : end))); + } catch { + meta = {}; + } + code.textContent = end < 0 ? '' : text.slice(end + 1); + if (meta.file) { + code.setAttribute('data-file', meta.file); + code.setAttribute('data-label', meta.file); + } + if (meta.tab) { + code.setAttribute('data-tab', meta.tab); + } + }); +} + +function mergeTabs(root: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { + const unitOf = (pre: Element): Element => { + const parent = pre.parentElement; + return parent && parent !== root && parent.tagName === 'DIV' && !/tb-markdown-view/.test(parent.className) + && parent.querySelectorAll(':scope > pre').length === 1 ? parent : pre; + }; + const pres = Array.from(root.querySelectorAll('pre')).filter(pre => pre.querySelector('code[data-tab]') && !pre.closest('.tb-codeblock')); + const used = new Set(); + pres.forEach(first => { + if (used.has(first)) { + return; + } + const group = [first]; + let next = unitOf(first).nextElementSibling; + while (next) { + const pre = next.matches('pre') ? next : next.querySelector(':scope > pre'); + if (!pre || !pre.querySelector('code[data-tab]')) { + break; + } + group.push(pre as HTMLPreElement); + next = unitOf(pre).nextElementSibling; + } + group.forEach(pre => used.add(pre)); + if (group.length < 2) { + return; + } + const tabs: CodeTab[] = group.map(pre => { + const code = pre.querySelector('code'); + const label = code.getAttribute('data-tab'); + const lang = /(?:^|\s)language-([\w+#-]+)/.exec(code.className)?.[1]?.toLowerCase(); + return {id: OS_TABS[label.toLowerCase()] ?? label, label, text: (code.textContent ?? '').replace(/\n$/, ''), lang}; + }); + const os = tabs.every(tab => Object.values(OS_TABS).includes(tab.id)); + const key = os ? 'os' : 'tabs:' + tabs.map(tab => tab.id).join('|'); + const local = /Windows/i.test(navigator.userAgent) ? 'windows' : /Mac/i.test(navigator.userAgent) ? 'macos' : 'linux'; + const preferred = codeTabGroup(key) ?? (os ? local : null); + const initial = Math.max(0, tabs.findIndex(tab => tab.id === preferred)); + const block = codeTabsBlock(tabs, tabs[0].lang ?? 'shell', translate, copy, initial, undefined, {group: key}); + const anchor = unitOf(group[0]); + anchor.parentNode.insertBefore(block, anchor); + group.forEach(pre => unitOf(pre).remove()); + }); +} + +function languageOf(pre: HTMLElement): CodeLanguage | null { + const classes = [pre.className, pre.querySelector('code')?.className ?? ''].join(' '); + const name = /(?:^|\s)language-([\w+#-]+)/.exec(classes)?.[1]?.toLowerCase(); + const file = pre.querySelector('code')?.getAttribute('data-file'); + if (file && (!name || name === 'text' || name === 'plaintext' || name === 'none')) { + return {...fileLanguage(file), label: file}; + } + if (!name || name === 'text' || name === 'plaintext' || name === 'none') { + return null; + } + const language = LANGUAGES[name] ?? {lang: 'text', label: name.toUpperCase(), icon: 'code'}; + const label = pre.querySelector('code')?.getAttribute('data-label'); + return label ? {...language, label} : language; +} + +function decorate(pre: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { + const text = (pre.textContent ?? '').replace(/\n$/, ''); + const file = pre.querySelector('code')?.getAttribute('data-file'); + const noCopy = pre.querySelector('code')?.hasAttribute('data-nocopy'); + const alwaysFolds = !!pre.querySelector('code')?.hasAttribute('data-fold'); + const language = languageOf(pre); + const lang = language?.lang ?? 'text'; + const shell = lang === 'shell' || lang === 'powershell'; + const commands = shell ? splitCommands(text) : [text]; + const code = element('code', 'lang-' + lang); + if (commands.length > 1) { + code.append(...commands.map(command => { + const row = element('div', 'tb-cmd'); + row.append(...lines(lang, command), commandCopyBtn(command, translate, copy)); + return row; + })); + } else { + code.append(...lines(lang, text)); + } + pre.className = 'tb-code'; + pre.replaceChildren(code); + const lineCount = text.split('\n').length; + const folds = (lineCount > FOLD_LINES || alwaysFolds) && lang !== 'diff'; + const block = element('div', 'tb-codeblock'); + const wrapper = pre.closest('.code-wrapper'); + if (wrapper) { + wrapper.parentNode.insertBefore(pre, wrapper); + wrapper.remove(); + } + block.dataset.lang = lang; + block.classList.toggle('shell', shell); + block.classList.toggle('labeled', !!language || folds); + block.classList.toggle('folds', folds); + block.classList.toggle('folded', folds); + pre.parentNode.insertBefore(block, pre); + const copyButton = copyBtn(text, translate, copy); + if (language || folds) { + const head = element('div', 'tb-codeblock-head'); + const label = element('span', 'tb-codeblock-label'); + label.textContent = language ? shownLabel(language.label, translate) : translate.instant('ai-assistant.code.script'); + if (folds) { + const toggle = element('button', 'tb-codefold') as HTMLButtonElement; + toggle.type = 'button'; + toggle.setAttribute('aria-expanded', 'false'); + const size = element('span', 'tb-codeblock-size'); + size.textContent = translate.instant('ai-assistant.code.lines', {count: lineCount}); + toggle.append(...[language ? icon(language.icon, 'tb-mat-16') : null, label, size, icon('expand_more', 'tb-mat-18 tb-codefold-tg')].filter(Boolean)); + toggle.addEventListener('click', () => { + const open = block.classList.toggle('folded') === false; + toggle.setAttribute('aria-expanded', String(open)); + if (open) { + aiRevealOpened(block); + } + }); + head.append(toggle); + } else { + head.append(icon(language.icon, 'tb-mat-16'), label); + } + const wrap = wrapBtn(block, text, translate); + head.append(...[wrap, noCopy ? null : copyButton, file ? downloadBtn(file, text, translate) : null].filter(Boolean)); + block.append(head, pre); + } else { + copyButton.classList.add('floating'); + block.append(...[pre, noCopy ? null : copyButton].filter(Boolean)); + } +} + +export interface CodeTab { + label: string; + text: string; + id?: string; + lang?: string; +} + +export interface CodeBlockOptions { + group?: string; + label?: string; + icon?: boolean; + check?: boolean; + labelledCopy?: boolean; + classes?: string; +} + +const GROUP_EVENT = 'tb-code-tab'; +const LABELLED_COPIED_MS = 1600; + +interface GroupPick { + group: string; + id: string; + from: HTMLElement; +} + +type PickableBlock = HTMLElement & {tbPick?: (id: string) => void}; + +let groupListening = false; + +function listenToGroups(): void { + if (groupListening) { + return; + } + groupListening = true; + document.addEventListener(GROUP_EVENT, (event: CustomEvent) => { + document.querySelectorAll('[data-code-group]').forEach(block => { + if (block !== event.detail.from && block.dataset.codeGroup === event.detail.group) { + block.tbPick?.(event.detail.id); + } + }); + }); +} + +export function codeTabGroup(group: string): string | null { + return readStored('tb-code-' + group); +} + +function storeCodeTab(group: string, id: string): void { + writeStored('tb-code-' + group, id); +} + +export function pickCodeTab(group: string, id: string, from: HTMLElement = document.body): void { + storeCodeTab(group, id); + listenToGroups(); + document.dispatchEvent(new CustomEvent(GROUP_EVENT, {detail: {group, id, from}})); +} + +export function onCodeTabGroup(group: string, picked: (id: string) => void): () => void { + const listener = (event: CustomEvent) => { + if (event.detail.group === group) { + picked(event.detail.id); + } + }; + document.addEventListener(GROUP_EVENT, listener); + return () => document.removeEventListener(GROUP_EVENT, listener); +} + +export function codeTabsBlock(tabs: CodeTab[], lang: string, translate: TranslateService, copy: (text: string) => boolean, + initial = 0, picked?: (tab: CodeTab) => void, options: CodeBlockOptions = {}): HTMLElement { + const languageOf = (tab: CodeTab) => { + const name = tab.lang ?? lang; + return LANGUAGES[name] ?? {lang: 'text', label: name.toUpperCase(), icon: 'code'}; + }; + const keyOf = (tab: CodeTab) => tab.id ?? tab.label; + let current = Math.min(Math.max(initial, 0), tabs.length - 1); + if (options.group) { + const stored = codeTabGroup(options.group); + const index = tabs.findIndex(tab => keyOf(tab) === stored); + if (index >= 0) { + current = index; + } + } + const block: PickableBlock = element('div', 'tb-codeblock labeled tabbed' + (options.classes ? ' ' + options.classes : '')); + const head = element('div', 'tb-codeblock-head'); + const list = element('div', 'tb-codetabs'); + list.setAttribute('role', 'tablist'); + if (options.label) { + list.setAttribute('aria-label', options.label); + } + const code = element('code', ''); + const pre = element('pre', 'tb-code'); + pre.append(code); + const select = (index: number, byPerson: boolean) => { + if (index === current) { + return; + } + current = index; + paint(); + if (byPerson) { + if (options.group) { + pickCodeTab(options.group, keyOf(tabs[current]), block); + } + picked?.(tabs[current]); + } + }; + const buttons = tabs.map((tab, index) => { + const button = element('button', 'tb-codetab') as HTMLButtonElement; + button.type = 'button'; + button.setAttribute('role', 'tab'); + button.textContent = tab.label; + button.addEventListener('click', () => select(index, true)); + button.addEventListener('keydown', event => { + const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0; + if (step) { + event.preventDefault(); + select((current + step + tabs.length) % tabs.length, true); + buttons[current].focus(); + } + }); + return button; + }); + const paint = () => { + const language = languageOf(tabs[current]); + block.dataset.lang = language.lang; + block.classList.toggle('shell', language.lang === 'shell' || language.lang === 'powershell'); + code.className = 'lang-' + language.lang; + buttons.forEach((button, index) => { + button.setAttribute('aria-selected', String(index === current)); + button.tabIndex = index === current ? 0 : -1; + }); + code.replaceChildren(...lines(language.lang, tabs[current].text)); + }; + if (options.group) { + listenToGroups(); + block.dataset.codeGroup = options.group; + block.tbPick = id => { + const index = tabs.findIndex(tab => keyOf(tab) === id); + if (index >= 0) { + select(index, false); + } + }; + } + list.append(...buttons); + head.append(...[options.icon === false ? null : icon(languageOf(tabs[current]).icon, 'tb-mat-16'), list, + copyBtn(() => tabs[current].text, translate, copy, options)].filter(Boolean)); + block.append(head, pre); + paint(); + return block; +} + +export function labelledCodeBlock(text: string, label: string, lang: string, translate: TranslateService, copy: (text: string) => boolean, + options: CodeBlockOptions = {}): HTMLElement { + const language = LANGUAGES[lang]?.lang ?? 'text'; + const block = element('div', 'tb-codeblock labeled' + (options.classes ? ' ' + options.classes : '')); + block.dataset.lang = language; + block.classList.toggle('shell', language === 'shell' || language === 'powershell'); + const head = element('div', 'tb-codeblock-head'); + const name = element('span', 'tb-codeblock-label'); + name.textContent = label; + head.append(name, copyBtn(text, translate, copy, options)); + const pre = element('pre', 'tb-code'); + const code = element('code', 'lang-' + language); + code.append(...lines(language, text)); + pre.append(code); + block.append(head, pre); + return block; +} + +export function valueBlock(label: string, value: string, translate: TranslateService, copy: (text: string) => boolean, + ariaLabel?: string): HTMLElement { + const block = element('div', 'tb-codeblock value'); + block.dataset.lang = 'text'; + const name = element('span', 'tb-codeblock-label'); + name.textContent = label; + const shown = element('code', 'tb-value'); + shown.textContent = value; + shown.title = value; + const button = copyBtn(value, translate, copy, {check: true}); + if (ariaLabel) { + button.setAttribute('aria-label', ariaLabel); + } + block.append(name, shown, button); + return block; +} + +export function commandRow(text: string, windows: boolean, translate: TranslateService, copy: (text: string) => boolean): HTMLElement { + const row = element('div', 'tb-cmdrow'); + const mark = element('span', 'tb-cmd-p'); + mark.setAttribute('aria-hidden', 'true'); + mark.textContent = windows ? '>' : '$'; + const command = element('code', 'tb-cmd-t'); + command.append(...lines('shell', text).flatMap(line => Array.from(line.childNodes))); + const button = copyBtn(text, translate, copy, {check: true}); + button.classList.add('tb-cmd-copy'); + button.setAttribute('aria-label', translate.instant('ai-assistant.copy') + ': ' + text); + row.append(mark, command, button); + return row; +} + +function wrapBtn(block: HTMLElement, text: string, translate: TranslateService): HTMLButtonElement | null { + if (!SIDEWAYS.includes(block.dataset.lang) || !text.split('\n').some(line => line.length > LONG_LINE)) { + return null; + } + const button = element('button', 'tb-codecopy tb-wrap') as HTMLButtonElement; + button.type = 'button'; + const tip = (on: boolean) => translate.instant(on ? 'ai-assistant.code.one-line-each' : 'ai-assistant.code.wrap-lines'); + button.dataset.tip = tip(false); + button.setAttribute('aria-label', translate.instant('ai-assistant.code.wrap-long-lines')); + button.setAttribute('aria-pressed', 'false'); + button.append(icon('wrap_text', 'tb-mat-16')); + button.addEventListener('click', () => { + const on = block.classList.toggle('wrap'); + button.setAttribute('aria-pressed', String(on)); + button.dataset.tip = tip(on); + }); + return button; +} + +function commandCopyBtn(text: string, translate: TranslateService, copy: (text: string) => boolean): HTMLButtonElement { + const button = copyBtn(text, translate, copy); + button.classList.add('tb-cmdcopy'); + return button; +} + +function copyBtn(text: string | (() => string), translate: TranslateService, copy: (text: string) => boolean, + options: CodeBlockOptions = {}): HTMLButtonElement { + const button = element('button', 'tb-codecopy') as HTMLButtonElement; + button.type = 'button'; + button.dataset.tip = translate.instant('ai-assistant.copy'); + button.dataset.copied = translate.instant('ai-assistant.copied'); + button.setAttribute('aria-label', translate.instant('ai-assistant.copy')); + const glyph = icon('content_copy', 'tb-mat-16'); + button.append(glyph); + let timer: ReturnType; + if (options.labelledCopy) { + button.classList.add('labelled'); + const word = element('span', 'lbl'); + word.setAttribute('aria-live', 'polite'); + word.textContent = translate.instant('ai-assistant.copy'); + button.append(word); + const done = (ms: number) => { + clearTimeout(timer); + button.classList.add('done'); + word.textContent = translate.instant('ai-assistant.copied'); + glyph.textContent = 'check'; + timer = setTimeout(() => { + button.classList.remove('done'); + word.textContent = translate.instant('ai-assistant.copy'); + glyph.textContent = 'content_copy'; + }, ms); + }; + button.addEventListener('click', () => { + if (copy(typeof text === 'function' ? text() : text)) { + done(LABELLED_COPIED_MS); + } + }); + return button; + } + button.append(icon('check', 'tb-mat-16 tb-copy-ok')); + button.addEventListener('click', () => { + if (copy(typeof text === 'function' ? text() : text)) { + button.classList.add('copied'); + announceCopied(translate.instant('ai-assistant.copied')); + clearTimeout(timer); + timer = setTimeout(() => button.classList.remove('copied'), COPIED_MS); + } + }); + return button; +} + +let copiedRegion: HTMLElement | null = null; + +export function announceCopied(words: string): void { + if (!copiedRegion?.isConnected) { + copiedRegion = element('div', 'tb-ai-sr-only'); + copiedRegion.setAttribute('role', 'status'); + copiedRegion.setAttribute('aria-live', 'polite'); + document.body.append(copiedRegion); + } + const region = copiedRegion; + region.textContent = ''; + setTimeout(() => region.textContent = words, 30); +} + +function downloadBtn(file: string, text: string, translate: TranslateService): HTMLButtonElement { + const button = element('button', 'tb-codecopy labelled tb-download') as HTMLButtonElement; + button.type = 'button'; + button.setAttribute('aria-label', translate.instant('ai-assistant.code.download-file', {name: file})); + const word = element('span', 'lbl'); + word.textContent = translate.instant('ai-assistant.code.download'); + button.append(icon('download', 'tb-mat-16'), word); + button.addEventListener('click', () => { + const url = URL.createObjectURL(new Blob([text.endsWith('\n') ? text : text + '\n'], {type: 'text/plain'})); + const link = document.createElement('a'); + link.href = url; + link.download = file; + link.click(); + setTimeout(() => URL.revokeObjectURL(url)); + }); + return button; +} + +function icon(name: string, size: string): HTMLElement { + const glyph = element('span', `mat-icon material-icons notranslate ${size}`); + glyph.setAttribute('aria-hidden', 'true'); + glyph.textContent = name; + return glyph; +} + +function element(tag: string, classes: string): HTMLElement { + const created = document.createElement(tag); + created.className = classes; + return created; +} + +type Piece = string | HTMLElement | null; + +interface ShellState { + command: boolean; + quote: string | null; + comment?: boolean; +} + +const KEYWORDS: Record = { + python: /^(import|from|as|def|return|if|else|elif|for|in|while|with|try|except|True|False|None|and|or|not|print)$/, + js: /^(const|let|var|await|async|function|return|if|else|for|of|new|true|false|null|import|from|export)$/, + c: /^(constexpr|const|char|int|uint16_t|uint32_t|bool|void|return|if|else|define|include|true|false)$/ +}; + +function splitCommands(text: string): string[] { + const groups: string[][] = []; + let quote: string | null = null; + let continued = false; + text.split('\n').forEach(line => { + if (!groups.length || (!quote && !continued)) { + groups.push([]); + } + groups[groups.length - 1].push(line); + quote = openQuoteAfter(line, quote); + continued = !quote && /\\\s*$/.test(line); + }); + return groups.map(group => group.join('\n')); +} + +function openQuoteAfter(line: string, quote: string | null): string | null { + for (let i = 0; i < line.length; i++) { + const char = line[i]; + if (quote) { + if (char === '\\' && quote === '"') { + i++; + } else if (char === quote) { + quote = null; + } + } else if (char === '\\') { + i++; + } else if (char === '#' && (i === 0 || /\s/.test(line[i - 1]))) { + break; + } else if (char === '"' || char === '\'') { + quote = char; + } + } + return quote; +} + +export function highlightCode(lang: string, text: string): HTMLElement[] { + return lines(lang, text); +} + +function lines(lang: string, text: string): HTMLElement[] { + const state: ShellState = {command: true, quote: null}; + const highlight = lineHighlighter(lang, state); + return text.split('\n').map((line, i, all) => { + let classes = 'tb-line'; + if (i && /\\\s*$/.test(all[i - 1])) { + classes += ' cont'; + } + if (lang === 'diff') { + classes += /^\+(?!\+\+ )/.test(line) ? ' add' : /^-(?!-- )/.test(line) ? ' del' : ''; + } + const span = element('span', classes); + span.append(...highlight(line).filter(piece => piece !== null && piece !== '')); + return span; + }); +} + +function lineHighlighter(lang: string, state: ShellState): (line: string) => Piece[] { + switch (lang) { + case 'shell': + case 'powershell': + return line => shellLine(line, state); + case 'json': + return jsonLine; + case 'yaml': + return yamlLine; + case 'log': + return logLine; + case 'diff': + return line => /^(\+\+\+ |--- |@@)/.test(line) ? [token('com', line)] : [line]; + case 'markup': + return line => markupLine(line, state); + case 'css': + return line => cssLine(line, state); + case 'python': + case 'js': + case 'c': + return line => codeLine(lang, line); + default: + return line => [line]; + } +} + +function blockComment(line: string, state: ShellState, open: string, close: string): [Piece[], string] { + const out: Piece[] = []; + let rest = line; + while (rest) { + if (state.comment) { + const end = rest.indexOf(close); + if (end < 0) { + out.push(token('com', rest)); + return [out, '']; + } + out.push(token('com', rest.slice(0, end + close.length))); + rest = rest.slice(end + close.length); + state.comment = false; + } + const start = rest.indexOf(open); + if (start < 0) { + return [out, rest]; + } + out.push(rest.slice(0, start)); + state.comment = true; + rest = rest.slice(start); + const end = rest.indexOf(close, open.length); + if (end >= 0) { + out.push(token('com', rest.slice(0, end + close.length))); + rest = rest.slice(end + close.length); + state.comment = false; + } else { + out.push(token('com', rest)); + return [out, '']; + } + } + return [out, '']; +} + +function markupLine(line: string, state: ShellState): Piece[] { + if (state.comment || line.includes(''); + return [...pieces.flatMap(piece => typeof piece === 'string' ? markupText(piece) : [piece]), ...markupText(rest)]; + } + return markupText(line); +} + +function markupText(text: string): Piece[] { + const out: Piece[] = []; + const pattern = /(?<\/?[\w:-]+)|(?\/?>)|(?[\w:@.[\]()*#-]+)(?==)|(?=)|(?"[^"]*"?|'[^']*'?)|(?\{\{.*?\}\})|(?@(?:if|else if|else|for|empty|switch|case|default|let)\b)|(?[^<>="'{@]+|[{@>])/g; + for (const match of text.matchAll(pattern)) { + const groups = match.groups ?? {}; + if (groups.tag) { + out.push(token('op', groups.tag.startsWith(' typeof piece === 'string' ? cssText(piece) : [piece]), ...cssText(rest)]; +} + +function cssText(text: string): Piece[] { + const declaration = /^(\s*)([\w-]+)(\s*:\s*)([^;{}]*)(;?)(.*)$/.exec(text); + if (declaration && !/[{]/.test(text) && !/^\s*[.#&:@]/.test(text)) { + const [, indent, property, colon, value, semi, tail] = declaration; + return [indent, token('key', property), token('op', colon), ...cssValue(value), semi ? token('op', semi) : '', ...cssText(tail)]; + } + const out: Piece[] = []; + matches(text, /@[\w-]+|[{};]|[^{};@]+/g).forEach(part => { + if (part.startsWith('@')) { + out.push(token('kw', part)); + } else if (/^[{};]$/.test(part)) { + out.push(token('op', part)); + } else { + out.push(part.trim() ? token('fn', part) : part); + } + }); + return out; +} + +function cssValue(value: string): Piece[] { + return matches(value, /#[0-9a-fA-F]{3,8}\b|-?\d*\.?\d+(?:px|%|em|rem|vh|vw|s|ms|deg|fr)?|"[^"]*"|'[^']*'|var\([^)]*\)|[^\s#\d"'(-]+\(?|\s+|./g) + .map(part => /^["']/.test(part) ? token('str', part) : /^(#|-?\d|\.\d)/.test(part) ? token('num', part) + : /^var\(/.test(part) ? token('var', part) : /^\s+$/.test(part) ? part : token('val', part)); +} + +function token(kind: string | null, text: string): Piece { + if (!kind) { + return text; + } + const span = element('span', 'hl-' + kind); + span.textContent = text; + return span; +} + +function shellLine(line: string, state: ShellState): Piece[] { + if (state.quote) { + const close = closingQuote(line, state.quote); + if (close < 0) { + return [token('str', line)]; + } + state.quote = null; + state.command = false; + return [token('str', line.slice(0, close + 1)), ...shellLine(line.slice(close + 1), state)]; + } + if (/^\s*#/.test(line)) { + state.command = true; + return [token('com', line)]; + } + const out: Piece[] = []; + matches(line, /"(?:\\.|[^"\\])*"?|'[^']*'?|\s+|&&|\|\||[|;]|[^\s|;&]+|&/g).forEach(word => { + if (/^\s+$/.test(word)) { + out.push(word); + return; + } + if (/^(&&|\|\||\||;|&)$/.test(word)) { + state.command = true; + out.push(token('op', word)); + return; + } + if (word === '\\') { + out.push(token('op', word)); + return; + } + if (/^["']/.test(word)) { + state.command = false; + if (word.length === 1 || !word.endsWith(word[0])) { + state.quote = word[0]; + } + out.push(token('str', word)); + return; + } + if (state.command && /^[A-Za-z_]\w*=/.test(word)) { + out.push(token('var', word)); + return; + } + const kind = state.command ? 'cmd' : /^--?[A-Za-z]/.test(word) ? 'flag' : /^https?:\/\//.test(word) ? 'str' + : /^\$/.test(word) ? 'var' : /^\d+(\.\d+)?$/.test(word) ? 'num' : null; + state.command = false; + out.push(token(kind, word)); + }); + if (!state.quote && !/\\\s*$/.test(line)) { + state.command = true; + } + return out; +} + +function closingQuote(line: string, quote: string): number { + for (let i = 0; i < line.length; i++) { + if (line[i] === '\\' && quote === '"') { + i++; + } else if (line[i] === quote) { + return i; + } + } + return -1; +} + +function codeLine(lang: string, line: string): Piece[] { + const comment = lang === 'python' ? /^(\s*)(#.*)$/ : /^(\s*)(\/\/.*)$/; + const match = line.match(comment); + if (match) { + return [match[1], token('com', match[2])]; + } + const words = new RegExp('"(?:\\\\.|[^"\\\\])*"?|\'(?:\\\\.|[^\'\\\\])*\'?|`[^`]*`?|' + + (lang === 'python' ? '#.*' : '\\/\\/.*') + '|\\d+(?:\\.\\d+)?|[A-Za-z_$][\\w$]*|\\s+|.', 'g'); + return matches(line, words).map((word, i, all) => { + if (/^(#|\/\/)/.test(word)) { + return token('com', word); + } + if (/^["'`]/.test(word)) { + return token('str', word); + } + if (/^\d/.test(word)) { + return token('num', word); + } + if (/^(true|false|null|undefined|True|False|None)$/.test(word)) { + return token('bool', word); + } + if (KEYWORDS[lang]?.test(word)) { + return token('kw', word); + } + if (/^[A-Za-z_$]/.test(word) && all[i + 1] === '(') { + return token('fn', word); + } + return /^[{}()[\],.:;=]$/.test(word) ? token('op', word) : word; + }); +} + +function jsonLine(line: string): Piece[] { + return matches(line, /"(?:\\.|[^"\\])*"(\s*:)?|-?\d+(?:\.\d+)?|true|false|null|\s+|./g).flatMap(word => { + if (/^".*:$/.test(word.replace(/\s/g, ''))) { + return [token('key', word.replace(/\s*:$/, '')), token('op', word.match(/\s*:$/)[0])]; + } + if (/^"/.test(word)) { + return [token('str', word)]; + } + if (/^-?\d/.test(word)) { + return [token('num', word)]; + } + if (/^(true|false|null)$/.test(word)) { + return [token('bool', word)]; + } + return [/^[{}[\],]$/.test(word) ? token('op', word) : word]; + }); +} + +function yamlValue(value: string): Piece[] { + const match = value.match(/^(\s*)(.*?)(\s+#.*)?$/); + const text = match[2]; + const kind = !text ? null : /^["']/.test(text) ? 'str' : /^(-?\d+(\.\d+)?)$/.test(text) ? 'num' + : /^(true|false|null|yes|no)$/i.test(text) ? 'bool' : /^[|>]-?$/.test(text) ? 'op' : 'val'; + return [match[1], text ? token(kind, text) : '', match[3] ? token('com', match[3]) : null]; +} + +function yamlLine(line: string): Piece[] { + if (/^\s*#/.test(line)) { + return [token('com', line)]; + } + const pair = line.match(/^(\s*)(-\s+)?([\w.\-/]+)(:)(.*)$/); + if (pair) { + return [pair[1], pair[2] ? token('op', pair[2]) : null, token('key', pair[3]), token('op', pair[4]), ...yamlValue(pair[5])]; + } + const item = line.match(/^(\s*)(-\s+)(.*)$/); + return item ? [item[1], token('op', item[2]), ...yamlValue(item[3])] : [line]; +} + +function logLine(line: string): Piece[] { + const match = line.match(/^(.*?\|\s*|\S+\s+\d\d:\d\d:\d\d\S*\s+)?(INFO|WARN(?:ING)?|ERROR|DEBUG)?(.*)$/); + const level = match[2]; + const kind = !level ? null : level === 'INFO' ? 'lvl' : level === 'DEBUG' ? 'com' : /^WARN/.test(level) ? 'warn' : 'err'; + return [match[1] ? token('com', match[1]) : null, level ? token(kind, level) : null, match[3]]; +} + +function matches(line: string, pattern: RegExp): string[] { + return line.match(pattern) ?? []; +} + +const LONG_CELL = 32; + +export function decorateTables(root: HTMLElement): void { + root.querySelectorAll('table td, table th').forEach((cell: HTMLElement) => { + cell.classList.toggle('long', (cell.textContent ?? '').trim().length > LONG_CELL); + }); + root.querySelectorAll('table td:first-child').forEach((cell: HTMLElement) => { + if (cell.firstElementChild?.classList.contains('k-md-lead') && cell.childNodes.length === 1) { + return; + } + const lead = element('span', 'k-md-lead'); + lead.append(...Array.from(cell.childNodes)); + cell.append(lead); + }); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html new file mode 100644 index 0000000000..26b3ad0bd7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html @@ -0,0 +1,46 @@ + +
+ @for (option of question().options; track option.label) { + + } + +
+@if (other()) { +
+ + + + + + + + +
+ @if (wrong()) { + + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts new file mode 100644 index 0000000000..27c16f7082 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input, model, output, signal } from '@angular/core'; +import { AiQuestion } from '@shared/models/solution-creator.models'; +import { aiColorOf, aiHexOf, aiIsFree } from '@home/components/ai/ai-question.models'; + +export function aiColorReady(question: AiQuestion, value: string): boolean { + return question.options.some(option => option.label === value) || !!aiHexOf(value); +} + +export function aiColorAnswer(question: AiQuestion, value: string): string { + return question.options.some(option => option.label === value) ? value : aiHexOf(value) ?? ''; +} + +@Component({ + selector: 'tb-ai-color-field', + templateUrl: './ai-color-field.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiColorFieldComponent { + + question = input.required(); + value = model(''); + enter = output(); + + private elementRef: ElementRef = inject(ElementRef); + + readonly colorOf = aiColorOf; + readonly wrong = signal(false); + readonly other = computed(() => aiIsFree(this.question()) || !this.question().options.some(option => option.label === this.value())); + readonly hex = computed(() => this.other() ? aiHexOf(this.value()) : null); + readonly digits = computed(() => this.value().replace(/^#/, '')); + readonly ready = computed(() => aiColorReady(this.question(), this.value())); + + pick(label: string): void { + this.wrong.set(false); + this.value.set(label); + } + + openHex(): void { + if (!this.other()) { + this.value.set('#'); + } + setTimeout(() => this.elementRef.nativeElement.querySelector('.k-hex-in')?.focus()); + } + + typeHex(field: HTMLInputElement): void { + if (field.value.startsWith('#')) { + field.value = field.value.slice(1); + } + this.value.set('#' + field.value.trim()); + if (aiHexOf(field.value)) { + this.wrong.set(false); + } + } + + checkHex(field: HTMLInputElement): void { + this.wrong.set(!!field.value.trim() && !aiHexOf(field.value)); + } + + hexEnter(event: Event, field: HTMLInputElement): void { + if ((event as KeyboardEvent).isComposing) { + return; + } + event.preventDefault(); + if (aiHexOf(field.value)) { + this.enter.emit(event); + } else { + this.wrong.set(true); + } + } + + openPicker(picker: HTMLInputElement, field: HTMLInputElement): void { + picker.value = aiHexOf(field.value) ?? '#000000'; + try { + picker.showPicker(); + } catch { + picker.click(); + } + } + + pickColor(picker: HTMLInputElement, field: HTMLInputElement): void { + field.value = picker.value.slice(1).toUpperCase(); + this.typeHex(field); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-composer.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai-composer.module.ts new file mode 100644 index 0000000000..6fb56345c0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-composer.module.ts @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { SharedModule } from '@shared/shared.module'; +import { AiCoreModule } from '@home/components/ai/ai-core.module'; +import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; +import { AiCreditsComponent } from '@home/components/ai/ai-credits.component'; +import { AiAttachmentsComponent } from '@home/components/ai/ai-attachments.component'; +import { AiAttachmentPreviewDialogComponent } from '@home/components/ai/ai-attachment-preview-dialog.component'; +import { AiShortcutsDialogComponent } from '@home/components/ai/ai-shortcuts-dialog.component'; + +@NgModule({ + declarations: [ + AiPromptInputComponent, + AiCreditsComponent, + AiAttachmentsComponent, + AiAttachmentPreviewDialogComponent, + AiShortcutsDialogComponent + ], + imports: [ + CommonModule, + SharedModule, + AiCoreModule + ], + exports: [ + AiCoreModule, + AiPromptInputComponent, + AiCreditsComponent, + AiAttachmentsComponent + ] +}) +export class AiComposerModule {} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts new file mode 100644 index 0000000000..3c15a3f45d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { SharedModule } from '@shared/shared.module'; +import { AiAssistantButtonComponent } from '@home/components/ai/ai-assistant-button.component'; +import { AiMarkComponent } from '@home/components/ai/ai-mark.component'; +import { AiSparkComponent } from '@home/components/ai/ai-spark.component'; +import { AiTipDirective } from '@home/components/ai/ai-tip.directive'; +import { AiFadeInImageDirective } from '@home/components/ai/ai-fade-in-image.directive'; +import { AiSpinComponent } from '@home/components/ai/ai-spin.component'; +import { AiSevMarkComponent } from '@home/components/ai/ai-sev-mark.component'; +import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry-modal.component'; +import { AiTipIfCutDirective, AiTooltipChainDirective } from '@home/components/ai/ai-tooltip'; + +@NgModule({ + declarations: [ + AiAssistantButtonComponent, + AiMarkComponent, + AiSparkComponent, + AiTipDirective, + AiFadeInImageDirective, + AiSpinComponent, + AiSevMarkComponent, + AiNoTelemetryModalComponent, + AiTooltipChainDirective, + AiTipIfCutDirective + ], + imports: [ + CommonModule, + SharedModule + ], + exports: [ + AiAssistantButtonComponent, + AiMarkComponent, + AiSparkComponent, + AiTipDirective, + AiFadeInImageDirective, + AiSpinComponent, + AiSevMarkComponent, + AiNoTelemetryModalComponent, + AiTooltipChainDirective, + AiTipIfCutDirective + ] +}) +export class AiCoreModule {} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.html new file mode 100644 index 0000000000..0e0709c24c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.html @@ -0,0 +1,49 @@ + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.scss new file mode 100644 index 0000000000..178025672c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.scss @@ -0,0 +1,155 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + max-width: 760px; + margin: 0 auto 8px; +} + +.k-credits-out { + display: flex; + flex-direction: column; + gap: 12px; + padding: 14px 14px 14px 16px; + border: 1px solid color-mix(in srgb, var(--tb-crit) 18%, transparent); + border-radius: 12px; + background: + linear-gradient(180deg, color-mix(in srgb, var(--tb-crit) 5%, var(--tb-surface, #fff)) 0%, var(--tb-surface, #fff) 100%); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06); + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.k-credits-out-head { + display: flex; + align-items: flex-start; + gap: 12px; +} + +.k-credits-out-mark { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 36px; + height: 36px; + border-radius: 10px; + background: color-mix(in srgb, var(--tb-crit) 10%, transparent); + color: var(--tb-crit); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } +} + +.k-credits-out-text { + display: flex; + flex: 1; + flex-direction: column; + gap: 2px; + min-width: 0; + + b { + font-weight: 500; + font-size: 15px; + line-height: 20px; + } + + span { + font-size: 13.5px; + line-height: 19px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } +} + +.k-credits-out-close.mat-mdc-icon-button.mat-mdc-button-base { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + margin: -4px -4px 0 0; + padding: 0; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } +} + +.k-credits-out-meter { + display: flex; + align-items: center; + gap: 12px; + padding-left: 48px; +} + +.k-credits-out-bar { + flex: 1; + height: 6px; + overflow: hidden; + border-radius: 3px; + background: color-mix(in srgb, var(--tb-crit) 10%, transparent); + + > i { + display: block; + height: 100%; + border-radius: 3px; + background: var(--tb-crit); + } +} + +.k-credits-out-count { + flex: none; + font-size: 13px; + line-height: 18px; + font-variant-numeric: tabular-nums; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.k-credits-out-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 12px; + padding-left: 48px; + + .mdc-button { + height: 32px; + } +} + +.k-credits-out-sent { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13.5px; + line-height: 19px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + color: var(--tb-primary-500); + } +} + +.k-credits-out-failed { + font-size: 13px; + line-height: 18px; + color: var(--tb-crit); +} + +@media (max-width: 599px) { + .k-credits-out-meter, .k-credits-out-actions { + padding-left: 0; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.ts new file mode 100644 index 0000000000..f7327d5df8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.ts @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, NgZone, OnInit, output, signal } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { NotificationService } from '@core/http/notification.service'; +import { ShortNumberPipe } from '@shared/pipe/short-number.pipe'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AiCreditsLimitType, aiCreditsResetDate, watchAiCredits } from '@home/components/ai/ai-credits.models'; + +type RequestState = 'idle' | 'sending' | 'sent' | 'failed'; + +@Component({ + selector: 'tb-ai-credits-out', + templateUrl: './ai-credits-out.component.html', + styleUrls: ['./ai-credits-out.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiCreditsOutComponent implements OnInit { + + limitType = input('TENANT'); + + dismissed = output(); + + private notificationService = inject(NotificationService); + private shortNumber = inject(ShortNumberPipe); + private readonly tenantId = getCurrentAuthUser(inject(Store))?.tenantId; + + readonly used = signal(null); + readonly limit = signal(null); + readonly resetDate = aiCreditsResetDate(); + readonly state = signal('idle'); + + readonly tenantLimit = computed(() => this.limitType() === 'TENANT'); + readonly hasUsage = computed(() => this.tenantLimit() && !!this.limit()); + readonly usedLabel = computed(() => this.shortNumber.transform(this.used() ?? 0, {roundDown: true})); + readonly limitLabel = computed(() => this.shortNumber.transform(this.limit() ?? 0)); + readonly percent = computed(() => { + const limit = this.limit(); + return limit ? Math.min(100, Math.round((this.used() ?? 0) / limit * 100)) : 100; + }); + + constructor() { + const subscriber = watchAiCredits(inject(TelemetryWebsocketService), inject(NgZone), update => { + if (update.count !== undefined) { + this.used.set(update.count); + } + if (update.limit !== undefined) { + this.limit.set(update.limit); + } + }); + inject(DestroyRef).onDestroy(() => subscriber.unsubscribe()); + } + + ngOnInit(): void { + if (this.wasRequested()) { + this.state.set('sent'); + } + } + + request(): void { + if (this.state() === 'sending' || this.state() === 'sent') { + return; + } + this.state.set('sending'); + this.notificationService.sendAiCreditsLimitIncreaseRequest(this.limitType(), {ignoreLoading: true, ignoreErrors: true}).subscribe({ + next: () => { + this.rememberRequested(); + this.state.set('sent'); + }, + error: () => this.state.set('failed') + }); + } + + private requestKey(): string { + return `tb-ai-credits-request:${this.tenantId}:${this.limitType()}`; + } + + private wasRequested(): boolean { + return readStored(this.requestKey()) === String(this.periodStart()); + } + + private rememberRequested(): void { + writeStored(this.requestKey(), String(this.periodStart())); + } + + private periodStart(): number { + const now = new Date(); + return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.html deleted file mode 100644 index 7f6baee9a2..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.html +++ /dev/null @@ -1,21 +0,0 @@ - -
-
- solution-creator.ai-credits - -
-
- -
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss deleted file mode 100644 index 371f0a9ebd..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -:host { - display: block; - - .ai-credits-popup-content { - width: 268px; - } - - .popup-title { - font-size: 16px; - font-weight: 500; - line-height: 24px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.87); - } - - .popup-description { - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - margin: 0; - - strong { - font-weight: 500; - letter-spacing: 0.25px; - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.ts deleted file mode 100644 index 7795ee295c..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.ts +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, Component, inject, output } from '@angular/core'; -import { TbPopoverComponent } from '@shared/components/popover.component'; - -@Component({ - selector: 'tb-ai-credits-popup', - templateUrl: './ai-credits-popup.component.html', - styleUrls: ['./ai-credits-popup.component.scss'], - changeDetection: ChangeDetectionStrategy.OnPush, - standalone: false -}) -export class AiCreditsPopupComponent { - - usedLabel: string; - maxLabel: string; - resetDate: Date; - - updatePlan = output(); - - private popover = inject>(TbPopoverComponent); - - cancel(): void { - this.popover.hide(); - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.html index 3dfde64edb..b5bd700a3c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.html @@ -5,58 +5,26 @@ --> @if (hasData()) { - @if (asButton()) { - - } @else { -
-
- - + + @if (near() || over()) { + {{ over() ? ('ai-assistant.credits.none-left' | translate) : ('ai-assistant.credits.left' | translate: {left: leftLabel(), count: left()}) }} + } + + + + + +
+
+ {{ 'ai-assistant.credits.title' | translate }} + {{ usagePercent() | number: '1.0-0' }}%
- @if (expanded()) { -
- {{ 'solution-creator.ai-credits' | translate }} - {{ usedLabel() }} / {{ maxLabel() }} -
- - } +

{{ 'ai-assistant.credits.used' | translate: {used: usedLabel(), max: maxLabel()} }}

+

{{ 'ai-assistant.credits.resets' | translate: {date: (resetDate() | date: 'MMMM d')} }}

- } +
} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss index 14313bb7c9..3c772e1f21 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss @@ -1,70 +1,94 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 :host { - .ai-credits-donut, - .mat-mdc-icon-button { - --_donut-color: #198038; - --_donut-track: rgba(0, 0, 0, 0.12); - - &.WARNING { - --_donut-color: var(--tb-warning); - --_donut-track: color-mix(in srgb, var(--tb-warning) 20%, transparent); - } - - &.DISABLED { - --_donut-color: var(--tb-crit); - --_donut-track: color-mix(in srgb, var(--tb-crit) 20%, transparent); - } + display: inline-flex; + min-width: 0; +} + +.cred { + display: inline-flex; + align-items: center; + gap: 8px; + min-width: 0; + + > :not(.cred-line) { + flex-shrink: 0; } +} - .ai-credits-donut { - &:hover { - background-color: rgba(0, 0, 0, 0.04); - } - - &:focus-visible { - outline: 2px solid var(--tb-primary-500, #00695c); - outline-offset: 2px; - } - - .donut-spinner { - width: 30px; - } - - .donut-title { - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.76); - } - - .donut-usage { - font-size: 13px; - line-height: 16px; - color: rgba(0, 0, 0, 0.54); - } +.cred-line { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + font: 400 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-76); + white-space: nowrap; +} + +.cred.near .cred-line { + color: var(--tb-caution-text); +} + +.cred-ring { + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 8px; + cursor: default; + transition: background-color .12s ease; + + &:hover, &[aria-describedby] { + background: rgba(0, 0, 0, 0.05); } - .update-btn { - --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.12); - --mat-button-outlined-horizontal-padding: 12px; + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; } -} -:host ::ng-deep .mat-mdc-progress-spinner { - --mat-progress-spinner-active-indicator-color: var(--_donut-color); + svg { + display: block; + width: 20px; + height: 20px; + } + + circle { + fill: none; + stroke-width: 2.5; + } - .mdc-circular-progress__determinate-circle { + .track { + stroke: rgba(0, 0, 0, 0.1); + } + + .arc { + stroke: var(--ai-teal-500); stroke-linecap: round; } +} + +.cred.near .arc { + stroke: var(--tb-caution); +} + +.cred.over .arc { + stroke: var(--tb-crit); +} + +:host-context(.tb-ai-composer.docked) .cred-ring { + width: 28px; + height: 28px; +} + +.tb-ai-tip-body .tip-value { + &.warn { + color: #f2c98a; + } - .mdc-circular-progress__determinate-container::before { - content: ''; - position: absolute; - inset: 0; - border-radius: 50%; - border: 4px solid var(--_donut-track); - box-sizing: border-box; + &.crit { + color: #ff9d92; } } + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.ts index cebcf7bdb6..ec6d4ee89c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.ts @@ -1,28 +1,10 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { - ChangeDetectionStrategy, - Component, - computed, - effect, - inject, - input, - NgZone, - OnDestroy, - Renderer2, - signal, - ViewContainerRef -} from '@angular/core'; -import { Subject } from 'rxjs'; -import { takeUntil } from 'rxjs/operators'; +import { ChangeDetectionStrategy, Component, computed, effect, inject, input, NgZone, OnDestroy, signal } from '@angular/core'; import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; import { TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; -import { AliasFilterType } from '@shared/models/alias.models'; -import { EntityKeyType } from '@shared/models/query/query.models'; +import { aiCreditsResetDate, watchAiCredits } from '@home/components/ai/ai-credits.models'; import { ApiUsageStateValue } from '@shared/models/api-usage.models'; -import { TbPopoverService } from '@shared/components/popover.service'; -import { PopoverPreferredPlacement } from '@shared/components/popover.models'; -import { AiCreditsPopupComponent } from './ai-credits-popup.component'; import { ShortNumberPipe } from '@shared/pipe/short-number.pipe'; @Component({ @@ -34,19 +16,7 @@ import { ShortNumberPipe } from '@shared/pipe/short-number.pipe'; }) export class AiCreditsComponent implements OnDestroy { - expanded = input(false); - asButton = input(false); active = input(true); - popoverPlacement = input(null); - tooltipPosition = input<'above' | 'below' | 'before' | 'after'>(null); - - resolvedTooltipPosition = computed(() => { - return this.tooltipPosition() ?? (this.asButton() ? 'above' : 'after'); - }); - - resolvedPopoverPlacement = computed(() => { - return this.popoverPlacement() ?? (this.asButton() ? 'bottom' : (this.expanded() ? 'top' : 'right')); - }); aiCreditsCount = signal(0); aiCreditsLimit = signal(0); @@ -61,24 +31,29 @@ export class AiCreditsComponent implements OnDestroy { status = computed(() => this.aiApiState() ?? ApiUsageStateValue.ENABLED); + over = computed(() => this.status() === ApiUsageStateValue.DISABLED || this.usagePercent() >= 100); + + near = computed(() => !this.over() && (this.status() === ApiUsageStateValue.WARNING || this.usagePercent() >= 80)); + + arcDash = computed(() => { + const circumference = 2 * Math.PI * 8; + const share = Math.max(this.usagePercent() / 100, this.aiCreditsCount() > 0 ? 0.02 : 0); + return `${(share * circumference).toFixed(2)} ${circumference.toFixed(2)}`; + }); + private shortNumber = inject(ShortNumberPipe); usedLabel = computed(() => this.shortNumber.transform(this.aiCreditsCount(), {roundDown: true})); maxLabel = computed(() => this.shortNumber.transform(this.aiCreditsLimit())); + left = computed(() => Math.max(0, this.aiCreditsLimit() - this.aiCreditsCount())); + leftLabel = computed(() => this.shortNumber.transform(this.left(), {roundDown: true})); - resetDate = computed(() => { - const now = new Date(); - return new Date(now.getFullYear(), now.getMonth() + 1, 2); - }); + resetDate = computed(() => aiCreditsResetDate()); private telemetryWsService = inject(TelemetryWebsocketService); private zone = inject(NgZone); - private popoverService = inject(TbPopoverService); - private renderer = inject(Renderer2); - private viewContainerRef = inject(ViewContainerRef); private telemetrySubscriber: TelemetrySubscriber; - private cancelSubscription$ = new Subject(); private activeEffect = effect(() => { if (this.active()) { @@ -90,83 +65,28 @@ export class AiCreditsComponent implements OnDestroy { ngOnDestroy(): void { this.unsubscribeFromCredits(); - this.cancelSubscription$.complete(); } private unsubscribeFromCredits(): void { - this.cancelSubscription$.next(); if (this.telemetrySubscriber) { this.telemetrySubscriber.unsubscribe(); this.telemetrySubscriber = null; } } - togglePopup(event: Event, trigger: Element): void { - event.stopPropagation(); - if (this.popoverService.hasPopover(trigger)) { - this.popoverService.hidePopover(trigger); - } else { - const popover = this.popoverService.displayPopover({ - trigger, - renderer: this.renderer, - componentType: AiCreditsPopupComponent, - hostView: this.viewContainerRef, - preferredPlacement: this.resolvedPopoverPlacement(), - hideOnClickOutside: true, - showCloseButton: true, - context: { - usedLabel: this.usedLabel(), - maxLabel: this.maxLabel(), - resetDate: this.resetDate() - } - }); - popover.tbComponentRef.instance.updatePlan.subscribe(() => { - this.onUpdatePlan(); - }); - } - } - - onUpdatePlan($event?: Event): void { - $event?.stopPropagation(); - alert('Update plan'); - } - private subscribeToCredits(): void { if (this.telemetrySubscriber) { return; } - const latestKeys = [ - { key: 'aiApiState', type: EntityKeyType.TIME_SERIES }, - { key: 'aiCreditsLimit', type: EntityKeyType.TIME_SERIES }, - { key: 'aiCreditsCount', type: EntityKeyType.TIME_SERIES } - ]; - - this.telemetrySubscriber = TelemetrySubscriber.createEntityFilterLatestSubscription( - this.telemetryWsService, - { type: AliasFilterType.apiUsageState }, - this.zone, - latestKeys - ); - - this.telemetrySubscriber.subscribe(); - this.telemetrySubscriber.entityData$.pipe( - takeUntil(this.cancelSubscription$) - ).subscribe(update => { - const entityData = update.data?.data ?? update.update; - if (entityData?.length) { - const latest = entityData[0].latest; - if (latest?.[EntityKeyType.TIME_SERIES]) { - const ts = latest[EntityKeyType.TIME_SERIES]; - if (ts.aiCreditsCount) { - this.aiCreditsCount.set(Number(ts.aiCreditsCount.value) || 0); - } - if (ts.aiCreditsLimit) { - this.aiCreditsLimit.set(Number(ts.aiCreditsLimit.value) || 0); - } - if (ts.aiApiState) { - this.aiApiState.set(ts.aiApiState.value); - } - } + this.telemetrySubscriber = watchAiCredits(this.telemetryWsService, this.zone, update => { + if (update.count !== undefined) { + this.aiCreditsCount.set(update.count); + } + if (update.limit !== undefined) { + this.aiCreditsLimit.set(update.limit); + } + if (update.state) { + this.aiApiState.set(update.state); } }); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-credits.models.ts new file mode 100644 index 0000000000..60498f56d3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits.models.ts @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { NgZone } from '@angular/core'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AliasFilterType } from '@shared/models/alias.models'; +import { EntityKeyType } from '@shared/models/query/query.models'; + +export type AiCreditsLimitType = 'TENANT' | 'POOL'; + +export interface AiCreditsUpdate { + count?: number; + limit?: number; + state?: string; +} + +export const watchAiCredits = (telemetryWsService: TelemetryWebsocketService, zone: NgZone, + onUpdate: (update: AiCreditsUpdate) => void): TelemetrySubscriber => { + const subscriber = TelemetrySubscriber.createEntityFilterLatestSubscription( + telemetryWsService, + {type: AliasFilterType.apiUsageState}, + zone, + [ + {key: 'aiApiState', type: EntityKeyType.TIME_SERIES}, + {key: 'aiCreditsLimit', type: EntityKeyType.TIME_SERIES}, + {key: 'aiCreditsCount', type: EntityKeyType.TIME_SERIES} + ] + ); + subscriber.entityData$.subscribe(update => { + const entityData = update.data?.data ?? update.update; + const ts = entityData?.[0]?.latest?.[EntityKeyType.TIME_SERIES]; + if (ts) { + onUpdate({ + count: ts.aiCreditsCount ? Number(ts.aiCreditsCount.value) || 0 : undefined, + limit: ts.aiCreditsLimit ? Number(ts.aiCreditsLimit.value) || 0 : undefined, + state: ts.aiApiState?.value + }); + } + }); + subscriber.subscribe(); + return subscriber; +}; + +export const aiCreditsResetDate = (): Date => { + const now = new Date(); + return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)); +}; + +export const aiCreditsLimitOf = (error: any): AiCreditsLimitType | null => { + if (error?.status !== 429) { + return null; + } + let body = error.error; + if (typeof body === 'string') { + try { + body = JSON.parse(body); + } catch { + return null; + } + } + return body?.aiCreditsLimit === 'TENANT' ? 'TENANT' : null; +}; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts index d1e86c90ae..96eb0771b6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts @@ -1,37 +1,30 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { DestroyRef, Injectable } from '@angular/core'; +import { Injectable } from '@angular/core'; import { createDefaultEntityDataPageLink, singleEntityFilterFromDeviceId } from '@shared/models/query/query.models'; -import { AiLoadingModalComponent, AiLoadingModalData } from '@home/components/ai/ai-loading-modal.component'; -import { dashboardGenerateImage, generateDashboardSteps } from '@home/components/ai/ai.models'; -import { finalize } from 'rxjs/operators'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; -import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { map } from 'rxjs/operators'; +import { forkJoin, of } from 'rxjs'; import { AiNoTelemetryModalComponent, AiNoTelemetryModalData } from '@home/components/ai/ai-no-telemetry-modal.component'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { Operation, Resource } from '@shared/models/security.models'; +import { Operation } from '@shared/models/security.models'; import { EntityType } from '@shared/models/entity-type.models'; import { EntityService } from '@core/http/entity.service'; +import { DeviceService } from '@core/http/device.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { MatDialog } from '@angular/material/dialog'; -import { AiChatService } from '@core/http/ai-chat.service'; -import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; -import { DomSanitizer } from '@angular/platform-browser'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { EntityGroupInfo } from '@shared/models/entity-group.models'; interface GenerateDashboardOptions { deviceId: string; - destroyRef?: DestroyRef; - noTelemetry: AiNoTelemetryModalData; - beforeOpen?: () => void; + deviceName?: string; + keys?: string[]; + checkTelemetry?: boolean; + noTelemetry?: AiNoTelemetryModalData; + beforeCompose?: () => void; } interface AllowDashboardGenerateOptions { @@ -45,48 +38,29 @@ interface AllowDashboardGenerateOptions { export class AiDashboardGenerationService { constructor(private entityService: EntityService, + private deviceService: DeviceService, private dialog: MatDialog, - private aiChatService: AiChatService, - private router: Router, + private panelService: AiAssistantPanelService, private translate: TranslateService, - private sanitizer: DomSanitizer, - private store: Store, private userPermissionsService: UserPermissionsService) { } - generateWithTelemetryCheck(opts: GenerateDashboardOptions): void { - this.entityService.findEntityKeysByQueryV2({ + askInChat(opts: GenerateDashboardOptions): void { + const telemetry$ = opts.checkTelemetry === false ? of(true) : this.entityService.findEntityKeysByQueryV2({ entityFilter: singleEntityFilterFromDeviceId(opts.deviceId), pageLink: createDefaultEntityDataPageLink(1), - }, true, false).subscribe((res) => { - opts.beforeOpen?.(); - if (res.timeseries.length) { - this.generate(opts.deviceId, opts.destroyRef); - } else { - this.openNoTelemetryModal(opts.noTelemetry); + }, true, false).pipe(map(res => res.timeseries.length > 0)); + const name$ = opts.deviceName ? of(opts.deviceName) : this.deviceService.getDevice(opts.deviceId, {ignoreLoading: true}).pipe(map(device => device.name)); + forkJoin([telemetry$, name$]).subscribe(([hasTelemetry, name]) => { + if (!hasTelemetry) { + this.openNoTelemetryModal(opts.noTelemetry ?? {}); + return; } - }); - } - - - generate(deviceId: string, destroyRef?: DestroyRef, timeseriesKeys: string[] = []): void { - const dialogRef = this.dialog.open(AiLoadingModalComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - data: { - messages: generateDashboardSteps, - estimateWaitTime: 60000, - image: dashboardGenerateImage - } as AiLoadingModalData - }); - let request$ = this.aiChatService.generateDashboard(deviceId, timeseriesKeys).pipe( - finalize(() => dialogRef.close()) - ); - if (destroyRef) { - request$ = request$.pipe(takeUntilDestroyed(destroyRef)); - } - request$.subscribe({ - next: (response) => this.router.navigate(['/dashboards', response]) + opts.beforeCompose?.(); + const keys = (opts.keys ?? []).filter(Boolean); + this.panelService.compose(keys.length + ? this.translate.instant('ai-assistant.ask.device-dashboard-keys', {name, keys: keys.join(', ')}) + : this.translate.instant('ai-assistant.ask.device-dashboard', {name})); }); } @@ -98,9 +72,7 @@ export class AiDashboardGenerationService { } isAllowedDashboardGenerate(opts: AllowDashboardGenerateOptions = {}): boolean { - const allowed = getCurrentAuthState(this.store).aiEnabled - && getCurrentAuthUser(this.store).authority === Authority.TENANT_ADMIN - && this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.WRITE) + const allowed = this.userPermissionsService.isAiAvailable(Operation.WRITE) && this.userPermissionsService.hasEntityTypeOperationPermission(EntityType.DASHBOARD, Operation.WRITE) && this.userPermissionsService.hasEntityTypeOperationPermission(EntityType.DEVICE, Operation.READ_ATTRIBUTES, opts.entityGroup); if (!opts.requireTelemetry) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html new file mode 100644 index 0000000000..7b65d79e94 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html @@ -0,0 +1,23 @@ + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.ts new file mode 100644 index 0000000000..11f0c2001e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.ts @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, ViewChild } from '@angular/core'; +import { MatCalendar } from '@angular/material/datepicker'; +import { TbPopoverComponent } from '@shared/components/popover.component'; +import { aiReadTime } from '@home/components/ai/ai-question.models'; + +export interface AiPickedDay { + date: Date; + time: string; +} + +@Component({ + selector: 'tb-ai-date-panel', + templateUrl: './ai-date-panel.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiDatePanelComponent implements AfterViewInit { + + @ViewChild(MatCalendar) calendar: MatCalendar; + + selected: Date; + time = '9:00'; + popover: TbPopoverComponent; + + readonly minDate = startOfDay(new Date()); + readonly applied = new EventEmitter(); + timeWrong = false; + + private cd = inject(ChangeDetectorRef); + private host: ElementRef = inject(ElementRef); + + ngAfterViewInit(): void { + setTimeout(() => this.calendar?.focusActiveCell()); + } + + hasFocus(): boolean { + return this.host.nativeElement.contains(document.activeElement); + } + + select(date: Date): void { + this.selected = date; + this.cd.markForCheck(); + } + + typeTime(field: HTMLInputElement): void { + this.time = field.value; + this.timeWrong = false; + } + + settleTime(field: HTMLInputElement): void { + const time = aiReadTime(field.value); + if (time) { + field.value = time; + this.time = time; + } + } + + stepTime(field: HTMLInputElement, minutes: number): void { + const time = aiReadTime(field.value); + if (!time) { + return; + } + const [hours, mins] = time.split(':').map(Number); + const total = (((hours * 60 + mins + minutes) % 1440) + 1440) % 1440; + field.value = `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`; + this.time = field.value; + } + + apply(field: HTMLInputElement): void { + const time = aiReadTime(field.value); + if (!time || !this.selected) { + this.timeWrong = !time; + this.cd.markForCheck(); + field.focus(); + return; + } + this.applied.emit({date: this.selected, time}); + } +} + +function startOfDay(date: Date): Date { + return new Date(date.getFullYear(), date.getMonth(), date.getDate()); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts new file mode 100644 index 0000000000..11e2c8b819 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts @@ -0,0 +1,132 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input, linkedSignal, WritableSignal } from '@angular/core'; + +const STORE = 'tb-ai-disclosure'; + +export function aiDisclosureRemembered(key: string): boolean { + try { + return !!key && JSON.parse(sessionStorage.getItem(STORE) ?? '[]').includes(key); + } catch { + return false; + } +} + +export function aiDisclosureRemember(key: string, open: boolean): void { + if (!key) { + return; + } + try { + const keys: string[] = JSON.parse(sessionStorage.getItem(STORE) ?? '[]').filter((item: string) => item !== key); + if (open) { + keys.push(key); + } + sessionStorage.setItem(STORE, JSON.stringify(keys.slice(-200))); + } catch { + return; + } +} + +export interface AiFold { + readonly open: WritableSignal; + toggle(): boolean; +} + +export function aiFold(key?: () => string): AiFold { + const open = linkedSignal(() => key ? aiDisclosureRemembered(key()) : false); + return { + open, + toggle: () => { + const next = !open(); + open.set(next); + if (key) { + aiDisclosureRemember(key(), next); + } + return next; + } + }; +} + +const REVEAL_GAP = 12; + +function scrollerOf(element: HTMLElement): HTMLElement | null { + for (let node = element.parentElement; node; node = node.parentElement) { + const overflow = getComputedStyle(node).overflowY; + if ((overflow === 'auto' || overflow === 'scroll') && node.scrollHeight > node.clientHeight) { + return node; + } + } + return null; +} + +export function aiRevealOpened(element: HTMLElement): void { + requestAnimationFrame(() => requestAnimationFrame(() => { + const scroller = scrollerOf(element); + if (!scroller) { + return; + } + const box = element.getBoundingClientRect(); + const view = scroller.getBoundingClientRect(); + const composer = scroller.querySelector('.ai-chat-composer') ?? element.closest('.ai-chat')?.querySelector('.ai-chat-composer'); + const composerTop = composer?.getBoundingClientRect().top ?? view.bottom; + const bottom = Math.min(view.bottom, composerTop) - REVEAL_GAP; + const overflow = box.bottom - bottom; + if (overflow <= 0) { + return; + } + const room = box.top - view.top - REVEAL_GAP; + scroller.scrollBy({top: Math.min(overflow, Math.max(room, 0)), behavior: 'smooth'}); + })); +} + +@Component({ + selector: 'tb-ai-disclosure', + template: ` +
+ {{ summary() }} + @if (open()) { + + } +
+ `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'tb-ai-disclosure' + } +}) +export class AiDisclosureComponent { + + summary = input.required(); + + variant = input<'section' | 'divided'>('section'); + + private host = inject(ElementRef); + + private fold = aiFold(); + + open = this.fold.open; + + classes = computed(() => 'tb-disc tb-disc-section' + (this.variant() === 'divided' ? ' tb-disc-divided' : '')); + + toggled(open: boolean): void { + if (open !== this.open() && this.fold.toggle()) { + aiRevealOpened(this.host.nativeElement); + } + } +} + +export function decorateSections(root: HTMLElement, scope: string): void { + root.querySelectorAll('details:not(.tb-disc)').forEach((section, index) => { + const summary = section.querySelector(':scope > summary'); + if (!summary) { + section.insertBefore(Object.assign(document.createElement('summary'), {textContent: '…'}), section.firstChild); + } + section.classList.add('tb-disc', 'tb-disc-section'); + const key = `${scope}:${index}:${section.querySelector(':scope > summary')?.textContent?.trim() ?? ''}`; + if (aiDisclosureRemembered(key)) { + section.open = true; + } + section.addEventListener('toggle', () => aiDisclosureRemember(key, section.open)); + }); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-fade-in-image.directive.ts b/ui-ngx/src/app/modules/home/components/ai/ai-fade-in-image.directive.ts new file mode 100644 index 0000000000..ebb2e86d0a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-fade-in-image.directive.ts @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Directive } from '@angular/core'; + +@Directive({ + selector: 'img[tbAiFadeIn]', + standalone: false, + host: { + class: 'tb-ai-fade-in', + '[class.loaded]': 'loaded', + '(load)': 'loaded = true', + '(error)': 'loaded = true' + } +}) +export class AiFadeInImageDirective { + + loaded = false; + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-file-body.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-file-body.component.ts new file mode 100644 index 0000000000..d184adf89b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-file-body.component.ts @@ -0,0 +1,551 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AfterViewInit, Component, computed, DestroyRef, effect, inject, ElementRef, EventEmitter, input, Output, signal, untracked, ViewChild } from '@angular/core'; +import { MatDialog } from '@angular/material/dialog'; +import { AiFile, aiFileDraftKey, aiImageSrc, downloadAiFile, downloadAiFileAsPng } from '@home/components/ai/ai-file.models'; +import { + AiAttachmentPreviewDialogComponent, + AiAttachmentPreviewDialogData +} from '@home/components/ai/ai-attachment-preview-dialog.component'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { highlightCode } from '@home/components/ai/ai-code-block'; + +export interface AiFileMarks { + from: number; + to: number; +} + +export interface AiFileCaret { + line: number; + col: number; + selected: number; +} + +export type AiFileSaver = (content: string) => Promise; + +const DRAFT_DELAY_MS = 400; +const SAVED_MS = 1600; + +@Component({ + selector: 'tb-ai-file-body', + template: ` + @if (editing()) { +
+ +
+ + +
+
+ } @else if (file().markdown) { +
+ +
+ } @else if (file().image) { +
+ @if (imageBroken()) { +

{{ 'ai-assistant.file.svg-broken' | translate }}

+ } @else { + + } +
+ } @else { + @if (finding()) { + + } +
+ } + `, + standalone: false, + host: {class: 'file-body', '(keydown)': 'onKey($event)'} +}) +export class AiFileBodyComponent implements AfterViewInit { + + file = input.required(); + wrap = input(false); + whitespace = input(false); + marks = input(null); + saver = input(null); + + @Output() marksChange = new EventEmitter(); + @Output() discarded = new EventEmitter(); + + @ViewChild('code') code: ElementRef; + @ViewChild('findInput') findInput: ElementRef; + @ViewChild('area') area: ElementRef; + @ViewChild('layer') layer: ElementRef; + @ViewChild('gutter') gutter: ElementRef; + + private dialog = inject(MatDialog); + private destroyRef = inject(DestroyRef); + + imageSrc = computed(() => aiImageSrc(this.file())); + + imageBroken = signal(false); + + editing = signal(false); + draft = signal(''); + caret = signal({line: 1, col: 1, selected: 0}); + saving = signal(false); + saved = signal(false); + + dirty = computed(() => this.editing() && this.draft() !== this.file().content); + + private shownId: string | null = null; + private draftTimer: ReturnType; + private savedTimer: ReturnType; + + finding = signal(false); + query = signal(''); + matches = signal(0); + current = signal(0); + + private anchor = 0; + + readonly markdownStyles = [ + '.tb-markdown-view {font-size: var(--chat-text); line-height: var(--chat-text-lh); color: var(--tb-ink);} ' + + '.tb-markdown-view > :first-child {margin-top: 0 !important;} ' + + '.tb-markdown-view h1, .tb-markdown-view h2, .tb-markdown-view h3, .tb-markdown-view h4, .tb-markdown-view h5 ' + + '{margin: 28px 0 8px !important; padding: 0 !important; border: 0 !important; font-weight: 500 !important; letter-spacing: -0.1px; color: var(--tb-ink);} ' + + '.tb-markdown-view h1, .tb-markdown-view h2 {font-size: var(--chat-title) !important; line-height: var(--chat-title-lh) !important; letter-spacing: -0.3px;} ' + + '.tb-markdown-view h3 {font-size: var(--chat-head) !important; line-height: var(--chat-head-lh) !important;} ' + + '.tb-markdown-view h4, .tb-markdown-view h5 {font-size: var(--chat-line) !important; line-height: var(--chat-line-lh) !important;} ' + + '.tb-markdown-view p {margin: 0 0 12px !important; padding: 0 !important; font-size: inherit; line-height: inherit;} ' + + '.tb-markdown-view ol, .tb-markdown-view ul {margin: 0 0 12px !important; padding-left: 24px !important; padding-inline-start: 24px;} ' + + '.tb-markdown-view li {font-size: inherit; line-height: inherit;} .tb-markdown-view li + li {margin-top: 4px;} ' + + '.tb-markdown-view div.code-wrapper {padding-left: 0 !important; margin: 0 0 16px !important;} ' + + '.tb-markdown-view pre {border-radius: 10px !important;} ' + + '.tb-markdown-view table, .tb-markdown-view div.code-wrapper {margin-left: 0 !important; margin-right: 0 !important;} ' + + '.tb-markdown-view :not(pre) > code {padding: 1px 5px; border-radius: 4px; background: color-mix(in srgb, var(--tb-ink) 6%, transparent) !important; ' + + 'color: var(--tb-ink) !important; font-family: var(--tb-mono); font-size: var(--chat-code);}' + ]; + + private redraw = effect(() => { + this.file(); + this.whitespace(); + this.editing(); + setTimeout(() => this.drawCode()); + }); + + private follow = effect(() => { + const file = this.file(); + untracked(() => { + if (file.executionId === this.shownId) { + return; + } + this.shownId = file.executionId; + this.imageBroken.set(false); + this.saved.set(false); + const stored = AiFileBodyComponent.storedDraft(file.executionId); + this.editing.set(stored !== null && stored !== file.content); + this.draft.set(stored ?? file.content); + if (this.editing()) { + setTimeout(() => this.drawEditor()); + } + }); + }); + + private relayout = effect(() => { + this.wrap(); + if (untracked(() => this.editing())) { + setTimeout(() => this.drawEditor()); + } + }); + + private remark = effect(() => { + const marks = this.marks(); + setTimeout(() => this.paintMarks(marks)); + }); + + ngAfterViewInit(): void { + this.drawCode(); + this.destroyRef.onDestroy(() => { + clearTimeout(this.draftTimer); + clearTimeout(this.savedTimer); + }); + } + + startEdit(): void { + const file = this.file(); + this.draft.set(AiFileBodyComponent.storedDraft(file.executionId) ?? file.content); + this.editing.set(true); + this.saved.set(false); + this.closeFind(); + setTimeout(() => { + this.drawEditor(); + const area = this.area?.nativeElement; + area?.focus({preventScroll: true}); + area?.setSelectionRange(0, 0); + this.updateCaret(); + }); + } + + done(): void { + this.leaveEditor(); + } + + discard(): void { + const file = this.file(); + this.leaveEditor(); + this.discarded.emit(file); + } + + async save(stay = false): Promise { + const saver = this.saver(); + if (!this.dirty()) { + if (!stay) { + this.leaveEditor(); + } + return; + } + if (!saver || this.saving()) { + return; + } + this.saving.set(true); + const ok = await saver(this.draft()); + this.saving.set(false); + if (!ok) { + return; + } + AiFileBodyComponent.storeDraft(this.file().executionId, null); + if (!stay) { + this.editing.set(false); + } + this.saved.set(true); + clearTimeout(this.savedTimer); + this.savedTimer = setTimeout(() => this.saved.set(false), SAVED_MS); + } + + onEditInput(value: string): void { + this.draft.set(value); + this.drawEditor(); + this.updateCaret(); + clearTimeout(this.draftTimer); + const id = this.file().executionId; + const content = this.file().content; + this.draftTimer = setTimeout(() => AiFileBodyComponent.storeDraft(id, value === content ? null : value), DRAFT_DELAY_MS); + } + + onEditKey(event: KeyboardEvent): void { + const area = event.target as HTMLTextAreaElement; + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') { + event.preventDefault(); + this.save(true); + } else if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + if (!this.dirty()) { + this.leaveEditor(); + } + } else if (event.key === 'Tab' && !event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey) { + event.preventDefault(); + area.setRangeText(' '.repeat(this.file().lang === 'python' ? 4 : 2), area.selectionStart, area.selectionEnd, 'end'); + this.onEditInput(area.value); + } + } + + focusEditor(event: MouseEvent): void { + if (event.target === event.currentTarget || (event.target as HTMLElement).closest('.file-edit-ln')) { + this.area?.nativeElement.focus(); + } + } + + updateCaret(): void { + const area = this.area?.nativeElement; + if (!area) { + return; + } + const before = area.value.slice(0, area.selectionStart); + const line = before.split('\n').length; + const col = area.selectionStart - before.lastIndexOf('\n'); + this.caret.set({line, col, selected: Math.abs(area.selectionEnd - area.selectionStart)}); + this.gutter?.nativeElement.querySelectorAll('li').forEach((item, index) => item.classList.toggle('now', index + 1 === line)); + } + + private leaveEditor(): void { + clearTimeout(this.draftTimer); + AiFileBodyComponent.storeDraft(this.file().executionId, null); + this.draft.set(this.file().content); + this.editing.set(false); + } + + private drawEditor(): void { + const layer = this.layer?.nativeElement; + const gutter = this.gutter?.nativeElement; + const area = this.area?.nativeElement; + if (!layer || !gutter || !area) { + return; + } + const text = this.draft(); + const rows = highlightCode(this.file().lang, text).map(line => { + const row = document.createElement('div'); + row.className = 'file-edit-row'; + row.append(line, '\n'); + return row; + }); + layer.replaceChildren(...rows); + const numbers = rows.map((row, index) => { + const item = document.createElement('li'); + item.textContent = String(index + 1); + return item; + }); + gutter.replaceChildren(...numbers); + if (this.wrap() || this.file().previewed) { + rows.forEach((row, index) => numbers[index].style.height = row.offsetHeight + 'px'); + } + area.style.height = '0px'; + area.style.height = Math.max(area.scrollHeight, layer.offsetHeight) + 'px'; + this.updateCaret(); + } + + private static storedDraft(executionId: string): string | null { + return readStored(aiFileDraftKey(executionId)); + } + + private static storeDraft(executionId: string, value: string | null): void { + writeStored(aiFileDraftKey(executionId), value); + } + + expandImage(): void { + const file = this.file(); + this.dialog.open(AiAttachmentPreviewDialogComponent, { + panelClass: ['tb-dialog', 'tb-ai-attachment-preview-dialog'], + maxWidth: '92vw', + data: {name: file.name, url: this.imageSrc(), vector: true, download: () => downloadAiFile(file), downloadPng: () => downloadAiFileAsPng(file)} + }); + } + + openFind(): void { + this.finding.set(true); + setTimeout(() => { + this.findInput?.nativeElement.focus(); + this.findInput?.nativeElement.select(); + }); + } + + closeFind(): void { + this.finding.set(false); + this.query.set(''); + this.paintFind(); + } + + setQuery(value: string): void { + this.query.set(value); + this.current.set(0); + this.paintFind(); + } + + step(by: number): void { + const count = this.matches(); + if (!count) { + return; + } + this.current.set((this.current() + by + count) % count); + this.focusMatch(); + } + + onFindKey(event: KeyboardEvent): void { + if (event.key === 'Enter') { + event.preventDefault(); + this.step(event.shiftKey ? -1 : 1); + } else if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + this.closeFind(); + } + } + + onKey(event: KeyboardEvent): void { + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'f' && !this.file().previewed && !this.editing()) { + event.preventDefault(); + this.openFind(); + } + } + + onCodeClick(event: MouseEvent): void { + const number = (event.target as HTMLElement).closest('.ln') as HTMLElement | null; + if (!number) { + return; + } + const line = Number(number.dataset.line); + const marks = this.marks(); + if (event.shiftKey && marks) { + this.marksChange.emit({from: Math.min(this.anchor, line), to: Math.max(this.anchor, line)}); + return; + } + if (marks && marks.from === line && marks.to === line) { + this.marksChange.emit(null); + return; + } + this.anchor = line; + this.marksChange.emit({from: line, to: line}); + } + + private drawCode(): void { + const container = this.code?.nativeElement; + if (!container) { + return; + } + const file = this.file(); + const list = document.createElement('ol'); + list.className = 'file-lines'; + highlightCode(file.lang, file.content.replace(/\n$/, '')).forEach((line, index) => { + const item = document.createElement('li'); + const number = document.createElement('button'); + number.type = 'button'; + number.className = 'ln'; + number.tabIndex = -1; + number.dataset.line = String(index + 1); + number.textContent = String(index + 1); + const code = document.createElement('code'); + const indent = /^\s*/.exec(line.textContent ?? '')?.[0].length ?? 0; + code.style.setProperty('--ind', indent + 'ch'); + if (this.whitespace()) { + AiFileBodyComponent.markWhitespace(line); + } + code.append(line); + item.append(number, code); + list.append(item); + }); + container.replaceChildren(list); + this.paintMarks(this.marks()); + this.paintFind(); + } + + private paintMarks(marks: AiFileMarks | null): void { + this.code?.nativeElement.querySelectorAll('.file-lines li').forEach((item, index) => { + item.classList.toggle('marked', !!marks && index + 1 >= marks.from && index + 1 <= marks.to); + }); + } + + private paintFind(): void { + const container = this.code?.nativeElement; + if (!container) { + return; + } + container.querySelectorAll('mark.fm').forEach(mark => mark.replaceWith(...Array.from(mark.childNodes))); + container.normalize(); + const query = this.query(); + let count = 0; + if (query) { + container.querySelectorAll('.file-lines li > code').forEach(code => { + count += AiFileBodyComponent.wrapMatches(code, query.toLowerCase()); + }); + } + this.matches.set(count); + if (this.current() >= count) { + this.current.set(0); + } + this.focusMatch(); + } + + private focusMatch(): void { + const marks = this.code?.nativeElement.querySelectorAll('mark.fm') ?? []; + marks.forEach((mark, index) => mark.classList.toggle('now', index === this.current())); + marks[this.current()]?.scrollIntoView({block: 'nearest', inline: 'nearest'}); + } + + private static wrapMatches(root: HTMLElement, query: string): number { + const text = (root.textContent ?? '').toLowerCase(); + const starts: number[] = []; + for (let at = text.indexOf(query); at >= 0; at = text.indexOf(query, at + query.length)) { + starts.push(at); + } + for (let i = starts.length - 1; i >= 0; i--) { + AiFileBodyComponent.wrapRange(root, starts[i], starts[i] + query.length); + } + return starts.length; + } + + private static wrapRange(root: HTMLElement, from: number, to: number): void { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const pieces: {node: Text; start: number; end: number}[] = []; + let offset = 0; + for (let node = walker.nextNode() as Text | null; node; node = walker.nextNode() as Text | null) { + const length = node.data.length; + const start = Math.max(from, offset); + const end = Math.min(to, offset + length); + if (start < end) { + pieces.push({node, start: start - offset, end: end - offset}); + } + offset += length; + } + pieces.forEach(({node, start, end}) => { + const middle = node.splitText(start); + middle.splitText(end - start); + const mark = document.createElement('mark'); + mark.className = 'fm'; + middle.replaceWith(mark); + mark.append(middle); + }); + } + + private static markWhitespace(line: HTMLElement): void { + const full = line.textContent ?? ''; + const trailFrom = full.replace(/[ \t]+$/, '').length; + const walker = document.createTreeWalker(line, NodeFilter.SHOW_TEXT); + const nodes: Text[] = []; + for (let node = walker.nextNode() as Text | null; node; node = walker.nextNode() as Text | null) { + nodes.push(node); + } + let offset = 0; + nodes.forEach(node => { + const data = node.data; + const fragment = document.createDocumentFragment(); + let plain = ''; + for (let i = 0; i < data.length; i++) { + const char = data[i]; + const at = offset + i; + if (char !== ' ' && char !== '\t') { + plain += char; + continue; + } + if (plain) { + fragment.append(plain); + plain = ''; + } + const span = document.createElement('span'); + span.textContent = char; + const run = (full[at - 1] === ' ' || full[at + 1] === ' ') && char === ' '; + span.className = char === '\t' ? 'ws tab' : at >= trailFrom ? 'ws trail' : run || at < (/^\s*/.exec(full)?.[0].length ?? 0) ? 'ws' : 'ws quiet'; + fragment.append(span); + } + if (plain) { + fragment.append(plain); + } + offset += data.length; + node.replaceWith(fragment); + }); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-file.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-file.models.ts new file mode 100644 index 0000000000..b5cda81c83 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-file.models.ts @@ -0,0 +1,192 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { fileLanguage } from '@home/components/ai/ai-code-block'; +import { AiResourceInfo } from '@shared/models/ai-chat.models'; + +export const WRITE_FILE_TOOL = 'write_file'; +export const CREATE_FILE_TOOL = 'create_file'; +export const FILE_MAKING_TOOLS = new Set([CREATE_FILE_TOOL, 'test_report_template', 'generate_report', 'read_reports']); + +export interface AiMadeFile { + executionId: string; + resource: AiResourceInfo; + label: string; + icon: string; + size: string; + preview: 'image' | null; + download: boolean; +} + +const MADE_KINDS: Record = { + 'image/png': {label: 'PNG', icon: 'image', preview: 'image'}, + 'application/pdf': {label: 'PDF', icon: 'picture_as_pdf', preview: null}, + 'text/csv': {label: 'CSV', icon: 'table_chart', preview: null}, + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': {label: 'Word', icon: 'description', preview: null}, + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': {label: 'Excel', icon: 'table_chart', preview: null} +}; + +export function aiMadeFileOf(executionId: string, result: unknown): AiMadeFile | null { + let parsed: unknown = result; + if (typeof result === 'string') { + const text = /^OK: [^\n]*\n/.test(result) ? result.slice(result.indexOf('\n') + 1) : result; + try { + parsed = JSON.parse(text); + } catch { + return null; + } + } + const file = (parsed as {file?: Partial})?.file; + const download = (parsed as {download?: unknown})?.download === true; + if (!file || typeof file.id !== 'string' || typeof file.name !== 'string' || typeof file.mediaType !== 'string') { + return null; + } + const kind = MADE_KINDS[file.mediaType] ?? {label: file.name.split('.').pop()?.toUpperCase() ?? 'File', icon: 'draft', preview: null}; + const bytes = typeof file.size === 'number' ? file.size : 0; + return { + executionId, + resource: {id: file.id, name: file.name, mediaType: file.mediaType, size: bytes}, + label: kind.label, + icon: kind.icon, + size: formatSize(bytes), + preview: kind.preview, + download + }; +} + +function formatSize(bytes: number): string { + return bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`; +} + +export interface AiFile { + executionId: string; + name: string; + content: string; + summary?: string; + lang: string; + label: string; + icon: string; + lines: number; + size: string; + markdown: boolean; + image: boolean; + previewed: boolean; + edited: boolean; +} + +export interface AiFileName { + base: string; + ext: string; +} + +const MARKS: Record = {JSON: 'data_object', YAML: 'data_object', TOML: 'data_object', XML: 'data_object', Markdown: 'article', SVG: 'image', Text: 'description', CSV: 'table_chart'}; + +export function aiFileName(name: string): AiFileName { + const found = /^(.+?)(\.[A-Za-z0-9]{1,8})$/.exec(name); + return found ? {base: found[1], ext: found[2]} : {base: name, ext: ''}; +} + +export function aiFileMark(file: AiFile): string { + return MARKS[file.label] ?? (file.lang === 'text' ? 'description' : 'code'); +} + +export function aiFileDraftKey(executionId: string): string { + return 'tbAiFileDraft:' + executionId; +} + +const PNG_SCALE = 2; +const PNG_MAX_SIDE = 4096; + +const XML_ENTITIES = new Set(['amp', 'lt', 'gt', 'quot', 'apos']); + +export function aiImageSrc(file: AiFile): string { + return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xmlEntities(file.content)); +} + +function xmlEntities(svg: string): string { + const decoder = document.createElement('textarea'); + return svg.replace(/&([a-zA-Z][a-zA-Z0-9]*);/g, (entity, name: string) => { + if (XML_ENTITIES.has(name)) { + return entity; + } + decoder.innerHTML = entity; + const text = decoder.value; + return text === entity ? '&' + name + ';' : Array.from(text).map(char => `&#${char.codePointAt(0)};`).join(''); + }); +} + +export function downloadAiFile(file: AiFile): void { + save(new Blob([file.content], {type: file.image ? 'image/svg+xml' : 'text/plain;charset=utf-8'}), file.name); +} + +export function downloadAiFileAsPng(file: AiFile): Promise { + return new Promise((resolve, reject) => { + const image = new Image(); + image.onload = () => { + const size = svgSize(file.content) ?? {width: image.naturalWidth || 800, height: image.naturalHeight || 400}; + const scale = Math.min(PNG_SCALE, PNG_MAX_SIDE / Math.max(size.width, size.height)); + const canvas = document.createElement('canvas'); + canvas.width = Math.max(1, Math.round(size.width * scale)); + canvas.height = Math.max(1, Math.round(size.height * scale)); + canvas.getContext('2d').drawImage(image, 0, 0, canvas.width, canvas.height); + canvas.toBlob(blob => { + if (blob) { + save(blob, file.name.replace(/\.svg$/i, '') + '.png'); + resolve(); + } else { + reject(new Error('PNG export failed')); + } + }, 'image/png'); + }; + image.onerror = () => reject(new Error('The image could not be drawn')); + image.src = aiImageSrc(file); + }); +} + +function svgSize(svg: string): {width: number; height: number} | null { + const root = new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement; + if (root?.nodeName.toLowerCase() !== 'svg') { + return null; + } + const width = parseFloat(root.getAttribute('width') ?? ''); + const height = parseFloat(root.getAttribute('height') ?? ''); + if (width > 0 && height > 0 && !/%/.test(root.getAttribute('width') + root.getAttribute('height'))) { + return {width, height}; + } + const box = (root.getAttribute('viewBox') ?? '').trim().split(/[\s,]+/).map(Number); + return box.length === 4 && box[2] > 0 && box[3] > 0 ? {width: box[2], height: box[3]} : null; +} + +function save(blob: Blob, name: string): void { + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = name; + link.click(); + setTimeout(() => URL.revokeObjectURL(url)); +} + +export function aiFileOf(executionId: string, args: unknown, edited = false): AiFile | null { + const values = (args ?? {}) as {name?: unknown; content?: unknown; summary?: unknown}; + if (typeof values.name !== 'string' || !values.name.trim() || typeof values.content !== 'string') { + return null; + } + const name = values.name.trim(); + const language = fileLanguage(name); + const content = values.content; + const bytes = new TextEncoder().encode(content).length; + return { + executionId, + name, + content, + summary: typeof values.summary === 'string' ? values.summary : undefined, + lang: language.lang, + label: language.label, + icon: language.icon, + lines: content.replace(/\n$/, '').split('\n').length, + size: bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`, + markdown: language.label === 'Markdown', + image: language.label === 'SVG', + previewed: language.label === 'Markdown' || language.label === 'SVG', + edited + }; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html new file mode 100644 index 0000000000..31aebbd8c5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html @@ -0,0 +1,197 @@ + +
+ @if (folded()) { + +

{{ arrivedLine() }}

+ } @else { +
+ {{ 'ai-assistant.hand-over.needs-you' | translate }} + {{ handOver().title }} +
+ @if (arrived()) { + + } @else if (time()) { + + } +
+ @if (handOver().text) { + + } + @if (handOver().choice; as choice) { +
+
+ + {{ choice.question }} + + @for (option of choice.options; track option.id) { + + } + +
+ @if (choiceText()) { +
+ } +
+ } + @if (steps().length) { +
    + @for (step of steps(); track step; let i = $index) { +
  1. + + @if (step.file && files().get(step.file); as file) { + + } + @if (step.values.length || step.markdown) { +
    +
    + @for (value of step.values; track $index; let v = $index) { +
    + + {{ value.label }} + {{ value.secret && !shown().has(i + '-' + v) ? masked(value.value) : value.value }} + @if (value.secret) { + + } + +
    + } +
    + @if (step.markdown) { + + } +
    + } +
  2. + } +
+ } + @if (!handOver().waitFor && handOver().test; as test) { + + @if (test.hint) { +

{{ test.hint }}

+ } +
+
+ } + @if (stopped()) { +
+
+ + {{ (undecoded() ? 'ai-assistant.hand-over.not-decoded' : 'ai-assistant.hand-over.stopped-at') | translate: {time: stoppedAt()} }} + @if (canListenAgain()) { + + + + } +
+
+ } @else if (quiet()) { +
+
+ + {{ (undecoded() ? 'ai-assistant.hand-over.not-decoded' : 'ai-assistant.hand-over.nothing-heard') | translate: {minutes: quietMinutes()} }} + {{ clock() }} + + + +
+
+ @if (canSendTest()) { + + } + + @if (handOver().paste; as paste) { + + } @else { + + } +
+ @if (handOver().test; as test) { + + @if (test.hint) { +

{{ test.hint }}

+ } +
+
+ } +
+ } @else if (waiting()) { +
+
+ + {{ waitLabel() }} + {{ clock() }} + + + +
+ @if (canSendTest()) { +
+ +
+ } +
+ } + @if (testNote(); as note) { +
+ + {{ note }} +
+ } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts new file mode 100644 index 0000000000..1b6dd6f36d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts @@ -0,0 +1,330 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AfterViewChecked, Component, computed, DestroyRef, effect, ElementRef, EventEmitter, inject, input, NgZone, Output, signal, untracked } from '@angular/core'; +import { AiFile, aiFileMark, aiFileName } from '@home/components/ai/ai-file.models'; +import { aiFold, aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; +import { Clipboard } from '@angular/cdk/clipboard'; +import { TranslateService } from '@ngx-translate/core'; +import { AiConnectionCheck, AiHandOver } from '@home/components/ai/ai-action.models'; +import { aiFenceMeta, announceCopied, codeTabGroup, codeTabsBlock, decorateCodeBlocks } from '@home/components/ai/ai-code-block'; + +export interface AiHandOverWait { + running: boolean; + startedAt: number; + progress?: string; + endedAt?: number; + check?: AiConnectionCheck | null; +} + +const MIN_SILENCE_MS = 120000; +const MAX_SILENCE_MS = 300000; +const TEST_MARKER = 'aiTestValue'; +const OS_LABELS: Record = {macos: 'macOS', windows: 'Windows', linux: 'Linux'}; + +function localOs(): string { + const platform = navigator.userAgent; + return /Windows/i.test(platform) ? 'windows' : /Mac/i.test(platform) ? 'macos' : 'linux'; +} +const COPIED_MS = 1500; +const PROGRESS_KEY = 'tb.ai.handOver.'; +const PROGRESS_INDEX = 'tb.ai.handOvers'; +const MAX_SAVED_PROGRESS = 50; + +export interface AiHandOverProgress { + title: string; + choice?: string; + ticks: number[]; + ticked: string[]; + steps: number; +} + +export function aiHandOverProgress(cardId: string): AiHandOverProgress | null { + if (!cardId) { + return null; + } + try { + const saved = readStored(PROGRESS_KEY + cardId); + return saved ? JSON.parse(saved) as AiHandOverProgress : null; + } catch { + return null; + } +} + +function aiSaveHandOverProgress(cardId: string, progress: AiHandOverProgress): void { + if (!cardId) { + return; + } + writeStored(PROGRESS_KEY + cardId, JSON.stringify(progress)); + let saved: string[] = []; + try { + saved = JSON.parse(readStored(PROGRESS_INDEX) ?? '[]'); + } catch { + saved = []; + } + const kept = [...saved.filter(id => id !== cardId), cardId]; + kept.slice(0, Math.max(0, kept.length - MAX_SAVED_PROGRESS)).forEach(id => writeStored(PROGRESS_KEY + id, null)); + writeStored(PROGRESS_INDEX, JSON.stringify(kept.slice(-MAX_SAVED_PROGRESS))); +} + +@Component({ + selector: 'tb-ai-hand-over', + templateUrl: './ai-hand-over.component.html', + standalone: false +}) +export class AiHandOverComponent implements AfterViewChecked { + + handOver = input.required(); + wait = input(null); + time = input(0); + files = input>(new Map()); + cardId = input(''); + testRequest = input(0); + + private handledTest = 0; + + private testRequested = effect(() => { + const request = this.testRequest(); + if (request > this.handledTest) { + this.handledTest = request; + untracked(() => this.sendTest()); + } + }); + canListenAgain = input(false); + + @Output() prompt = new EventEmitter(); + + @Output() stop = new EventEmitter(); + @Output() compose = new EventEmitter(); + @Output() openFile = new EventEmitter(); + @Output() listenAgain = new EventEmitter(); + + readonly fileMark = aiFileMark; + readonly fileName = aiFileName; + + private host = inject(ElementRef); + private translate = inject(TranslateService); + private clipboard = inject(Clipboard); + + readonly picked = signal(null); + readonly ticked = signal>(new Set()); + readonly shown = signal>(new Set()); + readonly copied = signal(null); + readonly now = signal(Date.now()); + private readonly fold = aiFold(); + + readonly open = this.fold.open; + readonly testState = signal<'idle' | 'sending' | 'sent' | 'failed'>('idle'); + readonly testAt = signal(0); + readonly testError = signal(''); + readonly lastTickAt = signal(0); + + readonly choiceValue = computed(() => this.picked() ?? this.handOver().choice?.value ?? null); + readonly steps = computed(() => { + const picked = this.handOver().choice?.options.find(option => option.id === this.choiceValue()); + return picked?.steps?.length ? picked.steps : this.handOver().steps; + }); + readonly choiceText = computed(() => this.handOver().choice?.options.find(option => option.id === this.choiceValue())?.text ?? ''); + + readonly arrived = computed(() => this.wait()?.check?.dataArriving === true); + readonly folded = computed(() => this.arrived() && !this.open()); + readonly arrivedLine = computed(() => { + const wait = this.wait(); + const at = wait?.endedAt ? new Date(wait.endedAt).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}) : ''; + return this.translate.instant('ai-assistant.hand-over.arrived-' + (this.handOver().waitFor ?? 'message'), {time: at}); + }); + + readonly waiting = computed(() => !!this.wait()?.running); + readonly canSendTest = computed(() => !!this.handOver().test?.sample && this.handOver().waitFor === 'message'); + readonly testNote = computed(() => { + const time = new Date(this.testAt()).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}); + switch (this.testState()) { + case 'sent': + return this.translate.instant('ai-assistant.hand-over.test-sent', {time}); + case 'failed': + return this.translate.instant('ai-assistant.hand-over.test-failed', {error: this.testError()}); + default: + return ''; + } + }); + readonly elapsed = computed(() => Math.max(0, this.now() - (this.wait()?.startedAt ?? this.now()))); + readonly clock = computed(() => { + const seconds = Math.floor(this.elapsed() / 1000); + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; + }); + readonly silenceMs = computed(() => Math.min(MAX_SILENCE_MS, + Math.max(MIN_SILENCE_MS, 2 * 1000 * (this.handOver().waitFor === 'gateway' ? 0 : this.handOver().intervalSeconds ?? 0)))); + readonly silent = computed(() => Math.max(0, this.now() - Math.max(this.wait()?.startedAt ?? this.now(), this.lastTickAt()))); + readonly quiet = computed(() => this.waiting() && this.silent() >= this.silenceMs()); + readonly quietMinutes = computed(() => Math.max(2, Math.floor(this.silent() / 60000))); + readonly undecoded = computed(() => this.wait()?.check?.failedStep === 'decoded'); + readonly stopped = computed(() => { + const wait = this.wait(); + return !!wait && !wait.running && !!wait.check && !wait.check.dataArriving; + }); + readonly stoppedAt = computed(() => { + const at = this.wait()?.endedAt; + return at ? new Date(at).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}) : ''; + }); + + constructor() { + const zone = inject(NgZone); + let timer: ReturnType | null = null; + const stopTimer = () => { + if (timer) { + clearInterval(timer); + timer = null; + } + }; + effect(() => { + if (this.waiting()) { + untracked(() => this.now.set(Date.now())); + if (!timer) { + timer = zone.runOutsideAngular(() => setInterval(() => this.now.set(Date.now()), 1000)); + } + } else { + stopTimer(); + } + }); + inject(DestroyRef).onDestroy(stopTimer); + effect(() => { + const saved = aiHandOverProgress(this.cardId()); + untracked(() => { + if (saved?.choice) { + this.picked.set(saved.choice); + } + this.ticked.set(new Set(saved?.ticks ?? [])); + }); + }); + effect(() => { + this.choiceText(); + this.steps(); + this.handOver(); + this.folded(); + setTimeout(() => this.decorate()); + }); + } + + md(text: string): string { + return aiFenceMeta(text); + } + + ngAfterViewChecked(): void { + if ((this.host.nativeElement as HTMLElement).querySelector('.k-test-slot:empty')) { + this.decorate(); + } + } + + decorate(): void { + const root = this.host.nativeElement as HTMLElement; + const test = this.handOver().test; + root.querySelectorAll('.k-test-slot:empty').forEach(slot => { + if (!test) { + return; + } + const order = ['macos', 'windows', 'linux']; + const tabs = [...test.commands].sort((a, b) => order.indexOf(a.os) - order.indexOf(b.os)).map(command => ({id: command.os, label: OS_LABELS[command.os], text: command.command, + lang: command.os === 'windows' ? 'powershell' : 'shell'})); + const preferred = codeTabGroup('os') ?? localOs(); + const initial = Math.max(0, tabs.findIndex(tab => tab.id === preferred)); + slot.append(codeTabsBlock(tabs, 'shell', this.translate, text => this.clipboard.copy(text), initial, undefined, {group: 'os'})); + }); + decorateCodeBlocks(root, this.translate, text => this.clipboard.copy(text)); + } + + waitLabel(): string { + return this.translate.instant('ai-assistant.hand-over.wait-' + (this.handOver().waitFor ?? 'message')); + } + + pick(id: string): void { + this.picked.set(id); + this.ticked.set(new Set()); + this.saveProgress(); + } + + tick(index: number): void { + const next = new Set(this.ticked()); + if (next.has(index)) { + next.delete(index); + } else { + next.add(index); + } + this.ticked.set(next); + this.lastTickAt.set(Date.now()); + this.saveProgress(); + } + + private saveProgress(): void { + const steps = this.steps(); + aiSaveHandOverProgress(this.cardId(), { + title: this.handOver().title, + choice: this.picked() ?? undefined, + ticks: [...this.ticked()], + ticked: steps.filter((_, index) => this.done(index)).map(step => step.title), + steps: steps.length + }); + } + + done(index: number): boolean { + return this.ticked().has(index) !== (this.steps()[index]?.done === true); + } + + reveal(key: string): void { + const next = new Set(this.shown()); + if (next.has(key)) { + next.delete(key); + } else { + next.add(key); + } + this.shown.set(next); + } + + masked(value: string): string { + return value.length > 8 ? value.slice(0, 4) + '••••••••' + value.slice(-4) : '••••••••'; + } + + copy(key: string, value: string): void { + if (this.clipboard.copy(value)) { + this.copied.set(key); + announceCopied(this.translate.instant('ai-assistant.copied')); + setTimeout(() => this.copied.set(null), COPIED_MS); + } + } + + async sendTest(): Promise { + const test = this.handOver().test; + if (!test?.sample || !test.accessToken || this.testState() === 'sending') { + return; + } + this.testState.set('sending'); + const ts = Date.now(); + try { + const response = await fetch(`/api/v1/${encodeURIComponent(test.accessToken)}/telemetry`, { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ts, values: {...test.sample, [TEST_MARKER]: true}}) + }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}`); + } + this.testAt.set(ts); + this.testState.set('sent'); + } catch (error) { + this.testError.set(error instanceof Error ? error.message : String(error)); + this.testState.set('failed'); + } + } + + unfold(): void { + this.open.set(true); + aiRevealOpened(this.host.nativeElement); + } + + startPaste(intro: string): void { + this.compose.emit(intro + '\n'); + } + + say(key: string): void { + this.prompt.emit(this.translate.instant(key)); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html new file mode 100644 index 0000000000..0ea48ad67d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html @@ -0,0 +1,31 @@ + +@let current = view(); +
+ + {{ noticeText() }} + @switch (current.action) { + @case ('request') { + @if (state() === 'sent') { + {{ 'ai-assistant.limit-out.sent' | translate }} + } @else { + + } + } + @case ('license') { + {{ 'ai-assistant.limit-out.manage-license' | translate }} + } + @case ('pricing') { + {{ 'subscription.upgrade-plan' | translate }} + } + } + +
+@if (state() === 'failed') { +

{{ 'ai-assistant.limit-out.failed' | translate }}

+} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts new file mode 100644 index 0000000000..b6878ea0f0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts @@ -0,0 +1,170 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiLocale } from '@home/components/ai/ai-text'; +import { ChangeDetectionStrategy, Component, computed, effect, inject, input, output, signal } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { TranslateService } from '@ngx-translate/core'; +import { Observable } from 'rxjs'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { NotificationService } from '@core/http/notification.service'; +import { Authority } from '@shared/models/authority.enum'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { AddonType, SubscriptionEntry, subscriptionEntryToEntityType } from '@shared/models/subscription.models'; +import { writeStored } from '@core/local-storage/stored'; +import { AiPlatformLimit } from '@shared/models/ai-chat.models'; + +type RequestState = 'idle' | 'sending' | 'sent' | 'failed'; + +type LimitAction = 'request' | 'license' | 'pricing' | 'none'; + +interface LimitView { + icon: string; + title: string; + action: LimitAction; + requestLabel?: string; + storageKey: string; + send?: () => Observable; +} + +const PRICING_URL = 'https://thingsboard.io/pricing/'; +const WL_REQUESTED_STORAGE_KEY = 'wlRequested'; +const PE_PACK_REQUESTED_STORAGE_KEY = 'pePackRequested'; +const FEATURE_KEYS: Record = { + [SubscriptionEntry.WHITE_LABELING]: 'white-labeling', + INTEGRATIONS: 'integrations', + SCHEDULER: 'scheduler', + REPORTING: 'reporting' +}; + +@Component({ + selector: 'tb-ai-limit-out', + templateUrl: './ai-limit-out.component.html', + styleUrls: ['./ai-credits-out.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiLimitOutComponent { + + platformLimit = input.required(); + + dismissed = output(); + + private notificationService = inject(NotificationService); + private translate = inject(TranslateService); + private readonly store = inject(Store); + private readonly user = getCurrentAuthUser(this.store); + private readonly authState = getCurrentAuthState(this.store); + + readonly pricingUrl = PRICING_URL; + readonly state = signal('idle'); + readonly view = computed(() => this.viewOf(this.platformLimit())); + readonly noticeText = computed(() => { + const limit = this.platformLimit(); + const title = this.view().title; + return limit.limit ? this.say('notice-count', {title, limit: this.count(limit.limit)}) : this.say('notice', {title}); + }); + + constructor() { + effect(() => this.state.set(this.wasRequested(this.view().storageKey) ? 'sent' : 'idle')); + } + + request(): void { + const send = this.view().send; + if (!send || this.state() === 'sending' || this.state() === 'sent') { + return; + } + this.state.set('sending'); + send().subscribe({ + next: () => { + this.rememberRequested(this.view().storageKey); + this.state.set('sent'); + }, + error: () => this.state.set('failed') + }); + } + + private count(value: number): string { + return value.toLocaleString(aiLocale(this.translate.currentLang)); + } + + private viewOf(limit: AiPlatformLimit): LimitView { + const sysAdmin = this.user?.authority === Authority.SYS_ADMIN; + const oldLicense = !(this.authState?.licenseVersion > 1); + const config = {ignoreLoading: true, ignoreErrors: true}; + if (limit.errorCode === 41 && limit.entityType) { + const entityType = limit.entityType; + return { + icon: 'data_usage', + title: this.say('entity-title', {entities: this.entities(entityType)}), + action: 'request', + requestLabel: 'ai-assistant.limit-out.request', + storageKey: `tb-entity-limit-request:${this.user?.tenantId}:${entityType}:${limit.limit}`, + send: () => this.notificationService.sendEntitiesLimitIncreaseRequest(entityType, false, config) + }; + } + const entry = limit.subscriptionEntry as SubscriptionEntry; + const licensedType = subscriptionEntryToEntityType.get(entry); + if (limit.subscriptionErrorCode === 'LIMIT_REACHED' && licensedType) { + return { + icon: 'data_usage', + title: this.say('entity-title', {entities: this.entities(licensedType)}), + action: oldLicense ? 'pricing' : (sysAdmin ? 'license' : 'request'), + requestLabel: 'ai-assistant.limit-out.request', + storageKey: `tb-entity-limit-request:${this.user?.tenantId}:${licensedType}:license`, + send: () => this.notificationService.sendEntitiesLimitIncreaseRequest(licensedType, true, config) + }; + } + const featureKey = FEATURE_KEYS[limit.subscriptionEntry ?? '']; + if (limit.subscriptionErrorCode === 'FEATURE_DISABLED' && featureKey) { + const whiteLabeling = entry === SubscriptionEntry.WHITE_LABELING; + const grant = !!this.authState?.communityGrantLicense; + const addon = whiteLabeling && !grant ? AddonType.WHITE_LABELING : AddonType.PROFESSIONAL_UPGRADE; + return { + icon: whiteLabeling ? 'palette' : 'lock', + title: grant + ? this.translate.instant(`platform-feature.${featureKey}.not-in-ce-grant`) + : (whiteLabeling ? this.translate.instant('platform-feature.white-labeling.not-in-plan') + : this.say('feature-title', {feature: this.say(`feature.${featureKey}`)})), + action: sysAdmin ? 'license' : (oldLicense && !grant ? 'pricing' : 'request'), + requestLabel: 'subscription.request-access', + storageKey: addon === AddonType.WHITE_LABELING ? WL_REQUESTED_STORAGE_KEY : PE_PACK_REQUESTED_STORAGE_KEY, + send: () => this.notificationService.sendAddonAccessRequest(addon, config) + }; + } + return { + icon: 'lock', + title: this.say('license-required'), + action: sysAdmin ? 'license' : 'none', + storageKey: '' + }; + } + + private entities(entityType: EntityType): string { + const translations = entityTypeTranslations.get(entityType); + return translations ? this.translate.instant(translations.typePlural) as string : entityType; + } + + private say(key: string, params?: object): string { + return this.translate.instant('ai-assistant.limit-out.' + key, params); + } + + private wasRequested(key: string): boolean { + if (!key) { + return false; + } + try { + const stored = localStorage.getItem(key); + return stored === 'sent' || stored === 'true'; + } catch { + return false; + } + } + + private rememberRequested(key: string): void { + if (!key) { + return; + } + writeStored(key, key === WL_REQUESTED_STORAGE_KEY || key === PE_PACK_REQUESTED_STORAGE_KEY ? JSON.stringify(true) : 'sent'); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-load-lines.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-load-lines.component.ts new file mode 100644 index 0000000000..79fc471864 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-load-lines.component.ts @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; + +const ROLL_MS = 720; + +@Component({ + selector: 'tb-ai-load-lines', + template: ` + {{ current() }} + + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'art-load-lines' + } +}) +export class AiLoadLinesComponent { + + line = input(''); + lines = input([]); + + current = signal(''); + previous = signal(null); + + private timer: ReturnType; + + constructor() { + effect(() => { + const text = this.line() ?? ''; + untracked(() => this.show(text)); + }); + inject(DestroyRef).onDestroy(() => clearTimeout(this.timer)); + } + + private show(text: string): void { + const now = this.current(); + if (text === now) { + return; + } + clearTimeout(this.timer); + this.previous.set(now || null); + this.current.set(text); + if (now) { + this.timer = setTimeout(() => this.previous.set(null), ROLL_MS); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.html deleted file mode 100644 index 59a00e96d0..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.html +++ /dev/null @@ -1,15 +0,0 @@ - -
-
- Loading -
- {{ statusMessage | translate }} - {{ 'solution-creator.estimate-wait-time' | translate: {time: (data.estimateWaitTime | milliSecondsToTimeString:true : true)} }} -
-
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.scss deleted file mode 100644 index 7af33d5f19..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.scss +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -.ai-backdrop-filter { - background: rgba(255, 255, 255, .01); - backdrop-filter: blur(8px); -} - -.tb-generated { - z-index: 3; - .panel { - box-shadow: 0 6px 12px 0 rgba(0, 0, 0, 0.04), 0 12px 32px 0 rgba(0, 0, 0, 0.08); - background-color: #fff; - width: 500px; - } - img { - width: 200px; - } - .info { - white-space: pre-line; - text-align: center; - line-height: 1.5; - letter-spacing: 0.15px; - } - - .msg.text-changed { - animation: fadeInSlideUp 0.5s ease-out forwards; - } - - @keyframes fadeInSlideUp { - 0% { - opacity: 0; - transform: translateY(15px); - } - 100% { - opacity: 1; - transform: translateY(0); - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.ts deleted file mode 100644 index 3ab1c957eb..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.ts +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, DestroyRef, Inject, OnInit, ViewEncapsulation } from '@angular/core'; -import { DialogComponent } from '@shared/components/dialog.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { Router } from '@angular/router'; -import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; -import { from, of } from 'rxjs'; -import { concatMap, delay } from 'rxjs/operators'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { generatedStateImages } from '@home/components/ai/ai.models'; - -export interface AiLoadingModalData { - messages: Array<{text: string; delay: number}>; - estimateWaitTime: number; - image?: string; -} - -@Component({ - selector: 'tb-ai-loading-modal', - templateUrl: './ai-loading-modal.component.html', - styleUrl: './ai-loading-modal.component.scss', - encapsulation: ViewEncapsulation.None, - standalone: false, - host: { - style: 'width: 100%; height: 100%; min-height: 100%; display: flex; overflow: hidden;' - } -}) -export class AiLoadingModalComponent extends DialogComponent implements OnInit { - - generateImage: string = generatedStateImages[Math.floor(Math.random() * generatedStateImages.length)]; - statusMessage: string = ''; - statusMessageChanged = false; - - constructor(protected store: Store, - protected router: Router, - @Inject(MAT_DIALOG_DATA) public data: AiLoadingModalData, - public dialogRef: MatDialogRef, - private destroyRef: DestroyRef) { - super(store, router, dialogRef); - } - - ngOnInit() { - this.initGenerateState(); - } - - private initGenerateState(): void { - from(this.data.messages).pipe( - concatMap(message => of(message).pipe(delay(message.delay))), - takeUntilDestroyed(this.destroyRef) - ).subscribe((msg) => { - this.statusMessageChanged = true; - this.statusMessage = msg.text; - setTimeout(() => { - this.statusMessageChanged = false; - }, 500); - }); - } - -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-mark.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-mark.component.ts new file mode 100644 index 0000000000..6a24e78074 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-mark.component.ts @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, ElementRef, inject, input, numberAttribute, booleanAttribute } from '@angular/core'; + +export type AiMarkCue = 'needs' | 'error'; + +const MARK_CYCLE_MS = 16000; +const LARGE_MARK = 44; + +@Component({ + selector: 'tb-ai-mark, button[tb-ai-mark]', + template: ` + + @if (icon()) { + {{ icon() }} + } @else if (large()) { + + } @else { + auto_awesome + } + + @if (button) { + + @if (cue()) { + + } + } @else { + + } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + '[class.tb-ai-mark]': '!button', + '[class.lg]': '!button && large()', + '[style.--m]': 'button ? null : sizePx()', + '[style.animation-delay]': 'button ? null : phase', + '[attr.aria-hidden]': 'button ? null : "true"', + '[class.tb-ai-mark-button]': 'button', + '[attr.type]': 'button ? "button" : null', + '[class.working]': 'button && working()', + '[class.glow]': 'button && glow()' + } +}) +export class AiMarkComponent { + + readonly button = inject>(ElementRef).nativeElement.tagName === 'BUTTON'; + + readonly phase = `-${Date.now() % MARK_CYCLE_MS}ms`; + + size = input(undefined, {transform: (value: unknown) => value == null || value === '' ? undefined : numberAttribute(value)}); + + icon = input(); + + working = input(false, {transform: booleanAttribute}); + + glow = input(false, {transform: booleanAttribute}); + + cue = input(null); + + large(): boolean { + return (this.size() ?? 0) >= LARGE_MARK; + } + + sizePx(): string | null { + const size = this.size() ?? (this.button ? 36 : undefined); + return size ? `${size}px` : null; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html new file mode 100644 index 0000000000..b2f16d33d2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html @@ -0,0 +1,22 @@ + +
+ + + @if (question().number?.unit) { + {{ question().number.unit }} + } + +
+@if (wrong()) { + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts new file mode 100644 index 0000000000..b7eae1fd27 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, inject, input, model, output, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AiQuestion } from '@shared/models/solution-creator.models'; +import { aiLocale, aiNumberReady, aiReadNumber, aiSayNumber, aiStepDecimals } from '@home/components/ai/ai-question.models'; + +@Component({ + selector: 'tb-ai-number-field', + templateUrl: './ai-number-field.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiNumberFieldComponent { + + question = input.required(); + value = model(''); + enter = output(); + + private translate = inject(TranslateService); + private touched = signal(false); + + readonly ready = computed(() => aiNumberReady(this.value(), this.locale())); + readonly wrong = computed(() => this.touched() && !!this.value().trim() && !this.ready()); + readonly size = computed(() => this.question().number?.size === 'short' ? 's' : this.question().number?.size === 'medium' ? 'm' : 'l'); + readonly step = computed(() => this.question().number?.step > 0 ? this.question().number.step : 1); + + typed(field: HTMLInputElement): void { + this.value.set(field.value); + } + + stepBy(field: HTMLInputElement, direction: number): void { + const current = aiReadNumber(field.value, this.locale()); + const base = isNaN(current) ? (this.question().number?.suggested ?? 0) : current; + const decimals = Math.max(aiStepDecimals(this.step()), isNaN(current) ? 0 : aiStepDecimals(current)); + field.value = aiSayNumber(+(base + direction * this.step()).toFixed(decimals), this.locale()); + this.touched.set(false); + this.value.set(field.value); + field.focus(); + } + + settle(): void { + this.touched.set(true); + } + + onEnter(event: Event): void { + if ((event as KeyboardEvent).isComposing) { + return; + } + if (!this.ready()) { + event.preventDefault(); + this.touched.set(true); + return; + } + this.enter.emit(event); + } + + private locale(): string { + return aiLocale(this.translate.currentLang); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html new file mode 100644 index 0000000000..e750917182 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html @@ -0,0 +1,64 @@ + +@if (folded()) { + +} +@if (!folded() || open()) { +
+
+ {{ 'ai-assistant.plan.title' | translate }} + {{ gate() || !progress() ? ('ai-assistant.plan.steps' | translate: {count: counted()}) : ('ai-assistant.plan.done-of' | translate: {done: done(), count: counted()}) }} + + @if (gate()) { + + } +
+
    + @for (step of steps(); track $index) { +
  1. + @if (gate() && step.optional) { + + } @else { + + } + @if (step.by === 'user') {{{ 'ai-assistant.plan.you' | translate }}}@for (part of parts(step.text); track $index) {@if (part.code) {{{ part.text }}} @else {{{ part.text }}}}@if (step.by === 'user' && step.needs) { {{ 'ai-assistant.plan.needs.' + step.needs | translate }}} +
  2. + } +
+ @if (gate()) { +
+ @if (autoApprove()) { + + + } @else { + + + } +
+ } +
+} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts new file mode 100644 index 0000000000..282a52dd5a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Component, computed, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { decorateReferences } from '@home/components/ai/ai-references'; +import { AiPlanProgress, AiPlanStep, aiPlanStatus } from '@home/components/ai/ai-action.models'; +import { aiFold } from '@home/components/ai/ai-disclosure.component'; + +export interface AiPlanRun { + auto: boolean; + skipped: number[]; +} + + +@Component({ + selector: 'tb-ai-plan', + templateUrl: './ai-plan.component.html', + standalone: false +}) +export class AiPlanComponent { + + steps = input.required(); + progress = input(null); + gate = input(false); + autoApprove = input(false); + replacedAfter = input(null); + + private fold = aiFold(); + + open = this.fold.open; + + @Output() run = new EventEmitter(); + @Output() changeRequested = new EventEmitter(); + + private cleared = signal>(new Set()); + + private host = inject(ElementRef); + private translate = inject(TranslateService); + + private chips = effect(() => { + const steps = this.steps(); + this.open(); + this.folded(); + setTimeout(() => { + const whats = (this.host.nativeElement as HTMLElement).querySelectorAll('.k-plan li .k-what'); + steps.forEach((step, index) => { + if (step.makes?.length && whats[index]) { + decorateReferences(whats[index], step.makes.map(made => ({name: made.name, entityType: made.type, id: ''}))); + } + }); + }); + }); + + status = computed(() => aiPlanStatus(this.steps(), this.progress())); + + marks = computed(() => this.status().marks); + + counted = computed(() => this.gate() + ? this.steps().filter((step, index) => !step.optional || !this.cleared().has(index)).length + : this.status().counted); + + done = computed(() => this.status().done); + + finished = computed(() => !this.gate() && this.status().finished); + + folded = computed(() => this.replacedAfter() !== null || this.finished()); + + foldText = computed(() => { + const translate = this.translate; + return this.replacedAfter() !== null + ? translate.instant('ai-assistant.plan.replaced', {done: this.replacedAfter(), count: this.counted()}) + : translate.instant('ai-assistant.plan.folded', {done: this.done(), count: this.counted()}); + }); + + toggleFold(): void { + this.fold.toggle(); + } + + parts(text: string): {text: string; code: boolean}[] { + return text.split('`').map((part, index) => ({text: part, code: index % 2 === 1})).filter(part => part.text); + } + + checked(index: number): boolean { + return !this.cleared().has(index); + } + + toggle(index: number): void { + this.cleared.update(set => { + const next = new Set(set); + if (next.has(index)) { + next.delete(index); + } else { + next.add(index); + } + return next; + }); + } + + start(auto: boolean): void { + const skipped = this.steps().map((step, index) => step.optional && this.cleared().has(index) ? index + 1 : 0).filter(Boolean); + this.run.emit({auto, skipped}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html index 082f2708b0..b01eee5cf8 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html @@ -4,13 +4,27 @@ SPDX-License-Identifier: BUSL-1.1 --> -
+
@if (attachEnabled()) { }
- @if (attachments().length) { + @if (attachments().length || quote) {
+ @if (quote) { + + {{ quote.icon }} + + {{ fileName(quote.name).base }}{{ fileName(quote.name).ext }} + {{ (quote.from === quote.to ? 'ai-assistant.file.line' : 'ai-assistant.file.lines-range') | translate: {from: quote.from, to: quote.to} }} + + + + } @for (attachment of attachments(); track attachment.key) { {{ attachment.status === 'error' ? 'error_outline' : attachment.icon }} } - {{ attachment.name }} + {{ fileName(attachment.name).base }}{{ fileName(attachment.name).ext }} {{ meta(attachment) }} @if (attachment.status === 'uploading') { @@ -38,26 +52,44 @@ }
+ @if (suggestion && !hasText()) { + + {{ 'ai-assistant.suggestion-sr' | translate: {text: suggestion} }} + } + @if (slim) { + + } - + @if (canStop) { + + } @else { + + }
@@ -69,17 +101,34 @@ attach_file } + @if (showAutoApprove) { + + } -
+ +
+
+ {{ 'ai-assistant.stop' | translate }} + Esc +
+
+
+
@@ -97,6 +146,16 @@
+ +
+
+ {{ 'ai-assistant.auto-approve' | translate }} + {{ (autoApprove ? 'ai-assistant.auto-approve-on' : 'ai-assistant.auto-approve-off') | translate }} +
+

{{ (autoApproveInChat ? 'ai-assistant.auto-approve-text' : 'ai-assistant.auto-approve-new-chat-text') | translate }}

+
+
+
{{ 'ai-assistant.shortcuts' | translate }}
@@ -108,6 +167,12 @@ {{ 'ai-assistant.new-line' | translate }} ShiftEnter
+ @if (suggestion && !hasText()) { +
+ {{ 'ai-assistant.accept-suggestion' | translate }} + Tab +
+ }
{{ 'ai-assistant.focus-composer' | translate }} / diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss index 088c205465..72fbccb13c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss @@ -1,19 +1,5 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -$ai-teal-300: #4db6ac; -$ai-teal-400: #26a69a; -$ai-action: #00695c; -$ai-action-hover: #004d40; -$ai-focus: #00695c; -$ai-teal-700: #00796b; -$ink: rgba(0, 0, 0, 0.87); -$ink-54: rgba(0, 0, 0, 0.54); -$ink-38: rgba(0, 0, 0, 0.38); -$faint: rgba(0, 0, 0, 0.56); -$line: rgba(0, 0, 0, 0.12); -$line-soft: rgba(0, 0, 0, 0.05); -$crit: #d12730; -$font: Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif; $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.75' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9 5l7 7-7 7'/%3E%3C/svg%3E"; :host { @@ -23,32 +9,32 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= .tb-ai-composer { width: 100%; - font-family: $font; - letter-spacing: 0.25px; + font-family: var(--tb-font); + letter-spacing: var(--chat-text-ls); text-align: left; .composer-field { position: relative; display: flow-root; - background: #fff; + background: var(--tb-surface); border: 1px solid transparent; border-radius: 14px; box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.04), 0 1px 2px rgba(16, 24, 40, 0.06), 0 8px 24px rgba(16, 24, 40, 0.08); transition: border-color .18s ease, box-shadow .18s ease; &:focus-within { - border-color: $ai-focus; - box-shadow: 0 0 0 1px $ai-focus, 0 8px 24px rgba(0, 105, 92, 0.12); + border-color: var(--ai-focus); + box-shadow: 0 0 0 1px var(--ai-focus), 0 8px 24px var(--ai-focus-shadow); .composer-chevron { - color: $ai-focus; + color: var(--ai-focus); } } } &.drop .composer-field { - box-shadow: inset 0 0 0 2px $ai-teal-300; - background: color-mix(in srgb, $ai-action 4%, #fff); + box-shadow: inset 0 0 0 2px var(--ai-teal-300); + background: color-mix(in srgb, var(--ai-action) 4%, var(--tb-surface)); } .composer-files { @@ -66,16 +52,16 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= max-width: 100%; overflow: hidden; padding: 6px 10px 6px 8px; - border: 1px solid $line; + border: 1px solid var(--tb-line); border-radius: 8px; - background: #fff; + background: var(--tb-surface); font-size: 13.5px; line-height: 20px; animation: composer-file-in .12s ease-out; .mat-icon { flex: none; - color: $ink-54; + color: var(--tb-ink-54); } .file-pic { @@ -99,15 +85,15 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= font-size: 13.5px; font-weight: 500; line-height: 18px; - color: $ink; + color: var(--tb-ink); text-overflow: ellipsis; white-space: nowrap; } small { - font-size: 12px; - line-height: 16px; - color: $faint; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-faint); } } @@ -116,7 +102,7 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= left: 0; bottom: 0; height: 2px; - background: $ai-action; + background: var(--ai-teal-500); transition: width .15s linear; } @@ -132,25 +118,25 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= border: 0; border-radius: 50%; background: none; - color: $ink-54; + color: var(--tb-ink-54); cursor: pointer; &:hover { background: rgba(0, 0, 0, 0.06); - color: $ink; + color: var(--tb-ink); } } &.up small { - color: $ai-teal-700; + color: var(--ai-teal-700); } &.bad { - border-color: color-mix(in srgb, $crit 40%, transparent); - background: color-mix(in srgb, $crit 4%, #fff); + border-color: color-mix(in srgb, var(--tb-crit) 40%, transparent); + background: color-mix(in srgb, var(--tb-crit) 4%, var(--tb-surface)); .mat-icon, small { - color: $crit; + color: var(--tb-crit); } } } @@ -170,7 +156,7 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= align-items: center; height: 24px; margin: 4px 0 0 -2px; - color: $ai-action; + color: var(--ai-teal-500); transition: color .18s ease; &::before { @@ -193,17 +179,17 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= outline: 0; resize: none; background: transparent; - font-family: $font; - font-size: 16px; - line-height: 24px; - letter-spacing: normal; - color: $ink; - caret-color: $ai-action; + font-family: var(--tb-font); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: inherit; + color: var(--tb-ink); + caret-color: var(--ai-action); tab-size: 2; transition: height .12s ease; &::placeholder { - color: $faint; + color: var(--k-faint); } } @@ -214,6 +200,67 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= display: inline-flex; } + .composer-stop.composer-stop { + background: none; + isolation: isolate; + + &::before { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + border-radius: inherit; + background: var(--ai-action); + transition: background-color .2s ease; + } + + &::after { + content: ''; + position: absolute; + inset: -9px; + z-index: -2; + border-radius: 50%; + background: var(--ai-glow); + filter: blur(9px); + pointer-events: none; + --ai-glow-peak: .85; + opacity: .55; + animation: composer-glow-breathe 2.4s ease-in-out infinite, composer-glow-turn 6s linear infinite; + transition: opacity .2s ease; + } + + &:hover:not(:disabled) { + background: none; + + &::before { + background: var(--tb-crit); + } + + &::after { + opacity: 0; + animation: none; + } + } + + &:disabled { + opacity: .6; + cursor: default; + } + + .mat-icon { + width: 24px; + height: 24px; + font-size: 24px; + animation: composer-pop .28s cubic-bezier(.2, 0, 0, 1.4); + } + + @media (prefers-reduced-motion: reduce) { + &::after, .mat-icon { + animation: none; + } + } + } + .composer-send { position: relative; display: inline-flex; @@ -225,13 +272,13 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= padding: 0; border: 0; border-radius: 10px; - background: $ai-action; - color: #fff; + background: var(--ai-action); + color: var(--ai-on-action); cursor: pointer; transition: background-color .2s ease, color .2s ease, box-shadow .2s ease, transform .16s cubic-bezier(.2, 0, 0, 1); &:hover:not(:disabled) { - background: $ai-action-hover; + background: var(--ai-action-hover); .return-glyph polyline { transform: scale(1.12); @@ -243,13 +290,13 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= } &:focus-visible { - outline: 2px solid $ai-focus; + outline: 2px solid var(--ai-focus); outline-offset: 2px; } &:disabled { background: rgba(0, 0, 0, 0.06); - color: $ink-38; + color: var(--tb-ink-38); cursor: default; } @@ -287,11 +334,11 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= align-items: center; gap: 2px; padding: 2px 8px 6px 16px; - border-top: 1px solid $line-soft; + border-top: 1px solid var(--tb-line-soft); border-radius: 0 0 14px 14px; font-size: 13px; line-height: 18px; - color: rgba(0, 0, 0, 0.6); + color: var(--tb-text-secondary); } .composer-spacer { @@ -309,19 +356,117 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= border: 0; border-radius: 8px; background: none; - color: $ink-54; + color: var(--tb-ink-54); cursor: pointer; transition: background-color .12s ease, color .12s ease; &:hover, &[aria-describedby] { - background: $line-soft; - color: $ink; + background: var(--tb-line-soft); + color: var(--tb-ink); } &:focus-visible { - outline: 2px solid $ai-focus; + outline: 2px solid var(--ai-focus); outline-offset: 1px; - color: $ink; + color: var(--tb-ink); + } + } + + .composer-auto { + position: relative; + display: inline-flex; + align-items: center; + gap: 8px; + height: 32px; + padding: 0 10px 0 8px; + border-radius: 8px; + font-size: 12.5px; + line-height: 18px; + color: var(--tb-text-secondary); + cursor: pointer; + user-select: none; + transition: background-color .12s ease, color .12s ease; + + &:hover, &[aria-describedby], &:has(input:focus-visible) { + background: rgba(0, 0, 0, 0.05); + color: var(--tb-ink); + } + + input { + position: absolute; + width: 0; + height: 0; + opacity: 0; + } + + .track { + position: relative; + flex: none; + width: 34px; + height: 14px; + border-radius: 7px; + background: rgba(0, 0, 0, 0.26); + transition: background-color .32s cubic-bezier(.4, 0, .2, 1); + } + + .knob { + position: absolute; + top: -3px; + left: 0; + display: inline-flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + border-radius: 50%; + background: #fafafa; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); + transition: transform .32s cubic-bezier(.4, 0, .2, 1), background-color .32s cubic-bezier(.4, 0, .2, 1), box-shadow .2s ease; + + .mat-icon { + font-size: 13px; + width: 13px; + height: 13px; + line-height: 13px; + color: var(--tb-ink-54); + transition: color .32s cubic-bezier(.4, 0, .2, 1); + } + } + + .label { + white-space: nowrap; + color: var(--tb-ink-76); + } + + &:active .knob { + box-shadow: 0 0 0 5px rgba(0, 0, 0, 0.04), 0 1px 3px rgba(0, 0, 0, 0.3); + } + + &.on { + color: var(--tb-ink-76); + + .track { + background: color-mix(in srgb, var(--ai-selected) 35%, transparent); + } + + .knob { + transform: translateX(14px); + background: var(--ai-selected); + + .mat-icon { + color: var(--ai-on-action); + } + } + + &:active .knob { + box-shadow: 0 0 0 5px color-mix(in srgb, var(--ai-selected) 10%, transparent), 0 1px 3px rgba(0, 0, 0, 0.3); + } + } + + @media (prefers-reduced-motion: reduce) { + .track, .knob, .knob .mat-icon { + transition: none; + } } } @@ -330,14 +475,14 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= } &.docked { - border-top: 1px solid $line; - background: #fff; - font-size: 14px; - line-height: 20px; + border-top: 1px solid var(--tb-line); + background: var(--tb-surface); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); transition: border-top-color .18s ease; &:focus-within { - border-top-color: $ai-focus; + border-top-color: var(--ai-focus); } .composer-field { @@ -347,12 +492,12 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= transition: box-shadow .18s ease; &:focus-within { - box-shadow: inset 0 1px 0 $ai-focus; + box-shadow: inset 0 1px 0 var(--ai-focus); } } &.drop .composer-field { - box-shadow: inset 0 0 0 2px $ai-teal-300; + box-shadow: inset 0 0 0 2px var(--ai-teal-300); } .composer-files { @@ -366,15 +511,19 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= .composer-chevron { --chevron: 17px; - height: 22px; + height: var(--chat-line-lh, 20px); + } + + .composer-foot .composer-auto { + height: 28px; } textarea { min-height: 44px; max-height: 160px; padding-right: 44px; - font-size: 14px; - line-height: 20px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); } .composer-send-slot { @@ -402,7 +551,7 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= gap: 6px 8px; padding: 2px 8px 6px 12px; border-radius: 0; - font-size: 12px; + font-size: var(--chat-meta); } .composer-tool { @@ -413,6 +562,27 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= .composer-foot > .composer-add:first-child { margin-left: -7.5px; } + + @container k-col (min-width: 481px) { + border-top: 0; + background: none; + + .composer-field, .composer-field:not(:focus-within) { + border: 1px solid var(--tb-line); + border-radius: 14px; + background: var(--tb-surface); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06), 0 10px 28px rgba(16, 24, 40, 0.10); + + &:focus-within { + border-color: var(--ai-focus); + box-shadow: 0 0 0 3px var(--ai-focus-shadow), 0 10px 28px rgba(16, 24, 40, 0.10); + } + } + + .composer-foot { + border-radius: 0 0 14px 14px; + } + } } } @@ -452,3 +622,129 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= } } } + +@keyframes composer-glow-breathe { + 0%, 100% { + opacity: calc(var(--ai-glow-peak, .85) * .35); + scale: .94; + } + 50% { + opacity: var(--ai-glow-peak, .85); + scale: 1.06; + } +} + +@keyframes composer-glow-turn { + to { + rotate: 1turn; + } +} + +@keyframes composer-pop { + from { + transform: scale(.4) rotate(-20deg); + opacity: 0; + } + to { + transform: none; + opacity: 1; + } +} + +.tb-ai-composer.slim { + .composer-field { + border-radius: 12px; + + &:not(:focus-within) { + border-color: transparent; + box-shadow: var(--tb-home-card-shadow, 0 1px 1px rgba(20, 52, 58, 0.06), 0 2px 6px -1px rgba(20, 52, 58, 0.08)); + } + } + + .composer-row { + padding-bottom: 12px; + transition: padding .24s ease; + } + + textarea { + min-height: 24px; + transition: min-height .24s cubic-bezier(.2, .7, .2, 1); + } + + .composer-foot { + max-height: 0; + padding-top: 0; + padding-bottom: 0; + border-top-width: 0; + opacity: 0; + overflow: clip; + transition: max-height .24s cubic-bezier(.2, .7, .2, 1), padding .24s cubic-bezier(.2, .7, .2, 1), opacity .18s ease; + } + + .composer-slash { + display: inline-flex; + align-items: center; + justify-content: center; + box-sizing: border-box; + min-width: 20px; + height: 20px; + padding: 0 5px; + border: 1px solid var(--tb-line); + border-bottom-width: 2px; + border-radius: 5px; + background: var(--chat-key); + color: var(--tb-ink-76); + font: 500 11px/1 var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; + position: absolute; + top: 50%; + right: 19px; + pointer-events: none; + transform: translateY(-50%); + } + + &:not(:focus-within):not(.has-text) .composer-send-slot { + visibility: hidden; + } + + &:is(:focus-within, .has-text) { + .composer-row { + padding-bottom: 8px; + } + + textarea { + min-height: 72px; + } + + .composer-foot { + max-height: 56px; + padding-top: 2px; + padding-bottom: 6px; + border-top-width: 1px; + opacity: 1; + overflow: visible; + } + + .composer-slash { + display: none; + } + } + + @media (hover: none), (max-width: 599px) { + .composer-slash { + display: none; + } + + &:not(:focus-within):not(.has-text) .composer-send-slot { + visibility: visible; + } + } + + @media (prefers-reduced-motion: reduce) { + textarea, .composer-foot, .composer-row { + transition: none; + } + } +} + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts index 5297f99045..dc85e60070 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts @@ -1,32 +1,37 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +import { aiFileName } from '@home/components/ai/ai-file.models'; import { AfterViewInit, + ChangeDetectionStrategy, Component, computed, ElementRef, EventEmitter, - HostListener, inject, Input, OnChanges, OnDestroy, Output, Renderer2, + SecurityContext, signal, SimpleChanges, untracked, - ViewChild, - SecurityContext + ViewChild } from '@angular/core'; import { FormControl } from '@angular/forms'; import { toSignal } from '@angular/core/rxjs-interop'; import { Subscription } from 'rxjs'; +import { take } from 'rxjs/operators'; import { TranslateService } from '@ngx-translate/core'; +import { MatDialog } from '@angular/material/dialog'; +import { AiShortcutsDialogComponent } from '@home/components/ai/ai-shortcuts-dialog.component'; import { DomSanitizer } from '@angular/platform-browser'; import { guid } from '@core/utils'; +import { AiSlashService } from '@core/services/ai-slash.service'; import { AiResourceService } from '@core/http/ai-resource.service'; -import { AI_IMAGE_MEDIA_TYPES, AiPromptMessage, AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models'; +import { AI_IMAGE_MEDIA_TYPES, AiLinesQuote, AiPromptMessage, AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models'; import { AI_SVG_EXTENSION, aiAttachmentKind, @@ -36,8 +41,7 @@ import { isAiSvg, namePastedImage, svgToAiImage, - aiServerMessage -} from '@home/components/ai/ai-attachment.models'; + aiServerMessage, aiResourceFact } from '@home/components/ai/ai-attachment.models'; interface PendingAttachment { key: string; @@ -56,6 +60,7 @@ interface PendingAttachment { const FLY_DURATION = 520; @Component({ + changeDetection: ChangeDetectionStrategy.OnPush, selector: 'tb-ai-prompt-input', templateUrl: './ai-prompt-input.component.html', styleUrls: ['./ai-prompt-input.component.scss'], @@ -63,24 +68,74 @@ const FLY_DURATION = 520; }) export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestroy { + readonly fileName = aiFileName; + private aiResourceService = inject(AiResourceService); private translate = inject(TranslateService); private sanitizer = inject(DomSanitizer); private renderer = inject(Renderer2); + private dialog = inject(MatDialog); private host = inject>(ElementRef); @Input() placeholder = ''; + @Input() suggestion: string | null = null; + + ghostTight = signal(false); + + @Input() quote: AiLinesQuote | null = null; + + @Output() quoteRemoved = new EventEmitter(); + @Input() loading: boolean; @Input() docked = false; + @Input() slim = false; + + @Input() pinned = false; + @Input() dropZone: HTMLElement; + @Input() showAutoApprove = false; + + @Input() autoApprove = false; + + @Input() autoApproveInChat = true; + @Output() messageSent = new EventEmitter(); + @Output() autoApproveChange = new EventEmitter(); + + @Input() stoppable = false; + + @Input() stopping = false; + + @Input() sendWhileWorking = false; + + @Input() blocked = false; + + @Output() stopped = new EventEmitter(); + + get working(): boolean { + return this.loading && this.stoppable; + } + + get canStop(): boolean { + return this.working && !(this.sendWhileWorking && this.hasContent()); + } + + stop(): void { + if (this.working && !this.stopping) { + this.stopped.emit(); + } + } + @ViewChild('textarea') textarea!: ElementRef; + private slash = inject(AiSlashService); + private removeSlash: () => void; + @ViewChild('fileInput') fileInput!: ElementRef; message = new FormControl(''); @@ -113,16 +168,31 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr get canSend(): boolean { const ready = this.attachments().some(attachment => attachment.status === 'ready'); - return !this.loading && !this.uploading() && (!!this.message.value?.trim() || ready); + return !this.blocked && (!this.loading || this.sendWhileWorking) && !this.uploading() && (!!this.message.value?.trim() || ready || !!this.quote); + } + + private hasContent(): boolean { + return this.hasText() || this.attachments().some(attachment => attachment.status === 'ready'); } ngOnChanges(changes: SimpleChanges): void { if (changes.dropZone) { this.listenForDrops(this.dropZone ?? this.host.nativeElement); } + if (changes.suggestion) { + setTimeout(() => this.fitGhost()); + } } ngAfterViewInit(): void { + this.removeSlash = this.slash.addComposer({ + field: () => this.textarea?.nativeElement, + focusEnd: () => { + const field = this.textarea?.nativeElement; + field.focus(); + field.selectionStart = field.selectionEnd = field.value.length; + } + }); if (!this.dropTarget) { this.listenForDrops(this.host.nativeElement); } @@ -130,32 +200,38 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr } ngOnDestroy(): void { + this.removeSlash?.(); this.destroyed = true; clearTimeout(this.flyTimer); this.stopListening(); this.clearAttachments(true); } - @HostListener('document:keydown', ['$event']) - onDocumentKeydown(event: KeyboardEvent): void { - if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey) { + openShortcuts(event: MouseEvent): void { + const from = event.currentTarget as HTMLElement; + if (this.dialog.openDialogs.some(open => open.componentInstance instanceof AiShortcutsDialogComponent)) { return; } - const target = event.target as HTMLElement; - if (target?.closest?.('input, textarea, select, [contenteditable]')) { + this.dialog.open(AiShortcutsDialogComponent, {panelClass: ['tb-dialog', 'tb-ai-keys-dialog'], autoFocus: 'dialog', restoreFocus: true}) + .afterClosed().subscribe(() => from?.focus({preventScroll: true})); + } + + onKeydown(event: KeyboardEvent): void { + if (event.key === 'Tab' && !event.shiftKey && this.suggestion && !this.message.value) { + event.preventDefault(); + this.setValue(this.suggestion); return; } - const visible = Array.from(document.querySelectorAll('.tb-ai-composer textarea')) - .filter(textarea => textarea.offsetParent); - const field = this.textarea?.nativeElement; - if (field && visible[visible.length - 1] === field) { + if (event.key === 'Escape' && this.working) { event.preventDefault(); - field.focus(); - field.selectionStart = field.selectionEnd = field.value.length; + this.stop(); + return; + } + if (event.key === 'Escape' && this.slim) { + event.preventDefault(); + this.textarea?.nativeElement.blur(); + return; } - } - - onKeydown(event: KeyboardEvent): void { if (event.key === 'Enter' && (!event.shiftKey || event.metaKey || event.ctrlKey)) { event.preventDefault(); this.send(); @@ -170,13 +246,17 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr send(): void { const msg = this.message.value?.trim() ?? ''; const ready = this.attachments().filter(attachment => attachment.status === 'ready'); - if (this.loading || this.uploading() || (!msg && !ready.length)) { + if ((this.loading && !this.sendWhileWorking) || this.uploading() || (!msg && !ready.length && !this.quote)) { return; } this.fly(); this.clearText(); this.clearAttachments(false); - this.messageSent.emit({message: msg, resources: ready.map(attachment => attachment.resource)}); + const sent: AiPromptMessage = {message: msg, resources: ready.map(attachment => attachment.resource)}; + if (this.quote) { + sent.quote = this.quote; + } + this.messageSent.emit(sent); } reset(): void { @@ -184,19 +264,47 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr this.clearAttachments(true); } + restoreAttachments(resources: AiResourceInfo[]): void { + const kept = untracked(() => this.attachments()); + const missing = (resources ?? []).filter(resource => !kept.some(attachment => attachment.resource?.id === resource.id)); + for (const resource of missing) { + const kind = aiAttachmentKind(resource.mediaType, resource.name); + const key = guid(); + this.attachments.update(list => [...list, { + key, name: resource.name, size: resource.size, icon: kind.icon, kind: kind.label, status: 'ready', progress: 100, resource + }]); + if (resource.mediaType?.startsWith('image/')) { + this.aiResourceService.getUrl(resource.id).pipe(take(1)).subscribe({ + next: previewUrl => this.patch(key, {previewUrl}), + error: () => {} + }); + } + } + } + focus(): void { this.textarea?.nativeElement.focus(); } - setValue(value: string): void { + setValue(value: string, showStart = false): void { this.message.setValue(value); this.hasText.set(!!value); setTimeout(() => { - this.textarea?.nativeElement.focus(); + const field = this.textarea?.nativeElement; + field?.focus({preventScroll: showStart}); + field?.setSelectionRange(field.value.length, field.value.length); this.resize(); + if (field && showStart) { + field.scrollTop = 0; + } }); } + toggleAutoApprove(event: Event): void { + this.autoApprove = (event.target as HTMLInputElement).checked; + this.autoApproveChange.emit(this.autoApprove); + } + openFilePicker(): void { this.fileInput?.nativeElement.click(); } @@ -228,7 +336,8 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr if (attachment.status === 'uploading') { return this.translate.instant('ai-assistant.attachment-uploading', {progress: attachment.progress}); } - return `${this.translate.instant(attachment.kind)} · ${formatAiFileSize(attachment.size)}`; + const fact = aiResourceFact(attachment.resource?.facts, this.translate); + return `${this.translate.instant(attachment.kind)} · ${fact ?? formatAiFileSize(attachment.size)}`; } addFiles(files: File[]): void { @@ -338,9 +447,40 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr if (!field) { return; } - const cap = this.docked ? Math.min(160, Math.round(innerHeight * 0.3)) : Math.min(220, Math.round(innerHeight * 0.4)); + const cap = this.docked ? Math.min(160, Math.round(innerHeight * 0.3)) : Math.min(this.pinned ? 240 : 220, Math.round(innerHeight * 0.4)); field.style.height = 'auto'; field.style.height = Math.min(field.scrollHeight, cap) + 'px'; + this.fitGhost(); + } + + ghostHead(): string { + const text = this.suggestion ?? ''; + const space = text.lastIndexOf(' '); + return space < 0 ? '' : text.slice(0, space + 1); + } + + ghostLast(): string { + const text = this.suggestion ?? ''; + return text.slice(text.lastIndexOf(' ') + 1); + } + + private fitGhost(): void { + const ghost = this.host.nativeElement.querySelector('.composer-ghost'); + const words = ghost?.firstElementChild as HTMLElement | null; + const key = ghost?.querySelector('kbd'); + if (!ghost || !words || !key) { + this.ghostTight.set(false); + return; + } + ghost.classList.remove('tight'); + const wrap = ghost.style.whiteSpace; + ghost.style.whiteSpace = 'nowrap'; + const keyWidth = key.getBoundingClientRect().width + parseFloat(getComputedStyle(key).marginLeft || '0'); + const wordsWidth = words.getBoundingClientRect().width - (words.contains(key) ? keyWidth : 0); + ghost.style.whiteSpace = wrap; + const tight = wordsWidth <= ghost.clientWidth && wordsWidth + keyWidth > ghost.clientWidth; + ghost.classList.toggle('tight', tight); + this.ghostTight.set(tight); } private clearText(): void { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html new file mode 100644 index 0000000000..3fe0631674 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html @@ -0,0 +1,187 @@ + +@if (answered(); as answers) { +
+
+ {{ 'ai-assistant.question.you-said' | translate }} +
+ @if (time()) { + + } + @for (item of answers; track item.question.id) { +
+ {{ item.question.question }} + +
+ } +
+} @else if (sheet()) { +
+
+ {{ 'ai-assistant.question.needs-answer' | translate }} +
+ @for (step of questions(); track step.id; let index = $index) { +
+ +
+ } +
+ + + +
+
+} @else if (current(); as question) { +
+
+ {{ 'ai-assistant.question.needs-answer' | translate }} + @if (questions().length > 1) { + {{ 'ai-assistant.question.count' | translate: {at: at() + 1, of: questions().length} }} + } +
+ @for (step of [question]; track step.id) { +
+ +
+ } +
+ @if (at() > 0) { + + } + + + +
+
+} + + +
+ @if (numbered) { + + } + @if (step.parts) {@for (part of step.parts; track $index) {@if (part.severity) {{{ ('alarm.severity-' + part.severity.toLowerCase()) | translate }}} @else {{{ part.text }}}}} @else {{{ step.question }}} + @if (step.why) { + {{ step.why }} + } +
+
+ @switch (kind(step)) { + @case ('color') { + + } + @case ('secret') { + + } + @case ('number') { + + } + @case ('text') { +
+
+ + {{ otherLabel(step) }} + + +
+
+ } + @case ('multi') { +
+ @for (option of step.options; track option.label) { + + } + +
+ } + @case ('date') { +
+ @for (option of step.options; track option.label) { + + } + +
+ } + @case ('chips') { +
+ @for (option of step.options; track option.label) { + + } + +
+ @if (isOther(step) && step.number) { + + } @else if (isOther(step)) { + + } @else if (chosenHint(step); as hint) { +

{{ hint }}

+ } + } + @default { +
+ @for (option of step.options; track option.label) { + + } + +
+ } + } +
+
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts new file mode 100644 index 0000000000..bc13df9505 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts @@ -0,0 +1,337 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, EventEmitter, inject, input, Output, Renderer2, signal, ViewContainerRef } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AiQuestion, AiQuestionAnswer, AiQuestionKind } from '@shared/models/solution-creator.models'; +import { TbPopoverService } from '@shared/components/popover.service'; +import { + aiColorOf, + aiIsFree, + aiIsNumber, + aiKindOf, + aiLocale, + aiNumberReady, + aiSayNumber +} from '@home/components/ai/ai-question.models'; +import { aiColorAnswer, aiColorReady } from '@home/components/ai/ai-color-field.component'; +import { AiDatePanelComponent, AiPickedDay } from '@home/components/ai/ai-date-panel.component'; + +const MULTI_SEPARATOR = ', '; + +export function aiAnswersText(answers: AiQuestionAnswer[]): string { + return answers.map(item => item.question.question.trim() + ' ' + item.answer.trim()).join('\n'); +} + +export function aiAnswersPrompt(answers: AiQuestionAnswer[]): {message: string; secrets?: Record} { + const secrets: Record = {}; + const lines = answers.map((item, index) => { + if (!item.secret || !item.answer) { + return item.question.question.trim() + ' ' + item.answer.trim(); + } + const name = (item.question.id || '').replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 64) || 'answer_' + (index + 1); + secrets[name] = item.answer; + return item.question.question.trim() + ' {{secret:' + name + '}}'; + }); + return Object.keys(secrets).length ? {message: lines.join('\n'), secrets} : {message: lines.join('\n')}; +} + +export function aiAnswersOf(content: string | undefined, questions: AiQuestion[] | undefined): AiQuestionAnswer[] | null { + if (!content || !questions?.length) { + return null; + } + const lines = content.split('\n').map(line => line.trim()).filter(Boolean); + const answers: AiQuestionAnswer[] = []; + for (const line of lines) { + const found = questions.map(question => ({question, asked: askedPrefix(question).exec(line)})).find(item => !!item.asked); + if (!found) { + return null; + } + answers.push({question: found.question, answer: line.slice(found.asked[0].length).trim()}); + } + return answers.length ? answers : null; +} + +function askedPrefix(question: AiQuestion): RegExp { + const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const asked = question.parts?.length + ? question.parts.map(part => part.severity ? '.+?' : escape(part.text ?? '')).join('') + : escape(question.question.trim()); + return new RegExp('^' + asked.trim() + ' '); +} + +function recommendedOf(question: AiQuestion): string[] { + const recommended = Array.isArray(question.recommended) ? question.recommended : question.recommended ? [question.recommended] : []; + return recommended.filter(label => question.options.some(option => option.label === label)); +} + +@Component({ + selector: 'tb-ai-question', + templateUrl: './ai-question.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiQuestionComponent { + + questions = input.required(); + answered = input(null); + time = input(undefined); + + @Output() done = new EventEmitter(); + @Output() skip = new EventEmitter(); + + private translate = inject(TranslateService); + private popoverService = inject(TbPopoverService); + private renderer = inject(Renderer2); + private viewContainerRef = inject(ViewContainerRef); + + colorOf = aiColorOf; + isFree = aiIsFree; + + at = signal(0); + move = signal<'next' | 'back' | null>(null); + dayOpen = signal(null); + private picked = signal>({}); + private days: Record = {}; + private chosen = signal>({}); + private typed = signal>({}); + + current = computed(() => this.questions()[Math.min(this.at(), this.questions().length - 1)]); + last = computed(() => this.at() >= this.questions().length - 1); + + valueOf(question: AiQuestion): string { + const picked = this.picked()[question.id]; + if (picked !== undefined) { + return picked; + } + return this.isFree(question) || question.date ? '' : this.defaultOf(question); + } + + kind(question: AiQuestion): AiQuestionKind { + return aiKindOf(question); + } + + isChosen(question: AiQuestion, label: string): boolean { + return (this.chosen()[question.id] ?? recommendedOf(question)).includes(label); + } + + toggle(question: AiQuestion, label: string): void { + const current = this.chosen()[question.id] ?? recommendedOf(question); + this.chosen.update(values => ({...values, [question.id]: current.includes(label) ? current.filter(item => item !== label) : [...current, label]})); + } + + isOther(question: AiQuestion): boolean { + if (this.isFree(question)) { + return true; + } + if (question.multiple) { + return !!this.otherText(question).trim(); + } + return this.picked()[question.id] === null; + } + + otherText(question: AiQuestion): string { + const typed = this.typed()[question.id]; + if (typed !== undefined) { + return typed; + } + const suggested = aiIsNumber(question) ? question.number?.suggested : undefined; + return suggested !== undefined && suggested !== null ? aiSayNumber(suggested, this.locale()) : ''; + } + + otherLabel(question: AiQuestion): string { + return question.other?.label || this.translate.instant(this.isFree(question) ? 'ai-assistant.question.your-answer' + : question.date ? 'ai-assistant.question.another-day' : 'ai-assistant.question.other'); + } + + colorValue(question: AiQuestion): string { + const picked = this.picked()[question.id]; + return picked === null || aiIsFree(question) ? this.typed()[question.id] ?? '' : picked ?? this.defaultOf(question); + } + + setColor(question: AiQuestion, value: string): void { + if (question.options.some(option => option.label === value)) { + this.pick(question, value); + } else { + this.picked.update(values => ({...values, [question.id]: null})); + this.typed.update(values => ({...values, [question.id]: value})); + } + } + + setTyped(question: AiQuestion, value: string): void { + this.pickOther(question); + this.typed.update(values => ({...values, [question.id]: value})); + } + + openDay(question: AiQuestion, chip: HTMLElement): void { + if (this.popoverService.hasPopover(chip)) { + this.popoverService.hidePopover(chip); + return; + } + const today = new Date(); + const chosen = this.days[question.id]; + const popover = this.popoverService.displayPopover({ + trigger: chip, + renderer: this.renderer, + hostView: this.viewContainerRef, + componentType: AiDatePanelComponent, + preferredPlacement: ['bottomLeft', 'bottom', 'topLeft', 'top'], + context: { + selected: chosen?.date ?? new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1), + time: chosen?.time ?? '9:00' + }, + showCloseButton: false, + popoverContentStyle: {padding: '8px 12px 12px'}, + isModal: true + }); + this.dayOpen.set(question.id); + popover.tbHideStart.subscribe(() => { + this.dayOpen.set(null); + if (popover.tbComponentRef?.instance.hasFocus() || document.activeElement === document.body) { + chip.focus(); + } + }); + popover.tbComponentRef.instance.popover = popover; + popover.tbComponentRef.instance.applied.subscribe((day: AiPickedDay) => { + this.days[question.id] = day; + this.picked.update(values => ({...values, [question.id]: null})); + this.typed.update(values => ({...values, [question.id]: + `${day.date.toLocaleDateString(this.locale(), {weekday: 'long', day: 'numeric', month: 'short'})}, ${day.time}`})); + popover.hide(); + }); + } + + private locale(): string { + return aiLocale(this.translate.currentLang); + } + + ready(question: AiQuestion): boolean { + if (question.multiple && !this.isFree(question)) { + return true; + } + if (aiKindOf(question) === 'color') { + return aiColorReady(question, this.colorValue(question)); + } + if (this.isOther(question) && aiIsNumber(question)) { + return aiNumberReady(this.otherText(question), this.locale()); + } + return this.isOther(question) ? !!this.otherText(question).trim() : !!this.valueOf(question); + } + + sheet = computed(() => this.questions().length > 1 && this.questions().every(question => + !question.multiple && !aiIsFree(question) && (aiKindOf(question) === 'chips' || aiKindOf(question) === 'color' || question.options.length <= 3))); + + allReady = computed(() => this.questions().every(question => this.ready(question))); + + finish(): void { + if (this.questions().every(question => this.ready(question))) { + this.done.emit(this.answers()); + } + } + + chosenHint(question: AiQuestion): string | undefined { + const value = this.valueOf(question); + return question.options.find(option => option.label === value)?.hint; + } + + pick(question: AiQuestion, label: string): void { + this.picked.update(values => ({...values, [question.id]: label})); + } + + pickOther(question: AiQuestion): void { + if (question.multiple || this.isFree(question)) { + return; + } + if (!this.isOther(question)) { + this.picked.update(values => ({...values, [question.id]: null})); + } + } + + type(question: AiQuestion, area: HTMLTextAreaElement | HTMLInputElement): void { + this.pickOther(question); + this.typed.update(values => ({...values, [question.id]: area.value})); + if (area instanceof HTMLTextAreaElement) { + area.style.height = 'auto'; + area.style.height = area.scrollHeight + 'px'; + } + } + + shown(item: {question: AiQuestion; answer: string}): string { + return item.question.secret && item.answer && item.answer !== this.translate.instant('ai-assistant.question.no-answer') ? '••••••••' : item.answer; + } + + next(): void { + const question = this.current(); + if (!question || !this.ready(question)) { + return; + } + if (this.last()) { + this.done.emit(this.answers()); + } else { + this.move.set('next'); + this.at.update(index => index + 1); + } + } + + back(): void { + this.move.set('back'); + this.at.update(index => Math.max(0, index - 1)); + } + + skipAll(): void { + this.skip.emit(this.questions().map(question => this.given(question) + ? {question, answer: this.answerOf(question), secret: !!question.secret && !question.options?.length} + : {question, answer: this.defaultOf(question)})); + } + + onEnter(event: Event): void { + const keyboard = event as KeyboardEvent; + if (!keyboard.shiftKey && !keyboard.isComposing) { + event.preventDefault(); + if (this.sheet()) { + this.finish(); + } else { + this.next(); + } + } + } + + private given(question: AiQuestion): boolean { + return question.multiple && !this.isFree(question) + ? this.answerOf(question) !== this.translate.instant('ai-assistant.question.none') + : this.ready(question); + } + + private answers(): AiQuestionAnswer[] { + return this.questions().map(question => ({question, answer: this.answerOf(question), secret: !!question.secret && !question.options?.length})); + } + + private answerOf(question: AiQuestion): string { + if (question.multiple && !this.isFree(question)) { + const values = [...question.options.map(option => option.label).filter(label => this.isChosen(question, label))]; + const typed = this.otherText(question).trim(); + if (typed) { + values.push(typed); + } + return values.length ? values.join(MULTI_SEPARATOR) : this.translate.instant('ai-assistant.question.none'); + } + if (aiKindOf(question) === 'color') { + return aiColorAnswer(question, this.colorValue(question)); + } + if (this.isOther(question) && aiIsNumber(question)) { + const value = this.otherText(question).trim(); + return value && question.number?.unit ? `${value} ${question.number.unit}` : value; + } + return this.isOther(question) ? this.otherText(question).trim() : this.valueOf(question); + } + + private defaultOf(question: AiQuestion): string { + if (this.isFree(question)) { + return this.translate.instant('ai-assistant.question.no-answer'); + } + if (question.multiple) { + const recommended = recommendedOf(question); + return recommended.length ? recommended.join(MULTI_SEPARATOR) : this.translate.instant('ai-assistant.question.none'); + } + return recommendedOf(question)[0] ?? question.options?.[0]?.label ?? ''; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-question.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-question.models.ts new file mode 100644 index 0000000000..ae0493c09d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-question.models.ts @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AiQuestion, AiQuestionKind } from '@shared/models/solution-creator.models'; +import { MINUS } from '@home/components/ai/ai-text'; + +export { aiLocale } from '@home/components/ai/ai-text'; + +const HEX_COLOR = /#[0-9a-f]{6}(?![0-9a-z])|#[0-9a-f]{3}(?![0-9a-z])/i; + + +export function aiColorOf(text: string | undefined): string | null { + return text?.match(HEX_COLOR)?.[0] ?? null; +} + +export function aiIsFree(question: AiQuestion): boolean { + return !question.options?.length; +} + +export function aiIsColor(question: AiQuestion): boolean { + return !question.multiple && !question.secret + && (!!question.color || (!!question.options?.length && question.options.every(option => !!aiColorOf(option.label)))); +} + +export function aiIsNumber(question: AiQuestion): boolean { + return !!question.number && !question.multiple && !question.secret && !question.date && !aiIsColor(question); +} + +export function aiIsChipRow(question: AiQuestion): boolean { + return !question.multiple && question.options.length >= 2 && question.options.length <= (aiIsColor(question) ? 6 : 4) + && question.options.every(option => option.label.length <= 24); +} + +export function aiQuestionKind(question: AiQuestion): AiQuestionKind { + const free = aiIsFree(question); + if (aiIsColor(question)) { + return 'color'; + } + if (free) { + return question.secret ? 'secret' : aiIsNumber(question) ? 'number' : 'text'; + } + if (question.multiple) { + return 'multi'; + } + if (question.date) { + return 'date'; + } + return aiIsChipRow(question) ? 'chips' : 'cards'; +} + +export function aiKindOf(question: AiQuestion): AiQuestionKind { + return question.kind ?? aiQuestionKind(question); +} + +function commaDecimal(locale?: string): boolean { + return (1.5).toLocaleString(locale).charAt(1) === ','; +} + +export function aiSayNumber(value: number, locale?: string): string { + const text = String(value).replace('-', MINUS); + return commaDecimal(locale) ? text.replace('.', ',') : text; +} + +export function aiReadNumber(text: string, locale?: string): number { + let normalized = String(text ?? '').trim().replace(/[\s\u00a0\u202f']/g, '').replace(MINUS, '-'); + if (commaDecimal(locale)) { + const grouped = normalized.includes(',') || /^-?\d{1,3}(\.\d{3})+$/.test(normalized); + normalized = (grouped ? normalized.replace(/\./g, '') : normalized).replace(',', '.'); + } else { + const thousands = /^-?\d{1,3}(,\d{3})+(\.\d+)?$/.test(normalized); + normalized = normalized.includes(',') && !normalized.includes('.') && !thousands ? normalized.replace(',', '.') : normalized.replace(/,/g, ''); + } + return /^[-+]?(\d+\.?\d*|\.\d+)$/.test(normalized) ? parseFloat(normalized) : NaN; +} + +export function aiNumberReady(text: string, locale?: string): boolean { + return !isNaN(aiReadNumber(text, locale)); +} + +export function aiStepDecimals(step: number): number { + const text = String(step); + return text.includes('e-') ? +text.split('e-')[1] : (text.split('.')[1]?.length ?? 0); +} + +export function aiHexOf(text: string | undefined): string | null { + const digits = (text ?? '').trim().replace(/^#/, ''); + if (!/^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(digits)) { + return null; + } + const full = digits.length === 3 ? digits.split('').map(digit => digit + digit).join('') : digits; + return '#' + full.toUpperCase(); +} + +export function aiReadTime(text: string): string | null { + const match = String(text).trim().match(/^(\d{1,2})(?:[:.h]?(\d{2}))?$/); + if (!match) { + return null; + } + const hours = +match[1]; + const minutes = match[2] ? +match[2] : 0; + return hours < 24 && minutes < 60 ? `${hours}:${String(minutes).padStart(2, '0')}` : null; +} + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts new file mode 100644 index 0000000000..e79673afdf --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts @@ -0,0 +1,243 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, ElementRef, inject, input, output, signal, viewChild } from '@angular/core'; +import { DomSanitizer } from '@angular/platform-browser'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { TranslateService } from '@ngx-translate/core'; +import { aiEntityKind, aiThingWord } from '@home/components/ai/ai-action.models'; +import { aiFactParts, AiRecordFact, AiRecordView } from '@home/components/ai/ai-record.models'; +import { AiCardAction } from '@home/components/ai/ai-card-actions.component'; +import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; +import { EntityType } from '@shared/models/entity-type.models'; + +const TIGHT_WIDTH = 400; + +export type AiRecordPrimary = 'open' | 'install' | null; + +export function aiDashboardThumb(cards: number): string { + const n = Math.max(1, Math.min(cards, 6)); + const w = (112 - (n - 1) * 3) / n; + const tiles = Array.from({length: n}, (_, i) => `` + + `` + + ``).join(''); + const rows = [40, 48, 56, 64].map(y => `` + + ``).join(''); + return `` + + `${tiles}` + + `` + + `` + + `${rows}`; +} + +export function aiWidgetThumb(): string { + return `` + + `` + + `` + + `` + + `` + + ``; +} + +@Component({ + selector: 'tb-ai-record-card', + template: ` + @let rec = view(); +
+
+ @if (picture()) { + + } @else { + + } +
+ @if (rec.url) { + {{ rec.name }} + } @else { + {{ rec.name }} + } + @if (rec.badge) { + {{ rec.badge }} + } + + @if (rec.hub; as listing) { + + {{ listing.type }}@if (listing.creator) {{{ listing.type ? ' · ' : '' }}{{ listing.creator }}}@if (listing.verified) {}@if (listing.installs) { · {{ listing.installs }}} + } @else { + {{ meta() || rec.meta }} + } + +
+ + @if (rec.hub) { + + IoT Hub + + } @else if (rec.alarm; as current) { + + {{ (current.cleared ? 'ai-assistant.record.cleared' : 'alarm.severity-' + current.severity.toLowerCase()) | translate }} + @if (current.acknowledged) { + + } + + } @else if (rec.state; as current) { + {{ current.label }} + } + @switch (primaryAction()) { + @case ('install') { + + } + @case ('open') { + + + + } + @default { + @if (rec.url) { + + + + } + } + } + +
+ @if (hasFoot()) { +
+ @if (note()) { +

{{ note() }}

+ } + @if (shownFacts().length) { +
+ @for (fact of shownFacts(); track $index) { +
{{ fact.label }}
+
@for (part of parts(fact); track $index) {@if (part.code) {{{ part.text }}} @else {{{ part.text }}}}
+ } +
+ } + @if (actions().length) { + + } +
+ } +
+ `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiRecordCardComponent { + + view = input.required(); + + primary = input(null); + + meta = input(null); + + facts = input([]); + + note = input(undefined); + + actions = input([]); + + act = output(); + + compose = output(); + + tight = signal(false); + + installing = signal(false); + + kind = computed(() => aiEntityKind(this.view().entityType, this.view().alarmRule, this.view().groupType)); + + picture = computed(() => { + const view = this.view(); + return !!(view.image || view.imageUrl || view.entityType === EntityType.DASHBOARD || view.entityType === EntityType.WIDGET_TYPE); + }); + + primaryAction = computed(() => { + const primary = this.primary(); + if (primary === 'install') { + return this.view().hubItem ? 'install' : null; + } + return primary === 'open' && this.view().url ? 'open' : null; + }); + + shownFacts = computed(() => { + const view = this.view(); + const said = [view.badge, this.meta() || view.meta].filter(Boolean).map(text => text.toLowerCase()); + const sameWords = (value: string) => said.some(text => text === value || text.split(' · ').includes(value)); + return this.facts().filter(fact => !sameWords(fact.value.trim().toLowerCase())); + }); + + hasFoot = computed(() => !!this.note() || this.shownFacts().length > 0 || this.actions().length > 0); + + thumb = computed(() => this.sanitizer.bypassSecurityTrustHtml(this.view().entityType === EntityType.WIDGET_TYPE + ? aiWidgetThumb() : aiDashboardThumb(this.view().widgets ?? 4))); + + openLabel = computed(() => this.translate.instant('ai-assistant.record.open-type', {type: this.typeWord()})); + + openTip = computed(() => this.view().hub ? this.translate.instant('ai-assistant.record.open-on-iot-hub') + : this.translate.instant('ai-assistant.record.open-new-tab', {type: this.typeWord()})); + + private card = viewChild>('card'); + + private sanitizer = inject(DomSanitizer); + private translate = inject(TranslateService); + private iotHubActions = inject(IotHubActionsService); + private destroyRef = inject(DestroyRef); + + constructor() { + effect(onCleanup => { + const card = this.card()?.nativeElement; + if (!card || !this.picture() || typeof ResizeObserver === 'undefined') { + return; + } + const observer = new ResizeObserver(() => this.tight.set(card.clientWidth > 0 && card.clientWidth < TIGHT_WIDTH)); + observer.observe(card); + onCleanup(() => observer.disconnect()); + }); + } + + parts(fact: AiRecordFact) { + return aiFactParts(fact.value); + } + + install(): void { + const item = this.view().hubItem; + if (!item || this.installing()) { + return; + } + this.installing.set(true); + this.iotHubActions.installItem(item).pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ + complete: () => this.installing.set(false), + error: () => this.installing.set(false) + }); + } + + private typeWord(): string { + const view = this.view(); + if (view.alarmRule) { + return this.translate.instant('ai-assistant.detail.thing.alarm-rule'); + } + if (view.entityType === 'SCADA_SYMBOL') { + return this.translate.instant('ai-assistant.review.type.SCADA_SYMBOL'); + } + return aiThingWord(this.translate, view.entityType, 'ai-assistant.record.entity'); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts new file mode 100644 index 0000000000..3fc7f6fda4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts @@ -0,0 +1,330 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiLocale } from '@home/components/ai/ai-text'; +import { TB_IMAGE_PREFIX } from '@shared/models/resource.models'; +import { ReportTemplateService } from '@core/http/report-template.service'; +import { widgetType, widgetTypesData } from '@shared/models/widget.models'; +import { ReportTemplateType } from '@shared/models/report.models'; +import { inject, Injectable } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { forkJoin, Observable, of } from 'rxjs'; +import { catchError, map, switchMap } from 'rxjs/operators'; +import { EntityId } from '@shared/models/id/entity-id'; +import { baseDetailsPageByEntityType, EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { EntityService } from '@core/http/entity.service'; +import { CalculatedFieldsService } from '@core/http/calculated-fields.service'; +import { NotificationService } from '@core/http/notification.service'; +import { DeviceService } from '@core/http/device.service'; +import { DeviceProfileService } from '@core/http/device-profile.service'; +import { DashboardService } from '@core/http/dashboard.service'; +import { AlarmService } from '@core/http/alarm.service'; +import { AttributeService } from '@core/http/attribute.service'; +import { UserService } from '@core/http/user.service'; +import { IotHubApiService } from '@core/http/iot-hub-api.service'; +import { CalculatedFieldType } from '@shared/models/calculated-field.models'; +import { AttributeScope } from '@shared/models/telemetry/telemetry.models'; +import { AlarmInfo, AlarmSeverity, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { DeviceInfo } from '@shared/models/device.models'; +import { getEntityDetailsPageURL } from '@core/utils'; +import { aiDateText } from '@home/components/ai/ai-action-detail.models'; +import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-utils'; +import { HttpClient } from '@angular/common/http'; +import { AiRecordRef, AiRecordState, AiRecordView } from '@home/components/ai/ai-record.models'; + +const CONFIG: RequestConfig = {ignoreLoading: true, ignoreErrors: true}; + +const NOTIFICATION_PAGES: Partial> = { + [EntityType.NOTIFICATION_RULE]: '/notification/rules', + [EntityType.NOTIFICATION_TEMPLATE]: '/notification/templates', + [EntityType.NOTIFICATION_TARGET]: '/notification/recipients' +}; + +const PROFILE_TYPES = new Set([EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE]); + +const HUB_KINDS: Record = { + [ItemType.DEVICE]: EntityType.DEVICE, + [ItemType.WIDGET]: EntityType.WIDGET_TYPE, + [ItemType.CALCULATED_FIELD]: EntityType.CALCULATED_FIELD, + [ItemType.ALARM_RULE]: 'ALARM_RULE', + [ItemType.RULE_CHAIN]: EntityType.RULE_CHAIN, + [ItemType.SOLUTION_TEMPLATE]: 'SOLUTION_TEMPLATE' +}; + +export interface AiRecordLoadOptions { + image?: boolean; +} + +@Injectable({providedIn: 'root'}) +export class AiRecordLoaderService { + + private entityService = inject(EntityService); + private calculatedFieldsService = inject(CalculatedFieldsService); + private notificationService = inject(NotificationService); + private deviceService = inject(DeviceService); + private deviceProfileService = inject(DeviceProfileService); + private dashboardService = inject(DashboardService); + private alarmService = inject(AlarmService); + private attributeService = inject(AttributeService); + private userService = inject(UserService); + private iotHubApi = inject(IotHubApiService); + private translate = inject(TranslateService); + private http = inject(HttpClient); + private reportTemplateService = inject(ReportTemplateService); + + loadAll(refs: AiRecordRef[], options: AiRecordLoadOptions = {}): Observable { + if (!refs.length) { + return of([]); + } + return forkJoin(refs.map(ref => this.load(ref, options).pipe(catchError(() => of(null))))) + .pipe(map(views => views.filter(view => !!view))); + } + + load(ref: AiRecordRef, options: AiRecordLoadOptions = {}): Observable { + return 'versionId' in ref ? this.hub(ref.versionId) : this.entity({entityType: ref.entityType, id: ref.id} as EntityId, options); + } + + hub(versionId: string): Observable { + if (!this.iotHubApi.baseUrl) { + return of(null); + } + return this.iotHubApi.getVersionInfo(versionId, CONFIG).pipe(map(item => item ? this.hubView(item) : null)); + } + + hubView(item: MpItemVersionView): AiRecordView { + const typeKey = itemTypeTranslations.get(item.type); + const installs = item.totalInstallCount ?? item.installCount; + return { + key: `HUB:${item.id}`, + entityType: HUB_KINDS[item.type] ?? 'SOLUTION_TEMPLATE', + alarmRule: item.type === ItemType.ALARM_RULE, + name: item.name, + meta: '', + url: `/iot-hub/version/${item.id}`, + hub: { + type: typeKey ? this.translate.instant(typeKey) : item.type, + creator: item.creatorDisplayName || undefined, + verified: !!item.creatorVerified, + installs: installs ? this.translate.instant('ai-assistant.record.installs', {count: installs, shown: installs.toLocaleString(this.locale())}) : undefined + }, + hubItem: item, + description: item.description || undefined, + imageUrl: this.hubImage(item), + square: item.type === ItemType.DEVICE, + wide: item.type === ItemType.SOLUTION_TEMPLATE + }; + } + + entity(entity: EntityId, options: AiRecordLoadOptions = {}): Observable { + const entityType = entity.entityType as EntityType; + const key = `${entityType}:${entity.id}`; + const url = getEntityDetailsPageURL(entity.id, entityType) || undefined; + switch (entityType) { + case EntityType.DEVICE: + return this.deviceService.getDeviceInfo(entity.id, CONFIG).pipe(switchMap(device => this.device(key, url, device, options))); + case EntityType.DASHBOARD: + return this.dashboardService.getDashboard(entity.id, CONFIG).pipe(map(dashboard => { + const widgets = Object.keys(dashboard.configuration?.widgets ?? {}).length; + return { + key, entityType, alarmRule: false, name: dashboard.title, url, widgets, image: dashboard.image || undefined, + meta: this.meta(this.typeLabel(entityType), widgets ? this.translate.instant('ai-assistant.record.widgets', {count: widgets}) : null) + }; + })); + case EntityType.CALCULATED_FIELD: + return this.calculatedFieldsService.getCalculatedFieldById(entity.id, CONFIG).pipe(switchMap(field => { + const alarmRule = field.type === CalculatedFieldType.ALARM; + const type = this.translate.instant(alarmRule ? 'ai-assistant.review.type.ALARM_RULE' : 'entity.type-calculated-field'); + const view = (target?: string): AiRecordView => ({ + key, entityType, alarmRule, name: field.name, meta: this.meta(type, target), + url: alarmRule ? `/alarms/alarm-rules/${entity.id}` : `/calculatedFields/${entity.id}` + }); + const owner = field.entityId; + if (!owner?.id) { + return of(view()); + } + return this.entityService.getEntity(owner.entityType as EntityType, owner.id, CONFIG).pipe( + map(found => view(found?.name ? this.onTarget(owner.entityType, found.name) : undefined)), + catchError(() => of(view())) + ); + })); + case EntityType.ALARM: + return this.alarmService.getAlarmInfo(entity.id, CONFIG).pipe(map(alarm => this.alarm(key, alarm))); + case EntityType.USER: + return this.userService.getUser(entity.id, CONFIG).pipe(map(user => { + const name = [user.firstName, user.lastName].filter(Boolean).join(' ') || user.email; + const invited = user.additionalInfo?.userActivated === false; + return { + key, entityType, alarmRule: false, name, url, + meta: this.meta(this.typeLabel(entityType), name !== user.email ? user.email : null), + state: invited ? {tone: 'wait', label: this.translate.instant('ai-assistant.record.invited')} : undefined + }; + })); + case EntityType.ENTITY_GROUP: + return this.entityService.getEntity(entityType, entity.id, CONFIG).pipe(map(found => { + const group = found as {name?: string; type?: EntityType}; + if (!group?.name) { + return null; + } + const base = group.type ? baseDetailsPageByEntityType.get(group.type) : undefined; + const typeKey = group.type ? entityTypeTranslations.get(group.type)?.type : undefined; + return { + key, entityType, alarmRule: false, name: group.name, groupType: group.type, + url: base ? `${base.replace(/\/all$/, '/groups')}/${entity.id}` : undefined, + meta: typeKey ? this.translate.instant('ai-assistant.record.group-of', {type: this.translate.instant(typeKey)}) + : this.typeLabel(entityType) + }; + })); + case EntityType.NOTIFICATION_RULE: + return this.notificationService.getNotificationRuleById(entity.id, CONFIG) + .pipe(map(rule => this.simple(key, entityType, rule.name, NOTIFICATION_PAGES[entityType]))); + case EntityType.NOTIFICATION_TEMPLATE: + return this.notificationService.getNotificationTemplateById(entity.id, CONFIG) + .pipe(map(template => this.simple(key, entityType, template.name, NOTIFICATION_PAGES[entityType]))); + case EntityType.REPORT_TEMPLATE: + return this.reportTemplateService.getReportTemplateInfo(entity.id, CONFIG).pipe(map(template => ({ + key, entityType, alarmRule: false, name: template.name, url: `/reporting/templates/${entity.id}`, + badge: template.format, + meta: this.translate.instant(template.type === ReportTemplateType.SUB_REPORT ? 'ai-assistant.record.sub-report' : 'ai-assistant.record.report') + }))); + case EntityType.WIDGET_TYPE: + return this.http.get<{name: string; widgetType?: string; image?: string; description?: string}>(`/api/widgetTypeInfo/${entity.id}`, + defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(info => ({ + key, entityType, alarmRule: false, name: info.name, url: `/resources/widgets-library/widget-types/${entity.id}`, + image: info.image || undefined, description: info.description || undefined, + meta: info.widgetType && widgetTypesData.get(info.widgetType as widgetType) + ? this.translate.instant(widgetTypesData.get(info.widgetType as widgetType).name) : undefined + }))); + case EntityType.TB_RESOURCE: + return this.http.get<{title: string; resourceType?: string; resourceSubType?: string; link?: string}>(`/api/resource/info/${entity.id}`, + defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(info => { + if (info.resourceType !== 'IMAGE' || !info.link) { + return this.simple(key, entityType, info.title, undefined); + } + const symbol = info.resourceSubType === 'SCADA_SYMBOL'; + const path = info.link.replace(/^\/api\/images\//, ''); + return { + key, entityType: symbol ? 'SCADA_SYMBOL' : entityType, alarmRule: false, name: info.title, + url: symbol ? `/resources/scada-symbols/${path}` : '/resources/images', + image: TB_IMAGE_PREFIX + info.link, + meta: this.translate.instant(symbol ? 'ai-assistant.review.type.SCADA_SYMBOL' : 'ai-assistant.review.type.IMAGE') + }; + })); + case EntityType.WIDGETS_BUNDLE: + return this.http.get<{title: string}>(`/api/widgetsBundle/${entity.id}`, defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(bundle => ({ + key, entityType, alarmRule: false, name: bundle.title, url: `/resources/widgets-library/widgets-bundles/${entity.id}`, meta: undefined + }))); + case EntityType.REPORT: + return this.http.get<{name: string; format?: string; templateInfo?: {name?: string}}>(`/api/v2/report/${entity.id}`, defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(report => ({ + key, entityType, alarmRule: false, name: report.name, url: '/reporting/reports', badge: report.format, + meta: report.templateInfo?.name + }))); + case EntityType.SCHEDULER_EVENT: + return this.http.get<{name: string; type?: string}>(`/api/schedulerEvent/${entity.id}`, defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(event => { + const report = event.type === 'generateReport' || event.type === 'generateDashboardReport'; + return { + key, entityType, alarmRule: false, name: event.name, url: report ? '/reporting/scheduling' : url, + meta: report ? this.translate.instant('ai-assistant.record.scheduled-report') : undefined + }; + })); + default: + return this.entityService.getEntity(entityType, entity.id, CONFIG).pipe(map(found => { + const view = this.simple(key, entityType, found?.name ?? (found as {title?: string})?.title, NOTIFICATION_PAGES[entityType] ?? url); + const subtype = (found as {type?: string})?.type; + if (view && subtype && (entityType === EntityType.ASSET || entityType === EntityType.ENTITY_VIEW)) { + view.meta = this.meta(view.meta, subtype); + } + return view; + })); + } + } + + private device(key: string, url: string, device: DeviceInfo, options: AiRecordLoadOptions): Observable { + const gateway = !!device.additionalInfo?.gateway; + const view: AiRecordView = { + key, entityType: gateway ? 'GATEWAY' : EntityType.DEVICE, alarmRule: false, name: device.name, url, + meta: this.meta(this.translate.instant(gateway ? 'ai-assistant.record.gateway' : 'entity.type-device'), device.type), + square: true + }; + const activity = device.active ? of(true) : this.attributeService.getEntityAttributes(device.id, AttributeScope.SERVER_SCOPE, ['lastActivityTime'], CONFIG) + .pipe( + map(attributes => Number(attributes?.find(attribute => attribute.key === 'lastActivityTime')?.value) > 0), + switchMap(seen => seen ? of(true) : this.http.get(`/api/plugins/telemetry/DEVICE/${device.id.id}/keys/timeseries`, + defaultHttpOptionsFromConfig(CONFIG)).pipe(map(keys => !!keys?.length))), + catchError(() => of(true)) + ); + const image = options.image && device.deviceProfileId?.id + ? this.deviceProfileService.getDeviceProfileInfo(device.deviceProfileId.id, CONFIG).pipe(map(profile => profile?.image || undefined), catchError(() => of(undefined))) + : of(undefined); + return forkJoin([activity, image]).pipe(map(([seen, picture]) => ({ + ...view, + image: picture, + state: this.deviceState(device.active, seen, gateway) + }))); + } + + private deviceState(active: boolean, seen: boolean, gateway: boolean): AiRecordState { + if (active) { + return {tone: 'ok', label: this.translate.instant('ai-assistant.record.active')}; + } + if (!seen) { + return {tone: 'wait', label: this.translate.instant(gateway ? 'ai-assistant.record.waiting-connect' : 'ai-assistant.record.waiting-data')}; + } + return {tone: 'off', label: this.translate.instant('ai-assistant.record.inactive')}; + } + + private alarm(key: string, alarm: AlarmInfo): AiRecordView { + const severity = alarm.severity ?? AlarmSeverity.INDETERMINATE; + const word = this.translate.instant(alarmSeverityTranslations.get(severity) ?? severity); + const tip = [word, this.translate.instant(alarm.cleared ? 'ai-assistant.record.cleared' : 'ai-assistant.record.alarm-active').toLowerCase(), + this.translate.instant(alarm.acknowledged ? 'ai-assistant.record.acknowledged' : 'ai-assistant.record.not-acknowledged').toLowerCase()].join(', '); + const when = alarm.cleared && alarm.clearTs + ? this.translate.instant('ai-assistant.record.cleared-at', {time: this.time(alarm.clearTs)}) + : alarm.startTs ? this.translate.instant('ai-assistant.record.since', {time: this.time(alarm.startTs)}) : null; + return { + key, entityType: EntityType.ALARM, alarmRule: false, name: alarm.type, + meta: this.meta(alarm.originatorName, when), + url: '/alarms', + alarm: {severity, cleared: !!alarm.cleared, acknowledged: !!alarm.acknowledged, tip} + }; + } + + private hubImage(item: MpItemVersionView): string | undefined { + if (!item.image) { + return undefined; + } + const [path, query] = item.image.split('?'); + const preview = path.endsWith('/preview') ? path : `${path}/preview`; + return this.iotHubApi.resolveResourceUrl(query ? `${preview}?${query}` : preview); + } + + private simple(key: string, entityType: EntityType, name: string, url?: string): AiRecordView | null { + return name ? {key, entityType, alarmRule: false, name, meta: this.typeLabel(entityType), url} : null; + } + + private onTarget(entityType: string, name: string): string { + return this.translate.instant(PROFILE_TYPES.has(entityType) ? 'ai-assistant.record.on-profile' : 'ai-assistant.record.on', {name}); + } + + private meta(...parts: Array): string { + return parts.filter(part => !!part).join(' · '); + } + + private typeLabel(entityType: EntityType): string { + const translation = entityTypeTranslations.get(entityType)?.type; + return translation ? this.translate.instant(translation) : entityType; + } + + private locale(): string | undefined { + return aiLocale(this.translate.currentLang); + } + + private time(ts: number): string { + return aiDateText(new Date(ts), this.locale()); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts new file mode 100644 index 0000000000..48c327ed29 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { AiAlarmState, AiHubMeta, AiRecordState } from '@home/components/ai/ai-record.models'; + +export { AiRecordState } from '@home/components/ai/ai-record.models'; + +@Component({ + selector: 'tb-ai-record', + template: ` + + @if (url()) { + {{ name() }} + } @else { + {{ name() }} + } + @if (badge(); as label) { + {{ label }} + } + @if (hub(); as listing) { + + + {{ listing.type }}@if (listing.creator) {{{ listing.type ? ' · ' : '' }}{{ listing.creator }}}@if (listing.verified) {}@if (listing.installs) { · {{ listing.installs }}} + + } @else if (meta()) { + {{ meta() }} + } + @if (alarm(); as current) { + + {{ (current.cleared ? 'ai-assistant.record.cleared' : 'alarm.severity-' + current.severity.toLowerCase()) | translate }} + @if (current.acknowledged) { + + } + + } @else if (state(); as current) { + {{ current.label }} + } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'tb-rec line', + '[attr.data-pal]': 'kind().palette' + } +}) +export class AiRecordComponent { + + entityType = input.required(); + + alarmRule = input(false); + groupType = input(undefined); + + name = input.required(); + + meta = input(); + + badge = input(); + + url = input(); + + state = input(); + + alarm = input(); + + hub = input(); + + kind = computed(() => aiEntityKind(this.entityType(), this.alarmRule(), this.groupType())); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts new file mode 100644 index 0000000000..d8d7308ec2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiTrueMinus } from '@home/components/ai/ai-text'; +import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; + +export const SHOW_RECORDS_TOOL = 'show_records'; + +export const MAX_SHOWN_RECORDS = 20; + +export interface AiRecordState { + tone: 'ok' | 'off' | 'warn' | 'wait'; + label: string; +} + +export interface AiAlarmState { + severity: string; + cleared: boolean; + acknowledged: boolean; + tip: string; +} + +export interface AiHubMeta { + type: string; + creator?: string; + verified?: boolean; + installs?: string; +} + +export interface AiRecordFact { + label: string; + value: string; +} + +export interface AiRecordView { + key: string; + entityType: string; + alarmRule: boolean; + groupType?: string; + name: string; + meta: string; + badge?: string; + url?: string; + state?: AiRecordState; + alarm?: AiAlarmState; + hub?: AiHubMeta; + hubItem?: MpItemVersionView; + description?: string; + image?: string; + imageUrl?: string; + widgets?: number; + square?: boolean; + wide?: boolean; +} + +export type AiRecordRef = {versionId: string} | {entityType: string; id: string}; + +export interface AiShownRecords { + refs: AiRecordRef[]; + facts: AiRecordFact[]; + note?: string; +} + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +const text = (value: unknown): string | null => typeof value === 'string' && value.trim() ? value.trim() : null; + +export function aiRecordKey(ref: AiRecordRef): string { + return 'versionId' in ref ? `HUB:${ref.versionId}` : `${ref.entityType}:${ref.id}`; +} + +export function aiShownRecordsOf(args: unknown): AiShownRecords | null { + const given = (args as {records?: unknown})?.records; + if (!Array.isArray(given)) { + return null; + } + const seen = new Set(); + const refs: AiRecordRef[] = []; + given.forEach(item => { + const versionId = text(item?.iotHubVersionId); + const id = text(item?.id); + const entityType = text(item?.entityType)?.toUpperCase(); + const ref: AiRecordRef | null = versionId && UUID.test(versionId) ? {versionId} + : id && entityType && UUID.test(id) ? {entityType: entityType === 'ALARM_RULE' ? 'CALCULATED_FIELD' : entityType, id} : null; + if (ref && !seen.has(aiRecordKey(ref))) { + seen.add(aiRecordKey(ref)); + refs.push(ref); + } + }); + if (!refs.length) { + return null; + } + const single = refs.length === 1; + const rawFacts = (args as {facts?: unknown})?.facts; + const facts = single && Array.isArray(rawFacts) + ? rawFacts.map(fact => ({label: text(fact?.label), value: text(fact?.value)})) + .filter(fact => fact.label && fact.value).slice(0, 4) as AiRecordFact[] + : []; + const note = single ? text((args as {note?: unknown})?.note) ?? undefined : undefined; + return {refs: refs.slice(0, MAX_SHOWN_RECORDS), facts, note}; +} + +export function aiFactParts(value: string): Array<{text: string; code: boolean}> { + return value.split(/(`[^`]+`)/).filter(part => part.length) + .map(part => part.length > 2 && part.startsWith('`') && part.endsWith('`') ? {text: part.slice(1, -1), code: true} + : {text: aiTrueMinus(part), code: false}); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts new file mode 100644 index 0000000000..ac27ede19d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, input, output, signal, untracked } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { TranslateService } from '@ngx-translate/core'; +import { Subscription, timer } from 'rxjs'; +import { concatMap, take, takeWhile } from 'rxjs/operators'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { aiRecordKey, AiRecordView, AiShownRecords } from '@home/components/ai/ai-record.models'; +import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; +import { AiCardAction } from '@home/components/ai/ai-card-actions.component'; +import { AiRecordPrimary } from '@home/components/ai/ai-record-card.component'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; + +const LIST_SHOWN = 8; + +const TARGETED_HUB_TYPES = new Set([ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE]); + +const WAIT_RECHECK_MS = 10000; +const WAIT_RECHECKS = 90; + +@Component({ + selector: 'tb-ai-records', + template: ` + @if (views().length === 1 && single(); as rec) { + + } @else if (views().length > 1) { +
+ + @if (listOpen()) { +
+ @for (rec of shownViews(); track rec.key) { + + } + @if (views().length > LIST_SHOWN) { + + } +
+ } +
+ } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiRecordsComponent { + + shown = input.required(); + + compose = output(); + + made = input([]); + + views = signal([]); + + allShown = signal(false); + + private listToggled = signal(null); + + listOpen = computed(() => this.listToggled() ?? true); + + toggleList(): void { + this.listToggled.set(!this.listOpen()); + } + + readonly LIST_SHOWN = LIST_SHOWN; + + single = computed(() => this.views()[0] ?? null); + + primary = computed(() => { + const single = this.single(); + if (single?.hubItem) { + return 'install'; + } + return single && this.made().includes(single.key) ? 'open' : null; + }); + + cardActions = computed(() => { + const item = this.single()?.hubItem; + if (!item || !TARGETED_HUB_TYPES.has(item.type)) { + return []; + } + return [{ + id: 'install-on', icon: 'edit', label: this.translate.instant('ai-assistant.record.install-on'), + compose: this.translate.instant('ai-assistant.record.install-on-prompt', {name: item.name}) + }]; + }); + + shownViews = computed(() => this.allShown() ? this.views() : this.views().slice(0, LIST_SHOWN)); + + sameKind = computed(() => new Set(this.views().map(view => this.kindKey(view))).size === 1); + + listKind = computed(() => this.sameKind() && this.views().length ? aiEntityKind(this.views()[0].entityType, this.views()[0].alarmRule, this.views()[0].groupType) : null); + + listLabel = computed(() => { + const views = this.views(); + if (views.every(view => !!view.hub)) { + return this.translate.instant('ai-assistant.record.hub-items', {count: views.length}); + } + if (!this.sameKind()) { + return this.translate.instant('ai-assistant.summary.entities', {count: views.length}); + } + const view = views[0]; + const plural = view.alarmRule ? 'ai-assistant.summary.alarm-rules' + : view.entityType === 'GATEWAY' ? 'ai-assistant.record.gateways' : entityTypeTranslations.get(view.entityType as EntityType)?.typePlural; + return plural ? `${views.length} ${this.translate.instant(plural).toLowerCase()}` : this.translate.instant('ai-assistant.summary.entities', {count: views.length}); + }); + + private loader = inject(AiRecordLoaderService); + private translate = inject(TranslateService); + private destroyRef = inject(DestroyRef); + private loading: Subscription; + + private key = computed(() => this.shown().refs.map(aiRecordKey).join(',')); + + constructor() { + effect(() => { + this.key(); + const shown = untracked(() => this.shown()); + this.loading?.unsubscribe(); + this.loading = timer(0, WAIT_RECHECK_MS).pipe( + take(WAIT_RECHECKS), + concatMap(() => this.loader.loadAll(shown.refs, {image: shown.refs.length === 1})), + takeWhile(views => views.some(view => view.state?.tone === 'wait'), true), + takeUntilDestroyed(this.destroyRef) + ).subscribe(views => this.views.set(views)); + }); + } + + lineMeta(view: AiRecordView): string { + if (view.hub) { + return view.meta; + } + const parts = view.meta.split(' · '); + return parts.length > 1 ? parts.slice(1).join(' · ') : ''; + } + + private kindKey(view: AiRecordView): string { + return view.hub ? 'HUB:' + view.entityType + view.alarmRule : view.alarmRule ? 'ALARM_RULE' : view.entityType; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-references.ts b/ui-ngx/src/app/modules/home/components/ai/ai-references.ts new file mode 100644 index 0000000000..39379705b6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-references.ts @@ -0,0 +1,401 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { SEVERITY_MARK } from '@home/components/ai/ai-text'; +import { AiFile, aiFileMark, aiFileName } from '@home/components/ai/ai-file.models'; +import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { aiSevMarkElement } from '@home/components/ai/ai-sev-mark.component'; + +export interface AiReference { + name: string; + entityType: string; + id: string; +} + +const SKIP = 'code, pre, a, .tb-chiplink, .k-ent'; + +export function decorateReferences(root: HTMLElement, references: AiReference[] | undefined): void { + if (!references?.length) { + return; + } + const linkable = references + .filter(reference => reference.name?.trim().length >= 3) + .sort((a, b) => b.name.length - a.name.length); + if (!linkable.length) { + return; + } + const pattern = new RegExp(`(? escape(reference.name)).join('|')})(?![\\p{L}\\p{N}_])`, 'u'); + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: node => node.parentElement?.closest(SKIP) || !node.textContent?.trim() ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT + }); + const nodes: Text[] = []; + while (walker.nextNode()) { + nodes.push(walker.currentNode as Text); + } + nodes.forEach(node => replaceIn(node, pattern, linkable)); +} + +const PLAIN_WORD = /^\p{Ll}+$/u; +const QUOTE_OPEN = /["'“‘«]$/u; +const QUOTE_CLOSE = /^["'”’»]/u; + +function replaceIn(node: Text, pattern: RegExp, references: AiReference[]): void { + let rest = node.textContent ?? ''; + let match = pattern.exec(rest); + if (!match) { + return; + } + const fragment = document.createDocumentFragment(); + while (match) { + if (match.index > 0) { + fragment.append(rest.slice(0, match.index)); + } + const reference = references.find(item => item.name === match[1]); + const before = rest.slice(0, match.index); + const after = rest.slice(match.index + match[1].length); + const standsAsName = !reference || !PLAIN_WORD.test(reference.name) + || (node.textContent ?? '').trim() === reference.name || (QUOTE_OPEN.test(before) && QUOTE_CLOSE.test(after)); + fragment.append(reference && standsAsName ? chip(reference) : match[1]); + rest = after; + match = pattern.exec(rest); + } + if (rest) { + fragment.append(rest); + } + node.replaceWith(fragment); +} + +const SVG_ICONS = new Map>(); + +function svgIcon(name: string): Promise { + let icon = SVG_ICONS.get(name); + if (!icon) { + const [namespace, file] = name.split(':'); + icon = namespace !== 'mdi' || !/^[a-z0-9-]+$/.test(file) ? Promise.resolve(null) + : fetch(`./assets/mdi/${file}.svg`).then(response => response.ok ? response.text() : '').then(text => { + const svg = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement; + return svg?.nodeName === 'svg' ? svg as unknown as SVGElement : null; + }).catch(() => null); + SVG_ICONS.set(name, icon); + } + return icon; +} + +function aiIconElement(name: string, className: string): HTMLElement { + const icon = document.createElement('span'); + icon.setAttribute('aria-hidden', 'true'); + if (!name.includes(':')) { + icon.className = 'mat-icon notranslate material-icons mat-ligature-font ' + className; + icon.textContent = name; + return icon; + } + icon.className = 'mat-icon notranslate ' + className; + svgIcon(name).then(svg => { + if (svg) { + const copy = svg.cloneNode(true) as SVGElement; + copy.setAttribute('width', '100%'); + copy.setAttribute('height', '100%'); + copy.setAttribute('fill', 'currentColor'); + copy.setAttribute('focusable', 'false'); + icon.replaceChildren(copy); + } + }); + return icon; +} + +const REFERENCE_PAGES: Record = { + ALARM_RULE: '/alarms/alarm-rules', + EDGE_RULE_CHAIN: '/edgeManagement/templates/ruleChains' +}; + +function chip(reference: AiReference): HTMLElement { + const kind = aiEntityKind(reference.entityType); + const code = document.createElement('code'); + code.className = 'k-ent'; + code.dataset.pal = kind.palette; + code.append(aiIconElement(kind.icon, 'k-ent-ic'), reference.name); + const base = REFERENCE_PAGES[reference.entityType] ?? baseDetailsPageByEntityType.get(reference.entityType as EntityType); + if (!base || !reference.id) { + return code; + } + const link = document.createElement('a'); + link.className = 'tb-chiplink'; + link.href = `${base}/${reference.id}`; + code.append(chipChevron()); + link.append(code); + return link; +} + +export function chipChevron(): HTMLElement { + const chevron = document.createElement('span'); + chevron.className = 'mat-icon notranslate material-icons mat-ligature-font tb-chip-go'; + chevron.setAttribute('aria-hidden', 'true'); + chevron.textContent = 'chevron_right'; + return chevron; +} + +function escape(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +export function decorateLinks(root: HTMLElement, newTab: string): void { + root.querySelectorAll('a[href]:not(.tb-chiplink)').forEach(link => { + if (link.closest('pre, code') || link.origin === location.origin || !/^https?:$/.test(link.protocol)) { + return; + } + link.target = '_blank'; + link.rel = 'noopener noreferrer'; + if (link.querySelector('.k-ext')) { + return; + } + const last = lastText(link); + const tail = document.createElement('span'); + tail.className = 'k-ext-tail'; + if (last) { + const text = last.textContent ?? ''; + const cut = text.trimEnd().lastIndexOf(' ') + 1; + tail.append(text.slice(cut)); + last.textContent = text.slice(0, cut); + last.after(tail); + } else { + link.append(tail); + } + const icon = document.createElement('span'); + icon.className = 'mat-icon notranslate material-icons mat-ligature-font k-ext'; + icon.setAttribute('aria-hidden', 'true'); + icon.textContent = 'north_east'; + tail.append(icon); + const hidden = document.createElement('span'); + hidden.className = 'tb-ai-sr-only'; + hidden.textContent = ' ' + newTab; + link.append(hidden); + }); +} + +function lastText(root: Node): Text | null { + for (let node = root.lastChild; node; node = node.previousSibling) { + if (node.nodeType === Node.TEXT_NODE) { + if (node.textContent?.trim()) { + return node as Text; + } + } else { + const found = lastText(node); + if (found) { + return found; + } + } + } + return null; +} + +const SEVERITY_SKIP = 'code, pre, a, table, .k-sev, .tb-chiplink, .tb-rec, tb-ai-record, tb-ai-records'; +const MARK_SKIP = 'code, pre, a, .k-sev, .tb-chiplink'; + +function aiHasSeverityMarks(text: string | undefined): boolean { + return !!text && SEVERITY_MARK.test(text); +} + +function severityChip(severity: string, label: (severity: string) => string): HTMLElement { + const chip = document.createElement('span'); + chip.className = 'k-sev ' + severity.toLowerCase(); + chip.append(aiSevMarkElement(severity), label(severity)); + return chip; +} + +function textNodes(root: HTMLElement, skip: string): Text[] { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: node => node.parentElement?.closest(skip) || !node.textContent?.trim() ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT + }); + const nodes: Text[] = []; + while (walker.nextNode()) { + nodes.push(walker.currentNode as Text); + } + return nodes; +} + +function replaceMatches(node: Text, pattern: RegExp, chip: (match: RegExpExecArray) => Node | null): void { + let rest = node.textContent ?? ''; + let match = pattern.exec(rest); + if (!match) { + return; + } + const fragment = document.createDocumentFragment(); + while (match) { + if (match.index > 0) { + fragment.append(rest.slice(0, match.index)); + } + fragment.append(chip(match) ?? match[0]); + rest = rest.slice(match.index + match[0].length); + match = pattern.exec(rest); + } + if (rest) { + fragment.append(rest); + } + node.replaceWith(fragment); +} + +export function decorateSeverities(root: HTMLElement, severities: string[] | undefined, label: (severity: string) => string): void { + if (aiHasSeverityMarks(root.textContent ?? '')) { + const lone = new RegExp('^\\s*' + SEVERITY_MARK.source + '\\s*$'); + root.querySelectorAll('code').forEach(code => { + const match = !code.closest('pre') ? lone.exec(code.textContent ?? '') : null; + if (match) { + code.replaceWith(severityChip(match[1], label)); + } + }); + textNodes(root, MARK_SKIP).forEach(node => replaceMatches(node, SEVERITY_MARK, match => severityChip(match[1], label))); + decorateAlarmTables(root); + return; + } + if (!severities?.length) { + return; + } + const pattern = new RegExp(`(? severity.toLowerCase()).join('|')})(?![\\p{L}\\p{N}_])`, 'iu'); + const chipped = new Set(); + textNodes(root, SEVERITY_SKIP).forEach(node => replaceMatches(node, pattern, match => { + const severity = match[1].toUpperCase(); + if (chipped.has(severity)) { + return null; + } + chipped.add(severity); + return severityChip(severity, label); + })); +} + +function decorateAlarmTables(root: HTMLElement): void { + root.querySelectorAll('table').forEach(table => { + const rows = Array.from(table.querySelectorAll('tbody tr')); + const columns = table.querySelectorAll('thead th').length; + if (columns < 4 || !rows.length || !rows.every(row => row.children[2]?.querySelector('.k-sev'))) { + return; + } + table.classList.add('k-alarms'); + rows.forEach(row => { + const [alarm, device] = [row.children[0] as HTMLElement, row.children[1] as HTMLElement]; + if (!alarm.querySelector('.k-cell-meta') && device?.textContent?.trim()) { + const meta = document.createElement('span'); + meta.className = 'k-cell-meta'; + meta.append(...Array.from(device.childNodes).map(node => node.cloneNode(true))); + alarm.append(meta); + } + }); + }); +} + +const HINT_KINDS: Record = { + note: {kind: 'note', icon: 'info_outline'}, + tip: {kind: 'tip', icon: 'lightbulb_outline'}, + 'heads-up': {kind: 'heads-up', icon: 'outlined_flag'} +}; + +export function decorateHints(root: HTMLElement): void { + root.querySelectorAll('blockquote').forEach(quote => { + const paragraph = quote.querySelector('p') ?? quote; + const first = paragraph.firstChild; + const match = first?.nodeType === Node.TEXT_NODE ? /^\s*(note|tip|heads-up)\s*:\s*/i.exec(first.textContent ?? '') : null; + if (!match) { + return; + } + const hint = HINT_KINDS[match[1].toLowerCase()]; + first.textContent = (first.textContent ?? '').slice(match[0].length); + const box = document.createElement('div'); + box.className = 'k-hint agent-hint ' + hint.kind; + const icon = document.createElement('mat-icon'); + icon.className = 'mat-icon material-icons mat-icon-no-color'; + icon.setAttribute('aria-hidden', 'true'); + icon.textContent = hint.icon; + const text = document.createElement('span'); + paragraph.querySelectorAll('strong').forEach(strong => { + const lead = document.createElement('b'); + lead.append(...Array.from(strong.childNodes)); + strong.replaceWith(lead); + }); + text.append(...Array.from(paragraph.childNodes)); + box.append(icon, text); + quote.replaceWith(box); + }); +} + +const VALUE_CODE = /^([^:\n]{1,60}):\s+(.+)$/; +const NUMBER = /^([-−]?\d+(?:\.\d+)?)(.*)$/; + +export function decorateValues(root: HTMLElement, readings: Array<{key: string; values: string[]}> | undefined): void { + if (!readings?.length) { + return; + } + root.querySelectorAll('code').forEach(code => { + if (code.closest('pre, a, .k-ent, .k-tel') || code.children.length) { + return; + } + const match = VALUE_CODE.exec(code.textContent?.trim() ?? ''); + const reading = match ? readings.find(item => item.key === match[1].trim()) : undefined; + if (!match || !reading) { + return; + } + const written = match[2].trim(); + const number = NUMBER.exec(written); + let value: string; + let unit = ''; + if (number && reading.values.some(item => Number(item) === Number(number[1].replace('−', '-')))) { + value = number[1].replace('-', '−'); + unit = number[2].trim(); + } else if (reading.values.includes(written)) { + value = written; + } else { + return; + } + const chip = document.createElement('span'); + chip.className = 'k-tel'; + const key = document.createElement('code'); + key.className = 'k-tel-key'; + key.textContent = reading.key; + const shown = document.createElement('span'); + shown.className = 'k-tel-val'; + shown.append(value); + if (unit) { + const unitEl = document.createElement('span'); + unitEl.className = 'k-tel-unit'; + unitEl.textContent = unit; + shown.append(unitEl); + } + chip.append(key, shown); + code.replaceWith(chip); + }); +} + +export function decorateFileChips(root: HTMLElement, files: ReadonlyMap, shown: string | null): void { + if (!files.size) { + return; + } + root.querySelectorAll('code').forEach(code => { + if (code.closest('pre, a, .k-ent, .k-tel, .art-chip') || code.children.length) { + return; + } + const file = files.get(code.textContent?.trim() ?? ''); + if (!file) { + return; + } + const chip = document.createElement('button'); + chip.type = 'button'; + chip.className = 'art-chip' + (file.name === shown ? ' on' : ''); + chip.dataset.file = file.name; + chip.setAttribute('aria-pressed', String(file.name === shown)); + chip.setAttribute('aria-label', `${file.name}, ${file.lines} · ${file.size}`); + const icon = document.createElement('span'); + icon.className = 'mat-icon notranslate material-icons-round mat-ligature-font'; + icon.setAttribute('aria-hidden', 'true'); + icon.textContent = aiFileMark(file); + const parts = aiFileName(file.name); + const name = document.createElement('span'); + name.className = 'art-name'; + name.textContent = parts.base; + if (parts.ext) { + const ext = document.createElement('span'); + ext.className = 'art-ext'; + ext.textContent = parts.ext; + name.append(ext); + } + chip.append(icon, name); + code.replaceWith(chip); + }); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.html deleted file mode 100644 index 641c9b706a..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.html +++ /dev/null @@ -1,33 +0,0 @@ - - -

{{ data.title }}

- - -
-
- - - -
-
- - -
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.ts deleted file mode 100644 index 304fa2d4e2..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.ts +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Inject } from '@angular/core'; -import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; -import { DialogComponent } from '@shared/components/dialog.component'; -import { AppState } from '@core/core.state'; -import { Router } from '@angular/router'; -import { Store } from '@ngrx/store'; -import { FormBuilder, Validators } from '@angular/forms'; - -export interface AiRenameDialogData { - title: string; - value: string; -} - -@Component({ - selector: 'tb-input-dialog', - templateUrl: './ai-rename-dialog.component.html', - styles: ':host{min-width: 100%;max-width: 100%;width: 420px;display: grid;grid-template-rows: min-content minmax(auto, 1fr) min-content;height: 100%}', - standalone: false -}) -export class AiRenameDialogComponent extends DialogComponent { - - valueControl = this.fb.control('', [Validators.required]); - - constructor(protected store: Store, - protected router: Router, - public dialogRef: MatDialogRef, - @Inject(MAT_DIALOG_DATA) public data: AiRenameDialogData, - private fb: FormBuilder) { - super(store, router, dialogRef); - this.valueControl.patchValue(data.value || ''); - } - - cancel(): void { - this.dialogRef.close(null); - } - - confirm(): void { - this.dialogRef.close(this.valueControl.value.trim()); - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts new file mode 100644 index 0000000000..3d512d4cf3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts @@ -0,0 +1,114 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { TranslateService } from '@ngx-translate/core'; +import { Subscription } from 'rxjs'; +import { EntityId } from '@shared/models/id/entity-id'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { AiRecordView } from '@home/components/ai/ai-record.models'; +import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; + +const LEAD_TYPES = new Set([EntityType.DASHBOARD, EntityType.WIDGET_TYPE, 'SCADA_SYMBOL']); + +@Component({ + selector: 'tb-ai-run-summary', + template: ` + @if (lead(); as card) { + + } + @if (rest().length > 1) { +
+ + @if (listOpen()) { +
+ @for (row of shownRows(); track row.key) { + + } + @if (rest().length > LIST_SHOWN) { + + } +
+ } +
+ } @else if (rest().length) { +
+ @for (row of rest(); track row.key) { + + } +
+ } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiRunSummaryComponent { + + entities = input.required(); + leadMeta = input(null); + + rows = signal([]); + + lead = computed(() => this.rows().find(row => LEAD_TYPES.has(row.entityType) && !!row.url) ?? null); + + rest = computed(() => this.rows().filter(row => row !== this.lead())); + + readonly LIST_SHOWN = 8; + + private listToggled = signal(null); + + allShown = signal(false); + + listOpen = computed(() => this.listToggled() ?? this.rest().length <= 3); + + shownRows = computed(() => this.allShown() ? this.rest() : this.rest().slice(0, this.LIST_SHOWN)); + + listKind = computed(() => { + const kinds = new Set(this.rest().map(row => row.alarmRule ? 'ALARM_RULE' : row.entityType)); + return kinds.size === 1 ? aiEntityKind([...kinds][0]) : null; + }); + + listLabel = computed(() => { + const rows = this.rest(); + const kinds = new Set(rows.map(row => row.alarmRule ? 'ALARM_RULE' : row.entityType)); + if (kinds.size !== 1) { + return this.translate.instant('ai-assistant.summary.entities', {count: rows.length}); + } + const kind = [...kinds][0]; + const plural = kind === 'ALARM_RULE' ? 'ai-assistant.summary.alarm-rules' : entityTypeTranslations.get(kind as EntityType)?.typePlural; + return plural ? `${rows.length} ${this.translate.instant(plural).toLowerCase()}` : this.translate.instant('ai-assistant.summary.entities', {count: rows.length}); + }); + + toggleList(): void { + this.listToggled.set(!this.listOpen()); + } + + private key = computed(() => this.entities().map(entity => `${entity.entityType}:${entity.id}`).join(',')); + + private loader = inject(AiRecordLoaderService); + private translate = inject(TranslateService); + private destroyRef = inject(DestroyRef); + + private loading: Subscription; + + constructor() { + effect(() => { + this.key(); + const entities = untracked(() => this.entities()); + this.loading?.unsubscribe(); + this.loading = this.loader.loadAll(entities.map(entity => ({entityType: entity.entityType, id: entity.id}))) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(rows => this.rows.set(rows)); + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html new file mode 100644 index 0000000000..cf6c0da3dd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html @@ -0,0 +1,19 @@ + +
+ + + + +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.ts new file mode 100644 index 0000000000..e7198963f6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.ts @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, input, model, output, signal } from '@angular/core'; +import { AiQuestion } from '@shared/models/solution-creator.models'; + +@Component({ + selector: 'tb-ai-secret-field', + templateUrl: './ai-secret-field.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiSecretFieldComponent { + + question = input.required(); + value = model(''); + enter = output(); + + readonly shown = signal(false); + readonly ready = computed(() => !!this.value()); + + toggle(field: HTMLInputElement): void { + this.shown.update(shown => !shown); + field.focus(); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-sev-mark.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-sev-mark.component.ts new file mode 100644 index 0000000000..2e01d13b07 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-sev-mark.component.ts @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, input } from '@angular/core'; +import { AlarmSeverity } from '@shared/models/alarm.models'; + +const TRIANGLE = 'M6 1.3c.33 0 .64.18.8.47l4.75 8.4c.33.58-.09 1.3-.76 1.3H1.21c-.67 0-1.09-.72-.76-1.3l4.75-8.4c.16-.29.47-.47.8-.47z'; + +const MARKS: Record = { + CRITICAL: ``, + MAJOR: ``, + MINOR: '', + WARNING: '', + INDETERMINATE: '' +}; + +export function aiSevMarkElement(severity: string): HTMLElement { + const mark = document.createElement('span'); + mark.className = 'tb-sev-mark ' + severity.toLowerCase(); + mark.setAttribute('aria-hidden', 'true'); + mark.innerHTML = ``; + return mark; +} + +@Component({ + selector: 'tb-ai-sev-mark', + template: ` + + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + '[class]': '"tb-sev-mark " + (severity() ?? "").toLowerCase()', + 'aria-hidden': 'true' + } +}) +export class AiSevMarkComponent { + + severity = input(); + + readonly triangle = 'M6 1.3c.33 0 .64.18.8.47l4.75 8.4c.33.58-.09 1.3-.76 1.3H1.21c-.67 0-1.09-.72-.76-1.3l4.75-8.4c.16-.29.47-.47.8-.47z'; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-shortcuts-dialog.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-shortcuts-dialog.component.ts new file mode 100644 index 0000000000..ece7cfd02b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-shortcuts-dialog.component.ts @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component } from '@angular/core'; + +interface ShortcutRow { + label: string; + keys: string[][]; +} + +const MOD = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl'; + +@Component({ + selector: 'tb-ai-shortcuts-dialog', + template: ` +
+

{{ 'ai-assistant.keys.title' | translate }}

+ +
+
+ @for (group of groups; track group.title) { +
+

{{ group.title | translate }}

+ @for (row of group.rows; track row.label) { +
+ {{ row.label | translate }} + + @for (keys of row.keys; track $index) { + + @for (key of keys; track $index) { + {{ key }} + } + + } + +
+ } +
+ } +
+ `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'k-keys-dialog', + 'data-ai': '' + } +}) +export class AiShortcutsDialogComponent { + + readonly groups: Array<{title: string; rows: ShortcutRow[]}> = [ + { + title: 'ai-assistant.keys.composer', + rows: [ + {label: 'ai-assistant.send', keys: [['Enter'], [MOD, 'Enter']]}, + {label: 'ai-assistant.new-line', keys: [['Shift', 'Enter']]}, + {label: 'ai-assistant.accept-suggestion', keys: [['Tab']]}, + {label: 'ai-assistant.keys.stop', keys: [['Esc']]}, + {label: 'ai-assistant.keys.slash', keys: [['/']]} + ] + }, + { + title: 'ai-assistant.keys.chat', + rows: [ + {label: 'ai-assistant.keys.search-chats', keys: [[MOD, 'K']]}, + {label: 'ai-assistant.keys.find', keys: [[MOD, 'F']]}, + {label: 'ai-assistant.keys.close-panel', keys: [['Esc']]} + ] + } + ]; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spark.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-spark.component.ts new file mode 100644 index 0000000000..b3aa186e5f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spark.component.ts @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component } from '@angular/core'; + +type Point = [number, number]; + +interface SparkPart { + d: string; + values: string; + keyTimes: string; + keySplines: string; + begin: string; +} + +const SPARK_WAIST = 0.55; +const CYCLE_MS = 8000; +const LOW_DELAY_MS = 2000; +const STARS: Record<'big' | 'top' | 'low', [number, number, number]> = { + big: [9.1, 11.85, 6.8], + top: [17.8, 5.95, 3.6], + low: [17.8, 17.75, 3.6] +}; + +let sparkCount = 0; + +function sparkPath(cx: number, cy: number, radius: number, waist = SPARK_WAIST, tip = 0.1): string { + const format = (p: Point) => `${p[0].toFixed(2)} ${p[1].toFixed(2)}`; + const inner = radius * waist; + const tips: Point[] = [0, 1, 2, 3].map(i => { + const angle = i * 90 * Math.PI / 180; + return [cx + radius * Math.sin(angle), cy - radius * Math.cos(angle)]; + }); + const controls: Point[] = [0, 1, 2, 3].map(i => { + const angle = (i * 90 + 45) * Math.PI / 180; + const distance = 2 * inner - radius / Math.SQRT2; + return [cx + distance * Math.sin(angle), cy - distance * Math.cos(angle)]; + }); + const along = (p0: Point, c: Point, p2: Point, t: number): Point => [ + (1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * c[0] + t * t * p2[0], + (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * c[1] + t * t * p2[1] + ]; + const after: Point[] = []; + const before: Point[] = []; + for (let i = 0; i < 4; i++) { + const next = (i + 1) % 4; + after[i] = along(tips[i], controls[i], tips[next], tip); + before[next] = along(tips[i], controls[i], tips[next], 1 - tip); + } + let d = 'M' + format(after[0]); + for (let i = 0; i < 4; i++) { + const next = (i + 1) % 4; + d += 'Q' + format(controls[i]) + ' ' + format(before[next]) + 'Q' + format(tips[next]) + ' ' + format(after[next]); + } + return d + 'Z'; +} + +function star(kind: keyof typeof STARS, waist?: number, tip?: number): string { + const [cx, cy, radius] = STARS[kind]; + return sparkPath(cx, cy, radius, waist, tip); +} + +function part(frames: string[], begin: number): SparkPart { + return { + d: frames[0], + values: frames.join(';'), + keyTimes: frames.map((_, i) => (i / (frames.length - 1)).toFixed(3)).join(';'), + keySplines: frames.slice(1).map(() => '0.42 0 0.58 1').join(';'), + begin: begin + 'ms' + }; +} + +@Component({ + selector: 'tb-ai-spark', + template: ` + + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'ai-spark-svg', + 'aria-hidden': 'true' + } +}) +export class AiSparkComponent { + + readonly id = 'tb-ai-spark-ink-' + (++sparkCount); + + readonly fill = `url(#${this.id})`; + + readonly still = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; + + readonly parts: SparkPart[]; + + constructor() { + const phase = -(Date.now() % CYCLE_MS); + const pinch = (kind: 'top' | 'low') => [star(kind), star(kind, 0.51), star(kind), star(kind, 0.51), star(kind)]; + this.parts = [ + part([star('big'), star('big', 0.61, 0.14), star('big')], phase), + part(pinch('top'), phase), + part(pinch('low'), phase + LOW_DELAY_MS) + ]; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss new file mode 100644 index 0000000000..faa2ed69ab --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + --spin: 22px; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: var(--spin); + height: var(--spin); + line-height: 0; + vertical-align: middle; + color: var(--spin-color, var(--ai-teal-500)); + + &[data-kind="wait"], + &[data-kind="listen"] { + color: var(--spin-color, var(--tb-caution)); + } + + &[data-kind="stop"] { + color: var(--spin-color, var(--tb-ink-38)); + } +} + +.cell { + display: inline-grid; + font-size: calc(var(--spin) * 1.5); + grid-template-columns: repeat(2, 0.115em); + grid-auto-rows: 0.115em; + gap: 0.075em 0.08em; + line-height: 0; + vertical-align: middle; + + i { + border-radius: 50%; + background: currentColor; + visibility: hidden; + + &.on { + visibility: visible; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts new file mode 100644 index 0000000000..1d72167969 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, ElementRef, inject, Input, NgZone, OnDestroy, OnInit } from '@angular/core'; +import { AiSpinKind } from '@home/components/ai/ai-action.models'; + +const FRAME_MS = 80; +const DOT_BITS = [0x01, 0x08, 0x02, 0x10, 0x04, 0x20]; + +const FRAMES: Record = { + think: [...'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'].map(glyph => glyph.charCodeAt(0) - 0x2800), + listen: [0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x3f, 0x3e, 0x3c, 0x38, 0x30, 0x20, 0x00], + gen: [0x01, 0x08, 0x10, 0x20, 0x04, 0x02].map(bit => 0x3f & ~bit), + install: [0x09, 0x12, 0x24, 0x2d, 0x36, 0x3f, 0x3f, 0x3f, 0x00], + stop: [0x12] +}; + +const spinners = new Set(); +let tick = 0; +let timer: ReturnType | undefined; + +function startTimer(zone: NgZone): void { + if (timer || matchMedia('(prefers-reduced-motion: reduce)').matches) { + return; + } + zone.runOutsideAngular(() => { + timer = setInterval(() => { + tick++; + spinners.forEach(spinner => spinner.draw()); + }, FRAME_MS); + }); +} + +@Component({ + selector: 'tb-ai-spin', + template: '', + styleUrls: ['./ai-spin.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'aria-hidden': 'true', + '[attr.data-kind]': 'kind' + } +}) +export class AiSpinComponent implements OnInit, OnDestroy { + + private kindValue: AiSpinKind = 'think'; + + @Input() + set kind(kind: AiSpinKind) { + this.kindValue = kind ?? 'think'; + this.draw(); + } + + get kind(): AiSpinKind { + return this.kindValue; + } + + private host = inject>(ElementRef); + private zone = inject(NgZone); + + ngOnInit(): void { + spinners.add(this); + this.draw(); + startTimer(this.zone); + } + + ngOnDestroy(): void { + spinners.delete(this); + if (!spinners.size && timer) { + clearInterval(timer); + timer = undefined; + } + } + + draw(): void { + const frames = FRAMES[this.kindValue]; + const bits = frames[tick % frames.length]; + const dots = this.host.nativeElement.querySelectorAll('i'); + dots.forEach((dot, index) => dot.classList.toggle('on', !!(bits & DOT_BITS[index]))); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts new file mode 100644 index 0000000000..d16c5e4c0d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts @@ -0,0 +1,133 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Observable, of, Subscription } from 'rxjs'; +import { catchError, map } from 'rxjs/operators'; +import { EntityService } from '@core/http/entity.service'; +import { CalculatedFieldsService } from '@core/http/calculated-fields.service'; +import { EntityType } from '@shared/models/entity-type.models'; +import { getEntityDetailsPageURL } from '@core/utils'; +import { RequestConfig } from '@core/http/http-utils'; +import { AiStartedFrom } from '@shared/models/solution-creator.models'; +import { isAiTitledView } from '@shared/models/ai-chat.models'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; + +interface AiPage { + name: string; + url?: string; +} + +const CONFIG: RequestConfig = {ignoreLoading: true, ignoreErrors: true}; + +const LIST_PAGES: Record = { + DEVICE_LIST: {entityType: EntityType.DEVICE, url: '/entities/devices'}, + DEVICE_GROUP_LIST: {entityType: EntityType.DEVICE, url: '/entities/devices/groups'}, + DASHBOARD_LIST: {entityType: EntityType.DASHBOARD, url: '/dashboards'}, + DASHBOARD_GROUP_LIST: {entityType: EntityType.DASHBOARD, url: '/dashboards/groups'}, + ALARM_LIST: {entityType: 'ALARM', url: '/alarms/alarms'}, + ALARM_RULE_LIST: {entityType: 'ALARM_RULE', url: '/alarms/alarm-rules'}, + CALCULATED_FIELD_LIST: {entityType: EntityType.CALCULATED_FIELD, url: '/calculatedFields'}, + ASSET_LIST: {entityType: EntityType.ASSET, url: '/entities/assets/all'}, + ASSET_GROUP_LIST: {entityType: EntityType.ASSET, url: '/entities/assets/groups'}, + ENTITY_VIEW_LIST: {entityType: EntityType.ENTITY_VIEW, url: '/entities/entityViews/all'}, + ENTITY_VIEW_GROUP_LIST: {entityType: EntityType.ENTITY_VIEW, url: '/entities/entityViews/groups'}, + DEVICE_PROFILE_LIST: {entityType: EntityType.DEVICE_PROFILE, url: '/profiles/deviceProfiles'}, + ASSET_PROFILE_LIST: {entityType: EntityType.ASSET_PROFILE, url: '/profiles/assetProfiles'}, + CUSTOMER_LIST: {entityType: EntityType.CUSTOMER, url: '/customers/all'}, + CUSTOMER_GROUP_LIST: {entityType: EntityType.CUSTOMER, url: '/customers/groups'}, + USER_LIST: {entityType: EntityType.USER, url: '/users/all'}, + USER_GROUP_LIST: {entityType: EntityType.USER, url: '/users/groups'}, + ROLE_LIST: {entityType: EntityType.ROLE, url: '/roles'}, + RULE_CHAIN_LIST: {entityType: EntityType.RULE_CHAIN, url: '/ruleChains'}, + INTEGRATION_LIST: {entityType: EntityType.INTEGRATION, url: '/integrationsCenter/integrations'}, + CONVERTER_LIST: {entityType: EntityType.CONVERTER, url: '/integrationsCenter/converters'}, + NOTIFICATION_TEMPLATE_LIST: {entityType: EntityType.NOTIFICATION_TEMPLATE, url: '/notification/templates'}, + NOTIFICATION_RULE_LIST: {entityType: EntityType.NOTIFICATION_RULE, url: '/notification/rules'}, + NOTIFICATION_RECIPIENT_LIST: {entityType: EntityType.NOTIFICATION_TARGET, url: '/notification/recipients'}, + SENT_NOTIFICATION_LIST: {entityType: EntityType.NOTIFICATION_RULE, url: '/notification/sent'}, + NOTIFICATION_INBOX: {entityType: EntityType.NOTIFICATION_RULE, url: '/notification/inbox'} +}; + +@Component({ + selector: 'tb-ai-started-from', + template: ` + @if (page(); as current) { + {{ 'ai-assistant.started-from' | translate }} + @if (current.url) { + + {{ current.name }} + + } @else { + {{ current.name }} + } + } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'k-start', + 'role': 'note', + '[hidden]': '!page()' + } +}) +export class AiStartedFromComponent { + + from = input.required(); + + page = signal(null); + + kind = computed(() => { + const from = this.from(); + const entityType = from.entityId?.entityType ?? LIST_PAGES[from.type]?.entityType ?? from.type; + return aiEntityKind(entityType, from.type === 'ALARM_RULE' || from.type === 'ALARM_RULE_LIST'); + }); + + private entityService = inject(EntityService); + private calculatedFieldsService = inject(CalculatedFieldsService); + private translate = inject(TranslateService); + private destroyRef = inject(DestroyRef); + + private loading: Subscription; + + constructor() { + effect(() => { + const from = this.from(); + untracked(() => { + this.loading?.unsubscribe(); + this.loading = this.resolve(from).pipe( + catchError(() => of(null)), + takeUntilDestroyed(this.destroyRef) + ).subscribe(page => this.page.set(page)); + }); + }); + } + + private resolve(from: AiStartedFrom): Observable { + if (isAiTitledView(from.type)) { + return of(from.title || from.path ? {name: from.title || from.path, url: from.path} : null); + } + const list = LIST_PAGES[from.type]; + if (list && !from.entityId?.id) { + return of({name: this.translate.instant('ai-assistant.page.' + from.type), url: list.url}); + } + const entityId = from.entityId; + if (!entityId?.id) { + return of(null); + } + if (entityId.entityType === EntityType.CALCULATED_FIELD) { + const alarmRule = from.type === 'ALARM_RULE'; + return this.calculatedFieldsService.getCalculatedFieldById(entityId.id, CONFIG).pipe(map(field => ({ + name: field.name, + url: alarmRule ? `/alarms/alarm-rules/${entityId.id}` : `/calculatedFields/${entityId.id}` + }))); + } + const entityType = entityId.entityType as EntityType; + return this.entityService.getEntity(entityType, entityId.id, CONFIG).pipe(map(entity => { + const named = entity as {name?: string; title?: string}; + const name = named?.title || named?.name; + return name ? {name, url: getEntityDetailsPageURL(entityId.id, entityType) || undefined} : null; + })); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-step-mark.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-step-mark.component.ts new file mode 100644 index 0000000000..ee9b4b60e0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-step-mark.component.ts @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, input } from '@angular/core'; +import { AiPlanMark } from '@home/components/ai/ai-action.models'; + +export type AiStepMark = AiPlanMark | 'listen' | 'run' | 'stopped'; + +@Component({ + selector: 'tb-ai-step-mark', + template: ` + @switch (mark()) { + @case ('stopped') { + + } + @case ('listen') { + + } + @case ('run') { + + } + @default { + + } + } + `, + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false, + host: { + 'class': 'tb-ai-step-mark' + } +}) +export class AiStepMarkComponent { + + mark = input.required(); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-text.ts b/ui-ngx/src/app/modules/home/components/ai/ai-text.ts new file mode 100644 index 0000000000..fadd7049b7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-text.ts @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +export const MINUS = '\u2212'; + +export const SEVERITY_MARK = /\{(CRITICAL|MAJOR|MINOR|WARNING|INDETERMINATE)\}/; + +export function aiTrueMinus(text: string): string { + return text.replace(/(^|[\s(=:])-(?=\d)/g, '$1' + MINUS); +} + +export function aiLocale(lang: string | undefined): string | undefined { + return lang ? lang.replace('_', '-') : undefined; +} + +export function aiClockText(time: number | undefined, lang: string | undefined): string { + return new Date(time ?? Date.now()).toLocaleTimeString(aiLocale(lang), {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}); +} + +const CHAT_NAME_MAX = 44; +const CHAT_NAME_MIN_CUT = 20; + +export function aiChatNameOf(prompt: string): string { + const first = prompt.replace(/[*`#>]|(? CHAT_NAME_MIN_CUT ? space : CHAT_NAME_MAX).replace(/[,;·\s]+$/, '') + '…'; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts b/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts index 4c20bb7dfc..a591cb2432 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts @@ -22,8 +22,6 @@ export class AiTipDirective implements OnInit, OnDestroy { @Input('tbAiTip') template: TemplateRef; - @Input() tipToggle = false; - private pointerType: string; private visibleSubscription: Subscription; private unlistenKeydown: () => void; @@ -75,14 +73,9 @@ export class AiTipDirective implements OnInit, OnDestroy { this.popover.hide(); } - @HostListener('click', ['$event']) - onClick(event: MouseEvent): void { - if (!this.tipToggle || this.popover.component?.visible) { - this.popover.hide(); - return; - } - event.preventDefault(); - this.popover.show(); + @HostListener('click') + onClick(): void { + this.popover.hide(); } private onShown(): void { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-tooltip.ts b/ui-ngx/src/app/modules/home/components/ai/ai-tooltip.ts new file mode 100644 index 0000000000..dbdd3d4eec --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-tooltip.ts @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Directive, ElementRef, inject, Provider } from '@angular/core'; +import { MAT_TOOLTIP_DEFAULT_OPTIONS, MatTooltip, MatTooltipDefaultOptions } from '@angular/material/tooltip'; + +export const AI_TOOLTIP_OPTIONS: MatTooltipDefaultOptions = { + showDelay: 500, + hideDelay: 0, + touchendHideDelay: 1500, + disableTooltipInteractivity: true, + tooltipClass: 'tb-ai-tip' +}; + +export const AI_TOOLTIP_PROVIDERS: Provider[] = [{provide: MAT_TOOLTIP_DEFAULT_OPTIONS, useValue: AI_TOOLTIP_OPTIONS}]; + +const NEXT_AT_ONCE_MS = 400; + +let lastTipAt = 0; + +function focusedByKeyboard(element: HTMLElement): boolean { + return element.matches(':focus-visible'); +} + +@Directive({ + selector: '[matTooltip]', + standalone: false, + host: { + '(mouseenter)': 'onEnter()', + '(mouseleave)': 'onLeave()', + '(focus)': 'onFocus()' + } +}) +export class AiTooltipChainDirective { + + private tooltip = inject(MatTooltip, {self: true}); + private host = inject>(ElementRef); + private inChat = inject(MAT_TOOLTIP_DEFAULT_OPTIONS, {optional: true}) === AI_TOOLTIP_OPTIONS; + + onEnter(): void { + if (this.inChat) { + this.tooltip.showDelay = Date.now() - lastTipAt < NEXT_AT_ONCE_MS ? 0 : AI_TOOLTIP_OPTIONS.showDelay; + } + } + + onLeave(): void { + if (this.inChat && this.tooltip._isTooltipVisible()) { + lastTipAt = Date.now(); + } + } + + onFocus(): void { + if (this.inChat && !this.tooltip.disabled && focusedByKeyboard(this.host.nativeElement)) { + this.tooltip.show(0); + } + } +} + +@Directive({ + selector: '[aiTipIfCut]', + standalone: false, + host: { + '(mouseenter)': 'check()', + '(focus)': 'onFocus()' + } +}) +export class AiTipIfCutDirective { + + private tooltip = inject(MatTooltip, {self: true}); + private host = inject>(ElementRef); + + check(): void { + const element = this.host.nativeElement.querySelector('.tb-ai-cut') ?? this.host.nativeElement; + this.tooltip.disabled = element.scrollWidth <= element.clientWidth + 1; + } + + onFocus(): void { + this.check(); + if (!this.tooltip.disabled && focusedByKeyboard(this.host.nativeElement)) { + this.tooltip.show(0); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-welcome.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-welcome.models.ts new file mode 100644 index 0000000000..ca918ccec0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-welcome.models.ts @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { TranslateService } from '@ngx-translate/core'; +import { EntityType } from '@shared/models/entity-type.models'; +import { AiAssistantPanelConfig, AiAssistantPromptExample, AiAssistantViewType, AiChatView } from '@shared/models/ai-chat.models'; + +export type AiWelcomePlace = 'dashboard' | 'list' | 'page'; + +export interface AiWelcome { + place: AiWelcomePlace; + title?: string; + line?: string; + examples: AiAssistantPromptExample[]; + suggestion: string | null; +} + +interface AiWelcomeKind { + key: string; + entity?: boolean; + owned?: boolean; + examples?: string[]; +} + +const WELCOMES: Partial> = { + [AiAssistantViewType.DASHBOARD_LIST]: {key: 'dashboards', examples: ['build', 'find']}, + [AiAssistantViewType.DASHBOARD]: {key: 'dashboard', entity: true}, + [AiAssistantViewType.REPORT_TEMPLATE_LIST]: {key: 'report-templates', examples: ['fleet', 'export']}, + [AiAssistantViewType.REPORT_TEMPLATE]: {key: 'report-template', entity: true}, + [AiAssistantViewType.SCHEDULED_REPORTS]: {key: 'scheduled-reports', examples: ['weekly', 'next']}, + [AiAssistantViewType.REPORTS]: {key: 'reports', examples: ['latest', 'now']}, + [AiAssistantViewType.WIDGET_TYPE_LIST]: {key: 'widget-types', examples: ['tank', 'heatmap']}, + [AiAssistantViewType.WIDGET_TYPE]: {key: 'widget-type', entity: true}, + [AiAssistantViewType.NEW_WIDGET_TYPE]: {key: 'widget-type-new'}, + [AiAssistantViewType.WIDGETS_BUNDLE_LIST]: {key: 'widgets-bundles', examples: ['custom']}, + [AiAssistantViewType.WIDGETS_BUNDLE]: {key: 'widgets-bundle', entity: true, examples: ['add', 'order']}, + [AiAssistantViewType.DEVICE_LIST]: {key: 'devices', examples: ['inactive']}, + [AiAssistantViewType.DEVICE]: {key: 'device', entity: true, examples: ['telemetry', 'alarm', 'dashboard']}, + [AiAssistantViewType.DEVICE_GROUP_LIST]: {key: 'device-groups', owned: true}, + [AiAssistantViewType.DEVICE_GROUP]: {key: 'device-group', entity: true, examples: ['status']}, + [AiAssistantViewType.ALARM_RULE_LIST]: {key: 'alarm-rules'}, + [AiAssistantViewType.ALARM_RULE]: {key: 'alarm-rule', entity: true, examples: ['explain']}, + [AiAssistantViewType.ALARM_LIST]: {key: 'alarms', examples: ['attention', 'triage']}, + [AiAssistantViewType.ALARM]: {key: 'alarm', entity: true, examples: ['explain', 'acknowledge']}, + [AiAssistantViewType.CALCULATED_FIELD_LIST]: {key: 'calculated-fields'}, + [AiAssistantViewType.CALCULATED_FIELD]: {key: 'calculated-field', entity: true, examples: ['explain']}, + [AiAssistantViewType.ASSET_LIST]: {key: 'assets', examples: ['find', 'hierarchy']}, + [AiAssistantViewType.ASSET]: {key: 'asset', entity: true, examples: ['telemetry', 'metric', 'dashboard']}, + [AiAssistantViewType.ASSET_GROUP_LIST]: {key: 'asset-groups', owned: true, examples: ['find']}, + [AiAssistantViewType.ASSET_GROUP]: {key: 'asset-group', entity: true, examples: ['status']}, + [AiAssistantViewType.ENTITY_VIEW_LIST]: {key: 'entity-views', examples: ['find', 'create']}, + [AiAssistantViewType.ENTITY_VIEW]: {key: 'entity-view', entity: true, examples: ['telemetry', 'source']}, + [AiAssistantViewType.DEVICE_PROFILE_LIST]: {key: 'device-profiles', examples: ['find']}, + [AiAssistantViewType.DEVICE_PROFILE]: {key: 'device-profile', entity: true, examples: ['devices', 'alarm', 'metric']}, + [AiAssistantViewType.ASSET_PROFILE_LIST]: {key: 'asset-profiles', examples: ['find', 'create']}, + [AiAssistantViewType.ASSET_PROFILE]: {key: 'asset-profile', entity: true, examples: ['assets', 'alarm']}, + [AiAssistantViewType.CUSTOMER_LIST]: {key: 'customers', examples: ['create', 'find']}, + [AiAssistantViewType.CUSTOMER]: {key: 'customer', entity: true, examples: ['user', 'share', 'devices']}, + [AiAssistantViewType.CUSTOMER_GROUP_LIST]: {key: 'customer-groups', owned: true, examples: ['create']}, + [AiAssistantViewType.CUSTOMER_GROUP]: {key: 'customer-group', entity: true, examples: ['list']}, + [AiAssistantViewType.USER_LIST]: {key: 'users', examples: ['invite', 'find']}, + [AiAssistantViewType.USER]: {key: 'user', entity: true, examples: ['access', 'notifications']}, + [AiAssistantViewType.USER_GROUP_LIST]: {key: 'user-groups', owned: true, examples: ['create']}, + [AiAssistantViewType.USER_GROUP]: {key: 'user-group', entity: true, examples: ['access', 'add']}, + [AiAssistantViewType.ROLE_LIST]: {key: 'roles', examples: ['create', 'explain']}, + [AiAssistantViewType.ROLE]: {key: 'role', entity: true, examples: ['explain']}, + [AiAssistantViewType.RULE_CHAIN_LIST]: {key: 'rule-chains', examples: ['alarm', 'notify']}, + [AiAssistantViewType.RULE_CHAIN]: {key: 'rule-chains', examples: ['alarm', 'notify']}, + [AiAssistantViewType.INTEGRATION_LIST]: {key: 'integrations', examples: ['connect']}, + [AiAssistantViewType.INTEGRATION]: {key: 'integration', entity: true, examples: ['connect']}, + [AiAssistantViewType.CONVERTER_LIST]: {key: 'converters', examples: ['connect']}, + [AiAssistantViewType.CONVERTER]: {key: 'converter', entity: true, examples: ['connect']}, + [AiAssistantViewType.EDGE_LIST]: {key: 'edges', examples: ['offline', 'create']}, + [AiAssistantViewType.EDGE]: {key: 'edge', entity: true, examples: ['status', 'assign', 'install']}, + [AiAssistantViewType.EDGE_GROUP_LIST]: {key: 'edge-groups', owned: true, examples: ['find']}, + [AiAssistantViewType.EDGE_GROUP]: {key: 'edge-group', entity: true, examples: ['status']}, + [AiAssistantViewType.EDGE_SCHEDULER]: {key: 'edge-scheduler', examples: ['assign']}, + [AiAssistantViewType.RULE_CHAIN_TEMPLATE_LIST]: {key: 'rule-chain-templates', examples: ['root', 'hub']}, + [AiAssistantViewType.RULE_CHAIN_TEMPLATE]: {key: 'rule-chain-template', entity: true, examples: ['edges', 'auto']}, + [AiAssistantViewType.INTEGRATION_TEMPLATE_LIST]: {key: 'integration-templates', examples: ['edges']}, + [AiAssistantViewType.INTEGRATION_TEMPLATE]: {key: 'integration-template', entity: true, examples: ['edges']}, + [AiAssistantViewType.CONVERTER_TEMPLATE_LIST]: {key: 'converter-templates', examples: ['explain']}, + [AiAssistantViewType.CONVERTER_TEMPLATE]: {key: 'converter-template', entity: true, examples: ['explain']}, + [AiAssistantViewType.AGENT_LIST]: {key: 'agents', examples: ['status', 'deploy']}, + [AiAssistantViewType.AGENT]: {key: 'agent', entity: true, examples: ['apps', 'edge', 'upgrade']}, + [AiAssistantViewType.AGENT_GROUP_LIST]: {key: 'agent-groups', owned: true, examples: ['find']}, + [AiAssistantViewType.AGENT_GROUP]: {key: 'agent-group', entity: true, examples: ['status']}, + [AiAssistantViewType.AGENT_APPLICATION_LIST]: {key: 'agent-applications', examples: ['status', 'install']}, + [AiAssistantViewType.AGENT_APPLICATION]: {key: 'agent-application', entity: true, examples: ['logs', 'restart']}, + [AiAssistantViewType.AGENT_EVENTS]: {key: 'agent-events', examples: ['failed']}, + [AiAssistantViewType.AGENT_PROFILE_LIST]: {key: 'agent-profiles', examples: ['create', 'default']}, + [AiAssistantViewType.AGENT_PROFILE]: {key: 'agent-profile', entity: true, examples: ['apps', 'bulk']}, + [AiAssistantViewType.AGENT_APP_PROFILE_LIST]: {key: 'agent-app-profiles', examples: ['edge', 'gateway']}, + [AiAssistantViewType.AGENT_APP_PROFILE]: {key: 'agent-app-profile', entity: true, examples: ['explain']}, + [AiAssistantViewType.AGENT_BULK_ACTION]: {key: 'agent-bulk-action', examples: ['progress']}, + [AiAssistantViewType.NOTIFICATION_TEMPLATE_LIST]: {key: 'notifications'}, + [AiAssistantViewType.NOTIFICATION_RULE_LIST]: {key: 'notifications'}, + [AiAssistantViewType.NOTIFICATION_RECIPIENT_LIST]: {key: 'notifications'}, + [AiAssistantViewType.SENT_NOTIFICATION_LIST]: {key: 'notifications'}, + [AiAssistantViewType.NOTIFICATION_INBOX]: {key: 'notifications'}, + [AiAssistantViewType.NOTIFICATION_TEMPLATE]: {key: 'notification-template', entity: true, examples: ['explain', 'slack']}, + [AiAssistantViewType.NOTIFICATION_RULE]: {key: 'notification-rule', entity: true, examples: ['explain', 'escalate']}, + [AiAssistantViewType.NOTIFICATION_RECIPIENT]: {key: 'notification-recipient', entity: true, examples: ['rules']}, + [AiAssistantViewType.IOT_HUB]: {key: 'iot-hub', examples: ['popular', 'alarm', 'installed']}, + [AiAssistantViewType.DASHBOARD_GROUP_LIST]: {key: 'dashboard-groups', owned: true, examples: ['share']}, + [AiAssistantViewType.DASHBOARD_GROUP]: {key: 'dashboard-group', entity: true, examples: ['access']}, + [AiAssistantViewType.ENTITY_VIEW_GROUP_LIST]: {key: 'entity-view-groups', owned: true}, + [AiAssistantViewType.ENTITY_VIEW_GROUP]: {key: 'entity-view-group', entity: true, examples: ['list']}, + [AiAssistantViewType.CUSTOMER_HIERARCHY]: {key: 'customer-hierarchy', examples: ['move']}, + [AiAssistantViewType.GATEWAYS]: {key: 'gateways', examples: ['modbus', 'status']}, + [AiAssistantViewType.OTA_UPDATES]: {key: 'ota-updates', examples: ['rollout', 'add']}, + [AiAssistantViewType.WHITE_LABELING]: {key: 'white-labeling', examples: ['brand']}, + [AiAssistantViewType.LOGIN_WHITE_LABELING]: {key: 'login-white-labeling', examples: ['match']}, + [AiAssistantViewType.MAIL_TEMPLATES]: {key: 'mail-templates', examples: ['name', 'activation']}, + [AiAssistantViewType.CUSTOM_TRANSLATION]: {key: 'custom-translation', examples: ['rename', 'find']}, + [AiAssistantViewType.CUSTOM_MENU]: {key: 'custom-menu', examples: ['simple', 'link']}, + [AiAssistantViewType.IMAGES]: {key: 'images', examples: ['icon']}, + [AiAssistantViewType.SCADA_SYMBOL_LIST]: {key: 'scada-symbols', examples: ['find', 'connectors']}, + [AiAssistantViewType.SCADA_SYMBOL]: {key: 'scada-symbol', entity: true, examples: ['explain', 'values']}, + [AiAssistantViewType.JAVASCRIPT_LIBRARY]: {key: 'javascript-library', examples: ['module']}, + [AiAssistantViewType.RESOURCES_LIBRARY]: {key: 'resources-library'}, + [AiAssistantViewType.TWO_FACTOR_AUTH]: {key: 'two-factor-auth', examples: ['review', 'methods', 'enforce']}, + [AiAssistantViewType.OAUTH2_DOMAINS]: {key: 'oauth2-domains', examples: ['missing', 'hide']}, + [AiAssistantViewType.OAUTH2_CLIENTS]: {key: 'oauth2-clients', examples: ['review']}, + [AiAssistantViewType.SELF_REGISTRATION]: {key: 'self-registration', examples: ['review']}, + [AiAssistantViewType.SECRETS]: {key: 'secrets', examples: ['create']}, + [AiAssistantViewType.AUDIT_LOGS]: {key: 'audit-logs', examples: ['changes', 'logins']}, + [AiAssistantViewType.VERSION_CONTROL]: {key: 'version-control', examples: ['save', 'history']}, + [AiAssistantViewType.TASK_MANAGER]: {key: 'task-manager', examples: ['failed']}, + [AiAssistantViewType.SCHEDULER]: {key: 'scheduler', examples: ['night', 'week']}, + [AiAssistantViewType.HOME_SETTINGS]: {key: 'home-settings', examples: ['set']}, + [AiAssistantViewType.MAIL_SERVER_SETTINGS]: {key: 'mail-server-settings', examples: ['setup', 'check']}, + [AiAssistantViewType.NOTIFICATION_SETTINGS]: {key: 'notification-settings', examples: ['slack', 'sms']}, + [AiAssistantViewType.REPOSITORY_SETTINGS]: {key: 'repository-settings', examples: ['connect']}, + [AiAssistantViewType.AUTO_COMMIT_SETTINGS]: {key: 'auto-commit-settings', examples: ['devices']}, + [AiAssistantViewType.AI_MODELS]: {key: 'ai-models', examples: ['add']}, + [AiAssistantViewType.API_USAGE]: {key: 'api-usage', examples: ['limits']}, + [AiAssistantViewType.MOBILE_BUNDLES]: {key: 'mobile-bundles', examples: ['dashboard', 'review']}, + [AiAssistantViewType.MOBILE_APPS]: {key: 'mobile-apps', examples: ['release', 'register']}, + [AiAssistantViewType.MOBILE_QR_CODE]: {key: 'mobile-qr-code', examples: ['home']}, + [AiAssistantViewType.ACCOUNT_PROFILE]: {key: 'account-profile', examples: ['home', 'units']}, + [AiAssistantViewType.ACCOUNT_SECURITY]: {key: 'account-security', examples: ['review', 'keys']}, + [AiAssistantViewType.ACCOUNT_NOTIFICATIONS]: {key: 'account-notifications', examples: ['quiet', 'review']}, + [AiAssistantViewType.TRENDZ]: {key: 'trendz'} +}; + +export function aiWelcome(view: AiChatView | undefined, name: string | null, config: AiAssistantPanelConfig | null, + translate: TranslateService): AiWelcome { + const configExamples = config?.promptExamples ?? []; + const kind = view ? WELCOMES[view.type] : undefined; + if (!kind) { + return {place: 'page', title: config?.title, line: config?.subTitle, examples: configExamples, suggestion: config?.suggestion ?? shortExample(configExamples)}; + } + const base = 'ai-assistant.welcome.' + (config?.welcomeKey ?? kind.key); + const own = (kind.examples ?? []).map(example => ({ + label: translate.instant(`${base}.example.${example}.label`), + message: translate.instant(`${base}.example.${example}.message`) + })); + const examples = kind.entity && own.length ? own : [...own, ...configExamples.filter(item => !own.some(mine => mine.message === item.message))]; + return { + place: view.type === AiAssistantViewType.DASHBOARD ? 'dashboard' : kind.entity ? 'page' : 'list', + title: translate.instant(`${base}.${titleKey(kind, view, name)}`, {name}), + line: translate.instant(`${base}.line`), + examples, + suggestion: translate.instant(`${base}.suggestion`) + }; +} + +function titleKey(kind: AiWelcomeKind, view: AiChatView, name: string | null): string { + if (kind.entity) { + return name ? 'title' : 'title-unnamed'; + } + return kind.owned && view.entityId?.entityType === EntityType.CUSTOMER ? 'title-customer' : 'title'; +} + +function shortExample(examples: AiAssistantPromptExample[]): string | null { + const example = examples[0]?.message?.trim(); + return example && example.length <= 80 && !example.includes('...') ? example : null; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts new file mode 100644 index 0000000000..852110daf2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts @@ -0,0 +1,372 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Injectable } from '@angular/core'; +import { firstValueFrom, forkJoin, from, Observable, of } from 'rxjs'; +import { catchError, filter, map, switchMap, take, timeout } from 'rxjs/operators'; +import { WidgetService } from '@core/http/widget.service'; +import { AiResourceService } from '@core/http/ai-resource.service'; +import { migrateWidgetTypeToDynamicForms, WidgetTypeDetails } from '@shared/models/widget.models'; +import { ImageService } from '@core/http/image.service'; +import { parseScadaSymbolMetadataFromContent, ScadaSymbolMetadata } from '@home/components/widget/lib/scada/scada-symbol.models'; +import { detailsToWidgetInfo, WidgetInfo } from '@home/models/widget-component.models'; + +const SETTLE_MS = 2500; +const RUN_TIMEOUT_MS = 30000; +const MAX_REASON_LENGTH = 1900; +const MAX_LINE_LENGTH = 300; +const PREVIEW_WIDTH = 1280; +const PREVIEW_HEIGHT = 800; +const STYLE_CHUNK = 8; +const ICON_FONT = /material (icons|symbols)/i; + +interface WidgetCheckReport { + initialised: boolean; + errors: string[]; + console: string[]; + noData?: boolean; + width?: number; + height?: number; + screenshot?: string; + rendered?: boolean; + activeValues?: Record; +} + +type CapturedReport = WidgetCheckReport & {canvas?: HTMLCanvasElement}; + +@Injectable({ + providedIn: 'root' +}) +export class AiWidgetCheckService { + + constructor(private widgetService: WidgetService, + private imageService: ImageService, + private aiResources: AiResourceService) { + } + + checkScadaSymbol(link: string): Observable { + const url = link.replace(/^tb-image;/, ''); + return forkJoin({ + widgetType: this.widgetService.getWidgetType('system.scada_symbol', {ignoreLoading: true, ignoreErrors: true}), + content: this.imageService.getImageString(url) + }).pipe( + switchMap(({widgetType, content}) => { + const widget = detailsToWidgetInfo(migrateWidgetTypeToDynamicForms(widgetType as WidgetTypeDetails)); + const active = this.activeValues(parseScadaSymbolMetadataFromContent(content)); + return from(this.runSymbol(widget, link, {}).then(normal => + this.runSymbol(widget, link, active.behavior).then(activeRun => ({normal, activeRun, values: active.values})))); + }), + switchMap(({normal, activeRun, values}) => { + const report: CapturedReport = { + initialised: normal.initialised && activeRun.initialised, + rendered: !!normal.rendered && !!activeRun.rendered, + errors: [...new Set([...normal.errors, ...activeRun.errors])], + console: [...new Set([...normal.console, ...activeRun.console])], + activeValues: values, + canvas: this.sideBySide(normal.canvas, activeRun.canvas) + }; + return this.attachScreenshot(report); + }), + map(report => this.toReason(report)), + timeout(2 * RUN_TIMEOUT_MS + 15000), + catchError(error => of(this.toReason({ + initialised: false, + errors: ['The symbol could not be loaded: ' + (error?.message || error?.statusText || error)], + console: [] + }))) + ); + } + + private runSymbol(widget: WidgetInfo, link: string, behavior: Record): Promise { + const config = JSON.parse(widget.defaultConfig || '{}'); + config.showTitle = false; + config.settings = {...(config.settings || {}), scadaSymbolUrl: link, simulated: true, + scadaSymbolObjectSettings: {behavior, properties: {}}}; + return this.run({...widget, defaultConfig: JSON.stringify(config)}); + } + + private activeValues(metadata: ScadaSymbolMetadata): {behavior: Record; values: Record} { + const behavior: Record = {}; + const values: Record = {}; + for (const item of metadata?.behavior || []) { + if (item.type !== 'value') { + continue; + } + const type = String(item.valueType); + const value = type === 'BOOLEAN' ? !/animation/i.test(item.id) + : type === 'DOUBLE' || type === 'INTEGER' ? (/capacity|max/i.test(item.id) ? 100 : 60) + : type === 'STRING' ? 'Test' : null; + behavior[item.id] = {...(item.defaultGetValueSettings || {}), action: 'DO_NOTHING', defaultValue: value}; + values[item.id] = value; + } + return {behavior, values}; + } + + private sideBySide(left?: HTMLCanvasElement, right?: HTMLCanvasElement): HTMLCanvasElement | undefined { + if (!left || !right) { + return left || right; + } + const gap = 16; + const canvas = document.createElement('canvas'); + canvas.width = left.width + gap + right.width; + canvas.height = Math.max(left.height, right.height); + const context = canvas.getContext('2d'); + context.fillStyle = '#ffffff'; + context.fillRect(0, 0, canvas.width, canvas.height); + context.drawImage(left, 0, 0); + context.drawImage(right, left.width + gap, 0); + return canvas; + } + + check(widgetTypeId: string): Observable { + return this.widgetService.getWidgetTypeById(widgetTypeId, {ignoreLoading: true, ignoreErrors: true}).pipe( + map(details => detailsToWidgetInfo(migrateWidgetTypeToDynamicForms(details))), + switchMap(widget => from(this.run(widget))), + switchMap(report => this.attachScreenshot(report)), + map(report => this.toReason(report)), + timeout(RUN_TIMEOUT_MS + 15000), + catchError(error => of(this.toReason({ + initialised: false, + errors: ['The widget could not be loaded: ' + (error?.message || error?.statusText || error)], + console: [] + }))) + ); + } + + private run(widget: WidgetInfo): Promise { + return new Promise(resolve => { + const report: CapturedReport = {initialised: false, errors: [], console: []}; + const config = JSON.parse(widget.defaultConfig || '{}'); + config.title = config.title || widget.widgetName; + const frame = document.createElement('iframe'); + frame.setAttribute('aria-hidden', 'true'); + frame.style.cssText = `position:fixed;left:-${PREVIEW_WIDTH + 200}px;top:0;width:${PREVIEW_WIDTH}px;height:${PREVIEW_HEIGHT}px;border:0;visibility:visible;`; + frame.setAttribute('data-widget', JSON.stringify({...widget, defaultConfig: JSON.stringify(config)})); + let settled = false; + let settleTimer: ReturnType; + const finish = async () => { + if (settled) { + return; + } + settled = true; + clearTimeout(settleTimer); + clearTimeout(overall); + window.removeEventListener('message', onMessage); + try { + this.inspect(frame, report); + report.canvas = await this.capture(frame); + } catch (e) { + report.console.push('Inspecting the preview failed: ' + (e as Error)?.message); + } + frame.remove(); + resolve(report); + }; + const onMessage = (event: MessageEvent) => { + if (event.source !== frame.contentWindow || typeof event.data !== 'string') { + return; + } + let message: {type: string; data?: any}; + try { + message = JSON.parse(event.data); + } catch (e) { + return; + } + if (message.type === 'widgetException') { + const data = message.data || {}; + const line = data.lineNumber ? ` (line ${data.lineNumber})` : ''; + report.errors.push(this.clip(this.plain(data.message || data.name || 'Widget error') + line)); + } else if (message.type === 'widgetEditModeInited') { + report.initialised = true; + settleTimer = setTimeout(finish, SETTLE_MS); + } + }; + const overall = setTimeout(finish, RUN_TIMEOUT_MS); + window.addEventListener('message', onMessage); + frame.addEventListener('load', () => this.watchConsole(frame, report)); + frame.setAttribute('src', '/widget-editor'); + document.body.appendChild(frame); + }); + } + + private watchConsole(frame: HTMLIFrameElement, report: WidgetCheckReport) { + try { + const win = frame.contentWindow as any; + const original = win.console.error.bind(win.console); + win.console.error = (...args: any[]) => { + report.console.push(this.clip(args.map(arg => arg?.message || (typeof arg === 'string' ? arg : this.safeJson(arg))).join(' '))); + original(...args); + }; + win.addEventListener('error', (event: ErrorEvent) => report.console.push(this.clip(event.message))); + win.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => + report.console.push(this.clip('Unhandled promise rejection: ' + (event.reason?.message || event.reason)))); + } catch (e) { + report.console.push('The preview console could not be watched'); + } + } + + private inspect(frame: HTMLIFrameElement, report: WidgetCheckReport) { + const doc = frame.contentDocument; + if (!doc) { + return; + } + const errorPanel = doc.querySelector('.tb-widget-error'); + if (errorPanel?.textContent?.trim()) { + const text = this.clip(errorPanel.textContent.trim().replace(/^Widget Error:\s*/, '')); + if (!report.errors.includes(text)) { + report.errors.push(text); + } + } + report.noData = !!doc.querySelector('.tb-widget-no-data'); + report.rendered = !!doc.querySelector('tb-scada-symbol-widget svg'); + const widget = doc.querySelector('tb-widget') as HTMLElement; + if (widget) { + const rect = widget.getBoundingClientRect(); + report.width = Math.round(rect.width); + report.height = Math.round(rect.height); + } + } + + private async capture(frame: HTMLIFrameElement): Promise { + const doc = frame.contentDocument; + const win = frame.contentWindow; + const target = (doc?.querySelector('tb-widget-container') || doc?.querySelector('tb-widget')) as HTMLElement; + if (!target || !win) { + return undefined; + } + const rect = target.getBoundingClientRect(); + const width = Math.ceil(rect.width); + const height = Math.ceil(rect.height); + if (!width || !height) { + return undefined; + } + const clone = target.cloneNode(true) as HTMLElement; + const sources = [target, ...Array.from(target.querySelectorAll('*'))]; + const copies = [clone, ...Array.from(clone.querySelectorAll('*'))]; + for (let i = 0; i < sources.length; i++) { + if (i % STYLE_CHUNK === STYLE_CHUNK - 1) { + await new Promise(resolve => setTimeout(resolve)); + } + this.copyElement(win, sources[i], copies[i]); + } + const markup = new XMLSerializer().serializeToString(clone); + const svg = `` + + `${markup}`; + const image = new Image(); + image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg); + await image.decode(); + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + canvas.getContext('2d').drawImage(image, 0, 0); + return canvas; + } + + private copyElement(win: Window, source: Element, copy: Element) { + const style = win.getComputedStyle(source); + let text = ''; + for (const property of Array.from(style)) { + if (!property.startsWith('--')) { + text += `${property}:${style.getPropertyValue(property)};`; + } + } + copy.setAttribute('style', text); + const glyph = source.tagName !== 'CANVAS' && ICON_FONT.test(style.fontFamily) && source.childElementCount === 0; + const image = source.tagName === 'CANVAS' ? this.canvasImage(source as HTMLCanvasElement) + : glyph ? this.glyphImage(win, source, style) : undefined; + if (glyph && !image) { + copy.setAttribute('style', text + 'visibility:hidden;'); + return; + } + if (image) { + const img = copy.ownerDocument.createElement('img'); + img.setAttribute('src', image); + img.setAttribute('style', text); + copy.replaceWith(img); + } + } + + private canvasImage(canvas: HTMLCanvasElement): string | undefined { + try { + return canvas.toDataURL(); + } catch (e) { + return undefined; + } + } + + private glyphImage(win: Window, source: Element, style: CSSStyleDeclaration): string | undefined { + const rect = source.getBoundingClientRect(); + const glyph = source.textContent?.trim(); + if (!glyph || !rect.width || !rect.height) { + return undefined; + } + const canvas = win.document.createElement('canvas'); + canvas.width = Math.ceil(rect.width); + canvas.height = Math.ceil(rect.height); + const context = canvas.getContext('2d'); + context.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`; + context.fillStyle = style.color; + context.textAlign = 'center'; + context.textBaseline = 'middle'; + context.fillText(glyph, canvas.width / 2, canvas.height / 2); + return this.canvasImage(canvas); + } + + private attachScreenshot(report: CapturedReport): Observable { + const canvas = report.canvas; + delete report.canvas; + return from(this.upload(canvas, 'widget-check.png')).pipe( + map(screenshot => { + if (screenshot) { + report.screenshot = screenshot; + } + return report; + }), + catchError(() => of(report)) + ); + } + + private upload(canvas: HTMLCanvasElement | undefined, name: string): Promise { + if (!canvas) { + return Promise.resolve(undefined); + } + return new Promise(resolve => canvas.toBlob(blob => resolve(blob), 'image/png')).then(blob => !blob ? undefined : + firstValueFrom(this.aiResources.upload(new File([blob], name, {type: 'image/png'})).pipe( + filter(event => event.type === 'done'), + take(1), + map(event => event.type === 'done' ? event.resource?.id : undefined), + catchError(() => of(undefined)) + ), {defaultValue: undefined})); + } + + private toReason(report: WidgetCheckReport): string { + const trimmed: WidgetCheckReport = {...report, errors: report.errors.slice(0, 6), console: [...new Set(report.console)].slice(0, 5)}; + let reason = JSON.stringify(trimmed); + while (reason.length > MAX_REASON_LENGTH && (trimmed.console.length || trimmed.errors.length > 1)) { + if (trimmed.console.length) { + trimmed.console.pop(); + } else { + trimmed.errors.pop(); + } + reason = JSON.stringify(trimmed); + } + return reason.length > MAX_REASON_LENGTH ? JSON.stringify({...trimmed, errors: [trimmed.errors[0]?.slice(0, 600)], console: []}) : reason; + } + + private plain(html: string): string { + const body = new DOMParser().parseFromString(html, 'text/html').body; + return (body.textContent || '').replace(/\s+/g, ' ').trim(); + } + + private clip(text: string): string { + const single = (text || '').replace(/\s+/g, ' ').trim(); + return single.length > MAX_LINE_LENGTH ? single.substring(0, MAX_LINE_LENGTH) + '…' : single; + } + + private safeJson(value: any): string { + try { + return JSON.stringify(value); + } catch (e) { + return String(value); + } + } + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss new file mode 100644 index 0000000000..fe1e9efea1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: flex; + align-items: flex-start; + gap: 8px; + font-family: var(--tb-mono); + font-size: 15px; + line-height: var(--chat-line-lh); + color: var(--tb-ink); + + tb-ai-spin { + margin-block: calc((var(--chat-line-lh) - var(--spin)) / 2); + } +} + +.say { + display: inline-block; + min-width: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + background: linear-gradient(90deg, var(--tb-ink-76) 0%, var(--tb-ink) 42%, var(--tb-ink-76) 58%, var(--tb-ink-76) 100%); + background-size: 260% 100%; + -webkit-background-clip: text; + background-clip: text; + color: transparent; + animation: k-shimmer 5s linear infinite, k-swap .2s ease-out; + + &.still { + animation: none; + background: none; + color: var(--k-faint); + } +} + +.clock { + flex: none; + white-space: nowrap; + font-family: var(--tb-mono); + font-variant-numeric: tabular-nums; + font-size: var(--chat-meta); + line-height: var(--chat-line-lh); + color: var(--k-faint); +} + +@keyframes k-shimmer { + from { + background-position: 130% 0; + } + to { + background-position: -130% 0; + } +} + +@keyframes k-swap { + from { + transform: translateY(6px); + opacity: .25; + } + to { + transform: none; + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .say { + animation: none; + background: none; + color: var(--tb-ink); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts new file mode 100644 index 0000000000..d5f567a735 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, linkedSignal, NgZone, OnInit, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AiSpinKind, aiWorkClock } from '@home/components/ai/ai-action.models'; + +const CLOCK_AFTER_MS = 10_000; +const STILL_AFTER_MS = 30_000; +const LONGER_AFTER_MS = 90_000; + +@Component({ + selector: 'tb-ai-work-line', + template: ` + + @for (words of [say()]; track words) { + {{ words }} + } + @if (tail(); as text) { + + } + `, + styleUrls: ['./ai-work-line.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'role': 'status', + '[attr.aria-label]': 'say()' + } +}) +export class AiWorkLineComponent implements OnInit { + + words = input.required(); + + kind = input('think'); + + since = input(Date.now()); + + held = input(false); + + private now = signal(Date.now()); + + private elapsed = computed(() => Math.max(0, this.now() - this.since())); + + private shown = computed(() => ({words: this.words(), since: this.since()}), { + equal: (a, b) => a.words === b.words && a.since === b.since + }); + + private wordsSince = linkedSignal<{words: string; since: number}, number>({ + source: this.shown, + computation: (shown, previous) => !previous || previous.source.since !== shown.since ? shown.since : Date.now() + }); + + say = computed(() => { + const words = this.words(); + if (this.held() || this.now() - this.wordsSince() < STILL_AFTER_MS || !words) { + return words; + } + return this.translate.instant('ai-assistant.work.still', {words: words.charAt(0).toLocaleLowerCase() + words.slice(1)}); + }); + + tail = computed(() => { + if (this.held()) { + return undefined; + } + const elapsed = this.elapsed(); + const parts: string[] = []; + if (this.kind() === 'gen') { + parts.push(this.translate.instant(elapsed < LONGER_AFTER_MS ? 'ai-assistant.work.estimate-minute' : 'ai-assistant.work.taking-longer')); + } + if (elapsed >= CLOCK_AFTER_MS) { + parts.push(aiWorkClock(elapsed)); + } + return parts.join(' · ') || undefined; + }); + + private translate = inject(TranslateService); + private zone = inject(NgZone); + private destroyRef = inject(DestroyRef); + + ngOnInit(): void { + const timer = this.zone.runOutsideAngular(() => setInterval(() => this.zone.run(() => this.now.set(Date.now())), 1000)); + this.destroyRef.onDestroy(() => clearInterval(timer)); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai.models.ts deleted file mode 100644 index 06298efabd..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai.models.ts +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -export const generatedStateImages: string[] = [ - '/assets/solution-creator/building-animated.webp', - '/assets/solution-creator/catch-animated.webp', - '/assets/solution-creator/dashboard-animated.webp', - '/assets/solution-creator/forest-animated.webp', - '/assets/solution-creator/parachute-animated.webp', - '/assets/solution-creator/rocket-animated.webp' -]; - -export const dashboardGenerateImage = '/assets/solution-creator/dashboard-animated.webp'; - -export const generateDashboardSteps = [ - { text: 'solution-creator.step-reading-device-data', delay: 0 }, - { text: 'solution-creator.step-analyzing-telemetry-attributes', delay: 2000 }, - { text: 'solution-creator.step-selecting-widgets', delay: 10000 }, - { text: 'solution-creator.step-configuring-titles-units-ranges', delay: 15000 }, - { text: 'solution-creator.step-designing-layout', delay: 25000 }, - { text: 'solution-creator.step-arranging-widgets', delay: 35000 }, - { text: 'solution-creator.step-loading-adding-finishing-touches', delay: 45000 }, -] diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts index d837940241..a85d2bcc33 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts @@ -3,48 +3,94 @@ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { SharedModule } from '@shared/shared.module'; -import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; +import { AiComposerModule } from '@home/components/ai/ai-composer.module'; import { AiAssistantPanelComponent } from '@home/components/ai/ai-assistant-panel.component'; import { AiChatMessagesComponent } from '@home/components/ai/ai-chat-messages.component'; +import { AiChatComponent } from '@home/components/ai/ai-chat.component'; import { AiApprovalCardComponent } from '@home/components/ai/ai-approval-card.component'; -import { AiRenameDialogComponent } from '@home/components/ai/ai-rename-dialog.component'; -import { AiCreditsComponent } from '@home/components/ai/ai-credits.component'; -import { AiCreditsPopupComponent } from '@home/components/ai/ai-credits-popup.component'; -import { AiLoadingModalComponent } from '@home/components/ai/ai-loading-modal.component'; -import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry-modal.component'; -import { AiAttachmentsComponent } from '@home/components/ai/ai-attachments.component'; -import { AiAttachmentPreviewDialogComponent } from '@home/components/ai/ai-attachment-preview-dialog.component'; -import { AiTipDirective } from '@home/components/ai/ai-tip.directive'; +import { AiCreditsOutComponent } from '@home/components/ai/ai-credits-out.component'; +import { AiLimitOutComponent } from '@home/components/ai/ai-limit-out.component'; +import { AiLoadLinesComponent } from '@home/components/ai/ai-load-lines.component'; +import { AiChatTitleComponent } from '@home/components/ai/ai-chat-title.component'; +import { AiWorkLineComponent } from '@home/components/ai/ai-work-line.component'; +import { AiActionLineComponent } from '@home/components/ai/ai-action-line.component'; +import { AiActionDetailComponent } from '@home/components/ai/ai-action-detail.component'; +import { AiRunSummaryComponent } from '@home/components/ai/ai-run-summary.component'; +import { AiStartedFromComponent } from '@home/components/ai/ai-started-from.component'; +import { AiRecordComponent } from '@home/components/ai/ai-record.component'; +import { AiRecordCardComponent } from '@home/components/ai/ai-record-card.component'; +import { AiRecordsComponent } from '@home/components/ai/ai-records.component'; +import { AiCardActionsComponent } from '@home/components/ai/ai-card-actions.component'; +import { AiDisclosureComponent } from '@home/components/ai/ai-disclosure.component'; +import { AiQuestionComponent } from '@home/components/ai/ai-question.component'; +import { AiNumberFieldComponent } from '@home/components/ai/ai-number-field.component'; +import { AiSecretFieldComponent } from '@home/components/ai/ai-secret-field.component'; +import { AiColorFieldComponent } from '@home/components/ai/ai-color-field.component'; +import { AiDatePanelComponent } from '@home/components/ai/ai-date-panel.component'; +import { AiStepMarkComponent } from '@home/components/ai/ai-step-mark.component'; +import { AiPlanComponent } from '@home/components/ai/ai-plan.component'; +import { AiHandOverComponent } from '@home/components/ai/ai-hand-over.component'; +import { AiArtifactPaneComponent } from '@home/components/ai/ai-artifact-pane.component'; +import { AiFileBodyComponent } from '@home/components/ai/ai-file-body.component'; @NgModule({ declarations: [ - AiPromptInputComponent, AiAssistantPanelComponent, + AiChatComponent, AiChatMessagesComponent, AiApprovalCardComponent, - AiRenameDialogComponent, - AiCreditsComponent, - AiCreditsPopupComponent, - AiLoadingModalComponent, - AiNoTelemetryModalComponent, - AiAttachmentsComponent, - AiAttachmentPreviewDialogComponent, - AiTipDirective + AiCreditsOutComponent, + AiLimitOutComponent, + AiWorkLineComponent, + AiActionLineComponent, + AiActionDetailComponent, + AiRunSummaryComponent, + AiStartedFromComponent, + AiRecordComponent, + AiRecordCardComponent, + AiRecordsComponent, + AiCardActionsComponent, + AiDisclosureComponent, + AiQuestionComponent, + AiNumberFieldComponent, + AiSecretFieldComponent, + AiColorFieldComponent, + AiDatePanelComponent, + AiStepMarkComponent, + AiPlanComponent, + AiHandOverComponent, + AiArtifactPaneComponent, + AiFileBodyComponent, + AiLoadLinesComponent, + AiChatTitleComponent ], imports: [ CommonModule, - SharedModule + SharedModule, + AiComposerModule ], exports: [ - AiPromptInputComponent, + AiComposerModule, + AiLoadLinesComponent, + AiChatTitleComponent, + AiWorkLineComponent, + AiRunSummaryComponent, AiAssistantPanelComponent, + AiChatComponent, AiChatMessagesComponent, AiApprovalCardComponent, - AiRenameDialogComponent, - AiCreditsComponent, - AiLoadingModalComponent, - AiNoTelemetryModalComponent, - AiAttachmentsComponent + AiCreditsOutComponent, + AiLimitOutComponent, + AiQuestionComponent, + AiPlanComponent, + AiHandOverComponent, + AiArtifactPaneComponent, + AiFileBodyComponent, + AiRecordComponent, + AiRecordCardComponent, + AiRecordsComponent, + AiCardActionsComponent, + AiDisclosureComponent ] }) export class AiModule {} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html new file mode 100644 index 0000000000..4a24e86361 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html @@ -0,0 +1,34 @@ + +
+ @if (dashboards.length > 1) { +
+ @for (dashboard of dashboards; track dashboard.name; let index = $index) { + + } +
+ } +
+ @for (dashboard of dashboards; track dashboard.name; let index = $index) { +
+
+ +
+

{{ dashboard.name }}

+ {{ dashboard.assignedTo }} +
+
+ @if (dashboard.overview) { +

{{ dashboard.overview }}

+ } + +
+ } @empty { +

{{ 'solution-creator.pane.no-dashboards' | translate }}

+ } +
+
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.scss new file mode 100644 index 0000000000..ac9767e0fe --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.scss @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.sol-dash { + padding: 16px var(--art-x) 8px; + + & + .sol-dash { + border-top: 1px solid var(--tb-line); + } +} + +.sol-dash-head { + display: flex; + align-items: flex-start; + gap: 10px; + + > .mat-icon { + flex: none; + margin-top: 2px; + color: var(--entity-view-fg); + } + + h3 { + margin: 0; + font: 500 var(--chat-head)/var(--chat-head-lh) var(--tb-font); + color: var(--tb-ink); + } + + small { + display: block; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-ink-60); + } +} + +.sol-dash-lead { + margin: 10px 0 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); +} + +.sol-dash-doc { + display: block; + margin-top: 4px; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.ts new file mode 100644 index 0000000000..d520c1f995 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.ts @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, inject, Input, OnDestroy, signal } from '@angular/core'; +import { DashboardsOverview } from '@shared/models/solution-creator.models'; + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-dashboards', + templateUrl: './solution-dashboards.component.html', + styleUrls: ['./solution-pane.scss', './solution-dashboards.component.scss'], + standalone: false +}) +export class SolutionDashboardsComponent implements AfterViewInit, OnDestroy { + + @Input({required: true}) dashboards: DashboardsOverview[] = []; + + readonly markdownStyles = [ + '.tb-markdown-view h1, .tb-markdown-view h2, .tb-markdown-view h3 { display: none; }', + '.tb-markdown-view h4, .tb-markdown-view h5 { font-size: 14px; line-height: 20px; font-weight: 500; margin: 16px 0 6px; padding: 0; }', + '.tb-markdown-view p, .tb-markdown-view li { font-size: 14px; line-height: 20px; padding: 0; }', + '.tb-markdown-view ul, .tb-markdown-view ol { padding-left: 20px; margin: 0; }' + ]; + + active = signal(0); + + wide = signal(false); + + private host = inject>(ElementRef); + private resize: ResizeObserver; + private scroller: HTMLElement | null = null; + private scrollListener = () => this.onScroll(); + + ngAfterViewInit(): void { + this.resize = new ResizeObserver(() => this.wide.set(this.host.nativeElement.clientWidth >= 660 && this.dashboards?.length > 1)); + this.resize.observe(this.host.nativeElement); + this.scroller = this.host.nativeElement.closest('.art-pane-body') as HTMLElement; + this.scroller?.addEventListener('scroll', this.scrollListener, {passive: true}); + } + + ngOnDestroy(): void { + this.resize?.disconnect(); + this.scroller?.removeEventListener('scroll', this.scrollListener); + } + + details(dashboard: DashboardsOverview): string { + const description = dashboard.description ?? ''; + if (!dashboard.overview) { + return description; + } + const lines = description.split('\n'); + const start = lines.findIndex(line => /^\s*(#{4,}\s|[-*+]\s|\d+[.)]\s|\*\*[^*]+\*\*:?\s*$)/.test(line)); + return start > 0 ? lines.slice(start).join('\n') : description; + } + + goTo(index: number): void { + this.active.set(index); + const target = this.host.nativeElement.querySelector(`[data-dash="${index}"]`) as HTMLElement; + if (target && this.scroller) { + const tabs = this.wide() ? 0 : (this.host.nativeElement.querySelector('.sol-tabs') as HTMLElement)?.offsetHeight ?? 0; + this.scroller.scrollTo({ + top: this.scroller.scrollTop + target.getBoundingClientRect().top - this.scroller.getBoundingClientRect().top - tabs, + behavior: 'smooth' + }); + } + } + + private onScroll(): void { + if (!this.scroller) { + return; + } + const top = this.scroller.getBoundingClientRect().top + (this.wide() ? 8 : 60); + let current = 0; + this.dashboards.forEach((_, index) => { + const el = this.host.nativeElement.querySelector(`[data-dash="${index}"]`) as HTMLElement; + if (el && el.getBoundingClientRect().top <= top) { + current = index; + } + }); + if (current !== this.active()) { + this.active.set(current); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html new file mode 100644 index 0000000000..3289cdf830 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html @@ -0,0 +1,134 @@ + +@if (creating()) { +} @else if (installed() && !bannerClosed()) { +
+ +
+ {{ 'solution-creator.pane.installed' | translate }} + {{ 'solution-creator.pane.installed-line' | translate: {entities: entityCount(), dashboards: dashboardCount()} }} +
+ @if (hasMain()) { + + } + +
+} @else if (!installed()) { +

{{ 'solution-creator.pane.not-installed' | translate }}

+} +
+ @for (section of sections(); track section.id) { +
+

+ @if (section.link) { + + {{ section.title | translate }} + + } @else { + {{ section.title | translate }} + } +

+
+ + + @for (row of section.rows; track row.key) { + + + @switch (section.id) { + @case ('dashboards') { + + + } + @case ('users') { + + + } + @case ('profiles') { + + } + @case ('roles') { + + } + @case ('alarms') { + + } + @case ('cfs') { + } + @default { + + } + } + + + } + +
+ @if (link(row.type, row); as url) { + + {{ row.primary.additionalData?.name }} + + } @else { + + {{ row.primary.additionalData?.name }} + + } + {{ row.details.role }} + + @if (link(row.type, row); as url) { + + open_in_new{{ 'solution-creator.pane.open' | translate }} + + } + @if (canViewAs(row)) { + + } + + {{ row.details.role }}{{ row.details.where }}{{ row.details.kindLabel }} +
+ @for (op of row.details.ops ?? []; track op) { + {{ op }} + } +
+
+
+ @for (severity of row.details.severities ?? []; track severity) { + + {{ severityLabel(severity) | translate }} + + } +
+
+ @if (row.details.chip; as chip) { + {{ chip.label }} + } + + @if (row.progress === 'wait') { + + } @else if (row.progress === 'now') { + + + + } @else { + + {{ statusIcon(row) }} + + } +
+ } @empty { +

{{ 'solution-creator.pane.nothing-created' | translate }}

+ } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.scss new file mode 100644 index 0000000000..5a47c2b3ef --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.scss @@ -0,0 +1,198 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.sol-done { + position: sticky; + top: 0; + z-index: 2; + display: flex; + align-items: center; + gap: 16px; + padding: 22px calc(var(--art-x) + 36px) 22px var(--art-x); + background: linear-gradient(90deg in oklab, + color-mix(in oklab, var(--ai-light-teal) 42%, var(--tb-surface)) 0%, + color-mix(in oklab, var(--ai-light-aqua) 26%, var(--tb-surface)) 48%, + var(--tb-surface) 100%); +} + +.sol-done-mark { + --ai-mark-fill: linear-gradient(var(--tb-surface), var(--tb-surface)); + --ai-mark-edge: inset 0 0 0 1px color-mix(in srgb, var(--tb-ink) 10%, transparent), 0 1px 2px rgb(16 24 40 / 0.06); + --ai-mark-ink: var(--tb-ok); + --ai-mark-ink-fill: linear-gradient(var(--tb-ok), var(--tb-ok)); + animation: none; +} + +.sol-done-t { + flex: 1; + display: grid; + gap: 2px; + min-width: 0; + + b { + font: 500 var(--chat-head)/var(--chat-head-lh) var(--tb-font); + color: var(--tb-ink); + } + + span { + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } +} + +.sol-done-go { + flex: none; + --mat-button-filled-container-color: var(--ai-action); + --mat-button-filled-label-text-color: var(--ai-on-action); +} + +.sol-done-x { + position: absolute; + top: 8px; + right: 8px; + width: 32px; + height: 32px; + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: var(--tb-ink-54); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } +} + +.sol-not-installed { + margin: 0; + padding: 16px var(--art-x) 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); +} + +.sol-installed-table { + table-layout: fixed; + + td.sol-installed-name { + width: 44%; + } + + td.act { + width: 170px; + } + + td.stc { + width: 44px; + } + + td code.k-ent, td .k-sev, td .sol-op { + vertical-align: baseline; + } + +} + +.sol-acts { + display: inline-flex; + gap: 2px; +} + +.sol-act.mat-mdc-button { + height: 36px; + margin: -8px 0 -6px; + padding: 0 8px; + gap: 8px; + border: 1px solid transparent; + line-height: 36px; + --mat-button-text-label-text-color: var(--tb-ink-76); + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + margin: 0 0 0 -4px; + } +} + +:host.narrow .sol-acts { + flex-direction: column; + align-items: flex-start; + gap: 8px; +} + +:host.narrow .sol-installed-table { + table-layout: auto; + + td.sol-installed-name { + width: auto; + } + + td.act { + width: 1px; + } +} + +.sol-st { + display: inline-flex; + align-items: center; + justify-content: center; + box-sizing: border-box; + width: 18px; + height: 18px; + margin-top: 1px; + border-radius: 50%; + color: var(--tb-surface); + cursor: default; + + .mat-icon { + font-size: 13px; + width: 13px; + height: 13px; + line-height: 13px; + font-weight: 500; + } + + &.wait { border: 1.5px solid var(--tb-ink-38); } + &.now { color: var(--ai-teal-500); } + &.ok { background: var(--tb-ok); } + &.warn { background: var(--tb-caution); } + &.error { background: var(--tb-crit); } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.sol-infos.creating tbody tr { + animation: sol-row-in .2s cubic-bezier(.2, 0, 0, 1); +} + +@keyframes sol-row-in { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .sol-infos.creating tbody tr { + animation: none; + } +} + +.sol-st.now tb-ai-spin { + --spin: 18px; +} + +tr.waiting > td:not(.stc) { + opacity: .42; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts new file mode 100644 index 0000000000..fc419a23f8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts @@ -0,0 +1,322 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { roleOperations } from './solution-overview.component'; +import { ChangeDetectionStrategy, Component, computed, DestroyRef, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AuthService } from '@core/auth/auth.service'; +import { EntityResult, SolutionCreatorInfo, SolutionInstallProgress, SolutionProgressItem } from '@shared/models/solution-creator.models'; +import { + baseDetailsPageByEntityType, + EntityType, + entityTypeTranslations, + groupUrlPrefixByEntityType +} from '@shared/models/entity-type.models'; +import { AlarmSeverity, alarmSeverityColors, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { + AggregatedEntityResult, + aggregateByName, + IssueStatus +} from '@home/components/ai/solution/solution-info/issues-aggregation'; + +interface InstalledSection { + id: string; + title: string; + link: string | null; + rows: InstalledRow[]; +} + +interface RowChip { + label: string; + icon: string; + palette: string; +} + +interface RowDetails { + role?: string; + where?: string; + chip?: RowChip; + kindLabel?: string; + ops?: string[]; + severities?: AlarmSeverity[]; +} + +type InstalledRow = AggregatedEntityResult & { + type: EntityType; + icon: string; + palette: string; + details: RowDetails; + progress?: 'wait' | 'now'; +}; + +interface SectionSpec { + id: string; + types: EntityType[]; + title: string; + link: string | null; +} + +const GROUPS: SectionSpec[] = [ + {id: 'dashboards', types: [EntityType.DASHBOARD], title: 'entity.type-dashboards', link: '/dashboards/all'}, + {id: 'devices', types: [EntityType.DEVICE], title: 'entity.type-devices', link: '/entities/devices/all'}, + {id: 'assets', types: [EntityType.ASSET], title: 'entity.type-assets', link: '/entities/assets/all'}, + {id: 'customers', types: [EntityType.CUSTOMER], title: 'entity.type-customers', link: '/customers/all'}, + {id: 'users', types: [EntityType.USER], title: 'entity.type-users', link: '/users/all'}, + {id: 'profiles', types: [EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE], title: 'solution-creator.pane.profiles', link: '/profiles/deviceProfiles'}, + {id: 'roles', types: [EntityType.ROLE], title: 'entity.type-roles', link: '/security-settings/roles'}, + {id: 'groups', types: [EntityType.ENTITY_GROUP], title: 'entity.type-entity-groups', link: null}, + {id: 'cfs', types: [EntityType.CALCULATED_FIELD], title: 'entity.type-calculated-fields', link: '/calculatedFields'}, + {id: 'alarms', types: [EntityType.ALARM], title: 'solution-creator.pane.alarm-rules', link: '/alarms/alarm-rules'}, + {id: 'chains', types: [EntityType.RULE_CHAIN], title: 'entity.type-rulechains', link: null} +]; + + +const SECTIONS: EntityType[] = GROUPS.flatMap(group => group.types); + +const SUPPORTING: EntityType[] = [EntityType.ENTITY_GROUP, EntityType.RULE_CHAIN]; + +const GENERATED: EntityType[] = [EntityType.DEVICE, EntityType.ASSET, EntityType.CUSTOMER, EntityType.USER]; + +const STEP_MS = 160; + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-installed', + templateUrl: './solution-installed.component.html', + styleUrls: ['./solution-pane.scss', './solution-installed.component.scss'], + standalone: false, + host: { + '[class.narrow]': 'narrow()' + } +}) +export class SolutionInstalledComponent { + + solution = input.required(); + creating = input(false); + items = input(null); + stage = input(null); + createShare = input(0.85); + seconds = input(90); + startedAt = input(0); + + @Output() openMain = new EventEmitter(); + + private translate = inject(TranslateService); + private authService = inject(AuthService); + + bannerClosed = signal(false); + + narrow = signal(false); + + private shown = signal(-1); + private elapsed = signal(0); + + private planned = computed(() => { + const items = this.items() ?? []; + return SECTIONS.flatMap(type => items.filter(item => item.type === type)); + }); + + private target = computed(() => { + const planned = this.planned(); + if (!planned.length) { + return 0; + } + const share = this.createShare(); + const install = this.stage() === 'INSTALL'; + const ready = planned.filter(item => install ? item.state === 'DONE' : item.state !== 'WORKING').length / planned.length; + let count = Math.floor(planned.length * (install ? share + (1 - share) * ready : share * ready)); + const pending = planned.findIndex(item => !item.name); + if (!install && pending >= 0) { + count = Math.min(count, pending); + } else if (!install && !planned.some(item => GENERATED.includes(item.type))) { + count = Math.min(count, Math.max(0, planned.filter(item => item.type === EntityType.DASHBOARD).length - 1)); + } + const paced = Math.floor(planned.length * this.elapsed() / Math.max(1, this.seconds())); + return Math.min(count, paced, planned.length - 1); + }); + + constructor() { + const created = Date.now(); + const timer = setInterval(() => { + this.elapsed.set((Date.now() - (this.startedAt() || created)) / 1000); + const target = this.target(); + if (this.shown() < 0) { + this.shown.set(target); + } else if (this.shown() < target) { + this.shown.update(count => count + 1); + } + }, STEP_MS); + const host = inject>(ElementRef).nativeElement; + const resize = new ResizeObserver(() => this.narrow.set(host.clientWidth <= 560)); + resize.observe(host); + inject(DestroyRef).onDestroy(() => { + clearInterval(timer); + resize.disconnect(); + }); + } + + installed = computed(() => !!this.solution()?.metadata?.installed); + + sections = computed(() => { + const results = this.solution()?.metadata?.installResult?.entityResults; + const items = this.items(); + if (items?.length) { + return this.plannedSections(items, results ?? {}); + } + if (!results) { + return []; + } + return this.grouped(type => aggregateByName(type, results[type]) + .filter(row => !SUPPORTING.includes(type) || row.status !== IssueStatus.OK) + .map(row => this.row(type, row))); + }); + + entityCount = computed(() => this.sections() + .filter(section => section.id !== 'dashboards') + .reduce((count, section) => count + section.rows.length, 0)); + + dashboardCount = computed(() => this.sections().find(section => section.id === 'dashboards')?.rows.length ?? 0); + + hasMain = computed(() => !!this.solution()?.metadata?.installResult?.mainDashboardId); + + private plannedSections(items: SolutionProgressItem[], results: Partial>): InstalledSection[] { + const shown = Math.max(0, this.shown()); + const install = this.stage() === 'INSTALL'; + let index = 0; + return this.grouped(type => { + const created = aggregateByName(type, results[type]); + return items.filter(item => item.type === type).map(item => { + const position = index++; + const result = item.name ? created.find(row => row.primary?.additionalData?.name === item.name) : undefined; + if (position < shown && install && result && item.state === 'DONE') { + return this.row(type, result, item); + } + const name = item.name ?? this.translate.instant('solution-creator.pane.pending-' + type, {profile: item.profile}); + return this.row(type, { + key: item.name ? `${type}:${item.name}` : `${type}:pending:${item.profile}`, + primary: {additionalData: {name}} as EntityResult, + status: IssueStatus.OK, + errors: [], + warnings: [] + }, item, position < shown ? undefined : position === shown ? 'now' : 'wait'); + }); + }); + } + + private grouped(rowsOf: (type: EntityType) => InstalledRow[]): InstalledSection[] { + return GROUPS + .map(group => ({id: group.id, title: group.title, link: group.link, rows: group.types.flatMap(type => rowsOf(type))})) + .filter(section => section.rows.length); + } + + private row(type: EntityType, row: AggregatedEntityResult, item?: SolutionProgressItem, progress?: 'wait' | 'now'): InstalledRow { + const kind = aiEntityKind(type === EntityType.ALARM ? 'ALARM_RULE' : type === EntityType.ROLE ? EntityType.USER : type); + const details = item && !item.name ? {} : this.detailsOf(type, row.primary?.additionalData ?? {}, item); + return {...row, type, icon: kind.icon, palette: kind.palette, details, progress}; + } + + private detailsOf(type: EntityType, data: Record, item?: SolutionProgressItem): RowDetails { + const solution = this.solution()?.data; + const name: string = item?.name ?? data.name; + switch (type) { + case EntityType.DASHBOARD: + return {role: solution?.dashboardsOverview?.find(dashboard => dashboard.name === name)?.assignedTo}; + case EntityType.DEVICE: + case EntityType.ASSET: + case EntityType.CUSTOMER: { + const profile = item?.profile ?? data.type ?? this.entityOf(type, name)?.profile; + const chipKind = aiEntityKind(type === EntityType.DEVICE ? EntityType.DEVICE_PROFILE : type); + return profile ? {chip: {label: profile, icon: chipKind.icon, palette: chipKind.palette}} : {}; + } + case EntityType.USER: { + const user = this.entityOf(type, name); + const customer = item ? item.customer : (data.customer ?? user?.customer); + return {role: item?.profile ?? user?.profile, where: customer || this.translate.instant('tenant.tenant')}; + } + case EntityType.DEVICE_PROFILE: + return {kindLabel: this.translate.instant('entity.type-device')}; + case EntityType.ASSET_PROFILE: + return {kindLabel: this.translate.instant('entity.type-asset')}; + case EntityType.ROLE: { + const permissions = solution?.solutionDescriptor?.iam?.find(role => role.name === name)?.permissions ?? ''; + const operations = roleOperations(permissions); + return {ops: operations.length ? [this.translate.instant('solution-creator.pane.all-resources'), + ...operations.map(operation => this.translate.instant('solution-creator.pane.op-' + operation))] : []}; + } + case EntityType.ALARM: + return {severities: data.severities?.length ? data.severities + : solution?.solutionDescriptor?.alarms?.find(alarm => alarm.alarmName === name)?.severities ?? []}; + default: + return {}; + } + } + + private entityOf(type: EntityType, name: string): Record | undefined { + const entities = this.solution()?.data?.entities; + const list: Array> = type === EntityType.DEVICE ? entities?.devices + : type === EntityType.ASSET ? entities?.assets + : type === EntityType.CUSTOMER ? entities?.customers + : type === EntityType.USER ? entities?.users : null; + return list?.find(entity => type === EntityType.USER + ? [[entity.firstName, entity.lastName].filter(Boolean).join(' '), entity.email].includes(name) + : entity.name === name); + } + + link(type: EntityType, row: AggregatedEntityResult): string | null { + const entity = row.primary; + if (!entity?.id?.id || row.status === IssueStatus.ERROR) { + return null; + } + if (type === EntityType.ENTITY_GROUP) { + const prefix = groupUrlPrefixByEntityType.get(entity.additionalData?.groupType as EntityType); + return prefix ? `${prefix}/${entity.id.id}` : null; + } + const base = baseDetailsPageByEntityType.get(entity.id.entityType as EntityType); + return base ? `${base}/${entity.id.id}` : null; + } + + severityColor(severity: AlarmSeverity): string { + return alarmSeverityColors.get(severity) ?? null; + } + + severityLabel(severity: AlarmSeverity): string { + return alarmSeverityTranslations.get(severity) ?? severity; + } + + statusIcon(row: AggregatedEntityResult): string { + return row.status === IssueStatus.ERROR ? 'close' : row.status === IssueStatus.WARN ? 'priority_high' : 'check'; + } + + statusTone(row: AggregatedEntityResult): string { + return row.status === IssueStatus.ERROR ? 'error' : row.status === IssueStatus.WARN ? 'warn' : 'ok'; + } + + statusTip(row: AggregatedEntityResult): string { + const word = this.translate.instant('solution-creator.pane.status-' + this.statusTone(row)); + const messages = [...row.errors, ...row.warnings].map(entry => entry.error?.message).filter(Boolean); + if (!messages.length) { + return word; + } + return row.status === IssueStatus.WARN ? messages.join('; ') : `${word}: ${messages.join('; ')}`; + } + + severityTone(severity: AlarmSeverity): string { + return (severity ?? '').toLowerCase(); + } + + canViewAs(row: AggregatedEntityResult): boolean { + return !!row.primary?.additionalData?.userId && row.status !== IssueStatus.ERROR; + } + + viewAs(row: AggregatedEntityResult): void { + const entity: EntityResult = row.primary; + const userId = entity.additionalData.userId; + const tenantUser = !this.findUser(userId)?.additionalData?.customer; + this.authService.redirectUrl = tenantUser ? `/dashboards/all/${entity.id.id}` : `/dashboards/${entity.id.id}`; + this.authService.loginAsUser(userId).subscribe(() => {}); + } + + private findUser(userId: string): EntityResult | undefined { + return this.solution()?.metadata?.installResult?.entityResults?.[EntityType.USER]?.find(user => user.id?.id === userId); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.html new file mode 100644 index 0000000000..b7f9d7f10b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.html @@ -0,0 +1,8 @@ + + diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.scss new file mode 100644 index 0000000000..e09b2e6757 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.scss @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: flex; + flex-direction: column; + min-height: 0; +} + +tb-ai-file-body { + --art-x: 16px; + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.ts new file mode 100644 index 0000000000..10b36b200f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.ts @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, EventEmitter, input, Output, viewChild } from '@angular/core'; +import { AiFile, aiFileOf } from '@home/components/ai/ai-file.models'; +import { AiFileBodyComponent, AiFileSaver } from '@home/components/ai/ai-file-body.component'; + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-json', + templateUrl: './solution-json.component.html', + styleUrls: ['./solution-json.component.scss'], + standalone: false +}) +export class SolutionJsonComponent { + + value = input(null); + + fileName = input('solution.json'); + + wrap = input(false); + + whitespace = input(false); + + @Output() applied = new EventEmitter(); + + @Output() discarded = new EventEmitter(); + + body = viewChild.required(AiFileBodyComponent); + + file = computed(() => aiFileOf('solution-json::' + this.fileName(), + {name: this.fileName(), content: JSON.stringify(this.value() ?? null, null, 2) + '\n'})); + + error = computed(() => { + const body = this.body(); + if (!body.editing()) { + return ''; + } + try { + JSON.parse(body.draft()); + return ''; + } catch (e) { + return (e as Error).message; + } + }); + + readonly saver: AiFileSaver = content => { + try { + this.applied.emit(JSON.parse(content)); + return Promise.resolve(true); + } catch { + return Promise.resolve(false); + } + }; + + text(): string { + const body = this.body(); + return body.editing() ? body.draft() : this.file().content; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html new file mode 100644 index 0000000000..871ee4af02 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html @@ -0,0 +1,287 @@ + +
+
+ @for (section of sections(); track section.id) { + + } +
+
+
+

{{ 'solution-creator.pane.profiles' | translate }}

+
+ + +
+
+ @if (mode() === 'list') { + + + + + + + + + + + @for (profile of profiles; track profile.name + profile.entityType) { + @let key = 'profile:' + profile.entityType + ':' + profile.name; + + + + + + + @if (open() === key) { + + + + } + } + +
{{ 'solution-creator.pane.name' | translate }}{{ 'solution-creator.pane.type' | translate }}{{ 'solution-creator.pane.data' | translate }}
+ + @if (profile.name?.trim()) {{{ profile.name }}} @else {{{ typeLabel(profile) }} {{ $index + 1 }}} + + {{ typeLabel(profile) }}{{ dataOf(profile) }}expand_more
+ +
+ } @else { +
+ + + + + + + + + + {{ cluster.label }} + + + + + + + + + + + @if (link.label) { + +
{{ link.label }}
+
+ } +
+
+
+
+ @if (schemaEntity(); as entity) { +
+
+ {{ entity.name }} +
+ +
+ } + } + +

{{ 'solution-creator.pane.roles' | translate }}

+ @if (descriptor?.iam?.length) { + + + + + + + + + + @for (iam of descriptor.iam; track iam.name) { + + + + + + } + +
{{ 'solution-creator.pane.role' | translate }}{{ 'solution-creator.pane.operations' | translate }}{{ 'solution-creator.pane.on' | translate }}
+ {{ iam.name }} + +
+ @if (operations(iam).length) { + {{ 'solution-creator.pane.all-resources' | translate }} + } + @for (operation of operations(iam); track operation) { + {{ ('solution-creator.pane.op-' + operation) | translate }} + } @empty { + {{ iam.permissions || '—' }} + } +
+
{{ iam.description }}
+ } @else { +

{{ 'solution-creator.pane.no-roles' | translate }}

+ } + +

{{ 'solution-creator.pane.calculated-fields' | translate }}

+ @if (descriptor?.metrics?.length) { + + + + + + + + + @for (metric of descriptor.metrics; track metric.calculatedFieldName) { + + + + + } + +
{{ 'solution-creator.pane.name' | translate }}{{ 'solution-creator.pane.calculates' | translate }}
+ + {{ metric.calculatedFieldName }} + + @if (metric.profileName) { +
+ {{ metric.profileName }} +
+ } +
{{ metric.calculation }}
+ } @else { +

{{ 'solution-creator.pane.no-calculated-fields' | translate }}

+ } + +

{{ 'solution-creator.pane.alarms' | translate }}

+ @if (descriptor?.alarms?.length) { + + + + + + + + + + @for (alarm of descriptor.alarms; track alarm.alarmName) { + @let key = alarmKey(alarm); + + + + + + @if (open() === key) { + + + + } + } + +
{{ 'solution-creator.pane.alarm-rule' | translate }}{{ 'solution-creator.pane.severity' | translate }}
+ + {{ alarm.alarmName }} + + @if (alarm.condition) { +
{{ alarm.condition }}
+ } +
+
+ @for (severity of alarm.severities; track severity) { + + {{ severityLabel(severity) | translate }} + + } +
+
expand_more
+
+
{{ 'solution-creator.pane.profiles' | translate }}
+
+
+ @for (profile of alarm.profileNames ?? []; track profile) { + {{ profile }} + } +
+
+
+ +
+ } @else { +

{{ 'solution-creator.pane.no-alarms' | translate }}

+ } +
+
+ + +
+ @if (profile.scope) { +
{{ 'solution-creator.pane.scope' | translate }}
+
{{ profile.scope }}
+ } + @if (profile.description) { +
{{ 'solution-creator.pane.description' | translate }}
+
{{ profile.description }}
+ } +
+
+ + +
+ @if (keysOf() === 'telemetry') { +
    + @for (item of profile.telemetry ?? []; track item.key) { +
  • + {{ item.key }} + {{ (item.telemetryType === 'ATTRIBUTE' ? 'solution-creator.pane.attribute' : 'solution-creator.pane.time-series') | translate }} + @if (item.calculatedFieldName) { + ƒx + } + {{ item.dataType }}{{ item.units ? ' · ' + item.units : '' }} +
  • + } @empty { +
  • {{ 'solution-creator.pane.no-keys' | translate }}
  • + } +
+ } @else { +
    + @for (relation of relationsOf(profile); track $index) { +
  • + {{ relation.parent }} + {{ relation.type }}{{ relation.cardinality ? ' (' + relation.cardinality + ')' : '' }} + {{ relation.child }} +
  • + } @empty { +
  • {{ 'solution-creator.pane.no-relations' | translate }}
  • + } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.scss new file mode 100644 index 0000000000..f23f0ea550 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.scss @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.sol-schema { + height: 380px; + margin: 0 var(--art-x); + overflow: hidden; + + .sol-graph { + display: block; + width: 100%; + height: 100%; + } + + ::ng-deep { + .sol-band rect { + fill: color-mix(in oklab, var(--ai-light-lilac) 34%, var(--tb-surface)); + } + + .sol-band.tenant rect { + fill: color-mix(in oklab, var(--ai-light-peach) 40%, var(--tb-surface)); + } + + .sol-band-title { + font: 400 12px var(--tb-font); + fill: var(--tb-ink-60); + } + + .sol-edge .line { + stroke: var(--tb-ink-38); + fill: none; + } + + .sol-arrow-head { + fill: var(--tb-ink-38); + } + + .sol-edge-label { + width: fit-content; + max-width: 120px; + margin: 0 auto; + padding: 1px 6px; + border: 1px solid var(--tb-line); + border-radius: 4px; + background: var(--tb-surface); + font: 400 12px/18px var(--tb-font); + color: var(--tb-ink-76); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + text-align: center; + } + + .sol-box { + display: flex; + flex-direction: column; + justify-content: center; + gap: 2px; + padding: 8px 12px; + box-sizing: border-box; + border: 1px solid var(--tb-line); + border-left: 3px solid var(--tb-ink-38); + border-radius: 8px; + background: var(--tb-surface); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06); + text-align: left; + cursor: pointer; + font-family: var(--tb-font); + + b { + font: 500 14px/18px var(--tb-font); + color: var(--tb-ink); + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + span { + font: 400 12px/16px var(--tb-font); + color: var(--tb-ink-60); + } + + &[data-pal="device"] { border-left-color: var(--entity-device-fg); } + &[data-pal="people"] { border-left-color: var(--entity-people-fg); } + &[data-pal="solution"] { border-left-color: var(--entity-solution-fg); } + &[data-pal="path"] { border-left-color: var(--entity-path-fg); } + + &:hover, &.on { + border-color: var(--tb-ink-38); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } + } +} + +.sol-schema-detail { + margin: 12px var(--art-x) 0; + padding: 12px 14px 14px; + border-radius: 8px; + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts new file mode 100644 index 0000000000..0ec3e04fb7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts @@ -0,0 +1,232 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + AfterViewInit, + ChangeDetectionStrategy, + Component, + computed, + ElementRef, + EventEmitter, + inject, + Input, + OnChanges, + OnDestroy, + Output, + signal, + ViewChild +} from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { ClusterNode, Edge, GraphComponent, Node } from '@swimlane/ngx-graph'; +import { DialogService } from '@core/services/dialog.service'; +import { + SolutionDescriptor, + SolutionDescriptorAlarm, + SolutionDescriptorEntityBase, + SolutionDescriptorEntityBaseRelation, + SolutionDescriptorIam +} from '@shared/models/solution-creator.models'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { AlarmSeverity, alarmSeverityColors, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { buildSolutionSchema } from '@home/components/ai/solution/pane/solution-schema'; + +type SectionId = 'profiles' | 'roles' | 'metrics' | 'alarms'; + +interface Section { + id: SectionId; + title: string; +} + +const OPERATIONS: Record = {C: 'create', R: 'read', U: 'update', D: 'delete'}; + +export function roleOperations(permissions: string | undefined): string[] { + const operations = (permissions ?? '').toUpperCase().split('').filter(letter => OPERATIONS[letter]).map(letter => OPERATIONS[letter]); + return operations.length === Object.keys(OPERATIONS).length ? ['all'] : operations; +} + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-overview', + templateUrl: './solution-overview.component.html', + styleUrls: ['./solution-pane.scss', './solution-overview.component.scss'], + standalone: false +}) +export class SolutionOverviewComponent implements OnChanges, AfterViewInit, OnDestroy { + + @Input({required: true}) descriptor: SolutionDescriptor; + + @Output() descriptorChange = new EventEmitter(); + + @ViewChild('graphContainer') graphContainer: ElementRef; + @ViewChild(GraphComponent) graphComponent: GraphComponent; + + private translate = inject(TranslateService); + private dialog = inject(DialogService); + private host = inject>(ElementRef); + + mode = signal<'list' | 'schema'>('list'); + open = signal(null); + keysOf = signal<'telemetry' | 'relations'>('telemetry'); + active = signal('profiles'); + wide = signal(false); + + profiles: SolutionDescriptorEntityBase[] = []; + nodes: Node[] = []; + links: Edge[] = []; + clusters: ClusterNode[] = []; + + sections = computed(() => [ + {id: 'profiles', title: 'solution-creator.pane.profiles'}, + {id: 'roles', title: 'solution-creator.pane.roles'}, + {id: 'metrics', title: 'solution-creator.pane.calculated-fields'}, + {id: 'alarms', title: 'solution-creator.pane.alarms'} + ]); + + private resize: ResizeObserver; + private scroller: HTMLElement | null = null; + private scrollListener = () => this.scroller && this.onScroll(this.scroller); + private graphResize: ResizeObserver; + + ngOnChanges(): void { + this.profiles = this.descriptor ? Object.values(this.descriptor.entityProfiles ?? {}).flat() as SolutionDescriptorEntityBase[] : []; + if (this.mode() === 'schema') { + this.buildSchema(); + } + } + + ngAfterViewInit(): void { + this.resize = new ResizeObserver(() => this.wide.set(this.host.nativeElement.clientWidth >= 660)); + this.resize.observe(this.host.nativeElement); + this.scroller = this.host.nativeElement.closest('.art-pane-body') as HTMLElement; + this.scroller?.addEventListener('scroll', this.scrollListener, {passive: true}); + } + + ngOnDestroy(): void { + this.resize?.disconnect(); + this.graphResize?.disconnect(); + this.scroller?.removeEventListener('scroll', this.scrollListener); + } + + severityColor(severity: string): string { + return alarmSeverityColors.get(severity?.toUpperCase() as AlarmSeverity) ?? null; + } + + severityTone(severity: string): string { + return (severity ?? '').toLowerCase(); + } + + severityLabel(severity: string): string { + return alarmSeverityTranslations.get(severity?.toUpperCase() as AlarmSeverity) ?? severity; + } + + setMode(mode: 'list' | 'schema'): void { + this.mode.set(mode); + if (mode === 'schema') { + this.buildSchema(); + requestAnimationFrame(() => this.observeGraph()); + } + } + + toggle(key: string): void { + this.open.set(this.open() === key ? null : key); + this.keysOf.set('telemetry'); + } + + goTo(section: SectionId): void { + this.active.set(section); + const target = this.host.nativeElement.querySelector(`[data-sec="${section}"]`) as HTMLElement; + const scroller = this.host.nativeElement.closest('.art-pane-body') as HTMLElement; + if (target && scroller) { + const tabs = this.wide() ? 0 : (this.host.nativeElement.querySelector('.sol-tabs') as HTMLElement)?.offsetHeight ?? 0; + scroller.scrollTo({top: scroller.scrollTop + target.getBoundingClientRect().top - scroller.getBoundingClientRect().top - tabs, behavior: 'smooth'}); + } + } + + onScroll(scroller: HTMLElement): void { + const top = scroller.getBoundingClientRect().top + (this.wide() ? 8 : 60); + let current: SectionId = 'profiles'; + for (const section of this.sections()) { + const el = this.host.nativeElement.querySelector(`[data-sec="${section.id}"]`) as HTMLElement; + if (el && el.getBoundingClientRect().top <= top) { + current = section.id; + } + } + if (current !== this.active()) { + this.active.set(current); + } + } + + kind(entity: SolutionDescriptorEntityBase): {icon: string; palette: string} { + return aiEntityKind((entity.entityType ?? '').toUpperCase()); + } + + typeLabel(entity: SolutionDescriptorEntityBase): string { + const type = (entity.entityType ?? '').toLowerCase(); + return type ? type.charAt(0).toUpperCase() + type.slice(1) : ''; + } + + relationsOf(entity: SolutionDescriptorEntityBase): SolutionDescriptorEntityBaseRelation[] { + return (this.descriptor?.relations ?? []).filter(relation => relation.parent === entity.name || relation.child === entity.name); + } + + dataOf(entity: SolutionDescriptorEntityBase): string { + const keys = entity.telemetry?.length ?? 0; + const relations = this.relationsOf(entity).length; + const parts = []; + if (keys) { + parts.push(this.translate.instant('solution-creator.pane.keys', {count: keys})); + } + if (relations) { + parts.push(this.translate.instant('solution-creator.pane.relations', {count: relations})); + } + return parts.join(' · ') || '—'; + } + + operations(iam: SolutionDescriptorIam): string[] { + return roleOperations(iam.permissions); + } + + alarmKey(alarm: SolutionDescriptorAlarm): string { + return 'alarm:' + alarm.alarmName; + } + + removeAlarm(alarm: SolutionDescriptorAlarm): void { + this.dialog.confirm( + this.translate.instant('solution-creator.delete-alarm-title'), + this.translate.instant('solution-creator.delete-alarm-text'), + null, + this.translate.instant('action.delete') + ).subscribe(confirmed => { + if (confirmed) { + this.open.set(null); + this.descriptorChange.emit({...this.descriptor, alarms: this.descriptor.alarms.filter(item => item !== alarm)}); + } + }); + } + + openFromSchema(node: Node): void { + const entity = node.data?.entity as SolutionDescriptorEntityBase; + if (entity) { + this.open.set(this.open() === 'schema:' + entity.name ? null : 'schema:' + entity.name); + } + } + + schemaEntity(): SolutionDescriptorEntityBase | undefined { + const key = this.open(); + return key?.startsWith('schema:') ? this.profiles.find(profile => 'schema:' + profile.name === key) : undefined; + } + + private buildSchema(): void { + const schema = buildSolutionSchema(this.descriptor, this.profiles); + this.nodes = schema.nodes; + this.links = schema.links; + this.clusters = schema.clusters; + } + + private observeGraph(): void { + this.graphResize?.disconnect(); + if (this.graphContainer?.nativeElement) { + this.graphResize = new ResizeObserver(() => this.graphComponent?.basicUpdate()); + this.graphResize.observe(this.graphContainer.nativeElement); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-pane.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-pane.scss new file mode 100644 index 0000000000..b3b53e77b8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-pane.scss @@ -0,0 +1,560 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + --art-x: 16px; + display: block; + min-width: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); +} + +.art-seg { + flex: none; + display: inline-flex; + padding: 3px; + border-radius: 999px; + background: color-mix(in srgb, var(--tb-ink) 6%, transparent); + + button { + height: 26px; + padding: 0 12px; + border: 0; + border-radius: 999px; + background: none; + font: 500 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-60); + cursor: pointer; + transition: background-color .15s ease, color .15s ease; + + &:hover { + color: var(--tb-ink); + } + + &[aria-pressed="true"] { + background: var(--ai-action); + color: var(--ai-on-action); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } +} + +:host > .sol-infos, :host > .sol-paged { + width: 100%; + box-sizing: border-box; +} + +.sol-paged { + display: flex; + flex-direction: column; + + &.wide { + display: grid; + grid-template-columns: 168px minmax(0, 1fr); + align-items: start; + + > .sol-tabs { + position: sticky; + top: 0; + flex-direction: column; + align-items: stretch; + gap: 2px; + padding: 12px 8px 12px var(--art-x); + border-bottom: 0; + overflow: visible; + + button { + display: block; + margin: 0; + padding: 6px 10px; + border: 0; + border-left: 2px solid transparent; + border-radius: 0 6px 6px 0; + white-space: normal; + + &[aria-selected="true"] { + border-left-color: var(--ai-action); + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + } + + &:hover { + background: color-mix(in srgb, var(--tb-ink) 3%, transparent); + } + } + } + } +} + +.sol-tabs { + position: sticky; + top: 0; + z-index: 2; + display: flex; + gap: 2px; + padding: 6px max(0px, calc(var(--art-x) - 6px)) 0; + border-bottom: 1px solid var(--tb-line); + background: var(--tb-surface); + overflow-x: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { + display: none; + } + + button { + flex: none; + padding: 6px 6px 8px; + border: 0; + border-bottom: 2px solid transparent; + margin-bottom: -1px; + background: none; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink-60); + text-align: left; + cursor: pointer; + white-space: nowrap; + + &:hover { + color: var(--tb-ink); + } + + &[aria-selected="true"] { + color: var(--tb-ink); + border-bottom-color: var(--ai-action); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: -2px; + border-radius: 6px; + } + } +} + +.sol-infos { + min-width: 0; + padding: 4px 0 16px; +} + +.sol-sec-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-height: 32px; + margin: 12px var(--art-x) 0; + box-sizing: border-box; + + h3 { + margin: 0; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + letter-spacing: .25px; + color: var(--tb-ink); + } +} + +.sol-infos > .sol-sec-head:first-child { + margin-top: 4px; +} + +.sol-sec-link { + display: inline-flex; + align-items: center; + gap: 4px; + color: inherit; + font: inherit; + letter-spacing: inherit; + text-decoration: none; + border-bottom: 0 !important; + transition: color .12s ease; + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + line-height: 16px; + color: var(--tb-ink-38); + opacity: 0; + transition: opacity .12s ease; + } + + &:hover, &:focus-visible { + color: var(--ai-link); + text-decoration: underline; + + .mat-icon { + opacity: 1; + } + } +} + +a.sol-ent { + color: inherit; + text-decoration: none; + border-bottom: 0 !important; + + b { + transition: color .12s ease; + } + + &:hover, &:focus-visible { + text-decoration: underline; + } + + &:hover b, &:focus-visible b { + color: var(--ai-link); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + border-radius: 4px; + } +} + +.sol-empty { + margin: 0; + padding: 4px var(--art-x) 12px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--k-faint); +} + +table.sol-table { + width: 100%; + border-collapse: collapse; + border-spacing: 0; + + th { + height: 30px; + padding: 0 10px 0 0; + font: 400 var(--chat-caption)/var(--chat-caption-lh) var(--tb-font); + letter-spacing: .2px; + color: var(--k-faint); + text-align: left; + border-bottom: 1px solid var(--tb-line); + } + + td { + min-width: 72px; + height: 40px; + padding: 9px 10px 9px 0; + box-sizing: border-box; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + letter-spacing: 0; + color: var(--tb-ink); + border-bottom: 1px solid var(--tb-line); + vertical-align: top; + } + + th:first-child, td:first-child { + padding-left: var(--art-x); + } + + th:last-child, td:last-child { + padding-right: var(--art-x); + } + + .secondary { + color: var(--tb-ink-76); + } + + .faint { + color: var(--k-faint); + } + + .wrap { + white-space: normal; + overflow-wrap: break-word; + } + + .nowrap { + white-space: nowrap; + } + + .chev, .stc, .act { + width: 1px; + white-space: nowrap; + text-align: right; + } + + .chev { + width: 18px; + } + + tbody tr.clickable { + cursor: pointer; + + &:hover td { + background: color-mix(in srgb, var(--tb-ink) 2.5%, transparent); + } + } + + tbody tr.on td { + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + border-bottom-color: transparent; + } + + tr.sol-exp td { + height: auto; + padding: 0 var(--art-x) 14px calc(var(--art-x) + 26px); + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + } +} + +.sol-chev { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + margin-top: 1px; + color: var(--tb-ink-38); + transition: transform .15s ease; + + &.open { + transform: rotate(180deg); + } +} + +.sol-name { + display: flex; + align-items: flex-start; + gap: 8px; + min-width: 0; + + > .mat-icon { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + margin-top: 1px; + color: var(--tb-ink-54); + } + + &[data-pal="device"] > .mat-icon { color: var(--entity-device-fg); } + &[data-pal="people"] > .mat-icon { color: var(--entity-people-fg); } + &[data-pal="path"] > .mat-icon { color: var(--entity-path-fg); } + &[data-pal="rule"] > .mat-icon { color: var(--entity-rule-fg); } + &[data-pal="view"] > .mat-icon { color: var(--entity-view-fg); } + &[data-pal="chain"] > .mat-icon { color: var(--entity-chain-fg); } + &[data-pal="solution"] > .mat-icon { color: var(--entity-solution-fg); } + + b { + font-weight: 500; + min-width: 0; + overflow-wrap: break-word; + } + + small { + display: block; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-ink-60); + } + + a { + color: var(--tb-ink); + border-bottom: 0 !important; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: transparent; + transition: text-decoration-color .15s ease; + + &:hover { + text-decoration-color: var(--tb-ink-54); + } + } +} + +.sol-sub { + margin-top: 2px; + padding-left: 26px; +} + +code.sol-cond { + display: inline-block; + max-width: 100%; + box-sizing: border-box; + padding: 2px 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font: 400 14px/18px var(--tb-mono); + color: var(--tb-ink); + white-space: normal; + overflow-wrap: anywhere; +} + +table.sol-table td code.k-ent, table.sol-table td .k-sev, table.sol-table td .sol-op { + vertical-align: baseline; +} + +.sol-chips { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.sol-op { + display: inline-block; + margin: 0; + padding: 1px 8px; + border-radius: 10px; + background: rgba(0, 0, 0, 0.06); + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--tb-ink-76); + white-space: nowrap; +} + +.sol-facts { + padding: 10px 0 0; +} + +.sol-keys-seg { + margin: 12px 0 8px; +} + +.sol-keys { + list-style: none; + margin: 0; + padding: 0; + display: grid; + + li { + display: flex; + align-items: baseline; + gap: 8px; + padding: 4px 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + } + + li + li { + border-top: 1px solid var(--tb-line); + } +} + +.sol-key { + padding: 1px 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: var(--chat-code); + line-height: 20px; + color: var(--tb-ink); +} + +.sol-key-type, .sol-key-dt { + color: var(--k-faint); + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); +} + +.sol-key-fx { + color: var(--entity-path-fg); + font-style: italic; + font-size: var(--chat-meta); +} + +.sol-key-dt { + margin-left: auto; + white-space: nowrap; +} + +.sol-remove { + margin-top: 10px; +} + +@container pane (max-width: 440px) { + table.sol-table, table.sol-table > tbody { + display: block; + } + + table.sol-table > thead { + display: none; + } + + table.sol-table > tbody > tr:not(.sol-exp) { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 2px 12px; + padding: 9px var(--art-x) 9px calc(var(--art-x) + 26px); + border-bottom: 1px solid var(--tb-line); + + > td { + display: block; + width: auto; + min-width: 0; + height: auto; + padding: 0; + border: 0; + background: none; + } + + > td:first-child { + flex: 1 1 0; + min-width: 0; + padding: 0; + + .sol-name { + position: relative; + + > .mat-icon { + position: absolute; + left: -26px; + top: 0; + } + } + + .sol-sub { + padding-left: 0; + } + } + + > td:is(.stc, .chev) { + order: 1; + flex: none; + } + + > td:not(:first-child):not(.stc):not(.chev) { + order: 2; + } + + &::after { + content: ''; + order: 1; + flex: 0 0 100%; + height: 0; + } + + > td.act { + margin-left: -8px; + } + } + + table.sol-table .act .mdc-button { + margin: 0; + } + + table.sol-table > tbody > tr.clickable:hover { + background: color-mix(in srgb, var(--tb-ink) 2.5%, transparent); + } + + table.sol-table > tbody > tr.on { + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + border-bottom-color: transparent; + } + + table.sol-table > tbody > tr.sol-exp, table.sol-table > tbody > tr.sol-exp > td { + display: block; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-schema.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-schema.ts new file mode 100644 index 0000000000..572887a35a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-schema.ts @@ -0,0 +1,165 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ClusterNode, Edge, Node } from '@swimlane/ngx-graph'; +import { SolutionDescriptor, SolutionDescriptorEntityBase } from '@shared/models/solution-creator.models'; + +export interface SolutionSchema { + nodes: Node[]; + links: Edge[]; + clusters: ClusterNode[]; +} + +export function buildSolutionSchema(descriptor: SolutionDescriptor, profiles: SolutionDescriptorEntityBase[]): SolutionSchema { + const nodes: Node[] = []; + const links: Edge[] = []; + const clusters: ClusterNode[] = []; + if (!descriptor) { + return {nodes, links, clusters}; + } + + const slug = (s: string) => + s.toLowerCase().normalize('NFKD') + .replace(/[\u0300-\u036f]/g, '') + .replace(/\s+/g, '-') + .replace(/[^a-z0-9_-]/g, '-') + .replace(/-+/g, '-') + .replace(/^-+|-+$/g, ''); + + const cssSafeId = (base: string) => { + const v = slug(base); + return v && !/^[a-z_]/.test(v) ? `n-${v}` : (v || 'n'); + }; + + const nodeIdOf = (type: string, name: string) => + `n-${cssSafeId(type)}__${cssSafeId(name)}`; + + const linkIdOf = (sourceNodeId: string, targetNodeId: string, label?: string) => + `e-${sourceNodeId}__to__${targetNodeId}${label ? `__${cssSafeId(label)}` : ''}`; + + const nodeByName = new Map(); + const nodeIdSet = new Set(); + const linkIdSet = new Set(); + const clusterByScope = new Map(); + const ensureCluster = (scope?: string | null) => { + if (!scope) return undefined; + if (!clusterByScope.has(scope)) { + const id = `c-${cssSafeId(scope)}`; + const clusterNode: ClusterNode = { id, label: scope, childNodeIds: [], data: {tone: scope === 'Tenant' ? 'tenant' : 'customer'} }; + clusterByScope.set(scope, clusterNode); + clusters.push(clusterNode); + } + return clusterByScope.get(scope); + }; + + const addNode = (entity: SolutionDescriptorEntityBase) => { + const id = nodeIdOf(entity.entityType || 'Entity', entity.name || 'Unnamed'); + if (nodeIdSet.has(id)) return id; + + const node: Node = { + id, + label: entity.name || 'Unnamed', + dimension: { + width: 200, + height: 56 + }, + data: { + entityType: entity.entityType || 'Entity', + scope: entity.scope, + entity + } + }; + + const scope = entity.entityType === 'Customer' ? entity.name : entity.scope; + const cluster = ensureCluster(scope); + if (cluster) { + cluster.childNodeIds?.push(id); + } + + nodes.push(node); + nodeIdSet.add(id); + nodeByName.set(entity.name, node); + return id; + }; + + const pushLink = (sourceId: string, targetId: string, label?: string) => { + const lbl = (label || '').trim(); + const id = linkIdOf(sourceId, targetId, lbl || undefined); + if (linkIdSet.has(id)) return; + links.push({ id, source: sourceId, target: targetId, label: lbl || undefined }); + linkIdSet.add(id); + }; + + const allProfiles: SolutionDescriptorEntityBase[] = profiles; + + for (const entity of allProfiles) { + addNode(entity); + } + + for (const relation of (descriptor.relations ?? [])) { + const fromNode = nodeByName.get(relation.parent); + const toNode = nodeByName.get(relation.child); + if (fromNode && toNode) { + const label = `${relation.type || ''}${relation.cardinality ? ` (${relation.cardinality})` : ''}`.trim(); + pushLink(fromNode.id, toNode.id, label || undefined); + } + } + + const byType = (t: string) => + allProfiles.filter(x => (x.entityType || '').toLowerCase() === t.toLowerCase()); + const tenantUsers = byType('User').filter(x => x.scope === 'Tenant'); + const customers = byType('Customer'); + const assets = byType('Asset'); + const devices = byType('Device'); + const customerUsers = byType('User').filter(x => x.scope !== 'Tenant'); + + for (const t of tenantUsers) { + const tId = nodeByName.get(t.name)?.id; + if (!tId) continue; + for (const c of customers) { + if (!(descriptor.relations ?? []).some(x => x.child === c.name)) { + const cId = nodeByName.get(c.name)?.id; + if (cId) pushLink(tId, cId, 'Manages'); + } + } + } + + for (const c of customers) { + const cId = nodeByName.get(c.name)?.id; + if (!cId) continue; + for (const a of assets) { + if (a.scope === c.name || a.scope === c.scope) { + if (!(descriptor.relations ?? []).some(x => x.child === a.name)) { + const aId = nodeByName.get(a.name)?.id; + if (aId) pushLink(cId, aId, 'Own'); + } + } + } + } + + for (const c of customers) { + const cId = nodeByName.get(c.name)?.id; + if (!cId) continue; + for (const d of devices) { + if (d.scope === c.name || d.scope === c.scope) { + if (!(descriptor.relations ?? []).some(x => x.child === d.name)) { + const aId = nodeByName.get(d.name)?.id; + if (aId) pushLink(cId, aId, 'Own'); + } + } + } + } + + for (const c of customers) { + const cId = nodeByName.get(c.name)?.id; + if (!cId) continue; + for (const u of customerUsers) { + if (u.scope === c.name || u.scope === c.scope) { + if (!(descriptor.relations ?? []).some(x => x.child === u.name)) { + const uId = nodeByName.get(u.name)?.id; + if (uId) pushLink(cId, uId, 'Manages'); + } + } + } + } + return {nodes, links, clusters}; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html new file mode 100644 index 0000000000..fcce6aea3a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html @@ -0,0 +1,424 @@ + +
+ + +
+ @if (title() || built()) { + + } + +
+
+
+ +@if (opening()) { +
+ + {{ 'solution-creator.opening' | translate }} +
+} @else if (isInitialEmpty()) { +
+
+
+ +

{{ 'solution-creator.what-should-it-do' | translate }}

+

{{ 'solution-creator.what-it-becomes' | translate }}

+ @if (creditsOut(); as limitType) { + + } @else if (notice(); as current) { +
+ {{ current.text }} +
+ } + + +
+ @for (ex of solutionExamples; track ex.key) { + + } +
+

{{ 'solution-creator.limits' | translate }}

+ +
+
+
+
+
+ {{ 'solution-creator.about-title' | translate }} + +
+
+ @for (feature of aboutFeatures; track feature.icon) { +
+ +
{{ feature.title | translate }}{{ feature.line | translate }}
+
+ } +
+
+
+
+} @else if (creatorStep()) { +
+
+
+ +
+
+
+ @if (pill(); as current) { + + } + @if (showPane() && !paneOpen()) { + + } + @if (creditsOut(); as limitType) { + + } @else if (notice(); as current) { +
+ {{ current.text }} +
+ } + + +
+
+ @if (showPane() && paneOpen()) { + +
+ @for (view of views(); track view.id) { + + } +
+ @if (json() && jsonView) { +
+
+ @if (!jsonView.body().editing()) { + + } + + +
+
+ + {{ jsonCopied() ? ('ai-assistant.copied' | translate) : '' }} + +
+
+ } + @if (jsonAvailable()) { + + } + @if (making() === 'solution' && currentView() === 'solution' && progressInfo(); as progress) { + + } @else if (making() && currentView() === making()) { +
+ + + + + +

{{ estimateOf(making()) }}

+
+ } @else if (json()) { + + } @else { + @switch (currentView()) { + @case ('overview') { + + } + @case ('dashboards') { + + } + @case ('solution') { + + } + } + } + @if (!making()) { +
+ @if (json() && jsonView; as view) { + + @if (view.body().editing()) { + @if (view.error(); as message) { + {{ 'solution-creator.pane.json-invalid' | translate: {message} }} + } @else if (view.body().dirty()) { + {{ 'ai-assistant.file.unsaved' | translate }} + } @else { + {{ 'ai-assistant.file.editing' | translate }} + } + @if (view.body().caret(); as caret) { + + {{ 'ai-assistant.file.position' | translate: {line: caret.line, col: caret.col} }} + } + } @else if (view.body().saved()) { + {{ 'solution-creator.pane.json-applied' | translate }} + } @else { + {{ view.fileName() }} + + {{ 'ai-assistant.file.lines' | translate: {count: view.file().lines} }} + + {{ view.file().size }} + } + + + @if (view.body().editing()) { + @if (view.body().dirty()) { + + + } @else { + + } + } @else { + + } + + } @else if (currentView() === 'solution' || creatorStep() === 'result') { + @if (installed()) { + + } + + + @if (installed()) { + @if (mainUser()) { + + } @else if (solutionMetadata.installResult?.mainDashboardId) { + + } + } @else { + + } + } @else if (currentView() === 'overview') { + {{ estimateOf('dashboards') }} + + } @else { + {{ estimateOf('solution') }} + + + + } +
+ } +
+ } +
+} + + + + @if (built() && creatorStep() === 'result') { + + } + @if (creatorStep() === 'result') { + + } + @if (installed()) { + + } + + + + + @if (!jsonView?.body()?.editing()) { + + } +
+ + {{ 'ai-assistant.file.theme' | translate }} +
+ + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss new file mode 100644 index 0000000000..8f55892ffe --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss @@ -0,0 +1,829 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use '../ai-icon-button' as *; +:host { + position: relative; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; + background: var(--tb-surface); + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); +} + +:host(.tb-fullscreen) { + margin: 0 !important; + border-radius: 0 !important; + box-shadow: none !important; +} + +.sol-head { + position: relative; + z-index: 2; + flex: none; + display: flex; + align-items: center; + gap: 8px; + height: 48px; + box-sizing: border-box; + padding: 0 8px 0 16px; + border-bottom: 1px solid rgba(0, 0, 0, 0.06); + background: var(--tb-surface); +} + +.sol-head-mark { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + color: var(--tb-ink-54); +} + +.sol-head-actions { + flex: none; + margin-left: auto; + display: flex; + align-items: center; + gap: 2px; +} + +tb-ai-chat-title:has(.ai-chat-status) + .sol-head-actions { + margin-left: 0; +} + +.sol-ib { + @include ai-icon-button($icon: 20px, $tap: false, $relative: false); +} + +.sol-toast { + position: absolute; + inset: 48px 0 auto; + pointer-events: none; +} + +.sol-hero { + --sol-dot: color-mix(in srgb, var(--tb-ink) 9%, transparent); + position: relative; + isolation: isolate; + flex: 1; + min-height: 0; + display: flex; + overflow: hidden; + contain: paint; + background: var(--ai-field-wash); + + &::after { + content: ''; + position: absolute; + left: -20vw; + top: -20vh; + width: 140vw; + height: 140vh; + z-index: -1; + pointer-events: none; + background: var(--ai-field-wash); + opacity: .9; + filter: blur(16px); + will-change: transform; + animation: sol-drift 16s ease-in-out infinite alternate; + } + + &::before { + content: ''; + position: absolute; + inset: -8px; + z-index: 0; + pointer-events: none; + mix-blend-mode: multiply; + will-change: transform; + animation: sol-dots 26s ease-in-out infinite alternate; + background: radial-gradient(circle, var(--sol-dot) 1px, transparent 1.4px) 0 0 / 16px 16px; + mask-image: radial-gradient(ellipse 56% 52% at 50% 44%, transparent 0%, rgba(0, 0, 0, .3) 55%, #000 100%), linear-gradient(180deg, #000 50%, transparent 100%); + mask-composite: intersect; + } + + @media (prefers-reduced-motion: reduce) { + &::before, &::after { + animation: none; + } + } +} + +@keyframes sol-drift { + 0% { transform: translate(-3%, -2%); } + 50% { transform: translate(3%, 2%); } + 100% { transform: translate(-1%, 3%); } +} + +@keyframes sol-dots { + from { transform: translate(-5px, -3px); } + to { transform: translate(5px, 4px); } +} + +.sol-hero-scroll { + position: relative; + z-index: 1; + flex: 1; + min-width: 0; + display: flex; + justify-content: center; + padding: 48px 24px 56px; + box-sizing: border-box; + overflow-y: auto; + overflow-x: hidden; +} + +.sol-hero-in { + position: relative; + z-index: 1; + width: 100%; + max-width: 720px; + margin: auto 0; + text-align: center; +} + +.sol-mark { + --ai-mark-fill: radial-gradient(80% 80% at 16% 10%, color-mix(in srgb, var(--tb-surface) 16%, transparent), transparent 62%), + linear-gradient(135deg in oklab, + color-mix(in oklab, var(--ai-light-teal) 34%, var(--tb-ink)) 0%, + color-mix(in oklab, var(--ai-light-aqua) 32%, var(--tb-ink)) 36%, + color-mix(in oklab, var(--ai-light-lilac) 36%, var(--tb-ink)) 68%, + color-mix(in oklab, var(--ai-light-peach) 34%, var(--tb-ink)) 100%); + --ai-mark-edge: 0 10px 28px color-mix(in oklab, var(--tb-ink) 24%, transparent); + --ai-mark-ink: var(--ai-on-action); + --ai-mark-ink-fill: linear-gradient(var(--ai-on-action), var(--ai-on-action)); + display: flex; + margin: 0 auto 14px; +} + +.sol-title { + margin: 0; + font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); + letter-spacing: -0.2px; + color: var(--tb-ink); +} + +.sol-lead { + margin: 8px auto 0; + max-width: 540px; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink-76); + text-wrap: balance; +} + +.sol-hero-input { + display: block; + margin-top: 24px; + text-align: left; +} + +.sol-hero-credits { + margin-top: 24px; + text-align: left; + + + .sol-hero-input { + margin-top: 0; + } +} + +.sol-hero-notice { + align-self: stretch; + margin: 24px 0 8px; + text-align: left; + + + .sol-hero-input { + margin-top: 0; + } +} + +.sol-examples { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 6px; + max-width: 600px; + margin: 22px auto 0; + + .ob-chip { + gap: 8px; + padding: 0 16px 0 12px; + + .mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + line-height: 20px; + color: var(--tb-ink-76); + } + } +} + +.sol-hero-foot { + margin: 20px 0 0; + letter-spacing: var(--chat-text-ls); + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-faint); +} + +.sol-cols { + flex: 1; + min-height: 0; + display: flex; +} + +.sol-chat { + position: relative; + flex: 1 1 0; + min-width: 0; + display: flex; + flex-direction: column; +} + +.sol-head::after, .sol-cols.with-pane .sol-chat::before { + content: ''; + position: absolute; + left: 0; + right: 0; + z-index: 3; + height: 12px; + background: linear-gradient(to bottom, color-mix(in srgb, var(--tb-ink) 9%, transparent), transparent); + opacity: 0; + transition: opacity .15s ease; + pointer-events: none; +} + +.sol-head::after { + top: 100%; +} + +.sol-cols.with-pane .sol-chat::before { + top: 0; +} + +.sol-head.scrolled::after, .sol-cols.with-pane .sol-chat.scrolled::before { + opacity: 1; +} + +.sol-cols.with-pane .sol-chat { + min-width: var(--chat-col-min, 340px); +} + +.sol-log { + flex: 1; + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; + padding: 20px 20px 0; + container: k-chat / inline-size; +} + +.sol-log-in { + width: 100%; + max-width: 760px; + margin: 0 auto; + padding-bottom: 24px; +} + +.sol-chips { + margin-top: 14px; +} + +.sol-closing { + margin-top: var(--chat-turn-gap, 28px); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); + + p { + margin: 0; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + } +} + +.sol-hint { + margin-top: 14px; +} + +.sol-closing .sol-chips { + margin-top: 14px; +} + +.sol-closing > .sol-hint { + margin-top: 12px; + + + .sol-chips { + margin-top: 36px; + } +} + +.sol-work { + margin-top: var(--chat-turn-gap, 28px); +} + +.sol-composer { + position: relative; + flex: none; + width: 100%; + max-width: 760px; + margin: 0 auto; + padding: 0 20px 14px; + box-sizing: border-box; +} + +.sol-toast-chat { + position: absolute; + inset: auto 0 100%; + pointer-events: none; +} + +.sol-views { + flex: 1; + min-width: 0; + display: flex; + align-items: center; + gap: 2px; + + button { + display: inline-flex; + align-items: center; + gap: 7px; + height: 32px; + padding: 0 14px 0 10px; + border: 0; + border-radius: 999px; + background: none; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink-60); + cursor: pointer; + white-space: nowrap; + transition: background-color .18s ease, color .18s ease; + + > .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + color: var(--tb-ink-54); + } + + &:not([aria-pressed="true"]):not([disabled]):hover { + background: color-mix(in srgb, var(--tb-ink) 5%, transparent); + color: var(--tb-ink); + } + + &[aria-pressed="true"] { + background: var(--ai-action); + color: var(--ai-on-action); + + > .mat-icon { + color: var(--ai-on-action); + } + } + + &[disabled] { + color: var(--tb-ink-38); + cursor: default; + + > .mat-icon { + color: var(--tb-ink-24, rgba(0, 0, 0, 0.24)); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } +} + +.sol-views button.working { + padding-left: 9px; +} + +@container pane (min-width: 660px) { + .sol-views button tb-ai-spin { + --spin: 24px; + } + + .sol-views button.working { + padding-left: 10px; + } + + .sol-views button { + height: 34px; + padding: 0 16px 0 12px; + gap: 8px; + + > .mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + } + } +} + +@container pane (max-width: 470px) { + .sol-views button:not([aria-pressed="true"]) { + padding: 0 9px; + + .sol-views-l { + display: none; + } + } +} + +.sol-tool { + flex: none; + display: inline-flex; + align-items: center; + gap: 4px; + height: 32px; + padding: 0 12px 0 8px; + border: 0; + border-radius: 8px; + background: transparent; + font: 500 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-60); + cursor: pointer; + transition: background-color .12s ease, color .12s ease; + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + color: var(--tb-ink-54); + } + + &:hover { + color: var(--tb-ink); + background: color-mix(in srgb, var(--tb-ink) 6%, transparent); + } + + &.on { + background: var(--ai-action); + color: var(--ai-on-action); + + .mat-icon { + color: var(--ai-on-action); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.sol-loading, .sol-json { + flex: 1; +} + +.sol-loading { + --art-x: 16px; +} + +.sol-json { + width: 100%; + min-height: 0; +} + + +.art-pane-foot { + .warn { + --mat-button-text-label-text-color: var(--tb-crit); + } + + .sol-foot-stroked.mat-mdc-outlined-button { + padding: 0 15px; + background: var(--tb-surface); + --mat-button-outlined-label-text-color: var(--tb-ink-76); + --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.1); + } +} + +.sol-foot-note { + flex: 1; + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--k-faint); +} + +.sol-spacer { + flex: 1; +} + +.sol-failure { + display: flex; + align-items: flex-start; + gap: 8px; + margin-top: 14px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-crit); + + .mat-icon { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + margin-top: 1px; + } +} + +.sol-issues { + ul { + margin: 8px 0 0; + padding-left: 20px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } + + b { + font-weight: 500; + color: var(--tb-ink); + } +} + +.sol-learn { + display: inline-flex; + align-items: center; + gap: 6px; + margin: 6px auto 0; + padding: 4px 10px 4px 8px; + border: 0; + border-radius: 8px; + background: none; + font: inherit; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + color: var(--tb-ink-60); + cursor: pointer; + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + } + + &:hover { + color: var(--tb-ink); + background: rgba(0, 0, 0, 0.05); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.sol-about { + position: absolute; + left: 0; + right: 0; + bottom: 0; + z-index: 2; + padding: 12px 24px 18px; + background: var(--tb-surface); + border-top: 1px solid var(--k-stroke, rgba(0, 0, 0, 0.1)); + transform: translateY(100%); + opacity: 0; + visibility: hidden; + will-change: transform; + transition: transform .26s cubic-bezier(.2, 0, 0, 1), opacity .2s ease, visibility 0s linear .26s; + + &::before { + content: ''; + position: absolute; + left: 0; + right: 0; + bottom: 100%; + height: 18px; + background: linear-gradient(to top, color-mix(in srgb, var(--tb-ink) 5%, transparent), transparent); + pointer-events: none; + } + + &.open { + transform: none; + opacity: 1; + visibility: visible; + transition-delay: 0s, 0s, 0s; + } + + @media (prefers-reduced-motion: reduce) { + transition: none; + } +} + +.sol-about-in { + max-width: 860px; + margin: 0 auto; + text-align: left; +} + +.sol-about-head { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 8px; + + b { + flex: 1; + display: inline-flex; + align-items: center; + gap: 8px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + color: var(--ai-action); + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + } + } + + .sol-ib { + width: 32px; + height: 32px; + margin: -4px -8px -4px 0; + border-radius: 50%; + font-size: 14px; + line-height: 20px; + color: var(--tb-ink-60); + } +} + +.sol-feats { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px 32px; + align-items: start; + + @media (max-width: 480px) { + grid-template-columns: minmax(0, 1fr); + } +} + +.sol-feat { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + column-gap: 12px; + align-items: start; + min-width: 0; + + > .mat-icon { + box-sizing: content-box; + font-size: 20px; + width: 20px; + height: 20px; + line-height: 20px; + margin-top: -6px; + padding: 6px; + border-radius: 8px; + background: color-mix(in oklab, var(--tb-ink) 5%, transparent); + color: var(--tb-ink-76); + } + + > div { + display: grid; + gap: 4px; + align-content: start; + min-width: 0; + } + + b { + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + color: var(--tb-ink); + } + + span { + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-grey); + } +} + +.sol-ask { + display: block; + margin-top: var(--chat-turn-gap, 28px); +} + +@media (min-width: 1100px) { + .sol-cols.with-pane { + .sol-log-in, .sol-composer { + max-width: none; + } + } +} + +.sol-views tb-ai-spin { + --spin: 20px; + --spin-color: var(--ai-action); +} + +.sol-views button[aria-pressed="true"] tb-ai-spin { + --spin-color: var(--ai-on-action); +} + +.sol-composer:has(.art-tray) .k-pill { + bottom: calc(100% + 44px); +} + +@media (max-width: 1099px) { + .sol-cols.with-pane .sol-chat { + min-width: 0; + } +} + +@container pane (max-width: 900px) { + .sol-json-on .sol-views button:not([aria-pressed="true"]) { + padding: 0 9px; + + .sol-views-l { + display: none; + } + } +} + +@container pane (max-width: 560px) { + .sol-json-on .sol-views button[aria-pressed="true"] { + padding: 0 9px; + + .sol-views-l { + display: none; + } + } + + .sol-json-on .sol-tool > span { + display: none; + } +} + +.art-dark { + .sol-views button { + color: rgba(255, 255, 255, 0.72); + + > .mat-icon { + color: rgba(255, 255, 255, 0.6); + } + + &:not([aria-pressed="true"]):not([disabled]):hover { + background: rgba(255, 255, 255, 0.08); + color: #fff; + } + + &[aria-pressed="true"] { + background: rgba(143, 227, 211, 0.14); + color: var(--ai-dark-accent); + + > .mat-icon { + color: var(--ai-dark-accent); + } + } + } + + .sol-tool { + color: rgba(255, 255, 255, 0.72); + + .mat-icon { + color: rgba(255, 255, 255, 0.6); + } + + &:hover { + background: rgba(255, 255, 255, 0.08); + color: #fff; + } + + &.on { + background: rgba(143, 227, 211, 0.14); + color: var(--ai-dark-accent); + + .mat-icon { + color: var(--ai-dark-accent); + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts new file mode 100644 index 0000000000..de3b8151f5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts @@ -0,0 +1,1945 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AI_TOOLTIP_PROVIDERS } from '@home/components/ai/ai-tooltip'; +import { aiCreditsLimitOf, AiCreditsLimitType } from '@home/components/ai/ai-credits.models'; +import { AiCardAction } from '@home/components/ai/ai-card-actions.component'; +import { AiNotice } from '@shared/models/ai-chat.models'; +import { AiArtifactPaneComponent } from '@home/components/ai/ai-artifact-pane.component'; +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + ElementRef, + EventEmitter, + HostListener, + inject, + OnDestroy, + OnInit, + Output, + signal, + untracked, + viewChild, + ViewChild +} from '@angular/core'; +import { + AiChatMessagesComponent, + AnswerRatingEvent, + AnswerReportEvent +} from '@home/components/ai/ai-chat-messages.component'; +import { PageComponent } from '@shared/components/page.component'; +import { DomSanitizer } from '@angular/platform-browser'; +import { ActivatedRoute, Router } from '@angular/router'; +import { + AiQuestion, + AiQuestionAnswer, + ChatMessage, + EntityResult, + DashboardsOverview, + GeneralChatMessage, + SolutionEstimate, + SolutionInstallProgress, + NEW_SOLUTION_ID, + SolutionCreatorInfo, + SolutionDescriptor, + SolutionInstallResult, + SolutionMetadata, + SolutionStep, + SolutionStepStatus +} from '@shared/models/solution-creator.models'; +import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; +import { AiPromptMessage, AiResourceInfo } from '@shared/models/ai-chat.models'; +import { SolutionsCreatorService } from '@core/http/solutions-creator.service'; +import { + catchError, + defaultIfEmpty, + filter, + finalize, + map, + switchMap, + take, + takeUntil, + tap +} from 'rxjs/operators'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { ClipboardService } from 'ngx-clipboard'; +import { downloadAiFile } from '@home/components/ai/ai-file.models'; +import { EMPTY, forkJoin, Observable, of, Subject, timer } from 'rxjs'; +import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; +import { DialogService } from '@core/services/dialog.service'; +import { TranslateService } from '@ngx-translate/core'; +import { AiSolutionsService } from '@core/services/ai-solutions.service'; +import { AuthService } from '@core/auth/auth.service'; +import { + SolutionInfoDialogComponent, + SolutionInfoDialogData +} from '@home/components/ai/solution/solution-info/solution-info-dialog.component'; +import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models'; +import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { aggregateByName, IssueStatus } from '@home/components/ai/solution/solution-info/issues-aggregation'; +import { SolutionJsonComponent } from '@home/components/ai/solution/pane/solution-json.component'; +import { AiChatTitleComponent } from '@home/components/ai/ai-chat-title.component'; +import { AiSpinKind } from '@home/components/ai/ai-action.models'; +import { aiAnswersOf, aiAnswersText } from '@home/components/ai/ai-question.component'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AiAnswerFeedback, aiRateAnswer, aiReportAnswer, aiTrackLogScroll } from '@home/components/ai/ai-chat-session'; +import { EntityId } from '@shared/models/id/entity-id'; + +export type SolutionView = 'overview' | 'dashboards' | 'solution'; + +function formatCredits(credits: number): string { + if (credits >= 1000) { + const thousands = credits / 1000; + return (thousands >= 10 ? Math.round(thousands) : Math.round(thousands * 10) / 10) + 'k'; + } + return String(credits); +} + +const isVisibleMessage = (msg: ChatMessage): boolean => + msg.from === 'AI' || (msg.from === 'USER' && !/^<[a-z-]+\/>$/.test(((msg as GeneralChatMessage).content ?? '').trim())); + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-chat', + templateUrl: './solution-chat.component.html', + styleUrls: ['./solution-chat.component.scss'], + standalone: false, + providers: AI_TOOLTIP_PROVIDERS +}) +export class SolutionChatComponent extends PageComponent implements OnInit, OnDestroy { + + private static readonly NARROW_WIDTH = 1100; + + private static readonly CREDITS_PIN_MS = 1500; + private static readonly CONNECTIVITY_GUIDE = 'https://thingsboard.io/docs/getting-started-guides/connectivity/'; + + @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; + @ViewChild(AiChatMessagesComponent) chatMessages: AiChatMessagesComponent; + @ViewChild(AiChatTitleComponent) titleRef: AiChatTitleComponent; + @ViewChild(AiArtifactPaneComponent) pane: AiArtifactPaneComponent; + @Output() loaded = new EventEmitter(); + + get hostElement(): HTMLElement { + return this.elementRef.nativeElement; + } + + isReadyStep = signal(false); + private static readonly DESIGN_POLL_MS = 4000; + + private static readonly DESIGN_POLL_LIMIT = 150; + + skipInterviewAllowed = signal(false); + solutionStep = signal(SolutionStep.INITIAL_CONFIGURATION); + creatorStep = signal<'chat' | 'result' | null>('chat'); + + messages = signal([]); + + loading = signal(false); + isGenerating = signal(false); + + work = signal<{words: string; kind: 'think' | 'gen' | 'install'; since: number; lines?: string[]} | null>(null); + + paneTalks = computed(() => this.showPane() && this.paneOpen() && !!this.making() && this.currentView() === this.making() + && !(this.making() === 'solution' && !!this.progressInfo())); + + fullscreen = signal(false); + + title = signal(''); + shownTitle = computed(() => this.title() || this.aiSolutions.find(this.info()?.id)?.solutionTitle || ''); + + built = signal(false); + + installed = signal(false); + + mainDashboard = signal([]); + + logScrolled = signal(false); + private atEnd = signal(true); + + private chatArea = viewChild>('chatArea'); + + private composer = viewChild>('composer'); + + private pinToEndUntil = 0; + + private creditsOutEffect = effect(() => { + if (this.creditsOut()) { + this.pinToEndUntil = Date.now() + SolutionChatComponent.CREDITS_PIN_MS; + setTimeout(() => this.scrollLogToEnd()); + } + }); + + private composerSizeEffect = effect(onCleanup => { + const area = this.chatArea()?.nativeElement; + const composer = this.composer()?.nativeElement; + if (!area || !composer) { + return; + } + let composerHeight = composer.offsetHeight; + const observer = new ResizeObserver(() => { + const height = composer.offsetHeight; + if (Date.now() < this.pinToEndUntil || (height > composerHeight && untracked(this.atEnd))) { + area.scrollTop = area.scrollHeight; + } + composerHeight = height; + }); + observer.observe(composer); + if (area.firstElementChild) { + observer.observe(area.firstElementChild); + } + onCleanup(() => observer.disconnect()); + }); + private newTurns = signal(0); + private seenTurns = 0; + + pill = computed<{mode: 'work' | 'new'; kind: AiSpinKind; label: string; count: number} | null>(() => { + if (this.atEnd()) { + return null; + } + const work = this.work(); + if (work && (this.loading() || this.isGenerating())) { + return {mode: 'work', kind: work.kind, label: work.words, count: 0}; + } + const count = this.newTurns(); + return count ? {mode: 'new', kind: 'think', label: this.translate.instant('ai-assistant.new-count', {count}), count} : null; + }); + + private newTurnsEffect = effect(() => { + const total = this.viewMessages().length; + untracked(() => { + if (this.atEnd() || total <= this.seenTurns) { + this.seenTurns = total; + return; + } + this.newTurns.update(count => count + total - this.seenTurns); + this.seenTurns = total; + }); + }); + + onLogScroll(area: HTMLElement): void { + aiTrackLogScroll(area, {scrolled: this.logScrolled, atEnd: this.atEnd, newTurns: this.newTurns}, () => this.seenTurns = this.viewMessages().length); + } + + goToEnd(area: HTMLElement): void { + const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; + area.scrollTo({top: area.scrollHeight, behavior: reduce ? 'auto' : 'smooth'}); + } + + statusTip = computed(() => { + const level = this.level(); + if (!level) { + return ''; + } + return level === 'error' && this.failure() ? this.failure() : this.translate.instant('ai-assistant.status-tip-' + level); + }); + + level = computed<'running' | 'needs' | 'error' | null>(() => this.loading() || this.isGenerating() + ? 'running' + : this.failure() ? 'error' + : this.pendingQuestions().length || (this.isReadyStep() && this.creatorStep() === 'chat' && !this.built()) ? 'needs' : null); + + info = signal(null); + + making = signal(null); + + pickedView = signal<{view: SolutionView; phase: string} | null>(null); + + json = signal(false); + + opening = signal(false); + + jsonWrap = signal(SolutionChatComponent.stored('tbAiFileWrap') === 'true'); + + jsonWhitespace = signal(SolutionChatComponent.stored('tbAiFileWhitespace') === 'true'); + + jsonDark = signal(SolutionChatComponent.stored('tbAiFileTheme') !== 'light'); + + jsonCopied = signal(false); + + private jsonCopiedTimer: ReturnType; + + private clipboardService = inject(ClipboardService); + + toggleJsonWrap(): void { + this.jsonWrap.update(wrap => !wrap); + SolutionChatComponent.store('tbAiFileWrap', String(this.jsonWrap())); + } + + toggleJsonWhitespace(): void { + this.jsonWhitespace.update(value => !value); + SolutionChatComponent.store('tbAiFileWhitespace', String(this.jsonWhitespace())); + } + + setJsonTheme(theme: 'dark' | 'light'): void { + this.jsonDark.set(theme === 'dark'); + SolutionChatComponent.store('tbAiFileTheme', theme); + } + + copyJson(): void { + if (this.jsonView && this.clipboardService.copyFromContent(this.jsonView.text())) { + this.jsonCopied.set(true); + clearTimeout(this.jsonCopiedTimer); + this.jsonCopiedTimer = setTimeout(() => this.jsonCopied.set(false), 1500); + } + } + + downloadJson(): void { + if (this.jsonView) { + downloadAiFile({...this.jsonView.file(), content: this.jsonView.text()}); + } + } + + onJsonDiscarded(): void { + this.store.dispatch(new ActionNotificationShow({ + message: this.translate.instant('solution-creator.pane.json-discarded'), + type: 'success', + modern: true, + verticalPosition: 'bottom', + horizontalPosition: 'center' + })); + } + + private static stored(key: string): string | null { + return readStored(key); + } + + private static store(key: string, value: string): void { + writeStored(key, value); + } + + uninstalledAt = signal(null); + + failure = signal(null); + failedAt = signal<'install' | 'step'>('step'); + installProgress = signal(null); + makeStartedAt = signal(0); + private installOnly = signal(false); + private messageSteps: SolutionStep[] = []; + + stopping = signal(false); + private readonly stopEnded = effect(() => { + if (!this.loading() && !this.isGenerating()) { + untracked(() => this.stopping.set(false)); + } + }); + + notice = signal(null); + + creditsOut = signal(null); + + private freshSolutionId: string | null = null; + + private stoppedAction: (() => void) | null = null; + + progressInfo = computed(() => { + const progress = this.installProgress(); + const info = this.info(); + if (!progress || !info || (!progress.items?.length && !Object.values(progress.entityResults ?? {}).some(results => results?.length))) { + return null; + } + return {...info, metadata: {built: true, installed: false, installResult: {createdEntities: [], entityResults: progress.entityResults as any}}}; + }); + + createShare = computed(() => { + if (this.installOnly()) { + return 0; + } + const estimates = this.info()?.estimates; + const create = estimates?.CREATE?.seconds; + const install = estimates?.INSTALL?.seconds; + return create > 0 && install > 0 ? Math.min(.95, Math.max(.5, create / (create + install))) : .85; + }); + + makeSeconds = computed(() => { + const estimates = this.info()?.estimates; + if (this.installOnly()) { + return Math.max(5, estimates?.INSTALL?.seconds ?? 15); + } + const seconds = (estimates?.CREATE?.seconds ?? 0) + (estimates?.INSTALL?.seconds ?? 0); + return estimates?.CREATE && estimates?.INSTALL ? Math.max(20, seconds) : 90; + }); + + private closingPatch = signal>({}); + + private stepActions(): ChatMessage[] { + const info = this.info(); + const result = info?.metadata?.installResult; + const metadata = info?.metadata; + const actions: ChatMessage[] = [{from: 'ACTION', data: {executionId: 'solution-create', tool: 'create_solution', status: 'SUCCESS', + startedAt: metadata?.builtTime ?? 0, durationMs: metadata?.createDurationMs}}]; + if (this.installed() && result) { + const entities = Object.entries(result.entityResults ?? {}) + .filter(([type]) => type !== EntityType.ENTITY_GROUP && type !== EntityType.RULE_CHAIN) + .flatMap(([, entries]) => (entries ?? []).filter(entry => entry?.id && entry.status !== 'ERROR').map(entry => entry.id)); + actions.push({from: 'ACTION', data: {executionId: 'solution-install', tool: 'install_solution', status: 'SUCCESS', + startedAt: result.installedTime ?? 0, durationMs: result.durationMs, affectedEntities: entities}}); + } + return actions; + } + + closing = computed(() => { + const info = this.info(); + if (this.creatorStep() !== 'result' || !this.built() || !info) { + return null; + } + const installed = this.installed(); + const result = info.metadata?.installResult; + const user = this.mainUser(); + const chips: GeneralChatMessage['chips'] = []; + if (installed && user) { + chips.push({id: 'view-as', icon: 'person', label: this.translate.instant('solution-creator.view-as-name', {name: user.name})}); + } + chips.push({id: 'edit', icon: 'edit', label: this.translate.instant('ai-assistant.edit-design')}); + if (installed) { + chips.push({id: 'connect', icon: 'memory', label: this.translate.instant('solution-creator.connect-devices')}); + chips.push({id: 'uninstall', icon: 'delete_sweep', label: this.translate.instant('solution-creator.uninstall-solution')}); + } + return { + from: 'AI', + content: installed ? this.installedSummary(result?.entityResults) : this.translate.instant('solution-creator.closing-created'), + time: installed ? result?.installedTime : undefined, + entities: installed && this.mainDashboard().length ? this.mainDashboard() : undefined, + entitiesMeta: installed ? this.mainDashboardMeta() : undefined, + hint: installed ? { + lead: this.translate.instant('solution-creator.closing-simulated-lead'), + text: this.translate.instant('solution-creator.closing-simulated') + } : undefined, + chips, + ...this.closingPatch() + }; + }); + + viewMessages = computed(() => { + const messages = this.messages(); + const lastAi = messages.map(message => message.from).lastIndexOf('AI'); + const waiting = this.isReadyStep() && this.creatorStep() === 'chat' && !this.built() && !this.loading() && !this.isGenerating(); + return messages.map((message, index) => { + if (message.from === 'AI') { + const general = message as GeneralChatMessage; + const patch: Partial = {}; + if (/^\s*(✅|🛠️|🛠)/u.test(general.content ?? '')) { + patch.done = true; + } else if (/^\s*(🤔|💡|🛑)/u.test(general.content ?? '')) { + patch.done = false; + } + if (general.questions?.length) { + patch.lead = this.translate.instant('solution-creator.assumptions'); + } + if (waiting && index === lastAi) { + patch.note = this.translate.instant(this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION + ? 'solution-creator.next-create' : 'solution-creator.next-dashboards-note'); + } + return Object.keys(patch).length ? {...general, ...patch} : message; + } + if (message.from === 'USER') { + const previous = messages[index - 1] as GeneralChatMessage; + const answers = previous?.from === 'AI' ? aiAnswersOf((message as GeneralChatMessage).content, previous.questions) : null; + return answers ? {...message, answers} as GeneralChatMessage : message; + } + return message; + }).concat(this.closing() ? [...this.stepActions(), this.closing()] : []); + }); + + onChip(id: string): void { + switch (id) { + case 'resume': + this.resume(); + break; + case 'view-as': + this.viewAsMainUser(); + break; + case 'edit': + this.editDesign(); + break; + case 'connect': + this.connectDevices(); + break; + case 'uninstall': + this.uninstallSolution(); + break; + } + } + + private installedSummary(results: Partial> | undefined): string { + const count = (...types: EntityType[]) => types.reduce((sum, type) => + sum + aggregateByName(type, results?.[type]).filter(row => row.status !== IssueStatus.ERROR).length, 0); + const parts = [ + ['device', count(EntityType.DEVICE)], + ['asset', count(EntityType.ASSET)], + ['profile', count(EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE)], + ['calculated-field', count(EntityType.CALCULATED_FIELD)], + ['alarm-rule', count(EntityType.ALARM)], + ['role', count(EntityType.ROLE)], + ['user', count(EntityType.USER)], + ['dashboard', count(EntityType.DASHBOARD)] + ].filter(([, n]) => (n as number) > 0) + .map(([key, n]) => this.translate.instant('solution-creator.installed-made.' + key, {count: n})); + if (!parts.length) { + return this.translate.instant('solution-creator.closing-installed'); + } + const items = parts.length === 1 ? parts[0] + : parts.slice(0, -1).join(', ') + ' ' + this.translate.instant('solution-creator.installed-and') + ' ' + parts[parts.length - 1]; + return this.translate.instant('solution-creator.installed-summary', {items}); + } + + private mainDashboardMeta(): string | undefined { + const result = this.info()?.metadata?.installResult; + const main = result?.mainDashboardId?.id; + const dashboard = main ? result?.entityResults?.[EntityType.DASHBOARD]?.find(entry => entry.id?.id === main) : undefined; + if (!dashboard) { + return undefined; + } + const role = this.info()?.data?.dashboardsOverview?.find(overview => overview.name === dashboard.additionalData?.name)?.assignedTo; + const user = this.mainUser(); + return [ + this.translate.instant('entity.type-dashboard'), + role, + user ? this.translate.instant('solution-creator.shared-with', {name: user.name}) : null + ].filter(Boolean).join(' · '); + } + + pendingQuestions = computed(() => { + const last = this.messages()[this.messages().length - 1] as GeneralChatMessage; + if (!last || last.from !== 'AI' || !last.questions?.length || this.loading() || this.isGenerating() || this.isReadyStep() + || this.solutionStep() !== SolutionStep.INITIAL_CONFIGURATION) { + return []; + } + return last.questions; + }); + + readonly aboutFeatures = [ + {icon: 'account_tree', title: 'solution-creator.about-design-title', line: 'solution-creator.about-design'}, + {icon: 'fact_check', title: 'solution-creator.about-approve-title', line: 'solution-creator.about-approve'}, + {icon: 'dashboard', title: 'solution-creator.about-dashboards-title', line: 'solution-creator.about-dashboards'}, + {icon: 'layers', title: 'solution-creator.about-installed-title', line: 'solution-creator.about-installed'} + ]; + + aboutOpen = signal(false); + + issues = computed>(() => { + const results = this.info()?.metadata?.installResult?.entityResults; + if (!results || !this.info()?.metadata?.installed) { + return []; + } + return Object.values(results).flat() + .filter(entry => entry?.status === 'ERROR' || entry?.status === 'WARN') + .map(entry => ({name: entry.additionalData?.name ?? '', status: entry.status, message: entry.error?.message})); + }); + + private paneEdgeEffect = effect(() => { + this.currentView(); + this.json(); + this.paneOpen(); + untracked(() => setTimeout(() => this.pane?.refreshEdges(), 50)); + }); + + private failureEffect = effect(() => { + const id = this.info()?.id; + const failure = this.failure(); + untracked(() => this.aiSolutions.setFailed(id, failure)); + }); + + private runningEffect = effect(() => { + const id = this.info()?.id; + const running = this.loading() || this.isGenerating(); + untracked(() => this.aiSolutions.setRunning(id, running)); + }); + + private needsEffect = effect(onCleanup => { + const id = this.info()?.id; + const needs = this.level() === 'needs'; + untracked(() => this.aiSolutions.setNeeds(id, needs)); + onCleanup(() => untracked(() => this.aiSolutions.setNeeds(id, false))); + }); + + mainUser = computed<{id: string; name: string} | null>(() => { + const result = this.info()?.metadata?.installResult; + const main = result?.mainDashboardId?.id; + const dashboard = main ? result?.entityResults?.[EntityType.DASHBOARD]?.find(entry => entry.id?.id === main) : undefined; + const userId = dashboard?.additionalData?.userId; + if (!userId) { + return null; + } + const user = result.entityResults?.[EntityType.USER]?.find(entry => entry.id?.id === userId); + return {id: userId, name: user?.additionalData?.name ?? ''}; + }); + + jsonValue = computed(() => this.currentView() === 'dashboards' + ? this.info()?.data?.dashboardsOverview + : this.info()?.data?.solutionDescriptor); + + @ViewChild('jsonView') jsonView: SolutionJsonComponent; + + paneOpen = signal(typeof window === 'undefined' || window.innerWidth >= SolutionChatComponent.NARROW_WIDTH); + + phase = computed(() => `${this.creatorStep()}:${this.solutionStep()}`); + + views = computed>(() => { + const info = this.info(); + const states = info?.states; + const have: Record = { + overview: !!info?.data?.solutionDescriptor && states?.[SolutionStep.INITIAL_CONFIGURATION]?.status === SolutionStepStatus.READY, + dashboards: !!info?.data?.dashboardsOverview?.length, + solution: !!info?.metadata?.built + }; + const icons: Record = {overview: 'account_tree', dashboards: 'dashboard', solution: 'layers'}; + return (['overview', 'dashboards', 'solution'] as SolutionView[]).map(id => ({ + id, + icon: icons[id], + state: this.making() === id ? 'working' : have[id] ? 'have' : 'next' + })); + }); + + currentView = computed(() => { + const views = this.views(); + const usable = (view: SolutionView) => views.find(item => item.id === view)?.state !== 'next'; + const picked = this.pickedView(); + if (picked && picked.phase === this.phase() && usable(picked.view)) { + return picked.view; + } + if (this.making()) { + return this.making(); + } + const preferred: SolutionView = this.creatorStep() === 'result' ? 'solution' + : this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION ? 'dashboards' : 'overview'; + if (usable(preferred)) { + return preferred; + } + return [...views].reverse().find(item => item.state !== 'next')?.id ?? null; + }); + + showPane = computed(() => !!this.currentView()); + + jsonAvailable = computed(() => !this.making() && (this.currentView() === 'overview' || this.currentView() === 'dashboards')); + + trayNote = computed(() => { + const making = this.making(); + if (making) { + return this.translate.instant(making === 'solution' ? 'solution-creator.pane.creating' : 'solution-creator.pane.designing'); + } + if (this.failure()) { + return this.translate.instant(this.failedAt() === 'install' ? 'solution-creator.pane.install-failed' : 'solution-creator.pane.step-failed'); + } + return this.translate.instant('solution-creator.pane.view-' + this.currentView()); + }); + + showMoreExamples = signal(false); + + isInitialEmpty = computed(() => + this.creatorStep() === 'chat' && + this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION && + !this.messages().length && + !this.loading() + ); + + activePlaceholder = computed(() => this.isInitialEmpty() + || (this.creatorStep() === 'chat' && this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION && !this.isReadyStep() && !this.pendingQuestions().length) + ? 'solution-creator.describe-solution-you-want' + : this.pendingQuestions().length ? 'solution-creator.type-the-answer' + : this.creatorStep() === 'result' ? 'solution-creator.ask-about-solution' : 'solution-creator.say-what-to-change'); + + solutionExamples: Array<{ key: string; labelKey: string; icon: string; message: string }> = [ + { + key: 'coffeeMonitor', + labelKey: 'solution-creator.coffee-machine-monitoring', + icon: 'coffee', + message: 'I want to monitor my coffee machine. It brews espresso, cappuccino, latte, and americano.\n\n' + + 'I need to track stock levels (beans, milk, water, cups), waste fullness, and temperatures. ' + + 'I also want to calculate daily totals for each drink type and daily revenue.\n\n' + + 'Alert me when stock runs low, waste is nearly full, or temperatures are out of range.' + }, + { + key: 'lorawanTracker', + labelKey: 'solution-creator.lorawan-tracking', + icon: 'cell_tower', + message: 'I need a simple device management dashboard for monitoring my LoRaWAN tracker devices and connectivity.\n' + + 'I want to assign a label to device and see them on the map.\n' + + 'I also want to browse the device telemetry related to signal strength and raise alerts when device is offline, low battery or low signal strength.' + }, + { + key: 'waterMetering', + labelKey: 'solution-creator.water-metering', + icon: 'water_drop', + message: 'I\'m building a water metering solution for a utility company. We deploy pulse-based water meters at residential and commercial properties to monitor consumption and track water costs.\n\n' + + 'The meter reports a cumulative pulse counter; consumption in liters is derived from the delta between readings.\n\n' + + 'Residential and commercial properties are billed at different rates. The price per liter is fixed per property type and set by the utility — not configurable per individual property.\n\n' + + 'Each property owner should see only their own consumption and cost data. Alert when consumption is abnormally high or a possible leak is detected. Alert thresholds should be configurable per property.' + }, + { + key: 'smartParking', + labelKey: 'solution-creator.smart-parking', + icon: 'local_parking', + message: 'I would like to create a simple smart parking solution to monitor single level indoor parking lots with magnetic sensors.\n\n' + + 'There will be three roles:\n' + + ' * Solution Administrator will provision customers, sensors and users. He needs to see the alarms from devices.\n' + + ' * Technician will oversee all sensor statuses. He is interested to track the alarms.\n' + + ' * Parking attendant view parking status.\n\n' + + 'Parking lots are relatively small, no need to create Zones or support parking spaces types.\n\n' + + 'Alarms:\n' + + 'An alarm must be generated for a sensor offline, a low battery, or if a vehicle overstays a designated time limit.\n' + + 'The low battery and max stay duration must be configured on the customer level.' + }, + { + key: 'weatherMonitoring', + labelKey: 'solution-creator.weather-monitoring', + icon: 'thermostat', + message: 'I want to monitor outdoor weather conditions across multiple locations using weather stations. ' + + 'Each station reports standard atmospheric data — temperature, humidity, pressure, wind speed and direction, and rainfall.\n\n' + + 'Show all stations on a map. Alert when conditions reach extreme levels such as frost, strong wind, or heavy rainfall.' + }, + { + key: 'fleetGeofencing', + labelKey: 'solution-creator.fleet-geofencing', + icon: 'local_shipping', + message: 'I want to build a fleet tracking solution for transport companies. Vehicles are tracked by GPS in real time and must operate within designated allowed zones while avoiding restricted areas.\n\n' + + 'Raise an alarm when a vehicle enters a restricted zone or leaves an allowed zone.' + }, + ]; + + SolutionStep = SolutionStep; + + private solutionId: string; + private _solutionInfo: SolutionCreatorInfo; + + private get solutionInfo(): SolutionCreatorInfo { + return this._solutionInfo; + } + + private set solutionInfo(value: SolutionCreatorInfo) { + this._solutionInfo = value; + this.info.set(value ? {...value} : null); + this.title.set(value?.data?.solutionTitle || value?.data?.aiSolutionTitle || ''); + this.built.set(!!value?.metadata?.built); + this.installed.set(!!value?.metadata?.installed); + const main = value?.metadata?.installResult?.mainDashboardId; + this.mainDashboard.set(value?.metadata?.installed && main ? [main] : []); + } + private messages$ = toObservable(this.messages); + private forceScroll = false; + + private cancelPending$ = new Subject(); + private workTimers: NodeJS.Timeout[] = []; + + constructor(private route: ActivatedRoute, + private solutionCreator: SolutionsCreatorService, + private router: Router, + private destroyRef: DestroyRef, + private elementRef: ElementRef, + private dialogService: DialogService, + private translate: TranslateService, + private sanitizer: DomSanitizer, + private aiSolutions: AiSolutionsService, + private authService: AuthService) { + super(); + + this.messages$.pipe( + takeUntilDestroyed(), + ).subscribe(value => { + const lastMsg = value[value.length - 1]; + if (this.forceScroll) { + setTimeout(() => { + const animationPanel: Element = this.elementRef.nativeElement.querySelector('.overview'); + if (animationPanel) { + animationPanel.addEventListener('animationend', () => { + this.scrollLogToEnd(); + }, { once: true }); + } else { + this.scrollLogToEnd(); + } + }, 0); + this.forceScroll = false; + } else if (lastMsg?.from === 'USER') { + setTimeout(() => this.scrollLogToEnd(true), 0); + } else if (lastMsg?.from === 'AI') { + setTimeout(() => this.scrollLastQuestionToTop(), 0); + } + }) + } + + ngOnInit() { + SolutionChatComponent.watchUnload(); + this.route.queryParams.pipe( + filter(data => this.solutionId !== data.solutionId), + tap(() => this.resetSolution()), + switchMap(data => { + if (data.solutionId && data.solutionId !== NEW_SOLUTION_ID) { + this.opening.set(true); + const listed$ = this.aiSolutions.loaded() ? of(null) : this.aiSolutions.load().pipe(catchError(() => of(null))); + return forkJoin([this.solutionCreator.getSolutionById(data.solutionId, {ignoreLoading: true, ignoreErrors: true}), listed$]).pipe( + map(([solution]) => solution), + catchError(err => { + this.opening.set(false); + this.creatorStep.set('chat'); + if (err?.status === 400 || err?.status === 404) { + this.router.navigate([], { + relativeTo: this.route, + queryParams: {solutionId: NEW_SOLUTION_ID}, + queryParamsHandling: 'merge', + replaceUrl: true + }); + } else { + this.showErrorMessage(err); + } + return EMPTY; + }) + ); + } else { + this.opening.set(false); + this.creatorStep.set('chat'); + return EMPTY; + } + }), + takeUntilDestroyed(this.destroyRef) + ).subscribe(solution => { + this.opening.set(false); + this.solutionId = solution.id; + this.solutionInfo = solution; + this.forceScroll = true; + this.initPredefinedSolution(); + this.loaded.emit(solution.id); + setTimeout(() => this.scrollLogToEnd(), 300); + }); + } + + ngOnDestroy(): void { + this.keepRunningListed(); + this.clearWork(); + this.cancelPending$.next(); + this.cancelPending$.complete(); + } + + toggleFullscreen(): void { + this.fullscreen.update(value => !value); + } + + renameTo(title: string): void { + if (!this.solutionId || title === this.title()) { + return; + } + this.aiSolutions.rename(this.aiSolutions.find(this.solutionId) ?? {id: this.solutionId}, title).subscribe({ + next: value => this.updatedSolution(value), + error: err => this.showErrorMessage(err) + }); + } + + deleteSolution(): void { + if (!this.solutionId) { + return; + } + this.aiSolutions.confirmAndDelete(this.aiSolutions.find(this.solutionId) ?? {id: this.solutionId, solutionTitle: this.title()}).subscribe({ + next: deleted => { + if (deleted) { + this.router.navigate([], {relativeTo: this.route, queryParams: {solutionId: NEW_SOLUTION_ID}, queryParamsHandling: 'merge'}); + } + }, + error: err => this.showErrorMessage(err) + }); + } + + @HostListener('keydown.escape') + closeAbout(): void { + this.aboutOpen.set(false); + } + + stop(): void { + if (!this.solutionId || this.stopping()) { + return; + } + this.stopping.set(true); + this.solutionCreator.stopSolution(this.solutionId, {ignoreLoading: true, ignoreErrors: true}).subscribe({ + next: stopped => { + if (!stopped) { + this.stopping.set(false); + } + }, + error: () => this.stopping.set(false) + }); + } + + resume(): void { + const action = this.stoppedAction; + this.stoppedAction = null; + this.messages.update(list => list.filter(message => (message as GeneralChatMessage).status !== 'STOPPED')); + action?.(); + } + + private creditsLimitOf(err: any, message?: string): AiCreditsLimitType | null { + const limitType = aiCreditsLimitOf(err); + if (limitType) { + return limitType; + } + const text = message ?? (parseHttpErrorMessage(err, this.translate, isNotEmptyStr(err?.error) ? 'text' : undefined, this.sanitizer).message ?? '').toString(); + return /out of ai credits|ai_credits limit exceeded/i.test(text) ? 'POOL' : null; + } + + private restorePrompt(msg: string): void { + const messages = this.messages(); + const last = messages.map(message => message.from).lastIndexOf('USER'); + let resources: AiResourceInfo[] = []; + if (last >= 0 && (messages[last] as GeneralChatMessage).content === msg) { + resources = (messages[last] as GeneralChatMessage).resources ?? []; + this.messages.set([...messages.slice(0, last), ...messages.slice(last + 1)]); + this.messageSteps = this.messageSteps.slice(0, -1); + } + setTimeout(() => { + this.promptInput?.setValue(msg); + this.promptInput?.restoreAttachments(resources); + }); + } + + private discardFreshSolution(msg: string): boolean { + const solutionId = this.freshSolutionId; + this.freshSolutionId = null; + if (!solutionId || solutionId !== this.solutionId) { + return false; + } + this.aiSolutions.discard(solutionId).subscribe(); + this.router.navigate([], {relativeTo: this.route, queryParams: {solutionId: NEW_SOLUTION_ID}, queryParamsHandling: 'merge', replaceUrl: true}) + .then(() => setTimeout(() => this.promptInput?.setValue(msg))); + return true; + } + + private noticeFor(err: any): boolean { + const status = err?.status; + const message = (parseHttpErrorMessage(err, this.translate, isNotEmptyStr(err?.error) ? 'text' : undefined, this.sanitizer).message ?? '').toString(); + const limitType = this.creditsLimitOf(err, message); + if (status === 0) { + this.setNotice('warn', 'wifi_off', 'connection-failed'); + } else if (limitType) { + this.creditsOut.set(limitType); + } else if (status === 429) { + this.setNotice('warn', 'hourglass_top', 'rate-limited'); + } else { + return false; + } + return true; + } + + private setNotice(kind: AiNotice['kind'], icon: string, key: string): void { + this.notice.set({kind, icon, text: this.translate.instant('ai-assistant.notice.' + key)}); + } + + private wasStopped(err: any, again: () => void, phase: 'chat' | 'build' | 'install' = 'chat'): boolean { + if (!this.stopping() || err?.status !== 409) { + return false; + } + this.stopping.set(false); + this.stoppedAction = again; + this.messageSteps = [...this.messageSteps, this.solutionStep()]; + const chips = phase === 'chat' ? undefined : [ + {id: 'resume', icon: 'play_arrow', label: this.translate.instant(phase === 'install' ? 'solution-creator.create-solution' : 'ai-assistant.resume')}, + {id: 'edit', icon: 'edit', label: this.translate.instant('solution-creator.change-design')} + ]; + this.messages.update(list => [...list, {from: 'AI', content: this.translate.instant('solution-creator.stopped' + (phase === 'chat' ? '' : '-' + phase)), + status: 'STOPPED', time: Date.now(), ...(chips ? {chips} : {})}]); + setTimeout(() => this.scrollLogToEnd(true)); + return true; + } + + private reportFailure(err: any, at?: 'install' | 'step'): void { + this.failedAt.set(at ?? (this.creatorStep() === 'result' ? 'install' : 'step')); + const responseType = isNotEmptyStr(err?.error) ? 'text' : undefined; + this.failure.set(parseHttpErrorMessage(err, this.translate, responseType, this.sanitizer).message); + this.paneOpen.set(true); + setTimeout(() => this.scrollLogToEnd(true)); + } + + private openPaneForStep(): void { + if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { + this.paneOpen.set(true); + } + } + + viewAsMainUser(): void { + const user = this.mainUser(); + const main = this.info()?.metadata?.installResult?.mainDashboardId?.id; + if (!user || !main) { + return; + } + const tenantUser = !this.info()?.metadata?.installResult?.entityResults?.[EntityType.USER] + ?.find(entry => entry.id?.id === user.id)?.additionalData?.customer; + this.authService.redirectUrl = tenantUser ? `/dashboards/all/${main}` : `/dashboards/${main}`; + this.authService.loginAsUser(user.id).subscribe(() => {}); + } + + connectDevices(): void { + window.open(SolutionChatComponent.CONNECTIVITY_GUIDE, '_blank', 'noopener'); + } + + fillExample(key: string): void { + const example = this.solutionExamples.find(ex => ex.key === key); + if (example) { + this.promptInput?.setValue(example.message, true); + } + } + + nextStep() { + const toDashboards = this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION || this.currentView() === 'overview'; + if (toDashboards && this.solutionInfo.states[SolutionStep.INITIAL_CONFIGURATION]?.status !== SolutionStepStatus.READY) { + return; + } + if (!toDashboards && this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]?.status !== SolutionStepStatus.READY) { + if (this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]?.pendingChanges?.length) { + this.sendDashboardConfigurationMsg(''); + } + return; + } + this.pickedView.set(null); + if (toDashboards) { + const dashboardState = this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]; + const notStarted = !dashboardState || (!dashboardState.messages?.length && dashboardState.status !== SolutionStepStatus.READY); + if (notStarted) { + this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION] = { + messages: [], + status: SolutionStepStatus.IN_PROGRESS, + chatId: dashboardState?.chatId ?? null + } + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + this.updatedCurrentMsg(); + this.sendDashboardConfigurationMsg(''); + } else if (dashboardState.pendingChanges?.length) { + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + this.updatedCurrentMsg(); + this.sendDashboardConfigurationMsg(''); + } else { + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + this.updatedCurrentMsg(); + } + } else { + if (this.solutionInfo.metadata?.built) { + this.creatorStep.set('result'); + } else { + this.installProgress.set(null); + this.makeStartedAt.set(Date.now()); + this.installOnly.set(false); + SolutionChatComponent.markMaking(this.solutionId, true); + const dialogRef = this.initGenerateState('create'); + const uninstallOrContinue$ = !this.solutionInfo.metadata?.installed + ? of(null) + : this.solutionCreator.uninstallSolution(this.solutionId, {ignoreLoading: true, ignoreErrors: true}); + uninstallOrContinue$.pipe( + switchMap(() => this.withProgress(this.solutionCreator.createSolution(this.solutionId, { + ignoreLoading: true, + ignoreErrors: true + }))), + tap(() => this.creatorStep.set('result')), + switchMap((solution) => + this.installWithProgress() + .pipe(map((installData) => { + if (!solution.metadata) { + solution.metadata = {} as SolutionMetadata; + } + solution.metadata.installed = true; + if (!solution.metadata.installResult) { + solution.metadata.installResult = {} as SolutionInstallResult; + } + Object.assign(solution.metadata.installResult, installData); + return solution; + })) + ), + takeUntil(this.cancelPending$), + finalize(() => { + this.isGenerating.set(false); + dialogRef.close(); + }) + ) + .subscribe({ + next: (value) => { + SolutionChatComponent.markMaking(value.id, false); + this.solutionInfo = value; + this.aiSolutions.upsert(value); + this.showInstalled(); + }, + error: (err) => { + if (err?.status !== 0 && !SolutionChatComponent.unloading) { + SolutionChatComponent.markMaking(this.solutionId, false); + } + if (!this.wasStopped(err, () => this.nextStep(), 'build') && !this.noticeFor(err)) { + this.reportFailure(err); + } + } + }); + } + } + } + + installSolution() { + this.failure.set(null); + this.installProgress.set(null); + this.makeStartedAt.set(Date.now()); + this.installOnly.set(true); + if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { + this.paneOpen.set(true); + } + const work = this.startWork([{text: 'solution-creator.step-loading-creating-entities', delay: 0}], 'install'); + this.making.set('solution'); + this.installWithProgress().pipe( + takeUntil(this.cancelPending$), + finalize(() => work.close()) + ).subscribe({ + next: (value) => { + SolutionChatComponent.markMaking(this.solutionId, false); + if (!this.solutionInfo.metadata) { + this.solutionInfo.metadata = {} as SolutionMetadata; + } + if (!this.solutionInfo.metadata.installResult) { + this.solutionInfo.metadata.installResult = {} as SolutionInstallResult; + } + Object.assign(this.solutionInfo.metadata.installResult, value); + this.solutionInfo.metadata.installed = true; + this.solutionInfo = {...this.solutionInfo}; + this.aiSolutions.update(this.solutionId, {installed: true}); + this.showInstalled(); + }, + error: (err) => { + if (err?.status !== 0 && !SolutionChatComponent.unloading) { + SolutionChatComponent.markMaking(this.solutionId, false); + } + if (!this.wasStopped(err, () => this.installSolution(), 'install') && !this.noticeFor(err)) { + this.reportFailure(err, 'install'); + } + } + }); + } + + private installWithProgress(): Observable { + return this.withProgress(this.solutionCreator.installSolution(this.solutionId, {ignoreLoading: true, ignoreErrors: true})); + } + + private withProgress(operation: Observable): Observable { + const solutionId = this.solutionId; + const finished$ = new Subject(); + timer(800, 1200).pipe( + switchMap(() => this.aiSolutions.installProgress(solutionId).pipe(catchError(() => of(null)))), + takeUntil(finished$), + takeUntil(this.cancelPending$) + ).subscribe(progress => { + if (progress?.running) { + this.installProgress.set(progress); + } + }); + return operation.pipe( + finalize(() => { + finished$.next(); + finished$.complete(); + }) + ); + } + + estimateOf(view: SolutionView): string { + const estimates = this.info()?.estimates; + const operations: Record>> = { + overview: ['INITIAL_CONFIGURATION'], + dashboards: ['DASHBOARDS_CONFIGURATION'], + solution: ['CREATE', 'INSTALL'] + }; + const known = operations[view].map(operation => estimates?.[operation]).filter((estimate): estimate is SolutionEstimate => !!estimate); + if (!known.length || known.length < operations[view].length) { + return this.translate.instant('solution-creator.pane.estimate-' + view); + } + const seconds = known.reduce((sum, estimate) => sum + estimate.seconds, 0); + const credits = known.reduce((sum, estimate) => sum + estimate.credits, 0); + const time = seconds < 50 + ? this.translate.instant('solution-creator.pane.about-seconds', {count: Math.max(10, Math.round(seconds / 10) * 10)}) + : seconds < 90 + ? this.translate.instant('solution-creator.pane.estimate-solution') + : this.translate.instant('solution-creator.pane.about-minutes', {count: Math.round(seconds / 60)}); + return credits > 0 ? time + ' · ' + this.translate.instant('solution-creator.pane.credits', {credits: formatCredits(credits), count: credits}) : time; + } + + answerQuestions(answers: AiQuestionAnswer[]): void { + this.sendMsgFromUser({message: aiAnswersText(answers), resources: []}); + } + + skipQuestions(answers: AiQuestionAnswer[]): void { + if (this.skipInterviewAllowed()) { + this.skipInterview(); + } else { + this.answerQuestions(answers); + } + } + + onRate(event: AnswerRatingEvent): void { + const target = this.answerAt(event.index); + if (target) { + aiRateAnswer(event, target.answer.rating, this.answerFeedback(event.index, target)); + } + } + + onReport(event: AnswerReportEvent): void { + const target = this.answerAt(event.index); + if (target) { + aiReportAnswer(event, this.answerFeedback(event.index, target), () => this.store.dispatch(new ActionNotificationShow({ + message: this.translate.instant('ai-assistant.feedback.thanks'), type: 'success', modern: true, + target: 'solution-creator-chat', verticalPosition: 'bottom', horizontalPosition: 'center' + }))); + } + } + + private answerFeedback(index: number, target: {answer: GeneralChatMessage; step: SolutionStep}): AiAnswerFeedback { + return { + patch: patch => this.patchAnswer(index, patch), + send: feedback => this.aiSolutions.sendFeedback(this.solutionId, target.step, {answer: target.answer.content, ...feedback}), + failed: () => this.showErrorMessage(this.translate.instant('ai-assistant.feedback.failed')) + }; + } + + private answerAt(index: number): {answer: GeneralChatMessage; step: SolutionStep} | null { + const message = this.viewMessages()[index] as GeneralChatMessage; + if (!this.solutionId || message?.from !== 'AI' || !message.content) { + return null; + } + return {answer: message, step: this.messageSteps[index] ?? this.solutionStep()}; + } + + private patchAnswer(index: number, patch: Partial): void { + if (index >= this.messages().length) { + this.closingPatch.update(current => ({...current, ...patch})); + return; + } + this.messages.update(list => list.map((message, at) => at === index ? {...message, ...patch} as GeneralChatMessage : message)); + } + + uninstallSolution() { + this.dialogService.confirm( + this.translate.instant('solution-creator.uninstall-solution-dialog-title', {name: this.solutionInfo.data.solutionTitle}), + this.translate.instant('solution-creator.uninstall-solution-dialog-text'), + this.translate.instant('action.no'), + this.translate.instant('solution-creator.uninstall-solution-dialog-confirm') + ).subscribe((value) => { + if (value) { + this.solutionCreator.uninstallSolution(this.solutionId, {ignoreErrors: true}).pipe( + takeUntil(this.cancelPending$) + ).subscribe((value) => { + this.solutionInfo = value; + this.aiSolutions.update(this.solutionId, {installed: false}); + this.uninstalledAt.set(Date.now()); + if (this.creatorStep() === 'result') { + this.pickedView.set({view: 'solution', phase: this.phase()}); + } + }); + } + }) + } + + startOver() { + this.initLoadingState(); + this.solutionCreator.clearStep(this.solutionId, this.solutionStep(), {ignoreLoading: true, ignoreErrors: true}).pipe( + takeUntil(this.cancelPending$) + ).subscribe({ + next: () => { + this.messages.set([]); + this.messageSteps = []; + this.isReadyStep.set(false); + if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { + this.sendDashboardConfigurationMsg(''); + } else { + this.stopLoadingState(); + } + }, + error: (err) => { + this.showErrorMessage(err); + this.stopLoadingState(); + }, + complete: () => { + this.stopLoadingState(); + } + }) + } + + editDesign(): void { + if (this.creatorStep() === 'result') { + this.back(); + } + } + + back(): void { + this.forceScroll = true; + if (this.creatorStep() === 'result') { + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + this.creatorStep.set('chat'); + } else if(this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { + this.solutionStep.set(SolutionStep.INITIAL_CONFIGURATION); + } + this.updatedCurrentMsg(); + } + + updatedSolutionDescriptor(descriptor: SolutionDescriptor) { + this.solutionCreator.updateSolutionData(this.solutionId, 'solutionDescriptor', descriptor, {ignoreLoading: true}).pipe( + takeUntil(this.cancelPending$) + ).subscribe(value => { + this.solutionInfo = value; + this.aiSolutions.upsert(value); + this.updatedCurrentMsg(); + }); + } + + updatedDashboardOverview(dashboards: DashboardsOverview[]) { + this.solutionCreator.updateSolutionData(this.solutionId, 'dashboardsOverview', dashboards, {ignoreLoading: true}).pipe( + takeUntil(this.cancelPending$) + ).subscribe(value => { + this.solutionInfo = value; + this.aiSolutions.upsert(value); + this.updatedCurrentMsg(); + }); + } + + get solutionMetadata(): Partial { + return this.solutionInfo?.metadata ?? {}; + } + + get nextButtonLabel(): string { + if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { + return 'solution-creator.go-dashboard-manager'; + } else { + if (this.solutionInfo.metadata?.built) { + return 'solution-creator.finish-edit'; + } + if (this.solutionInfo.data.entities || this.solutionInfo.data.dashboards) { + return 'solution-creator.update-solution'; + } + return 'solution-creator.create-solution'; + } + } + + updatedSolution($event: SolutionCreatorInfo) { + if ($event.id === this.solutionId) { + this.solutionInfo = $event; + } + } + + onInstalledChanged($event: {solutionId: string, installed: boolean}) { + if ($event.solutionId === this.solutionId && this.solutionInfo) { + if (!this.solutionInfo.metadata) { + this.solutionInfo.metadata = {} as SolutionMetadata; + } + this.solutionInfo.metadata.installed = $event.installed; + } + } + + startCreateSolution(key: string) { + const example = this.solutionExamples.find(ex => ex.key === key); + if (example) { + this.sendMsgFromUser({message: example.message, resources: []}); + } + } + + private showInstalled(): void { + this.creatorStep.set('result'); + this.json.set(false); + this.pickedView.set({view: 'solution', phase: this.phase()}); + if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { + this.paneOpen.set(true); + } + } + + gotoMainDashboard(openInfoDialog = false): void { + this.router.navigateByUrl( + this.router.createUrlTree([baseDetailsPageByEntityType.get(EntityType.DASHBOARD), this.solutionMetadata.installResult.mainDashboardId.id]) + ).then(()=> { + if (openInfoDialog) { + this.openInfo(); + } + }); + } + + openInfo(): void { + this.dialogService.dialog.open(SolutionInfoDialogComponent, { + disableClose: true, + panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], + data: { + solution: this.solutionInfo + } + }).afterClosed().subscribe(() => {}); + } + + private sendMessage(msg: string, resources: string[] = []): Observable { + this.initLoadingState(); + + const startOrContinue$ = this.solutionId + ? of(null) + : this.solutionCreator.startSolution({ignoreLoading: true, ignoreErrors: true}).pipe( + tap(solution => { + this.freshSolutionId = solution.id; + this.solutionId = solution.id; + this.solutionInfo = solution; + this.rememberSolution(); + this.router.navigate([], { + relativeTo: this.route, + queryParams: { solutionId: this.solutionId }, + queryParamsHandling: 'merge', + }).then(() => {}); + }) + ); + + return startOrContinue$.pipe( + switchMap(() => + this.solutionCreator.chatSolution(this.solutionId, this.solutionStep(), msg, {ignoreLoading: true, ignoreErrors: true}, resources) + ), + tap(solution => { + this.freshSolutionId = null; + this.solutionInfo = solution; + this.rememberSolution(); + this.updatedCurrentMsg(); + if (this.isReadyStep()) { + this.openPaneForStep(); + } + }), + catchError(err => { + if (this.creditsLimitOf(err)) { + this.restorePrompt(msg); + if (this.discardFreshSolution(msg)) { + this.noticeFor(err); + return EMPTY; + } + } + this.freshSolutionId = null; + if (err?.status === 0 && this.solutionId && this.solutionId !== NEW_SOLUTION_ID) { + this.setNotice('warn', 'wifi_off', 'connection-lost'); + this.recoverDroppedMessage(msg); + return EMPTY; + } + if (!this.wasStopped(err, () => this.sendMessage(msg, resources).subscribe(() => {})) && !this.noticeFor(err)) { + this.showErrorMessage(err); + } + this.rememberSolution(); + return EMPTY; + }), + takeUntil(this.cancelPending$), + finalize(() => this.stopLoadingState()) + ); + } + + private scrollLogToEnd(smooth = false): void { + const log = this.elementRef.nativeElement.querySelector('.sol-log') as HTMLElement; + log?.scrollTo({top: log.scrollHeight, behavior: smooth ? 'smooth' : 'auto'}); + } + + private scrollLastQuestionToTop(): void { + const log = this.elementRef.nativeElement.querySelector('.sol-log') as HTMLElement; + const questions = log?.querySelectorAll('tb-ai-chat-messages .user'); + const last = questions?.length ? questions[questions.length - 1] : null; + if (log && last) { + const top = log.scrollTop + last.getBoundingClientRect().top - log.getBoundingClientRect().top - 12; + log.scrollTo({top, behavior: 'smooth'}); + } + } + + private rememberSolution(): void { + if (this.solutionInfo) { + this.aiSolutions.upsert(this.solutionInfo); + } + } + + private sendDashboardConfigurationMsg(message: string): void { + const dialogRef = this.initGenerateState(message === '' ? 'sync' : 'design'); + this.sendMessage(message).pipe( + finalize(() => { + this.isGenerating.set(false); + dialogRef.close(); + }), + ).subscribe(() => {}); + } + + private updatedCurrentMsg() { + const steps = this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION + ? [SolutionStep.INITIAL_CONFIGURATION, SolutionStep.DASHBOARDS_CONFIGURATION] + : [SolutionStep.INITIAL_CONFIGURATION]; + const tagged = steps.flatMap(step => (this.solutionInfo.states[step]?.messages ?? []).filter(isVisibleMessage).map(message => ({message, step}))); + this.messageSteps = tagged.map(item => item.step); + this.messages.set(tagged.map(item => item.message)); + const stepState = this.solutionInfo.states[this.solutionStep()]; + if (stepState?.status === SolutionStepStatus.READY) { + if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { + } + if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { + } + this.isReadyStep.set(true); + this.skipInterviewAllowed.set(false); + } else { + this.isReadyStep.set(false); + this.skipInterviewAllowed.set(!!stepState?.skipInterviewAllowed); + } + } + + showErrorMessage(error: any): void { + const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; + const message = parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message; + const showOnTop = this.creatorStep() === 'result' || this.isInitialEmpty(); + this.store.dispatch(new ActionNotificationShow({ + message, + modern: true, + type: 'error', + target: showOnTop ? 'solution-creator' : 'solution-creator-chat', + verticalPosition: showOnTop ? 'top' : 'bottom', + horizontalPosition: 'center', + panelClass: showOnTop ? ( this.isInitialEmpty() ? 'mt-4' : 'mt-12') : '' + })); + } + + private keepRunningListed(): void { + if (this.solutionId && this.solutionId !== NEW_SOLUTION_ID && (this.loading() || this.isGenerating())) { + this.aiSolutions.keepRunning(this.solutionId); + } + } + + private resetSolution(): void { + this.keepRunningListed(); + this.clearWork(); + this.pickedView.set(null); + this.json.set(false); + this.installProgress.set(null); + this.failedAt.set('step'); + this.uninstalledAt.set(null); + this.cancelPending$.next(); + this.isReadyStep.set(false); + this.skipInterviewAllowed.set(false); + this.solutionStep.set(SolutionStep.INITIAL_CONFIGURATION); + this.messages.set([]); + this.messageSteps = []; + this.closingPatch.set({}); + this.stopping.set(false); + this.stopLoadingState(); + this.creatorStep.set(null); + this.promptInput?.reset(); + this.showMoreExamples.set(false); + this.solutionId = undefined; + this.solutionInfo = undefined; + } + + private initPredefinedSolution(): void { + const listed = this.aiSolutions.find(this.solutionInfo?.id); + this.failure.set(listed?.status === 'FAILED' ? listed.statusReason ?? null : null); + if (this.solutionInfo.metadata?.built) { + if (this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]) { + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + } + this.updatedCurrentMsg(); + this.creatorStep.set('result'); + if (!this.solutionInfo.metadata?.installed) { + this.resumeMaking(); + } + return; + } + this.creatorStep.set('chat'); + const initialStatus = this.solutionInfo.states[SolutionStep.INITIAL_CONFIGURATION]?.status; + const dashboardState = this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]; + const dashboardsStarted = !!dashboardState && (!!dashboardState.messages?.length || dashboardState.status === SolutionStepStatus.READY + || !this.aiSolutions.loaded() || this.aiSolutions.find(this.solutionInfo.id)?.status === 'RUNNING'); + this.solutionStep.set(initialStatus === SolutionStepStatus.READY && dashboardsStarted + ? SolutionStep.DASHBOARDS_CONFIGURATION : SolutionStep.INITIAL_CONFIGURATION); + this.updatedCurrentMsg(); + if (this.isReadyStep()) { + this.paneOpen.set(true); + } + if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION && dashboardState?.pendingChanges?.length) { + this.sendDashboardConfigurationMsg(''); + } + if (this.designStillRunning()) { + this.waitForDesign(); + } else if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION && this.isReadyStep()) { + this.resumeMaking(); + } + } + + private static unloading = false; + + private static watchUnload(): void { + window.addEventListener('pagehide', () => SolutionChatComponent.unloading = true, {once: true}); + } + + private static makingKey(solutionId: string): string { + return 'tb-ai-solution-making-' + solutionId; + } + + private static markMaking(solutionId: string | undefined, making: boolean): void { + if (!solutionId) { + return; + } + try { + if (making) { + sessionStorage.setItem(SolutionChatComponent.makingKey(solutionId), '1'); + } else { + sessionStorage.removeItem(SolutionChatComponent.makingKey(solutionId)); + } + } catch { + return; + } + } + + private static wasMaking(solutionId: string): boolean { + try { + return sessionStorage.getItem(SolutionChatComponent.makingKey(solutionId)) === '1'; + } catch { + return false; + } + } + + private resumeMaking(): void { + const solutionId = this.solutionId; + const pending = SolutionChatComponent.wasMaking(solutionId); + forkJoin([ + this.aiSolutions.load().pipe(catchError(() => of([]))), + this.aiSolutions.installProgress(solutionId).pipe(catchError(() => of(null))), + this.solutionCreator.getSolutionById(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe(catchError(() => of(null))) + ]).pipe(takeUntil(this.cancelPending$), takeUntilDestroyed(this.destroyRef)).subscribe(([, progress, fresh]) => { + if (this.solutionId !== solutionId || this.isGenerating()) { + return; + } + if (fresh) { + this.solutionInfo = fresh; + if (fresh.metadata?.built && this.creatorStep() !== 'result') { + this.creatorStep.set('result'); + } + if (fresh.metadata?.installed) { + SolutionChatComponent.markMaking(solutionId, false); + return; + } + } + const running = this.aiSolutions.find(solutionId)?.status === 'RUNNING' || !!progress?.running; + const built = !!this.solutionInfo?.metadata?.built; + if (!built && running) { + this.followCreate(); + } else if (built && running) { + this.followInstall(); + } else if (built && pending) { + this.installSolution(); + } + }); + } + + private followCreate(): void { + const solutionId = this.solutionId; + this.installProgress.set(null); + this.makeStartedAt.set(Date.now() - this.makeSeconds() * 1000); + this.installOnly.set(false); + SolutionChatComponent.markMaking(solutionId, true); + const dialogRef = this.initGenerateState('create'); + this.withProgress(timer(SolutionChatComponent.DESIGN_POLL_MS, SolutionChatComponent.DESIGN_POLL_MS).pipe( + take(SolutionChatComponent.DESIGN_POLL_LIMIT), + switchMap(() => this.solutionCreator.getSolutionById(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe(catchError(() => EMPTY))), + filter(solution => !!solution.metadata?.built), + take(1) + )).pipe( + takeUntil(this.cancelPending$), + finalize(() => { + this.isGenerating.set(false); + dialogRef.close(); + }), + takeUntilDestroyed(this.destroyRef) + ).subscribe(solution => { + if (this.solutionId !== solutionId) { + return; + } + this.solutionInfo = solution; + this.aiSolutions.upsert(solution); + this.creatorStep.set('result'); + if (!solution.metadata?.installed) { + setTimeout(() => this.installSolution(), 0); + } + }); + } + + private followInstall(): void { + const solutionId = this.solutionId; + this.installProgress.set(null); + this.makeStartedAt.set(Date.now() - this.makeSeconds() * 1000); + this.installOnly.set(true); + this.creatorStep.set('result'); + if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { + this.paneOpen.set(true); + } + const work = this.startWork([{text: 'solution-creator.step-loading-creating-entities', delay: 0}], 'install'); + this.making.set('solution'); + timer(800, 1200).pipe( + switchMap(() => this.aiSolutions.installProgress(solutionId).pipe(catchError(() => of(null)))), + tap(progress => { + if (progress?.running) { + this.installProgress.set(progress); + } + }), + filter(progress => !progress?.running), + take(1), + switchMap(() => this.solutionCreator.getSolutionById(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe(catchError(() => EMPTY))), + takeUntil(this.cancelPending$), + finalize(() => work.close()), + takeUntilDestroyed(this.destroyRef) + ).subscribe(solution => { + if (this.solutionId !== solutionId) { + return; + } + this.solutionInfo = solution; + this.aiSolutions.upsert(solution); + if (solution.metadata?.installed) { + SolutionChatComponent.markMaking(solutionId, false); + this.showInstalled(); + } + }); + } + + private recoverDroppedMessage(msg: string): void { + const solutionId = this.solutionId; + const step = this.solutionStep(); + const sent = this.messages().filter((message, at) => message.from === 'USER' && this.messageSteps[at] === step).length; + timer(0, SolutionChatComponent.DESIGN_POLL_MS).pipe( + take(SolutionChatComponent.DESIGN_POLL_LIMIT), + switchMap(() => forkJoin([ + this.solutionCreator.getSolutionById(solutionId, {ignoreLoading: true, ignoreErrors: true}), + this.aiSolutions.load() + ]).pipe(catchError(() => EMPTY))), + take(1), + defaultIfEmpty(null), + takeUntil(this.cancelPending$), + takeUntilDestroyed(this.destroyRef) + ).subscribe(result => { + if (this.solutionId !== solutionId) { + return; + } + this.notice.set(null); + const solution = result?.[0]; + const received = !!solution && (solution.states?.[step]?.messages ?? []) + .filter(message => message.from === 'USER' && isVisibleMessage(message)).length >= sent; + if (!received) { + this.restorePrompt(msg); + this.setNotice('warn', 'wifi_off', 'connection-failed'); + return; + } + this.solutionInfo = solution; + this.aiSolutions.upsert(solution); + this.initPredefinedSolution(); + }); + } + + private designStillRunning(): boolean { + return this.stepAwaitingReply(this.solutionInfo, this.solutionStep()); + } + + private stepAwaitingReply(solution: SolutionCreatorInfo | undefined, step: SolutionStep): boolean { + const state = solution?.states?.[step]; + const last = state?.messages?.at(-1) as GeneralChatMessage | undefined; + if (state && state.status !== SolutionStepStatus.READY && this.aiSolutions.find(solution.id)?.status === 'RUNNING') { + return true; + } + if (state && !last && state.status !== SolutionStepStatus.READY) { + return !this.aiSolutions.loaded() || this.aiSolutions.find(solution.id)?.status === 'RUNNING'; + } + if (last?.from === 'USER') { + return this.awaitingReply(solution.id, last); + } + return state?.status !== SolutionStepStatus.READY && this.awaitingReply(solution?.id, last); + } + + private awaitingReply(solutionId: string, last: GeneralChatMessage | undefined): boolean { + if (last?.from === 'USER') { + return !this.aiSolutions.loaded() || this.aiSolutions.find(solutionId)?.status === 'RUNNING'; + } + return last?.from === 'AI' && /^\s*(✅|🛠️|🛠)/u.test(last.content ?? ''); + } + + private waitForDesign(): void { + const solutionId = this.solutionId; + const step = this.solutionStep(); + this.skipInterviewAllowed.set(false); + const since = this.workSince(step); + if (step === SolutionStep.DASHBOARDS_CONFIGURATION) { + this.initGenerateState('design', since); + } else { + if ((this.messages().at(-1) as GeneralChatMessage | undefined)?.from === 'AI') { + this.messages.set(this.messages().slice(0, -1)); + this.messageSteps = this.messageSteps.slice(0, -1); + } + this.isGenerating.set(true); + this.startWork([{text: 'solution-creator.work-thinking', delay: 0}], 'think', since); + } + timer(SolutionChatComponent.DESIGN_POLL_MS, SolutionChatComponent.DESIGN_POLL_MS).pipe( + take(SolutionChatComponent.DESIGN_POLL_LIMIT), + switchMap(() => this.solutionCreator.getSolutionById(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe(catchError(() => EMPTY))), + filter(solution => !this.stepAwaitingReply(solution, step)), + take(1), + takeUntil(this.cancelPending$), + finalize(() => { + if (this.solutionId === solutionId) { + this.isGenerating.set(false); + this.clearWork(); + } + }), + takeUntilDestroyed(this.destroyRef) + ).subscribe(solution => { + if (this.solutionId !== solutionId) { + return; + } + this.isGenerating.set(false); + this.clearWork(); + this.solutionInfo = solution; + this.aiSolutions.upsert(solution); + this.initPredefinedSolution(); + }); + } + + private initGenerateState(kind: 'design' | 'sync' | 'create', since = Date.now()) { + this.failure.set(null); + this.isGenerating.set(true); + let messages: Array<{text: string; delay: number}>; + if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { + messages = [ + { text: 'solution-creator.step-loading-updating-entities', delay: 0 }, + { text: 'solution-creator.step-loading-restructuring-roles', delay: 10000 }, + { text: 'solution-creator.step-loading-rebuilding-alarm-rules', delay: 10000 }, + { text: 'solution-creator.step-loading-reassembling-dashboards', delay: 10000 }, + { text: 'solution-creator.step-loading-updating-solution', delay: 10000 }, + ]; + } else if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { + if (kind === 'design') { + messages = [ + { text: 'solution-creator.step-loading-designing-dashboards-structure', delay: 0 }, + { text: 'solution-creator.step-loading-designing-dashboards-states', delay: 10000 }, + { text: 'solution-creator.step-loading-designing-widgets', delay: 10000 }, + { text: 'solution-creator.step-loading-adding-finishing-touches', delay: 10000 }, + ]; + } else if (kind === 'sync') { + messages = [ + { text: 'solution-creator.step-loading-evaluating-solution-changes', delay: 0 }, + { text: 'solution-creator.step-loading-reevaluating-use-cases', delay: 5000 }, + { text: 'solution-creator.step-loading-finalizing', delay: 15000 }, + ]; + } else { + messages = [ + { text: 'solution-creator.step-loading-creating-entities', delay: 0 }, + { text: 'solution-creator.step-loading-configuring-devices', delay: 10000 }, + { text: 'solution-creator.step-loading-setting-up-relations', delay: 10000 }, + { text: 'solution-creator.step-loading-structuring-access-controls', delay: 10000 }, + { text: 'solution-creator.step-loading-building-calculated-fields', delay: 10000 }, + { text: 'solution-creator.step-loading-building-alarm-rules', delay: 10000 }, + { text: 'solution-creator.step-loading-assembling-dashboards', delay: 10000 }, + { text: 'solution-creator.step-loading-preparing-states', delay: 10000 }, + { text: 'solution-creator.step-loading-initializing-solution', delay: 10000 }, + ]; + } + } + + const creating = messages[0]?.text === 'solution-creator.step-loading-creating-entities'; + this.making.set(creating ? 'solution' : this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION ? 'dashboards' : 'overview'); + this.json.set(false); + if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { + this.paneOpen.set(true); + } + return this.startWork(messages, creating ? 'install' : 'gen', since); + } + + private static storeWork(solutionId: string, value: string): void { + try { + sessionStorage.setItem(SolutionChatComponent.workKey(solutionId), value); + } catch { + return; + } + } + + private static workKey(solutionId: string): string { + return `tb-ai-solution-work-${solutionId}`; + } + + private workSince(step: SolutionStep): number { + let since = 0; + try { + const [storedStep, storedSince] = (sessionStorage.getItem(SolutionChatComponent.workKey(this.solutionId)) ?? '').split(':'); + if (storedStep === step) { + since = Number(storedSince) || 0; + } + } catch { + since = 0; + } + const asked = (this.messages() as GeneralChatMessage[]).filter(message => message.from === 'USER' && message.time).at(-1)?.time ?? 0; + const start = Math.max(since, asked); + return start > 0 && start <= Date.now() ? start : Date.now(); + } + + private startWork(messages: Array<{text: string; delay: number}>, kind: 'think' | 'gen' | 'install', + since = Date.now()): {close: () => void} { + const making = this.making(); + this.clearWork(); + this.making.set(making); + if (kind !== 'install' && this.solutionId && this.solutionId !== NEW_SOLUTION_ID) { + SolutionChatComponent.storeWork(this.solutionId, `${this.solutionStep()}:${since}`); + } + const lines = messages.map(message => this.translate.instant(message.text) as string); + let at = 0; + messages.forEach((message, index) => { + at += message.delay; + this.workTimers.push(setTimeout(() => this.work.set({words: lines[index], kind, since, lines}), at)); + }); + return {close: () => this.clearWork()}; + } + + private clearWork(): void { + this.workTimers.forEach(timer => clearTimeout(timer)); + this.workTimers = []; + this.work.set(null); + this.making.set(null); + } + + pickView(view: SolutionView): void { + this.pickedView.set({view, phase: this.phase()}); + this.json.set(false); + } + + toggleJson(): void { + this.json.set(!this.json()); + } + + applyJson(value: unknown): void { + if (this.currentView() === 'dashboards') { + this.updatedDashboardOverview(value as DashboardsOverview[]); + } else { + this.updatedSolutionDescriptor(value as SolutionDescriptor); + } + } + + openPane(): void { + this.paneOpen.set(true); + } + + closePane(): void { + this.paneOpen.set(false); + this.json.set(false); + } + + toggleMoreExamples(): void { + this.showMoreExamples.update(v => !v); + } + + skipActions(): AiCardAction[] { + return [{id: 'skip', icon: 'fast_forward', label: this.translate.instant('solution-creator.skip-interview')}]; + } + + skipInterview(): void { + this.sendMessage('').subscribe(() => {}); + } + + sendMsgFromUser(prompt: AiPromptMessage): void { + const time = Date.now(); + this.messageSteps = [...this.messageSteps, this.solutionStep()]; + this.messages.update(list => [...list, prompt.resources.length + ? {from: 'USER', content: prompt.message, resources: prompt.resources, time} + : {from: 'USER', content: prompt.message, time}]); + this.sendMessage(prompt.message, prompt.resources.map(resource => resource.id)).subscribe(() => {}); + } + + private initLoadingState(): void { + this.failure.set(null); + if (this.notice()?.kind !== 'block') { + this.notice.set(null); + } + this.loading.set(true); + if (!this.workTimers.length) { + this.startWork([{text: this.messages().length ? 'solution-creator.work-thinking' : 'solution-creator.work-reading', delay: 0}], 'think'); + } + } + + private stopLoadingState(): void { + this.loading.set(false); + if (!this.isGenerating()) { + this.clearWork(); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.module.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.module.ts new file mode 100644 index 0000000000..20cf12a4f9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.module.ts @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { CommonModule } from '@angular/common'; +import { SharedModule } from '@shared/shared.module'; +import { HomeComponentsModule } from '@home/components/home-components.module'; +import { NgModule } from '@angular/core'; +import { SolutionChatComponent } from '@home/components/ai/solution/solution-chat.component'; +import { + SolutionInfoDialogComponent +} from '@home/components/ai/solution/solution-info/solution-info-dialog.component'; +import { + IssuesPopoverComponent +} from '@home/components/ai/solution/solution-info/issues-popover.component'; +import { NgxGraphModule } from '@swimlane/ngx-graph'; +import { SolutionOverviewComponent } from '@home/components/ai/solution/pane/solution-overview.component'; +import { SolutionDashboardsComponent } from '@home/components/ai/solution/pane/solution-dashboards.component'; +import { SolutionInstalledComponent } from '@home/components/ai/solution/pane/solution-installed.component'; +import { SolutionJsonComponent } from '@home/components/ai/solution/pane/solution-json.component'; +import { AiModule } from '@home/components/ai/ai.module'; + +@NgModule({ + declarations: [ + SolutionChatComponent, + SolutionOverviewComponent, + SolutionDashboardsComponent, + SolutionInstalledComponent, + SolutionJsonComponent, + SolutionInfoDialogComponent, + IssuesPopoverComponent + ], + imports: [ + CommonModule, + SharedModule, + HomeComponentsModule, + NgxGraphModule, + AiModule + ], + exports: [ + SolutionChatComponent + ] +}) +export class SolutionChatModule { } diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-aggregation.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-aggregation.ts similarity index 100% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-aggregation.ts rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-aggregation.ts diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.html similarity index 100% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.html rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.html diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.scss similarity index 100% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.scss rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.scss diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.ts similarity index 95% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.ts rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.ts index 9e01a9776d..5066957104 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { Component, Input } from '@angular/core'; -import { AggregatedEntityResult, issuesCountSummary } from '@home/pages/ai-solution-creator/solution-info/issues-aggregation'; +import { AggregatedEntityResult, issuesCountSummary } from '@home/components/ai/solution/solution-info/issues-aggregation'; import { EntityResult } from '@shared/models/solution-creator.models'; import { TranslateService } from '@ngx-translate/core'; diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.html similarity index 99% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.html rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.html index b2ce060ca6..fb24ae192e 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.html @@ -13,7 +13,7 @@
- +
@let dashboardEntries = aggregatedFor(EntityType.DASHBOARD); @if (dashboardEntries.length > 0) { diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.scss similarity index 100% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.scss rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.scss diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.ts similarity index 94% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.ts rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.ts index 991222e665..a903f4745f 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.ts @@ -17,9 +17,9 @@ import { AggregatedEntityResult, issuesCountSummary, IssueStatus -} from '@home/pages/ai-solution-creator/solution-info/issues-aggregation'; +} from '@home/components/ai/solution/solution-info/issues-aggregation'; import { TbPopoverService } from '@shared/components/popover.service'; -import { IssuesPopoverComponent } from '@home/pages/ai-solution-creator/solution-info/issues-popover.component'; +import { IssuesPopoverComponent } from '@home/components/ai/solution/solution-info/issues-popover.component'; export interface SolutionInfoDialogData { solution: SolutionCreatorInfo; @@ -28,7 +28,7 @@ export interface SolutionInfoDialogData { @Component({ selector: 'tb-solution-info-dialog', templateUrl: './solution-info-dialog.component.html', - styleUrls: ['../../../../../shared/components/markdown.component.scss', './solution-info-dialog.component.scss'], + styleUrls: ['../../../../../../shared/components/markdown.component.scss', './solution-info-dialog.component.scss'], standalone: false }) export class SolutionInfoDialogComponent extends DialogComponent { diff --git a/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts b/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts index 36ce683376..c2c801f634 100644 --- a/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts +++ b/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts @@ -124,7 +124,7 @@ export class AlarmRulesTableConfig extends EntityTableConfig -@if (show()) { -
- - -
-} diff --git a/ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.ts b/ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.ts deleted file mode 100644 index 731caf5423..0000000000 --- a/ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.ts +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, OnInit } from '@angular/core'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { AuthUser } from '@shared/models/user.model'; -import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; -import { Operation, Resource } from '@shared/models/security.models'; -import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { alarmRuleEntityTypeList } from '@shared/models/alarm-rule.models'; - -@Component({ - selector: 'tb-ai-assistant-alarm-button', - templateUrl: './ai-assistant-alarm-button.component.html', - standalone: false -}) -export class AiAssistantAlarmButtonComponent implements OnInit { - - private authUser: AuthUser = getCurrentAuthUser(this.store); - private hasPermission: boolean; - - constructor(private store: Store, - private panelService: AiAssistantPanelService, - private userPermissionsService: UserPermissionsService) { - } - - ngOnInit(): void { - this.hasPermission = getCurrentAuthState(this.store).aiEnabled && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) && - alarmRuleEntityTypeList.some(entityType => - this.userPermissionsService.hasGenericPermissionByEntityGroupType(Operation.READ_CALCULATED_FIELD, entityType)); - } - - show(): boolean { - return this.hasPermission && !this.panelService.open(); - } - - toggleAiAssistant($event: Event): void { - $event?.stopPropagation(); - this.panelService.toggle(); - } -} diff --git a/ui-ngx/src/app/modules/home/components/alarm/alarm-comment.component.scss b/ui-ngx/src/app/modules/home/components/alarm/alarm-comment.component.scss index 91f07bce91..8c482949f4 100644 --- a/ui-ngx/src/app/modules/home/components/alarm/alarm-comment.component.scss +++ b/ui-ngx/src/app/modules/home/components/alarm/alarm-comment.component.scss @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 @use '@angular/material' as mat; -@import "../theme/app-theme.scss"; +@import "../theme/app-theme-palette"; @import '../../../../../scss/constants'; $primary-color: mat.m2-get-color-from-palette($tb-primary); diff --git a/ui-ngx/src/app/modules/home/components/alarm/alarm-details-dialog.component.ts b/ui-ngx/src/app/modules/home/components/alarm/alarm-details-dialog.component.ts index 3115a38684..aae7ebe3da 100644 --- a/ui-ngx/src/app/modules/home/components/alarm/alarm-details-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/alarm/alarm-details-dialog.component.ts @@ -31,6 +31,7 @@ export interface AlarmDetailsDialogData { allowClear: boolean; displayDetails: boolean; allowAssign: boolean; + displayOriginatorName?: boolean; } @Component({ @@ -108,8 +109,10 @@ export class AlarmDetailsDialogComponent extends DialogComponent filter_list{{buttonDisplayValue}} diff --git a/ui-ngx/src/app/modules/home/components/alarm/alarm-table-config.ts b/ui-ngx/src/app/modules/home/components/alarm/alarm-table-config.ts index 2f846be65b..66b727ce14 100644 --- a/ui-ngx/src/app/modules/home/components/alarm/alarm-table-config.ts +++ b/ui-ngx/src/app/modules/home/components/alarm/alarm-table-config.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +import { aiSevMarkElement } from '@home/components/ai/ai-sev-mark.component'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { CellActionDescriptorType, DateEntityTableColumn, @@ -23,7 +25,6 @@ import { AlarmInfo, AlarmQueryV2, AlarmSearchStatus, - alarmSeverityColors, alarmSeverityTranslations, AlarmsMode, alarmStatusTranslations, @@ -44,7 +45,6 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { getEntityDetailsPageURL, isDefinedAndNotNull, isNotEmptyStr, isUndefinedOrNull } from '@core/utils'; -import { Authority } from '@shared/models/authority.enum'; import { ChangeDetectorRef, Injector, StaticProvider, ViewContainerRef } from '@angular/core'; import { ConnectedPosition, Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay'; import { @@ -106,8 +106,7 @@ export class AlarmTableConfig extends EntityTableConfig this.defaultSortOrder = {property: 'createdTime', direction: Direction.DESC}; - if (this.pageMode && this.authUser.authority === Authority.TENANT_ADMIN && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL)) { + if (this.pageMode && this.userPermissionsService.isAiAvailable()) { this.aiAssistantConfig = { view: { listView: AiAssistantViewType.ALARM_LIST @@ -138,11 +137,9 @@ export class AlarmTableConfig extends EntityTableConfig entity => this.utilsService.customTranslation(entity.type, entity.type))); this.columns.push( new EntityTableColumn('severity', 'alarm.severity', '25%', - (entity) => this.translate.instant(alarmSeverityTranslations.get(entity.severity)), - entity => ({ - fontWeight: 'bold', - color: alarmSeverityColors.get(entity.severity) - }))); + (entity) => '' + + aiSevMarkElement(entity.severity).outerHTML + + `${this.translate.instant(alarmSeverityTranslations.get(entity.severity))}`)); this.columns.push( new EntityTableColumn('assignee', 'alarm.assignee', '240px', (entity) => this.getAssigneeTemplate(entity), () => ({}), false, () => ({}), () => undefined, false, @@ -209,7 +206,7 @@ export class AlarmTableConfig extends EntityTableConfig } showAlarmDetails(entity: AlarmInfo) { - this.dialog.open + const dialog$ = this.dialog.open (AlarmDetailsDialogComponent, { disableClose: true, @@ -220,9 +217,15 @@ export class AlarmTableConfig extends EntityTableConfig allowAcknowledgment: this.writeEnabled, allowClear: this.writeEnabled, displayDetails: true, - allowAssign: true + allowAssign: true, + displayOriginatorName: true } - }).afterClosed().subscribe( + }).afterClosed(); + const closed$ = this.aiAssistantConfig + ? this.viewContainerRef.injector.get(AiAssistantPanelService).focusWhile( + {type: AiAssistantViewType.ALARM, entityId: entity.id}, entity.type, dialog$) + : dialog$; + closed$.subscribe( (res) => { if (res) { this.updateData(); diff --git a/ui-ngx/src/app/modules/home/components/attribute/attribute-table.component.html b/ui-ngx/src/app/modules/home/components/attribute/attribute-table.component.html index 4312b71358..38d7aa0379 100644 --- a/ui-ngx/src/app/modules/home/components/attribute/attribute-table.component.html +++ b/ui-ngx/src/app/modules/home/components/attribute/attribute-table.component.html @@ -239,11 +239,8 @@ showFirstLastButtons> @if (mode === 'widget' && widgetsList.length > 0) {
@for (widgets of widgetsList; track widgets) { @@ -267,6 +264,7 @@ @if (widgetsCarouselIndex > 0) {
- +
} @case (ReprocessingState.RESULTS) { diff --git a/ui-ngx/src/app/modules/home/components/calculated-fields/components/reprocessing/calculated-field-reprocessing-panel.component.ts b/ui-ngx/src/app/modules/home/components/calculated-fields/components/reprocessing/calculated-field-reprocessing-panel.component.ts index 005b7ec6bf..3e7276c155 100644 --- a/ui-ngx/src/app/modules/home/components/calculated-fields/components/reprocessing/calculated-field-reprocessing-panel.component.ts +++ b/ui-ngx/src/app/modules/home/components/calculated-fields/components/reprocessing/calculated-field-reprocessing-panel.component.ts @@ -210,11 +210,13 @@ export class CalculatedFieldReprocessingPanelComponent implements OnInit { if (this.showEntityProcessing) { const total = this.job().result.totalCount; if (isDefinedAndNotNull(total)) { + this.destroy$.next(); const process = processTask(this.job().result); - const progress = process > 0 ? Math.round(process / total * 100) : (total > 0 ? 0 : 100); - if (progress > this.processProgress()) { - this.processProgress.set(progress); + let progress = total > 0 ? Math.floor(process / total * 100) : 100; + if (workingTask.includes(this.job().status)) { + progress = Math.min(progress, 99); } + this.processProgress.set(progress); this.processInfo.set(`${process}/${total} (${progress}%)`); } } diff --git a/ui-ngx/src/app/modules/home/components/calculated-fields/components/simple-configuration/simple-configuration.component.html b/ui-ngx/src/app/modules/home/components/calculated-fields/components/simple-configuration/simple-configuration.component.html index 194e2f5958..9240206b71 100644 --- a/ui-ngx/src/app/modules/home/components/calculated-fields/components/simple-configuration/simple-configuration.component.html +++ b/ui-ngx/src/app/modules/home/components/calculated-fields/components/simple-configuration/simple-configuration.component.html @@ -87,7 +87,7 @@
+ [class.!hidden]="simpleConfiguration.get('output').value?.type !== OutputType.Timeseries">
calculated-fields.use-latest-timestamp diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.html index 3d331ae634..4b4e81f569 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.html @@ -6,6 +6,8 @@ -->
+ +

{{'widget.add' | translate}}:

@@ -52,6 +54,7 @@ [previewHeight]="widgetConfig.typeParameters.previewHeight">
} } - @if (showConfigureWithAi) { - - - } @if (isEdit) {
@if (previewMode) { } - @if (aiEnabled && entitiesTableConfig.aiAssistantConfig) { - - } @for (buttonDescriptor of entitiesTableConfig.headerButtonDescriptors; track buttonDescriptor.name) { } diff --git a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts index 05f6608ae5..20f6d5fe8b 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts @@ -110,10 +110,8 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa isDetailsOpen = false; detailsPanelOpened = new EventEmitter(); - get isAiAssistantOpen() { return this.panelService.open(); } aiEnabled = getCurrentAuthState(this.store).aiEnabled; - configureWithAiButton: HeaderActionDescriptor; replaceComponent: Type; @@ -203,7 +201,11 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa } goBack(): void { - this.router.navigate(this.entitiesTableConfig.backNavigationCommands, { relativeTo: this.route }); + if (isDefinedAndNotNull(this.entitiesTableConfig.backNavigationUrl)) { + this.router.navigateByUrl(this.entitiesTableConfig.backNavigationUrl); + } else { + this.router.navigate(this.entitiesTableConfig.backNavigationCommands, { relativeTo: this.route }); + } } private init(entitiesTableConfig: EntityTableConfig>) { @@ -224,23 +226,24 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa if (aiConfig) { this.panelService.setEnabled(true); this.panelService.setConfig(aiConfig); - this.configureWithAiButton = { - name: this.translate.instant('ai-assistant.configure-with-ai'), - icon: 'mdi:creation', - isEnabled: () => this.aiEnabled && aiConfig.showButton !== false && !this.isAiAssistantOpen, - onAction: ($event) => this.toggleAiAssistant($event) - }; this.updateAiClientContext(); - this.aiUpdatedData$?.unsubscribe(); - if (entitiesTableConfig.entityType) { - this.aiUpdatedData$ = this.panelService.updatedData$.pipe( - filter(affectedEntities => - affectedEntities.some(entityId => entityId.entityType === entitiesTableConfig.entityType)), - takeUntil(this.destroy$) - ).subscribe(() => { - this.updateData(); - }); - } + } + this.aiUpdatedData$?.unsubscribe(); + if (entitiesTableConfig.entityType) { + this.aiUpdatedData$ = this.panelService.updatedData$.pipe( + filter(affectedEntities => + affectedEntities.some(entityId => entityId.entityType === (entitiesTableConfig.aiReloadEntityType ?? entitiesTableConfig.entityType))), + takeUntil(this.destroy$) + ).subscribe(() => { + if (this.isDetailsOpen && this.entityDetailsPanel?.isEdit) { + this.panelService.keepEdits('entity', () => { + this.entityDetailsPanel.isEdit = false; + this.updateData(false, true); + }); + } else { + this.updateData(false); + } + }); } this.pageMode = this.entitiesTableConfig.pageMode; @@ -563,6 +566,7 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa ? {type: viewConfig.entityView, entityId: entity.id as EntityId} : {type: viewConfig.listView, entityId: viewConfig.listEntityId}; this.panelService.setClientContextForView(view); + this.panelService.setViewName(viewConfig.entityView && entity ? this.entitiesTableConfig.entityTitle(entity) : null); } toggleAiAssistant($event: Event) { @@ -787,9 +791,8 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa res = column.cellTooltipFunction(entity, column.key); res = isDefined(res) ? res : null; this.cellTooltipCache[index] = res; - } else { - return res !== null ? res : undefined; } + return res !== null ? res : undefined; } else { return undefined; } diff --git a/ui-ngx/src/app/modules/home/components/entity/entity-chips.component.ts b/ui-ngx/src/app/modules/home/components/entity/entity-chips.component.ts index 34e87ce4bf..190c733c96 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entity-chips.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entity-chips.component.ts @@ -4,7 +4,7 @@ import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; import { BaseData, GroupEntityInfo } from '@shared/models/base-data'; import { EntityId } from '@shared/models/id/entity-id'; -import { baseDetailsPageByEntityType, EntityType, groupUrlPrefixByEntityType } from '@app/shared/public-api'; +import { baseDetailsPageByEntityType, EntityType, groupUrlPrefixByEntityType } from '@shared/models/entity-type.models'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { isEqual, isNotEmptyStr, isObject } from '@core/utils'; diff --git a/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts b/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts index 0bbdb4a1ef..538ec3dfc2 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { EntityId } from '@shared/models/id/entity-id'; import { ChangeDetectionStrategy, ChangeDetectorRef, @@ -71,6 +73,7 @@ export class EntityDetailsPageComponent extends EntityDetailsPanelComponent impl private broadcast: BroadcastService, private translate: TranslateService, private dialogService: DialogService, + private panelService: AiAssistantPanelService, protected store: Store) { super(store, injector, cd); if (isDefinedAndNotNull(this.route.snapshot.data.entityGroup) && isUndefinedOrNull(this.route.snapshot.data.entitiesTableConfig)) { @@ -94,6 +97,20 @@ export class EntityDetailsPageComponent extends EntityDetailsPanelComponent impl this.reload(); } })); + this.subscriptions.push(this.panelService.updatedData$.subscribe(affected => { + const id = this.currentEntityId?.id; + if (!id || !affected.some(entityId => entityId.id === id)) { + return; + } + if (this.isEdit) { + this.panelService.keepEdits('entity', () => { + this.onToggleDetailsEditMode(); + this.reload(); + }); + } else { + this.reload(); + } + })); this.subscriptions.push(this.route.paramMap.subscribe( paramMap => { if (this.entitiesTableConfig) { const entityType = this.entitiesTableConfig.entityType; @@ -123,6 +140,9 @@ export class EntityDetailsPageComponent extends EntityDetailsPanelComponent impl } ngOnDestroy() { + if (this.entitiesTableConfig?.aiAssistantConfig?.view?.entityView) { + this.panelService.teardown(); + } super.ngOnDestroy(); } @@ -173,6 +193,18 @@ export class EntityDetailsPageComponent extends EntityDetailsPanelComponent impl this.broadcast.broadcast('updateBreadcrumb'); this.isReadOnly = this.entitiesTableConfig.detailsReadonly(this.entity); this.headerTitle = this.entitiesTableConfig.entityTitle(this.entity); + this.updateAiAssistant(); + } + + private updateAiAssistant(): void { + const config = this.entitiesTableConfig?.aiAssistantConfig; + if (!config?.view?.entityView || !this.entity?.id) { + return; + } + this.panelService.setEnabled(true); + this.panelService.setConfig(config); + this.panelService.setClientContextForView({type: config.view.entityView, entityId: this.entity.id as EntityId}); + this.panelService.setViewName(this.headerTitle); } private deleteEntity($event: Event, entity: BaseData) { diff --git a/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts b/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts index 393a4b8503..e71bf6405d 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts @@ -1,5 +1,7 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { AfterViewInit, ChangeDetectionStrategy, @@ -7,6 +9,7 @@ import { Component, ComponentRef, EventEmitter, + inject, Injector, Input, OnDestroy, @@ -59,6 +62,8 @@ export class EntityDetailsPanelComponent extends PageComponent implements AfterV entitiesTableConfigValue: EntityTableConfig>; isEditValue = false; + + private aiPanelService = inject(AiAssistantPanelService); selectedTab = 0; entityTypes = EntityType; @@ -93,6 +98,8 @@ export class EntityDetailsPanelComponent extends PageComponent implements AfterV this.currentEntityId = entityId; if (this.currentEntityId) { this.reloadEntity(); + } else { + this.isEdit = false; } } } @@ -115,6 +122,9 @@ export class EntityDetailsPanelComponent extends PageComponent implements AfterV } set isEdit(val: boolean) { + if (this.isEditValue && !val) { + this.aiPanelService.clearKeptEdits('entity'); + } this.isEditValue = val; if (this.entityComponent) { this.entityComponent.isEdit = val; diff --git a/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.resolver.ts b/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.resolver.ts index 132cfff504..d534be7c9b 100644 --- a/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.resolver.ts @@ -1,6 +1,6 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; @@ -22,12 +22,27 @@ import { AppState } from '@core/core.state'; import { EntityType } from '@shared/models/entity-type.models'; import { Operation, Resource } from '@shared/models/security.models'; import { deviceAiAssistantConfig } from '@shared/models/device.models'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; import { AiAssistantViewType } from '@shared/models/ai-chat.models'; +import { CustomerId } from '@shared/models/id/customer-id'; import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { EdgeId } from '@shared/models/id/edge-id'; + +const GROUP_LIST_VIEWS = new Map([ + [EntityType.ASSET, [AiAssistantViewType.ASSET_GROUP_LIST, AiAssistantViewType.ASSET_GROUP]], + [EntityType.ENTITY_VIEW, [AiAssistantViewType.ENTITY_VIEW_GROUP_LIST, AiAssistantViewType.ENTITY_VIEW_GROUP]], + [EntityType.DASHBOARD, [AiAssistantViewType.DASHBOARD_GROUP_LIST, AiAssistantViewType.DASHBOARD_GROUP]], + [EntityType.CUSTOMER, [AiAssistantViewType.CUSTOMER_GROUP_LIST, AiAssistantViewType.CUSTOMER_GROUP]], + [EntityType.USER, [AiAssistantViewType.USER_GROUP_LIST, AiAssistantViewType.USER_GROUP]], + [EntityType.EDGE, [AiAssistantViewType.EDGE_GROUP_LIST, AiAssistantViewType.EDGE_GROUP]], + [EntityType.AGENT, [AiAssistantViewType.AGENT_GROUP_LIST, AiAssistantViewType.AGENT_GROUP]] +]); @Injectable() export class EntityGroupsTableConfigResolver { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private entityGroupService: EntityGroupService, private customerService: CustomerService, private edgeService: EdgeService, @@ -63,10 +78,15 @@ export class EntityGroupsTableConfigResolver { params ); + const owner = config.edgeId ? new EdgeId(config.edgeId) : config.customerId ? new CustomerId(config.customerId) : undefined; if (config.groupType === EntityType.DEVICE) { config.aiAssistantConfig = deviceAiAssistantConfig(this.store, this.userPermissionsService, this.translate, this.userPermissionsService.hasGenericPermission(Resource.DEVICE, Operation.WRITE), - AiAssistantViewType.DEVICE_GROUP, AiAssistantViewType.DEVICE_GROUP_LIST); + AiAssistantViewType.DEVICE_GROUP, AiAssistantViewType.DEVICE_GROUP_LIST, owner); + } + const groupViews = GROUP_LIST_VIEWS.get(config.groupType); + if (groupViews) { + config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(groupViews[0], groupViews[1], owner); } if (config.customerId && resolveCustomer) { @@ -94,6 +114,7 @@ export class EntityGroupsTableConfigResolver { return this.edgeService.getEdge(config.edgeId).pipe( map((info) => { config.tableTitle = info.name + ': ' + this.translate.instant(entityGroupsTitle(config.groupType)); + config.edgeOwnerId = info.ownerId; return config; }) ); diff --git a/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.ts b/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.ts index 5ce3fc9abd..53b369e99b 100644 --- a/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.ts +++ b/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.ts @@ -30,10 +30,12 @@ import { EntityId } from '@shared/models/id/entity-id'; import { CustomTranslatePipe } from '@shared/pipe/custom-translate.pipe'; import { AuthUser } from '@shared/models/user.model'; import { edgeCreationAllowed } from '@shared/models/edge.models'; +import { Authority } from '@shared/models/authority.enum'; export class EntityGroupsTableConfig extends EntityTableConfig { edgeId: string; + edgeOwnerId: EntityId; groupType: EntityType; shared: boolean; @@ -115,7 +117,7 @@ export class EntityGroupsTableConfig extends EntityTableConfig this.saveEntity = (entityGroup, originalEntityGroup) => { entityGroup.type = this.groupType; - if (this.customerId) { + if (this.customerId && !entityGroup.id) { entityGroup.ownerId = { entityType: EntityType.CUSTOMER, id: this.customerId @@ -288,7 +290,13 @@ export class EntityGroupsTableConfig extends EntityTableConfig $event.stopPropagation(); } let ownerId = this.userPermissionsService.getUserOwnerId(); - if (this.params.customerId) { + if (this.edgeOwnerId && this.authUser.authority === Authority.TENANT_ADMIN) { + // List groups of the edge owner and its parent owners, so the groups of the customer that owns the edge are + // available no matter which page the edge was opened from (Edge management or Customers). + // Tenant admin only: for a customer user the edge owner may be outside their owner chain (an edge shared + // from the tenant or a parent customer), and the hierarchy request is then denied + ownerId = this.edgeOwnerId; + } else if (this.params.customerId) { ownerId = { id: this.params.customerId, entityType: EntityType.CUSTOMER diff --git a/ui-ngx/src/app/modules/home/components/group/group-entity-tabs.component.html b/ui-ngx/src/app/modules/home/components/group/group-entity-tabs.component.html index ffefcaba2c..a4d30e7883 100644 --- a/ui-ngx/src/app/modules/home/components/group/group-entity-tabs.component.html +++ b/ui-ngx/src/app/modules/home/components/group/group-entity-tabs.component.html @@ -115,7 +115,8 @@ [active]="versionControlTab.isActive" [entityId]="entity.id" [entityName]="entity.name" [externalEntityId]="entity.externalId || entity.id"> } -@if (entity && entityType === entityTypes.USER && (resource.API_KEY | hasGenericPermission: operation.READ)) { +@if (entity && entityType === entityTypes.USER && (resource.API_KEY | hasGenericPermission: operation.READ) + && (authUser.authority !== authorities.CUSTOMER_USER || entity.id?.id === authUser.userId)) { diff --git a/ui-ngx/src/app/modules/home/components/home-components.module.ts b/ui-ngx/src/app/modules/home/components/home-components.module.ts index 2093a762d4..39a74353e4 100644 --- a/ui-ngx/src/app/modules/home/components/home-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/home-components.module.ts @@ -220,12 +220,11 @@ import { ConverterTestDialogComponent } from '@home/components/converter/convert import { UpdatedPayloadPanelComponent } from '@home/components/converter/updated-payload-panel.component'; import { IntegrationComponentModule } from '@home/components/integration/integration-component.module'; import { MODULES_MAP } from '@shared/models/constants'; -import { modulesMap } from '@modules/common/modules-map'; +import { lazyModulesMap } from '@modules/common/lazy-modules-map'; import { AlarmAssigneePanelComponent } from '@home/components/alarm/alarm-assignee-panel.component'; import { RouterTabsComponent } from '@home/components/router-tabs.component'; import { AllEntitiesTableConfigService } from '@home/components/entity/all-entities-table-config.service'; import { SendNotificationButtonComponent } from '@home/components/notification/send-notification-button.component'; -import { AiAssistantAlarmButtonComponent } from '@home/components/alarm/ai-assistant-alarm-button.component'; import { GroupEntityInfoComponent } from '@home/components/group/group-entity-info.component'; import { ManageOwnerAndGroupsDialogComponent } from '@home/components/group/manage-owner-and-groups-dialog.component'; import { OwnerAndGroupsComponent } from '@home/components/group/owner-and-groups.component'; @@ -272,12 +271,14 @@ import { import { ConverterLibraryModelAutocompleteComponent } from '@home/components/converter/converter-library-model-autocomplete.component'; -import { AiModule } from '@home/components/ai/ai.module'; +import { AiCoreModule } from '@home/components/ai/ai-core.module'; import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack.component'; +import { LicenseHandOffDialogComponent } from '@home/components/license/license-hand-off-dialog.component'; @NgModule({ declarations: [ + LicenseHandOffDialogComponent, RouterTabsComponent, EntitiesTableComponent, AddEntityDialogComponent, @@ -447,7 +448,6 @@ import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack ConverterTestDialogComponent, UpdatedPayloadPanelComponent, SendNotificationButtonComponent, - AiAssistantAlarmButtonComponent, EntityChipsComponent, DashboardViewComponent, ConverterLibraryComponent, @@ -487,9 +487,10 @@ import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack EntityDebugSettingsButtonComponent, NotificationBellModule, GithubBadgeModule, - AiModule, + AiCoreModule, ], exports: [ + LicenseHandOffDialogComponent, SharedHomeComponentsModule, RouterTabsComponent, EntitiesTableComponent, @@ -639,7 +640,6 @@ import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack RateLimitsTextComponent, IntegrationWizardDialogComponent, SendNotificationButtonComponent, - AiAssistantAlarmButtonComponent, EntityChipsComponent, DashboardViewComponent, CancelTaskDialogComponent, @@ -665,7 +665,7 @@ import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack {provide: COMPLEX_FILTER_PREDICATE_DIALOG_COMPONENT_TOKEN, useValue: ComplexFilterPredicateDialogComponent}, {provide: DASHBOARD_PAGE_COMPONENT_TOKEN, useValue: DashboardPageComponent}, {provide: HOME_COMPONENTS_MODULE_TOKEN, useValue: HomeComponentsModule }, - {provide: MODULES_MAP, useValue: modulesMap} + {provide: MODULES_MAP, useValue: lazyModulesMap} ] }) export class HomeComponentsModule { diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html index 1bcad7d9c1..bd66080687 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html @@ -12,15 +12,17 @@ label="{{ 'integration.connection-string' | translate }}" requiredText="{{ 'integration.connection-string-required' | translate }}"> - - integration.iot-hub-name - - @if (azureEventHubIntegrationConfigForm.get('iotHubName').hasError('required')) { - - integration.event-iot-hub-name-required - - } - + @if (isSetDownLink) { + + integration.iot-hub-name + + @if (azureEventHubIntegrationConfigForm.get('iotHubName').hasError('required')) { + + integration.event-iot-hub-name-required + + } + + } diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html index 6e3cde027c..d48883be07 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html @@ -29,6 +29,21 @@ }
+ @if (isSetDownLink) { + + + + integration.downlink-topic-name + + @if (azureServicesBusIntegrationConfigForm.get('downlinkTopicName').hasError('required')) { + integration.downlink-topic-name-required + } + + } @@ -40,22 +55,6 @@ - - - - - integration.downlink-topic-name - - @if (azureServicesBusIntegrationConfigForm.get('downlinkTopicName').hasError('required')) { - - integration.downlink-topic-name-required - - } - - diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/custom-integration-form/custom-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/custom-integration-form/custom-integration-form.component.html index d7490b4c1c..d50d19d152 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/custom-integration-form/custom-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/custom-integration-form/custom-integration-form.component.html @@ -21,6 +21,10 @@ validateContent validateOnChange> +
+ info_outline + +
diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/http-integration-form/http-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/http-integration-form/http-integration-form.component.html index c4e619d4c8..6fb90a6a99 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/http-integration-form/http-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/http-integration-form/http-integration-form.component.html @@ -50,7 +50,9 @@ noDataText="integration.no-headers-filter" keyPlaceholderText="integration.header" isStrokedButton="true" + showRequiredErrors appearance="outline" + secretValues formControlName="headersFilter"> diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/kafka-integration-form/kafka-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/kafka-integration-form/kafka-integration-form.component.html index 1912f968fd..4b09f41dab 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/kafka-integration-form/kafka-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/kafka-integration-form/kafka-integration-form.component.html @@ -73,7 +73,7 @@
integration.other-properties - +
diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/kpn-integration-form/kpn-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/kpn-integration-form/kpn-integration-form.component.html index ffe43c2556..50f4d721be 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/kpn-integration-form/kpn-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/kpn-integration-form/kpn-integration-form.component.html @@ -62,7 +62,9 @@ noDataText="integration.no-headers-filter" keyPlaceholderText="integration.header" isStrokedButton="true" + showRequiredErrors appearance="outline" + secretValues formControlName="additionalHeadersFilter"> @if (kpnIntegrationConfigForm.get('additionalHeadersFilter').hasError('securityHeaderDuplicate')) { diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/loriot-integration-form/loriot-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/loriot-integration-form/loriot-integration-form.component.html index 19e59a1698..1d30ca3ef9 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/loriot-integration-form/loriot-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/loriot-integration-form/loriot-integration-form.component.html @@ -122,7 +122,9 @@ noDataText="integration.no-headers-filter" keyPlaceholderText="integration.header" isStrokedButton="true" + showRequiredErrors appearance="outline" + secretValues formControlName="headersFilter">
diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/particle-integration-form/particle-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/particle-integration-form/particle-integration-form.component.html index 3aa913d9e5..caf8189be6 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/particle-integration-form/particle-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/particle-integration-form/particle-integration-form.component.html @@ -67,7 +67,9 @@ noDataText="integration.no-headers-filter" keyPlaceholderText="integration.header" isStrokedButton="true" + showRequiredErrors appearance="outline" + secretValues formControlName="headersFilter"> diff --git a/ui-ngx/src/app/modules/home/components/integration/mqtt-topic-filters/mqtt-topic-filters.component.html b/ui-ngx/src/app/modules/home/components/integration/mqtt-topic-filters/mqtt-topic-filters.component.html index 7dc4ab6015..2f5ddbe7a6 100644 --- a/ui-ngx/src/app/modules/home/components/integration/mqtt-topic-filters/mqtt-topic-filters.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/mqtt-topic-filters/mqtt-topic-filters.component.html @@ -10,17 +10,22 @@ @for (topicFilter of mqttFiltersFromArray.controls; track topicFilter; let i = $index) {
- + @if (i === 0) { {{"integration.topic" | translate }} } - + + @if (topicFilter.get('filter').hasError('required')) { + integration.topics-required + } @if (i === 0) { {{"integration.mqtt-qos" | translate }} } - + @for (mqttQoS of mqttQosTypes; track mqttQoS) { {{ mqttQoS }} - {{ getMqttQosTranslation(mqttQoS) | translate}} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 23578f5490..b171984760 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -62,93 +62,7 @@ } @case ('progress') { - @if (data.update) { - - } @else { -
- @for (ep of ws.entitySteps; track ep.step.name; let i = $index) { - @if (i > 0) { -
- } - @if (ep.status === 'conflict' || ep.status === 'error') { -
-
-
- warning -
-
- - {{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }} - - @if (ep.status === 'conflict') { - - {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} - - } - @if (ep.status === 'error' && ep.errorMessage) { - {{ ep.errorMessage }} - } -
-
-
- @if (ep.status === 'conflict') { - @if (ep.conflictType === 'use-or-overwrite') { - - - } @else { - - - } - } - @if (ep.status === 'error') { - - } -
-
- } @else { -
-
- @switch (ep.status) { - @case ('pending') { -
{{ i + 1 }}
- } - @case ('running') { - - } - @case ('success') { - check_circle - } - } -
- - {{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }} - - - @if (ep.status === 'success') { - {{ 'iot-hub.done' | translate }} - } - @if (ep.status === 'running') { - {{ 'iot-hub.in-progress' | translate }} - } - -
- } - } -
- } + } }
@@ -156,18 +70,17 @@ - @let hint = textWithLink('iot-hub.device-update-modified'); - {{ hint.before }}{{ hint.link }}{{ hint.after }} + {{ modifiedHintText.before }}{{ modifiedHintText.link }}{{ modifiedHintText.after }} - - + +
- @for (ep of ws.entitySteps; track ep.step.name; let i = $index) { + @for (ep of ws.entitySteps; track ep.step; let i = $index) { @if (i > 0) {
} - @let plan = updatePlanOf(ep); + @let plan = planOf(ep); @let label = ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name); @if (ws.reviewing && plan && !plan.confirmed) {
@@ -177,12 +90,9 @@
{{ label }} - @if (plan.newDefaultConverter) { - {{ 'iot-hub.device-update-new-default-converter' | translate }} - } @if (plan.existing) { - {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} + {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate), name: plan.existing.name } }} } @if (plan.shared) { @@ -198,19 +108,21 @@
@if (plan.existing) { @if (ep.step.type === 'DASHBOARD') { - } @else { - } - + @if (canOverwriteExisting(ep)) { + + } } @else { - } @@ -237,7 +149,7 @@ } @case ('success') { - check_circle + check_circle } @default {
{{ i + 1 }}
@@ -249,15 +161,13 @@ {{ label }} - @if (plan?.action === 'create' && plan.resolution !== 'use-existing') { + + @if (data.update && plan?.action === 'create' && plan.resolution !== 'use-existing') { {{ 'iot-hub.device-update-new' | translate }} }
@if (ws.reviewing && plan?.confirmed) { - @if (plan.newDefaultConverter) { - {{ 'iot-hub.device-update-new-default-converter' | translate }} - } @if (plan.shared) { {{ 'iot-hub.device-update-shared' | translate }} } @@ -274,10 +184,10 @@ {{ 'iot-hub.in-progress' | translate }} } @case ('success') { - {{ updateOutcomeOf(plan) | translate }} + {{ appliedOutcomeOf(plan) | translate }} } @case ('skipped') { - {{ 'iot-hub.device-update-skipped' | translate }} + {{ 'iot-hub.device-package-skipped' | translate }} } @default { @@ -335,7 +245,7 @@
- @for (ws of wizardSteps; track ws.label) { + @for (ws of wizardSteps; track ws) { @@ -359,8 +269,8 @@ done - @for (ws of wizardSteps; track ws.label) { - {{ ws.label }} @@ -378,24 +288,24 @@ } - @if (data.update && currentWizardStep?.type === 'progress') { + @if (currentWizardStep?.type === 'progress') { @let step = currentWizardStep; - @if (hasUpdateError(step)) { -
+ @if (hasPackageError(step)) { +
error {{ step.progressError }}
- } @else if (step.reviewing && !step.checking && unconfirmedUpdateWarnings(step) > 0) { -
+ } @else if (step.reviewing && !step.checking && unconfirmedWarnings(step) > 0) { +
warning - {{ 'iot-hub.device-update-confirm-warnings' | translate:{ count: unconfirmedUpdateWarnings(step) } }} + {{ 'iot-hub.device-package-confirm-warnings' | translate:{ count: unconfirmedWarnings(step), action: (applyActionKey | translate) } }}
} } @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { @@ -432,13 +342,13 @@ } @case ('progress') { - @if (data.update && (step.reviewing || step.updating || step.progressError)) { - @if (step.progressError && !step.updating) { - - + - } @else if (step.updating) { + } @else if (step.applying) { } - } @else if (step.progressError) { - - } @else if (step.progressDone && isLastWizardStep) { - } @else if (!step.progressError) { + } @else {
} @case (FormFieldType.SELECT) { - {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} @@ -110,7 +110,7 @@ } @case (FormFieldType.STRING_AUTOCOMPLETE) { - {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} } @case (FormFieldType.PASSWORD) { - {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} } @case (FormFieldType.INTEGER) { - {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} } @default { - {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} { - return from(this.converterUpdateDialogData(update)).pipe( - switchMap(data => this.dialog.open( - TbIotHubConverterUpdateDialogComponent, { - panelClass: ['tb-dialog'], - disableClose: true, - autoFocus: false, - data - }).afterClosed()), - catchError(() => of(false)) - ); - } - - private async converterUpdateDialogData(update: DefaultConverterUpdate): Promise { - const installedItemId = update.installedItem.id.id; - const converterId = update.converter.id.id; - // The converter as it is now, not the table's copy: the dialog downloads it, and the update overwrites only this version - const [states, packages, converter] = await Promise.all([ - firstValueFrom(this.iotHubApiService.checkDeviceUpdate(installedItemId)), - loadInstalledDevicePackages(this.iotHubApiService), - firstValueFrom(this.converterService.getConverter(converterId)) as Promise - ]); - const state = states.find(s => s.stepName === update.stateKey); - // As the server decides what is shared: the converter is one of the entities another package tracks - const usedBy = packages - .filter(item => item.id.id !== installedItemId && - (item.descriptor as DeviceInstalledItemDescriptor)?.createdEntityIds?.some(id => id.id === converterId)) - .map(item => item.itemName); - return { update: { ...update, converter }, version: converter.version ?? state?.version, modified: state?.modified === true, usedBy }; - } - deleteItem(installedItem: IotHubInstalledItem): Observable { if (!installedItem) { return of(false); } - // A device package keeps what other installed packages use: the dialog opens with that already known + // A device package keeps some entities: the dialog opens with them already known const keptEntities$: Observable = installedItem.itemType === 'DEVICE' ? this.iotHubApiService.getInstalledItemKeptEntities(installedItem.id.id, {ignoreErrors: true}).pipe(catchError(() => of(null))) : of(null); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts index 99a2676c90..56c4720fa7 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts @@ -11,7 +11,6 @@ import { TbIotHubAddItemDialogComponent } from './iot-hub-add-item-dialog.compon import { TbIotHubInstallDialogComponent } from './iot-hub-install-dialog.component'; import { TbIotHubUpdateDialogComponent } from './iot-hub-update-dialog.component'; import { TbIotHubDeleteDialogComponent } from './iot-hub-delete-dialog.component'; -import { TbIotHubConverterUpdateDialogComponent } from './iot-hub-converter-update-dialog.component'; import { TbIotHubUnpublishedWarningDialogComponent } from './iot-hub-unpublished-warning-dialog.component'; import { TbDeviceInstallDialogComponent } from './device-install-dialog/device-install-dialog.component'; import { InstallFormRendererComponent } from './device-install-dialog/install-form-renderer/install-form-renderer.component'; @@ -23,12 +22,10 @@ import { TbIotHubSelectCfEntityDialogComponent } from './iot-hub-select-cf-entit import { TbIotHubUpgradeRequiredDialogComponent } from './iot-hub-upgrade-required-dialog.component'; import { TbIotHubMarkdownComponent } from './iot-hub-markdown.component'; import { SolutionInstallDialogComponent } from './solution-install-dialog.component'; -import { IotHubActionsService } from './iot-hub-actions.service'; import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link.module'; @NgModule({ declarations: [ - TbIotHubConverterUpdateDialogComponent, TbIotHubItemDetailDialogComponent, TbIotHubBrowseComponent, TbIotHubItemCardComponent, @@ -53,9 +50,6 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link SharedModule, IotHubItemLinkModule ], - providers: [ - IotHubActionsService - ], exports: [ TbIotHubItemDetailDialogComponent, TbIotHubBrowseComponent, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html deleted file mode 100644 index 0a153045f3..0000000000 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html +++ /dev/null @@ -1,55 +0,0 @@ - -
-

{{ 'iot-hub.converter-update-title' | translate }}

-

{{ 'iot-hub.device-update-new-default-converter' | translate }}

-
-
{{ data.update.converter.name }}
- @if (data.usedBy.length) { - {{ 'iot-hub.device-update-shared' | translate }} -
-
    - @for (name of usedByShown; track $index) { -
  • {{ name }}
  • - } -
- @if (usedByHidden.length) { -
-
    - @for (name of usedByHidden; track $index) { -
  • {{ name }}
  • - } -
-
- } -
- @if (usedByHidden.length) { - - } - } - @if (data.modified) { - - {{ modifiedHint.before }}{{ modifiedHint.link }}{{ modifiedHint.after }} - - } -
- @if (errorMessage) { - {{ errorMessage }} - } -
-
- - -
diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss deleted file mode 100644 index 926023ed3b..0000000000 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss +++ /dev/null @@ -1,97 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -:host { - display: block; - max-width: 600px; -} - -.tb-converter-update-title { - font-size: 20px; - font-weight: 600; - line-height: 24px; - letter-spacing: 0.1px; - color: rgba(0, 0, 0, 0.87); - margin: 0; -} - -.tb-converter-update-text { - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.54); - margin: 0; -} - -.tb-converter-update-box { - padding: 12px 16px; - border: 1px solid rgba(0, 0, 0, 0.12); - border-radius: 8px; -} - -.tb-converter-update-name { - font-size: 14px; - font-weight: 500; - line-height: 20px; - color: rgba(0, 0, 0, 0.87); -} - -.tb-converter-update-packages { - margin: 0; - padding-left: 20px; - font-size: 12px; - line-height: 16px; - color: rgba(0, 0, 0, 0.54); -} - -// Material expansion-panel timing -.tb-converter-update-more { - display: grid; - grid-template-rows: 0fr; - transition: grid-template-rows 225ms cubic-bezier(0.4, 0, 0.2, 1); - > ul { - overflow: hidden; - min-height: 0; - } - &.expanded { - grid-template-rows: 1fr; - } - @media (prefers-reduced-motion: reduce) { - transition: none; - } -} - -.tb-converter-update-toggle { - padding: 0; - border: none; - background: none; - font-size: 12px; - font-weight: 500; - line-height: 16px; - color: var(--tb-primary-500); - cursor: pointer; - &:hover, - &:focus-visible { - text-decoration: underline; - } -} - -.tb-converter-update-link { - color: #305680; - text-decoration: underline; - cursor: pointer; -} - -.tb-progress-alert-msg { - font-size: 12px; - font-weight: 400; - line-height: 16px; - letter-spacing: 0.4px; - - &.tb-progress-alert-msg-warning { - color: #f66716; - } - - &.tb-progress-alert-msg-error { - color: #dd2c00; - } -} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts deleted file mode 100644 index b33d11b2b6..0000000000 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts +++ /dev/null @@ -1,88 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Inject } from '@angular/core'; -import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; -import { Router } from '@angular/router'; -import { Store } from '@ngrx/store'; -import { TranslateService } from '@ngx-translate/core'; -import { AppState } from '@core/core.state'; -import { DialogComponent } from '@shared/components/dialog.component'; -import { IotHubApiService } from '@core/http/iot-hub-api.service'; -import { DefaultConverterUpdate, defaultConverterUpdateRequest } from '@home/components/iot-hub/iot-hub-default-converter'; -import { downloadEntityJson, readableMessage, requestFailureMessage, splitTextWithLink } from '@home/components/iot-hub/iot-hub-utils'; - -export interface IotHubConverterUpdateDialogData { - update: DefaultConverterUpdate; - // The version of the converter the dialog downloads: the server refuses the update if someone saved the converter since - version?: number; - // Someone changed the converter since a package installed or last updated it - modified: boolean; - // The names of the other installed packages that use the converter - usedBy: string[]; -} - -const USED_BY_SHOWN = 3; - -/** - * Brings an installed device package's default converter to ThingsBoard's default converter now, without a new version of - * the package. Closes with true once it is updated. - */ -@Component({ - selector: 'tb-iot-hub-converter-update-dialog', - standalone: false, - templateUrl: './iot-hub-converter-update-dialog.component.html', - styleUrls: ['./iot-hub-converter-update-dialog.component.scss'] -}) -export class TbIotHubConverterUpdateDialogComponent extends DialogComponent { - - readonly modifiedHint = splitTextWithLink(this.translate.instant('iot-hub.device-update-modified')); - readonly usedByShown: string[]; - readonly usedByHidden: string[]; - usedByExpanded = false; - updating = false; - errorMessage: string | null = null; - - constructor( - protected store: Store, - protected router: Router, - protected dialogRef: MatDialogRef, - @Inject(MAT_DIALOG_DATA) public data: IotHubConverterUpdateDialogData, - private iotHubApiService: IotHubApiService, - private translate: TranslateService - ) { - super(store, router, dialogRef); - // Collapse only when at least 2 packages would be hidden - const shownCount = data.usedBy.length > USED_BY_SHOWN + 1 ? USED_BY_SHOWN : data.usedBy.length; - this.usedByShown = data.usedBy.slice(0, shownCount); - this.usedByHidden = data.usedBy.slice(shownCount); - } - - downloadCurrent(): void { - downloadEntityJson(this.data.update.converter, this.data.update.converter.name); - } - - update(): void { - this.updating = true; - this.errorMessage = null; - this.iotHubApiService.updateDevicePackage(this.data.update.installedItem.id.id, - defaultConverterUpdateRequest(this.data.update, this.data.version), { ignoreErrors: true }).subscribe({ - next: result => { - if (result.success) { - this.dialogRef.close(true); - return; - } - // Nothing was changed: the server rolled it back - this.updating = false; - this.errorMessage = readableMessage(result.errorMessage) ?? this.translate.instant('iot-hub.device-install-unexpected-error'); - }, - error: error => { - this.updating = false; - this.errorMessage = requestFailureMessage(error, this.translate); - } - }); - } - - cancel(): void { - this.dialogRef.close(false); - } -} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts index 5db81a5b50..ee48ad50a7 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts @@ -5,27 +5,9 @@ import { ResourcesService } from '@core/services/resources.service'; import { Converter, ConverterConfigV2, ConverterType, getTargetField, getTargetTemplateUrl } from '@shared/models/converter.models'; import { IntegrationType } from '@shared/models/integration.models'; import { ScriptLanguage } from '@shared/models/rule-node.models'; -import { isEqual } from '@core/utils'; -import { DeviceInstalledItemDescriptor, DeviceUpdateRequest, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; -import { IotHubApiService } from '@core/http/iot-hub-api.service'; -import { PageLink } from '@shared/models/page/page-link'; -import { PageData } from '@shared/models/page/page-data'; - -/** An installed device package's default converter that differs from ThingsBoard's default converter now. */ -export interface DefaultConverterUpdate { - installedItem: IotHubInstalledItem; - // The key of the converter's step in the package's install state - stateKey: string; - converter: Converter; - defaultConverter: Partial; -} const DEFAULT_CONVERTERS_V2_CONFIGURATION_URL = '/assets/converters/default-converters-v2-configuration.json'; -// The settings of a default converter that decide what it does: the script is compared on its own -const V2_CONFIGURATION_KEYS: (keyof ConverterConfigV2)[] = - ['type', 'name', 'profile', 'label', 'customer', 'group', 'attributes', 'telemetry', 'updateOnlyKeys']; - /** * The uplink converter ThingsBoard creates for a new integration of this type, as a device package step with * "default": true installs it. Null when ThingsBoard has no default converter settings for the type. @@ -60,70 +42,3 @@ export const loadDefaultUplinkConverter = async (resourcesService: ResourcesServ additionalInfo: { description: '' } }; }; - -/** True when the converter does something else than the default one: another script or other settings. */ -export const differsFromDefaultConverter = (converter: Converter, defaultConverter: Partial): boolean => { - const field = getTargetField(ConverterType.UPLINK, converter.configuration.scriptLang); - const script = (value: string) => (value ?? '').trimEnd(); - return script(converter.configuration[field]) !== script(defaultConverter.configuration[field]) || - V2_CONFIGURATION_KEYS.some(key => !isEqual(converter.configuration[key] ?? null, defaultConverter.configuration[key] ?? null)); -}; - -/** All installed device packages of the tenant. */ -export const loadInstalledDevicePackages = async (iotHubApiService: IotHubApiService): Promise => { - const items: IotHubInstalledItem[] = []; - let pageLink = new PageLink(100); - let page: PageData; - do { - page = await firstValueFrom(iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true })); - items.push(...page.data); - pageLink = pageLink.nextPageLink(); - } while (page.hasNext); - return items; -}; - -/** - * The converters device packages installed themselves as their default converter, not ones they took as they were, of - * all installed device packages: only such a converter is ThingsBoard's default one, which a new ThingsBoard version - * may change. The installed items table and the update dialog both decide by it. - */ -export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiService): Promise> => { - const ids = new Set(); - for (const item of await loadInstalledDevicePackages(iotHubApiService)) { - for (const state of Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {})) { - if (state?.defaultConverter && state.entityOutput?.id && state.resolution !== 'use-existing') { - ids.add(state.entityOutput.id); - } - } - } - return ids; -}; - -/** - * The update of the installed version itself that brings its default converter to ThingsBoard's default one. It sends only - * the converter step: the server keeps the other steps, the forms and the integration's metadata as they are. - * expectedVersion is the converter's version the user reviewed. - */ -export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, expectedVersion?: number): DeviceUpdateRequest => { - const descriptor = update.installedItem.descriptor as DeviceInstalledItemDescriptor; - return { - versionId: update.installedItem.itemVersionId, - fromVersionId: update.installedItem.itemVersionId, - selectedInstallMethod: descriptor.selectedInstallMethod, - installState: {}, - steps: [{ - name: update.converter.name, - // The server keys the step's state by its id: the state stays under the key it has - id: update.stateKey, - type: 'UPLINK_CONVERTER', - action: 'OVERWRITE', - entityId: update.converter.id.id, - expectedVersion, - // The user confirmed it in the dialog, which names the other packages it affects - confirmed: true, - resolution: descriptor.installState?.[update.stateKey]?.resolution ?? 'created', - defaultConverter: true, - entity: update.defaultConverter - }] - }; -}; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html index f7bcce1201..30626b90f6 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html @@ -5,21 +5,30 @@ SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 --> -
-

{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}

-

{{ description }}

- @if (keptReferences) { -
- info_outline -
-
{{ keptTitle }}
-
{{ keptReason }}
- +

{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}

+ +
+

{{ description }}

+ @if (keptGroups.length) { +
+ info_outline +
+
{{ keptTitle }}
+
+ @for (group of keptGroups; track group.reason) { +
+
{{ group.reason }}
+ +
+ } +
+
-
- } -
-
+ } +
+ + -
+ diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss index 63fa684164..41e586417b 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +@import "../../../../../scss/constants"; + :host { display: block; max-width: 600px; @@ -13,6 +15,12 @@ letter-spacing: 0.1px; color: rgba(0, 0, 0, 0.87); margin: 0; + padding: 24px 24px 20px; + + // No baseline strut: the title keeps its own line height + &::before { + display: none; + } } .tb-iot-hub-delete-desc { @@ -23,3 +31,28 @@ color: rgba(0, 0, 0, 0.54); margin: 0; } + +.tb-iot-hub-kept-groups { + border: 1px solid color-mix(in srgb, var(--tb-primary-500) 40%, transparent); + + // Groups share the outer border; hide tb-image-references' own + ::ng-deep tb-image-references table.tb-entities-list-table { + padding: 0 10px 0 4px; + background: transparent; + + &:before { + display: none; + } + + // Narrow dialog: let type and name wrap + td.tb-entity-type { + @media #{$mat-xs} { + white-space: normal !important; + } + } + + td.tb-entity-name { + overflow-wrap: anywhere; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index 88bdf96fff..32cd6324c6 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts @@ -7,7 +7,7 @@ import { Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { DialogComponent } from '@shared/components/dialog.component'; -import { IotHubInstalledItemKeptEntities } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models'; +import { IotHubInstalledItemKeptEntities, IotHubKeptEntity } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; import { ResourceReferences } from '@shared/models/resource.models'; @@ -30,10 +30,8 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent, @@ -46,13 +44,21 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent ({ id: entity.entityId as EntityId, name: entity.name })); + const shared = kept?.entities ?? []; + const referenced = kept?.referencedEntities ?? []; + const references = (entities: IotHubKeptEntity[]): ResourceReferences => + entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name })); + if (shared.length) { // Kept because other packages use them, because the user had them before the package, or both const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' : !kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used'; - this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: kept.entities.length }); - this.keptReason = this.translate.instant(reasonKey, { kept: kept.entities.length }); + this.keptGroups.push({ reason: this.translate.instant(reasonKey, { kept: shared.length }), references: references(shared) }); + } + if (referenced.length) { + this.keptGroups.push({ reason: this.translate.instant('iot-hub.remove-kept-referenced'), references: references(referenced) }); + } + if (this.keptGroups.length) { + this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: shared.length + referenced.length }); } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 7f1dbac04e..bd6c163906 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -7,7 +7,7 @@ -->
- +
@@ -56,12 +56,6 @@ } - } @else if (hasConverterUpdate(item)) { - - } @else { check @@ -128,12 +122,16 @@ @if (!isLoading && dataSource.length === 0) {
-

{{ 'iot-hub.no-installed-items' | translate }}

-

{{ 'iot-hub.no-installed-items-text' | translate }}

- @if (hasActiveFilters()) { - + @if (loadFailed) { +

{{ 'iot-hub.unable-to-load' | translate }}

+

{{ 'iot-hub.unable-to-load-text' | translate }}

+ + } @else { +

{{ (onlyUpdates ? 'iot-hub.no-items-with-updates' : 'iot-hub.no-installed-items') | translate }}

+

{{ 'iot-hub.no-installed-items-text' | translate }}

+ @if (hasActiveFilters()) { + + } }
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 3c196cdb66..8ce7d9ba0a 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -36,15 +36,7 @@ import { entityTypeTranslations } from '@shared/models/entity-type.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; -import { ConverterService } from '@core/http/converter.service'; -import { ResourcesService } from '@core/services/resources.service'; -import { - DefaultConverterUpdate, - differsFromDefaultConverter, - loadDefaultUplinkConverter, - loadOwnDefaultConverterIds -} from '@home/components/iot-hub/iot-hub-default-converter'; -import { firstValueFrom } from 'rxjs'; +import { forkJoin } from 'rxjs'; @Component({ selector: 'tb-iot-hub-installed-items-table', @@ -77,11 +69,16 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, isLoading = false; publishedVersionMap = new Map(); - // Installed device packages whose default converter differs from ThingsBoard's default converter now - converterUpdates = new Map(); - private converterCheckRun = 0; updatesChecked = false; isCheckingUpdates = false; + updatesCheckFailed = false; + onlyUpdates = false; + // Totals, ignoring type filters and search + updatesCount: number | null = null; + installedCount = 0; + loadFailed = false; + private loadRun = 0; + private countRun = 0; private widgetResize$: ResizeObserver; @@ -95,9 +92,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private iotHubActions: IotHubActionsService, private elementRef: ElementRef, private zone: NgZone, - private cd: ChangeDetectorRef, - private converterService: ConverterService, - private resourcesService: ResourcesService + private cd: ChangeDetectorRef ) { this.widgetResize$ = new ResizeObserver(() => { this.zone.run(() => { @@ -127,10 +122,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, ngOnChanges(changes: SimpleChanges): void { if (changes.textSearch || changes.typeFilters) { if (!changes.textSearch?.firstChange || !changes.typeFilters?.firstChange) { - this.pageIndex = 0; - if (this.paginator) { - this.paginator.pageIndex = 0; - } + this.setPageIndex(0); this.loadData(); } } @@ -138,8 +130,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, ngAfterViewInit(): void { this.sort.sortChange.subscribe(() => { - this.pageIndex = 0; - this.paginator.pageIndex = 0; + this.setPageIndex(0); this.loadData(); }); } @@ -161,7 +152,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, deleteItem(item: IotHubInstalledItem): void { this.iotHubActions.deleteItem(item).subscribe(deleted => { if (deleted) { - this.loadData(); + this.reloadAfterChange(); } }); } @@ -191,7 +182,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.iotHubApiService.getVersionInfo(item.itemVersionId, {ignoreLoading: true}).subscribe(versionView => { this.iotHubActions.openItemDetail(versionView, item).subscribe(result => { if (result === 'updated' || result === 'deleted') { - this.loadData(); + this.reloadAfterChange(); } }); }); @@ -241,93 +232,122 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, checkForUpdates(): void { this.isCheckingUpdates = true; + if (this.updatesChecked) { + // Only the count failed: recount, keeping the list as it is + this.loadUpdatesCount(); + return; + } + this.updatesCheckFailed = false; this.iotHubApiService.getInstalledItemIds({ ignoreLoading: true }).pipe( - switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true })) + // Failure is shown next to the button, not as an error toast + switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true, ignoreErrors: true })) ).subscribe({ next: (infos) => { this.publishedVersionMap.clear(); infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); - this.updatesChecked = true; - this.isCheckingUpdates = false; - void this.checkConverterUpdates(); + this.loadUpdatesCount(() => { + this.updatesChecked = true; + // No updates: stay on the full list + this.showOnlyUpdates(this.updatesCount > 0); + }); }, error: () => { this.isCheckingUpdates = false; + this.updatesCheckFailed = true; } }); } - updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void { - this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => { - if (result === 'updated') { - this.loadData(); + showOnlyUpdates(onlyUpdates: boolean): void { + this.onlyUpdates = onlyUpdates; + this.setPageIndex(0); + this.loadData(); + } + + private setPageIndex(pageIndex: number): void { + this.pageIndex = pageIndex; + if (this.paginator) { + this.paginator.pageIndex = pageIndex; + } + } + + private publishedVersionIds(): Record { + const ids: Record = {}; + this.publishedVersionMap.forEach((info, itemId) => { + if (info.publishedVersionId) { + ids[itemId] = info.publishedVersionId; } }); + return ids; } - hasConverterUpdate(item: IotHubInstalledItem): boolean { - return this.converterUpdates.has(item.id.id); + retryLoad(): void { + this.loadData(); + if (this.updatesChecked && !this.itemVersion && this.updatesCount === null) { + this.loadUpdatesCount(); + } } - /** Brings the package's default converter to ThingsBoard's default one. Other packages on the converter take it too. */ - updateConverter(item: IotHubInstalledItem): void { - const update = this.converterUpdates.get(item.id.id); - if (!update) { + private reloadAfterChange(): void { + if (!this.updatesChecked || this.itemVersion) { + this.loadData(); return; } - this.iotHubActions.updateDefaultConverter(update).subscribe(updated => { - if (updated) { + this.loadUpdatesCount(() => { + if (this.onlyUpdates && this.updatesCount === 0) { + this.showOnlyUpdates(false); + } else { + this.loadData(); + } + }, () => { + // Count failed: fall back to the full list + if (this.onlyUpdates) { + this.showOnlyUpdates(false); + } else { this.loadData(); } }); } - /** - * The device packages on this page whose step with "default": true installed a converter that differs from - * ThingsBoard's default converter now. ThingsBoard's default changes with ThingsBoard, so the package has no new version for it. - */ - private async checkConverterUpdates(): Promise { - // A later load (another page, sort or search) starts another run: an earlier one finishing last mustn't win - const run = ++this.converterCheckRun; - // The package's default converter of each DEVICE package on the page - const checks: { item: IotHubInstalledItem; stateKey: string; converterId: string }[] = []; - // Over all installed packages, not only this page's, as the update dialog decides - let ownDefaultConverterIds: Set | undefined; - for (const item of this.dataSource) { - const states = item.itemType === 'DEVICE' ? Object.entries((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : []; - for (const [stateKey, state] of states) { - const id: string = state?.defaultConverter ? state.entityOutput?.id : undefined; - if (!id) { - continue; + // Latest call wins; previous counts stay until it returns + private loadUpdatesCount(onCounts?: () => void, onError?: () => void): void { + const run = ++this.countRun; + const config = { ignoreLoading: true, ignoreErrors: true }; + forkJoin({ + withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), config), + installed: this.iotHubApiService.getInstalledItemsCount(undefined, config) + }).subscribe({ + next: ({ withUpdates, installed }) => { + if (run !== this.countRun) { + return; } - // A converter taken as it was counts only when a package installed it as its default converter - if (state.resolution === 'use-existing') { - ownDefaultConverterIds ??= await loadOwnDefaultConverterIds(this.iotHubApiService); - if (!ownDefaultConverterIds.has(id)) { - continue; - } + this.updatesCount = withUpdates.totalElements; + this.installedCount = installed; + this.updatesCheckFailed = false; + this.isCheckingUpdates = false; + this.cd.markForCheck(); + onCounts?.(); + }, + error: () => { + if (run !== this.countRun) { + return; } - checks.push({ item, stateKey, converterId: id }); - } - } - const changed = await Promise.all(checks.map(async ({ item, stateKey, converterId }): Promise => { - const converter = await firstValueFrom(this.converterService.getConverter(converterId, {ignoreErrors: true, ignoreLoading: true})) - .catch(() => null); - if (!converter) { - return null; + this.updatesCount = null; + this.updatesCheckFailed = true; + this.isCheckingUpdates = false; + this.cd.markForCheck(); + onError?.(); } - const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, - converter.configuration.scriptLang, converter.name); - return defaultConverter && differsFromDefaultConverter(converter, defaultConverter) ? - { installedItem: item, stateKey, converter, defaultConverter } : null; - })); - if (run !== this.converterCheckRun) { - return; - } - this.converterUpdates = new Map(changed.filter(update => !!update).map(update => [update.installedItem.id.id, update])); - this.cd.markForCheck(); + }); } + updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void { + this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => { + if (result === 'updated') { + this.reloadAfterChange(); + } + }); + } getPublishedVersionInfo(item: IotHubInstalledItem): ItemPublishedVersionInfo | undefined { return this.publishedVersionMap.get(item.itemId); @@ -341,18 +361,34 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}).subscribe({ + // The empty state shows a failure of the only-updates list; one item's versions page lists them all + const items$ = this.onlyUpdates && !this.itemVersion + ? this.iotHubApiService.getInstalledItemsWithUpdates(pageLink, typeFilters, this.publishedVersionIds(), {ignoreLoading: true, ignoreErrors: true}) + : this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}); + const run = ++this.loadRun; + items$.subscribe({ next: (data) => { + if (run !== this.loadRun) { + return; + } + // The last page emptied after an update or a removal + if (!data.data.length && this.pageIndex > 0 && data.totalElements > 0) { + this.setPageIndex(Math.ceil(data.totalElements / this.pageSize) - 1); + this.loadData(); + return; + } this.dataSource = data.data; this.totalElements = data.totalElements; + this.loadFailed = false; this.isLoading = false; - if (this.updatesChecked && !this.itemVersion) { - void this.checkConverterUpdates(); - } }, error: () => { + if (run !== this.loadRun) { + return; + } this.dataSource = []; this.totalElements = 0; + this.loadFailed = true; this.isLoading = false; } }); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html index d544727d91..b44ae91453 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html @@ -1,7 +1,8 @@
@@ -98,13 +99,11 @@
{{ 'iot-hub.item-name' | translate }}
- - - {{ 'widgets.cluster-info.service-id' | translate }} - - - {{ serviceData.serviceId }} - - - - - {{ 'widgets.cluster-info.service-type' | translate }} - - - {{ serviceData.serviceType }} - - - - - {{ 'widgets.system-info.cpu' | translate }} - - - {{ serviceData.cpuUsage }}% - - - - - {{ 'widgets.system-info.ram' | translate }} - - - {{ serviceData.memoryUsage }}% - - - - - {{ 'widgets.system-info.disk' | translate }} - - - {{ serviceData.discUsage }}% - - - - -
-widgets.cluster-info.no-data diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.scss deleted file mode 100644 index c0ec6dcd57..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.scss +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -:host { - span.no-data-found { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - } - - .tb-resource-usage { - cursor: default; - &.tb-status-warn, &.tb-status-critical { - position: relative; - overflow: visible; - &:before { - position: absolute; - top: 15px; - left: -24px; - font-family: 'Material Icons Round'; - font-size: 20px; - line-height: 1; - } - } - &.tb-status-warn { - color: var(--tb-warning); - &:before { - content: "warning"; - color: var(--tb-warning); - } - } - &.tb-status-critical { - color: var(--tb-crit); - &:before { - content: "warning"; - color: var(--tb-crit); - } - } - } -} - -:host ::ng-deep { - .mdc-data-table__header-cell { - font-weight: 500; - font-size: 11px; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - } - .mdc-data-table__cell { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.ts deleted file mode 100644 index 6ec9483f6e..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.ts +++ /dev/null @@ -1,224 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 -import { AfterViewInit, Component, NgZone, OnInit, ViewChild } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { CollectionViewer, DataSource } from '@angular/cdk/collections'; -import { BehaviorSubject, Observable, of } from 'rxjs'; -import { emptyPageData, PageData } from '@shared/models/page/page-data'; -import { MAX_SAFE_PAGE_SIZE, PageLink } from '@shared/models/page/page-link'; -import { catchError, map, publishReplay, refCount, share } from 'rxjs/operators'; -import { MatSort } from '@angular/material/sort'; -import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; -import { EntityDataUpdate, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; -import { AliasFilterType } from '@shared/models/alias.models'; -import { EntityKeyType } from '@shared/models/query/query.models'; -import { TranslateService } from '@ngx-translate/core'; - -export interface SystemInfoData { - serviceId: string; - serviceType: string; - cpuUsage: number; - cpuCount: number; - memoryUsage: number; - totalMemory: number; - discUsage: number; - totalDiscSpace: number; -} - -@Component({ - selector: 'tb-cluster-info-table', - templateUrl: './cluster-info-table.component.html', - styleUrls: ['./cluster-info-table.component.scss'], - standalone: false -}) -export class ClusterInfoTableComponent extends PageComponent implements OnInit, AfterViewInit { - - @ViewChild(MatSort) sort: MatSort; - - displayedColumns = ['serviceId', 'serviceType', 'cpuUsage', 'memoryUsage', 'discUsage']; - - dataSource: SystemInfoDataSource; - - pageLink: PageLink; - - constructor(protected store: Store, - private telemetryWsService: TelemetryWebsocketService, - private translate: TranslateService, - private zone: NgZone) { - super(store); - } - - ngOnInit() { - this.dataSource = new SystemInfoDataSource(this.telemetryWsService, this.zone); - const sortOrder: SortOrder = { - property: 'serviceId', - direction: Direction.ASC - }; - this.pageLink = new PageLink(MAX_SAFE_PAGE_SIZE, 0, null, sortOrder); - this.dataSource.loadData(this.pageLink); - } - - ngAfterViewInit() { - this.sort.sortChange.subscribe(() => this.updateData()); - } - - updateData() { - this.pageLink.sortOrder.property = this.sort.active; - this.pageLink.sortOrder.direction = Direction[this.sort.direction.toUpperCase()]; - this.dataSource.loadData(this.pageLink); - } - - statusClass(value: number): string { - let status = ''; - if (value > 85) { - status = 'tb-status-critical'; - } else if (value > 75) { - status = 'tb-status-warn'; - } - return status; - } - - infoTooltip(serviceData: SystemInfoData, type: 'cpu' | 'ram' | 'disc'): string { - let tooltip = ''; - let value: number; - switch (type) { - case 'cpu': - value = serviceData.cpuUsage; - tooltip += value + ' / 100 %'; - break; - case 'ram': - value = serviceData.memoryUsage; - const memoryUsage = serviceData.memoryUsage; - const totalMemory = serviceData.totalMemory / 1073741824; - const usedMemory = (totalMemory * (memoryUsage / 100)).toFixed(0); - tooltip += usedMemory + ' / ' + totalMemory.toFixed(0) + ' Gb'; - break; - case 'disc': - value = serviceData.discUsage; - const discUsage = serviceData.discUsage; - const totalDiscSpace = serviceData.totalDiscSpace / 1073741824; - const usedDisc = (totalDiscSpace * (discUsage / 100)).toFixed(0); - tooltip += usedDisc + ' / ' + totalDiscSpace.toFixed(0) + ' Gb'; - break; - } - if (value > 85) { - switch (type) { - case 'cpu': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.cpu-critical-text'); - break; - case 'ram': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.ram-critical-text'); - break; - case 'disc': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.disk-critical-text'); - break; - } - } else if (value > 75) { - switch (type) { - case 'cpu': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.cpu-warning-text'); - break; - case 'ram': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.ram-warning-text'); - break; - case 'disc': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.disk-warning-text'); - break; - } - } - return tooltip; - } -} - -export class SystemInfoDataSource implements DataSource { - - private systemDataSubject = new BehaviorSubject([]); - private pageDataSubject = new BehaviorSubject>(emptyPageData()); - - public pageData$ = this.pageDataSubject.asObservable(); - - private allSystemData: Observable>; - - private telemetrySubscriber: TelemetrySubscriber; - - constructor(private telemetryWsService: TelemetryWebsocketService, - private zone: NgZone) { - } - - connect(collectionViewer: CollectionViewer): Observable> { - return this.systemDataSubject.asObservable(); - } - - disconnect(collectionViewer: CollectionViewer): void { - this.systemDataSubject.complete(); - this.pageDataSubject.complete(); - if (this.telemetrySubscriber) { - this.telemetrySubscriber.unsubscribe(); - this.telemetrySubscriber = null; - } - } - - loadData(pageLink: PageLink): void { - this.getAllSystemData().pipe( - map((data) => pageLink.filterData(data)), - catchError(() => of(emptyPageData())), - ).subscribe( - (pageData) => { - this.onSystemData(pageData.data); - this.pageDataSubject.next(pageData); - } - ); - } - - getAllSystemData(): Observable> { - if (!this.allSystemData) { - this.telemetrySubscriber = TelemetrySubscriber.createEntityFilterLatestSubscription( - this.telemetryWsService, { type: AliasFilterType.apiUsageState }, this.zone, - [ { key: 'clusterSystemData', type: EntityKeyType.TIME_SERIES } ]); - this.telemetrySubscriber.subscribe(); - this.allSystemData = this.telemetrySubscriber.entityData$.pipe( - map((update) => this.toSystemInfoData(update)), - publishReplay(1), - refCount() - ); - } - return this.allSystemData; - } - - private toSystemInfoData(entityDataUpdate: EntityDataUpdate): Array { - const entityData = entityDataUpdate.data?.data ? entityDataUpdate.data?.data : entityDataUpdate.update; - if (entityData && entityData.length) { - const latest = entityData[0].latest; - if (latest && latest[EntityKeyType.TIME_SERIES]) { - const latestTs = latest[EntityKeyType.TIME_SERIES]; - const tsValue = latestTs.clusterSystemData; - if (tsValue && tsValue.value) { - return JSON.parse(tsValue.value); - } - } - } - return []; - } - - protected onSystemData(data: SystemInfoData[]) { - this.systemDataSubject.next(data); - } - - isEmpty(): Observable { - return this.systemDataSubject.pipe( - map((entities) => !entities.length), - share() - ); - } - - total(): Observable { - return this.pageDataSubject.pipe( - map((pageData) => pageData.totalElements), - share() - ); - } - -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.html deleted file mode 100644 index 33345de243..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.html +++ /dev/null @@ -1,71 +0,0 @@ - - diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.scss deleted file mode 100644 index 168d3aaf4c..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.scss +++ /dev/null @@ -1,102 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -@import "../../../../../../../scss/constants"; - -:host { - - .tb-title { - margin-top: 8px; - } - - .tb-info-icon { - color: rgba(0, 0, 0, 0.12); - font-size: 16px; - width: 16px; - height: 16px; - line-height: 15px; - vertical-align: middle; - } - - .tb-features-list { - overflow: auto; - } - - .mat-grid-tile.tb-feature-tile { - overflow: visible; - } - - .tb-feature-button { - height: 50px; - display: flex; - overflow: hidden; - flex-direction: column; - justify-content: center; - padding: 12px; - background: #FFFFFF; - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - @media #{$mat-md-lg} { - height: 22px; - padding: 0 8px; - } - &:hover { - border: 1px solid rgba(0, 0, 0, 0.12); - box-shadow: 0 4px 10px rgba(23, 33, 90, 0.08); - } - .tb-feature-text { - font-weight: 400; - font-size: 14px; - line-height: 20px; - color: rgba(0, 0, 0, 0.87); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - } - .tb-feature-status { - display: inline-block; - font-family: 'Material Icons Round'; - font-size: 20px; - line-height: 20px; - color: rgba(0, 0, 0, 0.12); - font-weight: 600; - position: relative; - background: #F4F4F4; - border-radius: 4px; - width: 24px; - height: 24px; - padding: 2px; - margin-right: 8px; - vertical-align: middle; - @media #{$mat-md-lg} { - font-size: 14px; - line-height: 14px; - width: 18px; - height: 18px; - margin-right: 4px; - } - } - &.configured { - .tb-feature-status { - color: #198038; - background: transparent; - &:before { - content: ""; - position: absolute; - top: 0; - bottom: 0; - left: 0; - right: 0; - border-radius: 4px; - background: var(--tb-primary-500); - opacity: 0.04; - } - } - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.ts deleted file mode 100644 index f521e95201..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.ts +++ /dev/null @@ -1,88 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { AdminService } from '@core/http/admin.service'; -import { FeaturesInfo } from '@shared/models/settings.models'; -import { getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { of, Subscription } from 'rxjs'; -import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout'; -import { TranslateService } from '@ngx-translate/core'; -import { MediaBreakpoints } from '@shared/models/constants'; - -@Component({ - selector: 'tb-configured-features', - templateUrl: './configured-features.component.html', - styleUrls: ['./home-page-widget.scss', './configured-features.component.scss'], - standalone: false -}) -export class ConfiguredFeaturesComponent extends PageComponent implements OnInit, OnDestroy { - - authUser = getCurrentAuthUser(this.store); - featuresInfo: FeaturesInfo; - rowHeight = '50px'; - gutterSize = '12px'; - colspan = 2; - - private observeBreakpointSubscription: Subscription; - - constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService, - private translate: TranslateService, - private breakpointObserver: BreakpointObserver) { - super(store); - } - - ngOnInit() { - const isMdLg = this.breakpointObserver.isMatched(MediaBreakpoints['md-lg']); - const isLtMd = this.breakpointObserver.isMatched(MediaBreakpoints['lt-md']); - this.rowHeight = isMdLg ? '22px' : '50px'; - this.gutterSize = isMdLg ? '8px' : '12px'; - this.colspan = isLtMd ? 3 : 2; - this.observeBreakpointSubscription = this.breakpointObserver - .observe([MediaBreakpoints['md-lg'], MediaBreakpoints['lt-md']]) - .subscribe((state: BreakpointState) => { - if (state.breakpoints[MediaBreakpoints['md-lg']]) { - this.rowHeight = '22px'; - this.gutterSize = '8px'; - } else { - this.rowHeight = '50px'; - this.gutterSize = '12px'; - } - if (state.breakpoints[MediaBreakpoints['lt-md']]) { - this.colspan = 3; - } else { - this.colspan = 2; - } - this.cd.markForCheck(); - } - ); - (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.getFeaturesInfo() : of(null)).subscribe( - (featuresInfo) => { - this.featuresInfo = featuresInfo; - this.cd.markForCheck(); - } - ); - } - - ngOnDestroy() { - if (this.observeBreakpointSubscription) { - this.observeBreakpointSubscription.unsubscribe(); - } - super.ngOnDestroy(); - } - - featureTooltip(configured: boolean): string { - if (configured) { - return this.translate.instant('widgets.configured-features.feature-configured'); - } else { - return this.translate.instant('widgets.configured-features.feature-not-configured'); - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts index 55ea62bb7d..b44d03a596 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts @@ -4,9 +4,6 @@ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { SharedModule } from '@app/shared/shared.module'; -import { ClusterInfoTableComponent } from '@home/components/widget/lib/home-page/cluster-info-table.component'; -import { ConfiguredFeaturesComponent } from '@home/components/widget/lib/home-page/configured-features.component'; -import { VersionInfoComponent } from '@home/components/widget/lib/home-page/version-info.component'; import { DocLinksWidgetComponent } from '@home/components/widget/lib/home-page/doc-links-widget.component'; import { DocLinkComponent } from '@home/components/widget/lib/home-page/doc-link.component'; import { AddDocLinkDialogComponent } from '@home/components/widget/lib/home-page/add-doc-link-dialog.component'; @@ -15,7 +12,6 @@ import { GettingStartedWidgetComponent } from '@home/components/widget/lib/home- import { GettingStartedCompletedDialogComponent } from '@home/components/widget/lib/home-page/getting-started-completed-dialog.component'; -import { LicenseUsageInfoComponent } from '@home/components/widget/lib/home-page/license-usage-info.component'; import { UsageInfoWidgetComponent } from '@home/components/widget/lib/home-page/usage-info-widget.component'; import { QuickLinksWidgetComponent } from '@home/components/widget/lib/home-page/quick-links-widget.component'; import { QuickLinkComponent } from '@home/components/widget/lib/home-page/quick-link.component'; @@ -29,16 +25,12 @@ import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-compone @NgModule({ declarations: [ - ClusterInfoTableComponent, - ConfiguredFeaturesComponent, - VersionInfoComponent, DocLinksWidgetComponent, DocLinkComponent, AddDocLinkDialogComponent, EditLinksDialogComponent, GettingStartedWidgetComponent, GettingStartedCompletedDialogComponent, - LicenseUsageInfoComponent, UsageInfoWidgetComponent, QuickLinksWidgetComponent, QuickLinkComponent, @@ -52,16 +44,12 @@ import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-compone IotHubComponentsModule ], exports: [ - ClusterInfoTableComponent, - ConfiguredFeaturesComponent, - VersionInfoComponent, DocLinksWidgetComponent, DocLinkComponent, AddDocLinkDialogComponent, EditLinksDialogComponent, GettingStartedWidgetComponent, GettingStartedCompletedDialogComponent, - LicenseUsageInfoComponent, UsageInfoWidgetComponent, QuickLinksWidgetComponent, QuickLinkComponent, diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/iot-hub-widget.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/iot-hub-widget.component.ts index 5311eae1bb..2ffe865485 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/iot-hub-widget.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/iot-hub-widget.component.ts @@ -16,7 +16,7 @@ import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-it import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; +import { Operation } from '@shared/models/security.models'; const WIDGET_CARD_COUNT = 3; @@ -51,7 +51,7 @@ export class IotHubWidgetComponent extends PageComponent implements OnInit { ngOnInit() { this.ctx.overflowVisible = true; this.hasIotHubAccess = [Authority.TENANT_ADMIN].includes(this.authUser.authority) && - this.userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); + this.userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL); if (this.hasIotHubAccess) { this.load(); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.html deleted file mode 100644 index 809294b972..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.html +++ /dev/null @@ -1,80 +0,0 @@ - -
-
-
-
widgets.license-info.title
-
- {{ 'widgets.license-info.view-all' | translate }} -
-
- -
-
-
- - {{ statusIcon(licenseUsageInfo?.devicesCount, licenseUsageInfo?.maxDevices) }} - {{ 'widgets.license-info.devices-info' | translate: { count: licenseUsageInfo?.devicesCount, max: licenseUsageInfo?.maxDevices} }} -
-
- - {{ statusIcon(licenseUsageInfo?.assetsCount, licenseUsageInfo?.maxAssets) }} - {{ 'widgets.license-info.assets-info' | translate: { count: licenseUsageInfo?.assetsCount, max: licenseUsageInfo?.maxAssets} }} -
- @if (showEdges) { -
- - {{ statusIcon(licenseUsageInfo?.edgesCount, licenseUsageInfo?.maxEdges) }} - {{ 'widgets.license-info.edges-info' | translate: { count: licenseUsageInfo?.edgesCount, max: licenseUsageInfo?.maxEdges} }} -
- } - @if (!isMdLg) { -
- - check - {{ 'widgets.license-info.dashboards-info' | translate: { count: licenseUsageInfo?.dashboardsCount, max: 0} }} -
- } - @if (!isMdLg) { -
- - check - {{ 'widgets.license-info.integrations-info' | translate: { count: licenseUsageInfo?.integrationsCount, max: 0} }} -
- } -
- @if (!isMdLg) { -
-
- - check - {{ 'widgets.license-info.community-support' | translate }} -
-
- - {{ licenseUsageInfo?.whiteLabelingEnabled ? 'check' : 'close' }} - {{ 'widgets.license-info.white-labeling' | translate }} -
-
- - check - {{ 'widgets.license-info.unlimited-datapoints-and-messages' | translate }} -
-
- - check - {{ 'widgets.license-info.unlimited-api-calls' | translate }} -
-
- } -
-
-
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.scss deleted file mode 100644 index b9ef44a550..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.scss +++ /dev/null @@ -1,162 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -@import "../../../../../../../scss/constants"; - -:host { - .tb-card-content { - width: 100%; - height: 100%; - } - - .tb-card-header { - display: flex; - flex-direction: row; - justify-content: space-between; - align-items: center; - @media #{$mat-md-lg} { - margin-bottom: 4px; - } - } - - .tb-title { - font-style: normal; - font-weight: 500; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - @media #{$mat-md-lg} { - font-size: 12px; - line-height: 16px; - } - } - - .tb-view-all, .tb-license-portal { - @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - } - } - - .tb-license-info-container { - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - padding: 8px 16px 4px 16px; - display: flex; - flex-direction: column; - @media #{$mat-md-lg} { - padding: 4px; - } - } - - .tb-plan-link { - font-weight: 500; - font-size: 16px; - line-height: 24px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.76); - position: relative; - border-bottom: none; - @media #{$mat-md-lg} { - font-size: 12px; - line-height: 16px; - color: rgba(0, 0, 0, 0.54); - } - &:hover, &:focus { - border-bottom: none; - } - &::after { - content: 'arrow_forward'; - display: inline-block; - transform: rotate(315deg); - font-family: 'Material Icons'; - font-weight: normal; - font-style: normal; - font-size: 18px; - color: rgba(0, 0, 0, 0.12); - vertical-align: bottom; - margin-left: 6px; - } - &:hover::after { - color: inherit; - } - } - .tb-feature-text { - font-weight: 400; - font-size: 14px; - color: rgba(0, 0, 0, 0.87); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - .tb-feature-status { - display: inline-block; - font-family: 'Material Icons Round'; - position: relative; - border-radius: 4px; - width: 22px; - height: 22px; - margin-right: 8px; - @media #{$mat-md-lg} { - width: 18px; - height: 18px; - margin-right: 4px; - } - } - &.ok, &.disabled { - .tb-feature-status { - font-size: 20px; - line-height: 20px; - font-weight: 600; - padding: 1px; - vertical-align: sub; - @media #{$mat-md-lg} { - font-size: 14px; - line-height: 14px; - padding: 2px; - } - } - } - &.ok { - .tb-feature-status { - color: #198038; - background: transparent; - &:before { - content: ""; - position: absolute; - top: 0; - bottom: 0; - left: 0; - right: 0; - border-radius: 4px; - background: var(--tb-primary-500); - opacity: 0.04; - } - } - } - &.disabled { - .tb-feature-status { - color: rgba(0, 0, 0, 0.12); - background: #F4F4F4; - } - } - &.critical { - color: var(--tb-crit); - .tb-feature-status { - line-height: 24px; - font-size: 24px; - font-weight: normal; - padding: 0; - vertical-align: bottom; - @media #{$mat-md-lg} { - font-size: 18px; - line-height: 18px; - } - } - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.ts deleted file mode 100644 index 176cac3229..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.ts +++ /dev/null @@ -1,86 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { AdminService } from '@core/http/admin.service'; -import { LicenseUsageInfo } from '@shared/models/settings.models'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { of, Subscription } from 'rxjs'; -import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout'; -import { TranslateService } from '@ngx-translate/core'; -import { MediaBreakpoints } from '@shared/models/constants'; - -@Component({ - selector: 'tb-license-usage-info', - templateUrl: './license-usage-info.component.html', - styleUrls: ['./license-usage-info.component.scss'], - changeDetection: ChangeDetectionStrategy.OnPush, - standalone: false -}) -export class LicenseUsageInfoComponent extends PageComponent implements OnInit, OnDestroy { - - authUser = getCurrentAuthUser(this.store); - licenseUsageInfo: LicenseUsageInfo; - isMdLg = false; - authState = getCurrentAuthState(this.store); - showEdges = this.authState.licenseVersion > 1 && this.authState.edgesSupportEnabled && this.authState.edgeEnabled; - - private observeBreakpointSubscription: Subscription; - - constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService, - private translate: TranslateService, - private breakpointObserver: BreakpointObserver) { - super(store); - } - - ngOnInit() { - this.isMdLg = this.breakpointObserver.isMatched(MediaBreakpoints['md-lg']); - this.observeBreakpointSubscription = this.breakpointObserver - .observe(MediaBreakpoints['md-lg']) - .subscribe((state: BreakpointState) => { - this.isMdLg = state.matches; - this.cd.markForCheck(); - }); - (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.getLicenseUsageInfo() : of(null)).subscribe( - (licenseUsageInfo) => { - this.licenseUsageInfo = licenseUsageInfo; - this.cd.markForCheck(); - } - ); - } - - ngOnDestroy() { - if (this.observeBreakpointSubscription) { - this.observeBreakpointSubscription.unsubscribe(); - } - super.ngOnDestroy(); - } - - statusIcon(count?: number, max?: number): string { - let icon = 'check'; - if (count && max) { - const percent = (count / max) * 100; - if (percent > 85) { - icon = 'warning'; - } - } - return icon; - } - - statusClass(count?: number, max?: number): string { - let className = 'ok'; - if (count && max) { - const percent = (count / max) * 100; - if (percent > 85) { - className = 'critical'; - } - } - return className; - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/usage-info-widget.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/usage-info-widget.component.ts index 8174ec5794..5916598612 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/usage-info-widget.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/usage-info-widget.component.ts @@ -13,7 +13,7 @@ import { UsageInfo } from '@shared/models/usage.models'; import { UsageInfoService } from '@core/http/usage-info.service'; import { ShortNumberPipe } from '@shared/pipe/short-number.pipe'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; +import { Operation } from '@shared/models/security.models'; @Component({ selector: 'tb-usage-info-widget', @@ -48,7 +48,7 @@ export class UsageInfoWidgetComponent extends PageComponent implements OnInit, O ngOnInit() { this.hasUsageInfoAccess = this.authUser.authority === Authority.TENANT_ADMIN && - this.userPermissionsService.hasGenericPermission(Resource.ALL, Operation.READ); + this.userPermissionsService.hasGenericPermissionExceptAi(Operation.READ); if (this.hasUsageInfoAccess) { this.usageInfoService.getUsageInfo().subscribe( (usageInfo) => { diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html deleted file mode 100644 index b222ea9477..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html +++ /dev/null @@ -1,53 +0,0 @@ - -
-
-
-
widgets.version-info.title
-
- {{ 'widgets.version-info.contact-us' | translate }} -
-
-
-
- -
{{ updateMessage?.currentVersion }}
-
-
-
-
- @if (updateMessage?.updateAvailable) { - - } @else { -
-
check
-
widgets.version-info.version-is-up-to-date
-
- } -
-
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss deleted file mode 100644 index c3e815d550..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss +++ /dev/null @@ -1,130 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -@import "../../../../../../../scss/constants"; - -:host { - .tb-card-header { - display: flex; - flex-direction: row; - justify-content: space-between; - align-items: center; - margin-bottom: 8px; - @media #{$mat-md-lg} { - margin-bottom: 4px; - } - } - - .tb-contact-us { - @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - } - } - - .tb-version-info-container { - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - padding: 8px 16px 4px 16px; - overflow: hidden; - white-space: nowrap; - @media #{$mat-lt-md} { - padding: 16px; - } - @media #{$mat-md-lg} { - padding: 4px; - } - &.up-to-date { - position: relative; - box-shadow: none; - border: none; - white-space: initial; - text-align: center; - &:before { - content: ""; - position: absolute; - top: 0; - bottom: 0; - left: 0; - right: 0; - border-radius: 10px; - background: var(--tb-primary-500); - opacity: 0.04; - } - } - } - - .tb-version-link { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - position: relative; - border-bottom: none; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - &:hover, &:focus { - border-bottom: none; - } - &::after { - content: 'arrow_forward'; - display: inline-block; - transform: rotate(315deg); - font-family: 'Material Icons'; - font-weight: normal; - font-style: normal; - font-size: 18px; - color: rgba(0, 0, 0, 0.12); - vertical-align: bottom; - margin-left: 6px; - } - &:hover::after { - color: inherit; - } - } - - .tb-version { - font-weight: 500; - font-size: 18px; - line-height: 24px; - letter-spacing: 0.15px; - color: rgba(0, 0, 0, 0.87); - @media #{$mat-md-lg} { - font-size: 12px; - line-height: 14px; - } - } - - .tb-upgrade { - @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - padding: 0; - overflow: hidden; - } - } - - .check-icon { - color: #198038; - font-weight: 600; - @media #{$mat-md-lg} { - font-size: 16px; - } - } - - .up-to-date-text { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts deleted file mode 100644 index 921a6ba0a3..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 -import { ChangeDetectorRef, Component, OnInit } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { AdminService } from '@core/http/admin.service'; -import { UpdateMessage } from '@shared/models/settings.models'; -import { getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { of } from 'rxjs'; - -@Component({ - selector: 'tb-version-info', - templateUrl: './version-info.component.html', - styleUrls: ['./home-page-widget.scss', './version-info.component.scss'], - standalone: false -}) -export class VersionInfoComponent extends PageComponent implements OnInit { - - authUser = getCurrentAuthUser(this.store); - updateMessage: UpdateMessage; - - constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService) { - super(store); - } - - ngOnInit() { - (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.checkUpdates() : of(null)).subscribe( - (updateMessage) => { - this.updateMessage = updateMessage; - this.cd.markForCheck(); - } - ); - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts index e79a9cecbb..f56873a839 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { Datasource, FormattedData } from '@app/shared/models/widget.models'; import tinycolor from 'tinycolor2'; import { BaseIconOptions, Icon } from 'leaflet'; @@ -64,7 +65,7 @@ export interface GoogleMapProviderSettings { } export const defaultGoogleMapProviderSettings: GoogleMapProviderSettings = { - gmApiKey: 'AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q', + gmApiKey: null, gmDefaultMapType: GoogleMapType.roadmap }; @@ -128,7 +129,7 @@ export interface HereMapProviderSettings { export const defaultHereMapProviderSettings: HereMapProviderSettings = { mapProviderHere: HereMapProvider.hereNormalDay, credentials: { - apiKey: 'kVXykxAfZ6LS4EbCTO02soFVfjA7HoBzNVVH9u7nzoE' + apiKey: null } }; diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/google-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/google-map.ts index 585179df41..738802b595 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/google-map.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/google-map.ts @@ -44,11 +44,11 @@ export class GoogleMap extends LeafletMap { }, options.gmApiKey); } - private loadGoogle(callback: () => void, apiKey = 'AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q') { + private loadGoogle(callback: () => void, apiKey: string) { if (gmGlobals[apiKey]) { callback(); } else { - this.resource.loadResource(`https://maps.googleapis.com/maps/api/js?key=${apiKey}`).subscribe({ + this.resource.loadResource(`https://maps.googleapis.com/maps/api/js${apiKey ? `?key=${apiKey}` : ''}`).subscribe({ next: () => { gmGlobals[apiKey] = true; callback(); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts index 063ba5dcdb..ca528259e9 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import L from 'leaflet'; import LeafletMap from '../leaflet-map'; -import { DEFAULT_ZOOM_LEVEL, defaultHereMapProviderSettings, WidgetUnitedMapSettings } from '../map-models'; +import { DEFAULT_ZOOM_LEVEL, WidgetUnitedMapSettings } from '../map-models'; import { WidgetContext } from '@home/models/widget-component.models'; import { hereV3Provider } from '@shared/models/widget/maps/map.models'; @@ -19,13 +19,17 @@ export class HEREMap extends LeafletMap { zoomControl: !this.options.disableZoomControl, fadeAnimation: !ctx.reportService.reportView }).setView(options?.parsedDefaultCenterPosition, options?.defaultZoomLevel || DEFAULT_ZOOM_LEVEL); - const apiKey = options.credentials?.apiKey || defaultHereMapProviderSettings.credentials.apiKey; - const tileLayer = L.tileLayer.provider(hereV3Provider(options.mapProviderHere), {apiKey}); - tileLayer.addTo(map); - if (this.ctx.reportService.reportView) { - tileLayer.once('load', () => { - this.ctx.reportService.onMapLoaded(mapUuid); - }); + const apiKey = options.credentials?.apiKey; + if (apiKey) { + const tileLayer = L.tileLayer.provider(hereV3Provider(options.mapProviderHere), {apiKey}); + tileLayer.addTo(map); + if (this.ctx.reportService.reportView) { + tileLayer.once('load', () => { + this.ctx.reportService.onMapLoaded(mapUuid); + }); + } + } else if (this.ctx.reportService.reportView) { + this.ctx.reportService.onMapLoaded(mapUuid); } super.setMap(map); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/openstreet-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/openstreet-map.ts index 13ddf95988..11cd52a9e9 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/openstreet-map.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/openstreet-map.ts @@ -23,6 +23,9 @@ export class OpenStreetMap extends LeafletMap { tileLayer = L.tileLayer(options.customProviderTileUrl); } else { tileLayer = L.tileLayer.provider(options.mapProvider || 'OpenStreetMap.Mapnik'); + if (tileLayer.options.attribution && options.mapProvider?.startsWith('Esri.')) { + L.Util.setOptions(tileLayer, {attribution: `Powered by Esri | ${tileLayer.options.attribution}`}); + } } tileLayer.addTo(map); if (this.ctx.reportService.reportView) { diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts index 1df970fece..e364ee804e 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts @@ -1093,6 +1093,9 @@ const chinaProvider = (type: string, options?: L.TileLayerOptions): L.TB.TileLay // The worker is copied to assets by angular.json, bundlers cannot resolve it from import.meta.url setWorkerUrl(new URL('assets/maplibre-gl/maplibre-gl-worker.mjs', document.baseURI).href); +// Same as MapLibre's own default maxZoom +const MAP_LIBRE_GL_DEFAULT_MAX_ZOOM = 22; + class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { options: TB.MapLibreGL.LeafletMapLibreGLMapOptions; @@ -1107,18 +1110,25 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { constructor(options: TB.MapLibreGL.LeafletMapLibreGLMapOptions) { super(); - options = {...options, ...{ - updateInterval: 32, - padding: 0.1, - interactive: false, - pane: 'tilePane' - }}; + options = { + maxZoom: MAP_LIBRE_GL_DEFAULT_MAX_ZOOM, + ...options, + updateInterval: 32, + padding: 0.1, + interactive: false, + pane: 'tilePane' + }; options.attribution = this._loadAttribution(options); this._prepareTransformRequest(options); L.setOptions(this, options); this._throttledUpdate = L.Util.throttle(this._update, this.options.updateInterval, this); } + beforeAdd(map: L.Map): this { + map._addZoomLimit(this); + return this; + } + onAdd(map: L.Map): this { let update = false; if (!this._container) { @@ -1146,6 +1156,7 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { } const paneName = this.getPaneName(); map.getPane(paneName).removeChild(this._container); + map._removeZoomLimit(this); if (this._glMap) { this._glMap.remove(); @@ -1380,7 +1391,7 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { const style = options.style; if (typeof style !== 'string' && style.glyphs) { const glyphs = style.glyphs; - const glyphsRegexString = glyphs.replace(/\//g, '\\/').replace(/\./g, '\\.').replace('{fontstack}', '(.*)').replace('{range}', '(.*)'); + const glyphsRegexString = glyphs.replace(/[.*+?^$()|[\]\\/]/g, '\\$&').replace('{fontstack}', '(.*)').replace('{range}', '(.*)'); const glyphsRegex = new RegExp(glyphsRegexString); options.transformRequest = (url, resourceType) => { if (resourceType === 'Glyphs' && glyphsRegex && glyphsRegex.test(url)) { diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts index ae33b11db6..08590427a2 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts @@ -1,16 +1,20 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { CartoMapLayerSettings, CustomMapLayerSettings, defaultCartoMapLayerSettings, defaultCustomMapLayerSettings, + defaultEsriMapLayerSettings, defaultGoogleMapLayerSettings, defaultHereMapLayerSettings, defaultLayerTitle, defaultOpenFreeMapLayerSettings, defaultOpenStreetMapLayerSettings, defaultTencentMapLayerSettings, + EsriLayerType, + EsriMapLayerSettings, GoogleMapLayerSettings, HereMapLayerSettings, hereV3Provider, @@ -31,23 +35,78 @@ import { CustomTranslatePipe } from '@shared/pipe/custom-translate.pipe'; import L, { LeafletEvent } from 'leaflet'; import { catchError, map } from 'rxjs/operators'; import { ResourcesService } from '@core/services/resources.service'; -import { StyleSpecification } from '@maplibre/maplibre-gl-style-spec'; +import { StyleSpecification, VectorSourceSpecification } from '@maplibre/maplibre-gl-style-spec'; -const referenceLayerStyleUrlMap = new Map( +const poweredByEsriAttribution = 'Powered by Esri'; +const esriWorldBasemapAttribution = + 'Sources: Esri, TomTom, Garmin, FAO, NOAA, USGS, © OpenStreetMap contributors, and the GIS User Community'; + +// Esri content (Esri Master License Agreement): must not be bundled or self-hosted, so it is loaded from ArcGIS Online, +// with the user's own ArcGIS API key when one is specified. +const referenceLayerStyleMap = new Map( + [ + [ReferenceLayerType.openstreetmap_hybrid, { + itemId: 'f240fe360b434afc87dd989bf0c0b825', + attribution: 'Map data (c) OpenStreetMap contributors, Microsoft, Facebook, Google, Esri Community Maps contributors, Map layer by Esri' + }], + [ReferenceLayerType.world_edition_hybrid, {itemId: '30d6b8271e1849cd9c3042060001f425', attribution: esriWorldBasemapAttribution}], + [ReferenceLayerType.enhanced_contrast_hybrid, {itemId: 'c8ec7c62427d484a81397aefb7e59c5f', attribution: esriWorldBasemapAttribution}] + ] +); + +// With an API key: the World Street Map and World Topo Map raster services are retired (mature support), +// ArcGIS replaces them with the ArcGIS Streets and ArcGIS Topographic vector basemap styles. +const esriWorldImageryTokenTilesUrl = 'https://ibasemaps-api.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'; +const esriBasemapStylesUrl = 'https://basemapstyles-api.arcgis.com/arcgis/rest/services/styles/v2/styles'; +const esriLayerTokenStyles = new Map( [ - [ReferenceLayerType.openstreetmap_hybrid, '/assets/map/openstreetmap_hybrid_reference_style.json'], - [ReferenceLayerType.world_edition_hybrid, '/assets/map/world_edition_hybrid_reference_style.json'], - [ReferenceLayerType.enhanced_contrast_hybrid, '/assets/map/enhanced_contrast_hybrid_reference_style.json'] + [EsriLayerType.esriWorldStreetMap, `${esriBasemapStylesUrl}/arcgis/streets`], + [EsriLayerType.esriWorldTopoMap, `${esriBasemapStylesUrl}/arcgis/topographic`] ] ); -const referenceLayerCache = new Map>(); +const withArcGISToken = (url: string, token: string): string => + token ? `${url}${url.includes('?') ? '&' : '?'}token=${encodeURIComponent(token)}` : url; + +// ArcGIS VectorTileServer metadata is not TileJSON: relative tile URL, no attribution +const prepareReferenceLayerStyle = (spec: StyleSpecification, attribution: string, token: string): StyleSpecification => { + const source = spec.sources.esri as VectorSourceSpecification; + return { + ...spec, + sprite: typeof spec.sprite === 'string' ? withArcGISToken(spec.sprite, token) : spec.sprite, + glyphs: spec.glyphs ? withArcGISToken(spec.glyphs, token) : spec.glyphs, + sources: { + esri: { + ...source, + attribution, + url: withArcGISToken(source.url, token), + tiles: [withArcGISToken(`${source.url}/tile/{z}/{y}/{x}.pbf`, token)] + } + } + }; +}; + +const referenceLayerCache = new Map>(); interface TbMapLayerData { layer: L.Layer; attribution: boolean; } +// Placeholder for a provider layer without the required API key +class TbEmptyMapLayer extends L.Layer { + + onAdd(): this { + // The map waits for the 'load' event of its default layer, e.g. to generate a report + setTimeout(() => this.fire('load')); + return this; + } + + onRemove(): this { + return this; + } +} + export abstract class TbMapLayer { static fromSettings(ctx: WidgetContext, @@ -61,6 +120,8 @@ export abstract class TbMapLayer { return new TbOpenStreetMapLayer(ctx, inputSettings); case MapProvider.carto: return new TbCartoMapLayer(ctx, inputSettings); + case MapProvider.esri: + return new TbEsriMapLayer(ctx, inputSettings); case MapProvider.google: return new TbGoogleMapLayer(ctx, inputSettings); case MapProvider.tencent: @@ -110,7 +171,7 @@ export abstract class TbMapLayer { switchMap((baseLayer) => { if (baseLayer) { if (this.settings.referenceLayer) { - return this.loadReferenceLayer(this.settings.referenceLayer).pipe( + return this.loadReferenceLayer(this.settings.referenceLayer, this.referenceLayerApiKey()).pipe( map((referenceLayer) => { if (referenceLayer) { const layer = L.featureGroup(); @@ -161,27 +222,53 @@ export abstract class TbMapLayer { )); } - private loadReferenceLayer(referenceLayer: ReferenceLayerType): Observable { - let spec$ = referenceLayerCache.get(referenceLayer); + private loadReferenceLayer(referenceLayer: ReferenceLayerType, token: string): Observable { + const cacheKey = `${referenceLayer}:${token || ''}`; + let spec$ = referenceLayerCache.get(cacheKey); if (!spec$) { - const styleUrl = referenceLayerStyleUrlMap.get(referenceLayer); - spec$ = this.ctx.http.get(styleUrl).pipe( + const {itemId, attribution} = referenceLayerStyleMap.get(referenceLayer); + spec$ = this.ctx.http.get(withArcGISToken( + `https://cdn.arcgis.com/sharing/rest/content/items/${itemId}/resources/styles/root.json`, token) + ).pipe( + map(spec => prepareReferenceLayerStyle(spec, attribution, token)), + catchError((e) => { + console.error(`Map reference layer style load failed!`, e); + referenceLayerCache.delete(cacheKey); + return of(null); + }), shareReplay({ bufferSize: 1, refCount: true }) ); - referenceLayerCache.set(referenceLayer, spec$); + referenceLayerCache.set(cacheKey, spec$); } return spec$.pipe( map(spec => { + if (!spec) { + return null; + } return L.TB.MapLibreGL.mapLibreGLLayer({ - style: spec, + style: this.referenceLayerStyle(spec), + // The reference layer is drawn over a raster base, so the base layer's zoom limit applies + maxZoom: undefined }); }) ); } + protected referenceLayerApiKey(): string { + return this.settings.referenceLayerApiKey; + } + + protected referenceLayerStyle(spec: StyleSpecification): StyleSpecification { + const source = spec.sources.esri as VectorSourceSpecification; + return { + ...spec, + sources: {...spec.sources, esri: {...source, attribution: `${poweredByEsriAttribution} | ${source.attribution}`}} + }; + } + private title(): string { const customTranslate = this.ctx.$injector.get(CustomTranslatePipe); if (this.settings.label) { @@ -268,6 +355,47 @@ class TbCartoMapLayer extends TbMapLayer { } +class TbEsriMapLayer extends TbMapLayer { + + constructor(protected ctx: WidgetContext, + protected inputSettings: DeepPartial) { + super(ctx, inputSettings); + } + + protected defaultSettings(): EsriMapLayerSettings { + return defaultEsriMapLayerSettings; + } + + protected referenceLayerApiKey(): string { + return this.settings.apiKey; + } + + // The base Esri layer already shows 'Powered by Esri' + protected referenceLayerStyle(spec: StyleSpecification): StyleSpecification { + return spec; + } + + protected createLayer(): Observable { + const apiKey = this.settings.apiKey; + const tokenStyle = esriLayerTokenStyles.get(this.settings.layerType); + if (apiKey && tokenStyle) { + return of(L.TB.MapLibreGL.mapLibreGLLayer({ + style: withArcGISToken(tokenStyle, apiKey), + attributionControl: { + customAttribution: `${poweredByEsriAttribution} | ${esriWorldBasemapAttribution}` + } + })); + } + const layer = L.tileLayer.provider(this.settings.layerType); + L.Util.setOptions(layer, {attribution: `${poweredByEsriAttribution} | ${layer.options.attribution}`}); + if (apiKey && this.settings.layerType === EsriLayerType.esriWorldImagery) { + layer.setUrl(withArcGISToken(esriWorldImageryTokenTilesUrl, apiKey), true); + } + return of(layer); + } + +} + class TbGoogleMapLayer extends TbMapLayer { static loadedApiKeysGlobal: {[key: string]: boolean} = {}; @@ -296,12 +424,12 @@ class TbGoogleMapLayer extends TbMapLayer { } private loadGoogle(): Observable { - const apiKey = this.settings.apiKey || defaultGoogleMapLayerSettings.apiKey; + const apiKey = this.settings.apiKey || ''; if (TbGoogleMapLayer.loadedApiKeysGlobal[apiKey]) { return of(true); } else { const resourceService = this.ctx.$injector.get(ResourcesService); - return resourceService.loadResource(`https://maps.googleapis.com/maps/api/js?key=${apiKey}&loading=async`).pipe( + return resourceService.loadResource(`https://maps.googleapis.com/maps/api/js?${apiKey ? `key=${apiKey}&` : ''}loading=async`).pipe( map(() => { TbGoogleMapLayer.loadedApiKeysGlobal[apiKey] = true; return true; @@ -348,8 +476,10 @@ class TbHereMapLayer extends TbMapLayer { } protected createLayer(): Observable { - const apiKey = this.settings.apiKey || defaultHereMapLayerSettings.apiKey; - const layer = L.tileLayer.provider(hereV3Provider(this.settings.layerType), {apiKey}); + if (!this.settings.apiKey) { + return of(new TbEmptyMapLayer()); + } + const layer = L.tileLayer.provider(hereV3Provider(this.settings.layerType), {apiKey: this.settings.apiKey}); return of(layer); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-action-pretty-editor.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-action-pretty-editor.component.html index 5c85012257..479c35124f 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-action-pretty-editor.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-action-pretty-editor.component.html @@ -1,13 +1,14 @@
@if (!fullscreen) { -
-
-
- diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/date-format-select.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/date-format-select.component.html index 93a1f33612..27d92696b8 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/date-format-select.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/date-format-select.component.html @@ -1,7 +1,8 @@ @@ -11,13 +12,13 @@ } @if (dateFormatFormControl.value?.custom) { - } @if (dateFormatFormControl.value?.auto && !dateFormatFormControl.value?.custom) { - diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/gradient.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/gradient.component.html index 4b251eda4d..f2ff5c4499 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/gradient.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/gradient.component.html @@ -1,7 +1,8 @@ @@ -83,7 +84,7 @@
} -
} -
- diff --git a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html index c3047766af..f74ab22105 100644 --- a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html @@ -163,7 +163,7 @@ [genericAdditionalInfoTemplate]="genericAdditionalInfo" [executeRemotelyTemplate]="executeRemotely" [integrationType]="integrationWizardForm.get('type').value" - [isSetDownlink]="!!downlinkConverterForm.get('downlinkConverterId').value || downlinkConverterForm.get('converterType').value === 'new'" + [isSetDownlink]="isDownlinkConverterSet" [isEdgeTemplate]="isEdgeTemplate" > @@ -177,7 +177,7 @@
integration.metadata - +
diff --git a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts index fc73da1626..bd1e829cdf 100644 --- a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts @@ -283,6 +283,17 @@ export class IntegrationWizardDialogComponent extends } } + get isDownlinkConverterSet(): boolean { + switch (this.downlinkConverterForm.get('converterType').value) { + case ConverterSourceType.EXISTING: + return !!this.downlinkConverterForm.get('downlinkConverterId').value; + case ConverterSourceType.SKIP: + return false; + default: + return true; + } + } + private createDownlinkConverter(): Observable { const converterType = this.downlinkConverterForm.get('converterType').value; if (converterType === ConverterSourceType.SKIP) { diff --git a/ui-ngx/src/app/modules/home/dialogs/home-dialogs.service.ts b/ui-ngx/src/app/modules/home/dialogs/home-dialogs.service.ts index dfeb9a9669..b9e968bc0b 100644 --- a/ui-ngx/src/app/modules/home/dialogs/home-dialogs.service.ts +++ b/ui-ngx/src/app/modules/home/dialogs/home-dialogs.service.ts @@ -36,11 +36,6 @@ import { EntityGroupWizardDialogData, EntityGroupWizardDialogResult } from '@home/components/wizard/entity-group-wizard-dialog.component'; -import { DashboardInfo } from '@shared/models/dashboard.models'; -import { - DashboardInfoDialogData, - ImportDashboardFileDialogComponent -} from '@home/pages/dashboard/import-dashboard-file-dialog.component'; @Injectable() export class HomeDialogsService { @@ -141,20 +136,6 @@ export class HomeDialogsService { }).afterClosed(); } - public importDashboardFile($event: Event, dashboard: DashboardInfo): Observable { - if ($event) { - $event.stopPropagation(); - } - return this.dialog.open(ImportDashboardFileDialogComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - data: { - dashboard - } - }).afterClosed(); - } - public selectOwner($event: Event, selectOwnerTitle: string, confirmSelectTitle: string, placeholderText: string, notFoundText: string, requiredText: string, onOwnerSelected?: (targetOwnerId: EntityId) => Observable, diff --git a/ui-ngx/src/app/modules/home/home.component.html b/ui-ngx/src/app/modules/home/home.component.html index 852d1c4742..c7626e2a10 100644 --- a/ui-ngx/src/app/modules/home/home.component.html +++ b/ui-ngx/src/app/modules/home/home.component.html @@ -58,7 +58,7 @@ -
+
@if ((homeService.hideMainToolbar$ | async) === false) { -
- -
+ +

@@ -63,13 +63,13 @@

-