mirror of
https://github.com/lucasroyerdev/stock-pignon.git
synced 2026-05-10 11:02:26 +00:00
feat: online editor fully working, add/remove item/category
This commit is contained in:
@@ -1,8 +1,9 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html lang="fr">
|
||||||
|
|
||||||
<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;
|
||||||
@@ -132,7 +133,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 {
|
||||||
@@ -144,7 +145,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 {
|
||||||
@@ -168,7 +169,7 @@
|
|||||||
|
|
||||||
<body>
|
<body>
|
||||||
<h1>Éditeur de Catalogue</h1>
|
<h1>Éditeur de Catalogue</h1>
|
||||||
<form action="/save_editor" method="POST">
|
<form id="editor-form" accept-charset="UTF-8">
|
||||||
|
|
||||||
{{GENERATED_CONTENT}}
|
{{GENERATED_CONTENT}}
|
||||||
|
|
||||||
@@ -176,7 +177,8 @@
|
|||||||
<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-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>
|
<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;">
|
<button type="button" onclick="sendData()" class="btn-save" style="position:static; transform:none;">💾
|
||||||
|
Enregistrer tout</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
@@ -240,5 +242,56 @@
|
|||||||
|
|
||||||
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) => {
|
||||||
|
const catInput = card.querySelector('input[name^="cat|"]');
|
||||||
|
if (!catInput) return;
|
||||||
|
|
||||||
|
const techId = "c" + catIdx; // c0, c1...
|
||||||
|
catOrder.push(techId);
|
||||||
|
data.items["cat|" + techId + "|name"] = catInput.value;
|
||||||
|
|
||||||
|
// 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>
|
||||||
@@ -4,6 +4,7 @@ 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 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;
|
||||||
@@ -12,12 +13,15 @@ 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.io.ByteArrayOutputStream;
|
||||||
|
|
||||||
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.LinkedHashMap;
|
||||||
import java.util.Scanner;
|
import java.util.Scanner;
|
||||||
|
import java.util.Iterator;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a web server to remote management of app assets.
|
* Create a web server to remote management of app assets.
|
||||||
@@ -110,57 +114,67 @@ public class ControlServer extends NanoHTTPD {
|
|||||||
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<>();
|
||||||
|
int index = 0;
|
||||||
|
|
||||||
// Browse map : 'id' for categories name, 'items' for items list
|
// Browse map : 'id' for categories name, 'items' for items list
|
||||||
for (Map.Entry<String, List<Item>> section : DataLoader.getAllSections().entrySet()) {
|
for (Map.Entry<String, List<Item>> section : DataLoader.getAllSections().entrySet()) {
|
||||||
String id = section.getKey();
|
String technicalId = "cat_" + index;
|
||||||
|
String displayName = section.getKey();
|
||||||
List<Item> items = section.getValue();
|
List<Item> items = section.getValue();
|
||||||
|
|
||||||
// For each category, render a HTML card
|
orderList.add(technicalId);
|
||||||
html.append(renderCategorySection(id, items));
|
|
||||||
}
|
|
||||||
|
|
||||||
return getHtml("editor.html").replace("{{GENERATED_CONTENT}}", html.toString());
|
// For each category, render a HTML card
|
||||||
|
html.append(renderCategorySection(technicalId, displayName, items));
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
String orderField = "<input type='hidden' name='cat_order_list' value='" +
|
||||||
|
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 id, List<Item> items) {
|
private String renderCategorySection(String techId, String displayName, List<Item> items) {
|
||||||
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(id)) {
|
if ("global".equals(displayName)) {
|
||||||
sb.append("Articles globaux");
|
sb.append("Articles globaux");
|
||||||
// Hidden input to mark cat for server
|
// Hidden input to mark cat for server
|
||||||
sb.append("<input type='hidden' name='cat|").append(id).append("|name' value='global'>");
|
sb.append("<input type='hidden' name='cat|").append(displayName).append("|name' value='global'>");
|
||||||
|
techId = "global";
|
||||||
} else {
|
} else {
|
||||||
// Copy H2 theme
|
// Copy H2 theme
|
||||||
sb.append("<input type='text' name='cat|").append(id).append("|name' ")
|
sb.append("<input type='text' name='cat|").append(techId).append("|name' ")
|
||||||
.append("value=\"").append(id).append("\" ")
|
.append("value=\"").append(displayName).append("\" class='input-h2'>");
|
||||||
.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;'>");
|
|
||||||
|
|
||||||
// Delete category button
|
// Delete category button
|
||||||
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 et tous ses articles ?')) 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(id).append("'>");
|
sb.append("<table id='table-").append(techId).append("'>");
|
||||||
sb.append("<tr><th>Image</th><th>Nom</th><th>Prix Min</th><th>Prix Max</th><th></th></tr>");
|
sb.append("<tr><th>Image</th><th>Nom</th><th>Prix Min</th><th>Prix Max</th></tr>");
|
||||||
|
|
||||||
|
int rowIdx = 0;
|
||||||
for (Item item : items) {
|
for (Item item : items) {
|
||||||
sb.append(renderItemRow(id, item));
|
sb.append(renderItemRow(techId, item, rowIdx++));
|
||||||
}
|
}
|
||||||
|
|
||||||
sb.append("</table>");
|
sb.append("</table>");
|
||||||
|
|
||||||
// Button to add item in this category
|
// Button to add item in this category
|
||||||
sb.append("<button type='button' class='btn-add' onclick=\"addRow('").append(id).append("')\">+ Ajouter article</button>");
|
sb.append("<button type='button' class='btn-add' onclick=\"addRow('").append(techId).append("')\">+ Ajouter article</button>");
|
||||||
sb.append("</div>");
|
sb.append("</div>");
|
||||||
|
|
||||||
return sb.toString();
|
return sb.toString();
|
||||||
@@ -169,8 +183,8 @@ public class ControlServer extends NanoHTTPD {
|
|||||||
/**
|
/**
|
||||||
* Generate HTML row for each item
|
* Generate HTML row for each item
|
||||||
*/
|
*/
|
||||||
private String renderItemRow(String catName, Item item) {
|
private String renderItemRow(String techId, Item item, int idx) {
|
||||||
String prefix = "item|" + catName + "|" + item.getName();
|
String prefix = "item|" + techId + "|" + idx;
|
||||||
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)'>" +
|
||||||
@@ -202,105 +216,75 @@ 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 reads post request : copy all data then sort parameters
|
// NanoHTTPD read request
|
||||||
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();
|
|
||||||
|
|
||||||
// Temp struct for modified categories
|
String jsonStr = files.get("postData");
|
||||||
// Key is category is, value is item list
|
if (jsonStr == null || jsonStr.isEmpty()) {
|
||||||
Map<String, List<Item>> categoriesMap = new LinkedHashMap<>();
|
return newFixedLengthResponse(Response.Status.BAD_REQUEST, MIME_PLAINTEXT, "Données vides");
|
||||||
// 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);
|
|
||||||
|
|
||||||
// Create category only if it doesn't exist already
|
|
||||||
if (!categoriesMap.containsKey(catId)) {
|
|
||||||
categoriesMap.put(catId, new ArrayList<>());
|
|
||||||
categoryNames.put(catId, catName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Group field for each items
|
JSONObject fullJson = new JSONObject(jsonStr);
|
||||||
// Key = "catId|itemId", Value = "name, min, max, img""
|
// Get items
|
||||||
Map<String, Map<String, String>> itemDataCollector = new LinkedHashMap<>();
|
JSONObject allFields = fullJson.getJSONObject("items");
|
||||||
|
// Get categories order
|
||||||
|
String[] orderedIds = fullJson.getString("cat_order_list").split(",");
|
||||||
|
|
||||||
for (String key : params.keySet()) {
|
// LinkedHashMap to keep order
|
||||||
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];
|
|
||||||
List<String> values = params.get(key);
|
|
||||||
String value = (values != null && !values.isEmpty()) ? values.get(0) : "";
|
|
||||||
|
|
||||||
String fullId = catId + "|" + itemId;
|
|
||||||
Map<String, String> itemFields = itemDataCollector.get(fullId);
|
|
||||||
|
|
||||||
if (itemFields == null) {
|
|
||||||
itemFields = new HashMap<>();
|
|
||||||
itemDataCollector.put(fullId, itemFields);
|
|
||||||
}
|
|
||||||
|
|
||||||
itemFields.put(field, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (Map.Entry<String, Map<String, String>> entry : itemDataCollector.entrySet()) {
|
|
||||||
String catId = entry.getKey().split("\\|")[0];
|
|
||||||
Map<String, String> fields = entry.getValue();
|
|
||||||
|
|
||||||
String name = fields.get("name");
|
|
||||||
if (name == null) name = "Sans nom";
|
|
||||||
|
|
||||||
String img = fields.get("img");
|
|
||||||
if (img == null) img = "";
|
|
||||||
|
|
||||||
int min = 0;
|
|
||||||
int max = 0;
|
|
||||||
try {
|
|
||||||
String minStr = fields.get("min");
|
|
||||||
if (minStr != null) min = Integer.parseInt(minStr);
|
|
||||||
|
|
||||||
String maxStr = fields.get("max");
|
|
||||||
if (maxStr != null) max = Integer.parseInt(maxStr);
|
|
||||||
} catch (Exception e) {
|
|
||||||
// If error, keep 0
|
|
||||||
}
|
|
||||||
|
|
||||||
Item item = new Item(name, img, min, max);
|
|
||||||
List<Item> categoryItems = categoriesMap.get(catId);
|
|
||||||
|
|
||||||
if (categoryItems != null) {
|
|
||||||
categoryItems.add(item);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stop to use cat ID and replace with cat name
|
|
||||||
Map<String, List<Item>> finalData = new LinkedHashMap<>();
|
Map<String, List<Item>> finalData = new LinkedHashMap<>();
|
||||||
for (String catId : categoriesMap.keySet()) {
|
|
||||||
String realName = categoryNames.get(catId);
|
// For each category
|
||||||
finalData.put(realName, categoriesMap.get(catId));
|
for (String techId : orderedIds) {
|
||||||
|
// Create awaited label
|
||||||
|
String catNameKey = "cat|" + techId + "|name";
|
||||||
|
// Does it exist
|
||||||
|
if (!allFields.has(catNameKey)) continue;
|
||||||
|
|
||||||
|
// Get data
|
||||||
|
String realCatName = allFields.getString(catNameKey);
|
||||||
|
List<Item> itemsInCategory = new ArrayList<>();
|
||||||
|
|
||||||
|
// Browse and create items
|
||||||
|
int i = 0;
|
||||||
|
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;
|
||||||
|
|
||||||
|
itemsInCategory.add(new Item(
|
||||||
|
// Mandatory
|
||||||
|
allFields.getString(itemBase + "name"),
|
||||||
|
// Not mandatory
|
||||||
|
allFields.optString(itemBase + "img", ""),
|
||||||
|
parseSafely(allFields.optString(itemBase + "min", "0")),
|
||||||
|
parseSafely(allFields.optString(itemBase + "max", "0"))
|
||||||
|
));
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
finalData.put(realCatName, itemsInCategory);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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 lors de la sauvegarde", e);
|
Log.e("ControlServer", "Erreur save", e);
|
||||||
return newFixedLengthResponse("❌ Erreur : " + e.getMessage());
|
return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "Erreur");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int parseSafely(String val) {
|
||||||
|
if (val == null) return 0;
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(val.trim());
|
||||||
|
} catch (Exception e) {
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user