-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.html
More file actions
1359 lines (1191 loc) · 45.2 KB
/
admin.html
File metadata and controls
1359 lines (1191 loc) · 45.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OVICUE — Admin</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #f4f5f7;
--surface: #ffffff;
--border: #e2e4e9;
--text: #1a1d23;
--muted: #6b7280;
--primary: #2563eb;
--primary-hover: #1d4ed8;
--danger: #dc2626;
--danger-hover: #b91c1c;
--success: #16a34a;
--warning: #d97706;
--badge-auto: #dbeafe;
--badge-auto-text: #1e40af;
--badge-manual: #dcfce7;
--badge-manual-text: #166534;
--badge-black: #f1f0ef;
--badge-black-text: #374151;
--badge-unresolved: #ede9fe;
--badge-unresolved-text: #5b21b6;
--rojo: #fee2e2;
--rojo-text: #991b1b;
--naranja: #ffedd5;
--naranja-text: #92400e;
--amarillo: #fef9c3;
--amarillo-text: #854d0e;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
font-size: 14px;
}
header {
background: var(--surface);
border-bottom: 1px solid var(--border);
padding: 0 24px;
height: 56px;
display: flex;
align-items: center;
justify-content: space-between;
position: sticky;
top: 0;
z-index: 100;
}
header h1 { font-size: 16px; font-weight: 600; }
header h1 span { color: var(--muted); font-weight: 400; }
#auth-status {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: var(--muted);
}
.dot {
width: 8px; height: 8px;
border-radius: 50%;
background: var(--border);
}
.dot.ok { background: var(--success); }
main { max-width: 1100px; margin: 0 auto; padding: 24px 16px; }
.card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 20px;
margin-bottom: 16px;
}
.card h2 { font-size: 14px; font-weight: 600; margin-bottom: 14px; }
.row {
display: flex;
gap: 8px;
align-items: flex-end;
}
.field { display: flex; flex-direction: column; gap: 5px; flex: 1; }
.field label { font-size: 12px; font-weight: 500; color: var(--muted); }
input[type="text"], input[type="password"], select {
padding: 8px 12px;
border: 1px solid var(--border);
border-radius: 6px;
font-size: 14px;
background: var(--surface);
color: var(--text);
width: 100%;
outline: none;
transition: border-color 0.15s;
}
input:focus, select:focus { border-color: var(--primary); }
input[type="number"] {
padding: 8px 12px;
border: 1px solid var(--border);
border-radius: 6px;
font-size: 14px;
background: var(--surface);
color: var(--text);
width: 100%;
outline: none;
transition: border-color 0.15s;
}
input[type="number"]:focus { border-color: var(--primary); }
textarea {
padding: 8px 12px;
border: 1px solid var(--border);
border-radius: 6px;
font-size: 13px;
background: var(--surface);
color: var(--text);
width: 100%;
outline: none;
resize: vertical;
font-family: inherit;
line-height: 1.5;
transition: border-color 0.15s;
}
textarea:focus { border-color: var(--primary); }
.coords-row { display: flex; gap: 8px; }
.coords-row .field { flex: 1; }
.alias-chips {
display: flex;
flex-wrap: wrap;
gap: 4px;
max-height: 48px;
overflow: hidden;
}
.alias-chip {
background: var(--badge-black);
color: var(--badge-black-text);
border-radius: 3px;
padding: 1px 6px;
font-size: 11px;
}
.btn-success { background: var(--success); color: #fff; }
.btn-success:hover:not(:disabled) { background: #15803d; }
button {
padding: 8px 16px;
border: none;
border-radius: 6px;
font-size: 13px;
font-weight: 500;
cursor: pointer;
white-space: nowrap;
transition: background 0.15s, opacity 0.15s;
}
button:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-primary { background: var(--primary); color: #fff; }
.btn-primary:hover:not(:disabled) { background: var(--primary-hover); }
.btn-danger { background: var(--danger); color: #fff; }
.btn-danger:hover:not(:disabled) { background: var(--danger-hover); }
.btn-ghost {
background: transparent;
color: var(--muted);
border: 1px solid var(--border);
}
.btn-ghost:hover:not(:disabled) { background: var(--bg); }
.btn-sm { padding: 5px 10px; font-size: 12px; }
#msg {
padding: 10px 14px;
border-radius: 6px;
font-size: 13px;
margin-bottom: 16px;
display: none;
}
#msg.ok { background: #dcfce7; color: #166534; display: block; }
#msg.err { background: #fee2e2; color: #991b1b; display: block; }
#msg.info { background: #dbeafe; color: #1e40af; display: block; }
/* Events table */
.toolbar {
display: flex;
gap: 8px;
margin-bottom: 12px;
align-items: center;
}
.toolbar input { max-width: 280px; }
.count { font-size: 13px; color: var(--muted); margin-left: auto; }
table {
width: 100%;
border-collapse: collapse;
}
th {
text-align: left;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--muted);
padding: 8px 12px;
border-bottom: 1px solid var(--border);
}
td {
padding: 10px 12px;
border-bottom: 1px solid var(--border);
vertical-align: top;
}
tr:last-child td { border-bottom: none; }
tr:hover td { background: var(--bg); }
.badge {
display: inline-block;
padding: 2px 7px;
border-radius: 4px;
font-size: 11px;
font-weight: 500;
}
.badge-auto { background: var(--badge-auto); color: var(--badge-auto-text); }
.badge-manual { background: var(--badge-manual); color: var(--badge-manual-text); }
.badge-rojo { background: var(--rojo); color: var(--rojo-text); }
.badge-naranja { background: var(--naranja); color: var(--naranja-text); }
.badge-amarillo { background: var(--amarillo); color: var(--amarillo-text); }
.badge-archivado { background: var(--badge-black); color: var(--badge-black-text); }
.badge-unresolved { background: var(--badge-unresolved); color: var(--badge-unresolved-text); }
.actions { display: flex; gap: 6px; flex-wrap: wrap; }
a.src-link {
color: var(--primary);
text-decoration: none;
font-size: 12px;
word-break: break-all;
}
a.src-link:hover { text-decoration: underline; }
/* Modal */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.4);
z-index: 200;
display: none;
align-items: center;
justify-content: center;
}
.modal-overlay.open { display: flex; }
.modal {
background: var(--surface);
border-radius: 12px;
padding: 24px;
width: 100%;
max-width: 460px;
margin: 16px;
}
.modal h3 { font-size: 15px; font-weight: 600; margin-bottom: 6px; }
.modal .sub { font-size: 12px; color: var(--muted); margin-bottom: 18px; }
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 20px;
}
.spinner {
display: inline-block;
width: 14px; height: 14px;
border: 2px solid currentColor;
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.6s linear infinite;
vertical-align: middle;
margin-right: 4px;
}
@keyframes spin { to { transform: rotate(360deg); } }
#loading-row td {
text-align: center;
color: var(--muted);
padding: 32px;
}
#auth-section { display: block; }
#main-section { display: none; }
.workflow-link {
font-size: 12px;
color: var(--primary);
text-decoration: none;
}
.workflow-link:hover { text-decoration: underline; }
.stack {
display: flex;
flex-direction: column;
gap: 4px;
}
.muted {
color: var(--muted);
font-size: 12px;
}
</style>
</head>
<body>
<header>
<h1>OVICUE <span>/ Admin</span></h1>
<div id="auth-status">
<div class="dot" id="auth-dot"></div>
<span id="auth-label">No conectado</span>
<button class="btn-ghost btn-sm" id="btn-logout" style="display:none" onclick="logout()">Salir</button>
</div>
</header>
<main>
<div id="msg"></div>
<!-- Auth -->
<div class="card" id="auth-section">
<h2>Conectar con GitHub</h2>
<div class="row">
<div class="field">
<label>Token de acceso personal (repo scope)</label>
<input type="password" id="token-input" placeholder="ghp_…" autocomplete="off">
</div>
<button class="btn-primary" onclick="connect()">Conectar</button>
</div>
<p style="font-size:12px;color:var(--muted);margin-top:10px">
El token se guarda solo en memoria de la pestaña (sessionStorage) y nunca sale de tu navegador.
Necesita permisos <code>repo</code> y <code>workflow</code>.
</p>
</div>
<!-- Main panel -->
<div id="main-section">
<!-- Add news -->
<div class="card">
<h2>Agregar noticia por URL</h2>
<div class="row">
<div class="field">
<label>URL de la nota</label>
<input type="text" id="news-url" placeholder="https://www.diariodemorelos.com/noticias/…">
</div>
<button class="btn-primary" id="btn-add-news" onclick="addNews()">Agregar</button>
</div>
<p style="font-size:12px;color:var(--muted);margin-top:10px">
Lanza el workflow <code>add_news.yml</code> en GitHub Actions. La noticia aparecerá en el mapa
en cuanto el workflow termine (~3 min). Puedes ver el progreso en
<a class="workflow-link" href="https://github.com/ebalderasr/cuernavaca-risk-map/actions/workflows/add_news.yml" target="_blank">Actions</a>.
</p>
</div>
<!-- Events list -->
<div class="card">
<h2>Noticias en el mapa</h2>
<div class="toolbar">
<input type="text" id="search" placeholder="Buscar por lugar, delito o URL…" oninput="filterTable()">
<span class="count" id="event-count"></span>
<button class="btn-ghost btn-sm" onclick="loadAll()">↺ Recargar</button>
</div>
<div style="overflow-x:auto">
<table>
<thead>
<tr>
<th>Fecha</th>
<th>Lugar</th>
<th>Delito</th>
<th>Fuente</th>
<th>Origen</th>
<th>Acciones</th>
</tr>
</thead>
<tbody id="events-body">
<tr id="loading-row"><td colspan="6"><span class="spinner"></span> Cargando…</td></tr>
</tbody>
</table>
</div>
</div>
<!-- Unresolved violent news -->
<div class="card">
<h2>Violentas sin clasificar</h2>
<div class="toolbar">
<input type="text" id="unresolved-search" placeholder="Buscar por título, delito o ubicación…" oninput="filterUnresolvedTable()">
<span class="count" id="unresolved-count"></span>
<button class="btn-ghost btn-sm" onclick="loadAll()">↺ Recargar</button>
</div>
<div style="overflow-x:auto">
<table>
<thead>
<tr>
<th>Fecha</th>
<th>Nota</th>
<th>Detección</th>
<th>Fuente</th>
<th>Acciones</th>
</tr>
</thead>
<tbody id="unresolved-body">
<tr><td colspan="5" style="text-align:center;color:var(--muted);padding:24px">Cargando…</td></tr>
</tbody>
</table>
</div>
</div>
<!-- Colonias / Gazetteer -->
<div class="card">
<h2>Base de datos de colonias</h2>
<div class="toolbar">
<input type="text" id="colonia-search" placeholder="Buscar colonia o seudónimo…" oninput="filterColoniasTable()">
<span class="count" id="colonia-count"></span>
<button class="btn-success btn-sm" onclick="openColoniaModal(-1)">+ Nueva colonia</button>
<button class="btn-primary btn-sm" id="btn-regen-map" onclick="regenMap()">↺ Actualizar mapa</button>
</div>
<div style="overflow-x:auto">
<table>
<thead>
<tr>
<th>Nombre</th>
<th>Lat</th>
<th>Lon</th>
<th>Seudónimos</th>
<th>Acciones</th>
</tr>
</thead>
<tbody id="colonias-body">
<tr><td colspan="5" style="text-align:center;color:var(--muted);padding:24px">Cargando…</td></tr>
</tbody>
</table>
</div>
</div>
</div><!-- /main-section -->
</main>
<!-- Edit modal -->
<div class="modal-overlay" id="edit-modal">
<div class="modal">
<h3>Editar ubicación</h3>
<p class="sub" id="edit-modal-sub">Cambia la colonia o municipio al que pertenece esta noticia.</p>
<div class="field" style="margin-bottom:12px">
<label>Colonia / Municipio</label>
<select id="edit-colonia-select">
<option value="">Cargando opciones…</option>
</select>
</div>
<div class="field">
<label>O escribe manualmente</label>
<input type="text" id="edit-colonia-manual" placeholder="Nombre exacto del lugar">
</div>
<div class="modal-footer">
<button class="btn-ghost" onclick="closeModal()">Cancelar</button>
<button class="btn-primary" id="btn-save-edit" onclick="saveEdit()">Guardar y regenerar mapa</button>
</div>
</div>
</div>
<!-- Colonia modal -->
<div class="modal-overlay" id="colonia-modal">
<div class="modal" style="max-width:520px">
<h3 id="colonia-modal-title">Nueva colonia</h3>
<p class="sub" id="colonia-modal-sub">Los cambios se guardan en colonias_cuernavaca.json vía GitHub.</p>
<div class="field" style="margin-bottom:12px">
<label>Nombre canónico</label>
<input type="text" id="col-name" placeholder="Ej: Vista Hermosa">
</div>
<div class="coords-row" style="margin-bottom:12px">
<div class="field">
<label>Latitud</label>
<input type="number" id="col-lat" step="0.000001" placeholder="18.9218">
</div>
<div class="field">
<label>Longitud</label>
<input type="number" id="col-lon" step="0.000001" placeholder="-99.2347">
</div>
</div>
<div class="field">
<label>Seudónimos (uno por línea)</label>
<textarea id="col-aliases" rows="5" placeholder="VISTA HERMOSA Col. Vista Hermosa col vista hermosa"></textarea>
</div>
<div class="modal-footer">
<button class="btn-ghost" onclick="closeColoniaModal()">Cancelar</button>
<button class="btn-primary" id="btn-save-colonia" onclick="saveColonia()">Guardar</button>
</div>
</div>
</div>
<script>
const OWNER = 'ebalderasr'
const REPO = 'cuernavaca-risk-map'
const API = 'https://api.github.com'
let token = sessionStorage.getItem('ovicue_token') || ''
let allEvents = [] // merged events with source tag
let gazetteer = [] // colonias list (quick lookup)
let gazetteData = { colonias: [], sha: '' } // full gazette with sha
let blacklistData = { urls: [], sha: '' }
let manualData = { events: [], sha: '' }
let unresolvedData = { events: [], sha: '' }
let editingEvent = null
let editingColoniaIdx = -1 // -1 = nueva colonia
// ── Helpers ──────────────────────────────────────────────
function gh(path, opts = {}) {
return fetch(`${API}${path}`, {
...opts,
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
...(opts.headers || {}),
},
})
}
function b64decode(str) {
const binary = atob(str.replace(/\n/g, ''))
const bytes = Uint8Array.from(binary, c => c.charCodeAt(0))
return new TextDecoder().decode(bytes)
}
function b64encode(str) {
const bytes = new TextEncoder().encode(str)
let binary = ''
bytes.forEach(b => binary += String.fromCharCode(b))
return btoa(binary)
}
async function readGHFile(path) {
const res = await gh(`/repos/${OWNER}/${REPO}/contents/${path}`)
if (!res.ok) throw new Error(`No se pudo leer ${path}: ${res.status}`)
const data = await res.json()
return { content: JSON.parse(b64decode(data.content)), sha: data.sha }
}
async function writeGHFile(path, content, sha, message) {
const body = { message, content: b64encode(JSON.stringify(content, null, 2) + '\n'), sha }
const res = await gh(`/repos/${OWNER}/${REPO}/contents/${path}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!res.ok) {
const err = await res.json().catch(() => ({}))
throw new Error(err.message || `Error ${res.status}`)
}
return res.json()
}
async function triggerWorkflow(workflowFile, inputs = {}) {
const res = await gh(`/repos/${OWNER}/${REPO}/actions/workflows/${workflowFile}/dispatches`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ref: 'main', inputs }),
})
if (!res.ok && res.status !== 204) {
const err = await res.json().catch(() => ({}))
throw new Error(err.message || `Error ${res.status}`)
}
}
function showMsg(text, type = 'info') {
const el = document.getElementById('msg')
el.textContent = text
el.className = type
el.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}
function hideMsg() {
document.getElementById('msg').className = ''
}
function setLoading(btnId, loading, label) {
const btn = document.getElementById(btnId)
if (!btn) return
btn.disabled = loading
btn.innerHTML = loading ? `<span class="spinner"></span>${label}` : label
}
// ── Auth ─────────────────────────────────────────────────
async function connect() {
token = document.getElementById('token-input').value.trim()
if (!token) { showMsg('Ingresa un token.', 'err'); return }
try {
const res = await gh('/user')
if (!res.ok) throw new Error('Token inválido o sin permisos.')
const user = await res.json()
sessionStorage.setItem('ovicue_token', token)
setAuthOk(user.login)
await loadAll()
} catch (e) {
showMsg(e.message, 'err')
token = ''
}
}
function setAuthOk(login) {
document.getElementById('auth-dot').className = 'dot ok'
document.getElementById('auth-label').textContent = `@${login}`
document.getElementById('btn-logout').style.display = ''
document.getElementById('auth-section').style.display = 'none'
document.getElementById('main-section').style.display = 'block'
hideMsg()
}
function logout() {
sessionStorage.removeItem('ovicue_token')
token = ''
allEvents = []
document.getElementById('auth-dot').className = 'dot'
document.getElementById('auth-label').textContent = 'No conectado'
document.getElementById('btn-logout').style.display = 'none'
document.getElementById('auth-section').style.display = ''
document.getElementById('main-section').style.display = 'none'
document.getElementById('token-input').value = ''
document.getElementById('events-body').innerHTML =
'<tr id="loading-row"><td colspan="6"><span class="spinner"></span> Cargando…</td></tr>'
}
// ── Load data ─────────────────────────────────────────────
async function loadAll() {
document.getElementById('events-body').innerHTML =
'<tr id="loading-row"><td colspan="6"><span class="spinner"></span> Cargando datos…</td></tr>'
document.getElementById('unresolved-body').innerHTML =
'<tr><td colspan="5" style="text-align:center;color:var(--muted);padding:24px"><span class="spinner"></span> Cargando datos…</td></tr>'
hideMsg()
try {
const [scraped, manual, blacklist, gazette, unresolved] = await Promise.all([
readGHFile('data/events.json'),
readGHFile('data/manual_events.json').catch(() => ({ content: [], sha: null })),
readGHFile('data/blacklist.json').catch(() => ({ content: { urls: [] }, sha: null })),
readGHFile('data/colonias_cuernavaca.json').catch(() => ({ content: [], sha: null })),
readGHFile('data/unresolved_events.json').catch(() => ({ content: [], sha: null })),
])
blacklistData = { urls: blacklist.content.urls || [], sha: blacklist.sha }
manualData = { events: manual.content || [], sha: manual.sha }
gazetteData = { colonias: gazette.content || [], sha: gazette.sha }
unresolvedData = { events: unresolved.content || [], sha: unresolved.sha }
gazetteer = gazetteData.colonias
const blackSet = new Set(blacklistData.urls)
const manualUrls = new Set((manualData.events).map(e => e.fuente).filter(Boolean))
// Merge: manual first (takes precedence), then scraped
const seen = new Set()
allEvents = []
for (const ev of [...manualData.events, ...(scraped.content || [])]) {
const key = ev.fuente || ev.id
if (!key || seen.has(key) || blackSet.has(key)) continue
seen.add(key)
allEvents.push({ ...ev, _source: manualUrls.has(ev.fuente) ? 'manual' : 'auto' })
}
// Sort by date desc
allEvents.sort((a, b) => (b.fecha || '').localeCompare(a.fecha || ''))
populateGazeteerSelect()
renderTable(allEvents)
renderUnresolvedTable(unresolvedData.events.filter(ev => !blackSet.has(ev.fuente)))
renderColoniasTable(gazetteData.colonias)
} catch (e) {
showMsg('Error cargando datos: ' + e.message, 'err')
document.getElementById('events-body').innerHTML =
`<tr><td colspan="6" style="color:var(--danger);padding:20px">${e.message}</td></tr>`
document.getElementById('unresolved-body').innerHTML =
`<tr><td colspan="5" style="color:var(--danger);padding:20px">${e.message}</td></tr>`
}
}
// ── Render ────────────────────────────────────────────────
function renderTable(events) {
const tbody = document.getElementById('events-body')
document.getElementById('event-count').textContent = `${events.length} noticias`
if (!events.length) {
tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;color:var(--muted);padding:32px">Sin resultados</td></tr>'
return
}
tbody.innerHTML = events.map((ev, i) => {
const srcBadge = ev._source === 'manual'
? '<span class="badge badge-manual">manual</span>'
: '<span class="badge badge-auto">auto</span>'
const lugar = ev.location_name || ev.colonia || '–'
const scope = ev.location_scope === 'municipio' ? ' (mpio.)' : ''
const delito = ev.tipo_delito || '–'
const fecha = ev.fecha || '–'
const url = ev.fuente || ''
const shortUrl = url ? url.replace(/^https?:\/\/(www\.)?/, '').substring(0, 55) + (url.length > 60 ? '…' : '') : '–'
return `<tr data-idx="${i}">
<td>${fecha}</td>
<td>${escHtml(lugar)}${scope}</td>
<td>${escHtml(delito)}</td>
<td>${url ? `<a class="src-link" href="${escHtml(url)}" target="_blank">${escHtml(shortUrl)}</a>` : '–'}</td>
<td>${srcBadge}</td>
<td>
<div class="actions">
<button class="btn-ghost btn-sm" onclick="openEditModal(${i})">✏ Editar</button>
<button class="btn-danger btn-sm" onclick="blacklistEvent(${i})">✕ Quitar</button>
</div>
</td>
</tr>`
}).join('')
}
function filterTable() {
const q = document.getElementById('search').value.toLowerCase()
const filtered = allEvents.filter(ev => {
const haystack = [ev.fecha, ev.location_name, ev.colonia, ev.tipo_delito, ev.fuente]
.join(' ').toLowerCase()
return haystack.includes(q)
})
renderTable(filtered)
}
function escHtml(s) {
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"')
}
function unresolvedLocationLabel(ev) {
const parts = []
if (ev.location_name) parts.push(ev.location_name)
else if (ev.colonia) parts.push(ev.colonia)
if (ev.municipio_detectado) parts.push(`mpio detectado: ${ev.municipio_detectado}`)
return parts.join(' · ') || 'Sin ubicación resuelta'
}
function renderUnresolvedTable(events) {
const tbody = document.getElementById('unresolved-body')
document.getElementById('unresolved-count').textContent = `${events.length} pendientes`
if (!events.length) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;color:var(--muted);padding:32px">Sin pendientes</td></tr>'
return
}
tbody.innerHTML = events.map((ev, i) => {
const fecha = ev.published_at ? String(ev.published_at).slice(0, 10) : (ev.scraped_at || '').slice(0, 10) || '–'
const fuente = ev.fuente || ''
const shortUrl = fuente ? fuente.replace(/^https?:\/\/(www\.)?/, '').substring(0, 55) + (fuente.length > 60 ? '…' : '') : '–'
const conf = ev.extraction_confidence ?? '–'
const location = unresolvedLocationLabel(ev)
return `<tr>
<td>${escHtml(fecha)}</td>
<td>
<div class="stack">
<strong>${escHtml(ev.source_title || ev.resumen || 'Sin título')}</strong>
<span class="muted">${escHtml((ev.article_excerpt || '').slice(0, 180))}${(ev.article_excerpt || '').length > 180 ? '…' : ''}</span>
</div>
</td>
<td>
<div class="stack">
<span><span class="badge badge-unresolved">pendiente</span> ${escHtml(ev.tipo_delito || '–')}</span>
<span class="muted">${escHtml(location)} · conf: ${escHtml(String(conf))}</span>
</div>
</td>
<td>${fuente ? `<a class="src-link" href="${escHtml(fuente)}" target="_blank">${escHtml(shortUrl)}</a>` : '–'}</td>
<td>
<div class="actions">
<button class="btn-primary btn-sm" onclick="openUnresolvedModal(${i})">Clasificar</button>
<button class="btn-danger btn-sm" onclick="discardUnresolved(${i})">Descartar</button>
</div>
</td>
</tr>`
}).join('')
}
function filterUnresolvedTable() {
const q = document.getElementById('unresolved-search').value.toLowerCase()
const blackSet = new Set(blacklistData.urls)
const filtered = unresolvedData.events
.filter(ev => !blackSet.has(ev.fuente))
.filter(ev => {
const haystack = [
ev.source_title,
ev.resumen,
ev.tipo_delito,
ev.location_name,
ev.colonia,
ev.municipio_detectado,
ev.fuente,
ev.article_excerpt,
].join(' ').toLowerCase()
return haystack.includes(q)
})
renderUnresolvedTable(filtered)
}
// ── Blacklist ─────────────────────────────────────────────
async function blacklistEvent(idx) {
const ev = allEvents[idx]
const url = ev.fuente
if (!url) { showMsg('Esta noticia no tiene URL, no se puede quitar por URL.', 'err'); return }
if (!confirm(`¿Quitar esta noticia del mapa?\n\n${ev.fecha} — ${ev.location_name || ev.colonia}\n${url}`)) return
try {
showMsg('Quitando noticia…', 'info')
// Update blacklist
const newUrls = [...new Set([...blacklistData.urls, url])]
const newBlacklist = { urls: newUrls }
// We need current sha; if null, file doesn't exist yet, handle create
let res
if (!blacklistData.sha) {
// Create file
const createRes = await gh(`/repos/${OWNER}/${REPO}/contents/data/blacklist.json`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: 'Admin: quitar noticia del mapa',
content: b64encode(JSON.stringify(newBlacklist, null, 2) + '\n'),
}),
})
if (!createRes.ok) throw new Error('No se pudo crear blacklist.json')
res = await createRes.json()
blacklistData.sha = res.content.sha
} else {
res = await writeGHFile('data/blacklist.json', newBlacklist, blacklistData.sha, 'Admin: quitar noticia del mapa')
blacklistData.sha = res.content.sha
}
blacklistData.urls = newUrls
// Trigger regen
await triggerWorkflow('regen_map.yml')
// Remove from local list
allEvents = allEvents.filter(e => e.fuente !== url)
filterTable()
showMsg('✓ Noticia quitada. El mapa se regenerará en ~3 min.', 'ok')
} catch (e) {
showMsg('Error: ' + e.message, 'err')
}
}
// ── Edit modal ────────────────────────────────────────────
function populateGazeteerSelect() {
const sel = document.getElementById('edit-colonia-select')
const municipios = ['Cuernavaca', 'Jiutepec', 'Yautepec', 'Emiliano Zapata', 'Temixco', 'CIVAC']
const opts = [
'<option value="">— Elige una colonia —</option>',
'<optgroup label="Municipios conurbados">',
...municipios.map(m => `<option value="municipio:${m}">${m} (municipio)</option>`),
'</optgroup>',
'<optgroup label="Colonias de Cuernavaca">',
...gazetteer.map(c => `<option value="colonia:${c.name}">${c.name}</option>`),
'</optgroup>',
]
sel.innerHTML = opts.join('')
}
function openEditModal(idx) {
editingEvent = allEvents[idx]
document.getElementById('edit-modal-sub').textContent =
`${editingEvent.fecha || ''} — ${editingEvent.resumen || editingEvent.fuente || ''}`
document.getElementById('edit-colonia-manual').value = ''
document.getElementById('edit-colonia-select').value = ''
document.getElementById('edit-modal').classList.add('open')
}
function openUnresolvedModal(idx) {
editingEvent = unresolvedData.events[idx]
document.getElementById('edit-modal-sub').textContent =
`${editingEvent.published_at || editingEvent.scraped_at || ''} — ${editingEvent.source_title || editingEvent.resumen || editingEvent.fuente || ''}`
document.getElementById('edit-colonia-manual').value = editingEvent.location_name || editingEvent.colonia || ''
document.getElementById('edit-colonia-select').value = ''
document.getElementById('edit-modal').classList.add('open')
}
function closeModal() {
document.getElementById('edit-modal').classList.remove('open')
editingEvent = null
}
async function saveEdit() {
if (!editingEvent) return
const selectVal = document.getElementById('edit-colonia-select').value
const manualVal = document.getElementById('edit-colonia-manual').value.trim()
let locationScope, locationName, coords, bufferMeters
if (manualVal) {
// Manual text — try to look up in gazetteer
const match = gazetteer.find(c =>
c.name.toLowerCase() === manualVal.toLowerCase() ||
(c.aliases || []).some(a => a.toLowerCase() === manualVal.toLowerCase())
)
if (match) {
locationScope = 'colonia'
locationName = match.name
coords = match.coords
bufferMeters = 500
} else {
// Not in gazetteer — we still save the name but keep original coords
locationScope = 'colonia'
locationName = manualVal
coords = editingEvent.coordenadas
bufferMeters = editingEvent.buffer_meters || 500
}
} else if (selectVal) {
const [scope, name] = selectVal.split(':')
locationScope = scope
locationName = name
bufferMeters = scope === 'municipio' ? 1000 : 500
if (scope === 'colonia') {
const match = gazetteer.find(c => c.name === name)
coords = match ? match.coords : editingEvent.coordenadas
} else {
// municipio — keep original coords or use known center
coords = editingEvent.coordenadas
}
} else {
showMsg('Selecciona o escribe una ubicación.', 'err')
return
}
if (!coords || !Array.isArray(coords) || coords.length !== 2) {
showMsg('La ubicación elegida no tiene coordenadas. Agrégala primero en la base de colonias o selecciona una existente.', 'err')
return
}
setLoading('btn-save-edit', true, 'Guardando…')
try {
const fecha = editingEvent.fecha || (editingEvent.published_at ? String(editingEvent.published_at).slice(0, 10) : '') || new Date().toISOString().slice(0, 10)
const delito = editingEvent.tipo_delito || 'No especificado'
// Build updated event
const updated = {
...editingEvent,
id: editingEvent.id || `manual-${Date.now()}`,
fecha,
tipo_delito: delito,
nivel_inicial: editingEvent.nivel_inicial || 5,
colonia: locationScope === 'colonia' ? locationName : editingEvent.colonia,
municipio_detectado: locationScope === 'municipio' ? locationName : editingEvent.municipio_detectado,
location_scope: locationScope,
location_name: locationName,
coordenadas: coords,
buffer_meters: bufferMeters,
geo_confidence: 'admin_manual',
source_name: 'Manual',
source_type: 'manual',
_source: undefined,
}
delete updated._source
delete updated.article_excerpt
delete updated.es_violento
delete updated.es_en_cuernavaca
// Upsert in manual_events