Repository navigation
Expand file tree
/
Copy pathMainApp.tsx
More file actions
1785 lines (1643 loc) · 86.6 KB
/
Copy pathMainApp.tsx
File metadata and controls
1785 lines (1643 loc) · 86.6 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
import React, { useState, useEffect, useMemo } from 'react';
import FileUpload from './components/FileUpload';
import Dashboard from './components/Dashboard';
import InvoiceTable from './components/InvoiceTable';
import AddProductModal from './components/AddProductModal';
import TrackerSheets from './components/TrackerSheets';
import { AdminPanel } from './components/AdminPanel';
import { PlatformDashboard } from './components/PlatformDashboard';
import { Login } from './components/Login';
import { AnalysisResult, InvoiceItem, ProcessingStatus, SavedInvoice, Product, UserRole } from './types';
import { analyzeInvoiceImage } from './services/geminiService';
import { getAllGlCodes } from './services/glCodeService';
import { DEMO_BOOKING_URL } from './src/siteConfig';
import { GLCode } from './types';
import { saveInvoiceToHistory, checkForDuplicate, getSavedInvoices } from './services/storageService';
import { saveNewProduct, migrateLocalProductsToDb } from './services/productService';
import { signOut, getSession, getUserRole, getUserName, onAuthStateChange } from './services/authService';
import { supabase } from './services/supabaseClient';
interface LocationData {
id: string;
name: string;
location_code: string | null;
address?: string | null;
address_keywords?: string[] | null;
}
interface VendorData {
id: string;
canonical_name: string;
account_code: string | null;
aliases: string[];
}
interface OrgData {
id: string;
name: string;
plan: string;
is_trial: boolean;
trial_ends_at: string | null;
max_locations: number;
max_users: number;
max_invoices_per_month: number;
}
import { exportInvoiceToCSV } from './utils/csvExport';
import { Download, RotateCcw, CheckCircle2, AlertTriangle, AlertCircle, FileText, ExternalLink, LayoutDashboard, TableProperties, MapPin, LogOut, Database, Building2, Calendar, Hash, DollarSign, Tag, CheckCircle, Menu, X, Sparkles, Lock as LockIcon, ShieldCheck, TrendingUp } from 'lucide-react';
import { jsPDF } from 'jspdf';
import { PDFDocument } from 'pdf-lib';
import { motion, AnimatePresence } from 'motion/react';
const App: React.FC = () => {
const [currentUser, setCurrentUser] = useState<UserRole>(null);
const [currentLocation, setCurrentLocation] = useState<string>('Centerpointe');
const [locations, setLocations] = useState<LocationData[]>([]);
const [vendors, setVendors] = useState<VendorData[]>([]);
const [activeTab, setActiveTab] = useState<'processor' | 'trackers' | 'admin' | 'platform'>('processor');
const [isPlatformAdmin, setIsPlatformAdmin] = useState(false);
const [status, setStatus] = useState<ProcessingStatus>('idle');
const [result, setResult] = useState<AnalysisResult | null>(null);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [duplicateWarning, setDuplicateWarning] = useState<SavedInvoice | null>(null);
const [isSaved, setIsSaved] = useState(false);
const [previewImage, setPreviewImage] = useState<string | null>(null);
// State for Add Product Modal
const [isAddProductOpen, setIsAddProductOpen] = useState(false);
const [productToAdd, setProductToAdd] = useState<InvoiceItem | null>(null);
const [recentInvoices, setRecentInvoices] = useState<SavedInvoice[]>([]);
// Full saved-invoice list — powers the dashboard widgets
const [savedInvoices, setSavedInvoices] = useState<SavedInvoice[]>([]);
// Org's GL codes (from DB) — drives the review-table + add-product dropdowns
const [glCodes, setGlCodes] = useState<GLCode[]>([]);
// Which widget's drill-down panel is open ('spikes' | 'month' | null)
const [widgetDetail, setWidgetDetail] = useState<null | 'spikes' | 'month'>(null);
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const [userName, setUserName] = useState('');
const [userEmail, setUserEmail] = useState('');
// DB-driven role: 'owner' | 'manager' | 'chef' | 'viewer'
// Real security is enforced by RLS at the database layer — users physically
// cannot see invoices from locations they don't have access to. The sidebar
// dropdown simply filters to show only their accessible locations.
const [userDbRole, setUserDbRole] = useState<string>('owner');
const [userLocationId, setUserLocationId] = useState<string | null>(null);
const [org, setOrg] = useState<OrgData | null>(null);
// True when user arrives via invite or password-recovery email — they must
// set a password before they can use the app.
const [mustSetPassword, setMustSetPassword] = useState(false);
const [setPwForm, setSetPwForm] = useState({ pw: '', confirm: '', loading: false, error: '' });
useEffect(() => {
// Invite / password-recovery flow. The flag is captured in index.tsx before
// Supabase clears the hash; we also still check the live hash as a fallback.
const hash = window.location.hash;
const pwFlow = (() => { try { return sessionStorage.getItem('chefcode_pw_flow') === '1'; } catch { return false; } })();
if (pwFlow || hash.includes('type=invite') || hash.includes('type=recovery')) {
setMustSetPassword(true);
}
// Also catch the recovery event directly, in case the flag was missed.
const recoverySub = supabase.auth.onAuthStateChange((event) => {
if (event === 'PASSWORD_RECOVERY') setMustSetPassword(true);
});
// Check for existing Supabase session on load
getSession().then((session) => {
if (session?.user) {
setCurrentUser(getUserRole(session.user));
setUserName(getUserName(session.user));
setUserEmail(session.user.email || '');
}
});
// Listen for auth changes (login/logout from other tabs)
const subscription = onAuthStateChange((user) => {
if (user) {
setCurrentUser(getUserRole(user));
setUserName(getUserName(user));
setUserEmail(user.email || '');
} else {
setCurrentUser(null);
setUserName('');
setUserEmail('');
}
});
const savedLoc = localStorage.getItem('chefcode_location');
if (savedLoc) setCurrentLocation(savedLoc);
return () => { subscription.unsubscribe(); recoverySub.data.subscription.unsubscribe(); };
}, []);
// Load org-scoped data whenever the user signs in, and clear it on sign-out.
// This previously ran only on page load — signing in through the Login screen
// left locations/vendors empty until a full refresh, which is why the Active
// Location sometimes didn't populate.
useEffect(() => {
if (!currentUser) {
setLocations([]);
setVendors([]);
setOrg(null);
setRecentInvoices([]);
return;
}
const loadRecent = async () => {
const invoices = await getSavedInvoices();
setSavedInvoices(invoices);
setRecentInvoices(invoices.slice(0, 5));
};
loadRecent();
getAllGlCodes().then(setGlCodes).catch(() => {});
// One-time: rescue any products still trapped in this browser's localStorage
migrateLocalProductsToDb().catch(() => {});
// Load locations + vendors + user profile + access list from Supabase
const loadOrgData = async () => {
const { data: { user } } = await supabase.auth.getUser();
if (!user) return;
const savedLoc = localStorage.getItem('chefcode_location');
// Platform-admin flag — isolated query so that if the column doesn't
// exist yet (migration not run), it fails silently instead of breaking
// the rest of the org-data load.
const { data: paRow } = await supabase
.from('profiles')
.select('is_platform_admin')
.eq('id', user.id)
.single();
if ((paRow as any)?.is_platform_admin) setIsPlatformAdmin(true);
const [locRes, vendorRes, profileRes, accessRes] = await Promise.all([
supabase.from('locations').select('id, name, location_code, address, address_keywords').eq('is_active', true).order('name'),
supabase.from('vendors').select('id, canonical_name, account_code, aliases').eq('is_active', true).order('canonical_name'),
supabase.from('profiles').select('role, location_id, org_id').eq('id', user.id).single(),
supabase.from('user_location_access').select('location_id, role').eq('user_id', user.id),
]);
// Load the org data (for trial banner + limits)
const profileData: any = profileRes.data;
if (profileData?.org_id) {
const { data: orgRow } = await supabase
.from('organizations')
.select('id, name, plan, is_trial, trial_ends_at, max_locations, max_users, max_invoices_per_month')
.eq('id', profileData.org_id)
.single();
if (orgRow) setOrg(orgRow as OrgData);
}
if (vendorRes.data) setVendors(vendorRes.data as VendorData[]);
const allLocs = (locRes.data || []) as LocationData[];
const profile: any = profileRes.data;
if (profile?.role) setUserDbRole(profile.role);
if (profile?.location_id) setUserLocationId(profile.location_id);
// Build set of accessible location IDs
let accessRows = (accessRes.data || []) as { location_id: string; role: string }[];
let accessibleIds = new Set(accessRows.map(r => r.location_id));
// SAFETY NET: If user is an owner and has 0 access entries but their org
// already has locations (legacy users), auto-grant access to all of them.
// This fixes accounts created before user_location_access existed.
if (profile?.role === 'owner' && accessRows.length === 0 && allLocs.length > 0) {
const grants = allLocs.map(l => ({
user_id: user.id,
location_id: l.id,
role: 'owner',
}));
const { error: grantErr } = await supabase
.from('user_location_access')
.upsert(grants, { onConflict: 'user_id,location_id' });
if (!grantErr) {
accessibleIds = new Set(allLocs.map(l => l.id));
}
}
// Filter org locations to only accessible ones
const accessibleLocs = allLocs.filter(l => accessibleIds.has(l.id));
setLocations(accessibleLocs);
// Pick active location: saved → first accessible
let activeLoc: LocationData | undefined;
if (savedLoc) activeLoc = accessibleLocs.find(l => l.name === savedLoc);
if (!activeLoc && accessibleLocs.length > 0) activeLoc = accessibleLocs[0];
if (activeLoc) {
setCurrentLocation(activeLoc.name);
localStorage.setItem('chefcode_location', activeLoc.name);
}
};
loadOrgData();
}, [currentUser]);
// Close the widget drill-down panel on Escape
useEffect(() => {
if (!widgetDetail) return;
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setWidgetDetail(null); };
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [widgetDetail]);
// Close the mobile menu on Escape (the removed drawer's backdrop used to
// handle dismissal; the dropdown needs its own).
useEffect(() => {
if (!mobileMenuOpen) return;
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setMobileMenuOpen(false); };
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [mobileMenuOpen]);
const handleLogin = (role: UserRole) => {
setCurrentUser(role);
};
const handleLogout = async () => {
await signOut();
setCurrentUser(null);
};
const handleLocationChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const loc = e.target.value;
setCurrentLocation(loc);
localStorage.setItem('chefcode_location', loc);
};
// Helper to convert file to base64 and extract mimeType
const processFile = (file: File): Promise<{ base64: string, mimeType: string }> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const result = reader.result as string;
// Data URL format: "data:image/jpeg;base64,/9j/4AAQ..."
// Split at the comma to separate metadata from data
const [metadata, base64Data] = result.split(',');
// Extract mime type from metadata (e.g., "data:image/jpeg;base64")
const mimeType = metadata.match(/:(.*?);/)?.[1] || file.type || 'image/png';
resolve({ base64: base64Data, mimeType });
};
reader.onerror = (error) => reject(error);
});
};
const handleFileSelect = async (file: File) => {
// Trial gate: an expired trial must not get free AI extraction.
if (isReadOnly) {
setErrorMsg('Your trial has expired. Please upgrade to continue processing invoices.');
setStatus('error');
return;
}
setStatus('uploading');
setErrorMsg(null);
setDuplicateWarning(null);
setIsSaved(false);
try {
const { base64, mimeType } = await processFile(file);
setPreviewImage(`data:${mimeType};base64,${base64}`);
setStatus('analyzing');
const data = await analyzeInvoiceImage(
base64,
mimeType,
locations.map(l => ({ name: l.name, address: l.address, keywords: l.address_keywords }))
);
data.location = currentLocation;
// Check for price spikes. Compare each item against the MOST RECENT
// prior purchase of the same product AT THIS LOCATION. getSavedInvoices
// returns newest-first, so we sort matches by invoice date and take the
// latest one strictly before this invoice (guards against out-of-order entry).
const activeLocId = locations.find(l => l.name === currentLocation)?.id || null;
const fullHistory = await getSavedInvoices();
const history = fullHistory.filter(h =>
activeLocId ? (h.locationId === activeLocId || !h.locationId) : !h.locationId
);
const enrichedItems = data.items.map(item => {
let lastPrice: number | null = null;
let lastDate: string | null = null;
for (const inv of history) {
if (!inv.items) continue;
const matched = inv.items.find(historyItem =>
historyItem.description === item.description ||
(historyItem.productNumber && historyItem.productNumber === item.productNumber)
);
if (matched && matched.unitPrice) {
// Keep the most recent prior price (by invoice date)
if (!lastDate || (inv.invoiceDate || '') > lastDate) {
lastPrice = matched.unitPrice;
lastDate = inv.invoiceDate || '';
}
}
}
const isSpike = lastPrice !== null && item.unitPrice > lastPrice * 1.10; // 10% spike
return {
...item,
historicalPrice: lastPrice || undefined,
historicalDate: lastDate || undefined,
priceSpike: isSpike
};
});
data.items = enrichedItems;
// Check for duplicates (scoped to the active location)
const duplicate = await checkForDuplicate(data, activeLocId);
if (duplicate) {
setDuplicateWarning(duplicate);
}
setResult(data);
setStatus('complete');
} catch (err: any) {
console.error(err);
setErrorMsg(err.message || "Failed to analyze invoice. Please try again or check your API key.");
setStatus('error');
}
};
const handleUpdateItem = (id: string, field: keyof InvoiceItem, value: any) => {
if (!result) return;
const updatedItems = result.items.map(item => {
if (item.id === id) {
const updatedItem = { ...item, [field]: value };
// Recalculate totalPrice if quantity or unitPrice changes
if (field === 'quantity' || field === 'unitPrice') {
const qty = parseFloat(updatedItem.quantity as any) || 0;
const price = parseFloat(updatedItem.unitPrice as any) || 0;
updatedItem.totalPrice = qty * price;
}
return updatedItem;
}
return item;
});
setResult({ ...result, items: updatedItems });
};
const handleDeleteItem = (id: string) => {
if (!result) return;
const updatedItems = result.items.filter(item => item.id !== id);
setResult({ ...result, items: updatedItems });
};
const handleOpenAddProduct = (item: InvoiceItem) => {
setProductToAdd(item);
setIsAddProductOpen(true);
};
const handleSaveProduct = async (newProduct: Product) => {
await saveNewProduct(newProduct);
// Update the item in the current view to show it's now matched
if (result && productToAdd) {
const updatedItems = result.items.map(item =>
item.id === productToAdd.id
? {
...item,
glCode: newProduct.code,
categoryName: newProduct.category,
isDatabaseMatch: true
}
: item
);
setResult({...result, items: updatedItems});
}
};
const handleReset = () => {
setStatus('idle');
setResult(null);
setErrorMsg(null);
setDuplicateWarning(null);
setIsSaved(false);
setPreviewImage(null);
};
const handleSaveAndFinish = async () => {
if (isReadOnly) {
setErrorMsg('Your trial has expired. Please upgrade to save invoices.');
return;
}
if (result) {
try {
// Look up active location's UUID for proper RLS filtering
const activeLoc = locations.find(l => l.name === currentLocation);
await saveInvoiceToHistory(result, activeLoc?.id || null);
// Learn from the user's coding: add any line items that were coded but
// aren't in the product DB yet, so the AI auto-matches them next time.
// This makes "Finalize & Save" teach the database — no separate
// "Add to DB" step needed. saveNewProduct dedupes, so re-saves are safe.
try {
const toLearn = result.items.filter(
(it: any) => it.glCode && it.description && !it.isDatabaseMatch
);
await Promise.all(toLearn.map((it: any) => saveNewProduct({
productNo: it.productNumber || '',
description: it.description,
category: it.categoryName || it.category || '',
code: it.glCode || '',
})));
} catch (e) {
console.warn('Product learning on save failed (invoice still saved):', e);
}
setIsSaved(true);
// Refresh the widget stats + recent list with the newly saved invoice
getSavedInvoices().then(invoices => {
setSavedInvoices(invoices);
setRecentInvoices(invoices.slice(0, 5));
});
} catch (err: any) {
console.error('Failed to save invoice:', err);
setErrorMsg('Failed to save invoice. Please try again.');
}
}
};
const getCleanVendorName = (vendorName: string) => {
if (!vendorName) return "UnknownVendor";
const normalized = vendorName.toLowerCase();
if (normalized.includes('sysco')) return 'Sysco';
if (normalized.includes('sunrise')) return 'SunRise Produce';
if (normalized.includes('giuliano')) return 'Giulianos Bakery';
if (normalized.includes('performance')) return 'Performance';
if (normalized.includes('spadra')) return 'Spadra';
if (normalized.includes('pepsi')) return 'Pepsi';
if (normalized.includes('us food') || normalized.includes('usfood')) return 'US FOOD';
if (normalized.includes('bon suisse')) return 'Bon Suisse';
if (normalized.includes('wismettac')) return 'Wismettac';
if (normalized.includes('m cafe') || normalized.includes('mcafe')) return 'M cafe';
if (normalized.includes('freshpoint')) return 'Freshpoint';
if (normalized.includes('unistar')) return 'Unistar Foods';
if (normalized.includes('southern glazer') || normalized.includes('reliant')) return "Southern Glazer's";
if (normalized.includes('karat') || normalized.includes('lollicup')) return 'Karat By Lollicup';
if (normalized.includes('cali dumpling') || normalized.includes('raindrop')) return 'Cali Dumpling';
if (normalized.includes('coney island') || normalized.includes('golden waffle')) return 'Coney Island';
if (normalized.includes('ifs')) return 'IFS';
if (normalized.includes('south shore') || normalized.includes('core mark')) return 'SOUTH SHORE';
if (normalized.includes('calico')) return 'Calico';
if (normalized.includes('prudential')) return 'Prudential';
if (normalized.includes('sharpened')) return 'All Sharpened Knives';
if (normalized.includes('gna brook')) return 'GNA Brook Fire';
if (normalized.includes('dallas')) return 'Dallas Bros';
if (normalized.includes('whirley')) return 'Whirley Drink Works';
if (normalized.includes('cintas')) return 'CINTAS';
if (normalized.includes('airgas')) return 'Airgas';
if (normalized.includes('eco lab') || normalized.includes('ecolab')) return 'ECO LAB';
if (normalized.includes('don')) return 'DON';
// Fallback: return the original but split by common delimiters to remove location
return vendorName.split(',')[0].split('-')[0].trim();
};
// ── Dashboard widget stats ──
// Computed from saved invoices for the current location. Invoices saved
// before locations existed (no location field) are included so legacy data
// still counts. Month buckets use the YYYY-MM prefix of invoiceDate to
// avoid UTC parsing shifts; the spike window uses processedAt (when we
// caught it), falling back to invoiceDate.
// Re-load the GL-code list whenever the user returns to the Processor, so
// codes added/edited/deleted in the Admin panel show up without a full page
// reload (the list was previously fetched only once at startup).
useEffect(() => {
if (activeTab === 'processor') {
getAllGlCodes().then(setGlCodes).catch(() => {});
}
}, [activeTab]);
const widgetStats = useMemo(() => {
const monthKey = (d: string | undefined): string => {
if (!d) return '';
const m = d.match(/^(\d{4})-(\d{2})/);
if (m) return `${m[1]}-${m[2]}`;
const dt = new Date(d.replace(/-/g, '/'));
return isNaN(dt.getTime()) ? '' : `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}`;
};
const now = new Date();
const thisMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
const prev = new Date(now.getFullYear(), now.getMonth() - 1, 1);
const lastMonth = `${prev.getFullYear()}-${String(prev.getMonth() + 1).padStart(2, '0')}`;
const cutoff = Date.now() - 30 * 24 * 60 * 60 * 1000;
const activeLocId = locations.find(l => l.name === currentLocation)?.id || null;
let countThis = 0, countLast = 0, spendThis = 0;
let spikeItems = 0, spikeInvoices = 0, overcharge = 0;
const vendorSpend: Record<string, number> = {};
const monthInvoices: SavedInvoice[] = [];
const spikeDetails: { id: string; vendorName: string; invoiceNumber: string; invoiceDate: string; items: { description: string; unit: number; hist: number; qty: number }[] }[] = [];
for (const inv of savedInvoices) {
// Scope to the active location by UUID (survives location renames);
// legacy invoices with no location_id are included.
if (inv.locationId) {
if (inv.locationId !== activeLocId) continue;
} else if (inv.location && inv.location !== currentLocation) {
continue;
}
const mk = monthKey(inv.invoiceDate);
const amt = Number(inv.totalAmount) || 0;
if (mk === thisMonth) {
countThis++;
spendThis += amt;
monthInvoices.push(inv);
const v = getCleanVendorName(inv.vendorName || '');
vendorSpend[v] = (vendorSpend[v] || 0) + amt;
} else if (mk === lastMonth) {
countLast++;
}
const procTime = new Date(inv.processedAt || inv.invoiceDate).getTime();
if (!isNaN(procTime) && procTime >= cutoff && inv.items) {
const spiked: { description: string; unit: number; hist: number; qty: number }[] = [];
for (const it of inv.items) {
if (it.priceSpike) {
spikeItems++;
const hist = Number(it.historicalPrice);
const unit = Number(it.unitPrice);
const qty = Number(it.quantity) || 0;
if (hist > 0 && unit > hist) overcharge += (unit - hist) * qty;
spiked.push({ description: it.description, unit, hist, qty });
}
}
if (spiked.length > 0) {
spikeInvoices++;
spikeDetails.push({
id: inv.id,
vendorName: inv.vendorName,
invoiceNumber: inv.invoiceNumber,
invoiceDate: inv.invoiceDate,
items: spiked,
});
}
}
}
monthInvoices.sort((a, b) => (b.invoiceDate || '').localeCompare(a.invoiceDate || ''));
spikeDetails.sort((a, b) => (b.invoiceDate || '').localeCompare(a.invoiceDate || ''));
const topVendor = Object.entries(vendorSpend).sort((a, b) => b[1] - a[1])[0] || null;
return { countThis, countLast, spendThis, topVendor, spikeItems, spikeInvoices, overcharge, monthInvoices, spikeDetails };
}, [savedInvoices, currentLocation, locations]);
// Always show cents — this is accounting data, and rounding hides small
// overcharges (e.g. a $0.40 spike would otherwise read as "$0").
const fmtMoney = (n: number) =>
'$' + (Number.isFinite(n) ? n : 0).toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
// Lookup vendor account code (F02124, F02198, etc.) by matching invoice vendor name
// against the vendors table in Supabase
const getVendorAccountCode = (vendorName: string): string => {
if (!vendorName || vendors.length === 0) return '';
const normalized = vendorName.toLowerCase();
const matched = vendors.find(v => {
const canonName = (v.canonical_name || '').toLowerCase();
if (normalized.includes(canonName) || canonName.includes(normalized.split(',')[0].trim())) return true;
return (v.aliases || []).some(a => normalized.includes((a || '').toLowerCase()));
});
return matched?.account_code || '';
};
// Lookup current location's code (170130, 170131, etc.)
const getCurrentLocationCode = (): string => {
const loc = locations.find(l => l.name === currentLocation);
return loc?.location_code || '';
};
const handleDownloadUpdatedInvoice = async () => {
if (!result || !previewImage) return;
const cleanVendor = getCleanVendorName(result.vendorName);
const safeVendor = cleanVendor.replace(/[/\\?%*:|"<>]/g, '-');
const safeInvNum = (result.invoiceNumber || "UnknownInvoice").replace(/[/\\?%*:|"<>]/g, '-');
const totalAmt = parseFloat(result.totalAmount as any) || 0;
// Build prefix: VENDOR_CODE LOCATION_CODE (e.g. "F02124 170130")
// Falls back gracefully if codes aren't set yet
const vendorCode = getVendorAccountCode(result.vendorName);
const locCode = getCurrentLocationCode();
const codePrefix = [vendorCode, locCode].filter(Boolean).join(' ');
const fileName = codePrefix
? `${codePrefix} ${safeVendor} ${safeInvNum} $${totalAmt.toFixed(2)}.pdf`
: `${safeVendor} ${safeInvNum} $${totalAmt.toFixed(2)}.pdf`;
const doc = new jsPDF();
// Page 1: Cover Page
doc.setFontSize(22);
doc.text("Invoice Summary", 20, 30);
doc.setFontSize(12);
doc.text(`Vendor Name: ${result.vendorName}`, 20, 50);
doc.text(`Vendor Code: ${vendorCode || 'N/A'}`, 20, 60);
doc.text(`Location Code: ${locCode || 'N/A'}`, 20, 70);
doc.text(`Invoice Date: ${result.invoiceDate || 'N/A'}`, 20, 80);
doc.text(`Invoice Number: ${result.invoiceNumber || 'N/A'}`, 20, 90);
doc.text(`Total Amount: $${totalAmt.toFixed(2)}`, 20, 100);
doc.setFontSize(16);
doc.text("GL Code Breakdown", 20, 120);
// Calculate category breakdown by GL Code
const codeTotals: Record<string, number> = {};
result.items.forEach(item => {
const code = item.glCode || 'Uncategorized';
codeTotals[code] = (codeTotals[code] || 0) + (parseFloat(item.totalPrice as any) || 0);
});
let yPos = 135;
doc.setFontSize(12);
Object.entries(codeTotals).forEach(([code, total]) => {
doc.text(`${code}: $${total.toFixed(2)}`, 20, yPos);
yPos += 10;
});
if (previewImage.startsWith('data:image/')) {
// Page 2: Original Invoice Image
doc.addPage();
try {
// Calculate aspect ratio to fit image on page
const imgProps = doc.getImageProperties(previewImage);
const pdfWidth = doc.internal.pageSize.getWidth();
const pdfHeight = doc.internal.pageSize.getHeight();
const imgRatio = imgProps.width / imgProps.height;
const pdfRatio = pdfWidth / pdfHeight;
let finalWidth = pdfWidth;
let finalHeight = pdfHeight;
if (imgRatio > pdfRatio) {
// Image is wider than page
finalWidth = pdfWidth;
finalHeight = pdfWidth / imgRatio;
} else {
// Image is taller than page
finalHeight = pdfHeight;
finalWidth = pdfHeight * imgRatio;
}
// Center the image
const xOffset = (pdfWidth - finalWidth) / 2;
const yOffset = (pdfHeight - finalHeight) / 2;
let format = previewImage.substring(previewImage.indexOf('/') + 1, previewImage.indexOf(';')).toUpperCase();
if (format === 'JPEG') format = 'JPEG';
else if (format === 'JPG') format = 'JPEG';
doc.addImage(previewImage, format, xOffset, yOffset, finalWidth, finalHeight);
} catch (e) {
console.error("Error adding image to PDF:", e);
doc.setFontSize(12);
doc.text("Error: Could not attach the original invoice image.", 20, 30);
}
doc.save(fileName);
} else if (previewImage.startsWith('data:application/pdf')) {
try {
// Merge the jsPDF output with the original PDF using pdf-lib
const coverPdfBytes = doc.output('arraybuffer');
const mergedPdf = await PDFDocument.load(coverPdfBytes);
const originalPdfBytes = await fetch(previewImage).then(res => res.arrayBuffer());
const originalPdf = await PDFDocument.load(originalPdfBytes);
const copiedPages = await mergedPdf.copyPages(originalPdf, originalPdf.getPageIndices());
copiedPages.forEach((page) => mergedPdf.addPage(page));
const mergedPdfBytes = await mergedPdf.save();
// Create a blob and download
const blob = new Blob([mergedPdfBytes], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (e) {
console.error("Error merging PDF:", e);
doc.addPage();
doc.setFontSize(12);
doc.text("Error: Could not attach the original invoice PDF.", 20, 30);
doc.save(fileName);
}
} else {
doc.addPage();
doc.setFontSize(12);
doc.text("Original invoice was an unsupported format and cannot be attached.", 20, 30);
doc.save(fileName);
}
};
const handleOpenPreview = () => {
if (previewImage) {
const newTab = window.open();
if (newTab) {
if (previewImage.startsWith('data:application/pdf')) {
newTab.document.write(`
<!DOCTYPE html>
<html>
<head>
<title>Invoice Preview</title>
<style>
body { margin: 0; background-color: #0f172a; height: 100vh; overflow: hidden; }
iframe { width: 100%; height: 100%; border: none; }
</style>
</head>
<body>
<iframe src="${previewImage}"></iframe>
</body>
</html>
`);
} else {
newTab.document.write(`
<!DOCTYPE html>
<html>
<head>
<title>Invoice Preview</title>
<style>
body { margin: 0; display: flex; justify-content: center; align-items: center; background-color: #0f172a; height: 100vh; }
img { max-width: 100%; max-height: 100%; object-fit: contain; }
</style>
</head>
<body>
<img src="${previewImage}" alt="Invoice Preview" />
</body>
</html>
`);
}
newTab.document.close();
} else {
alert("Please allow popups to view the invoice preview.");
}
}
};
// Address verification — AI match first, keyword fallback.
// The AI compares the invoice's Ship To address against the org's registered
// locations (name + address) during analysis; result.matchedLocation holds the
// matched location name or ''. Keyword matching remains as a fallback for
// locations with manually curated address_keywords.
// Returns:
// 'verified' → invoice address matches the CURRENT location
// 'wrong-location' → invoice address matches a DIFFERENT location (cross-location warning)
// 'unverified' → no match found anywhere, but address was detected
// 'no-address' → no delivery address extracted from invoice
const addressVerification = (() => {
if (!result?.deliveryAddress) return { status: 'no-address' as const, matchedLocation: null };
const addrLower = result.deliveryAddress.toLowerCase();
// 1) AI-matched location (validated against our list in geminiService)
if (result.matchedLocation) {
const aiLoc = locations.find(l => l.name === result.matchedLocation);
if (aiLoc) {
return aiLoc.name === currentLocation
? { status: 'verified' as const, matchedLocation: aiLoc }
: { status: 'wrong-location' as const, matchedLocation: aiLoc };
}
}
// 2) Fallback: manual address_keywords matching
const findMatch = (loc: LocationData) => {
const kws = loc.address_keywords || [];
return kws.some(kw => kw && addrLower.includes(kw.toLowerCase()));
};
const currentLoc = locations.find(l => l.name === currentLocation);
if (currentLoc && findMatch(currentLoc)) {
return { status: 'verified' as const, matchedLocation: currentLoc };
}
// Check OTHER locations for cross-location warning
const otherMatched = locations.find(l => l.name !== currentLocation && findMatch(l));
if (otherMatched) {
return { status: 'wrong-location' as const, matchedLocation: otherMatched };
}
return { status: 'unverified' as const, matchedLocation: null };
})();
const isValidAddress = addressVerification.status === 'verified';
// ── Trial Status (drives banner + read-only mode) ──
const trialStatus = (() => {
if (!org) return { status: 'unknown' as const, daysLeft: null as number | null };
if (!org.is_trial) return { status: 'paid' as const, daysLeft: null };
if (!org.trial_ends_at) return { status: 'unknown' as const, daysLeft: null };
const end = new Date(org.trial_ends_at).getTime();
const now = Date.now();
const daysLeft = Math.ceil((end - now) / (1000 * 60 * 60 * 24));
if (daysLeft <= 0) return { status: 'expired' as const, daysLeft: 0 };
if (daysLeft <= 3) return { status: 'ending-soon' as const, daysLeft };
return { status: 'active' as const, daysLeft };
})();
const isReadOnly = trialStatus.status === 'expired';
// ── Password setup handler (invite / recovery flow) ──
const handleSetPassword = async (e: React.FormEvent) => {
e.preventDefault();
setSetPwForm(f => ({ ...f, error: '' }));
if (setPwForm.pw.length < 6) {
setSetPwForm(f => ({ ...f, error: 'Password must be at least 6 characters.' }));
return;
}
if (setPwForm.pw !== setPwForm.confirm) {
setSetPwForm(f => ({ ...f, error: 'Passwords do not match.' }));
return;
}
setSetPwForm(f => ({ ...f, loading: true }));
try {
const { error } = await supabase.auth.updateUser({ password: setPwForm.pw });
if (error) throw error;
// Clean the auth tokens out of the URL, then continue into the app
window.history.replaceState(null, '', window.location.pathname);
try { sessionStorage.removeItem('chefcode_pw_flow'); } catch { /* ignore */ }
setMustSetPassword(false);
setSetPwForm({ pw: '', confirm: '', loading: false, error: '' });
} catch (err: any) {
setSetPwForm(f => ({ ...f, loading: false, error: err.message || 'Failed to set password.' }));
}
};
// ── Set Password Screen (shown after clicking invite/recovery email) ──
if (mustSetPassword) {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-cyan-50/30 to-blue-50/50 flex items-center justify-center p-4">
<div className="w-full max-w-md">
<div className="text-center mb-8">
<img src="/logo.svg" alt="ChefCode" className="inline-block w-16 h-16 rounded-2xl shadow-xl shadow-cyan-500/20 mb-4" />
<h1 className="text-3xl font-bold text-slate-900 tracking-tight">Set Your Password</h1>
<p className="text-sm text-slate-600 mt-2">
Welcome to ChefCode<span className="text-cyan-600">.ai</span>! Choose a password to finish setting up your account.
</p>
</div>
<form onSubmit={handleSetPassword} className="bg-white rounded-2xl shadow-xl border border-slate-200/60 p-6 space-y-4">
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1.5 uppercase tracking-wider">
New Password
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<LockIcon size={16} className="text-slate-400" />
</div>
<input
type="password"
required
minLength={6}
value={setPwForm.pw}
onChange={(e) => setSetPwForm(f => ({ ...f, pw: e.target.value, error: '' }))}
className="w-full pl-10 text-sm border-slate-300 rounded-lg py-2.5 focus:ring-cyan-500 focus:border-cyan-500"
placeholder="At least 6 characters"
autoFocus
/>
</div>
</div>
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1.5 uppercase tracking-wider">
Confirm Password
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<LockIcon size={16} className="text-slate-400" />
</div>
<input
type="password"
required
minLength={6}
value={setPwForm.confirm}
onChange={(e) => setSetPwForm(f => ({ ...f, confirm: e.target.value, error: '' }))}
className="w-full pl-10 text-sm border-slate-300 rounded-lg py-2.5 focus:ring-cyan-500 focus:border-cyan-500"
placeholder="Re-enter password"
/>
</div>
</div>
{setPwForm.error && (
<div className="p-3 bg-red-50 border border-red-200 rounded-lg">
<p className="text-sm text-red-700">{setPwForm.error}</p>
</div>
)}
<button
type="submit"
disabled={setPwForm.loading || !setPwForm.pw || !setPwForm.confirm}
className="w-full flex justify-center items-center gap-2 py-3 px-4 rounded-lg text-sm font-bold text-white bg-gradient-to-r from-cyan-500 to-cyan-600 hover:from-cyan-600 hover:to-cyan-700 shadow-md disabled:opacity-50 transition-all"
>
{setPwForm.loading ? <CheckCircle2 size={14} className="animate-spin" /> : <CheckCircle size={14} />}
{setPwForm.loading ? 'Setting password...' : 'Set Password & Continue'}
</button>
</form>
<p className="text-center text-xs text-slate-500 mt-6">
By continuing, you agree to ChefCode's Terms of Service
</p>
</div>
</div>
);
}
if (!currentUser) {
return <Login onLogin={handleLogin} />;
}
// Single source of truth for the nav tabs — rendered by both the desktop
// top bar (short label) and the mobile dropdown (full label).
const navTabs = [
{ key: 'processor' as const, label: 'Processor', fullLabel: 'Invoice Processor', Icon: LayoutDashboard, show: true },
{ key: 'trackers' as const, label: 'Trackers', fullLabel: 'Tracker Sheets', Icon: TableProperties, show: currentUser === 'admin' },
{ key: 'admin' as const, label: 'Admin', fullLabel: 'Admin Panel', Icon: Database, show: currentUser === 'admin' },
{ key: 'platform' as const, label: 'Platform', fullLabel: 'Platform Admin', Icon: ShieldCheck, show: isPlatformAdmin },
].filter(t => t.show);
return (
<div className="min-h-screen bg-cream-50 flex flex-col">
{/* ═══════════════════════════════════════════════════════════
TOP NAVIGATION BAR (replaces the old sidebar)
═══════════════════════════════════════════════════════════ */}
<header className="bg-white border-b border-cream-200 sticky top-0 z-50 flex-shrink-0">
{/* Full-bleed bar: logo hugs the left corner, user controls hug the
right — no centered max-width (that's only for content below). */}
<div className="px-4 sm:px-5 h-16 flex items-center gap-3">
{/* Logo */}
<div className="flex items-center gap-2.5 shrink-0">
<img src="/logo.svg" alt="ChefCode" className="w-9 h-9 rounded-xl" />
<h1 className="text-lg font-bold tracking-tight text-brand-900 whitespace-nowrap">
ChefCode<span className="text-brand-600">.ai</span>
</h1>
</div>
{/* Desktop tabs */}
<nav className="hidden md:flex items-center gap-1 ml-4">
{navTabs.map(t => (
<button
key={t.key}
onClick={() => setActiveTab(t.key)}
aria-current={activeTab === t.key ? 'page' : undefined}
className={`flex items-center gap-1.5 px-3.5 py-2 rounded-full text-[13px] font-medium transition-colors ${
activeTab === t.key
? 'bg-brand-50 text-brand-700'
: 'text-slate-500 hover:text-brand-700 hover:bg-cream-100'
}`}
>
<t.Icon size={15} />
{t.label}
</button>
))}
</nav>