File size: 2,073 Bytes
8204e2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2f2b65
 
 
 
 
 
8204e2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// services.js - Core Business Logic

import { appState, saveState } from './state.js';
import { refreshUI, showToast } from './ui.js';

export function handleUpdateStock(productName, quantity) {
    if (isNaN(quantity) || quantity <= 0) return;
    const recipe = appState.productRecipes[productName];
    if (!recipe) { showToast(`Error: No recipe found for ${productName}.`, 'error'); return; }

    for (const materialName in recipe) {
        const required = recipe[materialName] * quantity;
        const material = appState.materials.find(m => m.name === materialName);
        if (!material || material.currentStock < required) {
            showToast(`Insufficient materials for ${quantity}x ${productName}.`, 'error');
            return;
        }
    }

    for (const materialName in recipe) {
        const required = recipe[materialName] * quantity;
        appState.materials.find(m => m.name === materialName).currentStock -= required;
    }
    
    appState.productionLog.push({ productName, quantity, date: new Date().toISOString() });
    
    saveState();
    refreshUI();
    showToast(`Produced ${quantity}x ${productName}.`, 'success');
    
    document.querySelectorAll('.dashboard-card').forEach(card => {
        const h3 = card.querySelector('h3');
        if (h3 && h3.textContent === productName) {
            card.querySelector('input').value = '0';
        }
    });
}

export function handleRestock(materialName, quantity) {
    if (isNaN(quantity) || quantity <= 0) return;
    const material = appState.materials.find(m => m.name === materialName);
    if (!material) return;
    
    const oldStock = material.currentStock;
    let newStock = oldStock + quantity;

    if (newStock > material.maxStock) {
        newStock = material.maxStock;
        showToast(`Stock for ${materialName} is full. Added ${newStock - oldStock} units.`, 'info');
    } else {
        showToast(`Restocked ${quantity} ${material.unit} of ${materialName}.`, 'success');
    }
    
    material.currentStock = newStock;
    saveState();
    refreshUI();
}