Spaces:
Running
Running
Create services.js
Browse files- services.js +56 -0
services.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// services.js - Core Business Logic
|
| 2 |
+
|
| 3 |
+
import { appState, saveState } from './state.js';
|
| 4 |
+
import { refreshUI, showToast } from './ui.js';
|
| 5 |
+
|
| 6 |
+
export function handleUpdateStock(productName, quantity) {
|
| 7 |
+
if (isNaN(quantity) || quantity <= 0) return;
|
| 8 |
+
const recipe = appState.productRecipes[productName];
|
| 9 |
+
if (!recipe) { showToast(`Error: No recipe found for ${productName}.`, 'error'); return; }
|
| 10 |
+
|
| 11 |
+
// Check if there are enough materials
|
| 12 |
+
for (const materialName in recipe) {
|
| 13 |
+
const required = recipe[materialName] * quantity;
|
| 14 |
+
const material = appState.materials.find(m => m.name === materialName);
|
| 15 |
+
if (!material || material.currentStock < required) {
|
| 16 |
+
showToast(`Insufficient materials for ${quantity}x ${productName}.`, 'error');
|
| 17 |
+
return;
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
// Deduct materials
|
| 22 |
+
for (const materialName in recipe) {
|
| 23 |
+
const required = recipe[materialName] * quantity;
|
| 24 |
+
appState.materials.find(m => m.name === materialName).currentStock -= required;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
appState.productionLog.push({ productName, quantity, date: new Date().toISOString() });
|
| 28 |
+
|
| 29 |
+
saveState();
|
| 30 |
+
refreshUI();
|
| 31 |
+
showToast(`Produced ${quantity}x ${productName}.`, 'success');
|
| 32 |
+
|
| 33 |
+
// Clear input field after production
|
| 34 |
+
const productCard = document.querySelector(`.product-card[data-product-name="${productName}"]`);
|
| 35 |
+
if(productCard) productCard.querySelector('input').value = '0';
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
export function handleRestock(materialName, quantity) {
|
| 39 |
+
if (isNaN(quantity) || quantity <= 0) return;
|
| 40 |
+
const material = appState.materials.find(m => m.name === materialName);
|
| 41 |
+
if (!material) return;
|
| 42 |
+
|
| 43 |
+
const oldStock = material.currentStock;
|
| 44 |
+
let newStock = oldStock + quantity;
|
| 45 |
+
|
| 46 |
+
if (newStock > material.maxStock) {
|
| 47 |
+
newStock = material.maxStock;
|
| 48 |
+
showToast(`Stock for ${materialName} is full. Added ${newStock - oldStock} units.`, 'info');
|
| 49 |
+
} else {
|
| 50 |
+
showToast(`Restocked ${quantity} ${material.unit} of ${materialName}.`, 'success');
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
material.currentStock = newStock;
|
| 54 |
+
saveState();
|
| 55 |
+
refreshUI();
|
| 56 |
+
}
|