feat: predict expiry date from product history when adding items
- PHP: new 'expiry_history' action computes avg shelf life (expiry_date - added_at)
from inventory table for the same product_id (last 730 days, valid entries only)
- JS: _fetchExpiryHistoryAndUpdate() fires async after showAddForm() renders
and replaces the rule-based estimate with the historical average if available
- Labeled with '📊 storico' badge on the estimate line (tooltip shows sample count)
- recalculateAddExpiry() and selectPurchaseType('new') both honour window._historyExpiryDays
- Vacuum-sealed multiplier still applied on top of historical base
- Falls back silently to rule-based estimateExpiryDays when no history exists
This commit is contained in:
@@ -194,6 +194,10 @@ try {
|
||||
ttsProxy();
|
||||
break;
|
||||
|
||||
case 'expiry_history':
|
||||
getExpiryHistory($db);
|
||||
break;
|
||||
|
||||
default:
|
||||
http_response_code(404);
|
||||
echo json_encode(['error' => 'Unknown action: ' . $action]);
|
||||
@@ -255,6 +259,36 @@ function ttsProxy() {
|
||||
|
||||
// ===== CLIENT LOG =====
|
||||
|
||||
// ===== EXPIRY HISTORY =====
|
||||
function getExpiryHistory($db): void {
|
||||
$productId = (int)($_GET['product_id'] ?? $_POST['product_id'] ?? 0);
|
||||
if (!$productId) {
|
||||
echo json_encode(['avg_days' => null, 'count' => 0]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Compute average shelf life (expiry_date - added_at) for this product
|
||||
// Only use entries where expiry_date is clearly in the future relative to added_at
|
||||
$stmt = $db->prepare("
|
||||
SELECT ROUND(AVG(CAST(JULIANDAY(expiry_date) - JULIANDAY(added_at) AS REAL))) AS avg_days,
|
||||
COUNT(*) AS count
|
||||
FROM inventory
|
||||
WHERE product_id = ?
|
||||
AND expiry_date IS NOT NULL
|
||||
AND expiry_date > date(added_at)
|
||||
AND added_at >= date('now', '-730 days')
|
||||
");
|
||||
$stmt->execute([$productId]);
|
||||
$row = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$row || !$row['count'] || $row['avg_days'] === null) {
|
||||
echo json_encode(['avg_days' => null, 'count' => 0]);
|
||||
return;
|
||||
}
|
||||
|
||||
echo json_encode(['avg_days' => (int)$row['avg_days'], 'count' => (int)$row['count']]);
|
||||
}
|
||||
|
||||
function clientLog(): void {
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$logFile = __DIR__ . '/../data/client_debug.log';
|
||||
|
||||
Reference in New Issue
Block a user