-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1758 lines (1528 loc) · 55.7 KB
/
app.js
File metadata and controls
1758 lines (1528 loc) · 55.7 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// StreetBridge Application - Firebase v12 Modular SDK Implementation
// Import Firebase modules using CDN
import { initializeApp } from 'https://www.gstatic.com/firebasejs/12.0.0/firebase-app.js';
import {
getAuth,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signOut,
onAuthStateChanged,
browserLocalPersistence,
setPersistence
} from 'https://www.gstatic.com/firebasejs/12.0.0/firebase-auth.js';
import {
getFirestore,
collection,
doc,
addDoc,
setDoc,
updateDoc,
deleteDoc,
getDoc,
getDocs,
query,
where,
orderBy,
onSnapshot,
serverTimestamp
} from 'https://www.gstatic.com/firebasejs/12.0.0/firebase-firestore.js';
// Firebase Configuration
const firebaseConfig = {
apiKey: "AIzaSyD0bpIMwlWtejOnNLpE6oiWIIJrFzQyibE",
authDomain: "streetbridge-f7691.firebaseapp.com",
projectId: "streetbridge-f7691",
storageBucket: "streetbridge-f7691.firebasestorage.app",
messagingSenderId: "519880397736",
appId: "1:519880397736:web:54fa60ce7843a5e551c39d",
measurementId: "G-B6012C4B3M"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
// Set authentication persistence
setPersistence(auth, browserLocalPersistence);
// Application State
let currentUser = null;
let currentUserRole = null;
let currentChat = null;
let orderCart = [];
let unsubscribeChat = null;
let currentInvoiceData = null;
// Sample data for initialization
const SAMPLE_ITEMS = [
{
name: 'Fresh Tomatoes',
description: 'Fresh red tomatoes per kg',
price: 30,
category: 'Vegetables',
stock: 100,
available: true
},
{
name: 'Red Onions',
description: 'Premium red onions per kg',
price: 25,
category: 'Vegetables',
stock: 80,
available: true
},
{
name: 'Fresh Apples',
description: 'Premium fresh apples per kg',
price: 80,
category: 'Fruits',
stock: 60,
available: true
},
{
name: 'Paper Cups (100pc)',
description: 'Disposable paper cups pack',
price: 75,
category: 'Packaging',
stock: 50,
available: true
},
{
name: 'Gas Cylinder (5kg)',
description: 'Cooking gas cylinder',
price: 750,
category: 'Gas Cylinders',
stock: 25,
available: true
}
];
// Categories
const CATEGORIES = [
"Vegetables",
"Fruits",
"Packaging",
"Gas Cylinders",
"Paper Products",
"Cleaning Supplies"
];
// Utility Functions
const $ = (id) => document.getElementById(id);
const showLoading = (show = true) => {
const overlay = $('loading-overlay');
if (overlay) overlay.classList.toggle('hidden', !show);
};
const showToast = (message, type = 'success') => {
const toast = $('toast');
const messageEl = $('toast-message');
if (toast && messageEl) {
messageEl.textContent = message;
toast.className = `toast ${type}`;
toast.classList.remove('hidden');
setTimeout(() => toast.classList.add('hidden'), 5000);
}
};
const formatCurrency = (amount) => `₹${Number(amount).toLocaleString('en-IN')}`;
const formatDate = (date) => {
if (!date) return 'N/A';
const dateObj = date.toDate ? date.toDate() : new Date(date);
return dateObj.toLocaleDateString('en-IN', {
year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'
});
};
const generateOrderNumber = () => 'SB' + Date.now().toString().slice(-8);
// UI Functions - Define early to avoid hoisting issues
const switchAuthTab = (tabId) => {
console.log('Switching auth tab to:', tabId);
// Remove active class from all tabs and forms
document.querySelectorAll('.auth-tab').forEach(tab => tab.classList.remove('active'));
document.querySelectorAll('.auth-form').forEach(form => form.classList.remove('active'));
// Add active class to clicked tab
const tabButton = document.querySelector(`[data-tab="${tabId}"]`);
if (tabButton) {
tabButton.classList.add('active');
console.log('Tab button activated:', tabButton);
}
// Show corresponding form
const tabContent = document.getElementById(`${tabId}-form`);
if (tabContent) {
tabContent.classList.add('active');
console.log('Tab content shown:', tabContent);
}
};
const switchTab = (tabId) => {
console.log('Switching dashboard tab to:', tabId, 'for role:', currentUserRole);
if (currentUserRole === 'vendor') {
document.querySelectorAll('#vendor-dashboard .nav-tab').forEach(tab => tab.classList.remove('active'));
document.querySelectorAll('#vendor-dashboard .tab-content').forEach(content => content.classList.remove('active'));
const tabButton = document.querySelector(`#vendor-dashboard [data-tab="${tabId}"]`);
const tabContent = document.getElementById(tabId);
if (tabButton) tabButton.classList.add('active');
if (tabContent) tabContent.classList.add('active');
}
if (currentUserRole === 'supplier') {
document.querySelectorAll('#supplier-dashboard .nav-tab').forEach(tab => tab.classList.remove('active'));
document.querySelectorAll('#supplier-dashboard .tab-content').forEach(content => content.classList.remove('active'));
const tabButton = document.querySelector(`#supplier-dashboard [data-tab="${tabId}"]`);
const tabContent = document.getElementById(tabId);
if (tabButton) tabButton.classList.add('active');
if (tabContent) tabContent.classList.add('active');
}
};
// Authentication Functions
const setupAuthStateListener = () => {
onAuthStateChanged(auth, async (user) => {
console.log('Auth state changed:', user ? 'User logged in' : 'User logged out');
showLoading(true);
if (user) {
currentUser = user;
try {
const userDoc = await getDoc(doc(db, 'users', user.uid));
if (userDoc.exists()) {
const userData = userDoc.data();
currentUserRole = userData.role;
console.log('User role:', currentUserRole);
$('landing-page').classList.add('hidden');
if (currentUserRole === 'vendor') {
$('vendor-dashboard').classList.remove('hidden');
const userNameEl = $('user-name');
if (userNameEl) userNameEl.textContent = userData.name || user.email;
await initializeVendorDashboard();
} else if (currentUserRole === 'supplier') {
$('supplier-dashboard').classList.remove('hidden');
const supplierUserNameEl = $('supplier-user-name');
if (supplierUserNameEl) supplierUserNameEl.textContent = userData.name || user.email;
await initializeSupplierDashboard();
}
} else {
console.error('User profile not found');
await signOut(auth);
}
} catch (error) {
console.error('Error getting user profile:', error);
showToast('Error loading user profile', 'error');
await signOut(auth);
}
} else {
currentUser = null;
currentUserRole = null;
$('landing-page').classList.remove('hidden');
$('vendor-dashboard').classList.add('hidden');
$('supplier-dashboard').classList.add('hidden');
}
showLoading(false);
});
};
const handleLogin = async (email, password) => {
console.log('Attempting login for:', email);
try {
showLoading(true);
await signInWithEmailAndPassword(auth, email, password);
showToast('Login successful!', 'success');
} catch (error) {
console.error('Login error:', error);
let errorMessage = 'Login failed';
const errorMessages = {
'auth/invalid-login-credentials': 'Invalid email or password. Please try again.',
'auth/user-not-found': 'Invalid email or password. Please try again.',
'auth/wrong-password': 'Invalid email or password. Please try again.',
'auth/invalid-email': 'Please enter a valid email address.',
'auth/too-many-requests': 'Too many failed attempts. Please try again later.',
'auth/network-request-failed': 'Network error. Please check your connection.',
'auth/user-disabled': 'This account has been disabled.'
};
errorMessage = errorMessages[error.code] || error.message;
showToast(errorMessage, 'error');
} finally {
showLoading(false);
}
};
const handleSignup = async (email, password, name, role, businessType = '') => {
console.log('Attempting signup for:', email, 'as', role);
try {
showLoading(true);
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
const user = userCredential.user;
const userData = {
uid: user.uid,
email: email,
name: name,
role: role,
createdAt: serverTimestamp(),
lastLogin: serverTimestamp()
};
if (role === 'vendor') {
userData.businessType = businessType;
} else if (role === 'supplier') {
userData.category = businessType;
}
await setDoc(doc(db, 'users', user.uid), userData);
// Initialize sample items for suppliers
if (role === 'supplier') {
await initializeSampleItems(user.uid);
}
showToast('Account created successfully!', 'success');
} catch (error) {
console.error('Signup error:', error);
let errorMessage = 'Account creation failed';
const errorMessages = {
'auth/email-already-in-use': 'This email is already registered.',
'auth/weak-password': 'Password should be at least 6 characters.',
'auth/invalid-email': 'Please enter a valid email address.',
'auth/network-request-failed': 'Network error. Please check your connection.'
};
errorMessage = errorMessages[error.code] || error.message;
showToast(errorMessage, 'error');
} finally {
showLoading(false);
}
};
const initializeSampleItems = async (supplierId) => {
try {
for (const item of SAMPLE_ITEMS) {
await addDoc(collection(db, 'items'), {
...item,
supplierId: supplierId,
createdAt: serverTimestamp()
});
}
console.log('Sample items initialized successfully');
} catch (error) {
console.error('Error initializing sample items:', error);
}
};
// Vendor Dashboard Functions
const initializeVendorDashboard = async () => {
console.log('Initializing vendor dashboard');
await loadAllItems();
await loadVendorOrders();
setupVendorChat();
setupSearchAndFilter();
};
const loadAllItems = async () => {
try {
const itemsGrid = $('suppliers-grid');
if (!itemsGrid) return;
itemsGrid.innerHTML = '<div class="skeleton skeleton-text"></div>'.repeat(6);
const itemsSnapshot = await getDocs(query(
collection(db, 'items'),
where('available', '==', true)
));
if (itemsSnapshot.empty) {
itemsGrid.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📦</div>
<h3>No Items Available</h3>
<p>No suppliers have added items yet. Check back later!</p>
</div>
`;
return;
}
// Group items by supplier
const supplierItems = {};
const supplierIds = new Set();
itemsSnapshot.docs.forEach(docSnapshot => {
const itemData = { id: docSnapshot.id, ...docSnapshot.data() };
const supplierId = itemData.supplierId;
if (!supplierItems[supplierId]) {
supplierItems[supplierId] = [];
}
supplierItems[supplierId].push(itemData);
supplierIds.add(supplierId);
});
// Get supplier details
const suppliers = [];
for (const supplierId of supplierIds) {
try {
const supplierDoc = await getDoc(doc(db, 'users', supplierId));
if (supplierDoc.exists()) {
const supplierData = supplierDoc.data();
suppliers.push({
id: supplierId,
...supplierData,
items: supplierItems[supplierId] || []
});
}
} catch (error) {
console.error('Error loading supplier:', supplierId, error);
}
}
renderItemsGrid(suppliers);
} catch (error) {
console.error('Error loading items:', error);
showToast('Error loading items', 'error');
const itemsGrid = $('suppliers-grid');
if (itemsGrid) {
itemsGrid.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">⚠️</div>
<h3>Unable to Load Items</h3>
<p>There was an error loading items. Please refresh the page or try again later.</p>
</div>
`;
}
}
};
const renderItemsGrid = (suppliers) => {
const itemsGrid = $('suppliers-grid');
if (!itemsGrid) return;
if (suppliers.length === 0) {
itemsGrid.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">🏪</div>
<h3>No Suppliers Found</h3>
<p>No suppliers with available items at the moment.</p>
</div>
`;
return;
}
itemsGrid.innerHTML = suppliers.map(supplier => `
<div class="supplier-card" data-supplier-id="${supplier.id}">
<div class="supplier-header">
<div class="supplier-info">
<h3>${supplier.name || 'Unknown Supplier'}</h3>
<div class="supplier-category">${supplier.category || 'General Supplier'}</div>
<div class="supplier-contact">${supplier.email || ''}</div>
</div>
</div>
<div class="supplier-products">
<h4>Available Items (${supplier.items.length})</h4>
<div class="product-list">
${supplier.items.slice(0, 5).map(item => `
<div class="product-item" data-product-id="${item.id}" data-category="${item.category || ''}">
<div class="product-name">${item.name}</div>
<div class="product-price">${formatCurrency(item.price || 0)}</div>
<div class="product-actions">
<input type="number" class="quantity-input" min="1" max="${item.stock || 999}" value="1" data-product-id="${item.id}">
<button class="add-to-cart" data-supplier-id="${supplier.id}" data-item-id="${item.id}" data-item-name="${item.name}" data-item-price="${item.price || 0}" data-item-stock="${item.stock || 999}">
Add
</button>
</div>
</div>
`).join('')}
${supplier.items.length > 5 ? `
<div class="product-item">
<span class="product-name">+ ${supplier.items.length - 5} more items</span>
<button class="btn btn--outline btn--sm view-all-items" data-supplier-id="${supplier.id}" data-supplier-name="${supplier.name || 'Supplier'}">
View All
</button>
</div>
` : ''}
</div>
</div>
<div class="supplier-actions">
<button class="btn btn--outline btn--sm start-chat-btn" data-supplier-id="${supplier.id}" data-supplier-name="${supplier.name || 'Supplier'}">
💬 Chat
</button>
<button class="btn btn--primary btn--sm view-all-items" data-supplier-id="${supplier.id}" data-supplier-name="${supplier.name || 'Supplier'}">
🛒 Order Items
</button>
</div>
</div>
`).join('');
// Add event listeners for dynamic buttons
setupDynamicEventListeners();
};
const setupDynamicEventListeners = () => {
// Add to cart buttons
document.querySelectorAll('.add-to-cart').forEach(button => {
button.addEventListener('click', (e) => {
const supplierId = e.target.dataset.supplierId;
const itemId = e.target.dataset.itemId;
const itemName = e.target.dataset.itemName;
const itemPrice = parseFloat(e.target.dataset.itemPrice);
const itemStock = parseInt(e.target.dataset.itemStock);
addToCart(supplierId, itemId, itemName, itemPrice, itemStock);
});
});
// View all items buttons
document.querySelectorAll('.view-all-items').forEach(button => {
button.addEventListener('click', (e) => {
const supplierId = e.target.dataset.supplierId;
const supplierName = e.target.dataset.supplierName;
viewAllSupplierItems(supplierId, supplierName);
});
});
// Start chat buttons
document.querySelectorAll('.start-chat-btn').forEach(button => {
button.addEventListener('click', (e) => {
const supplierId = e.target.dataset.supplierId;
const supplierName = e.target.dataset.supplierName;
startChat(supplierId, supplierName);
});
});
};
const setupSearchAndFilter = () => {
const searchInput = $('supplier-search');
const categoryFilter = $('category-filter');
if (searchInput) {
searchInput.addEventListener('input', filterItems);
}
if (categoryFilter) {
categoryFilter.addEventListener('change', filterItems);
}
};
const filterItems = () => {
const searchTerm = $('supplier-search')?.value.toLowerCase() || '';
const selectedCategory = $('category-filter')?.value || '';
const supplierCards = document.querySelectorAll('.supplier-card');
supplierCards.forEach(card => {
const supplierName = card.querySelector('.supplier-info h3')?.textContent.toLowerCase() || '';
const productItems = card.querySelectorAll('.product-item');
let hasMatchingItems = false;
productItems.forEach(product => {
const productName = product.querySelector('.product-name')?.textContent.toLowerCase() || '';
const productCategory = product.dataset.category || '';
const matchesSearch = !searchTerm || productName.includes(searchTerm) || supplierName.includes(searchTerm);
const matchesCategory = !selectedCategory || productCategory === selectedCategory;
if (matchesSearch && matchesCategory) {
product.style.display = 'flex';
hasMatchingItems = true;
} else {
product.style.display = 'none';
}
});
card.style.display = hasMatchingItems ? 'block' : 'none';
});
};
const addToCart = (supplierId, itemId, itemName, price, stock) => {
const quantityInput = document.querySelector(`input[data-product-id="${itemId}"]`);
const quantity = parseInt(quantityInput?.value) || 1;
if (quantity > stock) {
showToast(`Only ${stock} items available in stock`, 'warning');
if (quantityInput) quantityInput.value = stock;
return;
}
let supplierCart = orderCart.find(item => item.supplierId === supplierId);
if (!supplierCart) {
supplierCart = { supplierId: supplierId, items: [] };
orderCart.push(supplierCart);
}
const existingItem = supplierCart.items.find(p => p.itemId === itemId);
if (existingItem) {
const newQuantity = existingItem.quantity + quantity;
if (newQuantity > stock) {
showToast(`Cannot add more. Stock limit: ${stock}`, 'warning');
return;
}
existingItem.quantity = newQuantity;
} else {
supplierCart.items.push({
itemId: itemId,
name: itemName,
price: price,
quantity: quantity,
stock: stock
});
}
if (quantityInput) quantityInput.value = 1;
showToast(`Added ${quantity} ${itemName} to cart`, 'success');
};
const viewAllSupplierItems = async (supplierId, supplierName) => {
try {
const itemsSnapshot = await getDocs(query(
collection(db, 'items'),
where('supplierId', '==', supplierId),
where('available', '==', true)
));
const items = itemsSnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
showOrderModal(supplierId, supplierName, items);
} catch (error) {
console.error('Error loading supplier items:', error);
showToast('Error loading items', 'error');
}
};
const showOrderModal = async (supplierId, supplierName, items = []) => {
const modal = $('order-modal');
const supplierInfo = $('order-supplier-info');
const orderItems = $('order-items');
if (!modal || !supplierInfo || !orderItems) return;
try {
const supplierDoc = await getDoc(doc(db, 'users', supplierId));
const supplierData = supplierDoc.exists() ? supplierDoc.data() : {};
supplierInfo.innerHTML = `
<h4>${supplierName}</h4>
<p><strong>Category:</strong> ${supplierData.category || 'General'}</p>
<p><strong>Contact:</strong> ${supplierData.email || 'N/A'}</p>
`;
if (items.length === 0) {
const itemsSnapshot = await getDocs(query(
collection(db, 'items'),
where('supplierId', '==', supplierId),
where('available', '==', true)
));
items = itemsSnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
}
const supplierCart = orderCart.find(item => item.supplierId === supplierId);
orderItems.innerHTML = `
<h5>Available Items:</h5>
<div class="order-items-grid">
${items.map(item => {
const cartItem = supplierCart?.items.find(p => p.itemId === item.id);
const quantity = cartItem?.quantity || 0;
return `
<div class="order-item-card">
<div class="item-info">
<div class="item-name">${item.name}</div>
<div class="item-description">${item.description || ''}</div>
<div class="item-price">${formatCurrency(item.price || 0)}</div>
<div class="item-stock">Stock: ${item.stock || 0}</div>
</div>
<div class="item-quantity-controls">
<label>Quantity:</label>
<input type="number" class="quantity-input order-quantity-input" min="0" max="${item.stock || 999}" value="${quantity}"
data-supplier-id="${supplierId}" data-item-id="${item.id}" data-item-name="${item.name}" data-item-price="${item.price || 0}" data-item-stock="${item.stock || 999}">
</div>
</div>
`;
}).join('')}
</div>
`;
// Add event listeners for quantity inputs
document.querySelectorAll('.order-quantity-input').forEach(input => {
input.addEventListener('change', (e) => {
const supplierId = e.target.dataset.supplierId;
const itemId = e.target.dataset.itemId;
const itemName = e.target.dataset.itemName;
const itemPrice = parseFloat(e.target.dataset.itemPrice);
const itemStock = parseInt(e.target.dataset.itemStock);
const quantity = e.target.value;
updateOrderQuantity(supplierId, itemId, itemName, itemPrice, itemStock, quantity);
});
});
updateOrderTotal();
modal.classList.remove('hidden');
} catch (error) {
console.error('Error loading supplier details:', error);
showToast('Error loading supplier details', 'error');
}
};
const updateOrderQuantity = (supplierId, itemId, itemName, price, stock, quantity) => {
quantity = parseInt(quantity) || 0;
if (quantity > stock) {
showToast(`Only ${stock} items available`, 'warning');
const input = document.querySelector(`input[data-item-id="${itemId}"]`);
if (input) input.value = stock;
quantity = stock;
}
let supplierCart = orderCart.find(item => item.supplierId === supplierId);
if (!supplierCart && quantity > 0) {
supplierCart = { supplierId: supplierId, items: [] };
orderCart.push(supplierCart);
}
if (supplierCart) {
const existingItem = supplierCart.items.find(p => p.itemId === itemId);
if (quantity > 0) {
if (existingItem) {
existingItem.quantity = quantity;
} else {
supplierCart.items.push({
itemId: itemId,
name: itemName,
price: price,
quantity: quantity,
stock: stock
});
}
} else if (existingItem) {
supplierCart.items = supplierCart.items.filter(p => p.itemId !== itemId);
}
if (supplierCart.items.length === 0) {
orderCart = orderCart.filter(item => item.supplierId !== supplierId);
}
}
updateOrderTotal();
};
const updateOrderTotal = () => {
const supplierCart = orderCart.find(item => item.items && item.items.length > 0);
if (!supplierCart) {
$('order-subtotal').textContent = formatCurrency(0);
$('order-tax').textContent = formatCurrency(0);
$('order-total-amount').textContent = formatCurrency(0);
return;
}
const subtotal = supplierCart.items.reduce((sum, item) =>
sum + ((item.price || 0) * (item.quantity || 0)), 0
);
const tax = subtotal * 0.10;
const total = subtotal + tax;
$('order-subtotal').textContent = formatCurrency(subtotal);
$('order-tax').textContent = formatCurrency(tax);
$('order-total-amount').textContent = formatCurrency(total);
};
const confirmOrder = async () => {
try {
showLoading(true);
const activeSupplierCart = orderCart.find(item => item.items && item.items.length > 0);
if (!activeSupplierCart) {
showToast('Please add items to your order', 'warning');
showLoading(false);
return;
}
const subtotal = activeSupplierCart.items.reduce((sum, item) =>
sum + ((item.price || 0) * (item.quantity || 0)), 0
);
const tax = subtotal * 0.10;
const total = subtotal + tax;
const orderData = {
vendorId: currentUser.uid,
supplierId: activeSupplierCart.supplierId,
items: activeSupplierCart.items,
subtotal: subtotal,
tax: tax,
total: total,
status: 'pending',
createdAt: serverTimestamp(),
orderNumber: generateOrderNumber()
};
const docRef = await addDoc(collection(db, 'orders'), orderData);
// Update stock levels
for (const item of activeSupplierCart.items) {
try {
const itemDoc = await getDoc(doc(db, 'items', item.itemId));
if (itemDoc.exists()) {
const currentStock = itemDoc.data().stock || 0;
await updateDoc(doc(db, 'items', item.itemId), {
stock: Math.max(0, currentStock - (item.quantity || 0))
});
}
} catch (error) {
console.error('Error updating stock for item:', item.itemId, error);
}
}
// Clear cart for this supplier
orderCart = orderCart.filter(item => item.supplierId !== activeSupplierCart.supplierId);
$('order-modal').classList.add('hidden');
showToast('Order placed successfully!', 'success');
await loadVendorOrders();
await loadAllItems();
// Show invoice option
setTimeout(() => {
if (confirm('Order placed successfully! Would you like to download the invoice?')) {
generateInvoicePDF(docRef.id, { ...orderData, id: docRef.id });
}
}, 1000);
} catch (error) {
console.error('Error placing order:', error);
showToast('Error placing order', 'error');
} finally {
showLoading(false);
}
};
const loadVendorOrders = async () => {
try {
const ordersList = $('vendor-orders-list');
if (!ordersList) return;
ordersList.innerHTML = '<div class="skeleton skeleton-text"></div>'.repeat(3);
const ordersSnapshot = await getDocs(query(
collection(db, 'orders'),
where('vendorId', '==', currentUser.uid)
));
if (ordersSnapshot.empty) {
ordersList.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📋</div>
<h3>No Orders Yet</h3>
<p>Your orders will appear here once you place them with suppliers.</p>
</div>
`;
return;
}
const orders = [];
for (const docSnapshot of ordersSnapshot.docs) {
const orderData = docSnapshot.data();
try {
const supplierDoc = await getDoc(doc(db, 'users', orderData.supplierId));
const supplierName = supplierDoc.exists() ? supplierDoc.data().name : 'Unknown Supplier';
orders.push({
id: docSnapshot.id,
...orderData,
supplierName
});
} catch (error) {
console.error('Error loading supplier for order:', docSnapshot.id, error);
orders.push({
id: docSnapshot.id,
...orderData,
supplierName: 'Unknown Supplier'
});
}
}
// Sort orders by creation date (newest first)
orders.sort((a, b) => {
const dateA = a.createdAt?.toDate ? a.createdAt.toDate() : new Date(0);
const dateB = b.createdAt?.toDate ? b.createdAt.toDate() : new Date(0);
return dateB - dateA;
});
ordersList.innerHTML = orders.map(order => `
<div class="order-card">
<div class="order-header">
<div class="order-info">
<h4>Order #${order.orderNumber || 'N/A'}</h4>
<div class="order-date">${formatDate(order.createdAt)}</div>
<div class="supplier-name"><strong>Supplier:</strong> ${order.supplierName}</div>
</div>
<div class="order-status ${order.status || 'pending'}">${(order.status || 'pending').toUpperCase()}</div>
</div>
<div class="order-items">
<h5>Items Ordered:</h5>
${(order.items || []).map(item => `
<div class="order-item">
<div class="item-details">
<div class="item-name">${item.name || 'Unknown Item'}</div>
<div class="item-quantity">Qty: ${item.quantity || 0}</div>
</div>
<div class="item-total">${formatCurrency((item.price || 0) * (item.quantity || 0))}</div>
</div>
`).join('')}
</div>
<div class="order-total">
<div class="total-row">
<span>Subtotal:</span>
<span>${formatCurrency(order.subtotal || 0)}</span>
</div>
<div class="total-row">
<span>Tax (10%):</span>
<span>${formatCurrency(order.tax || 0)}</span>
</div>
<div class="total-row total-final">
<span>Total:</span>
<span>${formatCurrency(order.total || 0)}</span>
</div>
</div>
<div class="order-actions">
<button class="btn invoice-download-btn invoice-btn" data-order-id="${order.id}" data-order-data='${JSON.stringify(order)}'>
📄 Download Invoice
</button>
<button class="btn btn--outline btn--sm start-chat-btn" data-supplier-id="${order.supplierId}" data-supplier-name="${order.supplierName}">
💬 Contact Supplier
</button>
</div>
</div>
`).join('');
// Add event listeners for invoice buttons
document.querySelectorAll('.invoice-btn').forEach(button => {
button.addEventListener('click', (e) => {
const orderId = e.target.dataset.orderId;
const orderData = JSON.parse(e.target.dataset.orderData);
generateInvoicePDF(orderId, orderData);
});
});
} catch (error) {
console.error('Error loading vendor orders:', error);
showToast('Error loading orders', 'error');
}
};
// Supplier Dashboard Functions
const initializeSupplierDashboard = async () => {
console.log('Initializing supplier dashboard');
await loadSupplierItems();
await loadSupplierOrders();
setupSupplierChat();
setupSupplierFilters();
};
const setupSupplierFilters = () => {
const categoryFilter = $('supplier-category-filter');
if (categoryFilter) {
categoryFilter.addEventListener('change', filterSupplierItems);
}
};
const filterSupplierItems = () => {
const selectedCategory = $('supplier-category-filter')?.value || '';
const itemCards = document.querySelectorAll('.product-card');
itemCards.forEach(card => {
const category = card.dataset.category || '';
if (!selectedCategory || category === selectedCategory) {
card.style.display = 'block';
} else {
card.style.display = 'none';
}
});
};
const loadSupplierItems = async () => {
try {
const itemsGrid = $('products-grid');
if (!itemsGrid || !currentUser) return;
itemsGrid.innerHTML = '<div class="skeleton skeleton-text"></div>'.repeat(6);
const itemsSnapshot = await getDocs(query(
collection(db, 'items'),
where('supplierId', '==', currentUser.uid)
));
if (itemsSnapshot.empty) {
itemsGrid.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📦</div>
<h3>No Items Added</h3>
<p>Start by adding your first item to the catalog.</p>
<button class="btn btn--primary" id="add-first-item-btn">➕ Add First Item</button>
</div>
`;
// Add event listener to the add first item button
const addFirstItemBtn = $('add-first-item-btn');
if (addFirstItemBtn) {
addFirstItemBtn.addEventListener('click', () => showItemModal());
}