1 Commits

Author SHA1 Message Date
05f01247e2 feat: add online editor, work in progress 2026-01-30 19:48:30 +01:00
7 changed files with 169 additions and 281 deletions

View File

@@ -10,8 +10,8 @@ android {
applicationId "com.stock.pignon" applicationId "com.stock.pignon"
minSdkVersion 17 minSdkVersion 17
targetSdkVersion 36 targetSdkVersion 36
versionCode 8 versionCode 7
versionName "0.6.0" versionName "0.5.2"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
} }

View File

@@ -1,9 +1,8 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="fr"> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Éditeur de Catalogue</title>
<style> <style>
body { body {
font-family: sans-serif; font-family: sans-serif;
@@ -96,7 +95,6 @@
cursor: pointer; cursor: pointer;
padding: 0; padding: 0;
font-size: 12px; font-size: 12px;
appearance: none;
-webkit-appearance: none; -webkit-appearance: none;
outline: none; outline: none;
} }
@@ -133,7 +131,7 @@
cursor: pointer; cursor: pointer;
font-size: 18px; font-size: 18px;
font-weight: bold; font-weight: bold;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3); box-shadow: 0 4px 15px rgba(0,0,0,0.3);
} }
.btn-back { .btn-back {
@@ -145,7 +143,7 @@
cursor: pointer; cursor: pointer;
font-size: 18px; font-size: 18px;
font-weight: bold; font-weight: bold;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3); box-shadow: 0 4px 15px rgba(0,0,0,0.3);
} }
.input-h2 { .input-h2 {
@@ -155,9 +153,10 @@
background: transparent !important; background: transparent !important;
color: #555 !important; color: #555 !important;
width: auto; width: auto;
max-width: 20%; max-width: 70%;
border-bottom: 1px dashed #ccc !important; border-bottom: 1px dashed #ccc !important;
outline: none; outline: none;
/* Enlève le contour bleu au clic */
} }
.input-h2:focus { .input-h2:focus {
@@ -169,16 +168,15 @@
<body> <body>
<h1>Éditeur de Catalogue</h1> <h1>Éditeur de Catalogue</h1>
<form id="editor-form" accept-charset="UTF-8"> <form action="/save_editor" method="POST">
{{GENERATED_CONTENT}} {{GENERATED_CONTENT}}
<div class="actions-bar"> <div class="actions-bar">
<button type="button" class="btn-back" onclick="window.location.href= '/'">← Retour </button> <button type="button" class="btn-back" onclick="window.location.href= '/'">← Retour </button>
<button type="button" class="btn-cat" onclick="addCategory()">+ Catégorie</button>
<button type="button" onclick="sendData()" class="btn-save" style="position:static; transform:none;">💾
Enregistrer tout</button>
<button type="button" class="btn-cancel" onclick="handleCancel(event)">✖ Tout annuler</button> <button type="button" class="btn-cancel" onclick="handleCancel(event)">✖ Tout annuler</button>
<button type="button" class="btn-cat" onclick="addCategory()">+ Catégorie</button>
<input type="submit" value="💾 Enregistrer tout" class="btn-save" style="position:static; transform:none;">
</div> </div>
</form> </form>
@@ -187,40 +185,32 @@
var t = document.getElementById('table-' + cat); var t = document.getElementById('table-' + cat);
var r = t.insertRow(-1); var r = t.insertRow(-1);
var id = Date.now(); var id = Date.now();
r.innerHTML = '<td><input type="file" id="f_' + id + '" style="display:none" onchange="uImg(this)">' +
r.innerHTML = '<td>' + '<button type="button" class="link-mod" onclick="document.getElementById(\'f_' + id + '\').click()">Ajouter</button>' +
'<img src="" class="img-p" onerror="this.src=\'https://placehold.co/60?text=?\'" style="display:block; margin-bottom:5px;">' + '<input type="hidden" name="new|' + cat + '|' + id + '|img" value=""></td>' +
'<input type="file" accept=".jpg,.png" style="font-size:10px; width:70px" onchange="uImg(this)">' +
'<input type="hidden" name="new|' + cat + '|' + id + '|img" value="">' +
'</td>' +
'<td><input type="text" name="new|' + cat + '|' + id + '|name" placeholder="Nom..." required></td>' + '<td><input type="text" name="new|' + cat + '|' + id + '|name" placeholder="Nom..." required></td>' +
'<td><input type="number" name="new|' + cat + '|' + id + '|min" value="0" min="0" required></td>' + '<td><input type="number" name="new|' + cat + '|' + id + '|min" value="0" min="0" required></td>' +
'<td><input type="number" name="new|' + cat + '|' + id + '|max" value="0" min="0" required></td>' + '<td><input type="number" name="new|' + cat + '|' + id + '|max" value="0" min="0" required></td>' +
'<td><button type="button" class="btn-del" onclick="var l=this.parentNode.parentNode; l.parentNode.removeChild(l);">×</button></td>'; '<td><button type="button" class="btn-del" onclick="var l=this.parentNode.parentNode; l.parentNode.removeChild(l);">×</button></td>';
} }
function uImg(element) { function uImg(el) {
var f = element.files[0]; var f = el.files[0];
if (!f) return; if (!f) return;
var row = el.parentNode.parentNode;
var td = element.parentNode; var id = f.name.split('.').slice(0, -1).join('.');
var imgTag = td.querySelector('.img-p'); row.querySelector('input[type="hidden"]').value = id;
var hiddenInput = td.querySelector('input[type="hidden"]'); var fd = new FormData();
fd.append('images', f);
var reader = new FileReader(); fetch('/upload_images', { method: 'POST', body: fd }).then(function () { alert('Image envoyée : ' + id); });
reader.onload = function(e) {
imgTag.src = e.target.result;
hiddenInput.value = e.target.result;
};
reader.readAsDataURL(f);
} }
function handleCancel(e) { function handleCancel(e) {
// Avoid form to wait for data to send // Empêche le formulaire de faire quoi que ce soit
if (e) e.preventDefault(); if (e) e.preventDefault();
if (confirm("Attention : toutes vos modifications seront perdues. Continuer ?")) { if (confirm("Attention : toutes vos modifications seront perdues. Continuer ?")) {
// Random URL parameters ?t= to force browser to forget previous data // Le ?t= force le navigateur à oublier les saisies en cours
window.location.href = "/edit?t=" + Date.now(); window.location.href = "/edit?t=" + Date.now();
} }
} }
@@ -229,20 +219,15 @@
var name = prompt("Nom de la nouvelle catégorie ?"); var name = prompt("Nom de la nouvelle catégorie ?");
if (!name || name.trim() === "") return; if (!name || name.trim() === "") return;
// Temp ID // On crée un ID temporaire basé sur le temps
var tempId = "newcat_" + Date.now(); var tempId = "newcat_" + Date.now();
// On crée la structure HTML de la carte
var container = document.createElement('div'); var container = document.createElement('div');
container.className = 'card'; container.className = 'card';
container.innerHTML = container.innerHTML =
'<h2>' + '<h2>' +
'<input type="text" class="input-h2" name="cat|' + tempId + '|name" value="' + name + '">' + '<input type="text" class="input-h2" name="cat|' + tempId + '|name" value="' + name + '">' +
'<div style="display:inline-block; vertical-align:middle; margin: 0 15px;">' +
'<small>Fond:</small><br><input type="color" name="cat|' + tempId + '|bgColor" value="#0049AF" style="width:30px; height:25px; border:none; cursor:pointer;">' +
'</div>' +
'<div style="display:inline-block; vertical-align:middle; margin-right:15px;">' +
'<small>Texte:</small><br><input type="color" name="cat|' + tempId + '|textColor" value="#FFFFFF" style="width:30px; height:25px; border:none; cursor:pointer;">' +
'</div>' +
' <button type="button" class="btn-del" onclick="if(confirm(\'Supprimer cette catégorie ?\')) this.closest(\'.card\').remove()">×</button>' + ' <button type="button" class="btn-del" onclick="if(confirm(\'Supprimer cette catégorie ?\')) this.closest(\'.card\').remove()">×</button>' +
'</h2>' + '</h2>' +
'<table id="table-' + tempId + '">' + '<table id="table-' + tempId + '">' +
@@ -250,67 +235,13 @@
'</table>' + '</table>' +
'<button type="button" class="btn-add" onclick="addRow(\'' + tempId + '\')">+ Ajouter article</button>'; '<button type="button" class="btn-add" onclick="addRow(\'' + tempId + '\')">+ Ajouter article</button>';
// On l'insère avant la barre d'actions (en bas de la liste)
var form = document.querySelector('form'); var form = document.querySelector('form');
var actionBar = document.querySelector('.actions-bar'); var actionBar = document.querySelector('.actions-bar');
form.insertBefore(container, actionBar); form.insertBefore(container, actionBar);
// On scrolle vers la nouvelle catégorie
container.scrollIntoView({ behavior: 'smooth' }); container.scrollIntoView({ behavior: 'smooth' });
} }
function sendData() {
const form = document.getElementById('editor-form');
const data = {
cat_order_list: "",
items: {}
};
// Browse showed categories
const catOrder = [];
document.querySelectorAll('.card').forEach((card, catIdx) => {
let techId = card.querySelector('input[name^="cat|"]')?.name.split('|')[1] || "c" + catIdx; // c0, c1 but avoid globals
catOrder.push(techId);
const catInput = card.querySelector('input[name$="|name"]');
const bgInput = card.querySelector('input[name$="|bgColor"]');
const textInput = card.querySelector('input[name$="|textColor"]');
if (!catInput) return;
data.items["cat|" + techId + "|name"] = catInput.value;
data.items["cat|" + techId + "|bgColor"] = bgInput ? bgInput.value : "#0049AF";
data.items["cat|" + techId + "|textColor"] = textInput ? textInput.value : "#FFFFFF";
// Browse each line
card.querySelectorAll('table tr').forEach((row, itemIdx) => {
if (itemIdx === 0) return; // Skip title line (th)
const realIdx = itemIdx - 1; // Start at 0
row.querySelectorAll('input').forEach(input => {
const parts = input.name.split('|');
if (parts.length >= 4) {
// parts[0] = "item" ou "new", parts[3] = "name" ou "min" ou "max"
const finalKey = "item|" + techId + "|" + realIdx + "|" + parts[3];
data.items[finalKey] = input.value;
}
});
});
});
data.cat_order_list = catOrder.join(',');
// Create new clean struct : cat|c0|name, item|c0|0|name...
fetch('/save_editor', {
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
body: JSON.stringify(data)
})
.then(r => {
if (r.ok) {
alert("✅ Enregistré !");
window.location.reload(); // Optionnel : rafraîchit pour voir le résultat propre
} else {
alert("❌ Erreur serveur");
}
})
.catch(() => alert("❌ Erreur réseau"));
}
</script> </script>
</body> </body>

View File

@@ -20,10 +20,8 @@ public class CartItem {
public int getMinPrice() { return minPrice; } public int getMinPrice() { return minPrice; }
public int getMaxPrice() { return maxPrice; } public int getMaxPrice() { return maxPrice; }
public int getQuantity() { return quantity; } public int getQuantity() { return quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; }
public int getTotalMin() { return minPrice * quantity; } public int getTotalMin() { return minPrice * quantity; }
public int getTotalMax() { return maxPrice * quantity; } public int getTotalMax() { return maxPrice * quantity; }
public String getImageFile() { return imageFile; } public String getImageFile() { return imageFile; }
// Setters
public void setQuantity(int quantity) { this.quantity = quantity; }
} }

View File

@@ -8,14 +8,10 @@ public class CartManager {
// Unified and global list for whole application // Unified and global list for whole application
private static final List<CartItem> items = new ArrayList<>(); private static final List<CartItem> items = new ArrayList<>();
/** // Private constructor: utility class, it should not be instantiated
* Private constructor: utility class, it should not be instantiated
*/
private CartManager() {} private CartManager() {}
/** // Returns the direct reference to the list to save memory on older devices
* Returns the direct reference to the list to save memory on older devices
*/
public static List<CartItem> getItems() { public static List<CartItem> getItems() {
return items; return items;
} }
@@ -29,9 +25,7 @@ public class CartManager {
return null; return null;
} }
/** // Logic for adding, updating or removing items based on quantity, prevents duplicate entries
* Logic for adding, updating or removing items based on quantity, prevents duplicate entries
*/
public static void addOrUpdateItem(String name, int minPrice, int maxPrice, int quantity, String imageFile) { public static void addOrUpdateItem(String name, int minPrice, int maxPrice, int quantity, String imageFile) {
CartItem current = getItemByName(name); CartItem current = getItemByName(name);
@@ -46,27 +40,20 @@ public class CartManager {
} }
} }
/** // Range-based pricing
* Range-based pricing
*/
public static int getGlobalTotalMin() { public static int getGlobalTotalMin() {
int total = 0; int total = 0;
for (CartItem item : items) total += item.getTotalMin(); for (CartItem item : items) total += item.getTotalMin();
return total; return total;
} }
/**
* Range-based pricing
*/
public static int getGlobalTotalMax() { public static int getGlobalTotalMax() {
int total = 0; int total = 0;
for (CartItem item : items) total += item.getTotalMax(); for (CartItem item : items) total += item.getTotalMax();
return total; return total;
} }
/**
* Remove item from cart
*/
public static void clear() { public static void clear() {
items.clear(); items.clear();
} }

View File

@@ -30,9 +30,7 @@ public class Category {
public String getName() { return name; } public String getName() { return name; }
public String getBgColor() { return bgColor; } public String getBgColor() { return bgColor; }
public String getTextColor() { return textColor; } public String getTextColor() { return textColor; }
public List<Item> getItems() { return items != null ? items : new ArrayList<>(); } public List<Item> getItems() {
return items != null ? items : new ArrayList<>();
// Setters }
public void setBgColor(String bgColor) { this.bgColor = bgColor; }
public void setTextColor(String textColor) { this.textColor = textColor; }
} }

View File

@@ -3,8 +3,6 @@ package com.stock.pignon;
import android.content.Context; import android.content.Context;
import android.os.Environment; import android.os.Environment;
import android.util.Log;
import org.json.JSONObject;
import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.NanoHTTPD;
import java.io.File; import java.io.File;
@@ -13,17 +11,17 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.List; import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Map; import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Scanner; import java.util.Scanner;
/** /**
* Create a web server to remote management of app assets. * Create a web server to remote management of app assets.
* Inherit what is needed to build a web server from NanoHTTPD
*/ */
// Inherit what is needed to build a web server
public class ControlServer extends NanoHTTPD { public class ControlServer extends NanoHTTPD {
private final Context context; private final Context context;
@@ -39,7 +37,7 @@ public class ControlServer extends NanoHTTPD {
} }
/** /**
* Main method which manage requests * Main method which receive remote request
*/ */
@Override @Override
public Response serve(IHTTPSession session) { public Response serve(IHTTPSession session) {
@@ -73,10 +71,8 @@ public class ControlServer extends NanoHTTPD {
if (session.getMethod() == Method.POST) { if (session.getMethod() == Method.POST) {
switch (uri) { switch (uri) {
// Soon deprecated with online editor
case "/upload_json": case "/upload_json":
return handleJsonUpload(session); return handleJsonUpload(session);
// Soon deprecated with online editor
case "/upload_images": case "/upload_images":
return handleImagesUpload(session); return handleImagesUpload(session);
case "/save_editor": case "/save_editor":
@@ -93,7 +89,7 @@ public class ControlServer extends NanoHTTPD {
private String getHtml(String file) { private String getHtml(String file) {
try { try {
InputStream is = context.getAssets().open(file); InputStream is = context.getAssets().open(file);
// Scanner html file from the beginning with "\\A" // Scanner html file from the beginning \\A
Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A");
String html = s.hasNext() ? s.next() : ""; String html = s.hasNext() ? s.next() : "";
is.close(); is.close();
@@ -107,87 +103,61 @@ public class ControlServer extends NanoHTTPD {
* Read from asset and return html file * Read from asset and return html file
*/ */
private String fillEditor() { private String fillEditor() {
// Get data from assets // Get data for assets
DataLoader.loadData(); DataLoader.loadData();
// Create an html string to fill the template // Create an html string to fill the template
StringBuilder html = new StringBuilder(); StringBuilder html = new StringBuilder();
// Save categories order
List<String> orderList = new ArrayList<>();
// Globals // Browse map : 'id' for categories name, 'items' for items list
String globalId = "global"; for (Map.Entry<String, List<Item>> section : DataLoader.getAllSections().entrySet()) {
Category globalCat = new Category("global", DataLoader.getGlobalItems()); String id = section.getKey();
html.append(renderCategorySection(globalId, globalCat)); List<Item> items = section.getValue();
orderList.add(globalId);
// Browser categories // For each category, render a HTML card
int index = 0; html.append(renderCategorySection(id, items));
for (Category cat : DataLoader.getCategories()) {
// cat_0, cat_1...
String techId = "cat_" + index;
html.append(renderCategorySection(techId, cat));
orderList.add(techId);
index++;
} }
String orderField = "<input type='hidden' name='cat_order_list' value='" + return getHtml("editor.html").replace("{{GENERATED_CONTENT}}", html.toString());
android.text.TextUtils.join(",", orderList) + "'>";
return getHtml("editor.html").replace("{{GENERATED_CONTENT}}", html + orderField);
} }
/** /**
* Generate HTML section for each category * Generate HTML section for each category
*/ */
private String renderCategorySection(String techId, Category cat) { private String renderCategorySection(String id, List<Item> items) {
String displayName = cat.getName();
List<Item> items = cat.getItems();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("<div class='card'>"); sb.append("<div class='card'>");
sb.append("<h2>"); sb.append("<h2>");
if ("global".equals(displayName)) { if ("global".equals(id)) {
sb.append("Articles globaux"); sb.append("Articles globaux");
sb.append("<input type='hidden' name='cat|global|name' value='global'>"); // Hidden input to mark cat for server
techId = "global"; sb.append("<input type='hidden' name='cat|").append(id).append("|name' value='global'>");
} else { } else {
// Nom // Copy H2 theme
sb.append("<input type='text' name='cat|").append(techId).append("|name' value=\"").append(displayName).append("\" class='input-h2'>"); sb.append("<input type='text' name='cat|").append(id).append("|name' ")
.append("value=\"").append(id).append("\" ")
.append("style='font-size: 1.5rem; font-weight: bold; border: none; background: transparent; color: #555; width: auto; max-width: 70%; border-bottom: 1px dashed #ccc;'>");
// Couleur de Fond (on utilise cat.getBgColor()) // Delete category button
sb.append("<div style='display:inline-block; vertical-align:middle; margin-right:15px;'>");
sb.append("<div style='font-weight: bold; font-size: 0.7em; padding-bottom: 5px;'>Fond</div>");
sb.append("<input type='color' name='cat|").append(techId).append("|bgColor' value='").append(cat.getBgColor()).append("' style='width:30px; height:25px; border:none; cursor:pointer;'>");
sb.append("</div>");
// Couleur de Texte (on utilise cat.getTextColor())
sb.append("<div style='display:inline-block; vertical-align:middle; margin-right:15px;'>");
sb.append("<div style='font-weight: bold; font-size: 0.7em; padding-bottom: 5px;'>Texte</div>");
sb.append("<input type='color' name='cat|").append(techId).append("|textColor' value='").append(cat.getTextColor()).append("' style='width:30px; height:25px; border:none; cursor:pointer;'>");
sb.append("</div>");
// Bouton supprimer
sb.append(" <button type='button' class='btn-del' style='vertical-align: middle; margin-left: 10px;' ") sb.append(" <button type='button' class='btn-del' style='vertical-align: middle; margin-left: 10px;' ")
.append("onclick=\"if(confirm('Supprimer cette catégorie?')) this.closest('.card').remove()\">×</button>"); .append("onclick=\"if(confirm('Supprimer cette catégorie et tous ses articles ?')) this.closest('.card').remove()\">×</button>");
} }
sb.append("</h2>"); sb.append("</h2>");
// Build table // Build table
sb.append("<table id='table-").append(techId).append("'>"); sb.append("<table id='table-").append(id).append("'>");
sb.append("<tr><th>Image</th><th>Nom</th><th>Prix Min</th><th>Prix Max</th></tr>"); sb.append("<tr><th>Image</th><th>Nom</th><th>Prix Min</th><th>Prix Max</th><th></th></tr>");
int rowIdx = 0;
for (Item item : items) { for (Item item : items) {
sb.append(renderItemRow(techId, item, rowIdx++)); sb.append(renderItemRow(id, item));
} }
sb.append("</table>"); sb.append("</table>");
// Button to add item in this category // Bouton pour ajouter un article dans CETTE table précise
sb.append("<button type='button' class='btn-add' onclick=\"addRow('").append(techId).append("')\">+ Ajouter article</button>"); sb.append("<button type='button' class='btn-add' onclick=\"addRow('").append(id).append("')\">+ Ajouter article</button>");
sb.append("</div>"); sb.append("</div>");
return sb.toString(); return sb.toString();
@@ -196,8 +166,8 @@ public class ControlServer extends NanoHTTPD {
/** /**
* Generate HTML row for each item * Generate HTML row for each item
*/ */
private String renderItemRow(String techId, Item item, int idx) { private String renderItemRow(String catName, Item item) {
String prefix = "item|" + techId + "|" + idx; String prefix = "item|" + catName + "|" + item.getName();
return "<tr>" + return "<tr>" +
"<td><img src='/img_view/" + item.getImage() + "' class='img-p' onerror=\"this.src='https://placehold.co/60?text=?'\">" + "<td><img src='/img_view/" + item.getImage() + "' class='img-p' onerror=\"this.src='https://placehold.co/60?text=?'\">" +
"<br><input type='file' accept='.jpg,.png' style='font-size:10px; width:70px' onchange='uImg(this)'>" + "<br><input type='file' accept='.jpg,.png' style='font-size:10px; width:70px' onchange='uImg(this)'>" +
@@ -219,7 +189,7 @@ public class ControlServer extends NanoHTTPD {
try { try {
Response res = newChunkedResponse(Response.Status.OK, "image/jpeg", new FileInputStream(file)); Response res = newChunkedResponse(Response.Status.OK, "image/jpeg", new FileInputStream(file));
// Avoid cache if user change image // avoid cache if user change image
res.addHeader("Cache-Control", "no-cache, no-store, must-revalidate"); res.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.addHeader("Pragma", "no-cache"); res.addHeader("Pragma", "no-cache");
res.addHeader("Expires", "0"); res.addHeader("Expires", "0");
@@ -229,93 +199,98 @@ public class ControlServer extends NanoHTTPD {
} }
} }
/**
* Receive JSON and update cache and storage catalog
*/
private Response handleSaveEditor(IHTTPSession session) { private Response handleSaveEditor(IHTTPSession session) {
try { try {
// NanoHTTPD read request // NanoHTTPD reads post request : copy all data then sort parameters
Map<String, String> files = new HashMap<>(); Map<String, String> files = new HashMap<>();
session.parseBody(files); session.parseBody(files);
Map<String, List<String>> params = session.getParameters();
String jsonStr = files.get("postData"); // Temp struct for modified categories
if (jsonStr == null || jsonStr.isEmpty()) { // Key is category is, value is item list
return newFixedLengthResponse(Response.Status.BAD_REQUEST, MIME_PLAINTEXT, "Données vides"); Map<String, List<Item>> categoriesMap = new LinkedHashMap<>();
// Map id and categories names
Map<String, String> categoryNames = new HashMap<>();
// Identify categories with "cat|id123|name"
for (Map.Entry<String, List<String>> paramEntry : params.entrySet()) {
String key = paramEntry.getKey();
if (key.startsWith("cat|") && key.endsWith("|name")) {
String[] parts = key.split("\\|");
String catId = parts[1];
String catName = paramEntry.getValue().get(0);
// Si on ne l'a pas déjà ajouté (sécurité)
if (!categoriesMap.containsKey(catId)) {
categoriesMap.put(catId, new ArrayList<Item>());
categoryNames.put(catId, catName);
}
}
} }
JSONObject fullJson = new JSONObject(jsonStr); // Group field for each items
// Get items // Key = "catId|itemId", Value = "name, min, max, img""
JSONObject allFields = fullJson.getJSONObject("items"); Map<String, Map<String, String>> itemDataCollector = new LinkedHashMap<String, Map<String, String>>();
// Get categories order
String[] orderedIds = fullJson.getString("cat_order_list").split(",");
List<Category> finalData = new ArrayList<>(); for (String key : params.keySet()) {
if (key.startsWith("item|") || key.startsWith("new|")) {
String[] parts = key.split("\\|"); // [type, catId, itemId, field]
String catId = parts[1];
String itemId = parts[2];
String field = parts[3];
String value = params.get(key).get(0);
// For each category String fullId = catId + "|" + itemId;
for (String techId : orderedIds) { if (!itemDataCollector.containsKey(fullId)) {
String catNameKey = "cat|" + techId + "|name"; itemDataCollector.put(fullId, new HashMap<String, String>());
// Does it exist }
if (!allFields.has(catNameKey)) continue; itemDataCollector.get(fullId).put(field, value);
}
}
String name = allFields.getString(catNameKey); for (Map.Entry<String, Map<String, String>> entry : itemDataCollector.entrySet()) {
List<Item> itemsInCategory = new ArrayList<>(); String catId = entry.getKey().split("\\|")[0];
Map<String, String> fields = entry.getValue();
// Browse and create items String name = fields.get("name");
int i = 0; if (name == null) name = "Sans nom";
while (true) {
String itemBase = "item|" + techId + "|" + i + "|";
// On vérifie si l'item suivant existe (via son champ name)
if (!allFields.has(itemBase + "name")) break;
// Manage image String img = fields.get("img");
String imgVal = allFields.optString(itemBase + "img", ""); if (img == null) img = "";
if (imgVal.startsWith("data:image")) {
int min = 0;
int max = 0;
try { try {
String newImgName = "img_" + System.currentTimeMillis() + "_" + i; String minStr = fields.get("min");
String base64Data = imgVal.split(",")[1]; if (minStr != null) min = Integer.parseInt(minStr);
byte[] decoded = android.util.Base64.decode(base64Data, android.util.Base64.DEFAULT);
File imageFile = new File(imagesDir, newImgName + ".jpg"); String maxStr = fields.get("max");
try (FileOutputStream fos = new FileOutputStream(imageFile)) { if (maxStr != null) max = Integer.parseInt(maxStr);
fos.write(decoded); } catch (Exception e) {
} // If error, keep 0
imgVal = newImgName; // Replace base64 with name of created jpg file
} catch (Exception e) { Log.e("ControlServer", "Img Error", e); }
} }
itemsInCategory.add(new Item( Item item = new Item(name, img, min, max);
// Mandatory if (categoriesMap.containsKey(catId)) {
allFields.getString(itemBase + "name"), categoriesMap.get(catId).add(item);
// Not mandatory }
imgVal,
parseSafely(allFields.optString(itemBase + "min", "0")),
parseSafely(allFields.optString(itemBase + "max", "0"))
));
i++;
} }
// Create category with items and colors // Stop to use cat id and replace with cat name
Category cat = new Category(name, itemsInCategory); Map<String, List<Item>> finalData = new LinkedHashMap<>();
cat.setBgColor(allFields.optString("cat|" + techId + "|bgColor", "#0049AF")); for (String catId : categoriesMap.keySet()) {
cat.setTextColor(allFields.optString("cat|" + techId + "|textColor", "#FFFFFF")); String realName = categoryNames.get(catId);
finalData.add(cat); finalData.put(realName, categoriesMap.get(catId));
} }
// Save data to disk in JSON format
DataLoader.saveData(finalData); DataLoader.saveData(finalData);
return newFixedLengthResponse(Response.Status.OK, MIME_PLAINTEXT, "OK");
return newFixedLengthResponse("✅ Catalogue enregistré ! <a href='/'>Retour</a>");
} catch (Exception e) { } catch (Exception e) {
Log.e("ControlServer", "Erreur save", e); e.printStackTrace();
return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "Erreur"); return newFixedLengthResponse("❌ Erreur : " + e.getMessage());
}
}
private int parseSafely(String val) {
if (val == null) return 0;
try {
return Integer.parseInt(val.trim());
} catch (Exception e) {
return 0;
} }
} }
@@ -326,9 +301,8 @@ public class ControlServer extends NanoHTTPD {
private Response handleJsonUpload(IHTTPSession session) { private Response handleJsonUpload(IHTTPSession session) {
Map<String, String> tmpFiles = new HashMap<>(); Map<String, String> tmpFiles = new HashMap<>();
try { try {
// NanoHTTPD stores loaded file in temp file
session.parseBody(tmpFiles); session.parseBody(tmpFiles);
// tmpFiles map stores file name and path to tmp folder // NanoHTTPD stocke le fichier avec le nom du champ HTML (json_file)
String tmpPath = tmpFiles.get("json_file"); String tmpPath = tmpFiles.get("json_file");
if (tmpPath == null) return newFixedLengthResponse("❌ Aucun fichier reçu."); if (tmpPath == null) return newFixedLengthResponse("❌ Aucun fichier reçu.");
@@ -358,17 +332,17 @@ public class ControlServer extends NanoHTTPD {
int count = 0; int count = 0;
// Browse temp files created by NanoHTTPD // On parcourt les fichiers temporaires créés par NanoHTTPD
for (Map.Entry<String, String> entry : tmpFiles.entrySet()) { for (Map.Entry<String, String> entry : tmpFiles.entrySet()) {
// Manage multiple files uppload // NanoHTTPD indexe les envois multiples (images, images1, images2...)
if (entry.getKey().startsWith("images")) { if (entry.getKey().startsWith("images")) {
String tmpPath = entry.getValue(); String tmpPath = entry.getValue();
// Get file name // Récupération sécurisée des paramètres pour obtenir le nom original
List<String> params = session.getParameters().get(entry.getKey()); List<String> params = session.getParameters().get(entry.getKey());
if (params != null && !params.isEmpty()) { if (params != null && !params.isEmpty()) {
// Clean file name to remove path, only keep image.jpg or image.png // Nettoyage du nom de fichier (pour ne garder que "image.jpg" sans le chemin PC)
String originalName = new File(params.get(0)).getName(); String originalName = new File(params.get(0)).getName();
File src = new File(tmpPath); File src = new File(tmpPath);

View File

@@ -25,9 +25,6 @@ public class DataLoader {
private static List<Item> cachedGlobals = new ArrayList<>(); private static List<Item> cachedGlobals = new ArrayList<>();
/**
* Get data from input JSON PIECES_FILE
*/
public static void loadData() { public static void loadData() {
File dir = new File(Environment.getExternalStorageDirectory(), EXTERNAL_DIR); File dir = new File(Environment.getExternalStorageDirectory(), EXTERNAL_DIR);
File jsonFile = new File(dir, PIECES_FILE); File jsonFile = new File(dir, PIECES_FILE);
@@ -66,8 +63,8 @@ public class DataLoader {
/** /**
* Create a merge list with global items and items from a specified category for main activity * Create a merge list with global items and items from a specified category for main activity
* Compromise between CPU usage and memory usage : keep cache raw data and combinate global and specific items at call
*/ */
// Compromise between CPU usage and memory usage : keep cache raw data and combinate global and specific items at call
public static List<Item> getItemsForCategory(String categoryName) { public static List<Item> getItemsForCategory(String categoryName) {
// Add global items // Add global items
@@ -102,9 +99,6 @@ public class DataLoader {
public static List<Category> getCategories() { public static List<Category> getCategories() {
return cachedCategories; return cachedCategories;
} }
public static List<Item> getGlobalItems() {
return cachedGlobals;
}
/** /**
* Internal class for GSON * Internal class for GSON
@@ -117,30 +111,36 @@ public class DataLoader {
/** /**
* Write JSON from online editor data * Write JSON from online editor data
*/ */
public static void saveData(List<Category> categoriesList) throws Exception { public static void saveData(Map<String, List<Item>> sections) throws Exception {
File dir = new File(Environment.getExternalStorageDirectory(), EXTERNAL_DIR);
File jsonFile = new File(dir, PIECES_FILE);
// To respect original format, we use the same format as GSON
List<Item> globalList = sections.get("global");
if (globalList == null) {
globalList = new ArrayList<Item>();
}
CategoriesWrapper wrapper = new CategoriesWrapper(); CategoriesWrapper wrapper = new CategoriesWrapper();
wrapper.categories = new ArrayList<>(); wrapper.globalItems = globalList;
wrapper.globalItems = new ArrayList<>(); wrapper.categories = new ArrayList<Category>();
// Browse category // Fill each category
for (Category cat : categoriesList) { for (Map.Entry<String, List<Item>> entry : sections.entrySet()) {
if ("global".equals(cat.getName())) { if (!"global".equals(entry.getKey())) {
wrapper.globalItems = cat.getItems(); wrapper.categories.add(new Category(entry.getKey(), entry.getValue()));
} else {
wrapper.categories.add(cat);
} }
} }
// Create JSON // Convert to pretty JSON, human readable
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
String jsonString = gson.toJson(wrapper); String jsonString = gson.toJson(wrapper);
File dir = new File(Environment.getExternalStorageDirectory(), Config.EXTERNAL_DIR_NAME); // Write to disk
File jsonFile = new File(dir, Config.INPUT_JSON_NAME); try (FileOutputStream fos = new FileOutputStream(jsonFile);
OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8")) {
// Write JSON
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(jsonFile), "UTF-8")) {
writer.write(jsonString); writer.write(jsonString);
writer.flush();
} }
// Update app cache // Update app cache