mirror of
https://github.com/lucasroyerdev/stock-pignon.git
synced 2026-05-10 11:02:26 +00:00
Compare commits
4 Commits
develop
...
2c225f6821
| Author | SHA1 | Date | |
|---|---|---|---|
| 2c225f6821 | |||
| 7b53f8407c | |||
| 7bea2fa9cf | |||
| 5e69a13487 |
@@ -10,8 +10,8 @@ android {
|
|||||||
applicationId "com.stock.pignon"
|
applicationId "com.stock.pignon"
|
||||||
minSdkVersion 17
|
minSdkVersion 17
|
||||||
targetSdkVersion 36
|
targetSdkVersion 36
|
||||||
versionCode 3
|
versionCode 5
|
||||||
versionName "0.3.0"
|
versionName "0.5.0"
|
||||||
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package com.stock.pignon;
|
|||||||
|
|
||||||
import android.app.AlertDialog;
|
import android.app.AlertDialog;
|
||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
import android.content.Intent;
|
|
||||||
import android.os.Handler;
|
import android.os.Handler;
|
||||||
import android.os.Environment;
|
import android.os.Environment;
|
||||||
import android.text.Html;
|
import android.text.Html;
|
||||||
@@ -22,9 +21,8 @@ import java.io.FileOutputStream;
|
|||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
import java.io.OutputStreamWriter;
|
import java.io.OutputStreamWriter;
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.util.HashMap;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Action on shopping cart: validation, clearing, and persistence
|
* Action on shopping cart: validation, clearing, and persistence
|
||||||
@@ -33,6 +31,21 @@ public class CartActionHelper {
|
|||||||
|
|
||||||
private static final String TAG = "CartActionHelper";
|
private static final String TAG = "CartActionHelper";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Data structure for JSON and CSV
|
||||||
|
*/
|
||||||
|
private static class StockEntry {
|
||||||
|
String date;
|
||||||
|
String name;
|
||||||
|
int qty;
|
||||||
|
|
||||||
|
StockEntry(String date, String name, int qty) {
|
||||||
|
this.date = date;
|
||||||
|
this.name = name;
|
||||||
|
this.qty = qty;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resets the cart data and refreshes UI
|
* Resets the cart data and refreshes UI
|
||||||
*/
|
*/
|
||||||
@@ -90,6 +103,74 @@ public class CartActionHelper {
|
|||||||
.show();
|
.show();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merges current cart items with the existing stock file (json and csv) on the SD Card.
|
||||||
|
*/
|
||||||
|
private static void saveCartToExternalFile(List<CartItem> cartItems) {
|
||||||
|
File dir = new File(Environment.getExternalStorageDirectory(), Config.EXTERNAL_DIR_NAME);
|
||||||
|
File stockFile = new File(dir, Config.OUTPUT_JSON_NAME);
|
||||||
|
File csvFile = new File(dir, Config.OUTPUT_CSV_NAME);
|
||||||
|
|
||||||
|
String today = DateHelper.getTodayIso();
|
||||||
|
Gson gson = new Gson();
|
||||||
|
|
||||||
|
// Load previous list
|
||||||
|
List<StockEntry> history = loadHistory(stockFile, gson);
|
||||||
|
|
||||||
|
// Merge current cart items in previous list
|
||||||
|
for (CartItem cartItem : cartItems) {
|
||||||
|
boolean merged = false;
|
||||||
|
for (StockEntry entry : history) {
|
||||||
|
// Same date same name ? Add it
|
||||||
|
if (entry.date.equals(today) && entry.name.equals(cartItem.getName())) {
|
||||||
|
entry.qty += cartItem.getQuantity();
|
||||||
|
merged = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Not found on the same date ? Create it
|
||||||
|
if (!merged) {
|
||||||
|
history.add(new StockEntry(today, cartItem.getName(), cartItem.getQuantity()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Save to JSON
|
||||||
|
try (FileOutputStream fos = new FileOutputStream(stockFile);
|
||||||
|
OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8")) {
|
||||||
|
gson.newBuilder().setPrettyPrinting().create().toJson(history, writer);
|
||||||
|
} catch (Exception e) {
|
||||||
|
Log.e(TAG, "Error writing JSON", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save to CSV, french format with ";"
|
||||||
|
try (FileOutputStream fos = new FileOutputStream(csvFile);
|
||||||
|
OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8")) {
|
||||||
|
writer.write('\ufeff');
|
||||||
|
writer.write("Date;Article;Quantité\n");
|
||||||
|
for (StockEntry entry : history) {
|
||||||
|
writer.write(entry.date + ";" + entry.name.replace(";", ",") + ";" + entry.qty + "\n");
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
Log.e(TAG, "Error writing CSV", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load JSON history
|
||||||
|
*/
|
||||||
|
private static List<StockEntry> loadHistory(File file, Gson gson) {
|
||||||
|
if (!file.exists()) return new ArrayList<>();
|
||||||
|
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
|
||||||
|
Type type = new TypeToken<List<StockEntry>>(){}.getType();
|
||||||
|
List<StockEntry> result = gson.fromJson(reader, type);
|
||||||
|
return (result != null) ? result : new ArrayList<>();
|
||||||
|
} catch (Exception e) {
|
||||||
|
Log.e(TAG, "Error reading json history", e);
|
||||||
|
return new ArrayList<>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Displays a thank you popup and returns to the main menu after 2 seconds.
|
* Displays a thank you popup and returns to the main menu after 2 seconds.
|
||||||
*/
|
*/
|
||||||
@@ -101,87 +182,21 @@ public class CartActionHelper {
|
|||||||
.create();
|
.create();
|
||||||
merciDialog.show();
|
merciDialog.show();
|
||||||
|
|
||||||
|
|
||||||
new Handler().postDelayed(() -> {
|
new Handler().postDelayed(() -> {
|
||||||
// Close dialog
|
// Close dialog
|
||||||
merciDialog.dismiss();
|
merciDialog.dismiss();
|
||||||
|
|
||||||
|
if (activity instanceof MainActivity) {
|
||||||
|
MainActivity main = (MainActivity) activity;
|
||||||
// Go to home if not already
|
// Go to home if not already
|
||||||
if (!(activity instanceof MainActivity)) {
|
main.showHome();
|
||||||
Intent intent = new Intent(activity, MainActivity.class);
|
|
||||||
// Clear the backstack so the user can't "go back" to a validated cart
|
// Clear the backstack so the user can't "go back" to a validated cart
|
||||||
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
|
GridLayout grid = main.findViewById(R.id.gridPieces);
|
||||||
activity.startActivity(intent);
|
refreshGridQuantities(grid);
|
||||||
}
|
}
|
||||||
}, 2000);
|
}, 2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Merges current cart items with the existing stock file (json and csv) on the SD Card.
|
|
||||||
*/
|
|
||||||
private static void saveCartToExternalFile(List<CartItem> cartItems) {
|
|
||||||
File dir = new File(Environment.getExternalStorageDirectory(), Config.EXTERNAL_DIR_NAME);
|
|
||||||
File stockFile = new File(dir, Config.OUPUT_JSON_NAME);
|
|
||||||
File csvFile = new File(dir, Config.OUPUT_CSV_NAME);
|
|
||||||
|
|
||||||
Gson gson = new Gson();
|
|
||||||
// Load previous list
|
|
||||||
Map<String, Integer> stockMap = loadExistingStock(stockFile, gson);
|
|
||||||
|
|
||||||
// Add current cart item
|
|
||||||
for (CartItem item : cartItems) {
|
|
||||||
Integer qtyObj = stockMap.get(item.getName());
|
|
||||||
int currentQty = (qtyObj != null) ? qtyObj : 0;
|
|
||||||
stockMap.put(item.getName(), currentQty + item.getQuantity());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save to JSON
|
|
||||||
try (FileOutputStream fos = new FileOutputStream(stockFile);
|
|
||||||
OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8")) {
|
|
||||||
gson.toJson(stockMap, writer);
|
|
||||||
} catch (Exception e) {
|
|
||||||
Log.e(TAG, "Failed to write stock file", e);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save to CSV, french format with ";"
|
|
||||||
try (FileOutputStream fos = new FileOutputStream(csvFile);
|
|
||||||
OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8")) {
|
|
||||||
|
|
||||||
// UTF-8 BOM and columns headers
|
|
||||||
writer.write('\ufeff');
|
|
||||||
writer.write("Article;Quantité\n");
|
|
||||||
|
|
||||||
for (Map.Entry<String, Integer> entry : stockMap.entrySet()) {
|
|
||||||
writer.write(entry.getKey().replace(";", ",") + ";" + entry.getValue() + "\n");
|
|
||||||
}
|
|
||||||
Log.i(TAG, "CSV Export updated successfully");
|
|
||||||
} catch (Exception e) {
|
|
||||||
Log.e(TAG, "Failed to write CSV file", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reads the current stock file. If the file is missing or corrupted, returns an empty map.
|
|
||||||
*/
|
|
||||||
private static Map<String, Integer> loadExistingStock(File stockFile, Gson gson) {
|
|
||||||
if (!stockFile.exists()) return new HashMap<>();
|
|
||||||
|
|
||||||
try (FileInputStream fis = new FileInputStream(stockFile);
|
|
||||||
@SuppressWarnings("CharsetObjectCanBeUsed")
|
|
||||||
InputStreamReader reader = new InputStreamReader(fis, "UTF-8")) {
|
|
||||||
|
|
||||||
// Type definition for Map required by GSON : <String, Integer>
|
|
||||||
Type type = new TypeToken<Map<String, Integer>>(){}.getType();
|
|
||||||
// Read and fill map
|
|
||||||
Map<String, Integer> result = gson.fromJson(reader, type);
|
|
||||||
|
|
||||||
return (result != null) ? result : new HashMap<>();
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
Log.e(TAG, "Error reading existing stock, starting fresh", e);
|
|
||||||
return new HashMap<>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates the UI grid to reflect quantities.
|
* Updates the UI grid to reflect quantities.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -22,17 +22,23 @@ import java.util.List;
|
|||||||
public class CartViewHelper {
|
public class CartViewHelper {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Refreshes the entire cart side-panel or list
|
* Short version for app resume : update without changing validate/back button state
|
||||||
* Clears everything and rebuild on current CartManager data
|
|
||||||
*/
|
*/
|
||||||
public static void updateCartView(LinearLayout cartList, Context context) {
|
public static void updateCartView(LinearLayout cartList, Context context) {
|
||||||
|
updateCartView(cartList, context, false, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Full version with validate/back button management
|
||||||
|
*/
|
||||||
|
public static void updateCartView(LinearLayout cartList, Context context, boolean updateButton, boolean isHome) {
|
||||||
if (cartList == null) return;
|
if (cartList == null) return;
|
||||||
|
|
||||||
// Clear and get current items
|
// Clean item lists
|
||||||
cartList.removeAllViews();
|
cartList.removeAllViews();
|
||||||
List<CartItem> cartItems = CartManager.getItems();
|
List<CartItem> cartItems = CartManager.getItems();
|
||||||
|
|
||||||
// If empty cart, show it to user
|
// Manage empty cart
|
||||||
if (cartItems.isEmpty()) {
|
if (cartItems.isEmpty()) {
|
||||||
TextView empty = new TextView(context);
|
TextView empty = new TextView(context);
|
||||||
empty.setText(context.getString(R.string.cart_empty));
|
empty.setText(context.getString(R.string.cart_empty));
|
||||||
@@ -40,35 +46,24 @@ public class CartViewHelper {
|
|||||||
empty.setGravity(Gravity.CENTER);
|
empty.setGravity(Gravity.CENTER);
|
||||||
empty.setPadding(0, 50, 0, 0);
|
empty.setPadding(0, 50, 0, 0);
|
||||||
cartList.addView(empty);
|
cartList.addView(empty);
|
||||||
|
|
||||||
updateTotalDisplay(context, 0, 0);
|
updateTotalDisplay(context, 0, 0);
|
||||||
return;
|
} else {
|
||||||
}
|
// Create list if not empty
|
||||||
|
|
||||||
// Build list and calculate total at the same time
|
|
||||||
int totalMin = 0;
|
int totalMin = 0;
|
||||||
int totalMax = 0;
|
int totalMax = 0;
|
||||||
|
|
||||||
for (CartItem item : cartItems) {
|
for (CartItem item : cartItems) {
|
||||||
totalMin += item.getTotalMin();
|
totalMin += item.getTotalMin();
|
||||||
totalMax += item.getTotalMax();
|
totalMax += item.getTotalMax();
|
||||||
|
|
||||||
// Create and add the row view
|
// Create a line for each item
|
||||||
cartList.addView(createCartItemView(item, cartList, context));
|
cartList.addView(createCartItemView(item, cartList, context));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Display global price range at the end
|
|
||||||
updateTotalDisplay(context, totalMin, totalMax);
|
updateTotalDisplay(context, totalMin, totalMax);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Update validate/back button
|
||||||
* Updates the global price range at the bottom of the screen
|
if (updateButton && context instanceof MainActivity) {
|
||||||
*/
|
((MainActivity) context).updateActionButton(isHome);
|
||||||
private static void updateTotalDisplay(Context context, int min, int max) {
|
|
||||||
TextView totalView = ((Activity) context).findViewById(R.id.totalView);
|
|
||||||
if (totalView != null) {
|
|
||||||
// Using string resources
|
|
||||||
totalView.setText(context.getString(R.string.price_range, min, max, "€"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,7 +76,6 @@ public class CartViewHelper {
|
|||||||
row.setOrientation(LinearLayout.HORIZONTAL);
|
row.setOrientation(LinearLayout.HORIZONTAL);
|
||||||
row.setGravity(Gravity.CENTER_VERTICAL);
|
row.setGravity(Gravity.CENTER_VERTICAL);
|
||||||
|
|
||||||
// Layout parameters
|
|
||||||
LinearLayout.LayoutParams rowParams = new LinearLayout.LayoutParams(
|
LinearLayout.LayoutParams rowParams = new LinearLayout.LayoutParams(
|
||||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
LinearLayout.LayoutParams.MATCH_PARENT,
|
||||||
LinearLayout.LayoutParams.WRAP_CONTENT);
|
LinearLayout.LayoutParams.WRAP_CONTENT);
|
||||||
@@ -96,7 +90,7 @@ public class CartViewHelper {
|
|||||||
image.setLayoutParams(imgParams);
|
image.setLayoutParams(imgParams);
|
||||||
row.addView(image);
|
row.addView(image);
|
||||||
|
|
||||||
// Sublayout for name + [quantity + price]
|
// Sublayout infos
|
||||||
LinearLayout infoLayout = new LinearLayout(context);
|
LinearLayout infoLayout = new LinearLayout(context);
|
||||||
infoLayout.setOrientation(LinearLayout.VERTICAL);
|
infoLayout.setOrientation(LinearLayout.VERTICAL);
|
||||||
infoLayout.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
|
infoLayout.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
|
||||||
@@ -108,7 +102,7 @@ public class CartViewHelper {
|
|||||||
nameView.setTypeface(null, Typeface.BOLD);
|
nameView.setTypeface(null, Typeface.BOLD);
|
||||||
infoLayout.addView(nameView);
|
infoLayout.addView(nameView);
|
||||||
|
|
||||||
// Quantity and price range
|
// Quantity / price
|
||||||
TextView detailsView = new TextView(context);
|
TextView detailsView = new TextView(context);
|
||||||
String details = context.getString(R.string.cart_item, item.getQuantity(), item.getTotalMin(), item.getTotalMax());
|
String details = context.getString(R.string.cart_item, item.getQuantity(), item.getTotalMin(), item.getTotalMax());
|
||||||
detailsView.setText(details);
|
detailsView.setText(details);
|
||||||
@@ -124,42 +118,35 @@ public class CartViewHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates the delete button
|
* Creates the delete button for each item
|
||||||
*/
|
*/
|
||||||
private static Button createRemoveButton(CartItem item, LinearLayout cartList, Context context) {
|
private static Button createRemoveButton(CartItem item, LinearLayout cartList, Context context) {
|
||||||
Button btn = new Button(context);
|
Button btn = new Button(context);
|
||||||
btn.setText("✖");
|
btn.setText("✖");
|
||||||
btn.setTextSize(18);
|
|
||||||
btn.setTextColor(Color.WHITE);
|
btn.setTextColor(Color.WHITE);
|
||||||
btn.setGravity(Gravity.CENTER);
|
|
||||||
|
|
||||||
// Conversion DP to PX for consistent size on all screens
|
|
||||||
float scale = context.getResources().getDisplayMetrics().density;
|
float scale = context.getResources().getDisplayMetrics().density;
|
||||||
int sizePx = (int) (48 * scale + 0.5f);
|
int sizePx = (int) (48 * scale + 0.5f);
|
||||||
|
btn.setLayoutParams(new LinearLayout.LayoutParams(sizePx, sizePx));
|
||||||
|
|
||||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(sizePx, sizePx);
|
|
||||||
btn.setLayoutParams(params);
|
|
||||||
|
|
||||||
// Background: grey rounded rectangle (API 17 fallback)
|
|
||||||
GradientDrawable shape = new GradientDrawable();
|
GradientDrawable shape = new GradientDrawable();
|
||||||
shape.setColor(Color.parseColor("#E53935")); // Reddish to indicate delete
|
shape.setColor(Color.parseColor("#E53935"));
|
||||||
shape.setCornerRadius(4 * scale);
|
shape.setCornerRadius(4 * scale);
|
||||||
btn.setBackground(shape);
|
btn.setBackground(shape);
|
||||||
|
|
||||||
btn.setOnClickListener(v -> {
|
btn.setOnClickListener(v -> {
|
||||||
// setting quantity to 0 removes the item
|
CartManager.addOrUpdateItem(item.getName(), item.getMinPrice(), item.getMaxPrice(), 0, item.getImageFile());
|
||||||
CartManager.addOrUpdateItem(
|
|
||||||
item.getName(),
|
|
||||||
item.getMinPrice(),
|
|
||||||
item.getMaxPrice(),
|
|
||||||
0, // Setting quantity to 0 triggers removal
|
|
||||||
item.getImageFile()
|
|
||||||
);
|
|
||||||
|
|
||||||
// visual refresh of the cart list
|
|
||||||
updateCartView(cartList, context);
|
updateCartView(cartList, context);
|
||||||
});
|
});
|
||||||
|
|
||||||
return btn;
|
return btn;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manage price range for whole cart
|
||||||
|
*/
|
||||||
|
private static void updateTotalDisplay(Context context, int min, int max) {
|
||||||
|
TextView totalView = ((Activity) context).findViewById(R.id.totalView);
|
||||||
|
if (totalView != null) {
|
||||||
|
totalView.setText(context.getString(R.string.price_range, min, max, "€"));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -12,8 +12,8 @@ public class Config {
|
|||||||
public static final String INPUT_JSON_NAME = "pieces.json";
|
public static final String INPUT_JSON_NAME = "pieces.json";
|
||||||
|
|
||||||
// Output json
|
// Output json
|
||||||
public static final String OUPUT_JSON_NAME = "stock.json";
|
public static final String OUTPUT_JSON_NAME = "stock.json";
|
||||||
|
|
||||||
// Output json
|
// Output json
|
||||||
public static final String OUPUT_CSV_NAME = "stock.csv";
|
public static final String OUTPUT_CSV_NAME = "stock.csv";
|
||||||
}
|
}
|
||||||
@@ -42,16 +42,16 @@ public class ControlServer extends NanoHTTPD {
|
|||||||
return downloadFile(Config.INPUT_JSON_NAME);
|
return downloadFile(Config.INPUT_JSON_NAME);
|
||||||
|
|
||||||
case "/output_json":
|
case "/output_json":
|
||||||
return viewFile(Config.OUPUT_JSON_NAME);
|
return viewFile(Config.OUTPUT_JSON_NAME);
|
||||||
|
|
||||||
case "/download_output_json":
|
case "/download_output_json":
|
||||||
return downloadFile(Config.OUPUT_JSON_NAME);
|
return downloadFile(Config.OUTPUT_JSON_NAME);
|
||||||
|
|
||||||
case "/output_csv":
|
case "/output_csv":
|
||||||
return viewFile(Config.OUPUT_CSV_NAME);
|
return viewFile(Config.OUTPUT_CSV_NAME);
|
||||||
|
|
||||||
case "/download_output_csv":
|
case "/download_output_csv":
|
||||||
return downloadFile(Config.OUPUT_CSV_NAME);
|
return downloadFile(Config.OUTPUT_CSV_NAME);
|
||||||
|
|
||||||
case "/":
|
case "/":
|
||||||
case "/index.html":
|
case "/index.html":
|
||||||
|
|||||||
15
app/src/main/java/com/stock/pignon/DateHelper.java
Normal file
15
app/src/main/java/com/stock/pignon/DateHelper.java
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
// DateHelper.java
|
||||||
|
package com.stock.pignon;
|
||||||
|
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
public class DateHelper {
|
||||||
|
/**
|
||||||
|
* Return ISO format date (AAAA-MM-JJ)
|
||||||
|
*/
|
||||||
|
public static String getTodayIso() {
|
||||||
|
return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,12 +61,6 @@ public class MainActivity extends AppCompatActivity {
|
|||||||
gridPieces = findViewById(R.id.gridPieces);
|
gridPieces = findViewById(R.id.gridPieces);
|
||||||
mainImage = findViewById(R.id.mainImage);
|
mainImage = findViewById(R.id.mainImage);
|
||||||
|
|
||||||
// Setup Back Button
|
|
||||||
Button backBtn = findViewById(R.id.backToHomeBtn);
|
|
||||||
if (backBtn != null) {
|
|
||||||
backBtn.setOnClickListener(v -> showHome());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Copy assets to sd card if not founded
|
// Copy assets to sd card if not founded
|
||||||
copyAssetsIfEmpty();
|
copyAssetsIfEmpty();
|
||||||
// Get data from sd card
|
// Get data from sd card
|
||||||
@@ -85,6 +79,14 @@ public class MainActivity extends AppCompatActivity {
|
|||||||
getSupportActionBar().setTitle(" 🚲 Atelier du Pignon - Gestion du stock à prix libre");
|
getSupportActionBar().setTitle(" 🚲 Atelier du Pignon - Gestion du stock à prix libre");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get app version
|
||||||
|
String versionName;
|
||||||
|
try {
|
||||||
|
versionName = "App v" + getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
|
||||||
|
} catch (Exception e) {
|
||||||
|
versionName = ""; // Fallback
|
||||||
|
}
|
||||||
|
|
||||||
// Launch server
|
// Launch server
|
||||||
server = new ControlServer(8080);
|
server = new ControlServer(8080);
|
||||||
try {
|
try {
|
||||||
@@ -93,12 +95,12 @@ public class MainActivity extends AppCompatActivity {
|
|||||||
|
|
||||||
// On met l'URL directement dans le sous-titre de l'ActionBar
|
// On met l'URL directement dans le sous-titre de l'ActionBar
|
||||||
if (getSupportActionBar() != null) {
|
if (getSupportActionBar() != null) {
|
||||||
getSupportActionBar().setSubtitle("🟢 Serveur actif : " + url);
|
getSupportActionBar().setSubtitle("Serveur en ligne : " + url + " - " + versionName);
|
||||||
}
|
}
|
||||||
Log.i(TAG, "Serveur démarré sur : " + url);
|
Log.i(TAG, "Server started on : " + url);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
if (getSupportActionBar() != null) {
|
if (getSupportActionBar() != null) {
|
||||||
getSupportActionBar().setSubtitle("🔴 Erreur serveur : Port 8080 occupé");
|
getSupportActionBar().setSubtitle("Erreur serveur" + " - " + versionName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -115,7 +117,7 @@ public class MainActivity extends AppCompatActivity {
|
|||||||
super.onDestroy();
|
super.onDestroy();
|
||||||
if (server != null) {
|
if (server != null) {
|
||||||
server.stop();
|
server.stop();
|
||||||
Log.i(TAG, "Serveur arrêté.");
|
Log.i(TAG, "Server stopped.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,6 +194,8 @@ public class MainActivity extends AppCompatActivity {
|
|||||||
homeLayout.setVisibility(View.GONE);
|
homeLayout.setVisibility(View.GONE);
|
||||||
categoryItemsLayout.setVisibility(View.VISIBLE);
|
categoryItemsLayout.setVisibility(View.VISIBLE);
|
||||||
|
|
||||||
|
updateActionButton(false);
|
||||||
|
|
||||||
gridPieces.removeAllViews();
|
gridPieces.removeAllViews();
|
||||||
|
|
||||||
// Calculate item width for a 4-column grid
|
// Calculate item width for a 4-column grid
|
||||||
@@ -258,9 +262,11 @@ public class MainActivity extends AppCompatActivity {
|
|||||||
CartViewHelper.updateCartView(cartList, this);
|
CartViewHelper.updateCartView(cartList, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void showHome() {
|
public void showHome() {
|
||||||
categoryItemsLayout.setVisibility(View.GONE);
|
categoryItemsLayout.setVisibility(View.GONE);
|
||||||
homeLayout.setVisibility(View.VISIBLE);
|
homeLayout.setVisibility(View.VISIBLE);
|
||||||
|
|
||||||
|
updateActionButton(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void loadMainImage() {
|
private void loadMainImage() {
|
||||||
@@ -268,8 +274,6 @@ public class MainActivity extends AppCompatActivity {
|
|||||||
ImageLoader.loadImage(mainImage, "_velo", 800,800);
|
ImageLoader.loadImage(mainImage, "_velo", 800,800);
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Button Actions (linked via android:onClick in XML) ---
|
|
||||||
|
|
||||||
public void emptyCart(View view) {
|
public void emptyCart(View view) {
|
||||||
CartActionHelper.emptyCart(cartList, this);
|
CartActionHelper.emptyCart(cartList, this);
|
||||||
}
|
}
|
||||||
@@ -278,29 +282,87 @@ public class MainActivity extends AppCompatActivity {
|
|||||||
CartActionHelper.validateCart(cartList, this);
|
CartActionHelper.validateCart(cartList, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void updateActionButton(boolean isHome) {
|
||||||
|
Button btn = findViewById(R.id.validateCartBtn);
|
||||||
|
if (btn == null) return;
|
||||||
|
|
||||||
|
if (isHome) {
|
||||||
|
// Home mode : validate button
|
||||||
|
btn.setText(getString(R.string.cart_validate_btn));
|
||||||
|
btn.setBackgroundColor(Color.parseColor("#43A047")); // Vert
|
||||||
|
btn.setOnClickListener(v -> validateCart(v));
|
||||||
|
} else {
|
||||||
|
// Category mode : back button
|
||||||
|
btn.setText(getString(R.string.cart_back_btn));
|
||||||
|
btn.setBackgroundColor(Color.parseColor("#1E88E5")); // Bleu
|
||||||
|
btn.setOnClickListener(v -> showHome());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private int dpToPx(int dp) {
|
private int dpToPx(int dp) {
|
||||||
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
|
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void copyAssetsIfEmpty() {
|
private void copyAssetsIfEmpty() {
|
||||||
File folder = new File(Environment.getExternalStorageDirectory(), Config.EXTERNAL_DIR_NAME);
|
File rootDir = new File(Environment.getExternalStorageDirectory(), Config.EXTERNAL_DIR_NAME);
|
||||||
|
|
||||||
// First safety : is folder already in sdcard ?
|
// Create root folder if not found
|
||||||
if (!folder.exists()) {
|
if (!rootDir.exists()) {
|
||||||
// Second safety : are we able to create folder ?
|
if (!rootDir.mkdirs()) {
|
||||||
if (folder.mkdirs()) {
|
Log.e("MainActivity", "Can't create root dir." + rootDir.getAbsolutePath());
|
||||||
// Copy JSON file
|
return;
|
||||||
copyFileFromAssets(Config.INPUT_JSON_NAME, new File(folder, Config.INPUT_JSON_NAME));
|
|
||||||
|
|
||||||
// Copy images subfolder
|
|
||||||
File imgFolder = new File(folder, Config.IMAGES_SUBDIR_NAME);
|
|
||||||
if (imgFolder.mkdirs()) {
|
|
||||||
copyFolderFromAssets(Config.IMAGES_SUBDIR_NAME, imgFolder);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check pieces.json
|
||||||
|
File inputJson = new File(rootDir, Config.INPUT_JSON_NAME);
|
||||||
|
if (!inputJson.exists()) {
|
||||||
|
Log.i("MainActivity", "pieces.json not found, copying it...");
|
||||||
|
copyFileFromAssets(Config.INPUT_JSON_NAME, inputJson);
|
||||||
|
} else {
|
||||||
|
Log.d("MainActivity", "Keep existing pieces.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check stock.json and stock.csv output files to avoid control server error
|
||||||
|
checkOrCreateEmptyFile(new File(rootDir, Config.OUTPUT_JSON_NAME), "[]");
|
||||||
|
checkOrCreateEmptyFile(new File(rootDir, Config.OUTPUT_CSV_NAME), "");
|
||||||
|
|
||||||
|
// Check images folder
|
||||||
|
File imgDir = new File(rootDir, Config.IMAGES_SUBDIR_NAME);
|
||||||
|
if (!imgDir.exists()) {
|
||||||
|
if (!imgDir.mkdirs()) {
|
||||||
|
Log.e("MainActivity", "Can't create images dir.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy images only if not found
|
||||||
|
String[] filesInImgDir = imgDir.list();
|
||||||
|
if (filesInImgDir == null || filesInImgDir.length == 0) {
|
||||||
|
Log.i("MainActivity", "Images folder empty. Installing images...");
|
||||||
|
copyFolderFromAssets(Config.IMAGES_SUBDIR_NAME, imgDir);
|
||||||
|
} else {
|
||||||
|
Log.d("MainActivity", "Keep existing images.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a file with default content if not found
|
||||||
|
*/
|
||||||
|
private void checkOrCreateEmptyFile(File file, String defaultContent) {
|
||||||
|
if (!file.exists()) {
|
||||||
|
try (FileOutputStream fos = new FileOutputStream(file)) {
|
||||||
|
fos.write(defaultContent.getBytes());
|
||||||
|
Log.d(TAG, "Initialisation de : " + file.getName());
|
||||||
|
} catch (IOException e) {
|
||||||
|
Log.e(TAG, "Erreur lors de l'initialisation de " + file.getName(), e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy folder from assets
|
||||||
|
*/
|
||||||
private void copyFolderFromAssets(String assetDirName, File destDir) {
|
private void copyFolderFromAssets(String assetDirName, File destDir) {
|
||||||
try {
|
try {
|
||||||
String[] files = getAssets().list(assetDirName);
|
String[] files = getAssets().list(assetDirName);
|
||||||
@@ -316,25 +378,28 @@ public class MainActivity extends AppCompatActivity {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
Log.e("MainActivity", "Erreur listing assets: " + assetDirName, e);
|
Log.e("MainActivity", "Listing assets error: " + assetDirName, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy file from assets
|
||||||
|
*/
|
||||||
private void copyFileFromAssets(String assetName, File destFile) {
|
private void copyFileFromAssets(String assetName, File destFile) {
|
||||||
// Optimized read
|
// Optimized read
|
||||||
// Try-with-resources ensures streams are automatically closed, avoid memory leaks
|
// Try-with-resources ensures streams are automatically closed, avoid memory leaks
|
||||||
try (InputStream in = getAssets().open(assetName);
|
try (InputStream in = getAssets().open(assetName);
|
||||||
OutputStream out = new FileOutputStream(destFile)) {
|
OutputStream out = new FileOutputStream(destFile)) {
|
||||||
|
|
||||||
byte[] buffer = new byte[1024];
|
byte[] buffer = new byte[8192];
|
||||||
int read;
|
int read;
|
||||||
while ((read = in.read(buffer)) != -1) {
|
while ((read = in.read(buffer)) != -1) {
|
||||||
out.write(buffer, 0, read);
|
out.write(buffer, 0, read);
|
||||||
}
|
}
|
||||||
Log.d("MainActivity", "Succès : " + assetName + " copié.");
|
Log.d("MainActivity", "Success : " + assetName + " copied.");
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
Log.e("MainActivity", "Erreur copie asset: " + assetName, e);
|
Log.e("MainActivity", "Can't copy asset: " + assetName, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -355,7 +420,7 @@ public class MainActivity extends AppCompatActivity {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Log.e(TAG, "Erreur IP", e);
|
Log.e(TAG, "IP error", e);
|
||||||
}
|
}
|
||||||
return "127.0.0.1";
|
return "127.0.0.1";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,12 +42,6 @@
|
|||||||
android:visibility="gone"
|
android:visibility="gone"
|
||||||
android:padding="10dp">
|
android:padding="10dp">
|
||||||
|
|
||||||
<Button
|
|
||||||
android:id="@+id/backToHomeBtn"
|
|
||||||
android:layout_width="wrap_content"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:text="← Retour" />
|
|
||||||
|
|
||||||
<ScrollView
|
<ScrollView
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
android:layout_height="match_parent">
|
android:layout_height="match_parent">
|
||||||
|
|||||||
@@ -3,8 +3,9 @@
|
|||||||
|
|
||||||
<string name="cart_name">Mes sacoches</string>
|
<string name="cart_name">Mes sacoches</string>
|
||||||
<string name="cart_validate_btn">Valider</string>
|
<string name="cart_validate_btn">Valider</string>
|
||||||
|
<string name="cart_back_btn">Retour</string>
|
||||||
<string name="cart_empty_btn">Vider</string>
|
<string name="cart_empty_btn">Vider</string>
|
||||||
<string name="cart_empty">Sacoches vides</string>
|
<string name="cart_empty">C\'est vide !</string>
|
||||||
<string name="cart_item">Quantité : %1$d (%2$d - %3$d €)</string>
|
<string name="cart_item">Quantité : %1$d (%2$d - %3$d €)</string>
|
||||||
|
|
||||||
<string name="currency">€</string>
|
<string name="currency">€</string>
|
||||||
@@ -13,6 +14,6 @@
|
|||||||
<string name="popup_name">Mes sacoches</string>
|
<string name="popup_name">Mes sacoches</string>
|
||||||
<string name="popup_item"><![CDATA[<b>%1$d x %2$s</b> : %3$d - %4$d €<br>]]></string>
|
<string name="popup_item"><![CDATA[<b>%1$d x %2$s</b> : %3$d - %4$d €<br>]]></string>
|
||||||
<string name="popup_total"><![CDATA[<br><b>Contribution consciente dans la petite boîte : %1$d - %2$d €</b>]]></string>
|
<string name="popup_total"><![CDATA[<br><b>Contribution consciente dans la petite boîte : %1$d - %2$d €</b>]]></string>
|
||||||
<string name="popup_end">Sacoches sauvegardées, merci !</string>
|
<string name="popup_end">Sacoches sauvegardées, merci ! ❤️</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
Reference in New Issue
Block a user