Tataaicoltd commited on
Commit
4e2d9ce
·
verified ·
1 Parent(s): f8fa21c

feat: POI move/bulk-save + APK download page

Browse files
.gitattributes CHANGED
@@ -68,3 +68,4 @@ admin/images/map_608.jpg filter=lfs diff=lfs merge=lfs -text
68
  admin/images/map_609.jpg filter=lfs diff=lfs merge=lfs -text
69
  admin/images/map_658.jpg filter=lfs diff=lfs merge=lfs -text
70
  admin/images/map_659.jpg filter=lfs diff=lfs merge=lfs -text
 
 
68
  admin/images/map_609.jpg filter=lfs diff=lfs merge=lfs -text
69
  admin/images/map_658.jpg filter=lfs diff=lfs merge=lfs -text
70
  admin/images/map_659.jpg filter=lfs diff=lfs merge=lfs -text
71
+ admin/file/app.apk filter=lfs diff=lfs merge=lfs -text
admin/css/maps.css CHANGED
@@ -381,6 +381,61 @@ h1 {
381
  text-overflow: ellipsis;
382
  }
383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  /* ==================== SEARCH ==================== */
385
 
386
  .search-btn {
 
381
  text-overflow: ellipsis;
382
  }
383
 
384
+ /* ==================== POI MARKERS ==================== */
385
+
386
+ .poi-marker {
387
+ position: fixed;
388
+ transform: translate(-50%, -100%);
389
+ z-index: 60;
390
+ pointer-events: auto;
391
+ cursor: pointer;
392
+ display: flex;
393
+ flex-direction: column;
394
+ align-items: center;
395
+ }
396
+
397
+ body.mode-move .poi-marker { cursor: grab; }
398
+ body.mode-move .poi-marker.active,
399
+ body.mode-move .poi-marker:active { cursor: grabbing; }
400
+
401
+ .poi-marker-dot {
402
+ width: 10px;
403
+ height: 10px;
404
+ border-radius: 50%;
405
+ background: #9C27B0;
406
+ border: 2px solid #fff;
407
+ box-shadow: 0 1px 4px rgba(0,0,0,0.4);
408
+ transition: transform 0.1s, box-shadow 0.1s;
409
+ }
410
+
411
+ .poi-marker.active .poi-marker-dot {
412
+ transform: scale(1.4);
413
+ box-shadow: 0 0 0 3px rgba(33,150,243,0.6), 0 1px 6px rgba(0,0,0,0.4);
414
+ }
415
+
416
+ .poi-marker.poi-edited .poi-marker-dot {
417
+ background: #FF9800;
418
+ box-shadow: 0 0 0 2px rgba(255,152,0,0.4), 0 1px 4px rgba(0,0,0,0.4);
419
+ }
420
+
421
+ .poi-marker.poi-edited .poi-marker-label {
422
+ background: rgba(255,152,0,0.9);
423
+ }
424
+
425
+ .poi-marker-label {
426
+ margin-top: 2px;
427
+ background: rgba(156,39,176,0.85);
428
+ color: #fff;
429
+ font-size: 9px;
430
+ padding: 1px 4px;
431
+ border-radius: 3px;
432
+ white-space: nowrap;
433
+ max-width: 120px;
434
+ overflow: hidden;
435
+ text-overflow: ellipsis;
436
+ pointer-events: none;
437
+ }
438
+
439
  /* ==================== SEARCH ==================== */
440
 
441
  .search-btn {
admin/file/app.apk ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1b9007982aceed60f61e715cdf118a2c07a6edb3a789cc6695139ef48ea8e51
3
+ size 8560562
admin/file/index.html ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="vi">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Tải ứng dụng — Diana Maps</title>
7
+ <style>
8
+ * { box-sizing: border-box; margin: 0; padding: 0; }
9
+ body {
10
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
11
+ min-height: 100vh;
12
+ display: flex;
13
+ align-items: center;
14
+ justify-content: center;
15
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
16
+ color: #fff;
17
+ padding: 20px;
18
+ }
19
+ .card {
20
+ background: rgba(255,255,255,0.12);
21
+ backdrop-filter: blur(10px);
22
+ border: 1px solid rgba(255,255,255,0.2);
23
+ border-radius: 16px;
24
+ padding: 40px 32px;
25
+ max-width: 380px;
26
+ width: 100%;
27
+ text-align: center;
28
+ box-shadow: 0 8px 32px rgba(0,0,0,0.2);
29
+ }
30
+ .logo {
31
+ font-size: 56px;
32
+ margin-bottom: 12px;
33
+ }
34
+ h1 { font-size: 22px; margin-bottom: 6px; font-weight: 600; }
35
+ p.sub { font-size: 13px; opacity: 0.85; margin-bottom: 24px; }
36
+ .download-btn {
37
+ display: inline-block;
38
+ background: #fff;
39
+ color: #5a3aa0;
40
+ padding: 14px 28px;
41
+ border-radius: 10px;
42
+ font-weight: 600;
43
+ text-decoration: none;
44
+ font-size: 15px;
45
+ transition: transform 0.15s, box-shadow 0.15s;
46
+ box-shadow: 0 4px 14px rgba(0,0,0,0.15);
47
+ }
48
+ .download-btn:hover {
49
+ transform: translateY(-2px);
50
+ box-shadow: 0 6px 20px rgba(0,0,0,0.25);
51
+ }
52
+ .meta {
53
+ margin-top: 20px;
54
+ font-size: 12px;
55
+ opacity: 0.7;
56
+ }
57
+ .note {
58
+ margin-top: 20px;
59
+ padding: 12px;
60
+ background: rgba(0,0,0,0.2);
61
+ border-radius: 8px;
62
+ font-size: 12px;
63
+ line-height: 1.5;
64
+ text-align: left;
65
+ }
66
+ .note strong { display: block; margin-bottom: 4px; }
67
+ </style>
68
+ </head>
69
+ <body>
70
+ <div class="card">
71
+ <div class="logo">📱</div>
72
+ <h1>Diana Maps</h1>
73
+ <p class="sub">Ứng dụng Android</p>
74
+ <a href="app.apk" class="download-btn" download>⬇️ Tải APK</a>
75
+ <div class="meta">Phiên bản APK · ~8.5 MB</div>
76
+ <div class="note">
77
+ <strong>Hướng dẫn cài đặt:</strong>
78
+ 1. Tải file APK về điện thoại<br>
79
+ 2. Mở file, cho phép "Cài từ nguồn không xác định"<br>
80
+ 3. Nhấn Cài đặt
81
+ </div>
82
+ </div>
83
+ </body>
84
+ </html>
admin/js/maps.js CHANGED
@@ -20,6 +20,8 @@ window.addEventListener('load', async () => {
20
  initSettings();
21
  initSearch();
22
  initStreetPanel();
 
 
23
 
24
  // Test pointr
25
  const allPointrs = [
 
20
  initSettings();
21
  initSearch();
22
  initStreetPanel();
23
+ await loadPois();
24
+ initPoiInteractions();
25
 
26
  // Test pointr
27
  const allPointrs = [
admin/js/maps/poi.js ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==================== POI STATE ====================
2
+ //
3
+ // Mirrors the pointr state model:
4
+ // _poiMap : Map<poiId, { poi, el, initialClientX, initialClientY, lat, long, edited }>
5
+ // _poiEditedIds : Set<poiId> of POIs with unsaved moves (queued for bulk save)
6
+ // activePoiId : currently-selected POI (drag / arrow-key target)
7
+ // isDraggingPoi : true while user is dragging an active POI marker
8
+
9
+ const _poiMap = new Map();
10
+ const _poiEditedIds = new Set();
11
+ let activePoiId = null;
12
+ let isDraggingPoi = false;
13
+
14
+ async function loadPois() {
15
+ const _apiBase = location.hostname === 'localhost' ? 'http://localhost:4000/api' : '/api';
16
+ try {
17
+ const res = await fetch(`${_apiBase}/pois`, {
18
+ headers: { 'X-API-Key': sessionStorage.getItem('admin_api_key') || '' }
19
+ });
20
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
21
+ const data = await res.json();
22
+ _poiMap.clear();
23
+ _poiEditedIds.clear();
24
+ (Array.isArray(data) ? data : []).forEach(p => {
25
+ if (p == null || p.id == null) return;
26
+ _poiMap.set(p.id, {
27
+ poi: p,
28
+ el: null,
29
+ initialClientX: 0,
30
+ initialClientY: 0,
31
+ lat: p.lat != null ? Number(p.lat) : null,
32
+ long: p.long != null ? Number(p.long) : null,
33
+ edited: false,
34
+ });
35
+ });
36
+ } catch (e) {
37
+ console.warn('Failed to load POIs:', e);
38
+ }
39
+ }
40
+
41
+ function _poiLabel(poi) {
42
+ const segs = (poi.name || '').split('|').map(s => s.trim()).filter(Boolean);
43
+ return segs[0] || poi.name || '';
44
+ }
45
+
46
+ function markPoiAsEdited(poiId) {
47
+ const entry = _poiMap.get(poiId);
48
+ if (!entry || entry.edited) return;
49
+ entry.edited = true;
50
+ _poiEditedIds.add(poiId);
51
+ if (entry.el) entry.el.classList.add('poi-edited');
52
+ }
53
+
54
+ function updateActivePoiVisual() {
55
+ document.querySelectorAll('.poi-marker.active').forEach(el => el.classList.remove('active'));
56
+ if (activePoiId != null) {
57
+ const e = _poiMap.get(activePoiId);
58
+ if (e && e.el) e.el.classList.add('active');
59
+ }
60
+ }
61
+
62
+ function _attachPoiInteractions(el, poiId) {
63
+ el.addEventListener('mousedown', (e) => {
64
+ const editor = document.querySelector('#editor');
65
+ if (!editor || editor.value !== 'move') return;
66
+ activePoiId = poiId;
67
+ if (typeof activePointrId !== 'undefined') activePointrId = null;
68
+ updateActivePoiVisual();
69
+ if (typeof updateActivePointrVisual === 'function') updateActivePointrVisual();
70
+ isDraggingPoi = true;
71
+ e.stopPropagation();
72
+ e.preventDefault();
73
+ });
74
+ el.addEventListener('click', (e) => {
75
+ e.stopPropagation();
76
+ const editor = document.querySelector('#editor');
77
+ if (editor && editor.value === 'move') {
78
+ activePoiId = poiId;
79
+ if (typeof activePointrId !== 'undefined') activePointrId = null;
80
+ updateActivePoiVisual();
81
+ if (typeof updateActivePointrVisual === 'function') updateActivePointrVisual();
82
+ }
83
+ });
84
+ }
85
+
86
+ function renderPois() {
87
+ // Detach + remove any existing elements (state is preserved in _poiMap)
88
+ _poiMap.forEach(entry => {
89
+ if (entry.el) { entry.el.remove(); entry.el = null; }
90
+ });
91
+
92
+ const show = document.getElementById('sIsPoi')?.checked;
93
+ if (!show || _poiMap.size === 0) return;
94
+
95
+ const layer = document.querySelector('.coordinates');
96
+ const container = document.querySelector('.container');
97
+ const sizePer = parseInt(document.getElementById('sSize')?.value || 400) / 2400;
98
+ const sl = container.scrollLeft;
99
+ const st = container.scrollTop;
100
+
101
+ _poiMap.forEach((entry, poiId) => {
102
+ const { poi, lat, long } = entry;
103
+ if (lat == null || long == null) return;
104
+ const { left, top } = latLonToPixel(lat, long, sizePer);
105
+ entry.initialClientX = left;
106
+ entry.initialClientY = top;
107
+
108
+ const el = document.createElement('div');
109
+ el.className = 'poi-marker';
110
+ el.id = `poi-marker-${poiId}`;
111
+ if (entry.edited) el.classList.add('poi-edited');
112
+ el.style.left = (left - sl) + 'px';
113
+ el.style.top = (top - st) + 'px';
114
+ el.innerHTML = `
115
+ <div class="poi-marker-dot"></div>
116
+ <div class="poi-marker-label" title="${escapeHtml(poi.address || poi.name || '')}">${escapeHtml(_poiLabel(poi))}</div>
117
+ `;
118
+ _attachPoiInteractions(el, poiId);
119
+ layer.appendChild(el);
120
+ entry.el = el;
121
+ });
122
+ updateActivePoiVisual();
123
+ }
124
+
125
+ function updatePoiMarkerPositions() {
126
+ if (_poiMap.size === 0) return;
127
+ const container = document.querySelector('.container');
128
+ const sizePer = parseInt(document.getElementById('sSize')?.value || 400) / 2400;
129
+ const sl = container.scrollLeft;
130
+ const st = container.scrollTop;
131
+ _poiMap.forEach(entry => {
132
+ if (!entry.el || entry.lat == null || entry.long == null) return;
133
+ const { left, top } = latLonToPixel(entry.lat, entry.long, sizePer);
134
+ entry.initialClientX = left;
135
+ entry.initialClientY = top;
136
+ entry.el.style.left = (left - sl) + 'px';
137
+ entry.el.style.top = (top - st) + 'px';
138
+ });
139
+ }
140
+
141
+ // ==================== POI DRAG / MOVE ====================
142
+
143
+ function _onPoiMouseMove(e) {
144
+ if (!isDraggingPoi || activePoiId == null) return;
145
+ const entry = _poiMap.get(activePoiId);
146
+ if (!entry) { isDraggingPoi = false; return; }
147
+ markPoiAsEdited(activePoiId);
148
+ const container = document.querySelector('.container');
149
+ entry.initialClientX = e.clientX + container.scrollLeft;
150
+ entry.initialClientY = e.clientY + container.scrollTop;
151
+ const sizePer = parseInt(document.getElementById('sSize')?.value || 400) / 2400;
152
+ const { lat: newLat, lon: newLon } = pixelToLatLon(entry.initialClientX, entry.initialClientY, sizePer);
153
+ entry.lat = newLat;
154
+ entry.long = newLon;
155
+ if (entry.el) {
156
+ entry.el.style.left = e.clientX + 'px';
157
+ entry.el.style.top = e.clientY + 'px';
158
+ }
159
+ }
160
+
161
+ function _onPoiMouseUp() { isDraggingPoi = false; }
162
+
163
+ function movePoi(direction) {
164
+ if (activePoiId == null) return;
165
+ const entry = _poiMap.get(activePoiId);
166
+ if (!entry) return;
167
+ markPoiAsEdited(activePoiId);
168
+ const step = 0.5;
169
+ switch (direction) {
170
+ case 'ArrowUp': entry.initialClientY -= step; break;
171
+ case 'ArrowDown': entry.initialClientY += step; break;
172
+ case 'ArrowLeft': entry.initialClientX -= step; break;
173
+ case 'ArrowRight': entry.initialClientX += step; break;
174
+ }
175
+ const sizePer = parseInt(document.getElementById('sSize')?.value || 400) / 2400;
176
+ const { lat: newLat, lon: newLon } = pixelToLatLon(entry.initialClientX, entry.initialClientY, sizePer);
177
+ entry.lat = newLat;
178
+ entry.long = newLon;
179
+ updatePoiMarkerPositions();
180
+ }
181
+
182
+ function initPoiInteractions() {
183
+ document.addEventListener('mousemove', _onPoiMouseMove);
184
+ document.addEventListener('mouseup', _onPoiMouseUp);
185
+ }
186
+
187
+ // ==================== BULK SAVE INTEGRATION ====================
188
+
189
+ function getEditedPoisForSave() {
190
+ const out = [];
191
+ _poiEditedIds.forEach(id => {
192
+ const entry = _poiMap.get(id);
193
+ if (!entry) return;
194
+ if (entry.lat == null || entry.long == null) return;
195
+ out.push({
196
+ poi_id: id,
197
+ name: entry.poi.name || '',
198
+ lat: entry.lat,
199
+ long: entry.long,
200
+ });
201
+ });
202
+ return out;
203
+ }
204
+
205
+ async function savePoisBulk() {
206
+ const items = getEditedPoisForSave();
207
+ if (items.length === 0) return { saved: 0 };
208
+ const _apiBase = location.hostname === 'localhost' ? 'http://localhost:4000/api' : '/api';
209
+ const payload = items.map(i => ({ poi_id: i.poi_id, lat: i.lat, long: i.long }));
210
+ const resp = await fetch(`${_apiBase}/pois/bulk`, {
211
+ method: 'POST',
212
+ headers: { 'Content-Type': 'application/json', 'X-API-Key': sessionStorage.getItem('admin_api_key') || '' },
213
+ body: JSON.stringify(payload),
214
+ });
215
+ if (!resp.ok) {
216
+ const txt = await resp.text();
217
+ throw new Error(txt || `POI bulk save failed (${resp.status})`);
218
+ }
219
+ const result = await resp.json();
220
+ // Clear edited markers + sync entry.poi.lat/long with what we just saved
221
+ items.forEach(i => {
222
+ const entry = _poiMap.get(i.poi_id);
223
+ if (!entry) return;
224
+ entry.edited = false;
225
+ if (entry.poi) { entry.poi.lat = i.lat; entry.poi.long = i.long; }
226
+ if (entry.el) entry.el.classList.remove('poi-edited');
227
+ });
228
+ _poiEditedIds.clear();
229
+ return { saved: items.length, result };
230
+ }
admin/js/maps/pointr.js CHANGED
@@ -140,6 +140,7 @@ function updatePointrPositions() {
140
  pointrData.forEach(applyPos);
141
  pointrReload.forEach(applyPos);
142
  refreshStreetPath();
 
143
  }
144
 
145
  // ==================== STREET PATH ====================
@@ -690,11 +691,14 @@ function showSaveAllModal() {
690
  pointrsList.push({ id: data.id, name, lat: data.lat, lon: data.lon, streets, dbId: data.dbId || null });
691
  });
692
 
693
- if (pointrsList.length === 0) {
 
 
 
694
  openModal(`
695
  <div class="modal-content">
696
  <h2>Save Pointrs</h2>
697
- <div class="modal-context">Không có Pointr nào cần lưu (hoặc chưa được gán street).</div>
698
  <div class="modal-actions">
699
  <button type="button" class="btn-cancel" onclick="closeModal()">Đóng</button>
700
  </div>
@@ -703,14 +707,29 @@ function showSaveAllModal() {
703
  return;
704
  }
705
 
706
- let html = `<div class="modal-content"><h2>Save Pointrs</h2><div class="modal-context">Danh sách Pointr sẽ được lưu:</div><ul style="margin:8px 0 0 18px;font-size:12px;">`;
707
- pointrsList.forEach(pt => {
708
- const streetNames = pt.streets
709
- .map(sid => (typeof allStreetsData !== 'undefined' ? allStreetsData : []).find(s => s.id === sid)?.name)
710
- .filter(Boolean).join(' - ');
711
- html += `<li style="margin:4px 0">${escapeHtml(pt.name)} <span style="color:#777;font-size:11px;margin-left:6px">[${escapeHtml(streetNames)}]</span> <span style="color:#777;font-size:11px;margin-left:6px">(#${pt.id}${pt.dbId ? ' ✏️ update' : ' 🆕 new'})</span></li>`;
712
- });
713
- html += `</ul><div class="modal-actions"><button type="button" class="btn-cancel" onclick="closeModal()">Đóng</button><button type="button" class="btn-submit" id="confirmSaveAll">Confirm</button></div></div>`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
714
 
715
  openModal(html);
716
 
@@ -731,76 +750,77 @@ function showSaveAllModal() {
731
  });
732
 
733
  console.log('positions bulk payload:', JSON.stringify(payload));
734
- if (payload.length === 0) {
735
- alert('No valid points to save.');
736
- confirmBtn.disabled = false;
737
- confirmBtn.textContent = 'Confirm';
738
- return;
739
- }
740
 
741
  try {
742
  const _apiBaseBulk = location.hostname === 'localhost' ? 'http://localhost:4000/api' : '/api';
743
- const resp = await fetch(`${_apiBaseBulk}/positions/bulk`, {
744
- method: 'POST',
745
- headers: { 'Content-Type': 'application/json', 'X-API-Key': sessionStorage.getItem('admin_api_key') || '' },
746
- body: JSON.stringify(payload)
747
- });
748
- if (!resp.ok) {
749
- const txt = await resp.text();
750
- throw new Error(txt || 'Server error');
751
- }
752
- const result = await resp.json();
753
- // result.created is expected to be an array of created/updated DB rows
754
- const created = result.created || result;
755
-
756
- // Build lat/lon → server row lookup for dbId assignment
757
- const latLonToServer = new Map();
758
- if (Array.isArray(created)) {
759
- created.forEach(pos => {
760
- const lat = parseFloat(pos.lat ?? pos.y);
761
- const lon = parseFloat(pos.long ?? pos.x);
762
- if (!isNaN(lat) && !isNaN(lon)) {
763
- latLonToServer.set(`${lat.toFixed(9)},${lon.toFixed(9)}`, pos);
764
- }
765
  });
766
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
767
 
768
- // Move ALL saved pointrs from pointrData → pointrReload using pointrsList
769
- // (pointrsList was captured at modal-open, so its ids are reliable even if server
770
- // response lat/lon precision differs)
771
- pointrsList.forEach(pt => {
772
- const data = pointrData.get(pt.id);
773
- if (!data) return; // already moved or deleted
774
-
775
- // Try to update dbId / metadata from server response via lat/lon key
776
- const key = `${Number(pt.lat).toFixed(9)},${Number(pt.lon).toFixed(9)}`;
777
- const pos = latLonToServer.get(key);
778
- if (pos) {
779
- data.dbId = pos.id;
780
- data.streets = Array.isArray(pos.streets) ? pos.streets : (data.streets || []);
781
- const sp = streetPointsList.find(p => p.id === pt.id);
782
- if (sp) {
783
- sp.streetId = data.streets[0] ?? sp.streetId;
784
- sp.ban = pos.ban ?? sp.ban;
785
- sp.speed = pos.speed ?? sp.speed;
786
- sp.park = pos.park ?? sp.park;
787
- sp.lane = pos.lane ?? sp.lane;
788
- sp.toll = pos.tool ?? sp.toll;
789
- sp.flooding = pos.flooding ?? sp.flooding;
790
  }
791
- } else if (pt.dbId) {
792
- // Was an update — keep existing dbId
793
- data.dbId = pt.dbId;
794
- }
795
 
796
- if (data.dbId) renderedDbIds.add(data.dbId);
797
- pointrReload.set(pt.id, data);
798
- pointrData.delete(pt.id);
799
- if (data.element) data.element.classList.add('pointr-reload');
800
- });
 
 
 
 
 
 
 
 
801
 
802
  closeModal();
803
- alert('Saved positions successfully.');
 
 
 
804
  } catch (err) {
805
  console.error(err);
806
  const errEl = document.getElementById('modalError');
@@ -1041,6 +1061,11 @@ function initKeyboardListener() {
1041
  if (editor.value === 'move' && activePointrId) {
1042
  movePointr(e.key);
1043
  e.preventDefault();
 
 
 
 
 
1044
  }
1045
  }
1046
  if (e.key === 'Delete' && selectedPointrIds.size > 0) {
@@ -1087,7 +1112,13 @@ function initEditorListener() {
1087
  _applyEditorCursor(e.target.value);
1088
  activePointrId = null;
1089
  updateActivePointrVisual();
 
 
 
 
1090
  });
1091
  // Apply initial cursor on load
1092
  _applyEditorCursor(editor.value);
 
 
1093
  }
 
140
  pointrData.forEach(applyPos);
141
  pointrReload.forEach(applyPos);
142
  refreshStreetPath();
143
+ if (typeof updatePoiMarkerPositions === 'function') updatePoiMarkerPositions();
144
  }
145
 
146
  // ==================== STREET PATH ====================
 
691
  pointrsList.push({ id: data.id, name, lat: data.lat, lon: data.lon, streets, dbId: data.dbId || null });
692
  });
693
 
694
+ // Edited POIs queued for bulk update (poi.js owns this list)
695
+ const poisList = (typeof getEditedPoisForSave === 'function') ? getEditedPoisForSave() : [];
696
+
697
+ if (pointrsList.length === 0 && poisList.length === 0) {
698
  openModal(`
699
  <div class="modal-content">
700
  <h2>Save Pointrs</h2>
701
+ <div class="modal-context">Không có Pointr/POI nào cần lưu.</div>
702
  <div class="modal-actions">
703
  <button type="button" class="btn-cancel" onclick="closeModal()">Đóng</button>
704
  </div>
 
707
  return;
708
  }
709
 
710
+ let html = `<div class="modal-content"><h2>Save Pointrs</h2>`;
711
+
712
+ if (pointrsList.length > 0) {
713
+ html += `<div class="modal-context">Pointrs (${pointrsList.length}):</div><ul style="margin:8px 0 0 18px;font-size:12px;">`;
714
+ pointrsList.forEach(pt => {
715
+ const streetNames = pt.streets
716
+ .map(sid => (typeof allStreetsData !== 'undefined' ? allStreetsData : []).find(s => s.id === sid)?.name)
717
+ .filter(Boolean).join(' - ');
718
+ html += `<li style="margin:4px 0">${escapeHtml(pt.name)} <span style="color:#777;font-size:11px;margin-left:6px">[${escapeHtml(streetNames)}]</span> <span style="color:#777;font-size:11px;margin-left:6px">(#${pt.id}${pt.dbId ? ' ✏️ update' : ' 🆕 new'})</span></li>`;
719
+ });
720
+ html += `</ul>`;
721
+ }
722
+
723
+ if (poisList.length > 0) {
724
+ html += `<div class="modal-context" style="margin-top:12px;">POIs (${poisList.length}):</div><ul style="margin:8px 0 0 18px;font-size:12px;">`;
725
+ poisList.forEach(p => {
726
+ html += `<li style="margin:4px 0">${escapeHtml(p.name || ('POI #' + p.poi_id))} <span style="color:#777;font-size:11px;margin-left:6px">[${p.lat.toFixed(6)}, ${p.long.toFixed(6)}]</span> <span style="color:#777;font-size:11px;margin-left:6px">(#${p.poi_id} ✏️ update)</span></li>`;
727
+ });
728
+ html += `</ul>`;
729
+ }
730
+
731
+ html += `<div class="modal-error" id="modalError" style="margin-top:8px;"></div>`;
732
+ html += `<div class="modal-actions"><button type="button" class="btn-cancel" onclick="closeModal()">Đóng</button><button type="button" class="btn-submit" id="confirmSaveAll">Confirm</button></div></div>`;
733
 
734
  openModal(html);
735
 
 
750
  });
751
 
752
  console.log('positions bulk payload:', JSON.stringify(payload));
 
 
 
 
 
 
753
 
754
  try {
755
  const _apiBaseBulk = location.hostname === 'localhost' ? 'http://localhost:4000/api' : '/api';
756
+
757
+ // 1) Save pointrs (if any)
758
+ if (payload.length > 0) {
759
+ const resp = await fetch(`${_apiBaseBulk}/positions/bulk`, {
760
+ method: 'POST',
761
+ headers: { 'Content-Type': 'application/json', 'X-API-Key': sessionStorage.getItem('admin_api_key') || '' },
762
+ body: JSON.stringify(payload)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763
  });
764
+ if (!resp.ok) {
765
+ const txt = await resp.text();
766
+ throw new Error(txt || 'Server error');
767
+ }
768
+ const result = await resp.json();
769
+ const created = result.created || result;
770
+
771
+ // Build lat/lon → server row lookup for dbId assignment
772
+ const latLonToServer = new Map();
773
+ if (Array.isArray(created)) {
774
+ created.forEach(pos => {
775
+ const lat = parseFloat(pos.lat ?? pos.y);
776
+ const lon = parseFloat(pos.long ?? pos.x);
777
+ if (!isNaN(lat) && !isNaN(lon)) {
778
+ latLonToServer.set(`${lat.toFixed(9)},${lon.toFixed(9)}`, pos);
779
+ }
780
+ });
781
+ }
782
 
783
+ pointrsList.forEach(pt => {
784
+ const data = pointrData.get(pt.id);
785
+ if (!data) return;
786
+ const key = `${Number(pt.lat).toFixed(9)},${Number(pt.lon).toFixed(9)}`;
787
+ const pos = latLonToServer.get(key);
788
+ if (pos) {
789
+ data.dbId = pos.id;
790
+ data.streets = Array.isArray(pos.streets) ? pos.streets : (data.streets || []);
791
+ const sp = streetPointsList.find(p => p.id === pt.id);
792
+ if (sp) {
793
+ sp.streetId = data.streets[0] ?? sp.streetId;
794
+ sp.ban = pos.ban ?? sp.ban;
795
+ sp.speed = pos.speed ?? sp.speed;
796
+ sp.park = pos.park ?? sp.park;
797
+ sp.lane = pos.lane ?? sp.lane;
798
+ sp.toll = pos.tool ?? sp.toll;
799
+ sp.flooding = pos.flooding ?? sp.flooding;
800
+ }
801
+ } else if (pt.dbId) {
802
+ data.dbId = pt.dbId;
 
 
803
  }
 
 
 
 
804
 
805
+ if (data.dbId) renderedDbIds.add(data.dbId);
806
+ pointrReload.set(pt.id, data);
807
+ pointrData.delete(pt.id);
808
+ if (data.element) data.element.classList.add('pointr-reload');
809
+ });
810
+ }
811
+
812
+ // 2) Save POIs (if any)
813
+ let poiSavedCount = 0;
814
+ if (poisList.length > 0 && typeof savePoisBulk === 'function') {
815
+ const poiRes = await savePoisBulk();
816
+ poiSavedCount = poiRes.saved || 0;
817
+ }
818
 
819
  closeModal();
820
+ const parts = [];
821
+ if (payload.length > 0) parts.push(`${payload.length} pointr(s)`);
822
+ if (poiSavedCount > 0) parts.push(`${poiSavedCount} POI(s)`);
823
+ alert('Saved ' + (parts.join(' + ') || 'nothing') + ' successfully.');
824
  } catch (err) {
825
  console.error(err);
826
  const errEl = document.getElementById('modalError');
 
1061
  if (editor.value === 'move' && activePointrId) {
1062
  movePointr(e.key);
1063
  e.preventDefault();
1064
+ } else if (editor.value === 'move'
1065
+ && typeof activePoiId !== 'undefined' && activePoiId != null
1066
+ && typeof movePoi === 'function') {
1067
+ movePoi(e.key);
1068
+ e.preventDefault();
1069
  }
1070
  }
1071
  if (e.key === 'Delete' && selectedPointrIds.size > 0) {
 
1112
  _applyEditorCursor(e.target.value);
1113
  activePointrId = null;
1114
  updateActivePointrVisual();
1115
+ if (typeof activePoiId !== 'undefined') {
1116
+ activePoiId = null;
1117
+ if (typeof updateActivePoiVisual === 'function') updateActivePoiVisual();
1118
+ }
1119
  });
1120
  // Apply initial cursor on load
1121
  _applyEditorCursor(editor.value);
1122
+ // Also set body class so CSS mode-specific selectors apply on first render
1123
+ document.body.className = `mode-${editor.value}`;
1124
  }
admin/js/maps/settings.js CHANGED
@@ -76,6 +76,10 @@ function initSettings() {
76
  refreshStreetPath();
77
  });
78
 
 
 
 
 
79
  document.getElementById('settingsSave').addEventListener('click', () => {
80
  const items = parseInt(document.getElementById('sItems').value) || 23;
81
  const newSize = parseInt(document.getElementById('sSize').value) || 400;
 
76
  refreshStreetPath();
77
  });
78
 
79
+ document.getElementById('sIsPoi').addEventListener('change', () => {
80
+ renderPois();
81
+ });
82
+
83
  document.getElementById('settingsSave').addEventListener('click', () => {
84
  const items = parseInt(document.getElementById('sItems').value) || 23;
85
  const newSize = parseInt(document.getElementById('sSize').value) || 400;
admin/maps.html CHANGED
@@ -88,6 +88,10 @@
88
  <input type="checkbox" id="sIsStreetPath">
89
  Street Path
90
  </label>
 
 
 
 
91
  <label class="settings-label">
92
  Opacity
93
  <input type="range" id="sOpacity" value="100" min="0" max="100" step="1" style="width:100%;">
@@ -101,6 +105,7 @@
101
  <script src="js/maps/navigation.js"></script>
102
  <script src="js/maps/settings.js"></script>
103
  <script src="js/maps/pointr.js"></script>
 
104
  <script src="js/maps/search.js"></script>
105
  <script src="js/maps.js"></script>
106
  </body>
 
88
  <input type="checkbox" id="sIsStreetPath">
89
  Street Path
90
  </label>
91
+ <label class="settings-label settings-label--row">
92
+ <input type="checkbox" id="sIsPoi">
93
+ POI
94
+ </label>
95
  <label class="settings-label">
96
  Opacity
97
  <input type="range" id="sOpacity" value="100" min="0" max="100" step="1" style="width:100%;">
 
105
  <script src="js/maps/navigation.js"></script>
106
  <script src="js/maps/settings.js"></script>
107
  <script src="js/maps/pointr.js"></script>
108
+ <script src="js/maps/poi.js"></script>
109
  <script src="js/maps/search.js"></script>
110
  <script src="js/maps.js"></script>
111
  </body>
backend/main.py CHANGED
@@ -90,6 +90,42 @@ async def health_check():
90
  raise HTTPException(status_code=500, detail="Database connection failed")
91
 
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  # ==================== CATEGORIES ENDPOINTS ====================
94
 
95
  @app.get("/api/categories", response_model=List[Category])
 
90
  raise HTTPException(status_code=500, detail="Database connection failed")
91
 
92
 
93
+ @app.get("/api/pois")
94
+ async def list_pois(city_id: Optional[int] = Query(None), district_id: Optional[int] = Query(None)):
95
+ try:
96
+ query = supabase.table("Pois").select("id, name, address, type, lat, long, city_id, district_id")
97
+ if district_id is not None:
98
+ query = query.eq("district_id", district_id)
99
+ elif city_id is not None:
100
+ query = query.eq("city_id", city_id)
101
+ result = query.order("name").execute()
102
+ return result.data or []
103
+ except Exception as e:
104
+ raise HTTPException(status_code=500, detail=str(e))
105
+
106
+
107
+ @app.put("/api/pois/{poi_id}")
108
+ async def update_poi(poi_id: int, body: dict = Body(...)):
109
+ try:
110
+ return await MapsService.update_poi(poi_id, body)
111
+ except Exception as e:
112
+ logger.error(f"Error updating POI {poi_id}: {str(e)}")
113
+ raise HTTPException(status_code=500, detail=str(e))
114
+
115
+
116
+ @app.post("/api/pois/bulk")
117
+ async def update_pois_bulk(payload: List[dict] = Body(...)):
118
+ """Bulk-update POIs.
119
+ Payload: [{poi_id, lat?, long?, name?, address?, type?}, ...]
120
+ """
121
+ try:
122
+ updated = await MapsService.update_pois_bulk(payload)
123
+ return {"updated": updated}
124
+ except Exception as e:
125
+ logger.error(f"Error updating POIs bulk: {str(e)}")
126
+ raise HTTPException(status_code=500, detail=str(e))
127
+
128
+
129
  # ==================== CATEGORIES ENDPOINTS ====================
130
 
131
  @app.get("/api/categories", response_model=List[Category])
backend/services/maps_service.py CHANGED
@@ -450,6 +450,45 @@ class MapsService:
450
  except Exception as e:
451
  raise Exception(f"Failed to create/update positions bulk: {str(e)}")
452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453
  @staticmethod
454
  async def search_nearest(points: list) -> dict:
455
  """
 
450
  except Exception as e:
451
  raise Exception(f"Failed to create/update positions bulk: {str(e)}")
452
 
453
+ @staticmethod
454
+ async def update_poi(poi_id: int, fields: dict) -> dict:
455
+ """Update a single Pois row with the provided fields (lat/long/name/address/type).
456
+ Returns the updated row.
457
+ """
458
+ try:
459
+ allowed = {"lat", "long", "name", "address", "type", "city_id", "district_id"}
460
+ payload = {k: v for k, v in (fields or {}).items() if k in allowed and v is not None}
461
+ if not payload:
462
+ raise Exception("No valid fields to update")
463
+ result = supabase.table("Pois").update(payload).eq("id", poi_id).execute()
464
+ if not result.data:
465
+ raise Exception(f"POI #{poi_id} not found or update failed")
466
+ return result.data[0]
467
+ except Exception as e:
468
+ raise Exception(f"Failed to update POI: {str(e)}")
469
+
470
+ @staticmethod
471
+ async def update_pois_bulk(payload: list) -> list:
472
+ """payload: [{poi_id, lat?, long?, name?, address?, type?}, ...]
473
+ Updates each POI by id. Returns list of updated rows.
474
+ """
475
+ updated = []
476
+ allowed = {"lat", "long", "name", "address", "type", "city_id", "district_id"}
477
+ try:
478
+ for item in payload or []:
479
+ poi_id = item.get("poi_id") or item.get("id")
480
+ if not poi_id:
481
+ continue
482
+ fields = {k: v for k, v in item.items() if k in allowed and v is not None}
483
+ if not fields:
484
+ continue
485
+ result = supabase.table("Pois").update(fields).eq("id", int(poi_id)).execute()
486
+ if result.data:
487
+ updated.append(result.data[0])
488
+ return updated
489
+ except Exception as e:
490
+ raise Exception(f"Failed to update POIs bulk: {str(e)}")
491
+
492
  @staticmethod
493
  async def search_nearest(points: list) -> dict:
494
  """