-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage.tsx
More file actions
2704 lines (2404 loc) · 126 KB
/
Copy pathpage.tsx
File metadata and controls
2704 lines (2404 loc) · 126 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
'use client';
import React, { useState, useEffect, useMemo, useRef, Suspense, useCallback } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { GradeMetrics, MultifamilyMarketBenchmarks, PropertyCharacteristics, MultifamilyGradeMetrics, MULTIFAMILY_BENCHMARKS, detectAssetClass, detectMarketTier, calculateMultifamilyGrade } from './grading-system';
// Removed PropertySummaryButton - analysis now handled on property details page
import { useAuth } from '@/contexts/AuthContext';
import { useOfferAnalyzerAccess } from './usePropertyAnalyzerAccess';
import { AuthGuard } from '@/components/auth/AuthGuard';
import { UnsavedChangesModal } from './UnsavedChangesModal';
import { CharlieTooltip } from './CharlieTooltip';
import { SaveOfferModal } from '@/components/shared/SaveOfferModal';
import AlertModal, { useAlert } from '@/components/shared/AlertModal';
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
ReferenceLine
} from 'recharts';
import { ArrowLeft } from 'lucide-react';
// Define the structure for data points in the chart
interface ChartDataPoint {
year: number;
cumulativeCashFlow: number;
noi: number;
cashFlowBeforeTax: number;
}
// Helper function to calculate IRR using Newton's method
const calculateIRR = (cashFlows: number[], guess: number = 0.1): number => {
// Defensive check: Ensure cashFlows is a valid, non-empty array
if (!Array.isArray(cashFlows) || cashFlows.length === 0) {
console.error("calculateIRR received an invalid or empty cashFlows array:", cashFlows);
return 0; // Return a default of 0 if input is invalid
}
// If only initial investment is present, IRR is not meaningful in standard calculation
// Or if all cash flows are 0 after initial investment
if (cashFlows.length === 1 && cashFlows[0] < 0) {
return 0;
}
const npv = (rate: number) => {
let sum = 0;
for (let i = 0; i < cashFlows.length; i++) {
sum += cashFlows[i] / Math.pow(1 + rate, i);
}
return sum;
};
const derivativeNpv = (rate: number): number => {
let sum = 0;
for (let i = 0; i < cashFlows.length; i++) {
sum -= i * cashFlows[i] / Math.pow(1 + rate, i + 1);
}
return sum;
};
let irr = guess;
const maxIterations = 100;
const tolerance = 0.0001;
for (let i = 0; i < maxIterations; i++) {
const nextIrr = irr - npv(irr) / derivativeNpv(irr);
if (Math.abs(nextIrr - irr) < tolerance) {
return nextIrr;
}
irr = nextIrr;
}
return irr; // Return the last approximation if not converged
};
// Component to handle search params
function SearchParamsHandler({ onParamsLoaded }: { onParamsLoaded: (params: { street: string; city: string; state: string; id?: string; offerId?: string; submissionId?: string; variationId?: string; readOnly?: boolean; source?: string }) => void }) {
const searchParams = useSearchParams();
useEffect(() => {
onParamsLoaded({
street: searchParams.get('street') || searchParams.get('address') || '',
city: searchParams.get('city') || '',
state: searchParams.get('state') || '',
id: searchParams.get('id') || undefined,
offerId: searchParams.get('offerId') || undefined,
submissionId: searchParams.get('submissionId') || undefined,
variationId: searchParams.get('variationId') || undefined,
readOnly: searchParams.get('readOnly') === 'true',
source: searchParams.get('source') || undefined
});
}, [searchParams, onParamsLoaded]);
return null;
}
export default function OfferAnalyzerPage() {
// Get user authentication and access control
const { user: currentUser } = useAuth();
const { userClass, hasAccess: hasOfferAnalyzerAccess, isLoading: isLoadingAccess } = useOfferAnalyzerAccess();
const router = useRouter();
const { showDelete, showError, AlertComponent } = useAlert();
// Redirect disabled users to pricing page
useEffect(() => {
if (!isLoadingAccess && !hasOfferAnalyzerAccess && userClass === 'disabled') {
router.replace('/pricing');
}
}, [isLoadingAccess, hasOfferAnalyzerAccess, userClass, router]);
// --- Modal State ---
const [showUnsavedChangesModal, setShowUnsavedChangesModal] = useState(false);
const [pendingNavigation, setPendingNavigation] = useState<(() => void) | null>(null);
const allowLeavingRef = useRef(false);
// --- Offer Management Modals ---
const [showSaveOfferModal, setShowSaveOfferModal] = useState(false);
const [showDuplicateAlert, setShowDuplicateAlert] = useState(false);
const [pendingOfferData, setPendingOfferData] = useState<{ name: string; description: string } | null>(null);
const [showOffersModal, setShowOffersModal] = useState(false);
const [selectedPropertyOffers, setSelectedPropertyOffers] = useState<any[]>([]);
const [loadedOfferName, setLoadedOfferName] = useState<string>('');
// --- Property Address State (from URL params, not displayed in UI) ---
const [propertyStreet, setPropertyStreet] = useState<string>('');
const [propertyCity, setPropertyCity] = useState<string>('');
const [propertyId, setPropertyId] = useState<string>('');
const [propertyState, setPropertyState] = useState<string>('');
const [submissionId, setSubmissionId] = useState<string>('');
const [variationId, setVariationId] = useState<string>('');
const [isReadOnly, setIsReadOnly] = useState<boolean>(false);
const [source, setSource] = useState<string>('');
const [scenarioOwnerId, setScenarioOwnerId] = useState<string>('');
// Determine if current user owns the scenario (for read-only logic)
const isOwner = !scenarioOwnerId || scenarioOwnerId === currentUser?.id;
const shouldDisableInputs = !!(variationId && scenarioOwnerId && scenarioOwnerId !== currentUser?.id);
// Callback to handle search params
const handleParamsLoaded = useCallback(async (params: { street: string; city: string; state: string; id?: string; offerId?: string; submissionId?: string; variationId?: string; readOnly?: boolean; source?: string }) => {
setPropertyStreet(params.street);
setPropertyCity(params.city);
setPropertyState(params.state);
if (params.submissionId) {
setSubmissionId(params.submissionId);
}
if (params.variationId) {
setVariationId(params.variationId);
}
if (params.id) {
setPropertyId(params.id);
}
if (params.readOnly) {
setIsReadOnly(params.readOnly);
}
// Handle loading pricing variation by ID
if (params.variationId) {
try {
console.log('Loading pricing variation with ID:', params.variationId);
const response = await fetch(`/api/pricing-variations/${params.variationId}`);
if (response.ok) {
const data = await response.json();
const scenarioData = data.variation.scenario_data;
const ownerId = data.variation.user_id;
console.log('Loading scenario data:', scenarioData);
console.log('Scenario owner ID:', ownerId);
// Store the scenario owner ID
setScenarioOwnerId(ownerId);
// Set read-only mode based on ownership (allow editing if user owns the scenario)
setIsReadOnly(ownerId !== currentUser?.id);
// Load all the scenario data into the analyzer state using the complete loader
loadOfferData(scenarioData);
console.log('Scenario data loaded successfully');
} else {
console.error('Failed to load pricing variation');
}
} catch (error) {
console.error('Error loading pricing variation:', error);
}
}
// If offerId is provided, load the saved offer scenario
if (params.offerId) {
try {
const response = await fetch(`/api/offer-scenarios/${params.offerId}`);
if (response.ok) {
const data = await response.json();
const offerData = data.scenario.offer_data;
// Set the loaded analysis name for display
setLoadedOfferName(data.scenario.offer_name || `Analysis ${params.offerId}`);
// Load all the saved values into the form fields
if (offerData) {
setPurchasePrice(parseFloat(offerData.purchasePrice) || 0);
setDownPaymentPercentage(parseFloat(offerData.downPaymentPercentage) || 20);
setInterestRate(parseFloat(offerData.interestRate) || 7.0);
setAmortizationPeriodYears(parseInt(offerData.amortizationPeriodYears) || 30);
setClosingCostsPercentage(parseFloat(offerData.closingCostsPercentage) || 3);
setNumUnits(parseInt(offerData.numUnits) || 0);
setAvgMonthlyRentPerUnit(parseFloat(offerData.avgMonthlyRentPerUnit) || 0);
setVacancyRate(parseFloat(offerData.vacancyRate) || 10);
setAnnualRentalGrowthRate(parseFloat(offerData.annualRentalGrowthRate) || 2);
setOtherIncomeAnnual(parseFloat(offerData.otherIncomeAnnual) || 0);
setIncomeReductionsAnnual(parseFloat(offerData.incomeReductionsAnnual) || 0);
setPropertyTaxes(parseFloat(offerData.propertyTaxes) || 0);
setInsurance(parseFloat(offerData.insurance) || 0);
setPropertyManagementFeePercentage(parseFloat(offerData.propertyManagementFeePercentage) || 6);
setMaintenanceRepairsAnnual(parseFloat(offerData.maintenanceRepairsAnnual) || 0);
setUtilitiesAnnual(parseFloat(offerData.utilitiesAnnual) || 0);
setContractServicesAnnual(parseFloat(offerData.contractServicesAnnual) || 0);
setInterestOnlyPeriodYears(parseInt(offerData.interestOnlyPeriodYears) || 10);
setRefinanceTermYears(parseInt(offerData.refinanceTermYears) || 25);
setDispositionCapRate(parseFloat(offerData.dispositionCapRate) || 6);
}
}
} catch (error) {
console.error('Error loading saved offer:', error);
}
}
// Set the source for back navigation
if (params.source) {
setSource(params.source);
}
}, []);
// --- Input States: FINANCING ---
const [purchasePrice, setPurchasePrice] = useState<number>(0);
const [downPaymentPercentage, setDownPaymentPercentage] = useState<number>(0); // Percentage
const [interestRate, setInterestRate] = useState<number>(0); // Percentage
const [loanStructure, setLoanStructure] = useState<'amortizing' | 'interest-only'>('amortizing'); // New loan structure selection
const [amortizationPeriodYears, setAmortizationPeriodYears] = useState<number>(0); // Years (updated from 24 to 30)
const [interestOnlyPeriodYears, setInterestOnlyPeriodYears] = useState<number>(0); // Years for IO period
const [refinanceTermYears, setRefinanceTermYears] = useState<number>(0); // Years (0 means sale)
const [closingCostsPercentage, setClosingCostsPercentage] = useState<number>(0); // Percentage of Purchase Price
const [dispositionCapRate, setDispositionCapRate] = useState<number>(0); // Target cap rate at sale
// --- Input States: RENTS ---
const [numUnits, setNumUnits] = useState<number>(0);
const [avgMonthlyRentPerUnit, setAvgMonthlyRentPerUnit] = useState<number>(0);
const [vacancyRate, setVacancyRate] = useState<number>(0); // Percentage
const [annualRentalGrowthRate, setAnnualRentalGrowthRate] = useState<number>(0); // Percentage
const [otherIncomeAnnual, setOtherIncomeAnnual] = useState<number>(0); // New State for Other Income
const [incomeReductionsAnnual, setIncomeReductionsAnnual] = useState<number>(0); // New State for Income Reductions
// --- Input States: OPERATING EXPENSES (ANNUAL) ---
const [propertyTaxes, setPropertyTaxes] = useState<number>(0);
const [insurance, setInsurance] = useState<number>(0);
const [propertyManagementFeePercentage, setPropertyManagementFeePercentage] = useState<number>(0); // Percentage of EGI
const [maintenanceRepairsAnnual, setMaintenanceRepairsAnnual] = useState<number>(0); // Total annual
const [utilitiesAnnual, setUtilitiesAnnual] = useState<number>(0); // Total annual
const [contractServicesAnnual, setContractServicesAnnual] = useState<number>(0); // New expense
const [payrollAnnual, setPayrollAnnual] = useState<number>(0); // New expense
const [marketingAnnual, setMarketingAnnual] = useState<number>(0); // New expense
const [gAndAAnnual, setGAndAAnnual] = useState<number>(0); // New expense
const [otherExpensesAnnual, setOtherExpensesAnnual] = useState<number>(0); // Total annual
const [expenseGrowthRate, setExpenseGrowthRate] = useState<number>(0); // Percentage
// --- Operating Expenses Toggle States ---
const [usePercentageMode, setUsePercentageMode] = useState<boolean>(false);
const [operatingExpensePercentage, setOperatingExpensePercentage] = useState<number>(0);
// --- Input States: CAPITAL EXPENDITURES (ANNUAL) ---
const [capitalReservePerUnitAnnual, setCapitalReservePerUnitAnnual] = useState<number>(0); // Per unit, annual
const [holdingPeriodYears, setHoldingPeriodYears] = useState<number>(0); // Years
const [deferredCapitalReservePerUnit, setDeferredCapitalReservePerUnit] = useState<number>(0);
// --- Helper function for formatting and parsing numerical inputs with commas ---
const formatAndParseNumberInput = (
setter: React.Dispatch<React.SetStateAction<number>>
) => (e: React.ChangeEvent<HTMLInputElement>) => {
// Remove all non-digit and non-decimal characters (allowing only one decimal point)
const cleanedValue = e.target.value.replace(/[^\d.]/g, '');
// Parse to float, default to 0 if invalid
const parsedValue = parseFloat(cleanedValue) || 0;
setter(Math.max(0, parsedValue));
};
// --- Calculated Metrics (Year 1) ---
// Financing Calculations (Year 1)
const downPaymentAmount = useMemo(() => {
return purchasePrice * (downPaymentPercentage / 100);
}, [purchasePrice, downPaymentPercentage]);
const loanAmount = useMemo(() => {
return purchasePrice - downPaymentAmount;
}, [purchasePrice, downPaymentAmount]);
const totalInitialInvestment = useMemo(() => {
return downPaymentAmount + (purchasePrice * (closingCostsPercentage / 100));
}, [downPaymentAmount, purchasePrice, closingCostsPercentage]);
const monthlyInterestRate = useMemo(() => {
return (interestRate / 100) / 12;
}, [interestRate]);
const numberOfPayments = useMemo(() => {
return amortizationPeriodYears * 12;
}, [amortizationPeriodYears]);
const monthlyMortgagePayment = useMemo(() => {
if (loanStructure === 'interest-only') {
// For interest-only loans, payment is just the interest
return loanAmount * monthlyInterestRate;
}
// For amortizing loans, use standard amortization formula
if (monthlyInterestRate === 0) { // Handle 0% interest rate to avoid division by zero
if (numberOfPayments === 0) return 0;
return loanAmount / numberOfPayments;
}
const numerator = monthlyInterestRate * Math.pow(1 + monthlyInterestRate, numberOfPayments);
const denominator = Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1;
if (denominator === 0) return loanAmount;
return loanAmount * (numerator / denominator);
}, [loanAmount, monthlyInterestRate, numberOfPayments, loanStructure]);
const annualDebtService = useMemo(() => {
return monthlyMortgagePayment * 12;
}, [monthlyMortgagePayment]);
// Rent Calculations (Year 1)
const grossPotentialRent = useMemo(() => {
return numUnits * avgMonthlyRentPerUnit * 12;
}, [numUnits, avgMonthlyRentPerUnit]);
const effectiveGrossIncome = useMemo(() => {
return (grossPotentialRent * (1 - vacancyRate / 100)) + otherIncomeAnnual - incomeReductionsAnnual;
}, [grossPotentialRent, vacancyRate, otherIncomeAnnual, incomeReductionsAnnual]);
// Expense Calculations (Year 1)
const propertyManagementFeeAmount = useMemo(() => {
if (usePercentageMode) return 0; // Show $0 in percentage mode
return effectiveGrossIncome * (propertyManagementFeePercentage / 100);
}, [usePercentageMode, effectiveGrossIncome, propertyManagementFeePercentage]);
const totalOperatingExpenses = useMemo(() => {
if (usePercentageMode) {
return effectiveGrossIncome * (operatingExpensePercentage / 100);
}
return propertyTaxes + insurance + propertyManagementFeeAmount + maintenanceRepairsAnnual + utilitiesAnnual + contractServicesAnnual + payrollAnnual + marketingAnnual + gAndAAnnual + otherExpensesAnnual;
}, [usePercentageMode, operatingExpensePercentage, effectiveGrossIncome, propertyTaxes, insurance, propertyManagementFeeAmount, maintenanceRepairsAnnual, utilitiesAnnual, contractServicesAnnual, payrollAnnual, marketingAnnual, gAndAAnnual, otherExpensesAnnual]);
const netOperatingIncome = useMemo(() => {
return effectiveGrossIncome - totalOperatingExpenses;
}, [effectiveGrossIncome, totalOperatingExpenses]);
const expenseRatio = useMemo(() => {
if (effectiveGrossIncome === 0) return 0;
return (totalOperatingExpenses / effectiveGrossIncome) * 100; // Percentage
}, [totalOperatingExpenses, effectiveGrossIncome]);
// Individual Operating Expense Line Items for Display (Year 1)
// These show $0 in percentage mode, actual values in detailed mode
const displayPropertyTaxes = useMemo(() => usePercentageMode ? 0 : propertyTaxes, [usePercentageMode, propertyTaxes]);
const displayInsurance = useMemo(() => usePercentageMode ? 0 : insurance, [usePercentageMode, insurance]);
const displayPropertyManagementFeeAmount = useMemo(() => usePercentageMode ? 0 : propertyManagementFeeAmount, [usePercentageMode, propertyManagementFeeAmount]);
const displayMaintenanceRepairsAnnual = useMemo(() => usePercentageMode ? 0 : maintenanceRepairsAnnual, [usePercentageMode, maintenanceRepairsAnnual]);
const displayUtilitiesAnnual = useMemo(() => usePercentageMode ? 0 : utilitiesAnnual, [usePercentageMode, utilitiesAnnual]);
const displayContractServicesAnnual = useMemo(() => usePercentageMode ? 0 : contractServicesAnnual, [usePercentageMode, contractServicesAnnual]);
const displayPayrollAnnual = useMemo(() => usePercentageMode ? 0 : payrollAnnual, [usePercentageMode, payrollAnnual]);
const displayMarketingAnnual = useMemo(() => usePercentageMode ? 0 : marketingAnnual, [usePercentageMode, marketingAnnual]);
const displayGAndAAnnual = useMemo(() => usePercentageMode ? 0 : gAndAAnnual, [usePercentageMode, gAndAAnnual]);
const displayOtherExpensesAnnual = useMemo(() => usePercentageMode ? 0 : otherExpensesAnnual, [usePercentageMode, otherExpensesAnnual]);
// Capital Reserve (Year 1)
const annualCapitalReserveTotal = useMemo(() => {
return capitalReservePerUnitAnnual * numUnits;
}, [capitalReservePerUnitAnnual, numUnits]);
const totalDeferredCapitalReserve = useMemo(() => {
return deferredCapitalReservePerUnit * numUnits;
}, [deferredCapitalReservePerUnit, numUnits]);
// Cash Flow & Returns (Year 1)
const cashFlowBeforeTax = useMemo(() => {
return netOperatingIncome - annualDebtService;
}, [netOperatingIncome, annualDebtService]);
const cashFlowAfterCapitalReserve = useMemo(() => {
return cashFlowBeforeTax - annualCapitalReserveTotal - totalDeferredCapitalReserve;
}, [cashFlowBeforeTax, annualCapitalReserveTotal, totalDeferredCapitalReserve]);
const capRate = useMemo(() => {
if (purchasePrice === 0) return 0;
return (netOperatingIncome / purchasePrice) * 100; // Percentage
}, [netOperatingIncome, purchasePrice]);
const cashOnCashReturn = useMemo(() => {
if (totalInitialInvestment === 0) return 0;
return (cashFlowAfterCapitalReserve / totalInitialInvestment) * 100; // Percentage
}, [cashFlowAfterCapitalReserve, totalInitialInvestment]);
// Debt Service Coverage Ratio (DSCR) Calculation
const debtServiceCoverageRatio = useMemo(() => {
if (annualDebtService === 0) return 0; // Avoid division by zero
return netOperatingIncome / annualDebtService;
}, [netOperatingIncome, annualDebtService]);
// --- Chart Data & Projections (Multi-Year) ---
const [chartData, setChartData] = useState<ChartDataPoint[]>([]);
const [breakEvenYear, setBreakEvenYear] = useState<number | null>(null);
const [projectedEquityAtHorizon, setProjectedEquityAtHorizon] = useState<number>(0);
const [roiAtHorizon, setRoiAtHorizon] = useState<number>(0);
const [irr, setIRR] = useState<number>(0);
const [overallGrade, setOverallGrade] = useState<string>('N/A');
const [gradeBreakdown, setGradeBreakdown] = useState<Record<string, number>>({});
const [detectedClassification, setDetectedClassification] = useState<{ assetClass: string; marketTier: string }>({
assetClass: 'b-class',
marketTier: 'tier-2'
});
const [year1LoanBalance, setYear1LoanBalance] = useState<number>(0);
const [actualGradingScore, setActualGradingScore] = useState<number>(0);
const [showMoreMenu, setShowMoreMenu] = useState(false);
const [toggleState, setToggleState] = useState<'clear' | 'defaults'>('clear'); // Initial state is 'clear' since form opens with defaults
const moreMenuRef = useRef<HTMLDivElement>(null);
// Function to save settings as blob
const saveSettings = () => {
// Reset the unsaved changes tracking since we're saving the scenario
if ((window as any).propertyAnalyzerSetSavingScenario) {
(window as any).propertyAnalyzerSetSavingScenario(true);
}
const settingsToSave = {
purchasePrice,
downPaymentPercentage,
interestRate,
loanStructure,
amortizationPeriodYears,
interestOnlyPeriodYears,
refinanceTermYears,
closingCostsPercentage,
dispositionCapRate,
numUnits,
avgMonthlyRentPerUnit,
vacancyRate,
annualRentalGrowthRate,
otherIncomeAnnual,
incomeReductionsAnnual,
propertyTaxes,
insurance,
propertyManagementFeePercentage,
maintenanceRepairsAnnual,
utilitiesAnnual,
contractServicesAnnual,
payrollAnnual,
marketingAnnual,
gAndAAnnual,
otherExpensesAnnual,
expenseGrowthRate,
capitalReservePerUnitAnnual,
deferredCapitalReservePerUnit,
holdingPeriodYears,
usePercentageMode,
operatingExpensePercentage,
savedAt: new Date().toISOString()
};
const blob = new Blob([JSON.stringify(settingsToSave, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
// Prompt user for filename
const defaultFilename = `property-analyzer-${new Date().toISOString().split('T')[0]}.json`;
const userFilename = prompt('Enter filename:', defaultFilename);
if (userFilename) {
a.download = userFilename.endsWith('.json') ? userFilename : userFilename + '.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// File was successfully saved, permanently reset the interaction flag
// This prevents warnings until user makes new changes
if ((window as any).propertyAnalyzerResetUserInteraction) {
(window as any).propertyAnalyzerResetUserInteraction();
}
}
URL.revokeObjectURL(url);
// Clean up the saving flag
if ((window as any).propertyAnalyzerSetSavingScenario) {
(window as any).propertyAnalyzerSetSavingScenario(false);
}
};
// --- Offer Management Functions ---
// Function to get current offer data for saving
const getCurrentOfferData = () => {
return {
// === INPUT PARAMETERS ===
purchasePrice,
downPaymentPercentage,
interestRate,
loanStructure,
amortizationPeriodYears,
interestOnlyPeriodYears,
refinanceTermYears,
closingCostsPercentage,
dispositionCapRate,
numUnits,
avgMonthlyRentPerUnit,
vacancyRate,
annualRentalGrowthRate,
otherIncomeAnnual,
incomeReductionsAnnual,
propertyTaxes,
insurance,
propertyManagementFeePercentage,
maintenanceRepairsAnnual,
utilitiesAnnual,
contractServicesAnnual,
payrollAnnual,
marketingAnnual,
gAndAAnnual,
otherExpensesAnnual,
expenseGrowthRate,
capitalReservePerUnitAnnual,
deferredCapitalReservePerUnit,
holdingPeriodYears,
// === CALCULATED RESULTS ===
projected_irr: irr.toFixed(2) + '%',
cash_on_cash_return: cashOnCashReturn.toFixed(2) + '%',
roi_at_horizon: roiAtHorizon.toFixed(2) + '%',
projected_equity_at_horizon: projectedEquityAtHorizon,
// Additional calculated fields
gross_operating_income: effectiveGrossIncome,
net_operating_income: netOperatingIncome,
debt_service_coverage_ratio: debtServiceCoverageRatio.toFixed(2),
cash_flow_before_tax: cashFlowBeforeTax,
cash_flow_after_capital_reserve: cashFlowAfterCapitalReserve,
annual_debt_service: annualDebtService,
loan_balance_year_1: calculateRemainingLoanBalance(1),
cap_rate_year_1: capRate.toFixed(2) + '%',
break_even_point: breakEvenYear ? `${breakEvenYear} years` : null,
total_acquisition_cost: purchasePrice + (purchasePrice * (closingCostsPercentage / 100)),
total_cash_invested: totalInitialInvestment,
down_payment_amount: downPaymentAmount,
loan_amount: loanAmount,
monthly_mortgage_payment: monthlyMortgagePayment,
expense_ratio_year_1: expenseRatio.toFixed(2) + '%',
usePercentageMode,
operatingExpensePercentage,
savedAt: new Date().toISOString()
};
};
// Function to load offer data
const loadOfferData = (offerData: any) => {
if (!offerData || typeof offerData !== 'object') return;
setPurchasePrice(offerData.purchasePrice ?? purchasePrice);
setDownPaymentPercentage(offerData.downPaymentPercentage ?? downPaymentPercentage);
setInterestRate(offerData.interestRate ?? interestRate);
setLoanStructure(offerData.loanStructure ?? loanStructure);
setAmortizationPeriodYears(offerData.amortizationPeriodYears ?? amortizationPeriodYears);
setInterestOnlyPeriodYears(offerData.interestOnlyPeriodYears ?? interestOnlyPeriodYears);
setRefinanceTermYears(offerData.refinanceTermYears ?? refinanceTermYears);
setClosingCostsPercentage(offerData.closingCostsPercentage ?? closingCostsPercentage);
setDispositionCapRate(offerData.dispositionCapRate ?? dispositionCapRate);
setNumUnits(offerData.numUnits ?? numUnits);
setAvgMonthlyRentPerUnit(offerData.avgMonthlyRentPerUnit ?? avgMonthlyRentPerUnit);
setVacancyRate(offerData.vacancyRate ?? vacancyRate);
setAnnualRentalGrowthRate(offerData.annualRentalGrowthRate ?? annualRentalGrowthRate);
setOtherIncomeAnnual(offerData.otherIncomeAnnual ?? otherIncomeAnnual);
setIncomeReductionsAnnual(offerData.incomeReductionsAnnual ?? incomeReductionsAnnual);
setPropertyTaxes(offerData.propertyTaxes ?? propertyTaxes);
setInsurance(offerData.insurance ?? insurance);
setPropertyManagementFeePercentage(offerData.propertyManagementFeePercentage ?? propertyManagementFeePercentage);
setMaintenanceRepairsAnnual(offerData.maintenanceRepairsAnnual ?? maintenanceRepairsAnnual);
setUtilitiesAnnual(offerData.utilitiesAnnual ?? utilitiesAnnual);
setContractServicesAnnual(offerData.contractServicesAnnual ?? contractServicesAnnual);
setPayrollAnnual(offerData.payrollAnnual ?? payrollAnnual);
setMarketingAnnual(offerData.marketingAnnual ?? marketingAnnual);
setGAndAAnnual(offerData.gAndAAnnual ?? gAndAAnnual);
setOtherExpensesAnnual(offerData.otherExpensesAnnual ?? otherExpensesAnnual);
setExpenseGrowthRate(offerData.expenseGrowthRate ?? expenseGrowthRate);
setCapitalReservePerUnitAnnual(offerData.capitalReservePerUnitAnnual ?? capitalReservePerUnitAnnual);
setDeferredCapitalReservePerUnit(offerData.deferredCapitalReservePerUnit ?? deferredCapitalReservePerUnit);
setHoldingPeriodYears(offerData.holdingPeriodYears ?? holdingPeriodYears);
setUsePercentageMode(offerData.usePercentageMode ?? usePercentageMode);
setOperatingExpensePercentage(offerData.operatingExpensePercentage ?? operatingExpensePercentage);
};
// Handle viewing all user offers
const handleViewOffers = async () => {
if (!currentUser) {
alert('Please log in to view offers.');
return;
}
try {
// Fetch offers from the offer_scenarios table (all user offers)
const response = await fetch('/api/offer-scenarios?all=true');
if (!response.ok) {
throw new Error('Failed to fetch offers');
}
const data = await response.json();
// Transform the data to match our UI format
const transformedOffers = data.scenarios.map((offer: any) => ({
id: offer.id,
name: offer.offer_name || `Offer ${offer.id}`,
description: offer.offer_description || 'No description',
property_address: offer.saved_properties?.address_full || 'Unknown Address',
offer_amount: offer.offer_data?.purchasePrice ? `$${parseInt(offer.offer_data.purchasePrice).toLocaleString()}` : 'N/A',
created_date: new Date(offer.created_at).toLocaleDateString(),
property_id: offer.property_id,
offer_data: offer.offer_data
}));
setSelectedPropertyOffers(transformedOffers);
setShowOffersModal(true);
} catch (error) {
console.error('Error fetching offers:', error);
alert('Failed to load offers. Please try again.');
}
};
const handleOfferSelection = (offer: any) => {
loadOfferData(offer.offer_data);
setLoadedOfferName(offer.name);
setShowOffersModal(false);
};
const handleDeleteOffer = async (offerId: string) => {
showDelete(
'Are you sure you want to delete this offer? This action cannot be undone.',
async () => {
try {
const response = await fetch(`/api/offer-scenarios/${offerId}`, {
method: 'DELETE'
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || 'Failed to delete offer');
}
// Remove from local state
setSelectedPropertyOffers(prev => prev.filter(offer => offer.id !== offerId));
} catch (error) {
console.error('Error deleting offer:', error);
showError('Failed to delete offer. Please try again.');
}
}
);
};
// Handle saving analysis to database
// Check if analysis name already exists
const checkDuplicateOfferName = async (offerName: string, propertyId: string): Promise<boolean> => {
try {
console.log('Checking for duplicate analysis name:', offerName, 'for property:', propertyId);
const response = await fetch(`/api/offer-scenarios?propertyId=${propertyId}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
if (!response.ok) {
console.log('API response not ok:', response.status);
return false; // If we can't check, proceed with save
}
const data = await response.json();
console.log('Existing scenarios:', data.scenarios);
const isDuplicate = data.scenarios?.some((scenario: any) =>
scenario.offer_name?.toLowerCase() === offerName.toLowerCase()
) || false;
console.log('Is duplicate?', isDuplicate);
return isDuplicate;
} catch (error) {
console.error('Error checking for duplicate offer name:', error);
return false; // If error, proceed with save
}
};
const handleSaveOffer = async (offerName: string, offerDescription: string) => {
if (submissionId) {
// For pricing variations, skip duplicate checking and go straight to save
await performSaveOffer(offerName, offerDescription);
setShowSaveOfferModal(false);
// Redirect back to the fund browse page where they started
router.push(`/fund/browse/${submissionId}`);
return;
}
// Original offer scenario logic - requires propertyId
if (!propertyId) {
throw new Error('Property ID is required to save offers');
}
// Get the correct property_id from saved_properties table for duplicate check
const favoritesResponse = await fetch('/api/favorites', {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
if (!favoritesResponse.ok) {
throw new Error('Failed to fetch saved properties');
}
const favoritesData = await favoritesResponse.json();
const savedProperty = favoritesData.favorites?.find((f: any) =>
f.property_data?.id === propertyId
);
if (!savedProperty || !savedProperty.property_id) {
throw new Error(`Property UUID ${propertyId} not found in favorites. This property must be saved to your favorites before creating offer scenarios.`);
}
const actualPropertyId = savedProperty.property_id;
// Check for duplicate offer name using the actual property_id
const isDuplicate = await checkDuplicateOfferName(offerName, actualPropertyId);
if (isDuplicate) {
// Store the pending offer data and show warning dialog
setPendingOfferData({ name: offerName, description: offerDescription });
// Close save modal first, then show duplicate alert
setShowSaveOfferModal(false);
// Use setTimeout to ensure save modal closes before duplicate alert appears
setTimeout(() => setShowDuplicateAlert(true), 0);
return;
}
// If no duplicate, proceed with save
await performSaveOffer(offerName, offerDescription);
// SaveOfferModal will close itself after successful save
};
// Handle user choice to overwrite existing offer
const handleConfirmOverwrite = async () => {
if (pendingOfferData) {
try {
// Perform the save without duplicate check (we already know we want to overwrite)
await performSaveOffer(pendingOfferData.name, pendingOfferData.description);
// Clear everything at once to minimize visual glitches
setPendingOfferData(null);
setShowDuplicateAlert(false);
setShowSaveOfferModal(false);
} catch (error) {
console.error('Error during overwrite save:', error);
// If there's an error, close duplicate and show save modal
setShowDuplicateAlert(false);
setShowSaveOfferModal(true);
}
}
};
// Handle user choice to cancel overwrite
const handleCancelOverwrite = () => {
setPendingOfferData(null);
setShowDuplicateAlert(false);
setShowSaveOfferModal(true); // Re-open the save modal so user can choose a different name
};
// Separate function to actually perform the save
const performSaveOffer = async (offerName: string, offerDescription: string) => {
// Check if we're saving a pricing variation (from submission) or regular offer scenario
// submissionId is available from state if this was opened from a fund submission
if (submissionId) {
// Check if we're updating an existing variation or creating a new one
if (variationId) {
// Update existing pricing variation
const response = await fetch(`/api/pricing-variations/${variationId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
analysisName: offerName,
description: offerDescription,
scenarioData: getCurrentOfferData()
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Failed to update pricing variation');
}
} else {
// Create new pricing variation - no propertyId needed
const response = await fetch('/api/pricing-variations', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
submissionId,
analysisName: offerName,
description: offerDescription,
scenarioData: getCurrentOfferData()
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Failed to save pricing variation');
}
}
} else {
// Original offer scenario save logic - propertyId required
if (!propertyId) {
throw new Error('Property ID is required to save offers');
}
// Get the correct property_id from saved_properties table
const favoritesResponse = await fetch('/api/favorites', {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
if (!favoritesResponse.ok) {
throw new Error('Failed to fetch saved properties');
}
const favoritesData = await favoritesResponse.json();
console.log('Looking for UUID:', propertyId);
// Find the saved property record where the internal UUID matches
const savedProperty = favoritesData.favorites?.find((f: any) =>
f.property_data?.id === propertyId
);
console.log('Found saved property:', savedProperty);
if (!savedProperty || !savedProperty.property_id) {
console.error('Available property_data IDs:', favoritesData.favorites?.map((f: any) => f.property_data?.id));
throw new Error(`Property UUID ${propertyId} not found in favorites. This property must be saved to your favorites before creating offer scenarios.`);
}
const actualPropertyId = savedProperty.property_id;
console.log('Using actual property_id:', actualPropertyId);
const response = await fetch('/api/offer-scenarios', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
propertyId: actualPropertyId, // Use the property_id field from saved_properties
offerName,
offerDescription,
offerData: getCurrentOfferData()
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Failed to save offer');
}
}
// Reset the unsaved changes tracking since we're saving the scenario
if ((window as any).propertyAnalyzerSetSavingScenario) {
(window as any).propertyAnalyzerSetSavingScenario(true);
}
// File was successfully saved, permanently reset the interaction flag
if ((window as any).propertyAnalyzerResetUserInteraction) {
(window as any).propertyAnalyzerResetUserInteraction();
}
// Clean up the saving flag
if ((window as any).propertyAnalyzerSetSavingScenario) {
(window as any).propertyAnalyzerSetSavingScenario(false);
}
};
// Property data for 10-year cash flow report (moved into Charlie's Analysis)
const propertyData = useMemo(() => ({
propertyStreet,
propertyCity,
propertyState,
purchasePrice,
downPaymentPercentage,
closingCostsPercentage,
interestRate,
amortizationPeriodYears,
loanStructure,
interestOnlyPeriodYears,
numUnits,
avgMonthlyRentPerUnit,
vacancyRate,
annualRentalGrowthRate,
otherIncomeAnnual,
incomeReductionsAnnual,
propertyTaxes: displayPropertyTaxes,
insurance: displayInsurance,
propertyManagementFeePercentage,
maintenanceRepairsAnnual: displayMaintenanceRepairsAnnual,
utilitiesAnnual: displayUtilitiesAnnual,
contractServicesAnnual: displayContractServicesAnnual,
payrollAnnual: displayPayrollAnnual,
marketingAnnual: displayMarketingAnnual,
gAndAAnnual: displayGAndAAnnual,
otherExpensesAnnual: displayOtherExpensesAnnual,
expenseGrowthRate,
usePercentageMode,
operatingExpensePercentage,
capitalReservePerUnitAnnual,
holdingPeriodYears
}), [
propertyStreet, propertyCity, propertyState,
purchasePrice, downPaymentPercentage, closingCostsPercentage, interestRate,
amortizationPeriodYears, loanStructure, interestOnlyPeriodYears, numUnits,
avgMonthlyRentPerUnit, vacancyRate, annualRentalGrowthRate, otherIncomeAnnual,
incomeReductionsAnnual, displayPropertyTaxes, displayInsurance, propertyManagementFeePercentage,
displayMaintenanceRepairsAnnual, displayUtilitiesAnnual, displayContractServicesAnnual, displayPayrollAnnual,
displayMarketingAnnual, displayGAndAAnnual, displayOtherExpensesAnnual, expenseGrowthRate,
usePercentageMode, operatingExpensePercentage, capitalReservePerUnitAnnual, holdingPeriodYears
]);
// Function to handle file loading
const handleFileLoad = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
try {
const content = e.target?.result as string;
const parsed = JSON.parse(content);
if (parsed && typeof parsed === "object") {
setPurchasePrice(parsed.purchasePrice ?? 0);
setDownPaymentPercentage(parsed.downPaymentPercentage ?? 0);
setInterestRate(parsed.interestRate ?? 0);
setLoanStructure(parsed.loanStructure ?? 'amortizing');
setAmortizationPeriodYears(parsed.amortizationPeriodYears ?? 30);
setInterestOnlyPeriodYears(parsed.interestOnlyPeriodYears ?? 10);
setRefinanceTermYears(parsed.refinanceTermYears ?? 25);
setClosingCostsPercentage(parsed.closingCostsPercentage ?? 0);
setDispositionCapRate(parsed.dispositionCapRate ?? 0);
setNumUnits(parsed.numUnits ?? 0);
setAvgMonthlyRentPerUnit(parsed.avgMonthlyRentPerUnit ?? 0);
setVacancyRate(parsed.vacancyRate ?? 0);
setAnnualRentalGrowthRate(parsed.annualRentalGrowthRate ?? 0);
setOtherIncomeAnnual(parsed.otherIncomeAnnual ?? 0);
setIncomeReductionsAnnual(parsed.incomeReductionsAnnual ?? 0);
setPropertyTaxes(parsed.propertyTaxes ?? 0);
setInsurance(parsed.insurance ?? 0);
setPropertyManagementFeePercentage(parsed.propertyManagementFeePercentage ?? 0);
setMaintenanceRepairsAnnual(parsed.maintenanceRepairsAnnual ?? 0);
setUtilitiesAnnual(parsed.utilitiesAnnual ?? 0);
setContractServicesAnnual(parsed.contractServicesAnnual ?? 0);
setPayrollAnnual(parsed.payrollAnnual ?? 0);
setMarketingAnnual(parsed.marketingAnnual ?? 0);
setGAndAAnnual(parsed.gAndAAnnual ?? 0);
setOtherExpensesAnnual(parsed.otherExpensesAnnual ?? 0);
setExpenseGrowthRate(parsed.expenseGrowthRate ?? 0);
setCapitalReservePerUnitAnnual(parsed.capitalReservePerUnitAnnual ?? 0);
setDeferredCapitalReservePerUnit(parsed.deferredCapitalReservePerUnit ?? 0);
setHoldingPeriodYears(parsed.holdingPeriodYears ?? 1);
setUsePercentageMode(parsed.usePercentageMode ?? false);
setOperatingExpensePercentage(parsed.operatingExpensePercentage ?? 45);
alert('Scenario loaded successfully!');
} else {
alert('Invalid file format');
}
} catch (error) {
alert('Error loading file: Invalid JSON format');
}
};
reader.readAsText(file);
// Reset the input so the same file can be loaded again if needed
event.target.value = '';
};
// Close dropdown menu when clicking outside
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (moreMenuRef.current && !moreMenuRef.current.contains(e.target as Node)) {
setShowMoreMenu(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
// Detect any changes on the page and warn before leaving