1use crate::config::CliConfig;
4use btctax_adapters::FileReport;
5use btctax_core::conventions::{tax_date, Sat, Usd, TRANSITION_DATE};
6use btctax_core::defensive::discovery::{Shortfall, Triage};
7use btctax_core::defensive::{
8 Advisory, DefensiveFilingView, PoolShort, SavingFlavor, TrancheRow, TrancheStatus,
9};
10use btctax_core::persistence::ImportReport;
11use btctax_core::DonationDetails;
12use btctax_core::{
13 conservation_report, disposal_compliance, form_8283, form_8949, schedule_d,
14 year_donation_deduction, BasisSource, Blocker, BlockerKind, ComplianceStatus,
15 ConservationReport, DisposalCompliance, DisposalLeg, DisposeKind, EventId, EventPayload,
16 Form8283HowAcquired, Form8283Section, Form8949Box, Form8949Part, GiftZone, HarvestReport,
17 HarvestStatus, HarvestTarget, InboundClass, IncomeKind, LedgerEvent, LedgerState, LotMethod,
18 LtcgBracket, OutflowClass, RemovalKind, RemovalLeg, ScheduleDTotals, SeTaxResult, SellReport,
19 SellStatus, Severity, TaxDate, Term, WalletId,
20};
21use btctax_store::fsperms;
22use csv::Writer;
23use std::collections::{BTreeMap, BTreeSet};
24use std::fmt::Write as _;
25use std::path::Path;
26
27fn fmt_money(d: btctax_core::conventions::Usd) -> String {
40 format!("{d:.2}")
41}
42
43fn basis_source_tag(bs: BasisSource) -> &'static str {
48 match bs {
49 BasisSource::ExchangeProvided => "exchange",
50 BasisSource::ComputedFromCost => "cost",
51 BasisSource::FmvAtIncome => "income_fmv",
52 BasisSource::CarriedFromTransfer => "transferred",
53 BasisSource::GiftCarryover => "gift_carryover",
54 BasisSource::GiftFmvFallback => "gift_fmv_fallback",
55 BasisSource::SafeHarborAllocated => "safe_harbor",
56 BasisSource::ReconstructedPerWallet => "reconstructed",
57 BasisSource::SelfTransferInbound => "self_transfer_in",
58 BasisSource::EstimatedConservative => "estimated_conservative",
59 }
60}
61
62fn pseudo_tag(pseudo: bool) -> &'static str {
68 if pseudo {
69 " [PSEUDO]"
70 } else {
71 ""
72 }
73}
74
75fn dispose_kind_tag(dk: DisposeKind) -> &'static str {
76 match dk {
77 DisposeKind::Sell => "sell",
78 DisposeKind::Spend => "spend",
79 }
80}
81
82fn income_kind_tag(ik: IncomeKind) -> &'static str {
83 match ik {
84 IncomeKind::Mining => "mining",
85 IncomeKind::Staking => "staking",
86 IncomeKind::Interest => "interest",
87 IncomeKind::Airdrop => "airdrop",
88 IncomeKind::Reward => "reward",
89 }
90}
91
92pub fn describe_inbound_class(c: &InboundClass) -> String {
99 match c {
100 InboundClass::Income {
101 kind,
102 fmv,
103 business,
104 } => {
105 let mut s = format!("income {}", income_kind_tag(*kind));
106 if let Some(v) = fmv {
107 let _ = write!(s, ", fmv ${}", fmt_money(*v));
108 }
109 if *business {
110 s.push_str(", business");
111 }
112 s
113 }
114 InboundClass::GiftReceived {
115 donor_basis,
116 donor_acquired_at,
117 fmv_at_gift,
118 } => {
119 let mut s = format!("gift received, fmv ${}", fmt_money(*fmv_at_gift));
120 if let Some(b) = donor_basis {
121 let _ = write!(s, ", donor-basis ${}", fmt_money(*b));
122 }
123 if let Some(d) = donor_acquired_at {
124 let _ = write!(s, ", donor-acquired {d}");
125 }
126 s
127 }
128 InboundClass::SelfTransferMine { basis, acquired_at } => {
129 let basis_s = match basis {
132 Some(v) => format!("${}", fmt_money(*v)),
133 None => "default".to_string(),
134 };
135 let acq_s = match acquired_at {
136 Some(d) => d.to_string(),
137 None => "default".to_string(),
138 };
139 format!("self-transfer (mine), basis {basis_s}, acquired {acq_s}")
140 }
141 }
142}
143
144pub fn describe_outflow_class(c: &OutflowClass) -> String {
147 match c {
148 OutflowClass::Dispose { kind } => dispose_kind_tag(*kind).to_string(),
149 OutflowClass::GiftOut => "gift".to_string(),
150 OutflowClass::Donate { appraisal_required } => {
151 if *appraisal_required {
152 "donate (appraisal required)".to_string()
153 } else {
154 "donate".to_string()
155 }
156 }
157 }
158}
159
160fn gift_zone_tag(gz: GiftZone) -> &'static str {
161 match gz {
162 GiftZone::Gain => "gain",
163 GiftZone::Loss => "loss",
164 GiftZone::NoGainNoLoss => "no_gain_no_loss",
165 }
166}
167
168fn removal_kind_tag(rk: RemovalKind) -> &'static str {
169 match rk {
170 RemovalKind::Gift => "gift",
171 RemovalKind::Donation => "donation",
172 }
173}
174
175fn term_tag(t: Term) -> &'static str {
177 match t {
178 Term::ShortTerm => "short",
179 Term::LongTerm => "long",
180 }
181}
182
183fn form8949_part_tag(p: Form8949Part) -> &'static str {
185 match p {
186 Form8949Part::ShortTerm => "ST",
187 Form8949Part::LongTerm => "LT",
188 }
189}
190
191fn form8949_box_tag(b: Form8949Box) -> &'static str {
196 match b {
197 Form8949Box::C => "C",
198 Form8949Box::F => "F",
199 Form8949Box::I => "I",
200 Form8949Box::L => "L",
201 }
202}
203
204fn form8283_section_tag(s: Form8283Section) -> &'static str {
207 match s {
208 Form8283Section::A => "A",
209 Form8283Section::B => "B",
210 }
211}
212
213fn form8283_how_acquired_tag(h: Form8283HowAcquired) -> &'static str {
216 match h {
217 Form8283HowAcquired::Purchased => "Purchased",
218 Form8283HowAcquired::Gift => "Gift",
219 Form8283HowAcquired::Other => "Other",
220 Form8283HowAcquired::Review => "Review",
221 }
222}
223
224fn compliance_status_tag(cs: &ComplianceStatus) -> String {
233 match cs {
234 ComplianceStatus::StandingOrder { effective_from } => {
235 format!("standing_order:{effective_from}")
236 }
237 ComplianceStatus::Contemporaneous => "contemporaneous".into(),
238 ComplianceStatus::AttestedRecording => "attested_recording".into(),
239 ComplianceStatus::NonCompliant => "non_compliant".into(),
240 }
241}
242
243pub fn render_file_reports(reports: &[FileReport], import: &ImportReport) -> String {
245 let mut out = String::new();
246 let _ = writeln!(out, "Import:");
247 for r in reports {
248 let _ = writeln!(
249 out,
250 " {} [{}]: parsed {} rows -> {} BTC events ({} dropped no-BTC, {} unclassified)",
251 r.source.tag(),
252 r.label,
253 r.parsed_rows,
254 r.btc_events,
255 r.dropped_no_btc,
256 r.unclassified
257 );
258 }
259 let _ = writeln!(
260 out,
261 " appended {} | duplicates {} | NEW import-conflicts {}",
262 import.appended, import.duplicates, import.conflicts
263 );
264 if import.conflicts > 0 {
265 let _ = writeln!(
266 out,
267 " ! resolve conflicts with `reconcile accept-conflict <id>` or `reject-conflict <id>` (see `verify`)"
268 );
269 }
270 out
271}
272
273pub fn wallet_label(w: &WalletId) -> String {
275 match w {
276 WalletId::Exchange { provider, account } => format!("exchange:{provider}:{account}"),
277 WalletId::SelfCustody { label } => format!("self:{label}"),
278 }
279}
280
281pub fn no_lots_message(wallet: &WalletId, at: TaxDate, available: Sat, requested: Sat) -> String {
288 if available == 0 {
289 format!("no BTC available in {} as of {}", wallet_label(wallet), at)
290 } else {
291 format!(
292 "only {} BTC available in {} as of {} (requested {} BTC)",
293 fmt_btc(available),
294 wallet_label(wallet),
295 at,
296 fmt_btc(requested),
297 )
298 }
299}
300
301fn disposal_year(d: &btctax_core::Disposal) -> i32 {
302 d.disposed_at.year()
303}
304
305pub fn render_report(state: &LedgerState, year: Option<i32>) -> String {
307 let mut out = String::new();
308 let yr = |y: i32| year.is_none_or(|f| f == y); let _ = writeln!(out, "Holdings (per wallet):");
311 if state.holdings_by_wallet.is_empty() {
312 let _ = writeln!(out, " none");
313 }
314 for (w, sat) in &state.holdings_by_wallet {
315 let _ = writeln!(out, " {}: {} sat", wallet_label(w), sat);
316 }
317 if state.stats.sigma_pending > 0 {
320 let n = state.pending_reconciliation.len();
321 let plural = if n == 1 { "transfer" } else { "transfers" };
322 let _ = writeln!(
323 out,
324 " Pending: {} BTC ({n} unreconciled {plural} — see `btctax verify`)",
325 fmt_btc(state.stats.sigma_pending),
326 );
327 }
328
329 let _ = writeln!(out, "Lots:");
330 if state.lots.is_empty() {
331 let _ = writeln!(out, " none");
332 }
333 for l in &state.lots {
334 let _ = writeln!(
335 out,
336 " {}#{} {} remaining {} sat | basis {} ({}){}{}",
337 l.lot_id.origin_event_id.canonical(),
338 l.lot_id.split_sequence,
339 wallet_label(&l.wallet),
340 l.remaining_sat,
341 l.usd_basis,
342 basis_source_tag(l.basis_source),
343 if l.basis_pending {
344 " [basis pending]"
345 } else {
346 ""
347 },
348 pseudo_tag(l.pseudo),
349 );
350 }
351
352 let label = match year {
353 Some(y) => format!("(year {y})"),
354 None => "(all years)".to_string(),
355 };
356
357 let disposals: Vec<_> = state
358 .disposals
359 .iter()
360 .filter(|d| yr(disposal_year(d)))
361 .collect();
362 if disposals.is_empty() {
363 let _ = writeln!(out, "Disposals {}: none", label);
364 } else {
365 let _ = writeln!(out, "Disposals {}:", label);
366 for d in disposals {
367 let _ = writeln!(
368 out,
369 " {} @ {} ({})",
370 dispose_kind_tag(d.kind),
371 d.disposed_at,
372 d.event.canonical()
373 );
374 for leg in &d.legs {
375 render_disposal_leg(&mut out, leg);
376 }
377 }
378 }
379
380 let removals: Vec<_> = state
381 .removals
382 .iter()
383 .filter(|r| yr(r.removed_at.year()))
384 .collect();
385 if removals.is_empty() {
386 let _ = writeln!(out, "Removals {}: none", label);
387 } else {
388 let _ = writeln!(out, "Removals {}:", label);
389 for r in removals {
390 let deduction_tag = match r.claimed_deduction {
391 Some(d) => format!(" [claimed deduction {}]", fmt_money(d)),
392 None => String::new(),
393 };
394 let _ = writeln!(
395 out,
396 " {} @ {} ({}){}",
397 removal_kind_tag(r.kind),
398 r.removed_at,
399 r.event.canonical(),
400 deduction_tag
401 );
402 for leg in &r.legs {
403 render_removal_leg(&mut out, leg);
404 }
405 }
406 }
407
408 let income: Vec<_> = state
409 .income_recognized
410 .iter()
411 .filter(|i| yr(i.recognized_at.year()))
412 .collect();
413 if income.is_empty() {
414 let _ = writeln!(out, "Income {}: none", label);
415 } else {
416 let _ = writeln!(out, "Income {}:", label);
417 for i in income {
418 let _ = writeln!(
419 out,
420 " {} @ {} {} sat = {} USD{}{}",
421 income_kind_tag(i.kind),
422 i.recognized_at,
423 i.sat,
424 i.usd_fmv,
425 if i.business { " [business]" } else { "" },
426 pseudo_tag(i.pseudo), );
428 }
429 }
430
431 let charitable_total: btctax_core::conventions::Usd = state
434 .removals
435 .iter()
436 .filter(|r| yr(r.removed_at.year()) && r.kind == RemovalKind::Donation)
437 .filter_map(|r| r.claimed_deduction)
438 .sum();
439 let _ = writeln!(
440 out,
441 "Charitable deduction {} (Schedule A itemized) — BEFORE §170(b) AGI limits / carryover: {}",
442 label,
443 fmt_money(charitable_total)
444 );
445
446 out
447}
448
449fn render_disposal_leg(out: &mut String, leg: &DisposalLeg) {
450 let zone = leg
451 .gift_zone
452 .map(|z| format!(" gift-zone {}", gift_zone_tag(z)))
453 .unwrap_or_default();
454 let _ = writeln!(
455 out,
456 " {} sat: proceeds {} basis {} gain {} {}{}{}",
457 leg.sat,
458 leg.proceeds,
459 leg.basis,
460 leg.gain,
461 term_tag(leg.term),
462 zone,
463 pseudo_tag(leg.pseudo),
464 );
465}
466
467fn render_removal_leg(out: &mut String, leg: &RemovalLeg) {
468 let _ = writeln!(
469 out,
470 " {} sat: basis {} fmv {} {} (zero gain){}",
471 leg.sat,
472 leg.basis,
473 leg.fmv_at_transfer,
474 term_tag(leg.term),
475 pseudo_tag(leg.pseudo),
476 );
477}
478
479pub fn filing_status_tag(fs: btctax_core::FilingStatus) -> &'static str {
487 use btctax_core::FilingStatus::*;
488 match fs {
489 Single => "single",
490 Mfj => "mfj",
491 Mfs => "mfs",
492 HoH => "hoh",
493 Qss => "qss",
494 }
495}
496
497pub fn fee_treatment_display(t: btctax_core::FeeTreatment) -> &'static str {
501 match t {
502 btctax_core::FeeTreatment::TreatmentC => "non-taxable, basis carries (TP8 c)",
503 btctax_core::FeeTreatment::TreatmentB => "taxable mini-disposition (TP8 b)",
504 }
505}
506
507pub fn lot_method_display(m: LotMethod) -> &'static str {
508 match m {
509 LotMethod::Fifo => "FIFO",
510 LotMethod::Lifo => "LIFO",
511 LotMethod::Hifo => "HIFO",
512 }
513}
514
515#[derive(Debug, Clone)]
517pub struct ElectionLine {
518 pub recorded: TaxDate,
519 pub effective_from: TaxDate,
520 pub method: LotMethod,
521 pub wallet: Option<WalletId>,
523 pub note: &'static str,
525}
526
527pub fn voided_targets(events: &[LedgerEvent]) -> BTreeSet<EventId> {
530 events
531 .iter()
532 .filter_map(|e| match &e.payload {
533 EventPayload::VoidDecisionEvent(v) => Some(v.target_event_id.clone()),
534 _ => None,
535 })
536 .collect()
537}
538
539pub fn method_election_lines(
543 events: &[LedgerEvent],
544 voided: &BTreeSet<EventId>,
545) -> Vec<ElectionLine> {
546 let mut election_events: Vec<(u64, &LedgerEvent)> = events
547 .iter()
548 .filter_map(|e| {
549 if let EventId::Decision { seq } = e.id {
550 if matches!(e.payload, EventPayload::MethodElection(_)) {
551 return Some((seq, e));
552 }
553 }
554 None
555 })
556 .collect();
557 election_events.sort_by_key(|(s, _)| *s);
558
559 election_events
560 .iter()
561 .map(|(_, e)| {
562 let EventPayload::MethodElection(me) = &e.payload else {
563 unreachable!("filtered to MethodElection above")
564 };
565 let recorded = tax_date(e.utc_timestamp, e.original_tz);
566 let note = if voided.contains(&e.id) {
567 "voided"
568 } else if me.effective_from < TRANSITION_DATE || me.effective_from < recorded {
569 "backdated/ignored"
570 } else {
571 "in force"
572 };
573 ElectionLine {
574 recorded,
575 effective_from: me.effective_from,
576 method: me.method,
577 wallet: me.wallet.clone(),
578 note,
579 }
580 })
581 .collect()
582}
583
584#[derive(Debug, Clone)]
586pub struct VerifyReport {
587 pub conservation: ConservationReport,
588 pub hard: Vec<Blocker>,
589 pub advisory: Vec<Blocker>,
590 pub pending: usize,
591 pub unknown_basis_inbounds: usize,
592 pub safe_harbor: String,
593 pub declared_pre2025_method: LotMethod,
595 pub pre2025_method_attested: bool,
596 pub elections: Vec<ElectionLine>,
598 pub selection_count: usize,
600 pub compliance: Vec<DisposalCompliance>,
602 pub drift: Vec<String>,
607}
608
609impl VerifyReport {
610 pub fn has_hard_blockers(&self) -> bool {
613 !self.hard.is_empty()
614 }
615}
616
617fn safe_harbor_status(state: &LedgerState, _events: &[LedgerEvent]) -> String {
628 let effective_path_b = state
631 .lots
632 .iter()
633 .any(|l| l.basis_source == BasisSource::SafeHarborAllocated)
634 || state.disposals.iter().any(|d| {
635 d.legs
636 .iter()
637 .any(|leg| leg.basis_source == BasisSource::SafeHarborAllocated)
638 })
639 || state.removals.iter().any(|r| {
640 r.legs
641 .iter()
642 .any(|leg| leg.basis_source == BasisSource::SafeHarborAllocated)
643 });
644 let unconservable = state
645 .blockers
646 .iter()
647 .any(|b| b.kind == BlockerKind::SafeHarborUnconservable);
648 let timebar = state
649 .blockers
650 .iter()
651 .any(|b| b.kind == BlockerKind::SafeHarborTimebar);
652 if unconservable {
656 "Path B allocation FAILS conservation/eligibility (hard, §7.4) — fix the allocation"
657 .to_string()
658 } else if effective_path_b {
659 "Path B safe-harbor allocation is effective (§7.4)".to_string()
660 } else if timebar {
661 "Path B time-barred -> using Path A (advisory); `reconcile safe-harbor attest` if timely in your books".to_string()
662 } else {
663 "Path A (actual per-wallet reconstruction; default, no election)".to_string()
664 }
665}
666
667pub fn build_verify(
668 state: &LedgerState,
669 events: &[LedgerEvent],
670 prices: &dyn btctax_core::price::PriceProvider,
671 cli: &CliConfig,
672) -> VerifyReport {
673 let conservation = conservation_report(state);
674 let mut hard = Vec::new();
675 let mut advisory = Vec::new();
676 for b in &state.blockers {
677 match b.kind.severity() {
678 Severity::Hard => hard.push(b.clone()),
679 Severity::Advisory => advisory.push(b.clone()),
680 }
681 }
682 let unknown_basis_inbounds = state
683 .blockers
684 .iter()
685 .filter(|b| b.kind == BlockerKind::UnknownBasisInbound)
686 .count();
687
688 let voided = voided_targets(events);
690
691 let elections = method_election_lines(events, &voided);
693
694 let selection_count = events
699 .iter()
700 .filter(|e| matches!(e.payload, EventPayload::LotSelection(_)) && !voided.contains(&e.id))
701 .count();
702
703 let compliance = disposal_compliance(events, state);
705
706 let drift = btctax_core::conservative_promote::promote_drift_advisory(events, prices);
709
710 VerifyReport {
711 conservation,
712 hard,
713 advisory,
714 pending: state.pending_reconciliation.len(),
715 unknown_basis_inbounds,
716 safe_harbor: safe_harbor_status(state, events),
717 declared_pre2025_method: cli.pre2025_method,
718 pre2025_method_attested: cli.pre2025_method_attested,
719 elections,
720 selection_count,
721 compliance,
722 drift,
723 }
724}
725
726pub fn write_csv_exports(
738 out_dir: &Path,
739 state: &LedgerState,
740 tax_year: Option<i32>,
741 se_result: Option<&SeTaxResult>,
742 donation_details: &BTreeMap<EventId, DonationDetails>,
743) -> Result<(), crate::CliError> {
744 fsperms::mkdir_owner_only(out_dir)?;
745
746 let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("lots.csv"))?);
747 w.write_record([
748 "origin_event",
749 "split",
750 "wallet",
751 "acquired_at",
752 "remaining_sat",
753 "usd_basis",
754 "basis_source",
755 "basis_pending",
756 ])?;
757 for l in &state.lots {
758 w.write_record([
759 l.lot_id.origin_event_id.canonical(),
760 l.lot_id.split_sequence.to_string(),
761 wallet_label(&l.wallet),
762 l.acquired_at.to_string(),
763 l.remaining_sat.to_string(),
764 l.usd_basis.to_string(),
765 basis_source_tag(l.basis_source).to_string(),
766 l.basis_pending.to_string(),
767 ])?;
768 }
769 w.flush()?;
770
771 let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("disposals.csv"))?);
772 w.write_record([
773 "event",
774 "kind",
775 "disposed_at",
776 "lot",
777 "sat",
778 "proceeds",
779 "basis",
780 "gain",
781 "term",
782 "gift_zone",
783 "acquired_at",
784 "wallet",
785 ])?;
786 for d in &state.disposals {
787 for leg in &d.legs {
788 w.write_record([
789 d.event.canonical(),
790 dispose_kind_tag(d.kind).to_string(),
791 d.disposed_at.to_string(),
792 format!(
793 "{}#{}",
794 leg.lot_id.origin_event_id.canonical(),
795 leg.lot_id.split_sequence
796 ),
797 leg.sat.to_string(),
798 leg.proceeds.to_string(),
799 leg.basis.to_string(),
800 leg.gain.to_string(),
801 term_tag(leg.term).to_string(),
802 leg.gift_zone
803 .map(|z| gift_zone_tag(z).to_string())
804 .unwrap_or_default(),
805 leg.acquired_at.to_string(),
806 wallet_label(&leg.wallet),
807 ])?;
808 }
809 }
810 w.flush()?;
811
812 let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("removals.csv"))?);
813 w.write_record([
820 "event",
821 "kind",
822 "removed_at",
823 "lot",
824 "sat",
825 "basis",
826 "fmv_at_transfer",
827 "term",
828 "acquired_at",
829 "claimed_deduction",
830 "donee",
831 ])?;
832 for r in &state.removals {
833 let deduction_first = r
834 .claimed_deduction
835 .map(|d| d.to_string())
836 .unwrap_or_default();
837 let donee_cell = r.donee.clone().unwrap_or_default();
838 for (leg_idx, leg) in r.legs.iter().enumerate() {
839 let deduction_cell: &str = if leg_idx == 0 { &deduction_first } else { "" };
842 w.write_record([
843 r.event.canonical(),
844 removal_kind_tag(r.kind).to_string(),
845 r.removed_at.to_string(),
846 format!(
847 "{}#{}",
848 leg.lot_id.origin_event_id.canonical(),
849 leg.lot_id.split_sequence
850 ),
851 leg.sat.to_string(),
852 leg.basis.to_string(),
853 leg.fmv_at_transfer.to_string(),
854 term_tag(leg.term).to_string(),
855 leg.acquired_at.to_string(),
856 deduction_cell.to_string(),
857 donee_cell.clone(),
858 ])?;
859 }
860 }
861 w.flush()?;
862
863 let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("income.csv"))?);
864 w.write_record([
865 "event",
866 "kind",
867 "recognized_at",
868 "sat",
869 "usd_fmv",
870 "business",
871 ])?;
872 for i in &state.income_recognized {
873 w.write_record([
874 i.event.canonical(),
875 income_kind_tag(i.kind).to_string(),
876 i.recognized_at.to_string(),
877 i.sat.to_string(),
878 i.usd_fmv.to_string(),
879 i.business.to_string(),
880 ])?;
881 }
882 w.flush()?;
883
884 if let Some(year) = tax_year {
887 write_form8949_csv(out_dir, state, year)?;
888 write_schedule_d_csv(out_dir, state, year)?;
889 write_form8283_csv(out_dir, state, year, donation_details)?;
890 write_basis_methodology_txt(out_dir, state, year)?; if let Some(se) = se_result {
898 write_schedule_se_csv(out_dir, se)?;
899 }
900 }
901 Ok(())
902}
903
904pub fn write_form_csvs(
920 out_dir: &Path,
921 state: &LedgerState,
922 year: i32,
923 se_result: Option<&SeTaxResult>,
924 donation_details: &BTreeMap<EventId, DonationDetails>,
925) -> Result<(), crate::CliError> {
926 fsperms::mkdir_owner_only(out_dir)?;
927 write_form8949_csv(out_dir, state, year)?;
928 write_schedule_d_csv(out_dir, state, year)?;
929 write_form8283_csv(out_dir, state, year, donation_details)?;
930 write_basis_methodology_txt(out_dir, state, year)?; if let Some(se) = se_result {
932 write_schedule_se_csv(out_dir, se)?;
933 }
934 Ok(())
935}
936
937pub fn write_form_8275_txt(
954 out_dir: &Path,
955 state: &LedgerState,
956 events: &[LedgerEvent],
957 year: i32,
958) -> Result<(), crate::CliError> {
959 write_form_8275_txt_named(out_dir, state, events, year, "form_8275.txt")
960}
961
962pub(crate) fn write_form_8275_txt_named(
968 out_dir: &Path,
969 state: &LedgerState,
970 events: &[LedgerEvent],
971 year: i32,
972 filename: &str,
973) -> Result<(), crate::CliError> {
974 use std::io::Write as _;
975 if let Some(disc) = btctax_core::tax::form8275::disclosure_8275(events, state, year) {
976 let mut file = fsperms::open_owner_only(&out_dir.join(filename))?;
977 write!(file, "{}", disc.render())?;
979 }
980 Ok(())
981}
982
983pub(crate) fn write_basis_methodology_txt(
988 out_dir: &Path,
989 state: &LedgerState,
990 year: i32,
991) -> Result<(), crate::CliError> {
992 use std::io::Write as _;
993 if let Some(text) = btctax_core::conservative::basis_methodology(state, year) {
994 let mut file = fsperms::open_owner_only(&out_dir.join("basis_methodology.txt"))?;
995 writeln!(file, "{text}")?;
996 }
997 Ok(())
998}
999
1000fn write_schedule_se_csv(out_dir: &Path, se: &SeTaxResult) -> Result<(), crate::CliError> {
1004 let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("schedule_se.csv"))?);
1005 w.write_record([
1006 "net_se_earnings",
1007 "se_base_9235",
1008 "ss_component",
1009 "medicare_component",
1010 "additional_medicare_component",
1011 "total_se_tax",
1012 "deductible_half",
1013 ])?;
1014 w.write_record([
1015 se.net_se.to_string(),
1016 se.base.to_string(),
1017 se.ss.to_string(),
1018 se.medicare.to_string(),
1019 se.addl.to_string(),
1020 se.total.to_string(),
1021 se.deductible_half.to_string(),
1022 ])?;
1023 w.flush()?;
1024 Ok(())
1025}
1026
1027pub const FORM_8283_AGGREGATION_CAVEAT: &str =
1033 "Section A/B reflects the \u{00a7}170(f)(11)(F) year-aggregate for similar property: all BTC \
1034 donations in the year are summed (all BTC is 'similar property'); if the year-total claimed \
1035 deduction exceeds $5,000 every row is Section B (qualified appraisal required), otherwise \
1036 Section A. CCA 202302012: the readily-valued exception does not apply to crypto.";
1037
1038pub fn render_donation_appraisal_advisory(state: &LedgerState, year: i32) -> Option<String> {
1056 use btctax_core::QUALIFIED_APPRAISAL_THRESHOLD;
1057 let agg = year_donation_deduction(state, year);
1058 if agg <= QUALIFIED_APPRAISAL_THRESHOLD {
1059 return None;
1060 }
1061 let threshold = fmt_money(QUALIFIED_APPRAISAL_THRESHOLD);
1064 Some(format!(
1065 "\u{00a7}170(f)(11)(F): your {year} BTC donations aggregate ${} of claimed deduction \
1066 (> ${threshold}) \u{2014} a qualified appraisal is required for the donated BTC even if \
1067 no single donation exceeds ${threshold} (all BTC is 'similar property'; CCA 202302012 \
1068 \u{2014} no readily-valued exception for crypto).",
1069 fmt_money(agg)
1070 ))
1071}
1072
1073fn write_form8283_csv(
1080 out_dir: &Path,
1081 state: &LedgerState,
1082 year: i32,
1083 details: &BTreeMap<EventId, DonationDetails>,
1084) -> Result<(), crate::CliError> {
1085 use std::io::Write as _;
1086 let mut file = fsperms::open_owner_only(&out_dir.join("form8283.csv"))?;
1087
1088 writeln!(file, "# {FORM_8283_AGGREGATION_CAVEAT}")?;
1090
1091 let total_deduction = year_donation_deduction(state, year);
1097 if total_deduction <= rust_decimal::Decimal::from(500) {
1098 writeln!(
1099 file,
1100 "# [R0-M1] The year's total noncash charitable deduction ({}) is <= $500; Form 8283 is \
1101 NOT required at that level (rows below are informational only).",
1102 fmt_money(total_deduction)
1103 )?;
1104 }
1105
1106 let mut w = Writer::from_writer(file);
1107 w.write_record([
1108 "section",
1109 "description",
1110 "how_acquired",
1111 "date_acquired",
1112 "date_contributed",
1113 "cost_basis",
1114 "fmv",
1115 "claimed_deduction",
1116 "fmv_method",
1117 "donee",
1118 "appraiser",
1119 "needs_review",
1120 "donee_ein",
1122 "donee_address",
1123 "appraiser_tin",
1124 "appraiser_ptin",
1125 "appraiser_qualifications",
1126 "appraisal_date",
1127 ])?;
1128 for row in form_8283(state, year, details) {
1129 let d = row.details.as_ref();
1130 w.write_record([
1131 row.section
1132 .map(form8283_section_tag)
1133 .unwrap_or("")
1134 .to_string(),
1135 row.description,
1136 form8283_how_acquired_tag(row.how_acquired).to_string(),
1137 row.date_acquired.to_string(),
1138 row.date_contributed.to_string(),
1139 row.cost_basis.to_string(),
1140 row.fmv.to_string(),
1141 row.claimed_deduction
1142 .map(|d| d.to_string())
1143 .unwrap_or_default(),
1144 row.fmv_method,
1145 row.donee,
1146 row.appraiser,
1147 row.needs_review.to_string(),
1148 d.and_then(|d| d.donee_ein.clone()).unwrap_or_default(),
1150 d.and_then(|d| d.donee_address.clone()).unwrap_or_default(),
1151 d.and_then(|d| d.appraiser_tin.clone()).unwrap_or_default(),
1152 d.and_then(|d| d.appraiser_ptin.clone()).unwrap_or_default(),
1153 d.and_then(|d| d.appraiser_qualifications.clone())
1154 .unwrap_or_default(),
1155 d.and_then(|d| d.appraisal_date.map(|dt| dt.to_string()))
1156 .unwrap_or_default(),
1157 ])?;
1158 }
1159 w.flush()?;
1160 Ok(())
1161}
1162
1163fn write_form8949_csv(
1166 out_dir: &Path,
1167 state: &LedgerState,
1168 year: i32,
1169) -> Result<(), crate::CliError> {
1170 let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("form8949.csv"))?);
1171 w.write_record([
1172 "part",
1173 "box",
1174 "box_needs_review",
1175 "description",
1176 "date_acquired",
1177 "date_sold",
1178 "proceeds",
1179 "cost_basis",
1180 "adjustment_code",
1181 "adjustment_amount",
1182 "gain",
1183 "wallet",
1184 "disposition_kind",
1185 ])?;
1186 for r in form_8949(state, year) {
1187 w.write_record([
1188 form8949_part_tag(r.part).to_string(),
1189 form8949_box_tag(r.box_).to_string(),
1190 r.box_needs_review.to_string(),
1191 r.description,
1192 r.date_acquired.to_string(),
1193 r.date_sold.to_string(),
1194 r.proceeds.to_string(),
1195 r.cost_basis.to_string(),
1196 r.adjustment_code,
1197 r.adjustment_amount.to_string(),
1198 r.gain.to_string(),
1199 wallet_label(&r.wallet),
1200 dispose_kind_tag(r.disposition_kind).to_string(),
1201 ])?;
1202 }
1203 w.flush()?;
1204 Ok(())
1205}
1206
1207fn write_schedule_d_csv(
1210 out_dir: &Path,
1211 state: &LedgerState,
1212 year: i32,
1213) -> Result<(), crate::CliError> {
1214 let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("schedule_d.csv"))?);
1215 w.write_record(["part", "proceeds", "cost_basis", "gain"])?;
1216 let totals = schedule_d(state, year);
1217 for (part, p) in [("ST", &totals.st), ("LT", &totals.lt)] {
1218 w.write_record([
1219 part.to_string(),
1220 p.proceeds.to_string(),
1221 p.cost_basis.to_string(),
1222 p.gain.to_string(),
1223 ])?;
1224 }
1225 w.flush()?;
1226 Ok(())
1227}
1228
1229#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1236pub enum PseudoDisclosure {
1237 None,
1239 Synthetic,
1241 Placeholder,
1243}
1244
1245impl PseudoDisclosure {
1246 pub fn contributed(self) -> bool {
1248 self != PseudoDisclosure::None
1249 }
1250 pub fn suffix(self) -> &'static str {
1253 if self.contributed() {
1254 " [PSEUDO]"
1255 } else {
1256 ""
1257 }
1258 }
1259 pub fn banner(self) -> &'static str {
1262 match self {
1263 PseudoDisclosure::None => "",
1264 PseudoDisclosure::Synthetic => {
1265 "⚠ [PSEUDO] This vault has pseudo-reconciled (deliberately-synthetic) entries; figures shown \
1266 are an ESTIMATE, not filing-ready. See '[PSEUDO]' rows in 'btctax report' and the \
1267 [PseudoReconcileActive] advisory in 'btctax verify'; resolve them before filing.\n"
1268 }
1269 PseudoDisclosure::Placeholder => {
1270 "⚠ [PSEUDO] These figures are estimated on a synthetic $0 placeholder profile — no tax \
1271 profile or full-return inputs are stored for this year. This is an ESTIMATE, not \
1272 filing-ready. Set a tax profile ('btctax tax-profile --year <Y> …' — setting is the \
1273 default; '--show' inverts), import inputs ('btctax income import'), or turn pseudo mode off \
1274 ('btctax reconcile pseudo off').\n"
1275 }
1276 }
1277 }
1278}
1279
1280pub fn render_tax_outcome(
1291 year: i32,
1292 out: &btctax_core::TaxOutcome,
1293 advisory: Option<&str>,
1294 pseudo: PseudoDisclosure,
1295) -> String {
1296 use btctax_core::TaxOutcome::*;
1297 let mut s = String::new();
1298 s.push_str(pseudo.banner());
1299 let _ = writeln!(s, "Federal tax attributable to crypto — tax year {year}");
1300 match out {
1301 NotComputable(b) => {
1302 let _ = writeln!(s, " NOT COMPUTABLE [{:?}]: {}", b.kind, b.detail);
1303 }
1304 Computed(r) => {
1305 let _ = writeln!(
1306 s,
1307 " net short-term: {} net long-term: {}",
1308 fmt_money(r.st_net),
1309 fmt_money(r.lt_net)
1310 );
1311 let _ = writeln!(
1312 s,
1313 " crypto ordinary income (level): {}",
1314 fmt_money(r.ordinary_from_crypto)
1315 );
1316 let ordinary_rate_attributable = r.total_federal_tax_attributable - r.ltcg_tax - r.niit;
1319 let _ = writeln!(
1320 s,
1321 " ordinary-rate tax (attributable): {}",
1322 fmt_money(ordinary_rate_attributable)
1323 );
1324 let _ = writeln!(
1325 s,
1326 " LTCG tax (attributable): {} NIIT (attributable): {}",
1327 fmt_money(r.ltcg_tax),
1328 fmt_money(r.niit)
1329 );
1330 let _ = writeln!(
1331 s,
1332 " TOTAL federal tax attributable to crypto (delta): {}{} \
1333 (= ordinary-rate + LTCG + NIIT attributable)",
1334 fmt_money(r.total_federal_tax_attributable),
1335 pseudo.suffix()
1336 );
1337 let _ = writeln!(
1338 s,
1339 " §1211 loss deduction (level): {} carryforward out: short {} / long {}",
1340 fmt_money(r.loss_deduction),
1341 fmt_money(r.carryforward_out.short),
1342 fmt_money(r.carryforward_out.long)
1343 );
1344 let _ = writeln!(
1345 s,
1346 " marginal rates: ordinary {} / LTCG {} / NIIT increased by crypto: {}",
1347 r.marginal_rates.ordinary,
1348 r.marginal_rates.ltcg,
1349 if r.marginal_rates.niit_applies {
1350 "yes"
1351 } else {
1352 "no"
1353 }
1354 );
1355 let _ = writeln!(
1356 s,
1357 " (incremental ceteris-paribus delta on the minimal profile; \
1358 excludes AGI-driven SS/IRMAA/AMT/QBI/phaseout effects — I5. §1411 NIIT reduces NII by the \
1359 §1211(b)-allowed net capital loss (≤ $3,000 / $1,500 MFS — Form 8960 line 5a / §1.1411-4(d)) \
1360 and is floored at $0; crypto ordinary income (mining/staking/airdrops/rewards) is correctly \
1361 excluded from NII; crypto-lending interest income (§1411(c)(1)(A)(i)) is INCLUDED in NII; \
1362 mining/staking/airdrops/rewards remain excluded (SE income per §1411(c)(6) or non-NII other income).)"
1363 );
1364 }
1365 }
1366 if let Some(msg) = advisory {
1369 let _ = writeln!(s, " ADVISORY (M4): {msg}");
1370 }
1371 s
1372}
1373
1374pub(crate) const ADVISORY_WRAP_COLS: usize = 92;
1376
1377pub(crate) fn wrap_bulleted(text: &str) -> String {
1382 const BULLET: &str = " \u{2022} ";
1383 const HANG: &str = " ";
1384 let mut out = String::new();
1385 let mut line = String::from(BULLET);
1386 let mut have_word = false;
1387
1388 for word in text.split_whitespace() {
1389 let prospective = line.chars().count() + usize::from(have_word) + word.chars().count();
1390 if have_word && prospective > ADVISORY_WRAP_COLS {
1391 out.push_str(line.trim_end());
1392 out.push('\n');
1393 line = String::from(HANG);
1394 have_word = false;
1395 }
1396 if have_word {
1397 line.push(' ');
1398 }
1399 line.push_str(word);
1400 have_word = true;
1401 }
1402 out.push_str(line.trim_end());
1403 out
1404}
1405
1406pub fn render_advisories(advisories: &[btctax_core::tax::advisories::Advisory]) -> String {
1410 let mut s = String::new();
1411 if advisories.is_empty() {
1412 return s;
1413 }
1414 let _ = writeln!(s, "\n ── ADVISORIES ({}) ──", advisories.len());
1415 for a in advisories {
1416 let _ = writeln!(s, "{}", wrap_bulleted(&a.message()));
1420 }
1421 let _ = writeln!(
1422 s,
1423 " (Advisories never change a number and never fail the command. See `btctax limitations`.)"
1424 );
1425 s
1426}
1427
1428pub fn provenance_label(p: crate::resolve::Provenance) -> &'static str {
1431 use crate::resolve::Provenance::*;
1432 match p {
1433 ReturnInputs => "ReturnInputs (derived from line items)",
1434 StoredProfile => "stored TaxProfile (raw override)",
1435 PseudoPlaceholder => "pseudo-reconcile placeholder ($0)",
1436 Missing => "none (TaxProfileMissing)",
1437 }
1438}
1439
1440pub fn render_dual_report(
1455 year: i32,
1456 ar: &btctax_core::AbsoluteReturn,
1457 printed: &btctax_core::tax::packet::PrintedForms,
1458 delta: &btctax_core::TaxOutcome,
1459 provenance: crate::resolve::Provenance,
1460 pseudo: PseudoDisclosure,
1461) -> String {
1462 let f = &printed.f1040;
1463 let mut s = String::new();
1464 let _ = writeln!(
1465 s,
1466 "\n═══ Absolute filed return (Form 1040) — tax year {year} ═══"
1467 );
1468 let _ = writeln!(s, " Profile source: {}", provenance_label(provenance));
1469 let _ = writeln!(s, " Total income (1040 L9): {}", fmt_money(f.line9));
1470 let _ = writeln!(s, " Adjustments (L10): {}", fmt_money(f.line10));
1471 let _ = writeln!(s, " AGI (L11): {}", fmt_money(f.line11));
1472 let ded_kind = if ar.deduction_is_itemized {
1473 "itemized"
1474 } else {
1475 "standard"
1476 };
1477 let _ = writeln!(s, " Deduction (L12, {ded_kind}): {}", fmt_money(f.line12));
1478 if ar.qbi_deduction > Usd::ZERO {
1479 let _ = writeln!(s, " QBI deduction (L13): {}", fmt_money(f.line13));
1480 }
1481 let _ = writeln!(s, " Taxable income (L15): {}", fmt_money(f.line15));
1482 let _ = writeln!(s, " Tax (L16): {}", fmt_money(f.line16));
1483 if ar.foreign_tax_credit > Usd::ZERO {
1484 let _ = writeln!(
1485 s,
1486 " Foreign tax credit (Sch 3 L1): {}",
1487 fmt_money(printed.sch_3.map_or(Usd::ZERO, |s3| s3.line1))
1488 );
1489 }
1490 if ar.se_tax_sch2_l4 > Usd::ZERO {
1491 let _ = writeln!(
1492 s,
1493 " Self-employment tax (Sch 2 L4): {}",
1494 fmt_money(printed.sch_2.map_or(Usd::ZERO, |s2| s2.line4))
1495 );
1496 }
1497 if ar.additional_medicare.additional_medicare_tax > Usd::ZERO {
1498 let _ = writeln!(
1499 s,
1500 " Additional Medicare (Form 8959 → Sch 2 L11): {}",
1501 fmt_money(printed.f8959.line18)
1502 );
1503 }
1504 if ar.niit.tax > Usd::ZERO {
1505 let _ = writeln!(
1506 s,
1507 " Net Investment Income Tax (Form 8960 → Sch 2 L12): {}",
1508 fmt_money(printed.f8960.map_or(Usd::ZERO, |f| f.line17))
1509 );
1510 }
1511 let _ = writeln!(
1512 s,
1513 " TOTAL TAX (L24): {}{}",
1514 fmt_money(f.line24),
1515 pseudo.suffix()
1516 );
1517 let _ = writeln!(s, " Total payments (L33): {}", fmt_money(f.line33));
1518 if f.line34 > Usd::ZERO {
1519 let _ = writeln!(s, " → REFUND (L35a): {}", fmt_money(f.line34));
1520 } else {
1521 let _ = writeln!(s, " → AMOUNT OWED (L37): {}", fmt_money(f.line37));
1522 }
1523 let delta_str = match delta {
1525 btctax_core::TaxOutcome::Computed(r) => fmt_money(r.total_federal_tax_attributable),
1526 btctax_core::TaxOutcome::NotComputable(_) => "not computable".to_string(),
1527 };
1528 let _ = writeln!(
1529 s,
1530 "\n ── Two DIFFERENT questions — NOT reconciled (SPEC §6) ──"
1531 );
1532 let _ = writeln!(
1533 s,
1534 " • Absolute TOTAL TAX (this filed return, WITH crypto): {}{}",
1535 fmt_money(f.line24),
1536 pseudo.suffix()
1537 );
1538 let _ = writeln!(
1539 s,
1540 " • Crypto-attributable tax (DELTA, shown above): {delta_str}"
1541 );
1542 let _ = writeln!(
1543 s,
1544 " The delta's implied deduction is fixed at derivation time (non-crypto AGI), so it is \
1545 APPROXIMATE where a\n deduction is AGI-sensitive (e.g. the 7.5% medical floor); the two do NOT \
1546 reconcile to the dollar."
1547 );
1548 s
1549}
1550
1551pub fn render_schedule_d(
1561 year: i32,
1562 totals: &ScheduleDTotals,
1563 outcome: &btctax_core::TaxOutcome,
1564) -> String {
1565 let mut s = String::new();
1566 let _ = writeln!(
1567 s,
1568 "Schedule D (raw pre-netting part totals) — tax year {year}"
1569 );
1570 let _ = writeln!(
1571 s,
1572 " Part I (short-term): proceeds {} cost basis {} gain {}",
1573 fmt_money(totals.st.proceeds),
1574 fmt_money(totals.st.cost_basis),
1575 fmt_money(totals.st.gain)
1576 );
1577 let _ = writeln!(
1578 s,
1579 " Part II (long-term): proceeds {} cost basis {} gain {}",
1580 fmt_money(totals.lt.proceeds),
1581 fmt_money(totals.lt.cost_basis),
1582 fmt_money(totals.lt.gain)
1583 );
1584 match outcome {
1585 btctax_core::TaxOutcome::NotComputable(_) => {
1586 let _ = writeln!(
1587 s,
1588 " (raw disposition totals shown above; the year's tax is NOT COMPUTABLE until \
1589 the blocker is resolved — these Form 8949/Schedule D part totals are \
1590 informational and are not netted/carried until the tax computes)."
1591 );
1592 }
1593 btctax_core::TaxOutcome::Computed(_) => {
1594 let _ = writeln!(
1595 s,
1596 " Note: §1222/§1211/§1212 netting + carryforward are applied in the tax \
1597 computation (report --tax-year); these are the raw pre-netting Form \
1598 8949/Schedule D part totals."
1599 );
1600 }
1601 }
1602 s
1603}
1604
1605pub fn render_schedule_se(
1627 year: i32,
1628 result: Option<&SeTaxResult>,
1629 gross_se: Usd,
1630 table_present: bool,
1631 schedule_c_expenses: Usd,
1632 w2_ss_wages: Usd,
1633 w2_medicare_wages: Usd,
1634) -> Option<String> {
1635 match result {
1636 Some(r) => {
1637 let mut s = String::new();
1638 let _ = writeln!(
1639 s,
1640 "Schedule SE (§1401 self-employment tax on business crypto income) — tax year {year}"
1641 );
1642 if schedule_c_expenses > Usd::ZERO {
1644 let gross_display = r.net_se + schedule_c_expenses;
1647 let _ = writeln!(
1648 s,
1649 " gross business income {} \u{2212} Schedule C expenses {} = net SE earnings {}",
1650 fmt_money(gross_display),
1651 fmt_money(schedule_c_expenses),
1652 fmt_money(r.net_se)
1653 );
1654 let _ = writeln!(
1656 s,
1657 " (Schedule C advisory) Schedule C expenses also reduce your ORDINARY taxable \
1658 income, but the income-tax total above uses GROSS crypto income \u{2014} to first \
1659 order it OVERSTATES your tax by your marginal ordinary rate applied to {}. The tax \
1660 profile cannot express this (an `ordinary_taxable_income` edit would shift both \
1661 legs of the crypto-attributable delta); the engine-side coordination is deferred \
1662 \u{2014} coordinate it on your actual return.",
1663 fmt_money(schedule_c_expenses)
1664 );
1665 } else {
1666 let _ = writeln!(
1667 s,
1668 " net self-employment income (business crypto, Interest excluded): {}",
1669 fmt_money(r.net_se)
1670 );
1671 let _ = writeln!(
1672 s,
1673 " (Schedule C) no Schedule C expenses supplied (--schedule-c-expenses)"
1674 );
1675 }
1676 let _ = writeln!(
1677 s,
1678 " \u{00d7} 92.35% net-earnings factor (\u{00a7}1402(a)) = net SE earnings: {}",
1679 fmt_money(r.base)
1680 );
1681 let _ = writeln!(
1682 s,
1683 " Social Security component (12.4%, §1401(a); capped at the SS wage base): {}",
1684 fmt_money(r.ss)
1685 );
1686 let _ = writeln!(
1687 s,
1688 " Medicare component (2.9%, §1401(b); uncapped): {}",
1689 fmt_money(r.medicare)
1690 );
1691 let _ = writeln!(
1692 s,
1693 " Additional Medicare component (0.9%, §1401(b)(2)): {}",
1694 fmt_money(r.addl)
1695 );
1696 let _ = writeln!(
1697 s,
1698 " TOTAL self-employment tax (§1401): {}",
1699 fmt_money(r.total)
1700 );
1701 let _ = writeln!(
1702 s,
1703 " §164(f) one-half-SE-tax deduction (above-the-line; EXCLUDES Additional Medicare per \
1704 §164(f)(1)): {}",
1705 fmt_money(r.deductible_half)
1706 );
1707 let _ = writeln!(
1710 s,
1711 " (§164(f) advisory) The §164(f) deduction ({}) is NOT auto-coordinated into the \
1712 income-tax total above — to first order, that total overstates your combined tax by \
1713 your marginal ordinary rate applied to {}. The tax profile cannot express this deduction \
1714 directly (reducing `ordinary_taxable_income` would shift BOTH legs of the \
1715 crypto-attributable delta and only correct the bracket differential, not the level) — \
1716 coordinate it on your actual return.",
1717 fmt_money(r.deductible_half),
1718 fmt_money(r.deductible_half)
1719 );
1720 if w2_ss_wages > Usd::ZERO || w2_medicare_wages > Usd::ZERO {
1723 let _ = writeln!(
1724 s,
1725 " (W-2 coordination applied) SS cap = max(0, wage base \u{2212} {}) (Box 3+7); \
1726 Additional-Medicare threshold reduced (not below 0) by {} (Box 5, \
1727 §1401(b)(2)(B)/Form 8959 Part II).",
1728 fmt_money(w2_ss_wages),
1729 fmt_money(w2_medicare_wages)
1730 );
1731 } else {
1732 let _ = writeln!(
1733 s,
1734 " (W-2) assumes $0 W-2 wages (set --w2-ss-wages/--w2-medicare-wages on the tax \
1735 profile if you had a wage job)."
1736 );
1737 }
1738 if r.base < rust_decimal::Decimal::from(400) {
1741 let _ = writeln!(
1742 s,
1743 " (§6017 filing floor) Net earnings from self-employment ({base}) are below $400: \
1744 a Schedule SE filing is required on account of this income only when net earnings \
1745 from self-employment (the ×92.35% base, §1402(a)) are $400 or more (§6017), and \
1746 below that floor no §1401 SE tax is imposed (§1402(b)(2); church employee income \
1747 excepted — §1402(j)(2), not modeled) — the figures above are shown for \
1748 transparency (other self-employment activities, if any, combine on your actual \
1749 Schedule SE).",
1750 base = fmt_money(r.base)
1751 );
1752 }
1753 let _ = writeln!(
1755 s,
1756 " (standalone) This §1401 SE tax is a SEPARATE federal liability, NOT included in the \
1757 income-tax + NIIT total above; the §164(f) one-half-SE-tax deduction is not \
1758 auto-coordinated into that total."
1759 );
1760 Some(s)
1761 }
1762 None => {
1763 if gross_se.is_zero() {
1764 None } else if !table_present {
1766 let mut s = String::new();
1768 let _ = writeln!(
1769 s,
1770 "Schedule SE (§1401 self-employment tax) — tax year {year}"
1771 );
1772 let _ = writeln!(
1773 s,
1774 " SS wage base unavailable for {year}: business self-employment income is present \
1775 but no bundled tax table (ss_wage_base) exists for {year}; the §1401 SE tax was \
1776 NOT computed (no silent drop)."
1777 );
1778 Some(s)
1779 } else {
1780 let mut s = String::new();
1783 let _ = writeln!(
1784 s,
1785 "Schedule SE (§1401 self-employment tax on business crypto income) — tax year {year}"
1786 );
1787 let _ = writeln!(
1788 s,
1789 " fully expensed: gross {} \u{2212} Schedule C expenses {} \u{2264} $0 \
1790 \u{2192} no \u{00a7}1401 SE tax for {year}.",
1791 fmt_money(gross_se),
1792 fmt_money(schedule_c_expenses)
1793 );
1794 Some(s)
1795 }
1796 }
1797 }
1798}
1799
1800pub fn render_gift_advisory(
1823 state: &LedgerState,
1824 year: i32,
1825 prior_taxable_gifts: btctax_core::conventions::Usd,
1826 tables: &impl btctax_core::TaxTables,
1827) -> Option<String> {
1828 use std::collections::BTreeMap;
1829
1830 let any_gift = state
1832 .removals
1833 .iter()
1834 .any(|r| r.kind == RemovalKind::Gift && r.removed_at.year() == year);
1835 if !any_gift {
1836 return None; }
1838
1839 let t = match tables.table_for(year) {
1841 None => {
1842 let total: btctax_core::conventions::Usd = state
1843 .removals
1844 .iter()
1845 .filter(|r| r.kind == RemovalKind::Gift && r.removed_at.year() == year)
1846 .flat_map(|r| r.legs.iter())
1847 .map(|leg| leg.fmv_at_transfer)
1848 .sum();
1849 return Some(format!(
1850 "Form 709 gift advisory ({year}): gift annual-exclusion table unavailable for \
1851 {year}; Form 709 exposure not evaluated — ${} in gifts recorded.",
1852 fmt_money(total)
1853 ));
1854 }
1855 Some(t) => t,
1856 };
1857 let excl = t.gift_annual_exclusion;
1858
1859 let mut labeled: BTreeMap<String, btctax_core::conventions::Usd> = BTreeMap::new();
1861 let mut unlabeled_count: usize = 0;
1862 let mut unlabeled_total: btctax_core::conventions::Usd = Default::default();
1863
1864 for r in state
1865 .removals
1866 .iter()
1867 .filter(|r| r.kind == RemovalKind::Gift && r.removed_at.year() == year)
1868 {
1869 let fmv: btctax_core::conventions::Usd = r.legs.iter().map(|l| l.fmv_at_transfer).sum();
1870 match &r.donee {
1871 Some(label) => {
1872 *labeled.entry(label.clone()).or_default() += fmv;
1873 }
1874 None => {
1875 unlabeled_count += 1;
1876 unlabeled_total += fmv;
1877 }
1878 }
1879 }
1880
1881 let mut filing_required_donees: Vec<String> = Vec::new();
1883 let mut total_taxable: btctax_core::conventions::Usd = Default::default();
1884 let mut s = format!("Form 709 gift advisory ({year}):");
1885
1886 if !labeled.is_empty() {
1887 s.push_str(&format!(
1888 "\n§2503(b) per-donee annual exclusion analysis (TY{year}, exclusion ${}):",
1889 fmt_money(excl)
1890 ));
1891 for (donee, &total) in &labeled {
1892 let applied = if total < excl { total } else { excl };
1893 let taxable: btctax_core::conventions::Usd = if total > excl {
1894 total - excl
1895 } else {
1896 Default::default()
1897 };
1898 s.push_str(&format!(
1899 "\n {donee}: total ${}, exclusion applied ${}, taxable ${}",
1900 fmt_money(total),
1901 fmt_money(applied),
1902 fmt_money(taxable)
1903 ));
1904 if total > excl {
1905 filing_required_donees.push(donee.clone());
1906 total_taxable += taxable;
1907 }
1908 }
1909 if !filing_required_donees.is_empty() {
1910 s.push_str(&format!(
1911 "\nForm 709 filing required (donee(s): {}). Total taxable gifts: ${}.",
1912 filing_required_donees.join(", "),
1913 fmt_money(total_taxable)
1914 ));
1915 } else {
1916 s.push_str(&format!(
1917 "\nNo Form 709 filing required based on per-donee totals \
1918 (each ≤ ${} exclusion). Total taxable gifts: $0.00.",
1919 fmt_money(excl)
1920 ));
1921 }
1922 }
1923
1924 if unlabeled_count > 0 {
1925 s.push_str(&format!(
1926 "\nNOTE: {unlabeled_count} gift(s) totalling ${} have no donee label — the §2503(b) \
1927 annual exclusion is PER DONEE and cannot be applied without one; label them via \
1928 `reconcile reclassify-outflow --donee`. Shown as a single conservative aggregate.",
1929 fmt_money(unlabeled_total)
1930 ));
1931 if unlabeled_total > excl {
1934 s.push_str(&format!(
1935 "\n Conservative aggregate ${} > ${} (one exclusion); \
1936 verify per-donee totals after labelling.",
1937 fmt_money(unlabeled_total),
1938 fmt_money(excl)
1939 ));
1940 } else {
1941 s.push_str(&format!(
1942 "\n Conservative aggregate ${} \u{2264} ${} (one exclusion); \
1943 per-donee exposure unverifiable without labels.",
1944 fmt_money(unlabeled_total),
1945 fmt_money(excl)
1946 ));
1947 }
1948 }
1949
1950 let lifetime_excl = t.gift_lifetime_exclusion;
1954 let cumulative_taxable = prior_taxable_gifts + total_taxable;
1955
1956 if cumulative_taxable > btctax_core::conventions::Usd::ZERO {
1958 let remaining = if cumulative_taxable >= lifetime_excl {
1959 btctax_core::conventions::Usd::ZERO
1960 } else {
1961 lifetime_excl - cumulative_taxable
1962 };
1963 s.push_str(&format!(
1964 "\n§2505 lifetime (basic) exclusion: you have used ${} of your ${} ({year}) lifetime \
1965 exclusion (${} remaining). No gift tax is DUE until cumulative taxable gifts exceed \
1966 the lifetime exclusion.",
1967 fmt_money(cumulative_taxable),
1968 fmt_money(lifetime_excl),
1969 fmt_money(remaining),
1970 ));
1971 if cumulative_taxable > lifetime_excl {
1973 let excess = cumulative_taxable - lifetime_excl;
1974 s.push_str(&format!(
1975 "\nlifetime exclusion EXCEEDED — gift tax may be due on ${} \
1976 (the excess base past the unified credit, not a computed tax); \
1977 consult a professional.",
1978 fmt_money(excess),
1979 ));
1980 }
1981 if unlabeled_count > 0 {
1984 s.push_str(&format!(
1985 "\n§2505 consumption reflects LABELED-donee taxable gifts only; \
1986 {unlabeled_count} unlabeled gift(s) totalling ${} are NOT included — \
1987 label them via `--donee` for a complete figure; consumption may be \
1988 understated / remaining overstated.",
1989 fmt_money(unlabeled_total),
1990 ));
1991 }
1992 }
1993
1994 s.push_str(
1997 "\nCaveats: §2513 gift-splitting (MFJ) not modeled (single-filer advisory only); \
1998 future-interest gifts (which require Form 709 filing regardless of amount) not \
1999 detectable; §2505 figures are advisory only — no portability/DSUE (§2010(c)(4)) \
2000 applied; prior cumulative taxable gifts are user-supplied (default $0 if \
2001 --prior-taxable-gifts not given).",
2002 );
2003
2004 Some(s)
2005}
2006
2007fn picks_str(picks: &[btctax_core::LotPick]) -> String {
2013 if picks.is_empty() {
2014 return "(none)".to_string();
2015 }
2016 picks
2017 .iter()
2018 .map(|p| {
2019 format!(
2020 "{}#{}:{}",
2021 p.lot.origin_event_id.canonical(),
2022 p.lot.split_sequence,
2023 p.sat
2024 )
2025 })
2026 .collect::<Vec<_>>()
2027 .join(", ")
2028}
2029
2030pub fn render_optimize_proposal(p: &btctax_core::OptimizeProposal) -> String {
2043 use btctax_core::{ApproxReason, Persistability};
2044 let mut s = String::new();
2045 let _ = writeln!(
2046 s,
2047 "Optimize (what-if) — tax year {} — NOTHING is filed or bound by running this.",
2048 p.year
2049 );
2050 if p.approximate {
2052 let why = match p.approx_reason {
2053 Some(ApproxReason::ComboCapExceeded { combos, cap }) => format!(
2054 "input exceeded the exhaustive bound ({combos} combos > {cap}); \
2055 a coordinate-descent fallback ran"
2056 ),
2057 Some(ApproxReason::ContentionUnenumerated { contended, .. }) => format!(
2058 "{contended} contended same-wallet disposal(s) could not be fully joint-enumerated"
2059 ),
2060 Some(ApproxReason::PoolHeuristic { lots, bound }) => format!(
2061 "a pool of {lots} lots exceeds the {bound}-lot exhaustive-enumeration bound; \
2062 only a deterministic heuristic SUBSET of that pool's identifications was searched"
2063 ),
2064 None => "approximate".to_string(),
2065 };
2066 let _ = writeln!(
2067 s,
2068 " \u{26a0} APPROXIMATE \u{2014} NOT a guaranteed global minimum: {why}."
2069 );
2070 let _ = writeln!(
2071 s,
2072 " The true least-tax assignment may be lower; this is a disclosed improvement over your"
2073 );
2074 let _ = writeln!(
2075 s,
2076 " current filing position (delta \u{2264} 0), NOT \u{2018}the least tax.\u{2019}"
2077 );
2078 }
2079 let _ = writeln!(
2080 s,
2081 " current federal tax (attributable): {}",
2082 p.baseline_tax
2083 );
2084 let _ = writeln!(
2085 s,
2086 " optimized federal tax (attributable): {}",
2087 p.optimized_tax
2088 );
2089 let _ = writeln!(
2090 s,
2091 " delta (optimized \u{2212} current): {} (negative = saving; always \u{2264} 0)",
2092 p.delta
2093 );
2094 for d in &p.per_disposal {
2095 let _ = writeln!(
2096 s,
2097 " {} @ {} [{}] :: {}",
2098 d.disposal.canonical(),
2099 d.date,
2100 wallet_label(&d.wallet),
2101 compliance_status_tag(&d.status)
2102 );
2103 if d.proposed_selection == d.current_selection {
2108 let _ = writeln!(
2109 s,
2110 " proposed: {} [no change \u{2014} already optimal under current identification]",
2111 picks_str(&d.proposed_selection)
2112 );
2113 continue;
2114 }
2115 let persist = match d.persistable {
2116 Persistability::ContemporaneousNow => {
2117 "persistable now (made \u{2264} sale \u{2192} Contemporaneous)"
2118 }
2119 Persistability::NeedsAttestation => {
2120 "already executed \u{2014} needs `optimize accept --disposal <ref> \
2121 --attest \"\u{2026}\"` (genuine contemporaneous ID only)"
2122 }
2123 Persistability::ForbiddenBroker2027 => {
2124 "2027+ broker-held \u{2014} CANNOT be persisted (own-books insufficient); \
2125 FIFO is the defensible position"
2126 }
2127 };
2128 let _ = writeln!(
2129 s,
2130 " proposed: {} [{}]",
2131 picks_str(&d.proposed_selection),
2132 persist
2133 );
2134 }
2135 let _ = writeln!(
2137 s,
2138 " (vertex-granularity identification: a multi-partial split landing exactly on a \
2139 tax-bracket kink is out of scope.)"
2140 );
2141 let _ = writeln!(
2142 s,
2143 " (this is the tax IF you had identified thus; adequate ID must exist by the time \
2144 of sale \u{2014} \u{a7}1.1012-1(j))"
2145 );
2146 let _ = writeln!(
2148 s,
2149 " (scope: global over taxable-disposal lot selections; self-transfer lot routing is \
2150 held at its baseline position and is not re-optimized.)"
2151 );
2152 s
2153}
2154
2155pub fn render_accept_outcome(o: &crate::cmd::optimize::AcceptOutcome) -> String {
2160 let mut s = String::new();
2161 let _ = writeln!(
2162 s,
2163 "Optimize accept \u{2014} {} persisted, {} skipped.",
2164 o.persisted.len(),
2165 o.skipped.len()
2166 );
2167 for (disposal, decision, basis) in &o.persisted {
2168 let _ = writeln!(
2169 s,
2170 " PERSISTED {} \u{2192} LotSelection {} [{}]{}",
2171 disposal.canonical(),
2172 decision.canonical(),
2173 basis,
2174 if *basis == "AttestedRecording" {
2175 " (+ attestation recorded; revoke with `reconcile void`)"
2176 } else {
2177 " (revoke with `reconcile void`)"
2178 }
2179 );
2180 }
2181 for (disposal, reason) in &o.skipped {
2182 let _ = writeln!(s, " skipped {}: {}", disposal.canonical(), reason);
2183 }
2184 if o.persisted.is_empty() && o.skipped.is_empty() {
2185 let _ = writeln!(s, " (no disposals matched)");
2186 }
2187 s
2188}
2189
2190pub fn render_consult(r: &btctax_core::ConsultReport) -> String {
2200 let mut s = String::new();
2201 let _ = writeln!(
2202 s,
2203 "Consult (read-only what-if): sell {} sat from {} on {}",
2204 r.req.sell_sat,
2205 wallet_label(&r.req.wallet),
2206 r.req.at
2207 );
2208 if r.approximate {
2210 let _ = writeln!(
2211 s,
2212 " \u{26a0} heuristic \u{2014} searched a subset of a large (>12-lot) pool; \
2213 the proposed selection may not be the exact minimum."
2214 );
2215 }
2216 let _ = writeln!(
2217 s,
2218 " proposed selection: {}",
2219 picks_str(&r.proposed_selection)
2220 );
2221 let _ = writeln!(
2222 s,
2223 " short-term gain: {} long-term gain: {}",
2224 r.st_gain, r.lt_gain
2225 );
2226 let _ = writeln!(s, " marginal federal tax (this sale): {}", r.marginal_tax);
2229 let _ = writeln!(
2230 s,
2231 " whole-year federal tax attributable (with this sale): {}",
2232 r.total_federal_tax_attributable
2233 );
2234 if let Some(t) = &r.timing {
2235 let _ = writeln!(
2236 s,
2237 " timing: {} sat of the best selection is short-term until {}; \
2238 selling on/after then would be taxed long-term, a \u{2248} {} difference.",
2239 t.st_sat_in_selection, t.latest_crossover, t.saving_if_waited
2240 );
2241 }
2242 let _ = writeln!(
2243 s,
2244 "Tax decision-support only \u{2014} consequences of a contemplated sale; \
2245 not investment advice (no buy/sell/hold recommendation)."
2246 );
2247 s
2248}
2249
2250fn ltcg_bracket_label(b: LtcgBracket) -> &'static str {
2252 match b {
2253 LtcgBracket::Zero => "0%",
2254 LtcgBracket::Fifteen => "15%",
2255 LtcgBracket::Twenty => "20%",
2256 }
2257}
2258
2259pub fn render_whatif_sell(r: &SellReport, magi_caveat: bool) -> String {
2265 let mut s = String::new();
2266 let _ = writeln!(
2267 s,
2268 "What-if (read-only): sell {} sat from {} on {}",
2269 r.req.sell_sat,
2270 wallet_label(&r.req.wallet),
2271 r.req.at
2272 );
2273 if magi_caveat {
2274 let _ = writeln!(
2275 s,
2276 " \u{26a0} MAGI assumed = ordinary income; NIIT may be understated if you have other MAGI."
2277 );
2278 }
2279 let _ = writeln!(s, " proceeds: {}", r.proceeds);
2280 let _ = writeln!(s, " lots consumed:");
2281 for leg in &r.lots {
2282 let term = match leg.term {
2283 Term::ShortTerm => "ST",
2284 Term::LongTerm => "LT",
2285 };
2286 let _ = writeln!(
2287 s,
2288 " {}#{} {} sat basis {} {} \u{2192} {} {} gain {}",
2289 leg.lot_id.origin_event_id.canonical(),
2290 leg.lot_id.split_sequence,
2291 leg.sat,
2292 leg.basis,
2293 leg.acquired_at,
2294 leg.sold_at,
2295 term,
2296 leg.gain
2297 );
2298 }
2299 let _ = writeln!(
2300 s,
2301 " short-term gain: {} long-term gain: {}",
2302 r.st_gain, r.lt_gain
2303 );
2304 match r.bracket_room {
2306 Some(room) => {
2307 let _ = writeln!(
2308 s,
2309 " \u{00a7}1(h) LTCG bracket: {} (room {} before the next breakpoint)",
2310 ltcg_bracket_label(r.bracket),
2311 room
2312 );
2313 }
2314 None => {
2315 let _ = writeln!(
2316 s,
2317 " \u{00a7}1(h) LTCG bracket: {} (top bracket \u{2014} no headroom)",
2318 ltcg_bracket_label(r.bracket)
2319 );
2320 }
2321 }
2322 let _ = writeln!(s, " marginal federal tax (this sale): {}", r.marginal_tax);
2324 match r.effective_rate {
2325 Some(rate) => {
2326 let _ = writeln!(s, " effective rate: {rate}");
2327 }
2328 None => {
2329 let _ = writeln!(
2330 s,
2331 " effective rate: n/a (a loss/zero-gain sale \u{2014} its value is the carryforward, \
2332 not this-year tax)"
2333 );
2334 }
2335 }
2336 let carried = r.carryforward_delta.short + r.carryforward_delta.long;
2339 if carried != Usd::ZERO || r.ordinary_offset_delta != Usd::ZERO {
2340 let _ = writeln!(
2341 s,
2342 " \u{00a7}1212: {} offsets ordinary income this year, {} carried to next year \
2343 (short {} / long {})",
2344 r.ordinary_offset_delta, carried, r.carryforward_delta.short, r.carryforward_delta.long
2345 );
2346 }
2347 if r.niit_applies {
2349 let dir = if r.niit_incremental < Usd::ZERO {
2350 "decrease"
2351 } else {
2352 "increase"
2353 };
2354 let _ = writeln!(
2355 s,
2356 " \u{00a7}1411 NIIT: {} ({dir}) attributable to this sale",
2357 r.niit_incremental
2358 );
2359 }
2360 let status = match r.status {
2361 SellStatus::Gain => "net gain",
2362 SellStatus::Loss => "net loss (the carryforward is the value \u{2014} not this-year tax)",
2363 };
2364 let _ = writeln!(s, " status: {status}");
2365 let _ = writeln!(
2366 s,
2367 "Tax decision-support only \u{2014} consequences of a contemplated sale; \
2368 not investment advice (no buy/sell/hold recommendation)."
2369 );
2370 s
2371}
2372
2373fn harvest_target_label(t: &HarvestTarget) -> String {
2375 match t {
2376 HarvestTarget::ZeroLtcg => {
2377 "zero-ltcg (all gain in the \u{00a7}1(h) 0% bracket)".to_string()
2378 }
2379 HarvestTarget::FifteenLtcg => "fifteen-ltcg (stay at/under 15%)".to_string(),
2380 HarvestTarget::Gain(x) => format!("gain \u{2264} {x}"),
2381 HarvestTarget::Tax(x) => format!("marginal tax \u{2264} {x}"),
2382 }
2383}
2384
2385pub fn render_whatif_harvest(r: &HarvestReport, magi_caveat: bool) -> String {
2391 let mut s = String::new();
2392 let _ = writeln!(
2393 s,
2394 "What-if HARVEST (read-only): {} from {} on {}",
2395 harvest_target_label(&r.req.target),
2396 wallet_label(&r.req.wallet),
2397 r.req.at
2398 );
2399 if magi_caveat {
2400 let _ = writeln!(
2401 s,
2402 " \u{26a0} MAGI assumed = ordinary income; NIIT may be understated if you have other MAGI."
2403 );
2404 }
2405 let status = match &r.status {
2406 HarvestStatus::Found => "FOUND (the target binds)",
2407 HarvestStatus::NotBinding => "NOT BINDING (the whole position fits)",
2408 HarvestStatus::AlreadyBreached => "ALREADY BREACHED at N=0 (nothing can be harvested)",
2409 HarvestStatus::NoLots => "NO LOTS (nothing to harvest from that wallet)",
2410 HarvestStatus::ProceedsRequired => "PROCEEDS REQUIRED",
2411 HarvestStatus::PreTransitionYear => "PRE-2025 (a closed year, not a plan)",
2412 HarvestStatus::YearNotComputable(_) => "YEAR NOT COMPUTABLE",
2413 };
2414 let _ = writeln!(s, " status: {status}");
2415 let _ = writeln!(s, " \u{2192} sell up to {} BTC ({} sat)", r.n_btc, r.n_sat);
2416 let _ = writeln!(s, " bound by: {}", r.binding_constraint);
2417 let _ = writeln!(
2418 s,
2419 " realized gain at N*: short-term {} long-term {}",
2420 r.st_gain, r.lt_gain
2421 );
2422 let ps = &r.with_result.pref_split;
2424 let bracket = if ps.at_20 > Usd::ZERO {
2425 "20%"
2426 } else if ps.at_15 > Usd::ZERO {
2427 "15%"
2428 } else {
2429 "0%"
2430 };
2431 let _ = writeln!(
2432 s,
2433 " \u{00a7}1(h) preferential dollars at N*: {} in 0% / {} in 15% / {} in 20% (top bracket: {})",
2434 ps.at_0, ps.at_15, ps.at_20, bracket
2435 );
2436 let _ = writeln!(s, " marginal federal tax at N*: {}", r.marginal_tax);
2437 let carried = r.carryforward_delta.short + r.carryforward_delta.long;
2439 if carried != Usd::ZERO {
2440 let dir = if carried < Usd::ZERO {
2441 "burned (spent)"
2442 } else {
2443 "carried to next year"
2444 };
2445 let _ = writeln!(
2446 s,
2447 " \u{00a7}1212 carryforward {}: {} (short {} / long {})",
2448 dir, carried, r.carryforward_delta.short, r.carryforward_delta.long
2449 );
2450 }
2451 if r.niit_applies {
2453 let dir = if r.niit_incremental < Usd::ZERO {
2454 "decrease"
2455 } else {
2456 "increase"
2457 };
2458 let _ = writeln!(
2459 s,
2460 " \u{00a7}1411 NIIT: {} ({dir}) at N* \u{2014} the +3.8% kink applies even inside a 0%/15% bracket answer",
2461 r.niit_incremental
2462 );
2463 }
2464 if let Some(note) = &r.plateau_note {
2465 let _ = writeln!(s, " \u{2139} {note}");
2466 }
2467 let _ = writeln!(
2468 s,
2469 "Tax decision-support only \u{2014} the engine-verified consequences of a contemplated harvest; \
2470 not investment advice (no buy/sell/hold recommendation)."
2471 );
2472 s
2473}
2474
2475pub fn render_verify(r: &VerifyReport) -> String {
2476 let mut out = String::new();
2477 let c = &r.conservation;
2478 let _ = writeln!(
2479 out,
2480 "Conservation (FR9): {}",
2481 if c.balanced { "BALANCED" } else { "DRIFT" }
2482 );
2483 let _ = writeln!(
2484 out,
2485 " in {} = disposed {} + removed {} + held {} + fee-sats {} + pending {}{}",
2486 c.sigma_in,
2487 c.sigma_disposed,
2488 c.sigma_removed,
2489 c.sigma_held,
2490 c.sigma_fee_sats,
2491 c.sigma_pending,
2492 if c.has_uncovered {
2493 " [identity undefined: uncovered disposal open]"
2494 } else {
2495 ""
2496 }
2497 );
2498 let _ = writeln!(out, "2025 transition: {}", r.safe_harbor);
2499 let _ = writeln!(
2500 out,
2501 "Pending reconciliation: {} transfer(s); unknown-basis inbounds: {}",
2502 r.pending, r.unknown_basis_inbounds
2503 );
2504
2505 let _ = writeln!(
2506 out,
2507 "Hard blockers (gate tax computation): {}",
2508 r.hard.len()
2509 );
2510 for b in &r.hard {
2511 let evt = b
2512 .event
2513 .as_ref()
2514 .map(|e| e.canonical())
2515 .unwrap_or_else(|| "-".to_string());
2516 let _ = writeln!(out, " [{:?}] {} :: {}", b.kind, evt, b.detail);
2517 if b.kind == BlockerKind::FmvMissing {
2520 let _ = writeln!(out, " ↳ {}", crate::price_cache::UPDATE_PRICES_HINT);
2521 }
2522 }
2523 let _ = writeln!(out, "Advisory blockers: {}", r.advisory.len());
2524 for b in &r.advisory {
2525 let evt = b
2526 .event
2527 .as_ref()
2528 .map(|e| e.canonical())
2529 .unwrap_or_else(|| "-".to_string());
2530 let _ = writeln!(out, " [{:?}] {} :: {}", b.kind, evt, b.detail);
2531 }
2532 let _ = writeln!(
2533 out,
2534 "Pre-2025 method (attested historical fact): {} (attested: {})",
2535 lot_method_display(r.declared_pre2025_method),
2536 r.pre2025_method_attested
2537 );
2538 let _ = writeln!(
2539 out,
2540 "Standing orders (MethodElection): {}",
2541 r.elections.len()
2542 );
2543 for e in &r.elections {
2544 let _ = writeln!(
2545 out,
2546 " recorded {} effective {} -> {} [{}]",
2547 e.recorded,
2548 e.effective_from,
2549 lot_method_display(e.method),
2550 e.note
2551 );
2552 }
2553 let _ = writeln!(out, "Lot selections recorded: {}", r.selection_count);
2554 let _ = writeln!(
2555 out,
2556 "Per-disposal compliance (post-2025): {}",
2557 r.compliance.len()
2558 );
2559 for c in &r.compliance {
2560 let _ = writeln!(
2561 out,
2562 " {} @ {} :: {}",
2563 c.disposal.canonical(),
2564 c.date,
2565 compliance_status_tag(&c.status)
2566 );
2567 }
2568 let _ = writeln!(out, "Promote-basis drift advisories: {}", r.drift.len());
2571 for d in &r.drift {
2572 let _ = writeln!(out, " {d}");
2573 }
2574 out
2575}
2576
2577#[cfg(test)]
2578mod gift_advisory_tests {
2579 use super::*;
2585 use btctax_core::conventions::Usd;
2586 use btctax_core::{EventId, LotId, Removal, RemovalLeg, TaxTable};
2587 use rust_decimal_macros::dec;
2588 use std::collections::BTreeMap;
2589 use time::macros::date;
2590
2591 fn gift_removal(seq: u64, removed_at: TaxDate, fmv: Usd) -> Removal {
2593 Removal {
2594 event: EventId::decision(seq),
2595 kind: RemovalKind::Gift,
2596 removed_at,
2597 legs: vec![RemovalLeg {
2598 lot_id: LotId {
2599 origin_event_id: EventId::decision(seq),
2600 split_sequence: 0,
2601 },
2602 sat: 100,
2603 basis: dec!(0),
2604 fmv_at_transfer: fmv,
2605 term: Term::LongTerm,
2606 basis_source: BasisSource::ComputedFromCost,
2607 acquired_at: date!(2024 - 01 - 01),
2608 pseudo: false,
2609 }],
2610 appraisal_required: false,
2611 donor_acquired_at: None,
2612 claimed_deduction: None,
2613 donee: None,
2614 }
2615 }
2616 fn gift_removal_labeled(seq: u64, removed_at: TaxDate, fmv: Usd, label: &str) -> Removal {
2618 Removal {
2619 donee: Some(label.to_string()),
2620 ..gift_removal(seq, removed_at, fmv)
2621 }
2622 }
2623 fn state_with(removals: Vec<Removal>) -> LedgerState {
2624 LedgerState {
2625 removals,
2626 ..Default::default()
2627 }
2628 }
2629 fn tables_with(year: i32, excl: Usd) -> BTreeMap<i32, TaxTable> {
2633 tables_with_lifetime(year, excl, dec!(13_990_000))
2634 }
2635
2636 fn tables_with_lifetime(year: i32, excl: Usd, lifetime_excl: Usd) -> BTreeMap<i32, TaxTable> {
2638 let mut m = BTreeMap::new();
2639 m.insert(
2640 year,
2641 TaxTable {
2642 year,
2643 source: "TEST",
2644 ordinary: BTreeMap::new(),
2645 ltcg: BTreeMap::new(),
2646 gift_annual_exclusion: excl,
2647 ss_wage_base: dec!(176100),
2648 gift_lifetime_exclusion: lifetime_excl,
2649 },
2650 );
2651 m
2652 }
2653
2654 #[test]
2658 fn no_gifts_is_none() {
2659 let st = state_with(vec![]);
2660 let tables = tables_with(2025, dec!(19000));
2661 assert!(render_gift_advisory(&st, 2025, dec!(0), &tables).is_none());
2662 }
2663
2664 #[test]
2667 fn gifts_present_but_no_table_emits_note_not_none() {
2668 let st = state_with(vec![gift_removal(1, date!(2026 - 06 - 01), dec!(50000))]);
2670 let tables = tables_with(2025, dec!(19000));
2672 let msg =
2673 render_gift_advisory(&st, 2026, dec!(0), &tables).expect("note expected, not None");
2674 assert!(msg.contains("unavailable"), "{msg}");
2675 assert!(msg.contains("Form 709 exposure not evaluated"), "{msg}");
2676 assert!(
2677 msg.contains("50000.00"),
2678 "must record the gift total: {msg}"
2679 );
2680 }
2681
2682 #[test]
2688 fn labeled_donee_over_exclusion_emits_advisory() {
2689 let st = state_with(vec![gift_removal_labeled(
2690 1,
2691 date!(2025 - 06 - 01),
2692 dec!(20000),
2693 "Alice",
2694 )]);
2695 let tables = tables_with(2025, dec!(19000));
2696 let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2697 assert!(msg.contains("20000.00"), "must show Alice's total: {msg}");
2698 assert!(msg.contains("19000.00"), "must show the exclusion: {msg}");
2699 assert!(
2700 msg.contains("Form 709 filing required"),
2701 "must flag filing required: {msg}"
2702 );
2703 assert!(msg.contains("Alice"), "must name Alice: {msg}");
2704 assert!(msg.contains("1000.00"), "taxable must be $1000.00: {msg}");
2706 assert!(
2708 !msg.contains("donee identity is not modeled"),
2709 "stale aggregate caveat must not appear: {msg}"
2710 );
2711 }
2712
2713 #[test]
2716 fn labeled_donee_under_exclusion_no_filing_required() {
2717 let st = state_with(vec![gift_removal_labeled(
2718 1,
2719 date!(2025 - 06 - 01),
2720 dec!(10000),
2721 "Alice",
2722 )]);
2723 let tables = tables_with(2025, dec!(19000));
2724 let msg =
2726 render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected, not None");
2727 assert!(
2728 msg.contains("No Form 709 filing required"),
2729 "must say no filing required: {msg}"
2730 );
2731 assert!(msg.contains("Alice"), "must mention Alice: {msg}");
2732 assert!(msg.contains("10000.00"), "must show Alice's total: {msg}");
2733 }
2734
2735 #[test]
2741 fn per_donee_under_exclusion_two_donees_no_filing_required() {
2742 let st = state_with(vec![
2743 gift_removal_labeled(1, date!(2025 - 03 - 01), dec!(15000), "Alice"),
2744 gift_removal_labeled(2, date!(2025 - 06 - 01), dec!(15000), "Bob"),
2745 ]);
2746 let tables = tables_with(2025, dec!(19000));
2747 let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2748 assert!(
2750 msg.contains("No Form 709 filing required"),
2751 "neither donee exceeds exclusion → no filing required: {msg}"
2752 );
2753 assert!(msg.contains("Alice"), "Alice must appear: {msg}");
2755 assert!(msg.contains("Bob"), "Bob must appear: {msg}");
2756 assert!(msg.contains("15000.00"), "donee total must appear: {msg}");
2758 assert!(
2760 !msg.contains("Form 709 filing required (donee(s):"),
2761 "filing trigger must NOT fire: {msg}"
2762 );
2763 assert!(
2765 msg.contains("Total taxable gifts: $0.00"),
2766 "total taxable must be $0.00: {msg}"
2767 );
2768 }
2769
2770 #[test]
2773 fn one_donee_over_exclusion_filing_required() {
2774 let st = state_with(vec![gift_removal_labeled(
2775 1,
2776 date!(2025 - 06 - 01),
2777 dec!(25000),
2778 "Alice",
2779 )]);
2780 let tables = tables_with(2025, dec!(19000));
2781 let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2782 assert!(
2783 msg.contains("Form 709 filing required (donee(s): Alice)"),
2784 "must trigger filing required for Alice: {msg}"
2785 );
2786 assert!(msg.contains("25000.00"), "Alice total must appear: {msg}");
2787 assert!(
2788 msg.contains("19000.00"),
2789 "exclusion applied must appear: {msg}"
2790 );
2791 assert!(
2793 msg.contains("6000.00"),
2794 "taxable $6,000.00 must appear: {msg}"
2795 );
2796 }
2797
2798 #[test]
2801 fn unlabeled_bucket_caveat_with_conservative_aggregate() {
2802 let st = state_with(vec![gift_removal(1, date!(2025 - 06 - 01), dec!(30000))]);
2803 let tables = tables_with(2025, dec!(19000));
2804 let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2805 assert!(
2807 msg.contains("no donee label"),
2808 "unlabeled caveat must appear: {msg}"
2809 );
2810 assert!(
2811 msg.contains("30000.00"),
2812 "unlabeled total must appear: {msg}"
2813 );
2814 assert!(
2816 msg.contains("Conservative aggregate"),
2817 "conservative aggregate signal must appear: {msg}"
2818 );
2819 assert!(
2820 msg.contains("19000.00"),
2821 "one-exclusion comparison must appear: {msg}"
2822 );
2823 assert!(
2825 !msg.contains("Form 709 filing required (donee(s):"),
2826 "labeled filing trigger must NOT fire for unlabeled gifts: {msg}"
2827 );
2828 }
2829
2830 #[test]
2833 fn mixed_labeled_over_and_unlabeled_shows_both() {
2834 let st = state_with(vec![
2835 gift_removal_labeled(1, date!(2025 - 03 - 01), dec!(25000), "Alice"),
2836 gift_removal(2, date!(2025 - 06 - 01), dec!(5000)), ]);
2838 let tables = tables_with(2025, dec!(19000));
2839 let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2840 assert!(
2842 msg.contains("Form 709 filing required"),
2843 "filing required for Alice: {msg}"
2844 );
2845 assert!(msg.contains("Alice"), "Alice must appear: {msg}");
2846 assert!(
2848 msg.contains("no donee label"),
2849 "unlabeled caveat must appear: {msg}"
2850 );
2851 assert!(
2852 msg.contains("5000.00"),
2853 "unlabeled total must appear: {msg}"
2854 );
2855 }
2856
2857 #[test]
2860 fn donations_excluded_from_form709_advisory() {
2861 let donation_removal = Removal {
2862 event: EventId::decision(1),
2863 kind: RemovalKind::Donation,
2864 removed_at: date!(2025 - 06 - 01),
2865 legs: vec![RemovalLeg {
2866 lot_id: LotId {
2867 origin_event_id: EventId::decision(1),
2868 split_sequence: 0,
2869 },
2870 sat: 100,
2871 basis: dec!(0),
2872 fmv_at_transfer: dec!(50000), term: Term::LongTerm,
2874 basis_source: BasisSource::ComputedFromCost,
2875 acquired_at: date!(2024 - 01 - 01),
2876 pseudo: false,
2877 }],
2878 appraisal_required: false,
2879 donor_acquired_at: None,
2880 claimed_deduction: Some(dec!(50000)),
2881 donee: Some("Charity X".to_string()),
2882 };
2883 let st = state_with(vec![donation_removal]);
2884 let tables = tables_with(2025, dec!(19000));
2885 assert!(
2887 render_gift_advisory(&st, 2025, dec!(0), &tables).is_none(),
2888 "Donation must be excluded from the Form 709 advisory"
2889 );
2890 }
2891
2892 #[test]
2898 fn section_2505_under_lifetime_shows_used_and_remaining() {
2899 let st = state_with(vec![gift_removal_labeled(
2900 1,
2901 date!(2025 - 06 - 01),
2902 dec!(100000),
2903 "Alice",
2904 )]);
2905 let tables = tables_with(2025, dec!(19000)); let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2907 assert!(
2909 msg.contains("81000.00"),
2910 "taxable $81,000 must appear: {msg}"
2911 );
2912 assert!(
2914 msg.contains("§2505 lifetime (basic) exclusion"),
2915 "§2505 block must appear: {msg}"
2916 );
2917 assert!(
2918 msg.contains("13990000.00"),
2919 "lifetime exclusion $13,990,000 must appear: {msg}"
2920 );
2921 assert!(
2923 msg.contains("13909000.00"),
2924 "remaining $13,909,000 must appear: {msg}"
2925 );
2926 assert!(
2928 !msg.contains("EXCEEDED"),
2929 "must NOT say EXCEEDED when under limit: {msg}"
2930 );
2931 assert!(
2933 !msg.contains("later chunk (Chunk 3)"),
2934 "stale Chunk-3 caveat must be absent: {msg}"
2935 );
2936 }
2937
2938 #[test]
2941 fn section_2505_prior_gifts_accumulate() {
2942 let st = state_with(vec![gift_removal_labeled(
2943 1,
2944 date!(2025 - 06 - 01),
2945 dec!(100000),
2946 "Alice",
2947 )]);
2948 let tables = tables_with(2025, dec!(19000));
2949 let msg =
2950 render_gift_advisory(&st, 2025, dec!(13_900_000), &tables).expect("advisory expected");
2951 assert!(
2953 msg.contains("13981000.00"),
2954 "cumulative $13,981,000 must appear: {msg}"
2955 );
2956 assert!(
2958 msg.contains("9000.00"),
2959 "remaining $9,000 must appear: {msg}"
2960 );
2961 assert!(
2962 !msg.contains("EXCEEDED"),
2963 "must NOT say EXCEEDED when under limit: {msg}"
2964 );
2965 }
2966
2967 #[test]
2971 fn section_2505_exceeds_lifetime_shows_exceeded_and_excess() {
2972 let st = state_with(vec![gift_removal_labeled(
2973 1,
2974 date!(2025 - 06 - 01),
2975 dec!(100000),
2976 "Alice",
2977 )]);
2978 let tables = tables_with(2025, dec!(19000));
2979 let msg =
2980 render_gift_advisory(&st, 2025, dec!(13_950_000), &tables).expect("advisory expected");
2981 assert!(
2982 msg.contains("14031000.00"),
2983 "cumulative $14,031,000 must appear: {msg}"
2984 );
2985 assert!(
2986 msg.contains("EXCEEDED"),
2987 "must say EXCEEDED when over lifetime limit: {msg}"
2988 );
2989 assert!(
2991 msg.contains("41000.00"),
2992 "excess $41,000 must appear: {msg}"
2993 );
2994 }
2995
2996 #[test]
3000 fn section_2505_exact_boundary_remaining_zero_not_exceeded() {
3001 let st = state_with(vec![gift_removal_labeled(
3002 1,
3003 date!(2025 - 06 - 01),
3004 dec!(100000),
3005 "Alice",
3006 )]);
3007 let tables = tables_with(2025, dec!(19000));
3008 let msg =
3010 render_gift_advisory(&st, 2025, dec!(13_909_000), &tables).expect("advisory expected");
3011 assert!(
3012 msg.contains("13990000.00"),
3013 "cumulative $13,990,000 must appear: {msg}"
3014 );
3015 assert!(
3017 msg.contains("($0.00 remaining)"),
3018 "remaining $0.00 in exact phrasing '($0.00 remaining)' must appear: {msg}"
3019 );
3020 assert!(
3022 !msg.contains("EXCEEDED"),
3023 "must NOT say EXCEEDED at exactly the limit: {msg}"
3024 );
3025 }
3026
3027 #[test]
3031 fn section_2505_prior_only_block_shows_even_when_current_taxable_zero() {
3032 let st = state_with(vec![gift_removal_labeled(
3033 1,
3034 date!(2025 - 06 - 01),
3035 dec!(10000), "Alice",
3037 )]);
3038 let tables = tables_with(2025, dec!(19000));
3039 let msg =
3040 render_gift_advisory(&st, 2025, dec!(5_000_000), &tables).expect("advisory expected");
3041 assert!(
3043 msg.contains("5000000.00"),
3044 "cumulative $5,000,000 must appear: {msg}"
3045 );
3046 assert!(
3047 msg.contains("§2505 lifetime (basic) exclusion"),
3048 "§2505 block must appear for prior-only case: {msg}"
3049 );
3050 assert!(!msg.contains("EXCEEDED"), "must NOT say EXCEEDED: {msg}");
3051 }
3052
3053 #[test]
3056 fn section_2505_no_block_when_cumulative_zero() {
3057 let st = state_with(vec![gift_removal_labeled(
3058 1,
3059 date!(2025 - 06 - 01),
3060 dec!(10000), "Alice",
3062 )]);
3063 let tables = tables_with(2025, dec!(19000));
3064 let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
3065 assert!(
3066 !msg.contains("§2505 lifetime"),
3067 "§2505 block must NOT appear when cumulative = 0: {msg}"
3068 );
3069 }
3070
3071 #[test]
3073 fn section_2505_default_zero_prior_shows_caveats() {
3074 let st = state_with(vec![gift_removal_labeled(
3075 1,
3076 date!(2025 - 06 - 01),
3077 dec!(100000), "Alice",
3079 )]);
3080 let tables = tables_with(2025, dec!(19000));
3081 let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
3082 assert!(
3084 !msg.contains("later chunk (Chunk 3)"),
3085 "stale 'later chunk (Chunk 3)' must be absent: {msg}"
3086 );
3087 assert!(
3089 msg.contains("§2513 gift-splitting"),
3090 "§2513 caveat must be present: {msg}"
3091 );
3092 assert!(
3093 msg.contains("portability/DSUE"),
3094 "portability/DSUE caveat must be present: {msg}"
3095 );
3096 assert!(
3097 msg.contains("prior cumulative taxable gifts are user-supplied"),
3098 "prior-cumulative disclosure caveat must be present: {msg}"
3099 );
3100 }
3101
3102 #[test]
3105 fn section_2505_mixed_shows_omission_disclosure_for_unlabeled() {
3106 let st = state_with(vec![
3107 gift_removal_labeled(1, date!(2025 - 03 - 01), dec!(100000), "Alice"),
3108 gift_removal(2, date!(2025 - 06 - 01), dec!(50000)), ]);
3110 let tables = tables_with(2025, dec!(19000));
3111 let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
3112 assert!(
3114 msg.contains("§2505 lifetime (basic) exclusion"),
3115 "§2505 block must appear: {msg}"
3116 );
3117 assert!(
3118 msg.contains("81000.00"),
3119 "used $81,000 (labeled only) must appear: {msg}"
3120 );
3121 assert!(
3123 msg.contains("§2505 consumption reflects LABELED-donee taxable gifts only"),
3124 "omission disclosure must appear: {msg}"
3125 );
3126 assert!(
3127 msg.contains("50000.00"),
3128 "unlabeled total $50,000 must appear in omission disclosure: {msg}"
3129 );
3130 assert!(
3131 msg.contains("consumption may be understated"),
3132 "under-stated warning must appear: {msg}"
3133 );
3134 }
3135
3136 #[test]
3138 fn section_2505_stale_chunk3_caveat_is_absent() {
3139 let st = state_with(vec![gift_removal_labeled(
3140 1,
3141 date!(2025 - 06 - 01),
3142 dec!(20000),
3143 "Alice",
3144 )]);
3145 let tables = tables_with(2025, dec!(19000));
3146 let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
3147 assert!(
3148 !msg.contains("later chunk (Chunk 3)"),
3149 "stale Chunk-3 caveat must be absent: {msg}"
3150 );
3151 assert!(
3152 !msg.contains("§2505 lifetime exemption is a later chunk"),
3153 "stale §2505 future-chunk phrase must be absent: {msg}"
3154 );
3155 }
3156}
3157
3158#[cfg(test)]
3159mod schedule_se_tests {
3160 use super::*;
3164 use rust_decimal_macros::dec;
3165
3166 fn golden1() -> SeTaxResult {
3168 SeTaxResult {
3169 net_se: dec!(100000),
3170 base: dec!(92350.00),
3171 ss: dec!(11451.40),
3172 medicare: dec!(2678.15),
3173 addl: dec!(0.00),
3174 total: dec!(14129.55),
3175 deductible_half: dec!(7064.78),
3176 }
3177 }
3178
3179 fn w2_headline() -> SeTaxResult {
3181 SeTaxResult {
3182 net_se: dec!(100000),
3183 base: dec!(92350.00),
3184 ss: dec!(3236.40),
3185 medicare: dec!(2678.15),
3186 addl: dec!(381.15),
3187 total: dec!(6295.70),
3188 deductible_half: dec!(2957.28),
3189 }
3190 }
3191
3192 fn w2_asymmetric() -> SeTaxResult {
3194 SeTaxResult {
3195 net_se: dec!(100000),
3196 base: dec!(92350.00),
3197 ss: dec!(3236.40),
3198 medicare: dec!(2678.15),
3199 addl: dec!(0.00),
3200 total: dec!(5914.55),
3201 deductible_half: dec!(2957.28),
3202 }
3203 }
3204
3205 fn expenses_headline() -> SeTaxResult {
3210 SeTaxResult {
3211 net_se: dec!(80000),
3212 base: dec!(73880.00),
3213 ss: dec!(9161.12),
3214 medicare: dec!(2142.52),
3215 addl: dec!(0.00),
3216 total: dec!(11303.64),
3217 deductible_half: dec!(5651.82),
3218 }
3219 }
3220
3221 fn expenses_w2_combined() -> SeTaxResult {
3231 SeTaxResult {
3232 net_se: dec!(80000),
3233 base: dec!(73880.00),
3234 ss: dec!(3236.40),
3235 medicare: dec!(2142.52),
3236 addl: dec!(214.92),
3237 total: dec!(5593.84),
3238 deductible_half: dec!(2689.46),
3239 }
3240 }
3241
3242 #[test]
3246 fn business_mining_year_renders_full_section() {
3247 let r = golden1();
3248 let s = render_schedule_se(
3249 2025,
3250 Some(&r),
3251 dec!(100000),
3252 true,
3253 Usd::ZERO,
3254 Usd::ZERO,
3255 Usd::ZERO,
3256 )
3257 .expect("SE section expected");
3258 assert!(s.contains("92350.00"), "net SE earnings base: {s}");
3260 assert!(s.contains("11451.40"), "SS component: {s}");
3261 assert!(s.contains("2678.15"), "Medicare component: {s}");
3262 assert!(s.contains("14129.55"), "total SE tax: {s}");
3263 assert!(s.contains("7064.78"), "§164(f) deductible half: {s}");
3264 assert!(
3265 s.contains("Additional Medicare"),
3266 "addl component labeled: {s}"
3267 );
3268 assert!(
3270 s.contains("$0 W-2 wages"),
3271 "short $0-W-2 note must appear (both W-2 = 0): {s}"
3272 );
3273 assert!(
3274 s.contains("--w2-ss-wages"),
3275 "$0 note must mention --w2-ss-wages flag: {s}"
3276 );
3277 assert!(
3278 !s.contains("OVERSTATED"),
3279 "old OVERSTATED text must be absent (Chunk A regression): {s}"
3280 );
3281 assert!(
3282 !s.contains("UNDERSTATED"),
3283 "old UNDERSTATED text must be absent (Chunk A regression): {s}"
3284 );
3285 assert!(
3287 s.contains("NOT auto-coordinated"),
3288 "§164(f) advisory must appear: {s}"
3289 );
3290 assert!(
3291 s.contains("coordinate it on your actual return"),
3292 "§164(f) advisory must include coordination instruction: {s}"
3293 );
3294 assert!(
3296 s.contains("SEPARATE federal liability"),
3297 "standalone note: {s}"
3298 );
3299 assert!(
3300 s.contains("not") && s.contains("§164(f)"),
3301 "notes §164(f) not auto-coordinated: {s}"
3302 );
3303 assert!(
3305 s.contains("no Schedule C expenses supplied"),
3306 "Chunk B $0-expenses note must appear: {s}"
3307 );
3308 assert!(
3309 s.contains("--schedule-c-expenses"),
3310 "$0 note must mention --schedule-c-expenses flag: {s}"
3311 );
3312 assert!(
3313 !s.contains("not modeled"),
3314 "old 'not modeled' caveat must be absent (replaced by Chunk B): {s}"
3315 );
3316 }
3317
3318 #[test]
3320 fn w2_set_renders_coordinated_disclosure() {
3321 let r = w2_headline();
3322 let s = render_schedule_se(
3323 2025,
3324 Some(&r),
3325 dec!(100000),
3326 true,
3327 Usd::ZERO,
3328 dec!(150000),
3329 dec!(150000),
3330 )
3331 .expect("SE section expected");
3332 assert!(
3334 s.contains("W-2 coordination applied"),
3335 "coordinated disclosure must appear: {s}"
3336 );
3337 assert!(
3338 s.contains("§1401(b)(2)(B)"),
3339 "must cite §1401(b)(2)(B): {s}"
3340 );
3341 assert!(
3342 s.contains("Form 8959 Part II"),
3343 "must cite Form 8959 Part II: {s}"
3344 );
3345 assert!(s.contains("150000"), "w2_ss_wages amount must appear: {s}");
3347 assert!(!s.contains("OVERSTATED"), "OVERSTATED must be absent: {s}");
3349 assert!(
3350 !s.contains("UNDERSTATED"),
3351 "UNDERSTATED must be absent: {s}"
3352 );
3353 assert!(s.contains("3236.40"), "reduced SS component: {s}");
3355 assert!(s.contains("381.15"), "non-zero addl: {s}");
3356 assert!(s.contains("6295.70"), "reduced total: {s}");
3357 assert!(s.contains("2957.28"), "deductible_half: {s}");
3358 }
3359
3360 #[test]
3364 fn w2_asymmetric_render_transposition_guard() {
3365 let r = w2_asymmetric();
3366 let s = render_schedule_se(
3367 2025,
3368 Some(&r),
3369 dec!(100000),
3370 true,
3371 Usd::ZERO,
3372 dec!(150000),
3373 Usd::ZERO,
3374 )
3375 .expect("SE section expected");
3376 assert!(
3378 s.contains("W-2 coordination applied"),
3379 "coordinated disclosure must appear: {s}"
3380 );
3381 assert!(s.contains("3236.40"), "ss must be 3236.40 (reduced): {s}");
3383 assert!(
3384 s.contains("0.00"),
3385 "addl must be 0.00 (threshold un-reduced): {s}"
3386 );
3387 assert!(!s.contains("OVERSTATED"), "{s}");
3389 assert!(!s.contains("UNDERSTATED"), "{s}");
3390 }
3391
3392 #[test]
3394 fn no_business_income_no_section() {
3395 assert!(
3396 render_schedule_se(2025, None, Usd::ZERO, true, Usd::ZERO, Usd::ZERO, Usd::ZERO)
3397 .is_none()
3398 );
3399 }
3400
3401 #[test]
3404 fn business_income_but_no_table_emits_note() {
3405 let s = render_schedule_se(
3406 2099,
3407 None,
3408 dec!(100000),
3409 false,
3410 Usd::ZERO,
3411 Usd::ZERO,
3412 Usd::ZERO,
3413 )
3414 .expect("wage-base-unavailable note expected");
3415 assert!(s.contains("SS wage base unavailable"), "{s}");
3416 assert!(s.contains("2099"), "names the year: {s}");
3417 assert!(s.contains("no silent drop"), "{s}");
3418 }
3419
3420 #[test]
3425 fn expenses_20k_no_w2_renders_breakout_and_advisory() {
3426 let r = expenses_headline(); let s = render_schedule_se(
3428 2025,
3429 Some(&r),
3430 dec!(100000), true,
3432 dec!(20000), Usd::ZERO,
3434 Usd::ZERO,
3435 )
3436 .expect("SE section expected");
3437 assert!(
3439 s.contains("gross business income"),
3440 "breakout line must appear: {s}"
3441 );
3442 assert!(
3443 s.contains("100000.00"),
3444 "gross ($100k) must appear in breakout: {s}"
3445 );
3446 assert!(
3447 s.contains("20000.00"),
3448 "expenses ($20k) must appear in breakout: {s}"
3449 );
3450 assert!(
3451 s.contains("80000.00"),
3452 "net_se ($80k) must appear in breakout: {s}"
3453 );
3454 assert!(
3456 s.contains("OVERSTATES"),
3457 "Schedule C advisory OVERSTATES text: {s}"
3458 );
3459 assert!(
3460 s.contains("ORDINARY taxable income"),
3461 "advisory must mention ORDINARY taxable income: {s}"
3462 );
3463 assert!(
3464 s.contains("engine-side coordination is deferred"),
3465 "advisory must mention deferred coordination: {s}"
3466 );
3467 assert!(
3469 !s.contains("reduce your ordinary_taxable_income"),
3470 "NO OTI-edit prescription allowed (spec D3): {s}"
3471 );
3472 assert!(
3473 !s.contains("set --ordinary-taxable-income"),
3474 "NO OTI-edit prescription allowed (spec D3): {s}"
3475 );
3476 assert!(s.contains("73880.00"), "base $73,880: {s}");
3478 assert!(s.contains("9161.12"), "ss $9,161.12: {s}");
3479 assert!(s.contains("2142.52"), "medicare $2,142.52: {s}");
3480 assert!(s.contains("11303.64"), "total $11,303.64: {s}");
3481 assert!(s.contains("5651.82"), "deductible_half $5,651.82: {s}");
3482 assert!(
3484 !s.contains("not modeled"),
3485 "old 'not modeled' caveat must be absent: {s}"
3486 );
3487 }
3488
3489 #[test]
3492 fn fully_expensed_shows_new_line_not_wage_base_note() {
3493 let s = render_schedule_se(
3496 2025,
3497 None,
3498 dec!(10000), true, dec!(15000), Usd::ZERO,
3502 Usd::ZERO,
3503 )
3504 .expect("fully-expensed section expected (not None)");
3505 assert!(
3507 s.contains("fully expensed"),
3508 "fully-expensed line must appear: {s}"
3509 );
3510 assert!(
3511 s.contains("10000.00"),
3512 "gross $10k must appear in fully-expensed line: {s}"
3513 );
3514 assert!(
3515 s.contains("15000.00"),
3516 "expenses $15k must appear in fully-expensed line: {s}"
3517 );
3518 assert!(
3519 s.contains("no §1401 SE tax"),
3520 "must state no SE tax owed: {s}"
3521 );
3522 assert!(s.contains("2025"), "must name the year: {s}");
3523 assert!(
3525 !s.contains("SS wage base unavailable"),
3526 "wage-base-unavailable note must be ABSENT for fully-expensed case: {s}"
3527 );
3528 }
3529
3530 #[test]
3532 fn expenses_w2_combined_renders_both() {
3533 let r = expenses_w2_combined(); let s = render_schedule_se(
3535 2025,
3536 Some(&r),
3537 dec!(100000),
3538 true,
3539 dec!(20000), dec!(150000), dec!(150000), )
3543 .expect("SE section expected");
3544 assert!(s.contains("gross business income"), "breakout line: {s}");
3546 assert!(s.contains("80000.00"), "net_se in breakout: {s}");
3547 assert!(s.contains("OVERSTATES"), "Schedule C advisory: {s}");
3549 assert!(
3551 s.contains("W-2 coordination applied"),
3552 "W-2 coordination: {s}"
3553 );
3554 assert!(s.contains("73880.00"), "base: {s}");
3556 assert!(s.contains("3236.40"), "ss (reduced by W-2 cap): {s}");
3557 assert!(s.contains("2142.52"), "medicare: {s}");
3558 assert!(s.contains("214.92"), "addl: {s}");
3559 assert!(s.contains("5593.84"), "total: {s}");
3560 assert!(s.contains("2689.46"), "deductible_half: {s}");
3561 }
3562
3563 #[test]
3565 fn schedule_se_csv_columns_and_values() {
3566 let dir = tempfile::tempdir().unwrap();
3567 let out = dir.path().join("export");
3568 let st = LedgerState::default();
3569 let r = golden1();
3570 write_csv_exports(&out, &st, Some(2025), Some(&r), &BTreeMap::new()).unwrap();
3571
3572 let path = out.join("schedule_se.csv");
3573 assert!(path.exists(), "schedule_se.csv must be written");
3574 let mut rdr = csv::Reader::from_reader(std::fs::File::open(&path).unwrap());
3575 let headers: Vec<String> = rdr.headers().unwrap().iter().map(String::from).collect();
3576 assert_eq!(
3577 headers,
3578 vec![
3579 "net_se_earnings",
3580 "se_base_9235",
3581 "ss_component",
3582 "medicare_component",
3583 "additional_medicare_component",
3584 "total_se_tax",
3585 "deductible_half",
3586 ]
3587 );
3588 let rec = rdr
3589 .records()
3590 .next()
3591 .expect("one data row")
3592 .expect("readable");
3593 assert_eq!(&rec[0], "100000"); assert_eq!(&rec[1], "92350.00"); assert_eq!(&rec[2], "11451.40"); assert_eq!(&rec[3], "2678.15"); assert_eq!(&rec[4], "0.00"); assert_eq!(&rec[5], "14129.55"); assert_eq!(&rec[6], "7064.78"); }
3601
3602 #[test]
3604 fn schedule_se_csv_omitted_when_no_se_tax() {
3605 let dir = tempfile::tempdir().unwrap();
3606 let out = dir.path().join("export");
3607 let st = LedgerState::default();
3608 write_csv_exports(&out, &st, Some(2025), None, &BTreeMap::new()).unwrap();
3609 assert!(!out.join("schedule_se.csv").exists());
3610 }
3611}
3612
3613#[cfg(test)]
3614mod form8283_csv_tests {
3615 use super::*;
3618
3619 #[test]
3621 fn form8283_csv_detail_columns_present_and_empty() {
3622 use btctax_core::{
3623 BasisSource, DonationDetails, EventId, LedgerState, Removal, RemovalKind, RemovalLeg,
3624 Term,
3625 };
3626 use time::macros::date;
3627
3628 let dir = tempfile::tempdir().unwrap();
3629 let out = dir.path().join("export");
3630
3631 let event = EventId::decision(99);
3633 let leg = RemovalLeg {
3634 lot_id: btctax_core::LotId {
3635 origin_event_id: event.clone(),
3636 split_sequence: 0,
3637 },
3638 sat: 100_000_000,
3639 basis: rust_decimal::Decimal::ZERO,
3640 fmv_at_transfer: rust_decimal::Decimal::from(52000),
3641 term: Term::LongTerm,
3642 basis_source: BasisSource::ComputedFromCost,
3643 acquired_at: date!(2025 - 01 - 01),
3644 pseudo: false,
3645 };
3646 let removal = Removal {
3647 event: event.clone(),
3648 kind: RemovalKind::Donation,
3649 removed_at: date!(2025 - 03 - 01),
3650 legs: vec![leg],
3651 appraisal_required: false,
3652 donor_acquired_at: None,
3653 claimed_deduction: Some(rust_decimal::Decimal::from(52000)),
3654 donee: Some("Test Charity Two".into()),
3655 };
3656 let event2 = EventId::decision(100);
3658 let leg2 = RemovalLeg {
3659 lot_id: btctax_core::LotId {
3660 origin_event_id: event2.clone(),
3661 split_sequence: 0,
3662 },
3663 sat: 10_000_000,
3664 basis: rust_decimal::Decimal::ZERO,
3665 fmv_at_transfer: rust_decimal::Decimal::from(8000),
3666 term: Term::LongTerm,
3667 basis_source: BasisSource::ComputedFromCost,
3668 acquired_at: date!(2025 - 01 - 15),
3669 pseudo: false,
3670 };
3671 let removal2 = Removal {
3672 event: event2.clone(),
3673 kind: RemovalKind::Donation,
3674 removed_at: date!(2025 - 05 - 01),
3675 legs: vec![leg2],
3676 appraisal_required: false,
3677 donor_acquired_at: None,
3678 claimed_deduction: Some(rust_decimal::Decimal::from(8000)),
3679 donee: Some("No Details Org".into()),
3680 };
3681
3682 let st = LedgerState {
3683 removals: vec![removal, removal2],
3684 ..Default::default()
3685 };
3686
3687 let mut dmap: BTreeMap<EventId, DonationDetails> = BTreeMap::new();
3688 dmap.insert(
3689 event,
3690 DonationDetails {
3691 donee_name: "Test Charity".into(),
3692 donee_ein: Some("12-3456789".into()),
3693 donee_address: Some("123 Main".into()),
3694 appraiser_name: "Test Appraiser".into(),
3695 appraiser_tin: Some("987654321".into()),
3696 appraiser_ptin: Some("P01234567".into()),
3697 appraiser_qualifications: Some("Certified".into()),
3698 appraisal_date: Some(date!(2025 - 06 - 01)),
3699 appraiser_address: None,
3700 fmv_method_override: None,
3701 },
3702 );
3703 write_csv_exports(&out, &st, Some(2025), None, &dmap).unwrap();
3706
3707 let path = out.join("form8283.csv");
3708 assert!(path.exists(), "form8283.csv must exist");
3709
3710 let mut rdr = csv::ReaderBuilder::new()
3711 .comment(Some(b'#'))
3712 .from_path(&path)
3713 .unwrap();
3714 let headers: Vec<String> = rdr.headers().unwrap().iter().map(String::from).collect();
3715 let idx = |name: &str| {
3716 headers
3717 .iter()
3718 .position(|h| h == name)
3719 .unwrap_or_else(|| panic!("header {name} not found"))
3720 };
3721 let all_recs: Vec<csv::StringRecord> = rdr.records().map(|r| r.unwrap()).collect();
3725 assert_eq!(
3726 all_recs.len(),
3727 2,
3728 "must have exactly two data rows (one per removal)"
3729 );
3730 let rec = &all_recs[0];
3731 let no_details_rec = &all_recs[1];
3732
3733 assert_eq!(&rec[idx("donee")], "Test Charity");
3735 assert_eq!(&rec[idx("appraiser")], "Test Appraiser");
3736 assert_eq!(&rec[idx("donee_ein")], "12-3456789");
3737 assert_eq!(&rec[idx("donee_address")], "123 Main");
3738 assert_eq!(&rec[idx("appraiser_tin")], "987654321");
3739 assert_eq!(&rec[idx("appraiser_ptin")], "P01234567");
3740 assert_eq!(&rec[idx("appraiser_qualifications")], "Certified");
3741 assert_eq!(&rec[idx("appraisal_date")], "2025-06-01");
3742 assert_eq!(&rec[idx("needs_review")], "false");
3743
3744 assert_eq!(
3746 &no_details_rec[idx("donee_ein")],
3747 "",
3748 "no-details row: donee_ein must be empty"
3749 );
3750 assert_eq!(
3751 &no_details_rec[idx("donee_address")],
3752 "",
3753 "no-details row: donee_address must be empty"
3754 );
3755 assert_eq!(
3756 &no_details_rec[idx("appraiser_tin")],
3757 "",
3758 "no-details row: appraiser_tin must be empty"
3759 );
3760 assert_eq!(
3761 &no_details_rec[idx("appraiser_ptin")],
3762 "",
3763 "no-details row: appraiser_ptin must be empty"
3764 );
3765 assert_eq!(
3766 &no_details_rec[idx("appraiser_qualifications")],
3767 "",
3768 "no-details row: appraiser_qualifications must be empty"
3769 );
3770 assert_eq!(
3771 &no_details_rec[idx("appraisal_date")],
3772 "",
3773 "no-details row: appraisal_date must be empty"
3774 );
3775 assert_eq!(
3776 &no_details_rec[idx("needs_review")],
3777 "true",
3778 "no-details carrier row: needs_review must be true"
3779 );
3780 }
3781}
3782
3783pub struct EventRow {
3786 pub reff: String,
3788 pub kind: &'static str,
3790 pub date: TaxDate,
3792 pub sat: Option<btctax_core::Sat>,
3794 pub usd: Option<Usd>,
3796 pub decision_ref: Option<String>,
3799}
3800
3801fn fmt_btc(sat: btctax_core::Sat) -> String {
3803 let whole = sat / 100_000_000;
3804 let frac = (sat % 100_000_000).unsigned_abs();
3805 format!("{whole}.{frac:08}")
3806}
3807
3808pub fn render_events_list(rows: &[EventRow]) -> String {
3811 let mut out = String::new();
3812 if rows.is_empty() {
3813 let _ = writeln!(out, "No decidable events.");
3814 return out;
3815 }
3816 let decided = rows.iter().filter(|r| r.decision_ref.is_some()).count();
3817 let _ = writeln!(
3818 out,
3819 "Decidable events — {} ({} decided, {} open):",
3820 rows.len(),
3821 decided,
3822 rows.len() - decided
3823 );
3824 for r in rows {
3825 let amount = match (r.sat, r.usd) {
3826 (Some(s), Some(u)) => format!("{} BTC (~${})", fmt_btc(s), fmt_money(u)),
3827 (Some(s), None) => format!("{} BTC", fmt_btc(s)),
3828 (None, _) => "—".to_string(),
3829 };
3830 let status = match &r.decision_ref {
3831 Some(d) => format!("[decided: {d}]"),
3832 None => "[decidable]".to_string(),
3833 };
3834 let _ = writeln!(
3835 out,
3836 " {} {} @ {} {} {}",
3837 r.reff, r.kind, r.date, amount, status
3838 );
3839 }
3840 out
3841}
3842
3843#[cfg(test)]
3844mod advisory_wrap_tests {
3845 use super::*;
3846
3847 #[test]
3851 fn advisories_wrap_to_the_house_width_with_a_hanging_indent() {
3852 use btctax_core::tax::advisories::Advisory;
3853 let out = render_advisories(&[Advisory::CtcOdcOmitted { dependents: 2 }]);
3854
3855 for line in out.lines() {
3856 assert!(
3857 line.chars().count() <= ADVISORY_WRAP_COLS,
3858 "line is {} cols, over the {}-col house width: {line:?}",
3859 line.chars().count(),
3860 ADVISORY_WRAP_COLS
3861 );
3862 }
3863 assert!(
3865 out.lines()
3866 .any(|l| l.starts_with(" ") && !l.trim().is_empty()),
3867 "a 300-char advisory must wrap onto continuation lines, got:\n{out}"
3868 );
3869 }
3870}
3871
3872#[cfg(test)]
3873mod events_list_render_tests {
3874 use super::*;
3875 use time::macros::date;
3876
3877 fn row(reff: &str, kind: &'static str, decision_ref: Option<&str>) -> EventRow {
3878 EventRow {
3879 reff: reff.to_owned(),
3880 kind,
3881 date: date!(2025 - 03 - 01),
3882 sat: Some(5_000_000),
3883 usd: Some(rust_decimal_macros::dec!(4271.78)),
3884 decision_ref: decision_ref.map(str::to_owned),
3885 }
3886 }
3887
3888 #[test]
3890 fn empty_renders_a_none_line() {
3891 assert_eq!(render_events_list(&[]), "No decidable events.\n");
3892 }
3893
3894 #[test]
3897 fn rows_are_ref_first_with_bracketed_status() {
3898 let out = render_events_list(&[
3899 row("import|coinbase|in|cb-recv", "transfer-in", None),
3900 row(
3901 "import|coinbase|out|cb-send",
3902 "transfer-out",
3903 Some("decision|1"),
3904 ),
3905 ]);
3906 let lines: Vec<&str> = out.lines().collect();
3907 assert!(
3908 lines[0].contains("2 (1 decided, 1 open)"),
3909 "header: {}",
3910 lines[0]
3911 );
3912 assert_eq!(
3914 lines[1].split_whitespace().next(),
3915 Some("import|coinbase|in|cb-recv")
3916 );
3917 assert!(lines[1].contains("[decidable]"), "open row: {}", lines[1]);
3918 assert!(
3919 lines[1].contains("0.05000000 BTC") && lines[1].contains("4271.78"),
3920 "amount: {}",
3921 lines[1]
3922 );
3923 assert!(
3924 lines[2].contains("[decided: decision|1]"),
3925 "decided row: {}",
3926 lines[2]
3927 );
3928 }
3929}
3930
3931#[cfg(test)]
3932mod holdings_pending_tests {
3933 use super::*;
3936 use btctax_core::state::PendingTransfer;
3937 use btctax_core::EventId;
3938
3939 #[test]
3940 fn holdings_pending_line_shows_in_btc_and_hides_when_reconciled() {
3941 let mut pending = LedgerState::default();
3942 pending.stats.sigma_pending = 3_000_000; pending.pending_reconciliation = vec![PendingTransfer {
3944 event: EventId::decision(1),
3945 principal_sat: 3_000_000,
3946 fee_sat: None,
3947 legs: vec![],
3948 }];
3949 let shown = render_report(&pending, None);
3950 assert!(shown.contains("Pending:"), "pending line present: {shown}");
3951 assert!(shown.contains("0.03000000 BTC"), "BTC unit: {shown}");
3952 assert!(
3953 shown.contains("1 unreconciled transfer"),
3954 "names the count (singular): {shown}"
3955 );
3956 assert!(shown.contains("verify"), "points at `verify`: {shown}");
3957
3958 let reconciled = LedgerState::default();
3960 let hidden = render_report(&reconciled, None);
3961 assert!(
3962 !hidden.contains("Pending:"),
3963 "no pending line when reconciled: {hidden}"
3964 );
3965 }
3966
3967 #[test]
3968 fn holdings_pending_line_pluralizes_multiple_transfers() {
3969 let mut pending = LedgerState::default();
3970 pending.stats.sigma_pending = 150_000_000; pending.pending_reconciliation = vec![
3972 PendingTransfer {
3973 event: EventId::decision(1),
3974 principal_sat: 100_000_000,
3975 fee_sat: None,
3976 legs: vec![],
3977 },
3978 PendingTransfer {
3979 event: EventId::decision(2),
3980 principal_sat: 50_000_000,
3981 fee_sat: None,
3982 legs: vec![],
3983 },
3984 ];
3985 let shown = render_report(&pending, None);
3986 assert!(
3987 shown.contains("2 unreconciled transfers"),
3988 "plural: {shown}"
3989 );
3990 assert!(shown.contains("1.50000000 BTC"), "{shown}");
3991 }
3992}
3993
3994#[cfg(test)]
3995mod decision_class_tests {
3996 use super::*;
4000 use btctax_core::{DisposeKind, InboundClass, IncomeKind, OutflowClass};
4001 use rust_decimal_macros::dec;
4002 use time::macros::date;
4003
4004 #[test]
4005 fn inbound_self_transfer_mine_is_human_no_debug_struct() {
4006 let s = describe_inbound_class(&InboundClass::SelfTransferMine {
4007 basis: Some(dec!(19000)),
4008 acquired_at: Some(date!(2026 - 01 - 01)),
4009 });
4010 assert!(s.contains("self-transfer"), "{s}");
4011 assert!(s.contains("$19000.00"), "names the basis in $: {s}");
4012 assert!(s.contains("2026-01-01"), "names the acquired date: {s}");
4013 assert!(!s.contains('{'), "no Debug struct braces: {s}");
4014 assert!(!s.contains("Some("), "no Debug Option wrapper: {s}");
4015 }
4016
4017 #[test]
4018 fn inbound_self_transfer_mine_defaults_are_named_not_none() {
4019 let s = describe_inbound_class(&InboundClass::SelfTransferMine {
4020 basis: None,
4021 acquired_at: None,
4022 });
4023 assert!(s.contains("self-transfer"), "{s}");
4024 assert!(
4025 s.matches("default").count() >= 2,
4026 "None basis AND date read as 'default': {s}"
4027 );
4028 assert!(!s.contains("None"), "no Debug None: {s}");
4029 }
4030
4031 #[test]
4032 fn inbound_income_names_kind_fmv_business() {
4033 let s = describe_inbound_class(&InboundClass::Income {
4034 kind: IncomeKind::Mining,
4035 fmv: Some(dec!(500)),
4036 business: true,
4037 });
4038 assert!(s.contains("income"), "{s}");
4039 assert!(s.contains("mining"), "names the income kind: {s}");
4040 assert!(s.contains("$500.00"), "names the fmv: {s}");
4041 assert!(s.contains("business"), "flags business: {s}");
4042 assert!(!s.contains('{'), "{s}");
4043 }
4044
4045 #[test]
4046 fn inbound_gift_received_names_fmv() {
4047 let s = describe_inbound_class(&InboundClass::GiftReceived {
4048 donor_basis: Some(dec!(1000)),
4049 donor_acquired_at: Some(date!(2024 - 05 - 05)),
4050 fmv_at_gift: dec!(30000),
4051 });
4052 assert!(s.contains("gift"), "{s}");
4053 assert!(s.contains("$30000.00"), "names the FMV at gift: {s}");
4054 assert!(!s.contains('{'), "{s}");
4055 }
4056
4057 #[test]
4058 fn outflow_classes_are_human() {
4059 assert_eq!(
4060 describe_outflow_class(&OutflowClass::Dispose {
4061 kind: DisposeKind::Sell
4062 }),
4063 "sell"
4064 );
4065 assert_eq!(
4066 describe_outflow_class(&OutflowClass::Dispose {
4067 kind: DisposeKind::Spend
4068 }),
4069 "spend"
4070 );
4071 assert_eq!(describe_outflow_class(&OutflowClass::GiftOut), "gift");
4072 let donate = describe_outflow_class(&OutflowClass::Donate {
4073 appraisal_required: true,
4074 });
4075 assert!(
4076 donate.contains("donate") && donate.contains("appraisal"),
4077 "{donate}"
4078 );
4079 assert_eq!(
4080 describe_outflow_class(&OutflowClass::Donate {
4081 appraisal_required: false
4082 }),
4083 "donate"
4084 );
4085 }
4086}
4087
4088fn render_defensive_candidate(s: &Shortfall) -> String {
4097 let wallet = s
4098 .wallet
4099 .as_ref()
4100 .map(wallet_label)
4101 .unwrap_or_else(|| "(no wallet on this shortfall)".to_string());
4102 let mut out = format!(
4103 " {} {wallet} {} short {} BTC (fee {} BTC)\n",
4104 s.event.canonical(),
4105 s.date,
4106 fmt_btc(s.short_sat),
4107 fmt_btc(s.fee_sat)
4108 );
4109 match &s.wallet {
4110 Some(w) => {
4111 let _ = writeln!(
4112 out,
4113 " -> btctax declare-tranche --amount {} --wallet {} --window-start <earliest \
4114 plausible date> --window-end {}",
4115 fmt_btc(s.short_sat),
4116 wallet_label(w),
4117 s.date
4118 );
4119 }
4120 None => {
4121 let _ = writeln!(
4122 out,
4123 " -> btctax declare-tranche --amount {} --wallet <pick one — this shortfall \
4124 carries none> --window-start <earliest plausible date> --window-end {}",
4125 fmt_btc(s.short_sat),
4126 s.date
4127 );
4128 }
4129 }
4130 out
4131}
4132
4133fn render_defensive_resolve_first(shortfall: &Shortfall, blocker: BlockerKind) -> String {
4134 let wallet = shortfall
4135 .wallet
4136 .as_ref()
4137 .map(wallet_label)
4138 .unwrap_or_else(|| "(no wallet on this shortfall)".to_string());
4139 format!(
4140 " {} {wallet} {} short {} BTC — blocked by {blocker:?}\n -> resolve the blocker \
4141 first (see `btctax events list` / `btctax verify`), then re-run `btctax defensive status`\n",
4142 shortfall.event.canonical(),
4143 shortfall.date,
4144 fmt_btc(shortfall.short_sat)
4145 )
4146}
4147
4148fn render_defensive_advisory(a: &Advisory) -> String {
4149 match a {
4150 Advisory::OverCovered { by_sat } => format!(
4151 " [advisory] this tranche is larger than the shortfall it covers by {} BTC — if a \
4152 later import supplied those coins, promoting files an estimated basis on documented \
4153 coins\n",
4154 fmt_btc(*by_sat)
4155 ),
4156 Advisory::NowDisplacing => " [advisory] this promoted floor now displaces documented \
4157 basis on a real disposal\n"
4158 .to_string(),
4159 Advisory::MethodInversion(msg) => format!(" [advisory] {msg}\n"),
4160 Advisory::TrancheDip(msg) => format!(" [advisory] {msg}\n"),
4161 Advisory::FeeOnlyPromoteNoop => {
4162 " [advisory] the shortfall(s) this tranche covers are \
4163 all fee-component — promoting would only ever substantiate fee-sat basis, never \
4164 principal\n"
4165 .to_string()
4166 }
4167 Advisory::WouldDisplaceIfPromoted => {
4168 " [advisory] promoting this tranche would displace \
4169 documented basis on a real disposal\n"
4170 .to_string()
4171 }
4172 }
4173}
4174
4175fn render_defensive_saving(s: &SavingFlavor) -> String {
4176 match s {
4177 SavingFlavor::ComputedTax { year, delta } => format!(
4178 " [assess] promoting this tranche would save an estimated ${} in federal tax for \
4179 {year} (clamped, never negative)\n",
4180 fmt_money(*delta)
4181 ),
4182 SavingFlavor::Uncomputable { year, gain_delta } => format!(
4183 " [assess] {year} cannot price a tax dollar figure yet (no bundled table / no \
4184 stored tax profile / a Hard blocker) — the realized-gain delta alone is ${}\n",
4185 fmt_money(*gain_delta)
4186 ),
4187 SavingFlavor::Named(msg) => format!(" [assess] {msg}\n"),
4188 }
4189}
4190
4191fn render_defensive_tranche(row: &TrancheRow) -> String {
4192 let mut out = format!(
4193 " {} {} BTC {}\n",
4194 row.target.canonical(),
4195 fmt_btc(row.sat),
4196 match row.status {
4197 TrancheStatus::DeclaredZero => "declared ($0, revocable)",
4198 TrancheStatus::Promoted => "promoted (filed, not revocable)",
4199 }
4200 );
4201 if row.status == TrancheStatus::DeclaredZero {
4202 let _ = writeln!(
4203 out,
4204 " -> btctax promote-tranche {} --provenance <kind> --part-ii-file <path> \
4205 [--i-acknowledge <phrase>]",
4206 row.target.canonical()
4207 );
4208 }
4209 for s in &row.clamped_saving {
4210 out.push_str(&render_defensive_saving(s));
4211 }
4212 for a in &row.advisories {
4213 out.push_str(&render_defensive_advisory(a));
4214 }
4215 out
4216}
4217
4218fn render_defensive_pool_short(ps: &PoolShort) -> String {
4219 format!(
4220 " {:?}: short {} BTC ({} BTC live in tranche(s) here) — don't declare again; review the \
4221 window/wallet on the existing tranche(s) instead\n",
4222 ps.pool,
4223 fmt_btc(ps.short_sat),
4224 fmt_btc(ps.live_tranche_sat)
4225 )
4226}
4227
4228pub fn render_defensive_status(view: &DefensiveFilingView) -> String {
4233 let mut out = String::new();
4234
4235 let nothing_outstanding = view.candidates.is_empty()
4236 && view.resolve_first.is_empty()
4237 && view.tranches.is_empty()
4238 && view.still_short.is_empty()
4239 && view.flagged_years.is_empty();
4240
4241 if nothing_outstanding {
4242 let _ = writeln!(
4243 out,
4244 "Nothing outstanding right now — no declare candidate, no blocked resolve-first \
4245 shortfall, no live tranche, and no flagged export year."
4246 );
4247 return out;
4248 }
4249
4250 if !view.candidates.is_empty() {
4251 let _ = writeln!(
4252 out,
4253 "Declare candidates ({}) — shortfalls a new $0 tranche could cover now:",
4254 view.candidates.len()
4255 );
4256 for s in &view.candidates {
4257 out.push_str(&render_defensive_candidate(s));
4258 }
4259 out.push('\n');
4260 }
4261
4262 if !view.resolve_first.is_empty() {
4263 let _ = writeln!(
4264 out,
4265 "Resolve first ({}) — an open blocker on the same pool/timeframe must clear before \
4266 these can be declared:",
4267 view.resolve_first.len()
4268 );
4269 for t in &view.resolve_first {
4270 if let Triage::ResolveFirst { shortfall, blocker } = t {
4271 out.push_str(&render_defensive_resolve_first(shortfall, *blocker));
4272 }
4273 }
4274 out.push('\n');
4275 }
4276
4277 if !view.tranches.is_empty() {
4278 let _ = writeln!(out, "Live tranches ({}):", view.tranches.len());
4279 for row in &view.tranches {
4280 out.push_str(&render_defensive_tranche(row));
4281 }
4282 out.push('\n');
4283 }
4284
4285 if !view.still_short.is_empty() {
4286 let _ = writeln!(out, "Pools still short ({}):", view.still_short.len());
4287 for ps in &view.still_short {
4288 out.push_str(&render_defensive_pool_short(ps));
4289 }
4290 out.push('\n');
4291 }
4292
4293 if !view.flagged_years.is_empty() {
4294 let years: Vec<String> = view.flagged_years.iter().map(|y| y.to_string()).collect();
4295 let _ = writeln!(
4296 out,
4297 "Flagged years needing (re-)export attention ({}): {}",
4298 years.len(),
4299 years.join(", ")
4300 );
4301 let _ = writeln!(
4302 out,
4303 " -> btctax export-irs-pdf --tax-year <year> (or `btctax export-snapshot` for the \
4304 CSV projection)"
4305 );
4306 out.push('\n');
4307 }
4308
4309 if view.safe_harbor_blocked {
4310 let _ = writeln!(
4311 out,
4312 "Safe-harbor allocation: BLOCKED — v1 keeps a pre-2025 conservative-filing tranche and \
4313 a safe-harbor allocation mutually exclusive."
4314 );
4315 }
4316
4317 if out.ends_with("\n\n") {
4319 out.pop();
4320 }
4321 out
4322}
4323
4324#[cfg(test)]
4325mod defensive_status_tests {
4326 use super::*;
4327 use btctax_core::identity::EventId;
4328 use std::collections::BTreeSet;
4329 use time::macros::date;
4330
4331 fn empty_view() -> DefensiveFilingView {
4332 DefensiveFilingView {
4333 candidates: vec![],
4334 resolve_first: vec![],
4335 tranches: vec![],
4336 still_short: vec![],
4337 flagged_years: BTreeSet::new(),
4338 safe_harbor_blocked: false,
4339 }
4340 }
4341
4342 #[test]
4343 fn nothing_outstanding_is_a_single_line_all_clear() {
4344 let out = render_defensive_status(&empty_view());
4345 assert!(out.contains("Nothing outstanding right now"), "{out}");
4346 }
4347
4348 #[test]
4349 fn candidate_names_the_declare_tranche_verb_with_its_own_amount_wallet_and_window_end() {
4350 let mut view = empty_view();
4351 view.candidates.push(Shortfall {
4352 event: EventId::decision(7),
4353 wallet: Some(WalletId::Exchange {
4354 provider: "coinbase".into(),
4355 account: "default".into(),
4356 }),
4357 date: date!(2019 - 03 - 14),
4358 short_sat: 5_000_000,
4359 fee_sat: 0,
4360 });
4361 let out = render_defensive_status(&view);
4362 assert!(out.contains("Declare candidates (1)"), "{out}");
4363 assert!(out.contains("decision|7"), "{out}");
4364 assert!(
4365 out.contains(
4366 "btctax declare-tranche --amount 0.05000000 \
4367 --wallet exchange:coinbase:default"
4368 ),
4369 "{out}"
4370 );
4371 assert!(out.contains("--window-end 2019-03-14"), "{out}");
4372 }
4373
4374 #[test]
4375 fn resolve_first_names_the_blocker_and_the_re_run_remedy_not_declare() {
4376 let mut view = empty_view();
4377 view.resolve_first.push(Triage::ResolveFirst {
4378 shortfall: Shortfall {
4379 event: EventId::decision(9),
4380 wallet: Some(WalletId::SelfCustody {
4381 label: "cold".into(),
4382 }),
4383 date: date!(2020 - 01 - 01),
4384 short_sat: 1_000_000,
4385 fee_sat: 0,
4386 },
4387 blocker: BlockerKind::UnknownBasisInbound,
4388 });
4389 let out = render_defensive_status(&view);
4390 assert!(out.contains("Resolve first (1)"), "{out}");
4391 assert!(out.contains("blocked by UnknownBasisInbound"), "{out}");
4392 assert!(
4393 !out.contains("declare-tranche"),
4394 "a resolve-first row must not offer the declare verb: {out}"
4395 );
4396 }
4397
4398 #[test]
4399 fn declared_zero_tranche_offers_promote_promoted_tranche_does_not() {
4400 let mut view = empty_view();
4401 view.tranches.push(TrancheRow {
4402 target: EventId::decision(3),
4403 sat: 5_000_000,
4404 status: TrancheStatus::DeclaredZero,
4405 clamped_saving: vec![],
4406 advisories: vec![],
4407 });
4408 view.tranches.push(TrancheRow {
4409 target: EventId::decision(5),
4410 sat: 2_000_000,
4411 status: TrancheStatus::Promoted,
4412 clamped_saving: vec![],
4413 advisories: vec![],
4414 });
4415 let out = render_defensive_status(&view);
4416 assert!(
4417 out.contains("btctax promote-tranche decision|3"),
4418 "declared ($0) row must offer promote-tranche: {out}"
4419 );
4420 assert!(
4421 !out.contains("promote-tranche decision|5"),
4422 "an already-promoted row must not offer promote-tranche again: {out}"
4423 );
4424 assert!(out.contains("declared ($0, revocable)"), "{out}");
4425 assert!(out.contains("promoted (filed, not revocable)"), "{out}");
4426 }
4427
4428 #[test]
4429 fn flagged_years_name_the_export_verb() {
4430 let mut view = empty_view();
4431 view.flagged_years.insert(2024);
4432 view.flagged_years.insert(2025);
4433 let out = render_defensive_status(&view);
4434 assert!(out.contains("2024, 2025"), "{out}");
4435 assert!(out.contains("btctax export-irs-pdf --tax-year"), "{out}");
4436 }
4437
4438 #[test]
4439 fn safe_harbor_blocked_is_named() {
4440 let mut view = empty_view();
4441 view.safe_harbor_blocked = true;
4442 view.flagged_years.insert(2024);
4444 let out = render_defensive_status(&view);
4445 assert!(out.contains("Safe-harbor allocation: BLOCKED"), "{out}");
4446 }
4447}