File size: 2,803 Bytes
e6e9d7a
 
bc9010f
e6e9d7a
bc9010f
e6e9d7a
 
 
 
 
 
bc9010f
e6e9d7a
 
 
 
 
 
 
 
 
bc9010f
 
e6e9d7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc9010f
 
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// state.js - Manages Application State with Supabase
import { supabase } from './supabaseClient.js';
import { MATERIALS_CONFIG, RECIPES_CONFIG } from './config.js';
import { showToast } from './ui.js';

export let appState = {
    user: null, // To store the logged-in user
    materials: [],
    productRecipes: RECIPES_CONFIG,
    productionLog: []
};

// Helper function to convert database material format to app format
function dbMaterialToAppMaterial(dbMaterial) {
    return {
        id: dbMaterial.id,
        name: dbMaterial.name,
        unit: dbMaterial.unit,
        currentStock: dbMaterial.current_stock,
        reorderPoint: dbMaterial.reorder_point
    };
}

// Function to load initial application state from Supabase
export async function loadInitialAppState() {
    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) throw new Error("User not authenticated.");
        appState.user = user;

        const { data: materials, error: materialsError } = await supabase
            .from('materials')
            .select('*')
            .order('name', { ascending: true });
        if (materialsError) throw materialsError;

        const { data: productionLog, error: logError } = await supabase
            .from('production_log')
            .select('*')
            .order('produced_at', { ascending: false })
            .limit(100); // Get latest 100 logs
        if (logError) throw logError;

        // If no materials in DB, initialize from config (first time setup)
        if (materials.length === 0 && MATERIALS_CONFIG.length > 0) {
            showToast('No materials found. Initializing from config...', 'info');
            const { data: insertedMaterials, error: insertError } = await supabase
                .from('materials')
                .insert(MATERIALS_CONFIG.map(m => ({
                    name: m.name,
                    unit: m.unit,
                    current_stock: m.currentStock,
                    reorder_point: m.reorderPoint
                })))
                .select();

            if (insertError) throw insertError;
            appState.materials = insertedMaterials.map(dbMaterialToAppMaterial);
        } else {
            appState.materials = materials.map(dbMaterialToAppMaterial);
        }

        appState.productionLog = productionLog.map(log => ({
            id: log.id,
            productName: log.product_name,
            quantity: log.quantity,
            date: log.produced_at
        }));
        
        console.log('App state loaded successfully from Supabase.');
        return true;
    } catch (error) {
        console.error('Error loading app state:', error.message);
        showToast(`Failed to load data: ${error.message}`, 'error');
        return false;
    }
}