* Include newer providers in automatic family sync
Coinbase, CoinStats, Mercury, and SnapTrade all implement Syncable
and have Syncer classes but were not listed in child_syncables,
meaning their data only refreshed on manual sync button clicks.
* refactor(syncer): Open/Closed principle for provider sync
- Adding new providers requires modifying child_syncables (violates O/C)
- plaid_items missing .active scope (bug: syncs deleted items)
- snaptrade_items can exist without user registration → fails on sync
- Scattered knowledge about 'ready to sync' logic
1. **Registry pattern**: SYNCABLE_ITEM_ASSOCIATIONS constant lists all
provider associations that participate in family sync
2. **Encapsulated sync-readiness**: Each item model defines its own
`syncable` scope that knows when it's ready for auto-sync:
- Most providers: `syncable = active` (not scheduled for deletion)
- SnapTrade: `syncable = active + user_registered` (has API creds)
3. **Single loop**: child_syncables iterates the registry, calling
`.syncable` on each association
- Adding a provider = add to registry + define syncable scope
- Each model owns its 'ready to sync' business logic
- Fixes plaid_items bug (now uses .active via .syncable)
- Fixes snaptrade auto-sync failures (filters unregistered items)
- Easy to extend with new conditions per provider
- family/syncer.rb: Registry + dynamic collection
- *_item.rb (7 files): Add `scope :syncable, -> { active }`
- snaptrade_item.rb: Add syncable with user_registered filter
* Fix rubocop bracket spacing in SnaptradeItem syncable scope
* Use dependent: :purge_later for user profile_image cleanup
This is a simpler alternative to PR #787's callback-based approach.
Instead of adding a custom callback and method, we use Rails' built-in
`dependent: :purge_later` option which is already used by FamilyExport
and other models in the codebase.
This single-line change ensures orphaned ActiveStorage attachments are
automatically purged when a user is destroyed, without the overhead of
querying all attachments manually.
https://claude.ai/code/session_01Np3deHEAJqCBfz3aY7c3Tk
* Add dependent: :purge_later to all ActiveStorage attachments
Extends the attachment cleanup from PR #787 to cover ALL models with
ActiveStorage attachments, not just User.profile_image.
Models updated:
- PdfImport.pdf_file - prevents orphaned PDF files from imports
- Account.logo - prevents orphaned account logos
- PlaidItem.logo, SimplefinItem.logo, SnaptradeItem.logo,
CoinstatsItem.logo, CoinbaseItem.logo, LunchflowItem.logo,
MercuryItem.logo, EnableBankingItem.logo - prevents orphaned
provider logos
This ensures that when a family is deleted (cascade from last user
purge), all associated storage files are properly cleaned up via
Rails' built-in dependent: :purge_later mechanism.
https://claude.ai/code/session_01Np3deHEAJqCBfz3aY7c3Tk
* Make sure `Provider` generator adds it
* Fix tests
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Initial sec
* Update PII fields
* FIX add tests
* FIX safely read plaintext data on rake backfill
* Update user.rb
* FIX tests
* encryption_ready? block
* Test conditional to encryption on
---------
Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
* Move provider config to family
* remove global settings
* Remove turbo auto submit
* Fix flash location
* Fix mssing syncer for lunchflow
* Update schema.rb
* FIX tests and encryption config
* FIX make rabbit happy
* FIX run migration in SQL
* FIX turbo frame modal
* Branding fixes
* FIX rabbit
* OCD with product names
* More OCD
* No other console.log|warn in codebase
---------
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
* Add support to unlink lunch flow accounts
* add support to link and unlink to any provider
* Fix tests and query
* Let's keep Amr happy about his brand
* Wrap unlink operations in a transaction and add error handling.
* Fix tests
---------
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
- Add support to link existing account with lunch-flow
The account will be promoted to a lunch flow connection now
( TBD if we want to allow un-linking? )
- Add support for proper de-dup at provider import level. This will handle de-dups for Lunch Flow, Plaid and SimpleFIN
- Fix plaid account removal on invalid credentials
* Remove skipped account functionality from SimpleFin
- Remove "Skip - don't add" option from account setup
- Simplify account setup flow to require all accounts be assigned types
- Update controller logic to handle all accounts without skipping
- Redirect to accounts page instead of SimpleFin items page
- Add I18N message support with t(".success")
* Simplify SimpleFin sync logic by removing skipped accounts
- Remove skipped account filtering from syncer
- All unlinked accounts now block sync until setup is complete
- Remove skipped account UI elements from setup view
- Streamline sync flow without complex skipped/non-skipped logic
* Fix cash balance calculation for SimpleFin investment accounts
- Update SimplefinAccount::Processor to recalculate balances during sync
- Properly calculate cash_balance for investment accounts using BalanceCalculator
- Handle negative balances for credit cards and loans correctly
- Ensure account balance and cash balance are updated from latest SimpleFin data
* Add I18N translations and edit view for SimpleFin
- Add comprehensive English translations for SimpleFin UI
- Create edit view for SimpleFin re-authentication
- Support status messages, errors, and user feedback
- Match translation structure with Plaid integration
* Add specialized SimpleFin data processors
- Add investment processors for transactions, holdings, and balance calculation
- Add liability processors for credit cards and loans
- Add transaction processor for standard account transactions
- Add account importer for SimpleFin account data
- Organize processors by account type for maintainable architecture
* Add loading button controller for SimpleFin forms
- Add Stimulus controller to show loading state during form submission
- Disable button and show loading text to prevent double submissions
- Improve user experience during SimpleFin account setup
* Add SimpleFin edit and update routes
- Add edit and update actions to SimpleFin items routes
- Enable re-authentication flow for expired SimpleFin connections
- Match route structure with Plaid items for consistency
* Add institution metadata fields to SimpleFin items
- Add institution_id, institution_name, institution_domain fields
- Add institution_url, institution_color for UI customization
- Add raw_institution_payload for complete institution data storage
- Enable better institution organization and display
* Enhance SimpleFin item with institution support and metadata
- Add institution summary and connected institutions methods
- Store and retrieve institution metadata from SimpleFin API
- Add institution-aware import functionality
- Support multiple institutions per SimpleFin connection
* Fix account creation and Plaid provider issues
- Fix cash balance calculation in Account.create_from_simplefin_account
- Add nil check for plaid_provider in remove_plaid_item method
- Ensure proper balance handling for investment accounts during creation
* Improve sync parent relationship handling
- Add parent sync assignment for existing syncs when parent_sync is provided
- Ensure sync hierarchy is maintained when expanding sync windows
- Fix sync relationship consistency in nested sync operations
* Update SimpleFin item view with enhanced UI
- Improve SimpleFin connection display and status information
- Add better visual styling and user feedback
- Match UI consistency with Plaid item views
* Update database schema with institution fields
- Add institution metadata fields to simplefin_items table
- Support institution tracking and organization features
* Update SimpleFin tests for new functionality
- Update controller tests for edit/update actions and removed skip functionality
- Update model tests for institution metadata and enhanced features
- Ensure test coverage for SimpleFin improvements
* Add migration to remove old institution fields
* Fix linting issues
* Apply suggestion from @coderabbitai[bot]
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Himmelschmidt <46351743+Himmelschmidt@users.noreply.github.com>
* Fix 2 failing tests
* Wrap SimpleFin account transfer in database transaction
* Make loading button controller more reusable
- Add loadingText Stimulus value for configurable loading text
- Remove unused originalText variable
- Update view to pass loading text via data attribute
* Remove unused SimplefinAccount::Importer class
This class was added in the PR but is never called anywhere in the codebase.
The actual SimpleFin account processing is handled by SimplefinAccount::Processor
and its specialized sub-processors.
* Fix SimpleFin account transfer bug during token updates
- Call import_latest_simplefin_data before account transfer to ensure
new SimpleFin accounts exist with account_id populated
- Prevents silent failure where accounts become orphaned when
refreshing expired SimpleFin tokens
* Fix SimpleFin error handling to render correct template and use i18n
- Update render_error method to accept context parameter for template selection
- Fix update action to render :edit template instead of :new on errors
- Replace hardcoded error messages with localized strings using t() calls
- Add comprehensive error message keys to SimpleFin locale file
* Improve loading button accessibility and HTML semantics
- Add aria-disabled and aria-busy attributes for screen readers
- Use semantic span elements instead of divs for button content
- Add aria-hidden to decorative spinner element
* Fix SimpleFin SSL verification to use OpenSSL constant
* Remove HTTParty streaming to prevent empty response body and PII logging
* Use BigDecimal zero for consistent numeric types in balance calculator
* Add investment account guard to holdings processor
* Remove duplicate balance normalization from SimpleFin loan processor
* Fix critical account deletion bug in SimpleFin token update
* Fix linting issues in SimpleFin controller tests
* Replace hardcoded colors with design system tokens in SimpleFin views
* Gate investment processors to Investment accounts only
Prevents investment processors from running on non-Investment account types,
matching the pattern used by liability processors.
* Localize hardcoded strings in SimpleFin edit form
* Adding the error message to a hover state.
* Use only 1 month for sync_start_date, new account restriction?
* Harden investment cash_balance calculation with error handling
- Add try/catch around SimplefinAccount::Investments::BalanceCalculator
- Fallback to zero on calculation errors or nil results
- Log warning with error details for debugging
- Prevents nil cash_balance that could cause downstream issues
* Fix SimpleFin institution fields migration and add DB constraints
- Remove destructive migration that dropped existing institution fields
- Add only new fields (institution_domain, institution_color)
- Add indexes on institution fields for query performance
- Add NOT NULL constraints on required fields (institution_id, institution_name)
- Fix schema jsonb consistency for raw_institution_payload
* Improve SimpleFin holdings error handling and BigDecimal consistency
* Add security attribute to external link in SimpleFin edit form
* Improve SimpleFin sync timing and add user-configurable date range
- Fix initial sync timing issue: change from 1 month to 7 days default lookback
- Add user-selectable sync start date in account setup UI
- Implement chunked historical sync that respects user-selected date range
- Add sync_start_date field to SimpleFin items
- Handle new accounts on existing connections with same date picker
This addresses SimpleFin API limitations and gives users control over
how much transaction history to sync during initial setup.
* Fix SimpleFin sync status to show detailed results instead of "Never synced"
- Modify sync completion logic to always complete even with unlinked accounts
- Add sync_stats column to track account sync statistics during sync process
- Update sync status display to show "X synced, Y need setup" instead of "Never synced"
- Store detailed sync statistics (total, linked, unlinked accounts) in sync record
- Add sync_status_summary method to provide meaningful status text
- Remove early return that prevented sync completion when accounts need setup
Resolves issue where successful account syncing still showed "Never synced" status.
* Fix Transaction persistence before Entry creation in SimpleFin processor
Persist Transaction with create! instead of new to ensure it has an ID before
creating Entry that references it as entryable. Prevents foreign key errors.
* Fix indifferent access for SimpleFin institution data extraction
The accounts_snapshot parameter comes from JSON with string keys, but the
code was accessing with symbol keys which could silently fail. Convert to
indifferent access to handle both string and symbol keys properly.
* Localize hardcoded deletion in progress string
Replace hardcoded "(deletion in progress...)" text with I18n translation
to maintain consistency with the rest of the view.
* Fix SimpleFin item update test to properly verify rebind/destroy behavior
The test now creates a different SimplefinItem instance and mocks
create_simplefin_item! to return it, ensuring the controller operates
on a new record instead of the same instance. This properly exercises
the rebind/destroy logic and verifies the original item is scheduled
for deletion.
* Fix potential transaction data loss in SimpleFin importer
Prevent wiping stored transactions when API omits transaction data by only
updating raw_transactions_payload when transactions are actually present
in the response, preserving existing transaction data when API doesn't
include transactions key.
* Fix SimpleFin sync chunking and enforce 3-year historical limit
- Fix SimpleFin's actual API limit from 365 days to 60 days per request
- Implement proper backward-walking chunked sync for historical data
- Enforce 3-year maximum historical data limit (60 days × 22 requests)
- Update date picker to reflect 3-year limit and better defaults
- Add comprehensive logging for debugging sync issues
* Add dedicated raw_holdings_payload storage for SimpleFin accounts
- Add raw_holdings_payload column to simplefin_accounts table
- Separates holdings data from general account data for cleaner processing
- Follows same pattern as raw_transactions_payload for consistency
- Enables proper SimpleFin holdings processing pipeline
* Enhance SimpleFin holdings storage with external ID tracking
- Add external_id and cost_basis columns to holdings table
- Update holdings processor to use external_id for precise matching
- Capture all available SimpleFin holdings data (shares, market_value, cost_basis, etc.)
- Use SimpleFin holding ID as external_id with "simplefin_" prefix
- Calculate price from market_value/shares when available
- Store raw holdings payload in simplefin_accounts for complete data retention
This enables better holdings tracking than composite key approach and ensures
we capture all SimpleFin data even if not immediately used in our models.
* Simplify SimpleFin transaction enrichment
- Add MerchantDetector that uses payee field directly for merchant creation
- Enhance SimpleFin entry name generation combining payee + description
- Remove transaction processor category matching logic
- Create dedicated SimpleFin entry processor
Uses SimpleFin's clean payee data without unnecessary filtering.
* Add source field to ProviderMerchant and fix data enrichment
- Add source field to ProviderMerchant model for provider-specific merchant tracking
- Fix DataEnrichment to handle string transaction IDs correctly with to_i conversion
Enables per-provider merchant deduplication and fixes transaction lookups.
* Fix SimpleFin controller parameter handling
- Convert string account_ids to integers for proper account lookup
- Ensure account selection works correctly with form submissions
Fixes account filtering when setting up SimpleFin sync.
* Fix linting issues - auto-corrected whitespace and formatting
* Derive institution domain from URL when missing in SimpleFin items
* Fix render_error to preserve persisted record for edit context
* Add unique index to prevent duplicate holdings
* Fix potential NameError in holdings processor rescue block
* Guard against missing SimpleFin transaction IDs
* Fix SimpleFin amount parsing error handling
Re-raise ArgumentError instead of silently returning BigDecimal("0")
to prevent misleading $0 transactions from invalid amount data.
* Fix SimpleFin chunked import data loss bug
Merge transaction arrays instead of overwriting to prevent data loss
during chunked imports. Preserve most recent holdings data only.
* Add external_id uniqueness validation to Holding model
* Fix holdings cost_basis precision and add external_id unique constraint
* Fix SimpleFin test mock expectations and remove debug statements
- Fixed SimplefinItemsControllerTest by properly mocking Provider::Simplefin
instead of over-mocking the create_simplefin_item! method
- Removed DEBUG puts statements from SimplefinItem::Importer
* Fix linting issues - auto-corrected whitespace and formatting
---------
Signed-off-by: Himmelschmidt <46351743+Himmelschmidt@users.noreply.github.com>
Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
* Balance sheet cache layer with cache-busting
* Update family cache timestamps during Sync
* Less blocking sync loaders
* Consolidate family data caching key logic
* Fix turbo stream broadcasts
* Remove dev delay
* Add back account group sorting
Breaks our Plaid sync process out into more manageable classes. Notably, this moves the sync process to a distinct, 2-step flow:
1. Import stage - we first make API calls and import Plaid data to "mirror" tables
2. Processing stage - read the raw data, apply business rules, build internal domain models and sync balances
This provides several benefits:
- Plaid syncs can now be "replayed" without fetching API data again
- Mirror tables provide better audit and debugging capabilities
- Eliminates the "all or nothing" sync behavior that is currently in place, which is brittle
* Domain model sketch
* Scaffold out rules domain
* Migrations
* Remove existing data enrichment for clean slate
* Sketch out business logic and basic tests
* Simplify rule scope building and action executions
* Get generator working again
* Basic implementation + tests
* Remove manual merchant management (rules will replace)
* Revert "Remove manual merchant management (rules will replace)"
This reverts commit 83dcbd9ff0aa7bbee211796b71aa48b71df5e57e.
* Family and Provider merchants model
* Fix brakeman warnings
* Fix notification loader
* Update notification position
* Add Rule action and condition registries
* Rule form with compound conditions and tests
* Split out notification types, add CTA type
* Rules form builder and Stimulus controller
* Clean up rule registry domain
* Clean up rules stimulus controller
* CTA message for rule when user changes transaction category
* Fix tests
* Lint updates
* Centralize notifications in Notifiable concern
* Implement category rule prompts with auto backoff and option to disable
* Fix layout bug caused by merge conflict
* Initialize rule with correct action for category CTA
* Add rule deletions, get rules working
* Complete dynamic rule form, split Stimulus controllers by resource
* Fix failing tests
* Change test password to avoid chromium conflicts
* Update integration tests
* Centralize all test password references
* Add re-apply rule action
* Rule confirm modal
* Run migrations
* Trigger rule notification after inline category updates
* Clean up rule styles
* Basic attribute locking for rules
* Apply attribute locks on user edits
* Log data enrichments, only apply rules to unlocked attributes
* Fix merge errors
* Additional merge conflict fixes
* Form UI improvements, ignore attribute locks on manual rule application
* Batch AI auto-categorization of transactions
* Auto merchant detection, ai enrichment in batches
* Fix Plaid merchant assignments
* Plaid category matching
* Cleanup 1
* Test cleanup
* Remove stale route
* Fix desktop chat UI issues
* Fix mobile nav styling issues
* Placeholder logic for missing prices
* Generate holdings properly for "offline" securities
* Separate forward and reverse calculators for holdings and balances
* Remove unnecessary currency conversion during sync
* Clearer sync process
* Move price caching logic to dedicated model
* Base holding calculator
* Base calculator for balances
* Finish balance calculators
* Better naming
* Logs cleanup
* Remove stale data type
* Remove stale test
* Fix price lookup logic for holdings sync
* Fix Plaid item sync regression
* Remove temp logging
* Calculate cash and holdings series
* Add holdings, cash, and balance series dropdown for investments
* Enhance Plaid connection management with re-authentication and error handling
- Add support for Plaid item status tracking (good/requires_update)
- Implement re-authentication flow for Plaid connections
- Handle connection errors and provide user-friendly reconnection options
- Update Plaid link token generation to support item updates
- Add localization for new connection management states
* Remove redundant 'reconnect' localization for Plaid items
* feat: Add institution details to Plaid items
- Fetch and store institution URL, ID, and primary color for Plaid items
- Update PlaidItem model to retrieve and save institution metadata
- Add new method in Plaid provider to get institution details
- Update account logo view to use institution domain for logo generation
* Add institution domain method to Account model
- Extract institution domain logic from view to Account model
- Simplify logo view by using new institution_domain method
- Improve code reusability and separation of concerns
* Initial pass at Plaid EU
* Add EU support to Plaid Items
* Lint
* Temp fix for rubocop isseus
* Merge cleanup
* Pass in region and get tests passing
* Use absolute path for translation
---------
Signed-off-by: Josh Pigford <josh@joshpigford.com>
* Basic plaid data model and linking
* Remove institutions, add plaid items
* Improve schema and Plaid provider
* Add webhook verification sketch
* Webhook verification
* Item accounts and balances sync setup
* Provide test encryption keys
* Fix test
* Only provide encryption keys in prod
* Try defining keys in test env
* Consolidate account sync logic
* Add back plaid account initialization
* Plaid transaction sync
* Sync UI overhaul for Plaid
* Add liability and investment syncing
* Handle investment webhooks and process current day holdings
* Remove logs
* Remove "all" period select for performance
* fix amount calc
* Remove todo comment
* Coming soon for investment historical data
* Document Plaid configuration
* Listen for holding updates