win-superpower / services.js
Ultronprime's picture
Update services.js
e2f2b65 verified
// 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();
}