mirror of
https://github.com/lucasroyerdev/stock-pignon.git
synced 2026-05-10 11:02:26 +00:00
Compare commits
1 Commits
main
...
05f01247e2
| Author | SHA1 | Date | |
|---|---|---|---|
| 05f01247e2 |
@@ -10,8 +10,8 @@ android {
|
||||
applicationId "com.stock.pignon"
|
||||
minSdkVersion 17
|
||||
targetSdkVersion 36
|
||||
versionCode 8
|
||||
versionName "0.6.0"
|
||||
versionCode 7
|
||||
versionName "0.5.2"
|
||||
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Éditeur de Catalogue</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
@@ -96,7 +95,6 @@
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
font-size: 12px;
|
||||
appearance: none;
|
||||
-webkit-appearance: none;
|
||||
outline: none;
|
||||
}
|
||||
@@ -133,7 +131,7 @@
|
||||
cursor: pointer;
|
||||
font-size: 18px;
|
||||
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 {
|
||||
@@ -145,7 +143,7 @@
|
||||
cursor: pointer;
|
||||
font-size: 18px;
|
||||
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 {
|
||||
@@ -155,9 +153,10 @@
|
||||
background: transparent !important;
|
||||
color: #555 !important;
|
||||
width: auto;
|
||||
max-width: 20%;
|
||||
max-width: 70%;
|
||||
border-bottom: 1px dashed #ccc !important;
|
||||
outline: none;
|
||||
/* Enlève le contour bleu au clic */
|
||||
}
|
||||
|
||||
.input-h2:focus {
|
||||
@@ -169,16 +168,15 @@
|
||||
|
||||
<body>
|
||||
<h1>Éditeur de Catalogue</h1>
|
||||
<form id="editor-form" accept-charset="UTF-8">
|
||||
<form action="/save_editor" method="POST">
|
||||
|
||||
{{GENERATED_CONTENT}}
|
||||
|
||||
<div class="actions-bar">
|
||||
<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-cat" onclick="addCategory()">+ Catégorie</button>
|
||||
<input type="submit" value="💾 Enregistrer tout" class="btn-save" style="position:static; transform:none;">
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -187,40 +185,32 @@
|
||||
var t = document.getElementById('table-' + cat);
|
||||
var r = t.insertRow(-1);
|
||||
var id = Date.now();
|
||||
|
||||
r.innerHTML = '<td>' +
|
||||
'<img src="" class="img-p" onerror="this.src=\'https://placehold.co/60?text=?\'" style="display:block; margin-bottom:5px;">' +
|
||||
'<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>' +
|
||||
r.innerHTML = '<td><input type="file" id="f_' + id + '" style="display:none" onchange="uImg(this)">' +
|
||||
'<button type="button" class="link-mod" onclick="document.getElementById(\'f_' + id + '\').click()">Ajouter</button>' +
|
||||
'<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="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><button type="button" class="btn-del" onclick="var l=this.parentNode.parentNode; l.parentNode.removeChild(l);">×</button></td>';
|
||||
}
|
||||
|
||||
function uImg(element) {
|
||||
var f = element.files[0];
|
||||
function uImg(el) {
|
||||
var f = el.files[0];
|
||||
if (!f) return;
|
||||
|
||||
var td = element.parentNode;
|
||||
var imgTag = td.querySelector('.img-p');
|
||||
var hiddenInput = td.querySelector('input[type="hidden"]');
|
||||
|
||||
var reader = new FileReader();
|
||||
reader.onload = function(e) {
|
||||
imgTag.src = e.target.result;
|
||||
hiddenInput.value = e.target.result;
|
||||
};
|
||||
reader.readAsDataURL(f);
|
||||
var row = el.parentNode.parentNode;
|
||||
var id = f.name.split('.').slice(0, -1).join('.');
|
||||
row.querySelector('input[type="hidden"]').value = id;
|
||||
var fd = new FormData();
|
||||
fd.append('images', f);
|
||||
fetch('/upload_images', { method: 'POST', body: fd }).then(function () { alert('Image envoyée : ' + id); });
|
||||
}
|
||||
|
||||
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 (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();
|
||||
}
|
||||
}
|
||||
@@ -229,20 +219,15 @@
|
||||
var name = prompt("Nom de la nouvelle catégorie ?");
|
||||
if (!name || name.trim() === "") return;
|
||||
|
||||
// Temp ID
|
||||
// On crée un ID temporaire basé sur le temps
|
||||
var tempId = "newcat_" + Date.now();
|
||||
|
||||
// On crée la structure HTML de la carte
|
||||
var container = document.createElement('div');
|
||||
container.className = 'card';
|
||||
container.innerHTML =
|
||||
'<h2>' +
|
||||
'<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>' +
|
||||
'</h2>' +
|
||||
'<table id="table-' + tempId + '">' +
|
||||
@@ -250,67 +235,13 @@
|
||||
'</table>' +
|
||||
'<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 actionBar = document.querySelector('.actions-bar');
|
||||
form.insertBefore(container, actionBar);
|
||||
|
||||
// On scrolle vers la nouvelle catégorie
|
||||
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>
|
||||
</body>
|
||||
@@ -20,10 +20,8 @@ public class CartItem {
|
||||
public int getMinPrice() { return minPrice; }
|
||||
public int getMaxPrice() { return maxPrice; }
|
||||
public int getQuantity() { return quantity; }
|
||||
public void setQuantity(int quantity) { this.quantity = quantity; }
|
||||
public int getTotalMin() { return minPrice * quantity; }
|
||||
public int getTotalMax() { return maxPrice * quantity; }
|
||||
public String getImageFile() { return imageFile; }
|
||||
|
||||
// Setters
|
||||
public void setQuantity(int quantity) { this.quantity = quantity; }
|
||||
}
|
||||
|
||||
@@ -8,14 +8,10 @@ public class CartManager {
|
||||
// Unified and global list for whole application
|
||||
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() {}
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
return items;
|
||||
}
|
||||
@@ -29,9 +25,7 @@ public class CartManager {
|
||||
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) {
|
||||
CartItem current = getItemByName(name);
|
||||
|
||||
@@ -46,27 +40,20 @@ public class CartManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Range-based pricing
|
||||
*/
|
||||
// Range-based pricing
|
||||
|
||||
public static int getGlobalTotalMin() {
|
||||
int total = 0;
|
||||
for (CartItem item : items) total += item.getTotalMin();
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Range-based pricing
|
||||
*/
|
||||
public static int getGlobalTotalMax() {
|
||||
int total = 0;
|
||||
for (CartItem item : items) total += item.getTotalMax();
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove item from cart
|
||||
*/
|
||||
public static void clear() {
|
||||
items.clear();
|
||||
}
|
||||
|
||||
@@ -30,9 +30,7 @@ public class Category {
|
||||
public String getName() { return name; }
|
||||
public String getBgColor() { return bgColor; }
|
||||
public String getTextColor() { return textColor; }
|
||||
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; }
|
||||
public List<Item> getItems() {
|
||||
return items != null ? items : new ArrayList<>();
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,6 @@ package com.stock.pignon;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Environment;
|
||||
import android.util.Log;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import fi.iki.elonen.NanoHTTPD;
|
||||
import java.io.File;
|
||||
@@ -13,17 +11,17 @@ import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
|
||||
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
|
||||
public Response serve(IHTTPSession session) {
|
||||
@@ -73,10 +71,8 @@ public class ControlServer extends NanoHTTPD {
|
||||
|
||||
if (session.getMethod() == Method.POST) {
|
||||
switch (uri) {
|
||||
// Soon deprecated with online editor
|
||||
case "/upload_json":
|
||||
return handleJsonUpload(session);
|
||||
// Soon deprecated with online editor
|
||||
case "/upload_images":
|
||||
return handleImagesUpload(session);
|
||||
case "/save_editor":
|
||||
@@ -93,7 +89,7 @@ public class ControlServer extends NanoHTTPD {
|
||||
private String getHtml(String file) {
|
||||
try {
|
||||
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");
|
||||
String html = s.hasNext() ? s.next() : "";
|
||||
is.close();
|
||||
@@ -107,87 +103,61 @@ public class ControlServer extends NanoHTTPD {
|
||||
* Read from asset and return html file
|
||||
*/
|
||||
private String fillEditor() {
|
||||
// Get data from assets
|
||||
// Get data for assets
|
||||
DataLoader.loadData();
|
||||
// Create an html string to fill the template
|
||||
StringBuilder html = new StringBuilder();
|
||||
// Save categories order
|
||||
List<String> orderList = new ArrayList<>();
|
||||
|
||||
// Globals
|
||||
String globalId = "global";
|
||||
Category globalCat = new Category("global", DataLoader.getGlobalItems());
|
||||
html.append(renderCategorySection(globalId, globalCat));
|
||||
orderList.add(globalId);
|
||||
// Browse map : 'id' for categories name, 'items' for items list
|
||||
for (Map.Entry<String, List<Item>> section : DataLoader.getAllSections().entrySet()) {
|
||||
String id = section.getKey();
|
||||
List<Item> items = section.getValue();
|
||||
|
||||
// Browser categories
|
||||
int index = 0;
|
||||
for (Category cat : DataLoader.getCategories()) {
|
||||
// cat_0, cat_1...
|
||||
String techId = "cat_" + index;
|
||||
|
||||
html.append(renderCategorySection(techId, cat));
|
||||
orderList.add(techId);
|
||||
|
||||
index++;
|
||||
// For each category, render a HTML card
|
||||
html.append(renderCategorySection(id, items));
|
||||
}
|
||||
|
||||
String orderField = "<input type='hidden' name='cat_order_list' value='" +
|
||||
android.text.TextUtils.join(",", orderList) + "'>";
|
||||
|
||||
return getHtml("editor.html").replace("{{GENERATED_CONTENT}}", html + orderField);
|
||||
return getHtml("editor.html").replace("{{GENERATED_CONTENT}}", html.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate HTML section for each category
|
||||
*/
|
||||
private String renderCategorySection(String techId, Category cat) {
|
||||
String displayName = cat.getName();
|
||||
List<Item> items = cat.getItems();
|
||||
private String renderCategorySection(String id, List<Item> items) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
sb.append("<div class='card'>");
|
||||
sb.append("<h2>");
|
||||
|
||||
if ("global".equals(displayName)) {
|
||||
if ("global".equals(id)) {
|
||||
sb.append("Articles globaux");
|
||||
sb.append("<input type='hidden' name='cat|global|name' value='global'>");
|
||||
techId = "global";
|
||||
// Hidden input to mark cat for server
|
||||
sb.append("<input type='hidden' name='cat|").append(id).append("|name' value='global'>");
|
||||
} else {
|
||||
// Nom
|
||||
sb.append("<input type='text' name='cat|").append(techId).append("|name' value=\"").append(displayName).append("\" class='input-h2'>");
|
||||
// Copy H2 theme
|
||||
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())
|
||||
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
|
||||
// Delete category button
|
||||
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>");
|
||||
|
||||
// Build table
|
||||
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></tr>");
|
||||
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><th></th></tr>");
|
||||
|
||||
int rowIdx = 0;
|
||||
for (Item item : items) {
|
||||
sb.append(renderItemRow(techId, item, rowIdx++));
|
||||
sb.append(renderItemRow(id, item));
|
||||
}
|
||||
|
||||
sb.append("</table>");
|
||||
|
||||
// Button to add item in this category
|
||||
sb.append("<button type='button' class='btn-add' onclick=\"addRow('").append(techId).append("')\">+ Ajouter article</button>");
|
||||
// Bouton pour ajouter un article dans CETTE table précise
|
||||
sb.append("<button type='button' class='btn-add' onclick=\"addRow('").append(id).append("')\">+ Ajouter article</button>");
|
||||
sb.append("</div>");
|
||||
|
||||
return sb.toString();
|
||||
@@ -196,8 +166,8 @@ public class ControlServer extends NanoHTTPD {
|
||||
/**
|
||||
* Generate HTML row for each item
|
||||
*/
|
||||
private String renderItemRow(String techId, Item item, int idx) {
|
||||
String prefix = "item|" + techId + "|" + idx;
|
||||
private String renderItemRow(String catName, Item item) {
|
||||
String prefix = "item|" + catName + "|" + item.getName();
|
||||
return "<tr>" +
|
||||
"<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)'>" +
|
||||
@@ -219,7 +189,7 @@ public class ControlServer extends NanoHTTPD {
|
||||
|
||||
try {
|
||||
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("Pragma", "no-cache");
|
||||
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) {
|
||||
try {
|
||||
// NanoHTTPD read request
|
||||
// NanoHTTPD reads post request : copy all data then sort parameters
|
||||
Map<String, String> files = new HashMap<>();
|
||||
session.parseBody(files);
|
||||
Map<String, List<String>> params = session.getParameters();
|
||||
|
||||
String jsonStr = files.get("postData");
|
||||
if (jsonStr == null || jsonStr.isEmpty()) {
|
||||
return newFixedLengthResponse(Response.Status.BAD_REQUEST, MIME_PLAINTEXT, "Données vides");
|
||||
// Temp struct for modified categories
|
||||
// Key is category is, value is item list
|
||||
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);
|
||||
// Get items
|
||||
JSONObject allFields = fullJson.getJSONObject("items");
|
||||
// Get categories order
|
||||
String[] orderedIds = fullJson.getString("cat_order_list").split(",");
|
||||
// Group field for each items
|
||||
// Key = "catId|itemId", Value = "name, min, max, img""
|
||||
Map<String, Map<String, String>> itemDataCollector = new LinkedHashMap<String, Map<String, String>>();
|
||||
|
||||
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
|
||||
for (String techId : orderedIds) {
|
||||
String catNameKey = "cat|" + techId + "|name";
|
||||
// Does it exist
|
||||
if (!allFields.has(catNameKey)) continue;
|
||||
|
||||
String name = 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;
|
||||
|
||||
// Manage image
|
||||
String imgVal = allFields.optString(itemBase + "img", "");
|
||||
if (imgVal.startsWith("data:image")) {
|
||||
try {
|
||||
String newImgName = "img_" + System.currentTimeMillis() + "_" + i;
|
||||
String base64Data = imgVal.split(",")[1];
|
||||
byte[] decoded = android.util.Base64.decode(base64Data, android.util.Base64.DEFAULT);
|
||||
|
||||
File imageFile = new File(imagesDir, newImgName + ".jpg");
|
||||
try (FileOutputStream fos = new FileOutputStream(imageFile)) {
|
||||
fos.write(decoded);
|
||||
}
|
||||
imgVal = newImgName; // Replace base64 with name of created jpg file
|
||||
} catch (Exception e) { Log.e("ControlServer", "Img Error", e); }
|
||||
String fullId = catId + "|" + itemId;
|
||||
if (!itemDataCollector.containsKey(fullId)) {
|
||||
itemDataCollector.put(fullId, new HashMap<String, String>());
|
||||
}
|
||||
itemDataCollector.get(fullId).put(field, value);
|
||||
}
|
||||
}
|
||||
|
||||
itemsInCategory.add(new Item(
|
||||
// Mandatory
|
||||
allFields.getString(itemBase + "name"),
|
||||
// Not mandatory
|
||||
imgVal,
|
||||
parseSafely(allFields.optString(itemBase + "min", "0")),
|
||||
parseSafely(allFields.optString(itemBase + "max", "0"))
|
||||
));
|
||||
i++;
|
||||
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
|
||||
}
|
||||
|
||||
// Create category with items and colors
|
||||
Category cat = new Category(name, itemsInCategory);
|
||||
cat.setBgColor(allFields.optString("cat|" + techId + "|bgColor", "#0049AF"));
|
||||
cat.setTextColor(allFields.optString("cat|" + techId + "|textColor", "#FFFFFF"));
|
||||
finalData.add(cat);
|
||||
Item item = new Item(name, img, min, max);
|
||||
if (categoriesMap.containsKey(catId)) {
|
||||
categoriesMap.get(catId).add(item);
|
||||
}
|
||||
}
|
||||
|
||||
// Stop to use cat id and replace with cat name
|
||||
Map<String, List<Item>> finalData = new LinkedHashMap<>();
|
||||
for (String catId : categoriesMap.keySet()) {
|
||||
String realName = categoryNames.get(catId);
|
||||
finalData.put(realName, categoriesMap.get(catId));
|
||||
}
|
||||
|
||||
// Save data to disk in JSON format
|
||||
DataLoader.saveData(finalData);
|
||||
return newFixedLengthResponse(Response.Status.OK, MIME_PLAINTEXT, "OK");
|
||||
|
||||
return newFixedLengthResponse("✅ Catalogue enregistré ! <a href='/'>Retour</a>");
|
||||
|
||||
} catch (Exception e) {
|
||||
Log.e("ControlServer", "Erreur save", e);
|
||||
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;
|
||||
e.printStackTrace();
|
||||
return newFixedLengthResponse("❌ Erreur : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,9 +301,8 @@ public class ControlServer extends NanoHTTPD {
|
||||
private Response handleJsonUpload(IHTTPSession session) {
|
||||
Map<String, String> tmpFiles = new HashMap<>();
|
||||
try {
|
||||
// NanoHTTPD stores loaded file in temp file
|
||||
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");
|
||||
if (tmpPath == null) return newFixedLengthResponse("❌ Aucun fichier reçu.");
|
||||
|
||||
@@ -358,17 +332,17 @@ public class ControlServer extends NanoHTTPD {
|
||||
|
||||
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()) {
|
||||
// Manage multiple files uppload
|
||||
// NanoHTTPD indexe les envois multiples (images, images1, images2...)
|
||||
if (entry.getKey().startsWith("images")) {
|
||||
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());
|
||||
|
||||
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();
|
||||
|
||||
File src = new File(tmpPath);
|
||||
|
||||
@@ -25,9 +25,6 @@ public class DataLoader {
|
||||
private static List<Item> cachedGlobals = new ArrayList<>();
|
||||
|
||||
|
||||
/**
|
||||
* Get data from input JSON PIECES_FILE
|
||||
*/
|
||||
public static void loadData() {
|
||||
File dir = new File(Environment.getExternalStorageDirectory(), EXTERNAL_DIR);
|
||||
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
|
||||
* 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) {
|
||||
|
||||
// Add global items
|
||||
@@ -102,9 +99,6 @@ public class DataLoader {
|
||||
public static List<Category> getCategories() {
|
||||
return cachedCategories;
|
||||
}
|
||||
public static List<Item> getGlobalItems() {
|
||||
return cachedGlobals;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal class for GSON
|
||||
@@ -117,30 +111,36 @@ public class DataLoader {
|
||||
/**
|
||||
* Write JSON from online editor data
|
||||
*/
|
||||
public static void saveData(List<Category> categoriesList) throws Exception {
|
||||
CategoriesWrapper wrapper = new CategoriesWrapper();
|
||||
wrapper.categories = new ArrayList<>();
|
||||
wrapper.globalItems = new ArrayList<>();
|
||||
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);
|
||||
|
||||
// Browse category
|
||||
for (Category cat : categoriesList) {
|
||||
if ("global".equals(cat.getName())) {
|
||||
wrapper.globalItems = cat.getItems();
|
||||
} else {
|
||||
wrapper.categories.add(cat);
|
||||
// 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();
|
||||
wrapper.globalItems = globalList;
|
||||
wrapper.categories = new ArrayList<Category>();
|
||||
|
||||
// Fill each category
|
||||
for (Map.Entry<String, List<Item>> entry : sections.entrySet()) {
|
||||
if (!"global".equals(entry.getKey())) {
|
||||
wrapper.categories.add(new Category(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
// Create JSON
|
||||
// Convert to pretty JSON, human readable
|
||||
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||
String jsonString = gson.toJson(wrapper);
|
||||
|
||||
File dir = new File(Environment.getExternalStorageDirectory(), Config.EXTERNAL_DIR_NAME);
|
||||
File jsonFile = new File(dir, Config.INPUT_JSON_NAME);
|
||||
|
||||
// Write JSON
|
||||
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(jsonFile), "UTF-8")) {
|
||||
// Write to disk
|
||||
try (FileOutputStream fos = new FileOutputStream(jsonFile);
|
||||
OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8")) {
|
||||
writer.write(jsonString);
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
// Update app cache
|
||||
|
||||
Reference in New Issue
Block a user