3 Commits

5 changed files with 184 additions and 103 deletions

View File

@@ -10,8 +10,8 @@ android {
applicationId "com.stock.pignon"
minSdkVersion 17
targetSdkVersion 36
versionCode 3
versionName "0.3.0"
versionCode 4
versionName "0.4.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

View File

@@ -22,9 +22,8 @@ import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Action on shopping cart: validation, clearing, and persistence
@@ -33,6 +32,21 @@ public class 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
*/
@@ -90,6 +104,74 @@ public class CartActionHelper {
.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.OUPUT_JSON_NAME);
File csvFile = new File(dir, Config.OUPUT_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.
*/
@@ -101,87 +183,21 @@ public class CartActionHelper {
.create();
merciDialog.show();
new Handler().postDelayed(() -> {
// Close dialog
merciDialog.dismiss();
// Go to home if not already
if (!(activity instanceof MainActivity)) {
Intent intent = new Intent(activity, MainActivity.class);
if (activity instanceof MainActivity) {
MainActivity main = (MainActivity) activity;
// Go to home if not already
main.showHome();
// 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);
activity.startActivity(intent);
GridLayout grid = main.findViewById(R.id.gridPieces);
refreshGridQuantities(grid);
}
}, 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.
*/

View 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());
}
}

View File

@@ -85,6 +85,14 @@ public class MainActivity extends AppCompatActivity {
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
server = new ControlServer(8080);
try {
@@ -93,12 +101,12 @@ public class MainActivity extends AppCompatActivity {
// On met l'URL directement dans le sous-titre de l'ActionBar
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) {
if (getSupportActionBar() != null) {
getSupportActionBar().setSubtitle("🔴 Erreur serveur : Port 8080 occupé");
getSupportActionBar().setSubtitle("Erreur serveur" + " - " + versionName);
}
}
}
@@ -115,7 +123,7 @@ public class MainActivity extends AppCompatActivity {
super.onDestroy();
if (server != null) {
server.stop();
Log.i(TAG, "Serveur arrêté.");
Log.i(TAG, "Server stopped.");
}
}
@@ -258,7 +266,7 @@ public class MainActivity extends AppCompatActivity {
CartViewHelper.updateCartView(cartList, this);
}
private void showHome() {
public void showHome() {
categoryItemsLayout.setVisibility(View.GONE);
homeLayout.setVisibility(View.VISIBLE);
}
@@ -268,8 +276,6 @@ public class MainActivity extends AppCompatActivity {
ImageLoader.loadImage(mainImage, "_velo", 800,800);
}
// --- Button Actions (linked via android:onClick in XML) ---
public void emptyCart(View view) {
CartActionHelper.emptyCart(cartList, this);
}
@@ -283,24 +289,65 @@ public class MainActivity extends AppCompatActivity {
}
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 ?
if (!folder.exists()) {
// Second safety : are we able to create folder ?
if (folder.mkdirs()) {
// Copy JSON file
copyFileFromAssets(Config.INPUT_JSON_NAME, new File(folder, Config.INPUT_JSON_NAME));
// Create root folder if not found
if (!rootDir.exists()) {
if (!rootDir.mkdirs()) {
Log.e("MainActivity", "Can't create root dir." + rootDir.getAbsolutePath());
return;
}
}
// 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.OUPUT_JSON_NAME), "[]");
checkOrCreateEmptyFile(new File(rootDir, Config.OUPUT_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) {
try {
String[] files = getAssets().list(assetDirName);
@@ -316,25 +363,28 @@ public class MainActivity extends AppCompatActivity {
}
}
} 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) {
// Optimized read
// Try-with-resources ensures streams are automatically closed, avoid memory leaks
try (InputStream in = getAssets().open(assetName);
OutputStream out = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
byte[] buffer = new byte[8192];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
Log.d("MainActivity", "Succès : " + assetName + " copié.");
Log.d("MainActivity", "Success : " + assetName + " copied.");
} catch (IOException e) {
Log.e("MainActivity", "Erreur copie asset: " + assetName, e);
Log.e("MainActivity", "Can't copy asset: " + assetName, e);
}
}
@@ -355,7 +405,7 @@ public class MainActivity extends AppCompatActivity {
}
}
} catch (Exception e) {
Log.e(TAG, "Erreur IP", e);
Log.e(TAG, "IP error", e);
}
return "127.0.0.1";
}

View File

@@ -4,7 +4,7 @@
<string name="cart_name">Mes sacoches</string>
<string name="cart_validate_btn">Valider</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="currency"></string>
@@ -13,6 +13,6 @@
<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_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>