mirror of
https://github.com/lucasroyerdev/stock-pignon.git
synced 2026-05-10 11:02:26 +00:00
Compare commits
3 Commits
05f01247e2
...
bae5186029
| Author | SHA1 | Date | |
|---|---|---|---|
| bae5186029 | |||
| 1df2d95586 | |||
| ebb10ed61b |
@@ -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;
|
||||||
@@ -95,6 +96,7 @@
|
|||||||
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;
|
||||||
}
|
}
|
||||||
@@ -131,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 {
|
||||||
@@ -143,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 {
|
||||||
@@ -153,10 +155,9 @@
|
|||||||
background: transparent !important;
|
background: transparent !important;
|
||||||
color: #555 !important;
|
color: #555 !important;
|
||||||
width: auto;
|
width: auto;
|
||||||
max-width: 70%;
|
max-width: 20%;
|
||||||
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 {
|
||||||
@@ -168,15 +169,16 @@
|
|||||||
|
|
||||||
<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}}
|
||||||
|
|
||||||
<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-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>
|
||||||
|
<button type="button" class="btn-cancel" onclick="handleCancel(event)">✖ Tout annuler</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
@@ -185,32 +187,40 @@
|
|||||||
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)">' +
|
|
||||||
'<button type="button" class="link-mod" onclick="document.getElementById(\'f_' + id + '\').click()">Ajouter</button>' +
|
r.innerHTML = '<td>' +
|
||||||
'<input type="hidden" name="new|' + cat + '|' + id + '|img" value=""></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>' +
|
||||||
'<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(el) {
|
function uImg(element) {
|
||||||
var f = el.files[0];
|
var f = element.files[0];
|
||||||
if (!f) return;
|
if (!f) return;
|
||||||
var row = el.parentNode.parentNode;
|
|
||||||
var id = f.name.split('.').slice(0, -1).join('.');
|
var td = element.parentNode;
|
||||||
row.querySelector('input[type="hidden"]').value = id;
|
var imgTag = td.querySelector('.img-p');
|
||||||
var fd = new FormData();
|
var hiddenInput = td.querySelector('input[type="hidden"]');
|
||||||
fd.append('images', f);
|
|
||||||
fetch('/upload_images', { method: 'POST', body: fd }).then(function () { alert('Image envoyée : ' + id); });
|
var reader = new FileReader();
|
||||||
|
reader.onload = function(e) {
|
||||||
|
imgTag.src = e.target.result;
|
||||||
|
hiddenInput.value = e.target.result;
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(f);
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleCancel(e) {
|
function handleCancel(e) {
|
||||||
// Empêche le formulaire de faire quoi que ce soit
|
// Avoid form to wait for data to send
|
||||||
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 ?")) {
|
||||||
// Le ?t= force le navigateur à oublier les saisies en cours
|
// Random URL parameters ?t= to force browser to forget previous data
|
||||||
window.location.href = "/edit?t=" + Date.now();
|
window.location.href = "/edit?t=" + Date.now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -219,15 +229,20 @@
|
|||||||
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;
|
||||||
|
|
||||||
// On crée un ID temporaire basé sur le temps
|
// Temp ID
|
||||||
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 + '">' +
|
||||||
@@ -235,13 +250,67 @@
|
|||||||
'</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>
|
||||||
@@ -20,8 +20,10 @@ 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; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,10 +8,14 @@ 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;
|
||||||
}
|
}
|
||||||
@@ -25,7 +29,9 @@ 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);
|
||||||
|
|
||||||
@@ -40,20 +46,27 @@ 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();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,9 @@ 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() {
|
public List<Item> getItems() { return items != null ? items : new ArrayList<>(); }
|
||||||
return items != null ? items : new ArrayList<>();
|
|
||||||
}
|
// Setters
|
||||||
|
public void setBgColor(String bgColor) { this.bgColor = bgColor; }
|
||||||
|
public void setTextColor(String textColor) { this.textColor = textColor; }
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,8 @@ 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;
|
||||||
@@ -11,17 +13,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;
|
||||||
@@ -37,7 +39,7 @@ public class ControlServer extends NanoHTTPD {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Main method which receive remote request
|
* Main method which manage requests
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Response serve(IHTTPSession session) {
|
public Response serve(IHTTPSession session) {
|
||||||
@@ -71,8 +73,10 @@ 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":
|
||||||
@@ -89,7 +93,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 \\A
|
// Scanner html file from the beginning with "\\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();
|
||||||
@@ -103,61 +107,87 @@ 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 for assets
|
// Get data from 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<>();
|
||||||
|
|
||||||
// Browse map : 'id' for categories name, 'items' for items list
|
// Globals
|
||||||
for (Map.Entry<String, List<Item>> section : DataLoader.getAllSections().entrySet()) {
|
String globalId = "global";
|
||||||
String id = section.getKey();
|
Category globalCat = new Category("global", DataLoader.getGlobalItems());
|
||||||
List<Item> items = section.getValue();
|
html.append(renderCategorySection(globalId, globalCat));
|
||||||
|
orderList.add(globalId);
|
||||||
|
|
||||||
// For each category, render a HTML card
|
// Browser categories
|
||||||
html.append(renderCategorySection(id, items));
|
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++;
|
||||||
}
|
}
|
||||||
|
|
||||||
return getHtml("editor.html").replace("{{GENERATED_CONTENT}}", html.toString());
|
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, Category cat) {
|
||||||
|
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(id)) {
|
if ("global".equals(displayName)) {
|
||||||
sb.append("Articles globaux");
|
sb.append("Articles globaux");
|
||||||
// Hidden input to mark cat for server
|
sb.append("<input type='hidden' name='cat|global|name' value='global'>");
|
||||||
sb.append("<input type='hidden' name='cat|").append(id).append("|name' value='global'>");
|
techId = "global";
|
||||||
} else {
|
} else {
|
||||||
// Copy H2 theme
|
// Nom
|
||||||
sb.append("<input type='text' name='cat|").append(id).append("|name' ")
|
sb.append("<input type='text' name='cat|").append(techId).append("|name' value=\"").append(displayName).append("\" class='input-h2'>");
|
||||||
.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;'>");
|
|
||||||
|
|
||||||
// Delete category button
|
// 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
|
||||||
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?')) 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>");
|
||||||
|
|
||||||
// Bouton pour ajouter un article dans CETTE table précise
|
// 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();
|
||||||
@@ -166,8 +196,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)'>" +
|
||||||
@@ -189,7 +219,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");
|
||||||
@@ -199,98 +229,93 @@ 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);
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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<String, Map<String, String>>();
|
JSONObject allFields = fullJson.getJSONObject("items");
|
||||||
|
// Get categories order
|
||||||
|
String[] orderedIds = fullJson.getString("cat_order_list").split(",");
|
||||||
|
|
||||||
for (String key : params.keySet()) {
|
List<Category> finalData = new ArrayList<>();
|
||||||
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);
|
|
||||||
|
|
||||||
String fullId = catId + "|" + itemId;
|
// For each category
|
||||||
if (!itemDataCollector.containsKey(fullId)) {
|
for (String techId : orderedIds) {
|
||||||
itemDataCollector.put(fullId, new HashMap<String, String>());
|
String catNameKey = "cat|" + techId + "|name";
|
||||||
}
|
// Does it exist
|
||||||
itemDataCollector.get(fullId).put(field, value);
|
if (!allFields.has(catNameKey)) continue;
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (Map.Entry<String, Map<String, String>> entry : itemDataCollector.entrySet()) {
|
String name = allFields.getString(catNameKey);
|
||||||
String catId = entry.getKey().split("\\|")[0];
|
List<Item> itemsInCategory = new ArrayList<>();
|
||||||
Map<String, String> fields = entry.getValue();
|
|
||||||
|
|
||||||
String name = fields.get("name");
|
// Browse and create items
|
||||||
if (name == null) name = "Sans nom";
|
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;
|
||||||
|
|
||||||
String img = fields.get("img");
|
// Manage image
|
||||||
if (img == null) img = "";
|
String imgVal = allFields.optString(itemBase + "img", "");
|
||||||
|
if (imgVal.startsWith("data:image")) {
|
||||||
int min = 0;
|
|
||||||
int max = 0;
|
|
||||||
try {
|
try {
|
||||||
String minStr = fields.get("min");
|
String newImgName = "img_" + System.currentTimeMillis() + "_" + i;
|
||||||
if (minStr != null) min = Integer.parseInt(minStr);
|
String base64Data = imgVal.split(",")[1];
|
||||||
|
byte[] decoded = android.util.Base64.decode(base64Data, android.util.Base64.DEFAULT);
|
||||||
|
|
||||||
String maxStr = fields.get("max");
|
File imageFile = new File(imagesDir, newImgName + ".jpg");
|
||||||
if (maxStr != null) max = Integer.parseInt(maxStr);
|
try (FileOutputStream fos = new FileOutputStream(imageFile)) {
|
||||||
} catch (Exception e) {
|
fos.write(decoded);
|
||||||
// If error, keep 0
|
}
|
||||||
|
imgVal = newImgName; // Replace base64 with name of created jpg file
|
||||||
|
} catch (Exception e) { Log.e("ControlServer", "Img Error", e); }
|
||||||
}
|
}
|
||||||
|
|
||||||
Item item = new Item(name, img, min, max);
|
itemsInCategory.add(new Item(
|
||||||
if (categoriesMap.containsKey(catId)) {
|
// Mandatory
|
||||||
categoriesMap.get(catId).add(item);
|
allFields.getString(itemBase + "name"),
|
||||||
}
|
// Not mandatory
|
||||||
|
imgVal,
|
||||||
|
parseSafely(allFields.optString(itemBase + "min", "0")),
|
||||||
|
parseSafely(allFields.optString(itemBase + "max", "0"))
|
||||||
|
));
|
||||||
|
i++;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop to use cat id and replace with cat name
|
// Create category with items and colors
|
||||||
Map<String, List<Item>> finalData = new LinkedHashMap<>();
|
Category cat = new Category(name, itemsInCategory);
|
||||||
for (String catId : categoriesMap.keySet()) {
|
cat.setBgColor(allFields.optString("cat|" + techId + "|bgColor", "#0049AF"));
|
||||||
String realName = categoryNames.get(catId);
|
cat.setTextColor(allFields.optString("cat|" + techId + "|textColor", "#FFFFFF"));
|
||||||
finalData.put(realName, categoriesMap.get(catId));
|
finalData.add(cat);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
||||||
e.printStackTrace();
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,8 +326,9 @@ 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);
|
||||||
// NanoHTTPD stocke le fichier avec le nom du champ HTML (json_file)
|
// tmpFiles map stores file name and path to tmp folder
|
||||||
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.");
|
||||||
|
|
||||||
@@ -332,17 +358,17 @@ public class ControlServer extends NanoHTTPD {
|
|||||||
|
|
||||||
int count = 0;
|
int count = 0;
|
||||||
|
|
||||||
// On parcourt les fichiers temporaires créés par NanoHTTPD
|
// Browse temp files created by NanoHTTPD
|
||||||
for (Map.Entry<String, String> entry : tmpFiles.entrySet()) {
|
for (Map.Entry<String, String> entry : tmpFiles.entrySet()) {
|
||||||
// NanoHTTPD indexe les envois multiples (images, images1, images2...)
|
// Manage multiple files uppload
|
||||||
if (entry.getKey().startsWith("images")) {
|
if (entry.getKey().startsWith("images")) {
|
||||||
String tmpPath = entry.getValue();
|
String tmpPath = entry.getValue();
|
||||||
|
|
||||||
// Récupération sécurisée des paramètres pour obtenir le nom original
|
// Get file name
|
||||||
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()) {
|
||||||
// Nettoyage du nom de fichier (pour ne garder que "image.jpg" sans le chemin PC)
|
// Clean file name to remove path, only keep image.jpg or image.png
|
||||||
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);
|
||||||
|
|||||||
@@ -25,6 +25,9 @@ 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);
|
||||||
@@ -63,8 +66,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
|
||||||
@@ -99,6 +102,9 @@ 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
|
||||||
@@ -111,36 +117,30 @@ public class DataLoader {
|
|||||||
/**
|
/**
|
||||||
* Write JSON from online editor data
|
* Write JSON from online editor data
|
||||||
*/
|
*/
|
||||||
public static void saveData(Map<String, List<Item>> sections) throws Exception {
|
public static void saveData(List<Category> categoriesList) 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.globalItems = globalList;
|
wrapper.categories = new ArrayList<>();
|
||||||
wrapper.categories = new ArrayList<Category>();
|
wrapper.globalItems = new ArrayList<>();
|
||||||
|
|
||||||
// Fill each category
|
// Browse category
|
||||||
for (Map.Entry<String, List<Item>> entry : sections.entrySet()) {
|
for (Category cat : categoriesList) {
|
||||||
if (!"global".equals(entry.getKey())) {
|
if ("global".equals(cat.getName())) {
|
||||||
wrapper.categories.add(new Category(entry.getKey(), entry.getValue()));
|
wrapper.globalItems = cat.getItems();
|
||||||
|
} else {
|
||||||
|
wrapper.categories.add(cat);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert to pretty JSON, human readable
|
// Create JSON
|
||||||
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||||
String jsonString = gson.toJson(wrapper);
|
String jsonString = gson.toJson(wrapper);
|
||||||
|
|
||||||
// Write to disk
|
File dir = new File(Environment.getExternalStorageDirectory(), Config.EXTERNAL_DIR_NAME);
|
||||||
try (FileOutputStream fos = new FileOutputStream(jsonFile);
|
File jsonFile = new File(dir, Config.INPUT_JSON_NAME);
|
||||||
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
|
||||||
|
|||||||
Reference in New Issue
Block a user