Create UID generator webapp

This commit is contained in:
Nik Verweel 2026-02-17 16:20:22 +01:00
parent 787a2d5b90
commit 8b02f90f7b
4 changed files with 587 additions and 0 deletions

View file

@ -254,6 +254,7 @@
<h2>ODK Data Viewer</h2>
<p>Upload ODK CSVs to visualise and turn field corner points into polygons</p>
<ul class="app-features">
<li>Upload ODK CSVs</li>
<li>View ODK data</li>
<li>Turn corner points into polygons</li>
<li>Download created polygons</li>
@ -261,6 +262,22 @@
<a href="./odk_viewer/" class="app-btn">Open Viewer</a>
</div>
</div>
<!-- Unique ID Generator -->
<div class="app-card">
<div class="app-icon">🆔</div>
<div class="app-content">
<h2>Unique ID generator</h2>
<p>Generate unique IDs for fields from different clients</p>
<ul class="app-features">
<li>Upload GeoJSONs</li>
<li>Identify client</li>
<li>Generate unique IDs following SmartCane structure</li>
<li>Download GeoJSON with new IDs</li>
</ul>
<a href="./uid_generator/" class="app-btn">Open Editor</a>
</div>
</div>
</div>
<footer>

BIN
webapps/res/id.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

View file

@ -0,0 +1,310 @@
// Global State
let clientList = [];
let rawGeoJSON = null;
let prevGeoJSON = null;
let generatedGeoJSON = null;
let detectedClientCode = null;
// DOM Elements
const clientListInput = document.getElementById('clientListInput');
const rawGeoJSONInput = document.getElementById('rawGeoJSONInput');
const prevGeoJSONInput = document.getElementById('prevGeoJSONInput');
const clientSelect = document.getElementById('clientSelect');
const processBtn = document.getElementById('processBtn');
const downloadBtn = document.getElementById('downloadBtn');
const controlsSection = document.getElementById('controlsSection');
const diffViewer = document.getElementById('diffViewer');
const rawTableContainer = document.getElementById('rawTableContainer');
const editedTableContainer = document.getElementById('editedTableContainer');
const clearAllBtn = document.getElementById('clearAllBtn');
// Event Listeners
clientListInput.addEventListener('change', handleClientListUpload);
rawGeoJSONInput.addEventListener('change', handleRawGeoJSONUpload);
prevGeoJSONInput.addEventListener('change', handlePrevGeoJSONUpload);
processBtn.addEventListener('click', processGeoJSON);
downloadBtn.addEventListener('click', downloadGeoJSON);
clientSelect.addEventListener('change', () => {
// If we have raw data, re-process or enable processing
if (rawGeoJSON) {
processBtn.disabled = false;
}
});
// Clear All Logic
clearAllBtn.addEventListener('click', () => {
if(confirm('Are you sure you want to clear all data and reset?')) {
window.location.reload();
}
});
// Helper: Attempt to match filename to client code
function tryAutoSelectClient(filename) {
if (!filename) return;
// Matches strings starting with alphanumerics followed by an underscore
// e.g. KQ001_2023-10-10.geojson -> match "KQ001"
const match = filename.match(/^([A-Z0-9]+)_/);
if (match && match[1]) {
const potentialCode = match[1];
console.log(`Detected potential client code from filename: ${potentialCode}`);
detectedClientCode = potentialCode;
// Try to select it in the dropdown if options exist
const option = Array.from(clientSelect.options).find(opt => opt.value === potentialCode);
if (option) {
clientSelect.value = potentialCode;
// Visual feedback could be added here if desired
}
}
}
// Helper: Parse Excel
function handleClientListUpload(e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
let sheetName = workbook.SheetNames.find(n => n === 'Client List') || workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet);
clientList = jsonData.map(row => ({
country: row['Country'],
name: row['Name'],
code: row['SC-client-Code']
})).filter(item => item.code);
// Show count instead of filename
document.getElementById('clientListStatus').textContent = `${clientList.length} clients uploaded`;
populateClientDropdown();
controlsSection.classList.remove('hidden');
};
reader.readAsArrayBuffer(file);
}
function populateClientDropdown() {
clientSelect.innerHTML = '<option value="">-- Select Client --</option>';
clientList.forEach(client => {
const option = document.createElement('option');
option.value = client.code;
option.textContent = `${client.code} - ${client.name} (${client.country})`;
clientSelect.appendChild(option);
});
// Attempt auto-selection if code was detected previously (e.g., from raw upload before client list)
if (detectedClientCode) {
const option = Array.from(clientSelect.options).find(opt => opt.value === detectedClientCode);
if (option) {
clientSelect.value = detectedClientCode;
}
}
}
// Helper: Parse GeoJSON
function handleRawGeoJSONUpload(e) {
const file = e.target.files[0];
if (!file) return;
// Show filename
document.getElementById('rawGeoJSONStatus').textContent = `Uploaded: ${file.name}`;
// Try to detect client code from this filename
tryAutoSelectClient(file.name);
const reader = new FileReader();
reader.onload = function(e) {
try {
rawGeoJSON = JSON.parse(e.target.result);
renderTable(rawGeoJSON, rawTableContainer, false);
// Clear the right column (edited view) when new raw file is uploaded
editedTableContainer.innerHTML = '';
// Reset generated GeoJSON and disable download
generatedGeoJSON = null;
downloadBtn.disabled = true;
diffViewer.classList.remove('hidden');
processBtn.disabled = false;
} catch (err) {
console.error('Error parsing GeoJSON:', err);
alert('Error parsing Raw GeoJSON');
}
};
reader.readAsText(file);
}
function handlePrevGeoJSONUpload(e) {
const file = e.target.files[0];
if (!file) return;
// Show filename
document.getElementById('prevGeoJSONStatus').textContent = `Uploaded: ${file.name}`;
// Try to detect client code from this filename
tryAutoSelectClient(file.name);
const reader = new FileReader();
reader.onload = function(e) {
try {
prevGeoJSON = JSON.parse(e.target.result);
console.log("Previous GeoJSON loaded", prevGeoJSON);
} catch (err) {
console.error("Error parsing Previous GeoJSON", err);
alert("Error parsing Previous GeoJSON");
}
};
reader.readAsText(file);
}
// Core Logic: Generate IDs
function processGeoJSON() {
if (!rawGeoJSON) {
alert("Please upload Raw GeoJSON first.");
return;
}
// Validate Client Selection for Prefix
const clientCode = clientSelect.value;
if (!clientCode) {
alert("Please select a Client first to generate the correct ID format.");
return;
}
// Helper to extract number from ID
// Handles simple "0001" or complex "CODE_0001"
const extractIdNumber = (idStr) => {
if (!idStr) return 0;
// Split by underscore and take the last segment
const parts = String(idStr).split('_');
const numPart = parts[parts.length - 1];
const num = parseInt(numPart, 10);
return isNaN(num) ? 0 : num;
};
// Determine max ID
let maxId = 0;
// 1. Scan Previous GeoJSON
if (prevGeoJSON && prevGeoJSON.features) {
prevGeoJSON.features.forEach(f => {
if (f.properties && f.properties['sc_id']) {
const num = extractIdNumber(f.properties['sc_id']);
if (num > maxId) maxId = num;
}
});
}
// 2. Scan Raw GeoJSON (avoid collisions)
if (rawGeoJSON && rawGeoJSON.features) {
rawGeoJSON.features.forEach(f => {
if (f.properties && f.properties['sc_id']) {
const num = extractIdNumber(f.properties['sc_id']);
if (num > maxId) maxId = num;
}
});
}
// Clone Raw GeoJSON to create Generated one
generatedGeoJSON = JSON.parse(JSON.stringify(rawGeoJSON));
let currentId = maxId;
generatedGeoJSON.features.forEach(f => {
if (!f.properties) f.properties = {};
let existingId = f.properties['sc_id'];
// Check if empty or missing
if (existingId === undefined || existingId === null || existingId === "") {
currentId++;
// Format: CLIENTCODE_0001
f.properties['sc_id'] = `${clientCode}_${String(currentId).padStart(4, '0')}`;
f.isNew = true; // Flag for UI
}
});
renderTable(generatedGeoJSON, editedTableContainer, true);
downloadBtn.disabled = false;
}
function renderTable(geojson, container, isEdited) {
if (!geojson || !geojson.features) return;
container.innerHTML = '';
const table = document.createElement('table');
const thead = document.createElement('thead');
const trHead = document.createElement('tr');
['Field', 'Subfield', 'SC_ID'].forEach(text => {
const th = document.createElement('th');
th.textContent = text;
trHead.appendChild(th);
});
thead.appendChild(trHead);
table.appendChild(thead);
const tbody = document.createElement('tbody');
geojson.features.forEach(f => {
const props = f.properties || {};
const field = props['field'] || '';
const subfield = props['subfield'] || '';
const scId = props['sc_id'] || '';
const tr = document.createElement('tr');
if (isEdited && f.isNew) {
tr.className = 'diff-row new';
}
const tdField = document.createElement('td');
tdField.textContent = field;
tr.appendChild(tdField);
const tdSubfield = document.createElement('td');
tdSubfield.textContent = subfield;
tr.appendChild(tdSubfield);
const tdScId = document.createElement('td');
tdScId.textContent = scId;
tr.appendChild(tdScId);
tbody.appendChild(tr);
});
table.appendChild(tbody);
container.appendChild(table);
}
function downloadGeoJSON() {
if (!generatedGeoJSON) return;
// Remove temporary flags
const cleanGeoJSON = JSON.parse(JSON.stringify(generatedGeoJSON));
cleanGeoJSON.features.forEach(f => {
delete f.isNew;
});
const clientCode = clientSelect.value || "UNKNOWN";
const date = new Date();
const dateStr = date.toISOString().split('T')[0]; // YYYY-MM-DD
const filename = `${clientCode}_${dateStr}.geojson`;
const blob = new Blob([JSON.stringify(cleanGeoJSON, null, 2)], { type: 'application/geo+json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}

View file

@ -0,0 +1,260 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Unique ID generator</title>
<script src="https://cdn.sheetjs.com/xlsx-0.20.2/package/dist/xlsx.full.min.js"></script>
<link rel="icon" type="image/png" href="../res/id.png">
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #faf8f3;
min-height: 100vh;
display: flex;
flex-direction: column;
margin: 0;
}
header {
background: linear-gradient(135deg, #2aab95 0%, #1e8e7b 100%); /* Adjusted var defaults */
color: white;
padding: 15px 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
display: flex;
align-items: center;
gap: 20px;
position: sticky;
top: 0;
z-index: 100;
}
header h1 {
font-size: 24px;
font-weight: 600;
flex: 1;
margin: 0;
}
/* Single Container Fix */
.container {
flex: 1;
max-width: 1200px;
margin: 20px auto; /* Reduced top/bottom margin */
width: 100%;
padding: 0 20px;
box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 15px; /* Controls distance between cards */
}
.card {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
border: 1px solid #e0d9d0;
width: 100%; /* Force full width */
box-sizing: border-box;
}
.card h2 {
margin-top: 0;
color: #333;
border-bottom: 2px solid #2aab95;
padding-bottom: 10px;
margin-bottom: 15px;
}
/* Diff Viewer Layout */
.diff-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.diff-column {
max-height: 600px;
overflow-y: auto;
border: 1px solid #eee;
padding: 10px;
border-radius: 4px;
}
.diff-row.new { background-color: #e6ffec; }
.diff-row.modified { background-color: #fffbdd; }
/* File Input Styling */
.file-input-wrapper {
position: relative;
display: inline-block;
width: 100%;
margin-top: 10px;
}
.file-input-label {
display: block;
padding: 30px;
border: 2px dashed #2aab95;
border-radius: 6px;
text-align: center;
cursor: pointer;
transition: all 0.3s;
background: rgba(42, 171, 149, 0.05);
}
.file-input-label:hover {
border-color: #1e8e7b;
background: rgba(37, 150, 190, 0.05);
}
.file-input-wrapper input[type="file"] { display: none; }
/* Buttons */
button {
background: #2aab95;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background 0.3s ease;
}
button:hover { background: #238b7d; }
button:disabled { background: #ccc; cursor: not-allowed; }
.header-btn {
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.4);
}
.header-btn:hover {
background: rgba(255, 255, 255, 0.3);
}
.hidden { display: none; }
.actions-row {
display: flex;
gap: 10px;
margin-top: 15px;
align-items: center;
flex-wrap: wrap;
}
footer {
background: white;
padding: 20px;
border-radius: 8px;
margin-top: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
text-align: center;
font-size: 13px;
color: #666;
border: 1px solid #e0d9d0;
}
.two-column-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin-top: 15px;
}
.upload-column { min-width: 0; }
/* Table Styling */
table { width: 100%; border-collapse: collapse; font-size: 13px; }
th { text-align: left; background: #f4f4f4; padding: 5px; position: sticky; top: 0; }
td { padding: 5px; border-bottom: 1px solid #eee; }
.status-text {
margin-top: 10px;
color: #2aab95;
font-weight: 500;
}
</style>
</head>
<body>
<script>
if (sessionStorage.getItem('authenticated') !== 'true') {
window.location.href = '../login.html';
}
</script>
<header>
<button class="header-btn" onclick="window.location.href='../';" title="Back to main tools">← Back</button>
<h1>🆔 Unique ID generator</h1>
<button class="header-btn" id="clearAllBtn">Clear all</button>
</header>
<main class="container">
<div class="card">
<h2><span style="font-size: 24px;">📋</span> Upload client list</h2>
<p>Upload the master client list (SmartCane_client_list.xlsx)</p>
<div class="file-input-wrapper">
<label class="file-input-label" for="clientListInput">
<div id="fileLabelText">Drop the client list file here<br><small>or click to browse</small></div>
</label>
<input type="file" id="clientListInput" accept=".xlsx, .xls"/>
</div>
<p id="clientListStatus" class="status-text"></p>
</div>
<div class="card">
<h2><span style="font-size: 24px;">🗺️</span> Upload GeoJSON file(s)</h2>
<div class="two-column-grid">
<div class="upload-column">
<p><strong>Raw GeoJSON</strong></p>
<p>Upload the raw GeoJSON for which you wish to generate Unique IDs.</p>
<div class="file-input-wrapper">
<label class="file-input-label" for="rawGeoJSONInput">
<div>Drop the raw GeoJSON file here (Required)<br><small>or click to browse</small></div>
</label>
<input type="file" id="rawGeoJSONInput" accept=".geojson, .json"/>
</div>
<p id="rawGeoJSONStatus" class="status-text"></p>
</div>
<div class="upload-column">
<p><strong>Previously edited GeoJSON</strong></p>
<p>If you have an edited GeoJSON, upload it here to continue numbering.</p>
<div class="file-input-wrapper">
<label class="file-input-label" for="prevGeoJSONInput">
<div>Drop the previous GeoJSON file here (Optional)<br><small>or click to browse</small></div>
</label>
<input type="file" id="prevGeoJSONInput" accept=".geojson, .json"/>
</div>
<p id="prevGeoJSONStatus" class="status-text"></p>
</div>
</div>
</div>
<div class="controls hidden" id="controlsSection">
<div class="card">
<h2><span style="font-size: 24px;">⚙️</span> Client selection & UID Generation</h2>
<label for="clientSelect">Select Client:</label>
<select id="clientSelect" style="padding: 8px; width: 100%; max-width: 300px;">
<option value="">-- Select Client --</option>
</select>
<div class="actions-row">
<button id="processBtn">Process / Update Diff</button>
<button id="downloadBtn" disabled>Download GeoJSON</button>
</div>
</div>
</div>
<div class="diff-viewer hidden" id="diffViewer">
<div class="card">
<h2><span style="font-size: 24px;">🔍</span> Review Changes</h2>
<div class="diff-grid">
<div class="diff-column" id="rawColumn">
<h3>Raw GeoJSON</h3>
<div id="rawTableContainer"></div>
</div>
<div class="diff-column" id="editedColumn">
<h3>Edited GeoJSON</h3>
<div id="editedTableContainer"></div>
</div>
</div>
</div>
</div>
<footer>
Unique ID Generator for SmartCane clients
</footer>
</main>
<script src="app.js"></script>
</body>
</html>