diff --git a/README.md b/README.md index e5ee3c7..095ac1f 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,9 @@ DOMAIN=sheep-service.com HTTP_PORT=4000 HTTPS_PORT=4001 +ADMIN_USER=<тут_твій_нікнейм> +ADMIN_TOKEN=<тут_твій_токен> + DB_PATH=/home/username/webapps/sheep-service.com/ CARDS_PATH=/home/username/webapps/sheep-service.com/cards MAP_PATH=/home/username/webapps/sheep-service.com/map diff --git a/api/controllers/sheeps.controller.js b/api/controllers/sheeps.controller.js index 1e27694..3121e7b 100644 --- a/api/controllers/sheeps.controller.js +++ b/api/controllers/sheeps.controller.js @@ -44,6 +44,24 @@ class SheepsController { } } + async getListStand(req, res) { + if (req.possibilities.can_view_stand) { + const result = await SheepsService.getListStand(req.mode); + + if (result) { + return res.status(200).send(result); + } else { + return res + .status(404) + .send({ message: 'User not found.' }); + } + } else { + return res + .status(404) + .send({ message: 'The sheep does not have enough rights.' }); + } + } + async createSheep(req, res) { const data = req.body; diff --git a/api/middleware/metrics.js b/api/middleware/metrics.js new file mode 100644 index 0000000..ddc8671 --- /dev/null +++ b/api/middleware/metrics.js @@ -0,0 +1,22 @@ +module.exports = (req, res, next) => { + const start = performance.now(); + + res.on("finish", () => { + const duration = performance.now() - start; + + fetch("http://metrics:4005/push", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + type: "rest", + path: req.originalUrl, + method: req.method, + status: res.statusCode, + time: duration, + timestamp: Date.now() + }) + }).catch(err => console.error(err)); + }); + + next(); +}; \ No newline at end of file diff --git a/api/routes/index.js b/api/routes/index.js index 69e08c9..88c09e5 100644 --- a/api/routes/index.js +++ b/api/routes/index.js @@ -1,6 +1,8 @@ const express = require('express'); const router = express.Router(); +const metrics = require('../middleware/metrics'); + const authRoutes = require('./auth.routes'); const sheepsRoutes = require('./sheeps.routes'); const constructorRoutes = require('./constructor.routes'); @@ -18,6 +20,9 @@ const pushRoutes = require('./push.routes'); const generatorCardsRoutes = require('./generator.cards.routes'); const generatorReportTerritoriesRoutes = require('./generator.report.territories.routes'); + +router.use(metrics); + router.use('/auth', authRoutes); router.use('/sheeps?', sheepsRoutes); router.use('/constructor', constructorRoutes); diff --git a/api/routes/sheeps.routes.js b/api/routes/sheeps.routes.js index eaa2002..7e81ec9 100644 --- a/api/routes/sheeps.routes.js +++ b/api/routes/sheeps.routes.js @@ -15,4 +15,8 @@ router .route('/list') .get(authenticate, SheepsController.getList); +router + .route('/list/stand') + .get(authenticate, SheepsController.getListStand); + module.exports = router; \ No newline at end of file diff --git a/api/services/sheeps.service.js b/api/services/sheeps.service.js index 0543567..ea43201 100644 --- a/api/services/sheeps.service.js +++ b/api/services/sheeps.service.js @@ -75,6 +75,7 @@ class SheepService { }); }); } + getList(mode) { return new Promise((res, rej) => { const sql = ` @@ -147,6 +148,82 @@ class SheepService { }); }); } + + getListStand(mode) { + return new Promise((res, rej) => { + const sql = ` + SELECT + sheeps.*, + possibilities.can_add_sheeps, + possibilities.can_view_sheeps, + possibilities.can_add_territory, + possibilities.can_view_territory, + possibilities.can_manager_territory, + possibilities.can_add_stand, + possibilities.can_view_stand, + possibilities.can_manager_stand, + possibilities.can_add_schedule, + possibilities.can_view_schedule + FROM + sheeps + LEFT JOIN + possibilities ON possibilities.sheep_id = sheeps.id + WHERE + possibilities.can_view_stand = '1' + ORDER BY + sheeps.group_id; + `; + + db.all(sql, (err, rows) => { + if (err) { + console.error(err.message); + return res(false); + } + + const fields = [ + "can_add_sheeps", + "can_view_sheeps", + "can_add_territory", + "can_view_territory", + "can_manager_territory", + "can_add_stand", + "can_view_stand", + "can_manager_stand", + "can_add_schedule", + "can_view_schedule" + ]; + + const result = rows.map(sheep => { + const data = { + id: sheep.id, + group_id: sheep.group_id, + name: sheep.name, + icon: sheep.icon, + uuid: (mode && mode == 2) ? sheep.uuid : null, + uuid_manager: (mode && mode == 2) ? sheep.uuid_manager : null, + mode: mode ? Number(sheep.mode) : 0, + mode_title: sheep.mode_title, + possibilities: {} + }; + + fields.forEach(f => { + data.possibilities[f] = false; + }); + + if (mode && (mode == 1 || mode == 2)) { + fields.forEach(f => { + data.possibilities[f] = !!sheep[f]; + }); + } + + return data; + }); + + res(result); + }); + }); + } + createSheep(data) { const stmt1 = db.prepare('INSERT INTO sheeps(name, group_id, uuid) VALUES (?, ?, ?)'); const stmt2 = db.prepare('INSERT INTO possibilities(can_view_territory, sheep_id) VALUES (?, ?)'); @@ -175,6 +252,7 @@ class SheepService { }); }); } + updateSheep(data) { const stmt1 = db.prepare(` UPDATE @@ -241,6 +319,7 @@ class SheepService { }); }); } + deleteSheep(data) { const stmtSelect = db.prepare('SELECT id FROM sheeps WHERE uuid = ?'); const stmtDeletePoss = db.prepare('DELETE FROM possibilities WHERE sheep_id = ?'); diff --git a/dash.json b/dash.json new file mode 100644 index 0000000..fb3e92e --- /dev/null +++ b/dash.json @@ -0,0 +1,163 @@ +{ + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "datasource", + "uid": "prometheus" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "target": { + "limit": 100, + "matchAny": false, + "tags": [], + "type": "dashboard" + }, + "type": "dashboard" + } + ] + }, + "editable": true, + "graphTooltip": 1, + "fiscalYearStartMonth": 0, + "id": null, + "links": [], + "panels": [ + + + { + "datasource": { "type": "datasource", "uid": "prometheus" }, + "fieldConfig": { + "defaults": { + "color": { "mode": "palette-classic" }, + "custom": { + "axisPlacement": "auto", + "drawStyle": "line", + "fillBorderColor": "rgba(255, 255, 255, 1)", + "gradientMode": "none", + "lineStyle": "solid", + "lineWidth": 1, + "scaleDistribution": { "type": "linear" }, + "showPoints": "auto", + "spanNulls": false, + "stacking": { "group": "A", "mode": "none" }, + "thresholdsStyle": { "mode": "off" } + }, + "unit": "ms" + }, + "overrides": [] + }, + "gridPos": { "h": 8, "w": 8, "x": 0, "y": 0 }, + "id": 2, + "options": { + "legend": { "calcs": ["mean", "max"], "displayMode": "list", "placement": "bottom" }, + "tooltip": { "mode": "single", "sort": "none" } + }, + "targets": [ + { "expr": "frontend_load_time", "legendFormat": "Завантаження: {{instance}}", "refId": "A" } + ], + "title": "Час завантаження Frontend (ms)", + "type": "timeseries" + }, + + { + "datasource": { "type": "datasource", "uid": "prometheus" }, + "fieldConfig": { + "defaults": { + "color": { "mode": "palette-classic" }, + "unit": "short" + } + }, + "gridPos": { "h": 8, "w": 8, "x": 8, "y": 0 }, + "id": 4, + "options": { + "legend": { + "calcs": ["last"], + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { "mode": "single", "sort": "none" } + }, + "targets": [ + { "expr": "users_online", "legendFormat": "Онлайн користувачі", "refId": "A" } + ], + "title": "Онлайн користувачі (Gauge)", + "type": "timeseries" + }, + + { + "datasource": { "type": "datasource", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 16, "y": 0 }, + "id": 10, + "targets": [ + { + "expr": "rest_request_duration_ms", + "legendFormat": "{{path}} ({{status}})", + "refId": "A" + } + ], + "title": "REST Запити (Duration)", + "type": "timeseries" + }, + + { + "datasource": { "type": "datasource", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 0, "y": 8 }, + "id": 6, + "targets": [ + { + "expr": "rate(ws_in_bytes_total[5m])", + "legendFormat": "Вхідний WS-трафік (байт/сек)", + "refId": "A" + }, + { + "expr": "rate(ws_out_bytes_total[5m])", + "legendFormat": "Вихідний WS-трафік (байт/сек)", + "refId": "B" + } + ], + "type": "timeseries", + "title": "WS трафік (Rate)" + }, + + { + "datasource": { "type": "datasource", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 8, "y": 8 }, + "id": 16, + "targets": [ + { "expr": "frontend_resource_count", "legendFormat": "Кількість ресурсів", "refId": "A" } + ], + "title": "Кількість завантажених ресурсів", + "type": "timeseries" + }, + + { + "datasource": { "type": "datasource", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 16, "y": 8 }, + "id": 14, + "targets": [ + { + "expr": "frontend_memory_used", + "legendFormat": "Використано JS Heap (MB)", + "refId": "A" + } + ], + "title": "Використання JS Heap (MB)", + "type": "timeseries" + } + ], + + "refresh": "5s", + "schemaVersion": 38, + "style": "dark", + "tags": ["Sheep Service", "pushgateway"], + + "time": { "from": "now-30m", "to": "now" }, + "timezone": "browser", + "title": "Sheep Service Metrics", + "version": 1 +} \ No newline at end of file diff --git a/data/cards/cache/house/T81.png b/data/cards/cache/house/T81.png new file mode 100644 index 0000000..6522424 Binary files /dev/null and b/data/cards/cache/house/T81.png differ diff --git a/data/cards/homestead/H1.webp b/data/cards/homestead/H1.webp index 58fc06b..8583df6 100644 Binary files a/data/cards/homestead/H1.webp and b/data/cards/homestead/H1.webp differ diff --git a/data/cards/homestead/H10.webp b/data/cards/homestead/H10.webp index 2ef1b93..8d7c559 100644 Binary files a/data/cards/homestead/H10.webp and b/data/cards/homestead/H10.webp differ diff --git a/data/cards/homestead/H11.webp b/data/cards/homestead/H11.webp index 1a1f6a8..44c3fab 100644 Binary files a/data/cards/homestead/H11.webp and b/data/cards/homestead/H11.webp differ diff --git a/data/cards/homestead/H12.webp b/data/cards/homestead/H12.webp index 789bd96..2d2eb90 100644 Binary files a/data/cards/homestead/H12.webp and b/data/cards/homestead/H12.webp differ diff --git a/data/cards/homestead/H13.webp b/data/cards/homestead/H13.webp index f1cae70..0c64444 100644 Binary files a/data/cards/homestead/H13.webp and b/data/cards/homestead/H13.webp differ diff --git a/data/cards/homestead/H14.webp b/data/cards/homestead/H14.webp index 2bf9e49..bf19f00 100644 Binary files a/data/cards/homestead/H14.webp and b/data/cards/homestead/H14.webp differ diff --git a/data/cards/homestead/H15.webp b/data/cards/homestead/H15.webp index a085c0b..fc7c537 100644 Binary files a/data/cards/homestead/H15.webp and b/data/cards/homestead/H15.webp differ diff --git a/data/cards/homestead/H16.webp b/data/cards/homestead/H16.webp index 3d3cbd6..a0d9880 100644 Binary files a/data/cards/homestead/H16.webp and b/data/cards/homestead/H16.webp differ diff --git a/data/cards/homestead/H17.webp b/data/cards/homestead/H17.webp index a13e488..7f1c241 100644 Binary files a/data/cards/homestead/H17.webp and b/data/cards/homestead/H17.webp differ diff --git a/data/cards/homestead/H18.webp b/data/cards/homestead/H18.webp index 84be4d0..a87ec62 100644 Binary files a/data/cards/homestead/H18.webp and b/data/cards/homestead/H18.webp differ diff --git a/data/cards/homestead/H19.webp b/data/cards/homestead/H19.webp index 17fb055..5933109 100644 Binary files a/data/cards/homestead/H19.webp and b/data/cards/homestead/H19.webp differ diff --git a/data/cards/homestead/H2.webp b/data/cards/homestead/H2.webp index 94a6700..ec43849 100644 Binary files a/data/cards/homestead/H2.webp and b/data/cards/homestead/H2.webp differ diff --git a/data/cards/homestead/H20.webp b/data/cards/homestead/H20.webp index 155e82b..5a71838 100644 Binary files a/data/cards/homestead/H20.webp and b/data/cards/homestead/H20.webp differ diff --git a/data/cards/homestead/H21.webp b/data/cards/homestead/H21.webp index c10f902..23ec082 100644 Binary files a/data/cards/homestead/H21.webp and b/data/cards/homestead/H21.webp differ diff --git a/data/cards/homestead/H22.webp b/data/cards/homestead/H22.webp index 1b60b2a..129a9cd 100644 Binary files a/data/cards/homestead/H22.webp and b/data/cards/homestead/H22.webp differ diff --git a/data/cards/homestead/H23.webp b/data/cards/homestead/H23.webp index c666fe5..35fdc79 100644 Binary files a/data/cards/homestead/H23.webp and b/data/cards/homestead/H23.webp differ diff --git a/data/cards/homestead/H24.webp b/data/cards/homestead/H24.webp index 37aba85..ead9d41 100644 Binary files a/data/cards/homestead/H24.webp and b/data/cards/homestead/H24.webp differ diff --git a/data/cards/homestead/H25.webp b/data/cards/homestead/H25.webp index 0da60c2..8de6110 100644 Binary files a/data/cards/homestead/H25.webp and b/data/cards/homestead/H25.webp differ diff --git a/data/cards/homestead/H26.webp b/data/cards/homestead/H26.webp index a9f5cb7..86315a6 100644 Binary files a/data/cards/homestead/H26.webp and b/data/cards/homestead/H26.webp differ diff --git a/data/cards/homestead/H27.webp b/data/cards/homestead/H27.webp index c89383e..2848746 100644 Binary files a/data/cards/homestead/H27.webp and b/data/cards/homestead/H27.webp differ diff --git a/data/cards/homestead/H28.webp b/data/cards/homestead/H28.webp index 25896ee..d9feb19 100644 Binary files a/data/cards/homestead/H28.webp and b/data/cards/homestead/H28.webp differ diff --git a/data/cards/homestead/H29.webp b/data/cards/homestead/H29.webp index 4e37947..1ca6545 100644 Binary files a/data/cards/homestead/H29.webp and b/data/cards/homestead/H29.webp differ diff --git a/data/cards/homestead/H3.webp b/data/cards/homestead/H3.webp index 139879e..efa0898 100644 Binary files a/data/cards/homestead/H3.webp and b/data/cards/homestead/H3.webp differ diff --git a/data/cards/homestead/H30.webp b/data/cards/homestead/H30.webp index 612b900..a5cb91e 100644 Binary files a/data/cards/homestead/H30.webp and b/data/cards/homestead/H30.webp differ diff --git a/data/cards/homestead/H31.webp b/data/cards/homestead/H31.webp index 6e8e247..ce181d8 100644 Binary files a/data/cards/homestead/H31.webp and b/data/cards/homestead/H31.webp differ diff --git a/data/cards/homestead/H32.webp b/data/cards/homestead/H32.webp index 2053778..23cd43c 100644 Binary files a/data/cards/homestead/H32.webp and b/data/cards/homestead/H32.webp differ diff --git a/data/cards/homestead/H33.webp b/data/cards/homestead/H33.webp index 1184fcd..cbacded 100644 Binary files a/data/cards/homestead/H33.webp and b/data/cards/homestead/H33.webp differ diff --git a/data/cards/homestead/H34.webp b/data/cards/homestead/H34.webp index 2639e01..a3598a2 100644 Binary files a/data/cards/homestead/H34.webp and b/data/cards/homestead/H34.webp differ diff --git a/data/cards/homestead/H35.webp b/data/cards/homestead/H35.webp index 3803c4f..20dc496 100644 Binary files a/data/cards/homestead/H35.webp and b/data/cards/homestead/H35.webp differ diff --git a/data/cards/homestead/H36.webp b/data/cards/homestead/H36.webp index 47a80bc..44f8423 100644 Binary files a/data/cards/homestead/H36.webp and b/data/cards/homestead/H36.webp differ diff --git a/data/cards/homestead/H37.webp b/data/cards/homestead/H37.webp index ca7bd65..3a8a8ad 100644 Binary files a/data/cards/homestead/H37.webp and b/data/cards/homestead/H37.webp differ diff --git a/data/cards/homestead/H38.webp b/data/cards/homestead/H38.webp index 2967fb7..bbf7294 100644 Binary files a/data/cards/homestead/H38.webp and b/data/cards/homestead/H38.webp differ diff --git a/data/cards/homestead/H39.webp b/data/cards/homestead/H39.webp index 3166755..d843a0d 100644 Binary files a/data/cards/homestead/H39.webp and b/data/cards/homestead/H39.webp differ diff --git a/data/cards/homestead/H4.webp b/data/cards/homestead/H4.webp index 708264e..a2f77b0 100644 Binary files a/data/cards/homestead/H4.webp and b/data/cards/homestead/H4.webp differ diff --git a/data/cards/homestead/H40.webp b/data/cards/homestead/H40.webp index c6f03eb..f3954c7 100644 Binary files a/data/cards/homestead/H40.webp and b/data/cards/homestead/H40.webp differ diff --git a/data/cards/homestead/H41.webp b/data/cards/homestead/H41.webp index 5852b08..0333982 100644 Binary files a/data/cards/homestead/H41.webp and b/data/cards/homestead/H41.webp differ diff --git a/data/cards/homestead/H42.webp b/data/cards/homestead/H42.webp index 025eb61..5669a11 100644 Binary files a/data/cards/homestead/H42.webp and b/data/cards/homestead/H42.webp differ diff --git a/data/cards/homestead/H43.webp b/data/cards/homestead/H43.webp index b5b8d01..6eb117a 100644 Binary files a/data/cards/homestead/H43.webp and b/data/cards/homestead/H43.webp differ diff --git a/data/cards/homestead/H44.webp b/data/cards/homestead/H44.webp index ff17874..f56eab4 100644 Binary files a/data/cards/homestead/H44.webp and b/data/cards/homestead/H44.webp differ diff --git a/data/cards/homestead/H45.webp b/data/cards/homestead/H45.webp index 790877e..89bd659 100644 Binary files a/data/cards/homestead/H45.webp and b/data/cards/homestead/H45.webp differ diff --git a/data/cards/homestead/H46.webp b/data/cards/homestead/H46.webp index 8f7fbe5..760990e 100644 Binary files a/data/cards/homestead/H46.webp and b/data/cards/homestead/H46.webp differ diff --git a/data/cards/homestead/H47.webp b/data/cards/homestead/H47.webp index 1a6ea4f..1c12d19 100644 Binary files a/data/cards/homestead/H47.webp and b/data/cards/homestead/H47.webp differ diff --git a/data/cards/homestead/H48.webp b/data/cards/homestead/H48.webp index 5b6e5f6..b636727 100644 Binary files a/data/cards/homestead/H48.webp and b/data/cards/homestead/H48.webp differ diff --git a/data/cards/homestead/H49.webp b/data/cards/homestead/H49.webp index 8378b2d..ed7286f 100644 Binary files a/data/cards/homestead/H49.webp and b/data/cards/homestead/H49.webp differ diff --git a/data/cards/homestead/H5.webp b/data/cards/homestead/H5.webp index 97123cd..ef58148 100644 Binary files a/data/cards/homestead/H5.webp and b/data/cards/homestead/H5.webp differ diff --git a/data/cards/homestead/H50.webp b/data/cards/homestead/H50.webp index 90270d4..c310778 100644 Binary files a/data/cards/homestead/H50.webp and b/data/cards/homestead/H50.webp differ diff --git a/data/cards/homestead/H51.webp b/data/cards/homestead/H51.webp index 2a79cd3..c6a26b5 100644 Binary files a/data/cards/homestead/H51.webp and b/data/cards/homestead/H51.webp differ diff --git a/data/cards/homestead/H52.webp b/data/cards/homestead/H52.webp index d2411a5..7194a1a 100644 Binary files a/data/cards/homestead/H52.webp and b/data/cards/homestead/H52.webp differ diff --git a/data/cards/homestead/H53.webp b/data/cards/homestead/H53.webp new file mode 100644 index 0000000..b4bdbce Binary files /dev/null and b/data/cards/homestead/H53.webp differ diff --git a/data/cards/homestead/H54.webp b/data/cards/homestead/H54.webp new file mode 100644 index 0000000..cd6ca54 Binary files /dev/null and b/data/cards/homestead/H54.webp differ diff --git a/data/cards/homestead/H55.webp b/data/cards/homestead/H55.webp new file mode 100644 index 0000000..51f7f18 Binary files /dev/null and b/data/cards/homestead/H55.webp differ diff --git a/data/cards/homestead/H56.webp b/data/cards/homestead/H56.webp new file mode 100644 index 0000000..5643998 Binary files /dev/null and b/data/cards/homestead/H56.webp differ diff --git a/data/cards/homestead/H57.webp b/data/cards/homestead/H57.webp new file mode 100644 index 0000000..14f89d9 Binary files /dev/null and b/data/cards/homestead/H57.webp differ diff --git a/data/cards/homestead/H58.webp b/data/cards/homestead/H58.webp new file mode 100644 index 0000000..cc6df5c Binary files /dev/null and b/data/cards/homestead/H58.webp differ diff --git a/data/cards/homestead/H59.webp b/data/cards/homestead/H59.webp new file mode 100644 index 0000000..cceba7e Binary files /dev/null and b/data/cards/homestead/H59.webp differ diff --git a/data/cards/homestead/H6.webp b/data/cards/homestead/H6.webp index 06cf00b..90bcda1 100644 Binary files a/data/cards/homestead/H6.webp and b/data/cards/homestead/H6.webp differ diff --git a/data/cards/homestead/H60.webp b/data/cards/homestead/H60.webp new file mode 100644 index 0000000..4cfcb12 Binary files /dev/null and b/data/cards/homestead/H60.webp differ diff --git a/data/cards/homestead/H61.webp b/data/cards/homestead/H61.webp new file mode 100644 index 0000000..f721727 Binary files /dev/null and b/data/cards/homestead/H61.webp differ diff --git a/data/cards/homestead/H62.webp b/data/cards/homestead/H62.webp new file mode 100644 index 0000000..7125b3b Binary files /dev/null and b/data/cards/homestead/H62.webp differ diff --git a/data/cards/homestead/H63.webp b/data/cards/homestead/H63.webp new file mode 100644 index 0000000..cc239d0 Binary files /dev/null and b/data/cards/homestead/H63.webp differ diff --git a/data/cards/homestead/H64.webp b/data/cards/homestead/H64.webp new file mode 100644 index 0000000..e367fdf Binary files /dev/null and b/data/cards/homestead/H64.webp differ diff --git a/data/cards/homestead/H65.webp b/data/cards/homestead/H65.webp new file mode 100644 index 0000000..920ecfe Binary files /dev/null and b/data/cards/homestead/H65.webp differ diff --git a/data/cards/homestead/H66.webp b/data/cards/homestead/H66.webp new file mode 100644 index 0000000..d1b01a7 Binary files /dev/null and b/data/cards/homestead/H66.webp differ diff --git a/data/cards/homestead/H67.webp b/data/cards/homestead/H67.webp new file mode 100644 index 0000000..5a2d034 Binary files /dev/null and b/data/cards/homestead/H67.webp differ diff --git a/data/cards/homestead/H68.webp b/data/cards/homestead/H68.webp new file mode 100644 index 0000000..4d6307f Binary files /dev/null and b/data/cards/homestead/H68.webp differ diff --git a/data/cards/homestead/H69.webp b/data/cards/homestead/H69.webp new file mode 100644 index 0000000..010bfb1 Binary files /dev/null and b/data/cards/homestead/H69.webp differ diff --git a/data/cards/homestead/H7.webp b/data/cards/homestead/H7.webp index a6ceec0..1027492 100644 Binary files a/data/cards/homestead/H7.webp and b/data/cards/homestead/H7.webp differ diff --git a/data/cards/homestead/H70.webp b/data/cards/homestead/H70.webp new file mode 100644 index 0000000..bd4290f Binary files /dev/null and b/data/cards/homestead/H70.webp differ diff --git a/data/cards/homestead/H71.webp b/data/cards/homestead/H71.webp new file mode 100644 index 0000000..93e6c1a Binary files /dev/null and b/data/cards/homestead/H71.webp differ diff --git a/data/cards/homestead/H72.webp b/data/cards/homestead/H72.webp new file mode 100644 index 0000000..7b9b079 Binary files /dev/null and b/data/cards/homestead/H72.webp differ diff --git a/data/cards/homestead/H73.webp b/data/cards/homestead/H73.webp new file mode 100644 index 0000000..c8113c8 Binary files /dev/null and b/data/cards/homestead/H73.webp differ diff --git a/data/cards/homestead/H74.webp b/data/cards/homestead/H74.webp new file mode 100644 index 0000000..9c7d215 Binary files /dev/null and b/data/cards/homestead/H74.webp differ diff --git a/data/cards/homestead/H75.webp b/data/cards/homestead/H75.webp new file mode 100644 index 0000000..bf23def Binary files /dev/null and b/data/cards/homestead/H75.webp differ diff --git a/data/cards/homestead/H76.webp b/data/cards/homestead/H76.webp new file mode 100644 index 0000000..db26f75 Binary files /dev/null and b/data/cards/homestead/H76.webp differ diff --git a/data/cards/homestead/H8.webp b/data/cards/homestead/H8.webp index b26bc46..48ff2d3 100644 Binary files a/data/cards/homestead/H8.webp and b/data/cards/homestead/H8.webp differ diff --git a/data/cards/homestead/H9.webp b/data/cards/homestead/H9.webp index ebec8ad..dcd0b0e 100644 Binary files a/data/cards/homestead/H9.webp and b/data/cards/homestead/H9.webp differ diff --git a/data/cards/house/T1.webp b/data/cards/house/T1.webp index 765371b..0cfb8ac 100644 Binary files a/data/cards/house/T1.webp and b/data/cards/house/T1.webp differ diff --git a/data/cards/house/T10.webp b/data/cards/house/T10.webp index ecaf32f..19b3adc 100644 Binary files a/data/cards/house/T10.webp and b/data/cards/house/T10.webp differ diff --git a/data/cards/house/T11.webp b/data/cards/house/T11.webp index 69c7ac6..0ca5ebd 100644 Binary files a/data/cards/house/T11.webp and b/data/cards/house/T11.webp differ diff --git a/data/cards/house/T12.webp b/data/cards/house/T12.webp index 958c2b4..8567b3c 100644 Binary files a/data/cards/house/T12.webp and b/data/cards/house/T12.webp differ diff --git a/data/cards/house/T13.webp b/data/cards/house/T13.webp index f774e9b..f16bf9c 100644 Binary files a/data/cards/house/T13.webp and b/data/cards/house/T13.webp differ diff --git a/data/cards/house/T14.webp b/data/cards/house/T14.webp index 74bc57b..2d0446f 100644 Binary files a/data/cards/house/T14.webp and b/data/cards/house/T14.webp differ diff --git a/data/cards/house/T15.webp b/data/cards/house/T15.webp index 9fe2aad..0202bfd 100644 Binary files a/data/cards/house/T15.webp and b/data/cards/house/T15.webp differ diff --git a/data/cards/house/T16.webp b/data/cards/house/T16.webp index 4557717..5c7888b 100644 Binary files a/data/cards/house/T16.webp and b/data/cards/house/T16.webp differ diff --git a/data/cards/house/T17.webp b/data/cards/house/T17.webp index 0854e8e..f4ff860 100644 Binary files a/data/cards/house/T17.webp and b/data/cards/house/T17.webp differ diff --git a/data/cards/house/T18.webp b/data/cards/house/T18.webp index c25e84d..dfddb65 100644 Binary files a/data/cards/house/T18.webp and b/data/cards/house/T18.webp differ diff --git a/data/cards/house/T19.webp b/data/cards/house/T19.webp index 95d9b96..c112570 100644 Binary files a/data/cards/house/T19.webp and b/data/cards/house/T19.webp differ diff --git a/data/cards/house/T2.webp b/data/cards/house/T2.webp index 1fb5ed2..fed0cec 100644 Binary files a/data/cards/house/T2.webp and b/data/cards/house/T2.webp differ diff --git a/data/cards/house/T20.webp b/data/cards/house/T20.webp index 0a166ab..b4a57d4 100644 Binary files a/data/cards/house/T20.webp and b/data/cards/house/T20.webp differ diff --git a/data/cards/house/T21.webp b/data/cards/house/T21.webp index 65b6cc4..46e1b4d 100644 Binary files a/data/cards/house/T21.webp and b/data/cards/house/T21.webp differ diff --git a/data/cards/house/T22.webp b/data/cards/house/T22.webp index c22438a..8ec88e6 100644 Binary files a/data/cards/house/T22.webp and b/data/cards/house/T22.webp differ diff --git a/data/cards/house/T23.webp b/data/cards/house/T23.webp index bf01268..43e459a 100644 Binary files a/data/cards/house/T23.webp and b/data/cards/house/T23.webp differ diff --git a/data/cards/house/T24.webp b/data/cards/house/T24.webp new file mode 100644 index 0000000..be440cb Binary files /dev/null and b/data/cards/house/T24.webp differ diff --git a/data/cards/house/T25.webp b/data/cards/house/T25.webp index a349687..97e578d 100644 Binary files a/data/cards/house/T25.webp and b/data/cards/house/T25.webp differ diff --git a/data/cards/house/T26.webp b/data/cards/house/T26.webp index 5302b59..2830b3e 100644 Binary files a/data/cards/house/T26.webp and b/data/cards/house/T26.webp differ diff --git a/data/cards/house/T27.webp b/data/cards/house/T27.webp new file mode 100644 index 0000000..b263c9a Binary files /dev/null and b/data/cards/house/T27.webp differ diff --git a/data/cards/house/T28.webp b/data/cards/house/T28.webp index 7fd16ba..b6f0721 100644 Binary files a/data/cards/house/T28.webp and b/data/cards/house/T28.webp differ diff --git a/data/cards/house/T29.webp b/data/cards/house/T29.webp index c4e9ef9..b64189e 100644 Binary files a/data/cards/house/T29.webp and b/data/cards/house/T29.webp differ diff --git a/data/cards/house/T3.webp b/data/cards/house/T3.webp index 0b3d713..0018b68 100644 Binary files a/data/cards/house/T3.webp and b/data/cards/house/T3.webp differ diff --git a/data/cards/house/T30.webp b/data/cards/house/T30.webp index 42f42c9..0cc1711 100644 Binary files a/data/cards/house/T30.webp and b/data/cards/house/T30.webp differ diff --git a/data/cards/house/T31.webp b/data/cards/house/T31.webp index 92e4b20..2d88f81 100644 Binary files a/data/cards/house/T31.webp and b/data/cards/house/T31.webp differ diff --git a/data/cards/house/T32.webp b/data/cards/house/T32.webp index a263ab4..d2fa7cd 100644 Binary files a/data/cards/house/T32.webp and b/data/cards/house/T32.webp differ diff --git a/data/cards/house/T33.webp b/data/cards/house/T33.webp index 8a764a8..e2b7004 100644 Binary files a/data/cards/house/T33.webp and b/data/cards/house/T33.webp differ diff --git a/data/cards/house/T34.webp b/data/cards/house/T34.webp index 216ba87..16c8df8 100644 Binary files a/data/cards/house/T34.webp and b/data/cards/house/T34.webp differ diff --git a/data/cards/house/T35.webp b/data/cards/house/T35.webp index 6d69558..2396cee 100644 Binary files a/data/cards/house/T35.webp and b/data/cards/house/T35.webp differ diff --git a/data/cards/house/T36.webp b/data/cards/house/T36.webp index 1287a73..3608c64 100644 Binary files a/data/cards/house/T36.webp and b/data/cards/house/T36.webp differ diff --git a/data/cards/house/T37.webp b/data/cards/house/T37.webp index 3fd6ac0..16511c9 100644 Binary files a/data/cards/house/T37.webp and b/data/cards/house/T37.webp differ diff --git a/data/cards/house/T38.webp b/data/cards/house/T38.webp index e730667..382b1a4 100644 Binary files a/data/cards/house/T38.webp and b/data/cards/house/T38.webp differ diff --git a/data/cards/house/T39.webp b/data/cards/house/T39.webp index a5c8eca..1fd3429 100644 Binary files a/data/cards/house/T39.webp and b/data/cards/house/T39.webp differ diff --git a/data/cards/house/T4.webp b/data/cards/house/T4.webp index f419e40..546b744 100644 Binary files a/data/cards/house/T4.webp and b/data/cards/house/T4.webp differ diff --git a/data/cards/house/T40.webp b/data/cards/house/T40.webp index 315f9b6..762ebd9 100644 Binary files a/data/cards/house/T40.webp and b/data/cards/house/T40.webp differ diff --git a/data/cards/house/T41.webp b/data/cards/house/T41.webp index 0144420..7495f29 100644 Binary files a/data/cards/house/T41.webp and b/data/cards/house/T41.webp differ diff --git a/data/cards/house/T42.webp b/data/cards/house/T42.webp index 0829a34..9cce2cb 100644 Binary files a/data/cards/house/T42.webp and b/data/cards/house/T42.webp differ diff --git a/data/cards/house/T43.webp b/data/cards/house/T43.webp index ca4f3e3..faad372 100644 Binary files a/data/cards/house/T43.webp and b/data/cards/house/T43.webp differ diff --git a/data/cards/house/T44.webp b/data/cards/house/T44.webp index ce3f3f7..119c8f9 100644 Binary files a/data/cards/house/T44.webp and b/data/cards/house/T44.webp differ diff --git a/data/cards/house/T45.webp b/data/cards/house/T45.webp index 2b7cb63..3bad107 100644 Binary files a/data/cards/house/T45.webp and b/data/cards/house/T45.webp differ diff --git a/data/cards/house/T46.webp b/data/cards/house/T46.webp index 5f3e51e..270aaf8 100644 Binary files a/data/cards/house/T46.webp and b/data/cards/house/T46.webp differ diff --git a/data/cards/house/T47.webp b/data/cards/house/T47.webp index db89c1b..a23179d 100644 Binary files a/data/cards/house/T47.webp and b/data/cards/house/T47.webp differ diff --git a/data/cards/house/T48.webp b/data/cards/house/T48.webp index 51d8f3f..4414475 100644 Binary files a/data/cards/house/T48.webp and b/data/cards/house/T48.webp differ diff --git a/data/cards/house/T49.webp b/data/cards/house/T49.webp index ed285d6..9ecf9fd 100644 Binary files a/data/cards/house/T49.webp and b/data/cards/house/T49.webp differ diff --git a/data/cards/house/T5.webp b/data/cards/house/T5.webp index fdcc9b9..276a6bc 100644 Binary files a/data/cards/house/T5.webp and b/data/cards/house/T5.webp differ diff --git a/data/cards/house/T50.webp b/data/cards/house/T50.webp index d001e39..2848be3 100644 Binary files a/data/cards/house/T50.webp and b/data/cards/house/T50.webp differ diff --git a/data/cards/house/T51.webp b/data/cards/house/T51.webp index eb22882..a12f7a2 100644 Binary files a/data/cards/house/T51.webp and b/data/cards/house/T51.webp differ diff --git a/data/cards/house/T52.webp b/data/cards/house/T52.webp index 34fbff2..dd8e2da 100644 Binary files a/data/cards/house/T52.webp and b/data/cards/house/T52.webp differ diff --git a/data/cards/house/T53.webp b/data/cards/house/T53.webp index 14f7207..f29b631 100644 Binary files a/data/cards/house/T53.webp and b/data/cards/house/T53.webp differ diff --git a/data/cards/house/T54.webp b/data/cards/house/T54.webp index 3c91acd..c5dac73 100644 Binary files a/data/cards/house/T54.webp and b/data/cards/house/T54.webp differ diff --git a/data/cards/house/T55.webp b/data/cards/house/T55.webp index d8f6173..47474df 100644 Binary files a/data/cards/house/T55.webp and b/data/cards/house/T55.webp differ diff --git a/data/cards/house/T56.webp b/data/cards/house/T56.webp index 32860ec..2c57803 100644 Binary files a/data/cards/house/T56.webp and b/data/cards/house/T56.webp differ diff --git a/data/cards/house/T57.webp b/data/cards/house/T57.webp index 15099bb..264ec11 100644 Binary files a/data/cards/house/T57.webp and b/data/cards/house/T57.webp differ diff --git a/data/cards/house/T58.webp b/data/cards/house/T58.webp index c1738b1..60e5aef 100644 Binary files a/data/cards/house/T58.webp and b/data/cards/house/T58.webp differ diff --git a/data/cards/house/T59.webp b/data/cards/house/T59.webp index a945fed..2dbb9d0 100644 Binary files a/data/cards/house/T59.webp and b/data/cards/house/T59.webp differ diff --git a/data/cards/house/T6.webp b/data/cards/house/T6.webp index 63e2059..30e3c3c 100644 Binary files a/data/cards/house/T6.webp and b/data/cards/house/T6.webp differ diff --git a/data/cards/house/T60.webp b/data/cards/house/T60.webp index 3ebb2cc..9d2319c 100644 Binary files a/data/cards/house/T60.webp and b/data/cards/house/T60.webp differ diff --git a/data/cards/house/T61.webp b/data/cards/house/T61.webp index 6183c95..e29a1bd 100644 Binary files a/data/cards/house/T61.webp and b/data/cards/house/T61.webp differ diff --git a/data/cards/house/T62.webp b/data/cards/house/T62.webp index 74c3e6c..194feef 100644 Binary files a/data/cards/house/T62.webp and b/data/cards/house/T62.webp differ diff --git a/data/cards/house/T63.webp b/data/cards/house/T63.webp index 71d53fd..997226e 100644 Binary files a/data/cards/house/T63.webp and b/data/cards/house/T63.webp differ diff --git a/data/cards/house/T64.webp b/data/cards/house/T64.webp index 2170367..fa70e8e 100644 Binary files a/data/cards/house/T64.webp and b/data/cards/house/T64.webp differ diff --git a/data/cards/house/T65.webp b/data/cards/house/T65.webp index f225eaf..cbeb6ef 100644 Binary files a/data/cards/house/T65.webp and b/data/cards/house/T65.webp differ diff --git a/data/cards/house/T66.webp b/data/cards/house/T66.webp index 7c63e5f..da81347 100644 Binary files a/data/cards/house/T66.webp and b/data/cards/house/T66.webp differ diff --git a/data/cards/house/T67.webp b/data/cards/house/T67.webp index a91ae19..2ad3ebc 100644 Binary files a/data/cards/house/T67.webp and b/data/cards/house/T67.webp differ diff --git a/data/cards/house/T68.webp b/data/cards/house/T68.webp index 3842fba..79e803a 100644 Binary files a/data/cards/house/T68.webp and b/data/cards/house/T68.webp differ diff --git a/data/cards/house/T69.webp b/data/cards/house/T69.webp index 5ad0159..27a54a7 100644 Binary files a/data/cards/house/T69.webp and b/data/cards/house/T69.webp differ diff --git a/data/cards/house/T7.webp b/data/cards/house/T7.webp index f678bef..cf56bb4 100644 Binary files a/data/cards/house/T7.webp and b/data/cards/house/T7.webp differ diff --git a/data/cards/house/T70.webp b/data/cards/house/T70.webp index 1dc2a84..2fa754d 100644 Binary files a/data/cards/house/T70.webp and b/data/cards/house/T70.webp differ diff --git a/data/cards/house/T71.webp b/data/cards/house/T71.webp index acaaedc..499d4da 100644 Binary files a/data/cards/house/T71.webp and b/data/cards/house/T71.webp differ diff --git a/data/cards/house/T72.webp b/data/cards/house/T72.webp index 9993529..be0d6d7 100644 Binary files a/data/cards/house/T72.webp and b/data/cards/house/T72.webp differ diff --git a/data/cards/house/T73.webp b/data/cards/house/T73.webp index 32863f5..b204572 100644 Binary files a/data/cards/house/T73.webp and b/data/cards/house/T73.webp differ diff --git a/data/cards/house/T74.webp b/data/cards/house/T74.webp index fafa643..23b4cda 100644 Binary files a/data/cards/house/T74.webp and b/data/cards/house/T74.webp differ diff --git a/data/cards/house/T75.webp b/data/cards/house/T75.webp index 966c0fa..d21a463 100644 Binary files a/data/cards/house/T75.webp and b/data/cards/house/T75.webp differ diff --git a/data/cards/house/T76.webp b/data/cards/house/T76.webp index 305de2f..82ab670 100644 Binary files a/data/cards/house/T76.webp and b/data/cards/house/T76.webp differ diff --git a/data/cards/house/T77.webp b/data/cards/house/T77.webp index ff295e5..9d1381a 100644 Binary files a/data/cards/house/T77.webp and b/data/cards/house/T77.webp differ diff --git a/data/cards/house/T78.webp b/data/cards/house/T78.webp index ac70fc3..05a2e13 100644 Binary files a/data/cards/house/T78.webp and b/data/cards/house/T78.webp differ diff --git a/data/cards/house/T79.webp b/data/cards/house/T79.webp index 15cc4b2..01730fe 100644 Binary files a/data/cards/house/T79.webp and b/data/cards/house/T79.webp differ diff --git a/data/cards/house/T8.webp b/data/cards/house/T8.webp index dd7979e..6446711 100644 Binary files a/data/cards/house/T8.webp and b/data/cards/house/T8.webp differ diff --git a/data/cards/house/T80.webp b/data/cards/house/T80.webp index 4401e30..99b3d2b 100644 Binary files a/data/cards/house/T80.webp and b/data/cards/house/T80.webp differ diff --git a/data/cards/house/T81.webp b/data/cards/house/T81.webp new file mode 100644 index 0000000..17b24f3 Binary files /dev/null and b/data/cards/house/T81.webp differ diff --git a/data/cards/house/T9.webp b/data/cards/house/T9.webp index 3f92f49..7a7da9e 100644 Binary files a/data/cards/house/T9.webp and b/data/cards/house/T9.webp differ diff --git a/data/prometheus.yml b/data/prometheus.yml new file mode 100644 index 0000000..fa41064 --- /dev/null +++ b/data/prometheus.yml @@ -0,0 +1,7 @@ +global: + scrape_interval: 5s + +scrape_configs: + - job_name: 'pushgateway' + static_configs: + - targets: ['pushgateway:9091'] diff --git a/docker-compose.yml b/docker-compose.yml index 72e894d..1f36d9c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -34,6 +34,8 @@ services: shm_size: '1gb' networks: - network + depends_on: + - metrics ws: image: sheep-service/ws @@ -49,6 +51,54 @@ services: networks: - network + metrics: + image: sheep-service/metrics + build: ./metrics + ports: + - "4005:4005" # HTTP push + - "4006:4006" # WebSocket + networks: + - network + depends_on: + - pushgateway + + pushgateway: + image: prom/pushgateway + ports: + - "4007:9091" + networks: + - network + + prometheus: + image: prom/prometheus + volumes: + - "${DATA_PATH:-./data}/prometheus.yml:/etc/prometheus/prometheus.yml" + ports: + - "4008:9090" + networks: + - network + depends_on: + - pushgateway + command: + - "--config.file=/etc/prometheus/prometheus.yml" + - "--storage.tsdb.path=/prometheus" + - "--storage.tsdb.retention.time=7d" + + grafana: + image: grafana/grafana + ports: + - "4009:3000" + networks: + - network + depends_on: + - prometheus + environment: + - GF_SERVER_ROOT_URL=%(protocol)s://%(domain)s/grafana/ + - GF_SECURITY_ADMIN_USER=${ADMIN_USER} + - GF_SECURITY_ADMIN_PASSWORD=${ADMIN_TOKEN} + volumes: + - ${DATA_PATH:-./data}/grafana:/var/lib/grafana + nginx: image: nginx:latest restart: always @@ -66,6 +116,8 @@ services: command: /bin/sh -c "envsubst '\$DOMAIN' < /etc/nginx/templates/default.conf.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'" networks: - network + depends_on: + - grafana cron: image: sheep-service/cron diff --git a/metrics/Dockerfile b/metrics/Dockerfile new file mode 100644 index 0000000..fc9b222 --- /dev/null +++ b/metrics/Dockerfile @@ -0,0 +1,14 @@ +FROM node:20.18 + +WORKDIR /app + +COPY package.json package-lock.json ./ + +RUN npm install + +COPY . . + +EXPOSE 4005 +EXPOSE 4006 + +CMD npm start diff --git a/metrics/metrics.js b/metrics/metrics.js new file mode 100644 index 0000000..ca9d111 --- /dev/null +++ b/metrics/metrics.js @@ -0,0 +1,133 @@ +const express = require("express"); +const cors = require("cors"); +const WebSocket = require("ws"); +const app = express(); + +const PORT_HTTP = 4005; +const PORT_WS = 4006; +const PUSHGATEWAY = "http://pushgateway:9091"; + +// --- HTTP server --- +app.use(cors({ origin: "*", methods: ["GET", "POST"], allowedHeaders: ["Content-Type"], credentials: true })); +app.use(express.json({ limit: "50mb" })); + +app.post("/push", (req, res) => { + const metric = req.body; + if (metric) pushToProm(metric); + res.send("ok"); +}); + +// --- WS server --- +const wss = new WebSocket.Server({ port: PORT_WS }); +wss.on("connection", ws => { + console.log("New WS connection. Online users:", wss.clients.size); + pushOnlineCount(); + + ws.on("message", msg => { + try { + const m = JSON.parse(msg); + pushToProm(m); + } catch (e) { + console.error("Invalid WS message:", e); + } + }); + + ws.on("close", () => pushOnlineCount()); +}); + +// --- Push metrics to Pushgateway --- +async function pushToProm(metric) { + if (!metric || !metric.type) return; + + const lines = []; + let job = "webapp"; // default job + let groupingKey = {}; + + switch (metric.type) { + case "frontend_metrics": + job = "webapp_frontend"; + + lines.push(`# HELP frontend_load_time Frontend page load time in ms`); + lines.push(`# TYPE frontend_load_time gauge`); + lines.push(`frontend_load_time{instance="${metric.id || 'default'}"} ${metric.navigation?.loadEventEnd || 0}`); + + if (metric.memory?.usedJSHeapSize) { + lines.push(`# HELP frontend_memory_used JS heap used in MB`); + lines.push(`# TYPE frontend_memory_used gauge`); + lines.push(`frontend_memory_used{instance="${metric.id || 'default'}"} ${metric.memory.usedJSHeapSize / 1024 / 1024}`); + } + + if (metric.resources?.length) { + lines.push(`# HELP frontend_resource_count Number of resources loaded`); + lines.push(`# TYPE frontend_resource_count gauge`); + lines.push(`frontend_resource_count{instance="${metric.id || 'default'}"} ${metric.resources.length}`); + } + + break; + + case "rest": + job = "webapp_api"; + lines.push(`# HELP rest_request_duration_ms REST request duration in ms`); + lines.push(`# TYPE rest_request_duration_ms gauge`); + lines.push(`rest_request_duration_ms{path="${metric.path}",status="${metric.status}"} ${metric.time}`); + break; + + case "ws_in": + job = "webapp_ws"; + lines.push(`# HELP ws_in_bytes_total WS bytes in`); + lines.push(`# TYPE ws_in_bytes_total counter`); + lines.push(`ws_in_bytes_total ${metric.length}`); + break; + + case "ws_out": + job = "webapp_ws"; + lines.push(`# HELP ws_out_bytes_total WS bytes out`); + lines.push(`# TYPE ws_out_bytes_total counter`); + lines.push(`ws_out_bytes_total ${metric.length}`); + break; + + case "connection_status": + job = "webapp_connection"; + lines.push(`# HELP users_online Users online`); + lines.push(`# TYPE users_online gauge`); + lines.push(`users_online ${metric.count || wss.clients.size}`); + + const putBody = lines.join("\n") + "\n"; + + // Отправляем как PUT для Gauge, чтобы сбросить старые значения + return await pushToPrometheus(`${PUSHGATEWAY}/metrics/job/${job}`, putBody, "PUT"); + } + + const body = lines.join("\n") + "\n"; + console.log(`Pushing metric for job=${job}:\n${body}\n`); + + // Используем POST по умолчанию для инкремента/добавления + await pushToPrometheus(`${PUSHGATEWAY}/metrics/job/${job}`, body, "POST"); +} + +async function pushToPrometheus(url, body, method) { + try { + const response = await fetch(url, { + method: method, + headers: { "Content-Type": "text/plain" }, + body + }); + if (response.status !== 200) { + console.error(`PushGateway error (${method} ${url}):`, response.status, await response.text()); + } + } catch (err) { + console.error("PushGateway network error:", err.message); + } +} + + +function pushOnlineCount() { + pushToProm({ type: "connection_status", count: wss.clients.size }); +} + +// --- Start HTTP server --- +app.listen(PORT_HTTP, () => console.log("Metrics HTTP listening on", PORT_HTTP)); +console.log("Metrics WS listening on", PORT_WS); + +// Запуск интервала после инициализации wss +setInterval(pushOnlineCount, 5000); \ No newline at end of file diff --git a/metrics/package-lock.json b/metrics/package-lock.json new file mode 100644 index 0000000..9a8b170 --- /dev/null +++ b/metrics/package-lock.json @@ -0,0 +1,796 @@ +{ + "name": "metrics", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "metrics", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "cors": "^2.8.5", + "express": "^5.2.1", + "ws": "^8.18.3" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/body-parser": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.1.tgz", + "integrity": "sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.0.tgz", + "integrity": "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/send": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", + "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, + "node_modules/ws": { + "version": "8.18.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", + "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/metrics/package.json b/metrics/package.json new file mode 100644 index 0000000..cbd543c --- /dev/null +++ b/metrics/package.json @@ -0,0 +1,16 @@ +{ + "name": "metrics", + "version": "1.0.0", + "main": "metrics.js", + "scripts": { + "start": "node metrics.js" + }, + "author": "", + "license": "ISC", + "description": "", + "dependencies": { + "cors": "^2.8.5", + "express": "^5.2.1", + "ws": "^8.18.3" + } +} diff --git a/nginx/default.conf.template b/nginx/default.conf.template index 2c0b94a..65041b4 100644 --- a/nginx/default.conf.template +++ b/nginx/default.conf.template @@ -10,6 +10,10 @@ upstream ws_backend { server ws:4004; } +upstream metrics_backend { + server metrics:4006; +} + # Загальні CORS-заголовки map $request_method $cors_preflight { OPTIONS 1; @@ -54,6 +58,25 @@ server { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } + # Metrics + location /metrics { + proxy_pass http://metrics_backend$request_uri; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } + + # Grafana + location /grafana/ { + proxy_pass http://grafana:3000/; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + } + # Frontend location / { proxy_pass http://frontend$request_uri; diff --git a/web/config.js b/web/config.js index 3286ac1..79e425e 100644 --- a/web/config.js +++ b/web/config.js @@ -1,5 +1,6 @@ const CONFIG = { "web": "https://test.sheep-service.com/", "api": "https://test.sheep-service.com/api/", - "wss": "wss://test.sheep-service.com/ws" + "wss": "wss://test.sheep-service.com/ws", + "metrics": "wss://test.sheep-service.com/metrics" } \ No newline at end of file diff --git a/web/css/main.css b/web/css/main.css index 70847c0..f038f02 100644 --- a/web/css/main.css +++ b/web/css/main.css @@ -73,6 +73,7 @@ margin: 0; font-weight: 400; outline: none; + -webkit-text-size-adjust: 100%; } *:disabled { @@ -419,76 +420,6 @@ body.modal-open { } - - -/* Уведомление и кнопка обновления приложения */ -#update_banner { - height: 55px; - transition: .3s ease; -} - -#update_banner .content { - margin: 0 auto; - max-width: 340px; - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; -} - -#update_banner .headline { - font-weight: 800; - font-size: var(--FontSize4); - color: var(--PrimaryColorText); - font-family: 'Roboto', sans-serif; - margin-bottom: 5px; - opacity: 0.9; -} - -#update_banner .subhead { - font-size: var(--FontSize2); - text-align: center; - color: var(--PrimaryColorText); - font-family: 'Roboto', sans-serif; -} - -#update_banner[data-state="noupdate"] { - display: none; -} - -#update_banner[data-state="updateavailable"] { - display: flex; - cursor: pointer; - background-color: var(--PrimaryColor); - color: var(--PrimaryColorText); - transition: .3s ease; - opacity: 0.95; - z-index: 9999; - position: fixed; - width: 350px; - margin: 10px; - padding: 5px; - border-radius: var(--border-radius); - right: 0; -} - -#update_banner_icon { - display: none; -} - -#update_banner_icon svg { - padding: 0px 50px; - width: 25px; - margin: -4px; - fill: var(--PrimaryColorText); -} - -@media (max-width: 700px) { - #update_banner[data-state="updateavailable"] { - width: calc(100% - 30px); - } -} - /* Стили для меню */ #navigation { position: fixed; diff --git a/web/index.html b/web/index.html index 413f488..719a6bd 100644 --- a/web/index.html +++ b/web/index.html @@ -41,6 +41,10 @@ + + + + @@ -59,6 +63,8 @@ + + @@ -117,6 +123,9 @@ + + + @@ -169,39 +178,12 @@ - -
-
-
-
-
- - - - - - -
-
-
+ +
diff --git a/web/lib/app.js b/web/lib/app.js index 2257650..cb7e3eb 100644 --- a/web/lib/app.js +++ b/web/lib/app.js @@ -1,6 +1,10 @@ let USER = {}; +let page = "Home"; let swRegistration = null; +// Реєструємо CustomElements +const Notifier = document.getElementById('notif-manager'); + // Определение ID главного блока let app = document.getElementById('app'); @@ -59,7 +63,7 @@ window.addEventListener('load', async function () { return response.json(); }); - console.log("USER Info: ", USER); + console.log("[APP] USER Info: ", USER); if (USER.possibilities.can_view_sheeps) document.getElementById("li-sheeps").style.display = ""; @@ -72,13 +76,39 @@ window.addEventListener('load', async function () { if (Cloud.socket) Cloud.socket.close(1000, "Перезапуск з'єднання"); Cloud.start(); - + editFontStyle(); Router.check().listen().delegateLinks(); + + setupFrontendMetrics(); } }); +let offlineNode = null; +window.addEventListener("offline", () => { + console.log("[APP] Інтернет зник"); + offlineNode = Notifier.error({ + title: 'Оффлайн', + text: 'Втрачено з\'єднання з інтернетом' + }, { timeout: 0, lock: true }); +}); + +window.addEventListener("online", () => { + console.log("[APP] Інтернет з'явився"); + if (offlineNode) { + Notifier._removeNode(offlineNode); + offlineNode = null; + } + Notifier.success({ + title: 'Онлайн', + text: 'Інтернет знову працює' + }, { timeout: 3000 }); + + if (Cloud.socket) Cloud.socket.close(1000, "Перезапуск з'єднання"); + Cloud.start(); +}); + function editFontStyle() { let fontSize = localStorage.getItem("fontSize") ? localStorage.getItem("fontSize") @@ -153,7 +183,7 @@ document.getElementById("pwa-install-button").addEventListener("click", async () deferredPrompt.prompt(); const { outcome } = await deferredPrompt.userChoice; - console.log(`Результат встановлення PWA: ${outcome}`); + console.log(`[APP] Результат встановлення PWA: ${outcome}`); closePopup(); }); @@ -172,28 +202,26 @@ function closePopup() { if ('serviceWorker' in navigator) { let refreshing = false; + let updateNode = null; - const showUpdateBanner = sw => { - const banner = document.getElementById('update_banner'); - if (!banner) return; + const updateCache = sw => { + if (updateNode) { + Notifier._removeNode(updateNode); + updateNode = null; + } - banner.dataset.state = 'updateavailable'; - banner.querySelector('.headline').textContent = 'Доступне оновлення'; - banner.querySelector('.subhead').textContent = 'Натисніть, щоб оновити додаток до останньої версії!'; + Notifier.warn({ title: `Завантаження оновлення`, text: `Додаток буде перезавантажено!` }, { timeout: 3000 }); - banner.addEventListener('click', () => { - banner.querySelector('.headline').textContent = ''; - banner.querySelector('.subhead').textContent = ''; - banner.querySelector('#update_banner_icon').style.display = 'block'; - - sw.postMessage('skipWaiting'); // активує новий SW - sw.postMessage('updateCache'); // оновлює кеш - }); + sw.postMessage('skipWaiting'); // активує новий SW + sw.postMessage('updateCache'); // оновлює кеш }; + navigator.serviceWorker.register('/sw.js').then(reg => { // якщо є waiting SW, показуємо банер - if (reg.waiting) showUpdateBanner(reg.waiting); + if (reg.waiting) { + updateNode = Notifier.click({ title: `Доступне оновлення`, text: `Натисніть, щоб оновити додаток до останньої версії!` }, { type: 'info', f: () => updateCache(reg.waiting), timeout: 0 }); + } // слідкуємо за новим воркером reg.addEventListener('updatefound', () => { @@ -202,7 +230,7 @@ if ('serviceWorker' in navigator) { newWorker.addEventListener('statechange', () => { if (newWorker.state === 'installed' && reg.waiting) { - showUpdateBanner(reg.waiting); // лише показ банера + updateNode = Notifier.click({ title: `Доступне оновлення`, text: `Натисніть, щоб оновити додаток до останньої версії!` }, { type: 'info', f: () => updateCache(reg.waiting), timeout: 0 }); } }); }); @@ -213,5 +241,5 @@ if ('serviceWorker' in navigator) { window.location.reload(); // відбувається ТІЛЬКИ після skipWaiting }); - }).catch(err => console.error('Помилка реєстрації SW:', err)); + }).catch(err => console.error('[ServiceWorker] Помилка реєстрації SW:', err)); } \ No newline at end of file diff --git a/web/lib/components/cloud.js b/web/lib/components/cloud.js index f159636..8164139 100644 --- a/web/lib/components/cloud.js +++ b/web/lib/components/cloud.js @@ -9,11 +9,13 @@ const Cloud = { Cloud.status = 'sync'; const uuid = localStorage.getItem("uuid"); + if(!navigator.onLine) alert("[APP] Інтернет з'єднання відсутнє!") + if (Cloud.socket && Cloud.socket.readyState <= 1) return; const ws = new WebSocket(CONFIG.wss, uuid); Cloud.socket = ws; - + ws.onopen = () => { console.log("[WebSocket] З'єднання встановлено"); Cloud.status = 'ok'; @@ -25,10 +27,10 @@ const Cloud = { } })); - if(Cloud.reconnecting == true) { - Router.navigate(location.pathname); + if (Cloud.reconnecting == true) { + Cloud.reconnect(); } - + Cloud.reconnecting = true; Cloud.reconnectAttempts = 0; clearTimeout(Cloud.reconnectTimeout); @@ -37,7 +39,7 @@ const Cloud = { ws.onmessage = (e) => { const data = JSON.parse(e.data); if (data.event === 'user_connected' && data.user.id !== USER.id) { - console.log(`Новий користувач: ${data.user.name}`); + console.log(`[WebSocket] Новий користувач: ${data.user.name}`); } if (data.event === 'message') { switch (data.type) { @@ -54,7 +56,7 @@ const Cloud = { case "stand_update": Stand_card.cloud.update(data); break; - + default: break; } @@ -65,7 +67,7 @@ const Cloud = { console.warn("[WebSocket] З'єднання розірвано"); Cloud.status = 'err'; - if (!Cloud.reconnecting) return; // защита от дублирования + if (!Cloud.reconnecting) return; // захист від дублювання if (Cloud.reconnectAttempts < 5) { Cloud.reconnectAttempts++; @@ -73,7 +75,7 @@ const Cloud = { Cloud.reconnectTimeout = setTimeout(() => { Cloud.start(); - }, 1000); + }, 500); } else { Cloud.reconnecting = false; @@ -90,6 +92,19 @@ const Cloud = { ws.onerror = (err) => { console.error("[WebSocket] Помилка", err); Cloud.status = 'err'; + ws.close(); }; }, + + async reconnect(){ + switch (page) { + case "Territory_card": + Territory_card.reload(); + break; + + default: + Router.navigate(location.pathname); + break; + } + } } \ No newline at end of file diff --git a/web/lib/components/metrics.js b/web/lib/components/metrics.js new file mode 100644 index 0000000..0a9d93e --- /dev/null +++ b/web/lib/components/metrics.js @@ -0,0 +1,56 @@ +let mws; +const RECONNECT_INTERVAL = 3000; +let isConnectedMetrics = false; + +function setupFrontendMetrics() { + console.log("[Metrics] Спроба підключення до метрик..."); + mws = new WebSocket(CONFIG.metrics); + + mws.onopen = () => { + console.log("[Metrics] З'єднання встановлено"); + isConnectedMetrics = true; + + // Відправляємо один раз навігацію та ресурси + sendMetrics(); + }; + + mws.onclose = () => { + console.warn("[Metrics] З'єднання розірвано"); + console.log(`[Metrics] Спроба перепідключення`); + isConnectedMetrics = false; + // Спроба перепідключення через заданий інтервал + setTimeout(setupFrontendMetrics, RECONNECT_INTERVAL); + }; + + mws.onerror = (err) => { + console.error("[Metrics] Помилка", err); + mws.close(); // Примусово закриваємо для запуску логіки перепідключення + }; +} + +async function sendMetrics() { + if (isConnectedMetrics) { + const perf = performance; + + const payload = { + type: "frontend_metrics", + memory: perf.memory || null, + resources: perf.getEntriesByType("resource").slice(0, 500), + id: USER.id + }; + mws.send(JSON.stringify(payload)); + } +} + +window.addEventListener('popstate', () => { + console.log("[Metrics] Запуск sendMetrics після popstate"); + sendMetrics(); +}); + +window.addEventListener('click', (e) => { + const target = e.target.closest('[data-route]'); + if (!target || !target.href) return; + + console.log("[Metrics] Запуск sendMetrics після click"); + sendMetrics(); +}); \ No newline at end of file diff --git a/web/lib/components/webPush.js b/web/lib/components/webPush.js index 14b329b..1b4f9fb 100644 --- a/web/lib/components/webPush.js +++ b/web/lib/components/webPush.js @@ -2,7 +2,7 @@ const webPush = { async init() { if (!('serviceWorker' in navigator) || !('PushManager' in window)) { - console.error('Push повідомлення не підтримуються'); + console.error('[WebPush] Push повідомлення не підтримуються'); return; } @@ -37,7 +37,7 @@ const webPush = { // Запитуємо дозвіл const permission = await Notification.requestPermission(); if (permission !== 'granted') { - console.warn('Push повідомлення заборонено користувачем'); + console.warn('[WebPush] Push повідомлення заборонено користувачем'); return; } @@ -63,15 +63,15 @@ const webPush = { body: JSON.stringify({ subscription, device: deviceInfo }) }); - console.log('Push підписка готова:', subscription); + console.log('[WebPush] Push підписка готова:', subscription); - console.log('Створено нову підписку'); + console.log('[WebPush] Створено нову підписку'); } else { - console.log('Підписка вже існує'); + console.log('[WebPush] Підписка вже існує'); } } catch (err) { - console.error('Помилка ініціалізації push:', err); + console.error('[WebPush] Помилка ініціалізації push:', err); } }, @@ -85,7 +85,7 @@ const webPush = { const success = await subscription.unsubscribe(); if (success) { - console.log("Локальна підписка скасована"); + console.log("[WebPush] Локальна підписка скасована"); // повідомляємо сервер await fetch(`${CONFIG.api}push//unsubscribe`, { @@ -98,7 +98,7 @@ const webPush = { }); } } else { - console.log("Підписки немає"); + console.log("[WebPush] Підписки немає"); } } } \ No newline at end of file diff --git a/web/lib/customElements/notification.js b/web/lib/customElements/notification.js new file mode 100644 index 0000000..8e1103f --- /dev/null +++ b/web/lib/customElements/notification.js @@ -0,0 +1,326 @@ +class AppNotificationContainer extends HTMLElement { + constructor() { + super(); + this.attachShadow({ mode: 'open' }); + + // Настройки по умолчанию + this._timeout = 4000; + this._maxVisible = 5; + this._position = 'top-right'; + this._mobileBottomEnabled = false; + + this._container = document.createElement('div'); + this._container.className = 'app-notification-container'; + this.shadowRoot.appendChild(this._container); + + this._insertStyles(); + + this._icons = { + info: ``, + success: ``, + warn: ` `, + error: `` + }; + } + + static get observedAttributes() { + return ['timeout', 'max-visible', 'position', 'mobile-position']; + } + + connectedCallback() { + this._updateSettings(); + } + + attributeChangedCallback(name, oldValue, newValue) { + if (oldValue !== newValue) { + this._updateSettings(); + } + } + + _updateSettings() { + this._position = this.getAttribute('position') || 'top-right'; + this._maxVisible = parseInt(this.getAttribute('max-visible')) || 5; + this._timeout = parseInt(this.getAttribute('timeout')) || 4000; + + const mobilePosAttr = this.getAttribute('mobile-position'); + // Если атрибут установлен в 'bottom' или присутствует (как пустая строка, если это булевый атрибут) + this._mobileBottomEnabled = mobilePosAttr === 'bottom' || mobilePosAttr === ''; + + this._container.setAttribute('data-position', this._position); + + this._applyMobileStyles(); + } + + /** + * Динамически применяет класс, который активирует мобильные стили "только снизу". + */ + _applyMobileStyles() { + if (this._mobileBottomEnabled) { + this._container.classList.add('mobile-bottom'); + } else { + this._container.classList.remove('mobile-bottom'); + } + } + + /** + * Публичный метод для изменения настройки мобильной позиции во время выполнения. + * @param {boolean} enable - true, чтобы принудительно устанавливать позицию снизу на мобильных, false, чтобы использовать обычные @media стили. + */ + setMobileBottom(enable) { + this._mobileBottomEnabled = !!enable; + this._applyMobileStyles(); + } + + show(message, options = {}) { + const { + type = 'info', + timeout = this._timeout, + title, + onClick, + lock + } = options; + + const content = typeof message === 'string' + ? { title: title || '', text: message } + : message; + + while (this._container.children.length >= this._maxVisible) { + const first = this._container.firstElementChild; + if (first) first.remove(); + else break; + } + + const node = document.createElement('div'); + node.className = `app-notification ${type}`; + if (onClick) node.style.cursor = "pointer" + + const icon = document.createElement('div'); + icon.className = 'icon'; + icon.innerHTML = this._icons[type] || this._icons.info; + + const body = document.createElement('div'); + body.className = 'body'; + if (content.title) { + const t = document.createElement('div'); + t.className = 'title'; + t.textContent = content.title; + body.appendChild(t); + } + const txt = document.createElement('div'); + txt.className = 'text'; + txt.textContent = content.text || ''; + body.appendChild(txt); + + node.appendChild(icon); + node.appendChild(body); + + if (!onClick && !lock) { + const closeDiv = document.createElement('div'); + closeDiv.className = 'blockClose'; + node.appendChild(closeDiv); + + const closeBtn = document.createElement('button'); + closeBtn.className = 'close'; + closeBtn.setAttribute('aria-label', 'Закрыть уведомление'); + closeBtn.innerHTML = ''; + closeDiv.appendChild(closeBtn); + closeBtn.addEventListener('click', () => this._removeNode(node)); + } + + this._container.appendChild(node); + requestAnimationFrame(() => node.classList.add('show')); + + let timer = null; + const startTimer = () => { + if (timeout === 0) return; + timer = setTimeout(() => this._removeNode(node), timeout); + }; + const clearTimer = () => { if (timer) { clearTimeout(timer); timer = null; } }; + + node.addEventListener('mouseenter', clearTimer); + node.addEventListener('mouseleave', startTimer); + + if (typeof onClick === 'function') { + node.addEventListener('click', () => { + try { onClick(); } catch (e) { } + this._removeNode(node); + }); + } + + startTimer(); + + return node; + } + + _removeNode(node) { + if (!node || !node.parentElement) return; + node.classList.remove('show'); + setTimeout(() => { + if (node && node.parentElement) node.parentElement.removeChild(node); + }, 200); + } + + clearAll() { + if (!this._container) return; + Array.from(this._container.children).forEach(n => this._removeNode(n)); + } + + info(message, opts = {}) { return this.show(message, { ...opts, type: 'info' }); } + success(message, opts = {}) { return this.show(message, { ...opts, type: 'success' }); } + warn(message, opts = {}) { return this.show(message, { ...opts, type: 'warn' }); } + error(message, opts = {}) { return this.show(message, { ...opts, type: 'error' }); } + click(message, opts = {}) { return this.show(message, { ...opts, onClick: opts.f }); } + + + _insertStyles() { + const style = document.createElement('style'); + style.textContent = ` + .app-notification-container { + position: fixed; + z-index: 9999; + pointer-events: none; + display: flex; + flex-direction: column; + gap: 10px; + padding: 12px; + } + .app-notification-container[data-position="top-right"] { top: 8px; right: 8px; align-items: flex-end; } + .app-notification-container[data-position="top-left"] { top: 8px; left: 8px; align-items: flex-start; } + .app-notification-container[data-position="bottom-right"] { bottom: 8px; right: 8px; align-items: flex-end; } + .app-notification-container[data-position="bottom-left"] { bottom: 8px; left: 8px; align-items: flex-start; } + + .app-notification { + pointer-events: auto; + min-width: 220px; + max-width: 360px; + background: #111; + color: #fff; + padding: 10px 12px 10px 12px; + border-radius: var(--border-radius, 8px); + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.25); + font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial; + font-size: var(--FontSize2, 14px); + line-height: 1.2; + display: flex; + gap: 10px; + align-items: center; + opacity: 0; + transform: translateY(-6px) scale(0.995); + transition: opacity .18s ease, transform .18s ease; + position: relative; + } + .app-notification.show { + opacity: 0.95; + transform: translateY(0) scale(1); + } + .app-notification .icon { + font-size: 18px; + width: 22px; + height: 22px; + display:flex; + align-items:center; + justify-content:center; + border-radius: calc(var(--border-radius, 8px) - 5px); + padding: 8px; + } + .app-notification .icon svg{ + width: 20px; + height: 20px; + fill: #fff; + } + .app-notification .body { flex:1; } + .app-notification .title { font-weight: 600; margin-bottom: 4px; font-size: 13px; } + .app-notification .blockClose { + width: 20px; + height: 20px; + } + .app-notification .blockClose .close { + position: absolute; + right: 10px; + top: 10px; + margin-left: 8px; + background: transparent; + border: none; + color: inherit; + cursor: pointer; + padding: 0; + } + .app-notification .blockClose .close svg { + width: 15px; + height: 15px; + fill: #fff; + opacity: 0.8; + display: block; + } + + .app-notification.info { + background: var(--ColorThemes3, #2196F3); + color: var(--ColorThemes0, #ffffff); + } + .app-notification.info .icon { background: var(--ColorThemes0, #ffffff); } + .app-notification.info .icon svg{fill: var(--ColorThemes3, #2196F3);} + .app-notification.info .close svg{fill: var(--ColorThemes0, #ffffff);} + + .app-notification.success { background: #52ac56; } + .app-notification.success .icon { background: #6dc450; } + .app-notification.success .close svg{fill: #fff;} + + .app-notification.warn { background: #d18515; } + .app-notification.warn .icon { background: #eaad57; } + .app-notification.warn .close svg{fill: #fff;} + + .app-notification.error { background: #9c2424; } + .app-notification.error .icon { background: #c45050; } + .app-notification.error .close svg{fill: #fff;} + + @media (max-width: 700px) { + .app-notification-container { + left: 0; + right: 0; + width: calc(100% - 24px); + align-items: center !important; + } + .app-notification-container .app-notification { + max-width: 95%; + min-width: 95%; + } + + .app-notification-container.mobile-bottom { + top: auto; + bottom: 0; + } + } + `; + this.shadowRoot.appendChild(style); + } +} + +customElements.define('app-notification-container', AppNotificationContainer); + +/* + */ +// const Notifier = document.getElementById('notif-manager'); + +// 💡 Включить принудительную позицию снизу для мобильных +// Notifier.setMobileBottom(true); + +// 💡 Отключить принудительную позицию снизу (вернется к поведению @media или position) +// Notifier.setMobileBottom(false); + + +// Пример использования + +// Notifier.info('Настройки мобильной позиции изменены.'); +// Notifier.info('Привет! Это ваше первое уведомление через Web Component.', { +// title: 'Успешная инициализация', +// onClick: () => alert('Вы кликнули!'), +// lock: false +// }); +// Notifier.success('Успешная операция.'); +// Notifier.error('Критическая ошибка!', { timeout: 0, lock: true }); +// Notifier.warn({ title: `Metrics`, text: `З'єднання встановлено` }, { timeout: 0 }); \ No newline at end of file diff --git a/web/lib/customElements/territoryCard.js b/web/lib/customElements/territoryCard.js new file mode 100644 index 0000000..199237c --- /dev/null +++ b/web/lib/customElements/territoryCard.js @@ -0,0 +1,323 @@ +const appTerritoryCardStyles = new CSSStyleSheet(); +appTerritoryCardStyles.replaceSync(` + :host { + display: inline-block; + box-sizing: border-box; + width: 300px; + height: 200px; + } + @media (max-width: 2300px) { + :host { + width: calc((100% / 5) - 40px); + } + } + + @media (max-width: 1960px) { + :host { + width: calc((100% / 4) - 40px); + } + } + + @media (max-width: 1640px) { + :host { + width: calc((100% / 3) - 40px); + } + } + + @media (max-width: 1280px) { + :host { + width: calc((100% / 2) - 40px); + } + } + + @media (max-width: 650px) { + :host { + width: 100%; + } + } + .card { + position: relative; + width: 100%; + height: 200px; + background-color: var(--ColorThemes2, #525151); + overflow: hidden; + cursor: pointer; + border-radius: calc(var(--border-radius, 15px) - 5px); + } + @media(hover: hover) { + .card:hover { + opacity: 0.8; + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); + } + } + img { + width: 100%; + height: 100%; + object-fit: cover; + position: absolute; + top: 0; + left: 0; + z-index: 1; + filter: blur(3px); + } + .contents { + position: relative; + z-index: 2; + background: rgb(64 64 64 / 0.7); + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + align-items: stretch; + justify-content: space-between; + border-radius: calc(var(--border-radius, 15px) - 5px); + } + .address { + margin: 10px; + height: 35px; + display: flex; + background: var(--ColorThemes0, #1c1c19); + align-items: center; + justify-content: center; + font-size: var(--FontSize3, 14px); + color: var(--ColorThemes3, #f3f3f3); + border-radius: calc(var(--border-radius, 15px) - 5px - 4px); + position: relative; + overflow: hidden; + font-weight: 400; + } + + + + /* Стили для режима 'sheep' */ + .sheep { + margin: 10px; + max-height: 50px; + border-radius: calc(var(--border-radius, 15px) - 5px - 4px); + padding: 10px 0; + margin-top: 10px; + display: flex; + background: var(--PrimaryColor, #cb9e44); + align-items: center; + flex-direction: column; + justify-content: space-around; + } + .sheep span { + color: var(--PrimaryColorText, #2e2e2e); + font-size: var(--FontSize3, 14px); + font-weight: 400; + opacity: 0.8; + } + .sheep p { + color: var(--PrimaryColorText, #2e2e2e); + font-size: var(--FontSize4, 15px); + font-weight: 400; + margin: 5px 0 0 0; + } + + + /* Стили для режима 'info' (прогресс) */ + .info { + margin: 10px; + } + .info > div { + position: relative; + background-color: var(--ColorThemes0, #1c1c19);; + border-radius: calc(var(--border-radius, 15px) - 5px - 4px); + overflow: hidden; + padding: 5px 10px; + display: flex; + justify-content: space-between; + align-items: center; + min-height: 25px; + } + .info span { + z-index: 2; + font-size: var(--FontSize1, 12px); + color: var(--ColorThemes3, #f3f3f3); + } + .info p { + z-index: 2; + margin: 0; + font-weight: 500; + font-size: var(--FontSize3, 14px); + color: var(--ColorThemes3, #f3f3f3); + } + .progress { + position: absolute; + top: 0; + left: 0; + height: 100%; + background-color: var(--PrimaryColor, #cb9e44); + transition: width 0.3s ease; + } + a { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 10; + } +`); + +class AppTerritoryCard extends HTMLElement { + constructor() { + super(); + this.attachShadow({ mode: 'open' }); + + if (this.shadowRoot.adoptedStyleSheets) { + this.shadowRoot.adoptedStyleSheets = [appTerritoryCardStyles]; + } + } + + // Определяем, какие атрибуты будем отслеживать + static get observedAttributes() { + return ['image', 'address', 'sheep', 'link', 'atWork', 'quantity']; + } + + get image() { + return this.getAttribute('image'); + } + set image(newValue) { + if (newValue === null) { + this.removeAttribute('image'); + } else { + this.setAttribute('image', newValue); + } + } + + get address() { + return this.getAttribute('address'); + } + set address(newValue) { + if (newValue === null) { + this.removeAttribute('address'); + } else { + this.setAttribute('address', newValue); + } + } + + get sheep() { + return this.getAttribute('sheep'); + } + set sheep(newValue) { + if (newValue === null) { + this.removeAttribute('sheep'); + } else { + this.setAttribute('sheep', newValue); + } + } + + get link() { + return this.getAttribute('link'); + } + set link(newValue) { + if (newValue === null) { + this.removeAttribute('link'); + } else { + this.setAttribute('link', newValue); + } + } + + + get atWork() { + return this.getAttribute('atWork'); + } + set atWork(newValue) { + if (newValue === null) { + this.removeAttribute('atWork'); + } else { + this.setAttribute('atWork', String(newValue)); + } + } + + get quantity() { + return this.getAttribute('quantity'); + } + set quantity(newValue) { + if (newValue === null) { + this.removeAttribute('quantity'); + } else { + this.setAttribute('quantity', String(newValue)); + } + } + + // Вызывается при добавлении элемента в DOM + connectedCallback() { + this.render(); + } + + // Вызывается при изменении одного из отслеживаемых атрибутов + attributeChangedCallback(name, oldValue, newValue) { + if (oldValue !== newValue) { + this.render(); + } + } + + render() { + const image = this.getAttribute('image') || ''; + const address = this.getAttribute('address') || ''; + const sheep = this.getAttribute('sheep'); // Может быть null или "" + const link = this.getAttribute('link') || '#'; + const atWork = this.getAttribute('atWork'); // Может быть null + const quantity = this.getAttribute('quantity'); // Может быть null + + // --- Логика определения контента --- + let contentHTML = ''; + const isProgressMode = atWork !== null && quantity !== null && !isNaN(parseInt(atWork)) && !isNaN(parseInt(quantity)); + const hasSheep = sheep !== null && sheep !== ''; + + if (isProgressMode) { + // Режим прогресса (свободные подъезды) + const atWorkNum = parseInt(atWork); + const quantityNum = parseInt(quantity); + + const free = quantityNum - atWorkNum; + const progressPercent = quantityNum > 0 ? (atWorkNum / quantityNum) * 100 : 100; + + contentHTML = ` +
+
+
+ Вільні під'їзди: +

${free} / ${quantityNum}

+
+
+ `; + } else if (sheep !== null && sheep !== '') { + // Режим ответственного + contentHTML = ` +
+ Територію опрацьовує: +

${sheep}

+
+ `; + } else if (sheep !== null) { + // Режим "не опрацьовується" + contentHTML = ` +
+ Територія не опрацьовується +
+ `; + } + + // --- Сборка всего шаблона --- + this.shadowRoot.innerHTML = ` +
+ ${address} +
+

${address}

+ ${contentHTML} +
+ +
+ `; + } +} + +// Регистрируем веб-компонент +customElements.define('app-territory-card', AppTerritoryCard); + +// document.getElementById('app-territory-card-1').setAttribute('sheep', 'test') + diff --git a/web/lib/pages/home/script.js b/web/lib/pages/home/script.js index 38cc5eb..a3aae0a 100644 --- a/web/lib/pages/home/script.js +++ b/web/lib/pages/home/script.js @@ -27,8 +27,8 @@ const Home = { return Home.personal.house.list; }, setHTML: async () => { - const list = Home.personal.house.list.length > 0 - ? Home.personal.house.list + const list = Home.personal.house.list.length > 0 + ? Home.personal.house.list : await Home.personal.house.loadAPI(); if (USER.possibilities.can_view_territory && list.length) @@ -53,8 +53,8 @@ const Home = { return Home.personal.homestead.list; }, setHTML: async () => { - const list = Home.personal.homestead.list.length > 0 - ? Home.personal.homestead.list + const list = Home.personal.homestead.list.length > 0 + ? Home.personal.homestead.list : await Home.personal.homestead.loadAPI(); if (USER.possibilities.can_view_territory && list.length) @@ -81,8 +81,8 @@ const Home = { return Home.group.house.list; }, setHTML: async () => { - const list = Home.group.house.list.length > 0 - ? Home.group.house.list + const list = Home.group.house.list.length > 0 + ? Home.group.house.list : await Home.group.house.loadAPI(); if (USER.possibilities.can_view_territory && list.length) @@ -107,8 +107,8 @@ const Home = { return Home.group.homestead.list; }, setHTML: async () => { - const list = Home.group.homestead.list.length > 0 - ? Home.group.homestead.list + const list = Home.group.homestead.list.length > 0 + ? Home.group.homestead.list : await Home.group.homestead.loadAPI(); if (USER.possibilities.can_view_territory && list.length) @@ -124,18 +124,10 @@ const Home = { const fragment = document.createDocumentFragment(); for (const el of list) { - const card = document.createElement("div"); - card.className = "card"; - - card.innerHTML = ` - -
-
-

${el.title} ${el.number}

-
-
- - `; + const card = document.createElement('app-territory-card'); + card.image = `${CONFIG.web}cards/${type}/${type === "house" ? "T" : "H"}${el.id}.webp`; + card.address = `${el.title} ${el.number})`; + card.link = `/territory/card/${type}/${el.id}`; fragment.appendChild(card); } diff --git a/web/lib/pages/home/style.css b/web/lib/pages/home/style.css index 5224294..77c68d1 100644 --- a/web/lib/pages/home/style.css +++ b/web/lib/pages/home/style.css @@ -102,123 +102,6 @@ overflow-y: auto; align-items: flex-start; transition: .3s ease; -} - -.page-home .card { - position: relative; - width: 300px; - height: 200px; - background-color: var(--ColorThemes2); - margin: 10px; - overflow: hidden; - cursor: pointer; - border-radius: calc(var(--border-radius) - 5px); -} - -@media (max-width: 2300px) { - .page-home .card { - width: calc((100% / 5) - 30px); - } -} - -@media (max-width: 1960px) { - .page-home .card { - width: calc((100% / 4) - 30px); - } -} - -@media (max-width: 1640px) { - .page-home .card { - width: calc((100% / 3) - 30px); - } -} - -@media (max-width: 1280px) { - .page-home .card { - width: calc((100% / 2) - 30px); - } -} - -@media (max-width: 650px) { - .page-home .card { - width: 100%; - } -} - -@media(hover: hover) { - .page-home .card:hover { - opacity: 0.8; - } -} - -.page-home .card>i { - position: absolute; - width: 100%; - height: 100%; - object-fit: cover; - z-index: 1; - filter: blur(2px); - /* background-repeat: round; */ - background-size: cover; - background-position: center; - background-color: var(--PrimaryColor); - border-radius: calc(var(--border-radius) - 5px); -} - -.page-home .card>a { - position: absolute; - width: 100%; - height: 100%; - z-index: 10; -} - -.page-home .contents { - position: absolute; - z-index: 2; - background: rgb(64 64 64 / 0.7); - width: 100%; - height: 100%; - font-size: 40px; - font-weight: 500; - color: #fff; - display: flex; - flex-direction: column; - align-items: stretch; - justify-content: space-between; - border-radius: calc(var(--border-radius) - 5px); -} - -.page-home .info { - margin: 10px; -} - -.page-home .info>div { - width: 100%; - height: 35px; - display: flex; - background: var(--ColorThemes0); - align-items: center; - justify-content: center; - font-size: var(--FontSize1); - color: var(--ColorThemes3); - border-radius: calc(var(--border-radius) - 5px - 4px); - position: relative; - overflow: hidden; -} - -.page-home .info>div>span { - color: var(--ColorThemes3); - font-size: var(--FontSize3); - font-weight: 300; - z-index: 2; -} - -.page-home .info>div>p { - color: var(--ColorThemes3); - font-size: var(--FontSize3); - font-weight: 400; + gap: 20px; padding: 10px; - z-index: 2; - width: 100%; - text-align: center; } \ No newline at end of file diff --git a/web/lib/pages/schedule/constructor/index.html b/web/lib/pages/schedule/constructor/index.html new file mode 100644 index 0000000..615ba76 --- /dev/null +++ b/web/lib/pages/schedule/constructor/index.html @@ -0,0 +1,3 @@ +
+ +
diff --git a/web/lib/pages/schedule/constructor/script.js b/web/lib/pages/schedule/constructor/script.js new file mode 100644 index 0000000..de36022 --- /dev/null +++ b/web/lib/pages/schedule/constructor/script.js @@ -0,0 +1,8 @@ +const Schedule_constructor = { + init: async () => { + let html = await fetch('/lib/pages/schedule/constructor/index.html').then((response) => response.text()); + app.innerHTML = html; + + + } +} \ No newline at end of file diff --git a/web/lib/pages/schedule/constructor/style.css b/web/lib/pages/schedule/constructor/style.css new file mode 100644 index 0000000..ec58c8c --- /dev/null +++ b/web/lib/pages/schedule/constructor/style.css @@ -0,0 +1,6 @@ +.page-schedule-constructor { + width: calc(100% - 40px); + display: flex; + flex-direction: column; + margin: 20px 20px 0 20px; +} \ No newline at end of file diff --git a/web/lib/pages/sheeps/index.html b/web/lib/pages/sheeps/index.html index 34bd3de..080891e 100644 --- a/web/lib/pages/sheeps/index.html +++ b/web/lib/pages/sheeps/index.html @@ -86,6 +86,7 @@ +
@@ -335,6 +336,7 @@ +
diff --git a/web/lib/pages/sheeps/script.js b/web/lib/pages/sheeps/script.js index c8b7455..c6b3bd1 100644 --- a/web/lib/pages/sheeps/script.js +++ b/web/lib/pages/sheeps/script.js @@ -285,7 +285,6 @@ const Sheeps = { }, setHTML: async (id, randomNumber) => { let sheep = await Sheeps.editor.loadAPI(id); - console.log(sheep); Router.navigate(`sheeps/${id}`, true, false); diff --git a/web/lib/pages/stand/card/index.html b/web/lib/pages/stand/card/index.html index 4f7188d..f6d802f 100644 --- a/web/lib/pages/stand/card/index.html +++ b/web/lib/pages/stand/card/index.html @@ -10,7 +10,7 @@ Розташування:

--

-
+
Геолокація: --
diff --git a/web/lib/pages/stand/card/script.js b/web/lib/pages/stand/card/script.js index cd19856..23a494a 100644 --- a/web/lib/pages/stand/card/script.js +++ b/web/lib/pages/stand/card/script.js @@ -23,14 +23,23 @@ const Stand_card = { info: { list: [], + sheeps: [], async setHTML() { - const url = `${CONFIG.api}stand/${Stand_card.id}`; - this.list = await Stand_card.loadAPI(url); + this.list = await Stand_card.loadAPI(`${CONFIG.api}stand/${Stand_card.id}`); + this.sheeps = await Stand_card.loadAPI(`${CONFIG.api}sheeps/list/stand`); + document.getElementById('stand-info-title').innerText = this.list.title; - document.getElementById('stand-info-geo').innerHTML = 'Відкрити Google Maps'; - document.getElementById('stand-info-geo').href = `https://www.google.com/maps?q=${this.list.geo[0]},${this.list.geo[1]}`; + + if(this.list.geo[0]>0){ + document.getElementById('stand-info-geo').innerHTML = 'Відкрити Google Maps'; + document.getElementById('stand-info-geo').href = `https://www.google.com/maps?q=${this.list.geo[0]},${this.list.geo[1]}`; + document.getElementById('stand-info-block-geo').style.display = ""; + } else { + document.getElementById('stand-info-block-geo').style.display = "none"; + } + document.getElementById('stand-info-image').setAttribute('src', ''); Stand_card.schedule.setHTML(); @@ -42,7 +51,7 @@ const Stand_card = { update(msg) { const { type, data, user } = msg; const el = document.getElementById(`name-${data?.id}`); - if (!el) return; // если элемент не найден — выходим + if (!el) return; // якщо елемент не знайдено - виходимо const isSelf = user.id == USER.id; @@ -56,7 +65,7 @@ const Stand_card = { break; case "stand_unlocking": - // Разблокируем только если событие от другого пользователя + // Розблокуємо лише якщо подія від іншого користувача if (!isSelf) { el.style.border = ""; el.style.backgroundColor = ""; @@ -70,18 +79,18 @@ const Stand_card = { const sid = data.sheep_id; const sname = data.sheep_name ?? ""; - // Менеджеру показываем весь список + // Менеджеру показуємо весь перелік if (USER.possibilities.can_manager_stand && Array.isArray(Sheeps?.sheeps_list?.list)) { el.innerHTML = ""; - // пустой вариант + // порожній варіант el.appendChild(Object.assign(document.createElement("option"), { value: "", textContent: " " })); - // заполняем всех овечек - Sheeps.sheeps_list.list.forEach(s => { + // заповнюємо всіх овечок + Stand_card.info.sheeps.forEach(s => { const opt = document.createElement("option"); opt.value = s.id; opt.textContent = s.name; @@ -91,7 +100,7 @@ const Stand_card = { el.removeAttribute("disabled"); } else { - // Обычное поведение для обычных пользователей + // Звичайна поведінка для звичайних користувачів if (sid == USER.id) { el.innerHTML = ``; el.removeAttribute("disabled"); @@ -130,7 +139,7 @@ const Stand_card = { } }; - if (Cloud.socket?.readyState === WebSocket.OPEN) { + if (navigator.onLine && Cloud.socket?.readyState === WebSocket.OPEN) { Cloud.socket.send(JSON.stringify(message)); } else { if (confirm("З'єднання розірвано! Перепідключитись?")) { @@ -152,7 +161,7 @@ const Stand_card = { } }; - if (Cloud.socket?.readyState === WebSocket.OPEN) { + if (navigator.onLine && Cloud.socket?.readyState === WebSocket.OPEN) { Cloud.socket.send(JSON.stringify(message)); } else { if (confirm("З'єднання розірвано! Перепідключитись?")) { @@ -177,14 +186,14 @@ const Stand_card = { }; if (USER.possibilities.can_manager_stand) { - const pos = Sheeps.sheeps_list.list.map(e => e.id).indexOf(Number(sheep_id)); + const pos = Stand_card.info.sheeps.map(e => e.id).indexOf(Number(sheep_id)); if (pos != -1) { - let name = Sheeps.sheeps_list.list[pos].name; + let name = Stand_card.info.sheeps[pos].name; message.data.sheep_name = name; } } - if (Cloud.socket?.readyState === WebSocket.OPEN) { + if (navigator.onLine && Cloud.socket?.readyState === WebSocket.OPEN) { Cloud.socket.send(JSON.stringify(message)); } else { if (confirm("З'єднання розірвано! Перепідключитись?")) { @@ -272,10 +281,10 @@ const Stand_card = { textContent: " " })); - // если есть права менеджера — добавляем всех пользователей - if (USER.possibilities.can_manager_stand && Array.isArray(Sheeps?.sheeps_list?.list)) { - Sheeps.sheeps_list.list.sort((a, b) => a.name.localeCompare(b.name, 'uk')); - Sheeps.sheeps_list.list.forEach(s => { + // якщо є права менеджера - додаємо всіх користувачів + if (USER.possibilities.can_manager_stand && Array.isArray(Stand_card.info.sheeps)) { + Stand_card.info.sheeps.sort((a, b) => a.name.localeCompare(b.name, 'uk')); + Stand_card.info.sheeps.forEach(s => { const option = document.createElement("option"); option.value = s.id; option.textContent = s.name; @@ -283,7 +292,7 @@ const Stand_card = { select.appendChild(option); }); } else { - // если есть владелец — показываем его + // якщо є власник - показуємо його const opt = document.createElement("option"); if (sheep.sheep_id) { opt.value = sheep.sheep_id; @@ -296,13 +305,13 @@ const Stand_card = { select.appendChild(opt); } - // если занят другим пользователем — блокируем + // якщо зайнятий іншим користувачем - блокуємо if (sheep.sheep_id && sheep.sheep_id !== USER.id && !USER.possibilities.can_manager_stand) { select.disabled = true; select.value = sheep.sheep_id; } - // --- обработчики --- + // --- обробники --- select.addEventListener("mousedown", () => Stand_card.cloud.mess.locking({ id: sheep.id })); select.addEventListener("change", () => Stand_card.cloud.mess.update({ sheep_id: select.value, id: sheep.id })); select.addEventListener("blur", () => Stand_card.cloud.mess.unlocking({ id: sheep.id })); @@ -347,7 +356,7 @@ const Stand_card = { if (USER.possibilities.can_add_stand) { const btn = Object.assign(document.createElement("button"), { id: "stand-new-button", - textContent: "Додати стенд(и)", + textContent: "Додати день", onclick: () => Stand_card.addStand() }); fragment.appendChild(btn); @@ -407,12 +416,14 @@ const Stand_card = { .then(response => { if (response.status == 200) { console.log({ 'setPack': 'ok' }); - button.innerText = "Стенд(и) додано"; + button.innerText = "День додано"; + Notifier.success('День додано'); return response.json() } else { console.log('err'); button.innerText = "Помилка запису"; + Notifier.error('Помилка додавання'); return } @@ -423,16 +434,12 @@ const Stand_card = { Stand_card.schedule.setHTML(); setTimeout(() => { - button.innerText = "Додати стенд(и)"; + button.innerText = "Додати день"; }, 3000); }) .catch(err => { console.log(err); button.innerText = "Помилка запису"; }) - }, - - edit({ sheep_id, stand_id }) { - } } \ No newline at end of file diff --git a/web/lib/pages/stand/constructor/index.html b/web/lib/pages/stand/constructor/index.html index 2bb6d07..1df9146 100644 --- a/web/lib/pages/stand/constructor/index.html +++ b/web/lib/pages/stand/constructor/index.html @@ -51,14 +51,12 @@ type="text" id="info-geo_lat" name="geo_lat" - required placeholder="49.5601856455014" />
diff --git a/web/lib/pages/stand/constructor/script.js b/web/lib/pages/stand/constructor/script.js index 0bd32d9..44a5d8d 100644 --- a/web/lib/pages/stand/constructor/script.js +++ b/web/lib/pages/stand/constructor/script.js @@ -50,11 +50,13 @@ const Stand_constructor = { if (response.status == 200) { console.log({ 'setPack': 'ok' }); button.innerText = "Стенд додано"; + Notifier.success('Стенд створено'); return response.json() } else { console.log('err'); button.innerText = "Помилка запису"; + Notifier.error('Помилка створення'); return } diff --git a/web/lib/pages/stand/editor/index.html b/web/lib/pages/stand/editor/index.html index a619a6f..7d089b6 100644 --- a/web/lib/pages/stand/editor/index.html +++ b/web/lib/pages/stand/editor/index.html @@ -51,14 +51,12 @@ type="text" id="info-geo_lat" name="geo_lat" - required placeholder="49.5601856455014" /> diff --git a/web/lib/pages/stand/editor/script.js b/web/lib/pages/stand/editor/script.js index d7f5dc7..1286a4f 100644 --- a/web/lib/pages/stand/editor/script.js +++ b/web/lib/pages/stand/editor/script.js @@ -83,11 +83,13 @@ const Stand_editor = { if (response.status == 200) { console.log({ 'setPack': 'ok' }); button.innerText = "Стенд відредаговано"; + Notifier.success('Стенд відредаговано'); return response.json() } else { console.log('err'); button.innerText = "Помилка при редагуванні"; + Notifier.error('Помилка при редагуванні'); return } diff --git a/web/lib/pages/stand/list/script.js b/web/lib/pages/stand/list/script.js index 71cab4d..82747d5 100644 --- a/web/lib/pages/stand/list/script.js +++ b/web/lib/pages/stand/list/script.js @@ -60,7 +60,7 @@ const Stand_list = { }, renderCard: ({ element }) => { - const imagesList = ['1.png', '2.png', '3.png', '4.png', '5.png', '6.png', '7.png', '8.png']; + const imagesList = ['1.png', '5.png', '8.png', '7.png', '2.png', '3.png', '4.png', '6.png']; // const randomImage = images[Math.floor(Math.random() * images.length)]; const image = imagesList[Stand_list.renderIndex % imagesList.length]; Stand_list.renderIndex++; @@ -85,5 +85,5 @@ const Stand_list = { `; - }, + } } \ No newline at end of file diff --git a/web/lib/pages/stand/list/style.css b/web/lib/pages/stand/list/style.css index 0a536ff..585cd9a 100644 --- a/web/lib/pages/stand/list/style.css +++ b/web/lib/pages/stand/list/style.css @@ -246,7 +246,8 @@ width: 100%; height: 200px; object-fit: cover; - filter: brightness(0.9) contrast(80%) saturate(110%) drop-shadow(2px 2px 4px rgba(0, 0, 0, 0.3)); + /* filter: brightness(0.9) contrast(80%) saturate(110%) drop-shadow(2px 2px 4px rgba(0, 0, 0, 0.3)); */ + filter: blur(1px) brightness(0.7) contrast(80%) saturate(110%) drop-shadow(2px 2px 4px rgba(0, 0, 0, 0.3)); border-radius: calc(var(--border-radius) - 5px); } @@ -266,7 +267,7 @@ .page-stand-list>details>#list>.card>.contents>.info>div { width: 100%; - height: 35px; + height: 40px; display: flex; background: var(--ColorThemes0); align-items: center; @@ -288,15 +289,15 @@ .page-stand-list>details>#list>.card>.contents>.info>div>p { color: var(--ColorThemes3); - font-size: var(--FontSize3); - font-weight: 400; + font-size: var(--FontSize4); + font-weight: 500; padding: 10px; z-index: 2; } .page-stand-list>details>#list>.card>.contents>.info>.button-edit { - min-width: 35px; - height: 35px; + min-width: 40px; + height: 40px; border-radius: calc(var(--border-radius) - 5px - 4px); background: var(--PrimaryColor); cursor: pointer; diff --git a/web/lib/pages/territory/card/script.js b/web/lib/pages/territory/card/script.js index ef600a2..3905995 100644 --- a/web/lib/pages/territory/card/script.js +++ b/web/lib/pages/territory/card/script.js @@ -1,4 +1,4 @@ -let map_card; +let map_card, Territory_reconnecting; const Territory_card = { // Глобальні змінні стану @@ -131,12 +131,12 @@ const Territory_card = { data: apt }; - if (Cloud.socket?.readyState === WebSocket.OPEN) { + if (navigator.onLine && Cloud.socket?.readyState === WebSocket.OPEN) { Cloud.socket.send(JSON.stringify(message)); } else { if (confirm("З'єднання розірвано! Перепідключитись?")) { - Territory_card.getEntrances({ update: true }); Cloud.start(); + Territory_card.getEntrances({ update: true }); } } }, @@ -178,11 +178,10 @@ const Territory_card = { data: apt }; - if (Cloud.socket?.readyState === WebSocket.OPEN) { + if (navigator.onLine && Cloud.socket?.readyState === WebSocket.OPEN) { Cloud.socket.send(JSON.stringify(message)); } else { if (confirm("З'єднання розірвано! Перепідключитись?")) { - Territory_card.getEntrances({ update: true }); Territory_card.cloud.start(); } } @@ -230,9 +229,9 @@ const Territory_card = { const details = document.createElement('details'); if (show === "open") details.setAttribute('open', ''); details.innerHTML = ` -

${title}

${icon}
-
- `; +

${title}

${icon}
+
+ `; fragment.appendChild(details); this.getApartment({ id, number: entrance_number, update: false }); @@ -487,6 +486,10 @@ const Territory_card = { }, }, + async reload(){ + Territory_card.getEntrances({ update: true }); + }, + // Сортування sort(mode, load) { const idx = Math.max(1, Math.min(4, Number(mode) || 1)); diff --git a/web/lib/pages/territory/list/script.js b/web/lib/pages/territory/list/script.js index 32536a5..e05fc7a 100644 --- a/web/lib/pages/territory/list/script.js +++ b/web/lib/pages/territory/list/script.js @@ -54,7 +54,7 @@ const Territory_list = { return Territory_list.house.list; }, setHTML: async function () { - const block_house = document.getElementById('list-house'); + const block = document.getElementById('list-house'); const territory_entrances = localStorage.getItem('territory_list_entrances') === 'true'; const sort_mode = localStorage.getItem('territory_list_sort') ?? "1"; const territory_list_filter = Number(localStorage.getItem("territory_list_filter") ?? 0); @@ -74,7 +74,7 @@ const Territory_list = { list.sort(compare); - let html = ""; + block.innerHTML = ''; for (const element of list) { const qty = element.entrance?.quantity ?? 0; const work = element.entrance?.working ?? 0; @@ -87,11 +87,33 @@ const Territory_list = { (territory_list_filter === 2 && element.working === false); if (statusMatch) { - html += this.renderCard({ element, territory_entrances }); + const card = document.createElement('app-territory-card'); + + if (territory_entrances) { + const working = element.working; + const person = working + ? `${element.history.name === 'Групова' ? 'Група ' + element.history.group_id : element.history.name}` + : ``; + + card.image = `${CONFIG.web}cards/house/T${element.house.id}.webp`; + card.address = `${element.house.title} ${element.house.number} (${element.title})`; + card.link = `/territory/manager/house/${element.house.id}`; + card.sheep = person; + block.appendChild(card); + } else { + const qty = element.entrance.quantity; + const work = element.entrance.working; + + card.image = `${CONFIG.web}cards/house/T${element.id}.webp`; + card.address = `${element.title} ${element.number}`; + card.link = `/territory/manager/house/${element.id}`; + card.atWork = work; + card.quantity = qty; + } + + block.appendChild(card); } } - - block_house.innerHTML = html; }, compareAB: (a, b, entrances, order = 'asc') => { const dir = order === 'asc' ? 1 : -1; @@ -110,57 +132,6 @@ const Territory_list = { return 0; }, - renderCard: ({ element, territory_entrances }) => { - if (territory_entrances) { - const working = element.working; - const bg = working ? `background: ${colorGroup(element.history.group_id)} color: #fff;` : ""; - - const person = working - ? `Територію опрацьовує:

${element.history.name === 'Групова' ? 'Група ' + element.history.group_id : element.history.name}

` - : `Територія не опрацьовується`; - - return ` -
- -
-
-
-

${element.house.title} ${element.house.number} (${element.title})

-
-
-
- ${person} -
-
- -
- `; - } else { - const qty = element.entrance.quantity; - const work = element.entrance.working; - const progress = ((work / qty) * 100).toFixed(1); - return ` -
- -
-
-
-

${element.title} ${element.number}

-
-
-
-
-
- Вільні під'їзди: -

${qty - work} / ${qty}

-
-
-
- -
- `; - } - }, territoryType: (type) => { localStorage.setItem('territory_list_entrances', type); document.getElementById('territory_entrances_true').setAttribute('data-state', type === 'false' ? 'active' : ''); @@ -202,8 +173,7 @@ const Territory_list = { list.sort(compare); - let html = ""; - + block.innerHTML = ''; for (const element of list) { const statusMatch = territory_list_filter === 0 || @@ -211,35 +181,20 @@ const Territory_list = { (territory_list_filter === 2 && !element.working); if (statusMatch) { - html += this.renderCard(element); + const working = element.working; + + const person = working + ? `${element.history.name === 'Групова' ? 'Група ' + element.history.group_id : element.history.name}` + : ``; + + const card = document.createElement('app-territory-card'); + card.image = `${CONFIG.web}cards/homestead/H${element.id}.webp`; + card.address = `${element.title} ${element.number}`; + card.link = `/territory/manager/homestead/${element.id}`; + card.sheep = person; + block.appendChild(card); } } - - block.innerHTML = html; - }, - renderCard: (element) => { - const working = element.working; - const bg = working ? `background: ${colorGroup(element.history.group_id)} color: #fff;` : ""; - const person = working - ? `Територію опрацьовує:

${element.history.name === 'Групова' ? 'Група ' + element.history.group_id : element.history.name}

` - : `Територія не опрацьовується`; - - return ` -
- -
-
-
-

${element.title} ${element.number}

-
-
-
- ${person} -
-
- -
- `; } }, filter: () => { @@ -252,6 +207,8 @@ const Territory_list = { Territory_list.homestead.setHTML(); }, report: async () => { + Notifier.info('Запит на генерацію звіту опрацювання відправлено'); + const uuid = localStorage.getItem("uuid"); const url = `${CONFIG.api}generator/report/territories`; await fetch(url, { diff --git a/web/lib/pages/territory/list/style.css b/web/lib/pages/territory/list/style.css index 91c27ed..08576dc 100644 --- a/web/lib/pages/territory/list/style.css +++ b/web/lib/pages/territory/list/style.css @@ -202,7 +202,7 @@ .page-territory #list-house, .page-territory #list-homestead { - width: 100%; + width: calc(100% - 20px); margin: 0; display: flex; flex-wrap: wrap; @@ -212,157 +212,6 @@ overflow-y: auto; align-items: flex-start; transition: .3s ease; -} - -.page-territory .card { - position: relative; - width: 300px; - height: 200px; - background-color: var(--ColorThemes2); - margin: 10px; - overflow: hidden; - cursor: pointer; - border-radius: calc(var(--border-radius) - 5px); -} - -@media (max-width: 2300px) { - .page-territory .card { - width: calc((100% / 5) - 40px); - } -} - -@media (max-width: 1960px) { - .page-territory .card { - width: calc((100% / 4) - 40px); - } -} - -@media (max-width: 1640px) { - .page-territory .card { - width: calc((100% / 3) - 40px); - } -} - -@media (max-width: 1280px) { - .page-territory .card { - width: calc((100% / 2) - 40px); - } -} - -@media (max-width: 650px) { - .page-territory .card { - width: 100%; - } -} - -@media(hover: hover) { - .page-territory .card:hover { - opacity: 0.8; - } -} - -.page-territory .card>i { - position: absolute; - width: 100%; - height: 100%; - object-fit: cover; - z-index: 1; - filter: blur(2px); - /* background-repeat: round; */ - background-size: cover; - background-position: center; - background-color: var(--PrimaryColor); - border-radius: calc(var(--border-radius) - 5px); -} - -.page-territory .card>a { - position: absolute; - width: 100%; - height: 100%; - z-index: 10; -} - -.page-territory .contents { - position: absolute; - z-index: 2; - background: rgb(64 64 64 / 0.7); - width: 100%; - height: 100%; - font-size: 40px; - font-weight: 500; - color: #fff; - display: flex; - flex-direction: column; - align-items: stretch; - justify-content: space-between; - border-radius: calc(var(--border-radius) - 5px); -} - - -.page-territory .info { - margin: 10px; -} - -.page-territory .info>div { - width: 100%; - height: 35px; - display: flex; - background: var(--ColorThemes0); - align-items: center; - justify-content: center; - font-size: var(--FontSize1); - color: var(--ColorThemes3); - border-radius: calc(var(--border-radius) - 5px - 4px); - position: relative; - overflow: hidden; -} - -.page-territory .progress { - background: var(--PrimaryColor); - height: 100%; - position: absolute; - z-index: 1; - left: 0; -} - -.page-territory .info>div>span { - color: var(--ColorThemes3); - font-size: var(--FontSize3); - font-weight: 300; - z-index: 2; -} - -.page-territory .info>div>p { - color: var(--ColorThemes3); - font-size: var(--FontSize3); - font-weight: 400; + gap: 20px; padding: 10px; - z-index: 2; -} - -.page-territory .sheep { - margin: 10px; - max-height: 50px; - border-radius: calc(var(--border-radius) - 5px - 4px); - padding: 10px 0; - margin-top: 10px; - display: flex; - background: var(--PrimaryColor); - align-items: center; - flex-direction: column; - justify-content: space-around; -} - -.page-territory .sheep>span { - color: var(--PrimaryColorText); - font-size: var(--FontSize3); - font-weight: 400; - opacity: 0.8; -} - -.page-territory .sheep>p { - color: var(--PrimaryColorText); - font-size: var(--FontSize4); - font-weight: 400; - margin-top: 5px; } \ No newline at end of file diff --git a/web/lib/pages/territory/manager/script.js b/web/lib/pages/territory/manager/script.js index 4fc9534..a68da30 100644 --- a/web/lib/pages/territory/manager/script.js +++ b/web/lib/pages/territory/manager/script.js @@ -279,12 +279,6 @@ const Territory_Manager = { }; L.polygon(data.points, polygonOptions).addTo(map_territory); - - console.log(data.zoom); - - // setTimeout(() => { - // map_territory.setZoom(data.zoom); - // }, 200) }, mess: { open: ({ type, id, number, mode }) => { @@ -359,11 +353,14 @@ const Territory_Manager = { if (!response.ok) throw new Error("Failed to assign"); + Notifier.success('Територія призначина успішно'); + Territory_Manager.mess.close(); Territory_Manager.entrances.list = []; await Territory_Manager.entrances.setHTML(type, id); } catch (err) { console.error('❌ Error:', err); + Notifier.error('Помилка призначення території'); const errorText = "Помилка"; if (newButton) newButton.innerText = errorText; if (groupButton) groupButton.innerText = errorText; @@ -391,8 +388,11 @@ const Territory_Manager = { Territory_Manager.entrances.list = []; await Territory_Manager.entrances.setHTML(type, id); + + Notifier.success('Територія забрана успішно'); } catch (error) { console.error("❌ Помилка зняття призначення:", error); + Notifier.error('Помилка зняття призначення'); if (button) button.innerText = "Помилка"; } }, diff --git a/web/lib/router/router.js b/web/lib/router/router.js index d231a8a..9eff8ca 100644 --- a/web/lib/router/router.js +++ b/web/lib/router/router.js @@ -123,7 +123,12 @@ const Router = { // Делегування кліків по посиланнях з data-route delegateLinks() { window.addEventListener('click', (e) => { - const target = e.target.closest('[data-route]'); + // const target = e.target.closest('[data-route]'); + const pathNodes = e.composedPath(); + const target = pathNodes.find(node => + node.tagName === 'A' && node.hasAttribute('data-route') + ); + if (!target || !target.href) return; const path = target.href.replace(location.origin, ''); @@ -148,7 +153,7 @@ const Router = { location.hash = this.clearSlashes(path); } - if(update == true) { + if (update == true) { window.scrollTo(0, 0); // Скидуємо прокрутку при переході this.check(); } diff --git a/web/lib/router/routes.js b/web/lib/router/routes.js index 8e734c3..1076ef3 100644 --- a/web/lib/router/routes.js +++ b/web/lib/router/routes.js @@ -1,71 +1,93 @@ Router .add('auth', function () { pageActive(''); - Auth.init();; + Auth.init(); + page = "Auth"; }) .add('territory/map', function () { pageActive(); - Territory_Map.init();; + Territory_Map.init(); + page = "Territory_Map"; }) .add('territory/constructor', function () { pageActive(); - Territory_constructor.init();; + Territory_constructor.init(); + page = "Territory_constructor"; }) .add('territory/manager/(.*)/(.*)', function (type, id) { pageActive(); Territory_Manager.init(type, id); + page = "Territory_Manager"; }) .add('territory/editor/(.*)/(.*)', function (type, id) { pageActive(); Territory_editor.init(type, id); + page = "Territory_editor"; }) .add('territory/card/(.*)/(.*)', function (type, id) { pageActive(); Territory_card.init(type, id); + page = "Territory_card"; }) .add('territory/history', function () { pageActive(); Territory_History.init(); + page = "Territory_History"; }) .add('territory', function () { pageActive('territory'); Territory_list.init(); + page = "Territory_list"; }) .add('sheeps/(.*)', function (name) { pageActive('sheeps'); - Sheeps.init(name);; + Sheeps.init(name); + page = "Sheeps"; }) .add('sheeps', function () { pageActive('sheeps'); - Sheeps.init();; + Sheeps.init(); + page = "Sheeps"; }) .add('home', function () { pageActive('home'); Home.init(); + page = "Home"; + }) + .add('schedule/constructor', function () { + pageActive(); + Schedule_constructor.init(); + page = "Schedule_constructor"; }) .add('schedule', function () { pageActive('schedule'); - Schedule_list.init();; + Schedule_list.init(); + page = "Schedule_list"; }) .add('stand/constructor', function () { pageActive(); - Stand_constructor.init();; + Stand_constructor.init(); + page = "Stand_constructor"; }) .add('stand/editor/(.*)', function (id) { pageActive(); - Stand_editor.init(id);; + Stand_editor.init(id); + page = "Stand_editor"; }) .add('stand/card/(.*)', function (id) { pageActive(); - Stand_card.init(id);; + Stand_card.init(id); + page = "Stand_card"; }) .add('stand', function () { pageActive('stand'); - Stand_list.init();; + Stand_list.init(); + page = "Stand_list"; }) .add('options', function () { pageActive('options'); - Options.init();; + Options.init(); + page = "Options"; }) .add(function () { page_404();; diff --git a/web/sw.js b/web/sw.js index b6b93c2..5eb5338 100644 --- a/web/sw.js +++ b/web/sw.js @@ -1,4 +1,4 @@ -const STATIC_CACHE_NAME = 'v2.0.40'; +const STATIC_CACHE_NAME = 'v2.0.103'; const FILES_TO_CACHE = [ '/', @@ -7,6 +7,8 @@ const FILES_TO_CACHE = [ "/lib/router/router.js", "/lib/router/routes.js", + "/lib/customElements/notification.js", + "/lib/components/leaflet/leaflet.css", "/lib/components/leaflet/leaflet.js", @@ -17,6 +19,8 @@ const FILES_TO_CACHE = [ "/lib/components/cloud.js", + "/lib/components/metrics.js", + "/lib/components/clipboard.js", "/lib/components/colorGroup.js", "/lib/components/makeid.js", @@ -91,6 +95,10 @@ const FILES_TO_CACHE = [ "/lib/pages/schedule/list/style.css", "/lib/pages/schedule/list/index.html", + "/lib/pages/schedule/constructor/script.js", + "/lib/pages/schedule/constructor/style.css", + "/lib/pages/schedule/constructor/index.html", + "/lib/app.js" ]; @@ -102,7 +110,7 @@ self.addEventListener('install', event => { fetch(url).then(res => { if (!res.ok) throw new Error(`${url} not found`); return cache.put(url, res); - }).catch(err => console.warn(err)) + }).catch(err => console.warn('[ServiceWorker] ', err)) )); }) ); @@ -130,12 +138,12 @@ self.addEventListener('fetch', event => { // ----------------------- PUSH ----------------------- self.addEventListener("push", event => { let data = {}; - try { data = event.data.json(); } catch { data = { title: "Уведомлення", body: event.data?.text() }; } + try { data = event.data.json(); } catch { data = { title: "Повідомлення", body: event.data?.text() }; } - console.log(data); + console.log('[ServiceWorker] ', data); - const title = data.title || "Уведомлення"; + const title = data.title || "Повідомлення"; const options = { body: data.body || "", icon: "/img/icon.png", @@ -177,7 +185,7 @@ async function updateALL() { fetch(url).then(res => { if (!res.ok) throw new Error(`${url} not found`); return cache.put(url, res); - }).catch(err => console.warn(err)) + }).catch(err => console.warn('[ServiceWorker] ', err)) )); - console.log('All caches updated'); + console.log('[ServiceWorker] All caches updated'); } \ No newline at end of file diff --git a/ws/middleware/pushToMetrics.js b/ws/middleware/pushToMetrics.js new file mode 100644 index 0000000..3b7a978 --- /dev/null +++ b/ws/middleware/pushToMetrics.js @@ -0,0 +1,13 @@ +async function pushToMetrics(metric) { + if (!metric || !metric.type) return; + + const payload = { ...metric, timestamp: Date.now() }; + + fetch("http://metrics:4005/push", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload) + }).catch(err => console.error("Metrics push error:", err)); +} + +module.exports = { pushToMetrics }; \ No newline at end of file diff --git a/ws/routes/message.js b/ws/routes/message.js index b25e7ab..caed596 100644 --- a/ws/routes/message.js +++ b/ws/routes/message.js @@ -2,9 +2,16 @@ const { updateApartment } = require("../services/apartments.service"); const { updateBuilding } = require("../services/buildings.service"); const { lockingStand, unlockingStand, updateStand } = require("../services/stand.service"); const { broadcast } = require("../utils/broadcaster"); +const { pushToMetrics } = require("../middleware/pushToMetrics"); module.exports = async (wss, ws, message) => { try { + pushToMetrics({ + type: "ws_out", + length: message.length, + timestamp: Date.now() + }); + switch (message.type) { case "apartment": await updateApartment(ws.user, message.data); diff --git a/ws/ws.js b/ws/ws.js index e54723d..5bf1c03 100644 --- a/ws/ws.js +++ b/ws/ws.js @@ -2,6 +2,7 @@ const WebSocket = require("ws"); const { URL } = require('url'); const { routeMessage } = require("./routes"); const { auth } = require("./middleware/auth"); +const { pushToMetrics } = require("./middleware/pushToMetrics"); const { setupPing } = require("./utils/ping"); require("dotenv").config(); @@ -28,10 +29,19 @@ wss.on("connection", async (ws, request) => { ws.user = user; ws.send(JSON.stringify({ connection: "success", api_version, user: {name: ws.user.name, id: ws.user.id } })); + pushToMetrics({ type: "connection_status", status: "online", api_version, user: {name: ws.user.name, id: ws.user.id } }); + // Periodic ping to maintain a connection setupPing(ws); ws.on("message", (raw) => { + + pushToMetrics({ + type: "ws_in", + length: raw.length, + timestamp: Date.now() + }); + try { const message = JSON.parse(raw); routeMessage(wss, ws, message); @@ -41,7 +51,10 @@ wss.on("connection", async (ws, request) => { } }); - ws.on("close", () => console.log("🔌 Client disconnected")); + ws.on("close", () => { + console.log("🔌 Client disconnected"); + pushToMetrics({ type: "connection_status", status: "offline" }); + }); ws.on("error", (err) => console.error("❌ WS error:", err)); } catch (err) { console.error("❌ Auth error:", err);