Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Weekly cleanup proactive insights chat for family admins (#3441) (#3442)

Juan José Mata4eb56b8e8d8d
diff --git a/app/jobs/weekly_cleanup_job.rb b/app/jobs/weekly_cleanup_job.rb
new file mode 100644
index 0000000000..fa1e9c5cfe
--- /dev/null
+++ b/app/jobs/weekly_cleanup_job.rb
@@ -0,0 +1,68 @@
+# Weekly proactive cleanup: runs the read-only WeeklyCleanup detectors per
+# family and opens one proactive chat per admin with the findings.
+#
+# Mirrors GenerateInsightsJob's shape: cron entry fans out one job per
+# preview-enabled family, each family run is re-gated and advisory-locked, and
+# the per-admin chat creation is idempotent via WeeklyCleanupRun.
+class WeeklyCleanupJob < ApplicationJob
+ queue_as :scheduled
+ sidekiq_options lock: :until_executed, on_conflict: :log
+
+ # Without args (cron): fans out one job per family.
+ # With family_id: generates this family's cleanup chats.
+ def perform(family_id: nil)
+ if family_id.present?
+ generate_for_family(family_id)
+ else
+ fan_out
+ end
+ end
+
+ private
+ def fan_out
+ Family.with_preview_features.find_each do |family|
+ WeeklyCleanupJob.perform_later(family_id: family.id)
+ rescue => e
+ Rails.logger.error("Failed to enqueue weekly cleanup for family #{family.id}: #{e.message}")
+ end
+ end
+
+ def generate_for_family(family_id)
+ family = Family.find_by(id: family_id)
+ return unless family
+ return if family.accounts.none?
+ # Re-gated here, not just at fan-out: this path is reachable directly via
+ # perform_later(family_id:).
+ return unless family.preview_features_enabled?
+
+ with_advisory_lock(family_id) do
+ I18n.with_locale(family.locale) do
+ WeeklyCleanup::ChatCreator.call(family:)
+ end
+ end
+ end
+
+ def with_advisory_lock(family_id)
+ lock_key = advisory_lock_key(family_id)
+ acquired = ActiveRecord::Base.connection.select_value(
+ ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_try_advisory_lock(?)", lock_key ])
+ )
+
+ unless acquired
+ Rails.logger.warn("Skipped weekly cleanup for family #{family_id}: advisory lock unavailable")
+ return
+ end
+
+ begin
+ yield
+ ensure
+ ActiveRecord::Base.connection.execute(
+ ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_advisory_unlock(?)", lock_key ])
+ )
+ end
+ end
+
+ def advisory_lock_key(family_id)
+ Digest::MD5.hexdigest("weekly_cleanup:#{family_id}").to_i(16) % (2**62)
+ end
+end
diff --git a/app/models/weekly_cleanup/chat_creator.rb b/app/models/weekly_cleanup/chat_creator.rb
new file mode 100644
index 0000000000..e2fea93efb
--- /dev/null
+++ b/app/models/weekly_cleanup/chat_creator.rb
@@ -0,0 +1,66 @@
+# Creates the proactive weekly cleanup chat: one user-owned Chat per family
+# admin, seeded with a single complete assistant message containing the
+# deterministic findings report. Idempotent per admin per weekly period via
+# WeeklyCleanupRun — reruns skip admins who already have this week's chat.
+class WeeklyCleanup::ChatCreator
+ def self.call(family:, period_start: WeeklyCleanupRun.period_for(family.local_date))
+ new(family:, period_start:).call
+ end
+
+ def initialize(family:, period_start:)
+ @family = family
+ @period_start = period_start
+ end
+
+ def call
+ created = []
+
+ admins.each do |user|
+ next if WeeklyCleanupRun.exists?(family:, user:, period_start:)
+
+ # Findings are built per admin so an account they can't access never
+ # shows up by name in their chat.
+ findings = collect_findings(user)
+ # A failed detector must not look like a clean week or burn the period:
+ # skip so the next run retries.
+ next if findings.nil?
+
+ report = WeeklyCleanup::Report.new(family:, findings:)
+ chat = nil
+ WeeklyCleanupRun.transaction do
+ chat = user.chats.create!(
+ title: report.title(period_start),
+ messages: [ AssistantMessage.new(content: report.markdown, ai_model: Chat.default_model, status: :complete) ]
+ )
+ WeeklyCleanupRun.create!(family:, user:, period_start:, summary: report.summary)
+ end
+ created << chat
+ end
+
+ created
+ end
+
+ private
+ attr_reader :family, :period_start
+
+ # Admin-only by design: findings are family-wide and can name merchants,
+ # categories, and amounts that members (or guests) must not see.
+ # Deactivated users and admins with AI turned off don't get a chat.
+ def admins
+ family.users.select { |user| user.admin? && user.active? && user.ai_enabled? }
+ end
+
+ # Returns nil when any detector raised, so a partial scan is never
+ # reported (or recorded) as a complete one.
+ def collect_findings(user)
+ failed = false
+ findings = WeeklyCleanup::Detector.registry.filter_map do |detector_class|
+ detector_class.new(family, user:).generate
+ rescue => e
+ failed = true
+ Rails.logger.error("WeeklyCleanup: detector #{detector_class.key} failed for family #{family.id}: #{e.class}: #{e.message}")
+ nil
+ end
+ failed ? nil : findings
+ end
+end
diff --git a/app/models/weekly_cleanup/detector.rb b/app/models/weekly_cleanup/detector.rb
new file mode 100644
index 0000000000..4fbc9720cf
--- /dev/null
+++ b/app/models/weekly_cleanup/detector.rb
@@ -0,0 +1,74 @@
+# Base class for weekly cleanup detectors. Each detector answers one question
+# about the family's books over a fixed window and returns a Finding (or nil
+# when everything is clean). Detectors are strictly read-only: they SELECT and
+# present, they never mutate.
+class WeeklyCleanup::Detector
+ WINDOW = 7.days
+ MAX_SAMPLES = 5
+
+ Finding = Data.define(:key, :heading, :count, :samples)
+
+ def self.registry
+ [
+ WeeklyCleanup::Detectors::UncategorizedTransactions,
+ WeeklyCleanup::Detectors::StaleImports,
+ WeeklyCleanup::Detectors::ProviderDataGaps,
+ WeeklyCleanup::Detectors::MissingMerchantInfo,
+ WeeklyCleanup::Detectors::DuplicateImportedEntries,
+ WeeklyCleanup::Detectors::MissingContext,
+ WeeklyCleanup::Detectors::MerchantDuplicates
+ ]
+ end
+
+ def self.key
+ name.demodulize.underscore
+ end
+
+ # `user` scopes account-level findings to what that admin can access
+ # (Account.accessible_by). Without one, findings cover every family account.
+ def initialize(family, user: nil)
+ @family = family
+ @user = user
+ end
+
+ # Returns a Finding, or nil when the detector found nothing worth reporting.
+ def generate
+ raise NotImplementedError
+ end
+
+ private
+ attr_reader :family, :user
+
+ # The family's calendar date, not the job's (UTC) one.
+ def today
+ family.local_date
+ end
+
+ def window_start
+ today - WINDOW.in_days.to_i
+ end
+
+ def accounts
+ user ? user.accessible_accounts : family.accounts
+ end
+
+ def entries
+ Entry.where(account_id: accounts.select(:id))
+ end
+
+ def finding(heading:, count:, samples: [])
+ return nil if count.zero?
+
+ Finding.new(key: self.class.key, heading: heading, count: count, samples: samples.first(MAX_SAMPLES))
+ end
+
+ # Recent standard (non-transfer, non-excluded) purchase/refund transactions
+ # joined to their entries — the base relation most detectors filter further.
+ def recent_standard_entries(since: window_start)
+ entries
+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")
+ .where(entryable_type: "Transaction", excluded: false)
+ .where(transactions: { kind: "standard" })
+ .where("entries.date >= ? AND entries.date <= ?", since, today)
+ end
+end
diff --git a/app/models/weekly_cleanup/detectors/duplicate_imported_entries.rb b/app/models/weekly_cleanup/detectors/duplicate_imported_entries.rb
new file mode 100644
index 0000000000..4e7fa2c941
--- /dev/null
+++ b/app/models/weekly_cleanup/detectors/duplicate_imported_entries.rb
@@ -0,0 +1,26 @@
+# Issue #3441 first-pass scope item 5: duplicate or overlapping imported data.
+# Flags import-created entries that look duplicated: same account, date,
+# amount, and normalized name appearing more than once in the window.
+class WeeklyCleanup::Detectors::DuplicateImportedEntries < WeeklyCleanup::Detector
+ DUPLICATE_WINDOW = 30.days
+
+ def generate
+ groups = entries
+ .where.not(import_id: nil)
+ .where("entries.date >= ? AND entries.date <= ?", today - DUPLICATE_WINDOW.in_days.to_i, today)
+ .group(:account_id, :date, :amount, Arel.sql("lower(entries.name)"))
+ .having("COUNT(*) > 1")
+ .pluck(:account_id, :date, :amount, Arel.sql("lower(entries.name)"), Arel.sql("COUNT(*)"))
+
+ samples = groups.first(MAX_SAMPLES).map do |account_id, date, amount, name, n|
+ account_name = accounts.detect { |a| a.id == account_id }&.name || "?"
+ "#{date} — #{name} (#{n}x, #{account_name})"
+ end
+
+ finding(
+ heading: I18n.t("weekly_cleanup.detectors.duplicate_imported_entries.heading"),
+ count: groups.size,
+ samples: samples
+ )
+ end
+end
diff --git a/app/models/weekly_cleanup/detectors/merchant_duplicates.rb b/app/models/weekly_cleanup/detectors/merchant_duplicates.rb
new file mode 100644
index 0000000000..c86e1c5084
--- /dev/null
+++ b/app/models/weekly_cleanup/detectors/merchant_duplicates.rb
@@ -0,0 +1,24 @@
+# The merchant de-dup report (deterministic — WeeklyCleanup::MerchantDedup does
+# normalization + trigram similarity; no LLM). Surfaces likely duplicate
+# merchant clusters so an admin can merge them by hand.
+class WeeklyCleanup::Detectors::MerchantDuplicates < WeeklyCleanup::Detector
+ MAX_CLUSTERS_LISTED = 5
+
+ def generate
+ result = WeeklyCleanup::MerchantDedup.call(family.merchants.alphabetically)
+ return nil if result.clusters.empty?
+
+ samples = result.clusters.first(MAX_CLUSTERS_LISTED).map do |cluster|
+ names = cluster.members.map(&:name)
+ "#{names.first} ⇄ #{names.second}" + (cluster.members.size > 2 ? " (+#{cluster.members.size - 2} more)" : "")
+ end
+
+ Finding.new(
+ key: self.class.key,
+ heading: I18n.t("weekly_cleanup.detectors.merchant_duplicates.heading",
+ total: result.total, clusters: result.clusters.size, coverage: result.coverage_pct),
+ count: result.clusters.size,
+ samples: samples
+ )
+ end
+end
diff --git a/app/models/weekly_cleanup/detectors/missing_context.rb b/app/models/weekly_cleanup/detectors/missing_context.rb
new file mode 100644
index 0000000000..18ff5bb366
--- /dev/null
+++ b/app/models/weekly_cleanup/detectors/missing_context.rb
@@ -0,0 +1,28 @@
+# Issue #3441 first-pass scope item 6: missing receipts, notes, or transaction
+# context. Flags recent larger expenses with neither a note nor an attachment —
+# the transactions most likely to need "what was this?" context later.
+class WeeklyCleanup::Detectors::MissingContext < WeeklyCleanup::Detector
+ AMOUNT_THRESHOLD = 100
+
+ def generate
+ scope = recent_standard_entries
+ .where("entries.amount >= ?", AMOUNT_THRESHOLD)
+ .where("entries.notes IS NULL OR entries.notes = ''")
+ .where(<<~SQL.squish)
+ NOT EXISTS (
+ SELECT 1 FROM active_storage_attachments asa
+ WHERE asa.record_type = 'Transaction' AND asa.record_id = transactions.id AND asa.name = 'attachments'
+ )
+ SQL
+
+ samples = scope.includes(:entryable).order(amount: :desc).limit(MAX_SAMPLES).map do |entry|
+ "#{entry.date} — #{entry.name} (#{entry.amount_money.format})"
+ end
+
+ finding(
+ heading: I18n.t("weekly_cleanup.detectors.missing_context.heading"),
+ count: scope.count,
+ samples: samples
+ )
+ end
+end
diff --git a/app/models/weekly_cleanup/detectors/missing_merchant_info.rb b/app/models/weekly_cleanup/detectors/missing_merchant_info.rb
new file mode 100644
index 0000000000..053663837c
--- /dev/null
+++ b/app/models/weekly_cleanup/detectors/missing_merchant_info.rb
@@ -0,0 +1,17 @@
+# Issue #3441 first-pass scope item 4: missing or suspicious merchant/category
+# information. Surfaces recent standard transactions with no merchant linked —
+# these are the rows most likely to also be miscategorized.
+class WeeklyCleanup::Detectors::MissingMerchantInfo < WeeklyCleanup::Detector
+ def generate
+ scope = recent_standard_entries.where(transactions: { merchant_id: nil })
+ samples = scope.includes(:entryable).order(date: :desc).limit(MAX_SAMPLES).map do |entry|
+ "#{entry.date} — #{entry.name} (#{entry.amount_money.format})"
+ end
+
+ finding(
+ heading: I18n.t("weekly_cleanup.detectors.missing_merchant_info.heading"),
+ count: scope.count,
+ samples: samples
+ )
+ end
+end
diff --git a/app/models/weekly_cleanup/detectors/provider_data_gaps.rb b/app/models/weekly_cleanup/detectors/provider_data_gaps.rb
new file mode 100644
index 0000000000..57ed06c670
--- /dev/null
+++ b/app/models/weekly_cleanup/detectors/provider_data_gaps.rb
@@ -0,0 +1,49 @@
+# Issue #3441 first-pass scope item 3: missing data from connected providers.
+# Flags recent failed or stale sync runs for syncables that belong to this
+# family (provider items, the family umbrella sync, etc.) — a failed/stale
+# sync means fresh provider data is not flowing.
+class WeeklyCleanup::Detectors::ProviderDataGaps < WeeklyCleanup::Detector
+ def generate
+ recent = Sync.where(status: %w[failed stale]).where("syncs.created_at >= ?", window_start)
+ count = 0
+ samples = []
+
+ recent.distinct.pluck(:syncable_type).each do |type|
+ klass = type.safe_constantize
+ next unless klass
+
+ # The family umbrella sync is keyed by syncable_id == family.id; every
+ # other syncable is owned through its family_id column.
+ owned_ids =
+ if type == "Family"
+ [ family.id ]
+ elsif klass.column_names.include?("family_id")
+ klass.where(family_id: family.id).select(:id)
+ else
+ next
+ end
+
+ # Only syncables whose latest sync is still failed/stale: a later run that
+ # went through means provider data is flowing again.
+ owned = recent.where(syncable_type: type, syncable_id: owned_ids).where(<<~SQL.squish)
+ NOT EXISTS (
+ SELECT 1 FROM syncs later
+ WHERE later.syncable_type = syncs.syncable_type
+ AND later.syncable_id = syncs.syncable_id
+ AND later.created_at > syncs.created_at
+ AND later.status = 'completed'
+ )
+ SQL
+ count += owned.count
+ owned.order(created_at: :desc).limit(MAX_SAMPLES).each do |sync|
+ samples << "#{type.underscore.humanize} — #{sync.status} (#{sync.created_at.to_date})"
+ end
+ end
+
+ finding(
+ heading: I18n.t("weekly_cleanup.detectors.provider_data_gaps.heading"),
+ count: count,
+ samples: samples.first(MAX_SAMPLES)
+ )
+ end
+end
diff --git a/app/models/weekly_cleanup/detectors/stale_imports.rb b/app/models/weekly_cleanup/detectors/stale_imports.rb
new file mode 100644
index 0000000000..b2198ac8fa
--- /dev/null
+++ b/app/models/weekly_cleanup/detectors/stale_imports.rb
@@ -0,0 +1,21 @@
+# Issue #3441 first-pass scope item 2: stale imports. Imports that failed
+# recently or that are stuck in a processing state past Import::STUCK_AFTER
+# (the same threshold SyncCleanerJob uses to reap them).
+class WeeklyCleanup::Detectors::StaleImports < WeeklyCleanup::Detector
+ def generate
+ imports = family.imports.where(account_id: [ nil, *accounts.select(:id) ])
+ failed = imports.where(status: "failed").where("imports.updated_at >= ?", window_start)
+ stuck = imports.where(status: %w[importing reverting]).where("imports.updated_at < ?", Import::STUCK_AFTER.ago)
+ scope = failed.or(stuck)
+
+ samples = scope.order(updated_at: :desc).limit(MAX_SAMPLES).map do |import|
+ "#{import.type.demodulize.underscore.humanize} — #{import.status} (#{import.updated_at.to_date})"
+ end
+
+ finding(
+ heading: I18n.t("weekly_cleanup.detectors.stale_imports.heading"),
+ count: scope.count,
+ samples: samples
+ )
+ end
+end
diff --git a/app/models/weekly_cleanup/detectors/uncategorized_transactions.rb b/app/models/weekly_cleanup/detectors/uncategorized_transactions.rb
new file mode 100644
index 0000000000..34e7374f21
--- /dev/null
+++ b/app/models/weekly_cleanup/detectors/uncategorized_transactions.rb
@@ -0,0 +1,17 @@
+# Issue #3441 first-pass scope item 1: uncategorized or hard-to-categorize
+# transactions. Surfaces recent standard transactions that landed without a
+# category so an admin can triage them.
+class WeeklyCleanup::Detectors::UncategorizedTransactions < WeeklyCleanup::Detector
+ def generate
+ scope = recent_standard_entries.where(transactions: { category_id: nil })
+ samples = scope.includes(:entryable).order(date: :desc).limit(MAX_SAMPLES).map do |entry|
+ "#{entry.date} — #{entry.name} (#{entry.amount_money.format})"
+ end
+
+ finding(
+ heading: I18n.t("weekly_cleanup.detectors.uncategorized_transactions.heading"),
+ count: scope.count,
+ samples: samples
+ )
+ end
+end
diff --git a/app/models/weekly_cleanup/merchant_dedup.rb b/app/models/weekly_cleanup/merchant_dedup.rb
new file mode 100644
index 0000000000..1d478c3598
--- /dev/null
+++ b/app/models/weekly_cleanup/merchant_dedup.rb
@@ -0,0 +1,97 @@
+# Deterministic merchant de-duplication: name normalization + character-trigram
+# (Jaccard) similarity, clustered with union-find. No LLM, no DB extensions —
+# pure Ruby so it behaves identically on every install.
+#
+# Result carries the total merchant count plus the duplicate clusters so the
+# report can present "351 merchants, 12 duplicate clusters (3.4% clustered)"
+# style coverage.
+class WeeklyCleanup::MerchantDedup
+ # Common business suffixes that rarely distinguish the actual merchant.
+ SUFFIXES = %w[
+ inc llc ltd ll lp llp corp corporation co company gmbh sarl sas bv nv ag
+ sa spa plc pty limited group holdings international intl
+ ].freeze
+
+ SIMILARITY_THRESHOLD = 0.6
+
+ Result = Data.define(:total, :clustered, :clusters) do
+ def coverage_pct
+ return 0 if total.zero?
+
+ (clustered.to_f / total * 100).round(1)
+ end
+ end
+
+ Cluster = Data.define(:members, :normalized_name)
+
+ def self.call(merchants)
+ new(merchants).call
+ end
+
+ def initialize(merchants)
+ @merchants = merchants.to_a
+ end
+
+ def call
+ normalized = @merchants.map { |m| [ m, self.class.normalize(m.name) ] }
+ # Skip merchants whose name normalizes to nothing (e.g. "###").
+ normalized = normalized.reject { |_, n| n.blank? }
+
+ parent = {}
+ find = ->(x) {
+ root = x
+ root = parent[root] while parent[root] && parent[root] != root
+ # path compression
+ while parent[x] && parent[x] != x
+ parent[x], x = root, parent[x]
+ end
+ root
+ }
+ union = ->(a, b) { parent[find.(a)] = find.(b) }
+
+ # Bucket by first trigram-rich token to avoid full O(n^2) on huge lists:
+ # only names sharing at least one token can reach the threshold anyway.
+ tokens = normalized.to_h { |m, n| [ m.object_id, n.split ] }
+ normalized.combination(2) do |(ma, na), (mb, nb)|
+ next if (tokens[ma.object_id] & tokens[mb.object_id]).empty? && na != nb
+
+ if na == nb || jaccard(trigrams(na), trigrams(nb)) >= SIMILARITY_THRESHOLD
+ union.(ma.object_id, mb.object_id)
+ end
+ end
+
+ groups = normalized.group_by { |m, _| find.(m.object_id) }.values
+ clusters = groups.select { |g| g.size > 1 }.map do |group|
+ members = group.map(&:first).sort_by(&:name)
+ Cluster.new(members: members, normalized_name: self.class.normalize(members.first.name))
+ end.sort_by { |c| -c.members.size }
+
+ Result.new(
+ total: @merchants.size,
+ clustered: clusters.sum { |c| c.members.size },
+ clusters: clusters
+ )
+ end
+
+ def self.normalize(name)
+ s = name.to_s.downcase
+ s = s.gsub(/&/, " and ")
+ s = s.gsub(/[^a-z0-9\s]/, " ") # punctuation (incl. store #1234) -> space
+ s = s.gsub(/\b\d{3,}\b/, " ") # long store/location numbers carry no brand signal
+ words = s.split - SUFFIXES
+ words.join(" ").squish
+ end
+
+ private
+ def trigrams(str)
+ padded = " #{str} "
+ padded.chars.each_cons(3).map(&:join).to_set
+ end
+
+ def jaccard(a, b)
+ return 1.0 if a == b
+ return 0.0 if a.empty? || b.empty?
+
+ (a & b).size.to_f / (a | b).size
+ end
+end
diff --git a/app/models/weekly_cleanup/report.rb b/app/models/weekly_cleanup/report.rb
new file mode 100644
index 0000000000..393eb7fc88
--- /dev/null
+++ b/app/models/weekly_cleanup/report.rb
@@ -0,0 +1,51 @@
+# Builds the deterministic markdown report seeded into the proactive cleanup
+# chat. Structured like a short assistant message: a one-line summary, then a
+# section per detector with counts and concrete examples. No LLM involved —
+# every number and name comes straight from the detectors.
+class WeeklyCleanup::Report
+ def self.markdown(family:, findings:)
+ new(family:, findings:).markdown
+ end
+
+ def initialize(family:, findings:)
+ @family = family
+ @findings = findings
+ end
+
+ def markdown
+ parts = [ intro ]
+ parts << clean_bill_of_health if findings.empty?
+ findings.each { |f| parts << section(f) }
+ parts << outro
+ parts.join("\n\n")
+ end
+
+ def title(date = family.local_date)
+ I18n.t("weekly_cleanup.chat_title", date: I18n.l(WeeklyCleanupRun.period_for(date), format: :long))
+ end
+
+ def summary
+ findings.to_h { |f| [ f.key, f.count ] }
+ end
+
+ private
+ attr_reader :family, :findings
+
+ def intro
+ I18n.t("weekly_cleanup.intro", count: findings.size)
+ end
+
+ def clean_bill_of_health
+ I18n.t("weekly_cleanup.clean")
+ end
+
+ def section(finding)
+ lines = [ "### #{finding.heading}" ]
+ lines.concat(finding.samples.map { |s| "- #{s}" })
+ lines.join("\n")
+ end
+
+ def outro
+ I18n.t("weekly_cleanup.outro")
+ end
+end
diff --git a/app/models/weekly_cleanup_run.rb b/app/models/weekly_cleanup_run.rb
new file mode 100644
index 0000000000..4a1510fb7d
--- /dev/null
+++ b/app/models/weekly_cleanup_run.rb
@@ -0,0 +1,16 @@
+# Minimal dedup record for WeeklyCleanupJob: one row per admin per weekly
+# period. Its existence means "this admin already got the proactive cleanup
+# chat for that week" — reruns of the job skip without respawning a chat.
+# The generated findings themselves live in the chat message; this table only
+# carries enough metadata to make reruns and debugging cheap.
+class WeeklyCleanupRun < ApplicationRecord
+ belongs_to :family
+ belongs_to :user
+
+ validates :period_start, presence: true
+ validates :period_start, uniqueness: { scope: [ :family_id, :user_id ] }
+
+ def self.period_for(date = Date.current)
+ date.beginning_of_week
+ end
+end
diff --git a/config/locales/views/weekly_cleanup/en.yml b/config/locales/views/weekly_cleanup/en.yml
new file mode 100644
index 0000000000..c9d56fc31b
--- /dev/null
+++ b/config/locales/views/weekly_cleanup/en.yml
@@ -0,0 +1,21 @@
+en:
+ weekly_cleanup:
+ chat_title: "Weekly cleanup — week of %{date}"
+ intro: "Here's your weekly cleanup report. I found %{count} area(s) worth a look — everything below is read-only; nothing has been changed."
+ clean: "Nothing to clean up this week — books look tidy."
+ outro: "Reply here if you want to dig into any of these — I can help you categorize, merge merchants, or review the duplicates."
+ detectors:
+ uncategorized_transactions:
+ heading: "Uncategorized transactions (past 7 days)"
+ stale_imports:
+ heading: "Stale or failed imports"
+ provider_data_gaps:
+ heading: "Provider sync problems (past 7 days)"
+ missing_merchant_info:
+ heading: "Transactions missing merchant info (past 7 days)"
+ duplicate_imported_entries:
+ heading: "Possible duplicate imported entries (past 30 days)"
+ missing_context:
+ heading: "Larger expenses without notes or receipts (past 7 days)"
+ merchant_duplicates:
+ heading: "Merchant de-duplication — %{total} merchants, %{clusters} duplicate clusters (%{coverage}% clustered)"
diff --git a/config/schedule.yml b/config/schedule.yml
index 57cadfb46c..fde324357e 100644
--- a/config/schedule.yml
+++ b/config/schedule.yml
@@ -88,6 +88,14 @@ generate_recurring_occurrences:
queue: "scheduled"
description: "Materializes the rolling window of recurring-transaction occurrences for every family"
+
+weekly_cleanup:
+ cron: "0 7 * * 1" # Mondays at 7:00 AM UTC, after the nightly jobs
+ class: "WeeklyCleanupJob"
+ active_job: true
+ queue: "scheduled"
+ description: "Opens a proactive weekly cleanup chat for each admin of preview-enabled families"
+
generate_insights:
cron: "0 6 * * *" # daily at 6:00 AM UTC, after the nightly cleanup jobs
class: "GenerateInsightsJob"
diff --git a/db/migrate/20260908012131_create_weekly_cleanup_runs.rb b/db/migrate/20260908012131_create_weekly_cleanup_runs.rb
new file mode 100644
index 0000000000..29a12c2785
--- /dev/null
+++ b/db/migrate/20260908012131_create_weekly_cleanup_runs.rb
@@ -0,0 +1,13 @@
+class CreateWeeklyCleanupRuns < ActiveRecord::Migration[8.1]
+ def change
+ create_table :weekly_cleanup_runs, id: :uuid do |t|
+ t.references :family, null: false, foreign_key: { on_delete: :cascade }, type: :uuid
+ t.references :user, null: false, foreign_key: { on_delete: :cascade }, type: :uuid
+ t.date :period_start, null: false
+ t.jsonb :summary, default: {}, null: false
+ t.timestamps
+
+ t.index [ :family_id, :user_id, :period_start ], unique: true, name: "idx_weekly_cleanup_runs_dedup"
+ end
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 0920665b2e..e8253560e0 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -3099,6 +3099,18 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) do
t.check_constraint "sign_count >= 0", name: "chk_webauthn_credentials_sign_count_non_negative"
end
+ create_table "weekly_cleanup_runs", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.datetime "created_at", null: false
+ t.uuid "family_id", null: false
+ t.date "period_start", null: false
+ t.jsonb "summary", default: {}, null: false
+ t.datetime "updated_at", null: false
+ t.uuid "user_id", null: false
+ t.index ["family_id", "user_id", "period_start"], name: "idx_weekly_cleanup_runs_dedup", unique: true
+ t.index ["family_id"], name: "index_weekly_cleanup_runs_on_family_id"
+ t.index ["user_id"], name: "index_weekly_cleanup_runs_on_user_id"
+ end
+
create_table "wise_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.string "balance_id", null: false
t.datetime "created_at", null: false
@@ -3335,4 +3347,6 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) do
add_foreign_key "webauthn_credentials", "users"
add_foreign_key "wise_accounts", "wise_items", on_delete: :cascade
add_foreign_key "wise_items", "families"
+ add_foreign_key "weekly_cleanup_runs", "families", on_delete: :cascade
+ add_foreign_key "weekly_cleanup_runs", "users", on_delete: :cascade
end
diff --git a/test/jobs/weekly_cleanup_job_test.rb b/test/jobs/weekly_cleanup_job_test.rb
new file mode 100644
index 0000000000..1bf3b7073b
--- /dev/null
+++ b/test/jobs/weekly_cleanup_job_test.rb
@@ -0,0 +1,120 @@
+require "test_helper"
+
+class WeeklyCleanupJobTest < ActiveJob::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @admin = users(:family_admin)
+ @member = users(:family_member)
+ @admin.update!(preferences: @admin.preferences.merge("preview_features_enabled" => true))
+ end
+
+ test "creates one proactive chat per admin, not for members" do
+ assert_difference -> { @admin.chats.count }, 1 do
+ assert_no_difference -> { @member.chats.count } do
+ WeeklyCleanupJob.perform_now(family_id: @family.id)
+ end
+ end
+
+ chat = @admin.chats.ordered.first
+ assert_equal 1, chat.messages.count
+ message = chat.messages.first
+ assert_instance_of AssistantMessage, message
+ assert message.complete?
+ assert_includes message.content, "cleanup"
+ end
+
+ test "is idempotent: rerunning does not respawn chats" do
+ WeeklyCleanupJob.perform_now(family_id: @family.id)
+
+ assert_no_difference -> { Chat.count } do
+ WeeklyCleanupJob.perform_now(family_id: @family.id)
+ end
+
+ assert_equal 1, WeeklyCleanupRun.where(family: @family, user: @admin).count
+ end
+
+ test "skips families without preview features" do
+ @admin.update!(preferences: @admin.preferences.merge("preview_features_enabled" => false))
+
+ assert_no_difference -> { Chat.count } do
+ WeeklyCleanupJob.perform_now(family_id: @family.id)
+ end
+ end
+
+ test "fan-out enqueues only for preview-enabled families" do
+ assert_enqueued_with(job: WeeklyCleanupJob, args: [ { family_id: @family.id } ]) do
+ WeeklyCleanupJob.perform_now
+ end
+ end
+
+ test "findings omit accounts the admin cannot access" do
+ other = users(:family_member)
+ hidden = Account.create!(
+ family: @family, owner: other, name: "Hidden Member Account", balance: 0, currency: "USD",
+ accountable: Depository.new
+ )
+ entry = hidden.entries.create!(
+ name: "Secret Merchant", date: 1.day.ago.to_date, amount: 42, currency: "USD",
+ entryable: Transaction.new(kind: "standard")
+ )
+ assert_not @admin.accessible_accounts.exists?(hidden.id)
+
+ WeeklyCleanupJob.perform_now(family_id: @family.id)
+
+ content = @admin.chats.ordered.first.messages.first.content
+ assert_not_includes content, entry.name
+ assert_not_includes content, hidden.name
+ end
+
+ test "skips deactivated admins and admins with AI turned off" do
+ @admin.update_columns(ai_enabled: false)
+
+ assert_no_difference -> { Chat.count } do
+ WeeklyCleanupJob.perform_now(family_id: @family.id)
+ end
+ end
+
+ test "dates the weekly period by the family's local date" do
+ @family.update!(timezone: "Pacific/Kiritimati")
+ travel_to Time.utc(2026, 11, 22, 12, 0) do # Sunday UTC, Monday in UTC+14
+ WeeklyCleanupJob.perform_now(family_id: @family.id)
+ end
+
+ assert_equal Date.new(2026, 11, 23), WeeklyCleanupRun.find_by!(family: @family, user: @admin).period_start
+ end
+
+ test "destroying a family with cleanup runs does not violate foreign keys" do
+ # A fresh family keeps the fixture family's Stripe/Plaid teardown (network
+ # calls) out of the way; family destroy still runs its real callbacks.
+ family = Family.create!(name: "Cleanup Destroy Family", currency: "USD", locale: "en")
+ admin = family.users.create!(
+ email: "[email protected]", password: "password-1234-abcd", role: "admin",
+ first_name: "Clean", last_name: "Up", onboarded_at: 1.day.ago, ai_enabled: true,
+ preferences: { "preview_features_enabled" => true }
+ )
+ Account.create!(family: family, owner: admin, name: "Checking", balance: 0, currency: "USD", accountable: Depository.new)
+
+ WeeklyCleanupJob.perform_now(family_id: family.id)
+ assert_equal 1, WeeklyCleanupRun.where(family: family).count
+
+ assert_nothing_raised { family.destroy! }
+ assert_equal 0, WeeklyCleanupRun.where(family_id: family.id).count
+ end
+
+ test "cleanup run foreign keys cascade so family and user deletes don't raise" do
+ foreign_keys = ActiveRecord::Base.connection.foreign_keys("weekly_cleanup_runs")
+
+ assert_equal %w[families users], foreign_keys.map(&:to_table).sort
+ assert(foreign_keys.all? { |fk| fk.on_delete == :cascade })
+ end
+
+ test "a failing detector skips the chat and does not record the period" do
+ WeeklyCleanup::Detectors::StaleImports.any_instance.stubs(:generate).raises(StandardError, "boom")
+
+ assert_no_difference -> { Chat.count } do
+ assert_no_difference -> { WeeklyCleanupRun.count } do
+ WeeklyCleanupJob.perform_now(family_id: @family.id)
+ end
+ end
+ end
+end
diff --git a/test/models/weekly_cleanup/detectors_test.rb b/test/models/weekly_cleanup/detectors_test.rb
new file mode 100644
index 0000000000..3f698aff66
--- /dev/null
+++ b/test/models/weekly_cleanup/detectors_test.rb
@@ -0,0 +1,156 @@
+require "test_helper"
+
+class WeeklyCleanup::DetectorsTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = families(:dylan_family)
+ @account = accounts(:depository)
+ end
+
+ test "uncategorized transactions detector finds recent uncategorized standard transactions" do
+ create_transaction(account: @account, name: "Mystery Store", date: 2.days.ago, amount: 42)
+ categorized = create_transaction(account: @account, name: "Known Store", date: 1.day.ago, amount: 10)
+ categorized.entryable.update!(category: categories(:food_and_drink))
+
+ finding = WeeklyCleanup::Detectors::UncategorizedTransactions.new(@family).generate
+
+ assert finding
+ assert_equal "uncategorized_transactions", finding.key
+ assert finding.count >= 1
+ assert finding.samples.any? { |s| s.include?("Mystery Store") }
+ end
+
+ test "uncategorized detector ignores transfers and excluded entries" do
+ create_transaction(account: @account, name: "Transfer Thing", date: 1.day.ago, amount: 50, kind: "funds_movement")
+ excluded = create_transaction(account: @account, name: "Excluded Thing", date: 1.day.ago, amount: 50)
+ excluded.update!(excluded: true)
+
+ finding = WeeklyCleanup::Detectors::UncategorizedTransactions.new(@family).generate
+
+ samples = finding ? finding.samples : []
+ assert samples.none? { |s| s.include?("Transfer Thing") }
+ assert samples.none? { |s| s.include?("Excluded Thing") }
+ end
+
+ test "missing merchant info detector finds merchantless transactions" do
+ create_transaction(account: @account, name: "No Merchant Here", date: 1.day.ago, amount: 25)
+ with_merchant = create_transaction(account: @account, name: "Has Merchant", date: 1.day.ago, amount: 25)
+ with_merchant.entryable.update!(merchant: merchants(:netflix))
+
+ finding = WeeklyCleanup::Detectors::MissingMerchantInfo.new(@family).generate
+
+ assert finding
+ assert finding.samples.any? { |s| s.include?("No Merchant Here") }
+ end
+
+ test "missing context detector only flags larger noteless attachment-free expenses" do
+ big = create_transaction(account: @account, name: "Big Purchase", date: 1.day.ago, amount: 250)
+ small = create_transaction(account: @account, name: "Small Purchase", date: 1.day.ago, amount: 20)
+ noted = create_transaction(account: @account, name: "Noted Purchase", date: 1.day.ago, amount: 300, notes: "birthday gift")
+
+ finding = WeeklyCleanup::Detectors::MissingContext.new(@family).generate
+
+ assert finding
+ assert finding.samples.any? { |s| s.include?("Big Purchase") }
+ assert finding.samples.none? { |s| s.include?("Small Purchase") }
+ assert finding.samples.none? { |s| s.include?("Noted Purchase") }
+ end
+
+ test "stale imports detector finds failed and stuck imports" do
+ failed = imports(:transaction)
+ failed.update!(status: "failed")
+ stuck = imports(:trade)
+ stuck.update!(status: "importing")
+ stuck.update_column(:updated_at, (Import::STUCK_AFTER + 1.hour).ago)
+ fresh = imports(:account) # importing but recent - not stale
+ fresh.update!(status: "importing")
+
+ finding = WeeklyCleanup::Detectors::StaleImports.new(@family).generate
+
+ assert finding
+ assert_equal 2, finding.count
+ end
+
+ test "duplicate imported entries detector groups same account/date/amount/name imports" do
+ import = imports(:transaction)
+ 2.times do
+ create_transaction(account: @account, name: "DUP CHARGE", date: 3.days.ago, amount: 9.99, import: import)
+ end
+ create_transaction(account: @account, name: "UNIQUE CHARGE", date: 3.days.ago, amount: 9.99, import: import)
+ # not imported - manual entries should never count
+ 2.times { create_transaction(account: @account, name: "MANUAL SAME", date: 3.days.ago, amount: 5) }
+
+ finding = WeeklyCleanup::Detectors::DuplicateImportedEntries.new(@family).generate
+
+ assert finding
+ assert finding.count >= 1
+ assert finding.samples.any? { |s| s.include?("dup charge") }
+ end
+
+ test "merchant duplicates detector reports clusters with coverage" do
+ @family.merchants.create!(name: "Whole Foods")
+ @family.merchants.create!(name: "Whole Foods Market, Inc.")
+
+ finding = WeeklyCleanup::Detectors::MerchantDuplicates.new(@family).generate
+
+ assert finding
+ assert finding.heading.include?("duplicate clusters")
+ assert finding.count >= 1
+ end
+
+ test "merchant duplicates detector returns nil when no clusters" do
+ quiet_family = Family.create!(name: "No Dup Family")
+ assert_nil WeeklyCleanup::Detectors::MerchantDuplicates.new(quiet_family).generate
+ end
+
+ test "provider data gaps counts the family umbrella sync" do
+ Sync.create!(syncable: @family, status: "failed")
+
+ finding = WeeklyCleanup::Detectors::ProviderDataGaps.new(@family).generate
+
+ assert finding
+ assert_operator finding.count, :>=, 1
+ end
+
+ test "future-dated entries are outside the cleanup window" do
+ create_transaction(account: @account, name: "Scheduled Future Thing", date: 3.days.from_now.to_date, amount: 42)
+
+ finding = WeeklyCleanup::Detectors::UncategorizedTransactions.new(@family).generate
+
+ assert_nil finding&.samples&.find { |s| s.include?("Scheduled Future Thing") }
+ end
+
+ test "provider data gaps ignores a failed sync that a later sync recovered" do
+ Sync.where(syncable: @family).delete_all
+ Sync.create!(syncable: @family, status: "failed", created_at: 2.days.ago)
+ Sync.create!(syncable: @family, status: "completed", created_at: 1.day.ago)
+
+ assert_nil WeeklyCleanup::Detectors::ProviderDataGaps.new(@family).generate
+ end
+
+ test "detectors scoped to a user count only accounts that user can access" do
+ member = users(:family_member)
+ hidden = Account.create!(family: @family, owner: member, name: "Hidden", balance: 0, currency: "USD", accountable: Depository.new)
+ create_transaction(account: hidden, name: "Hidden Purchase", date: 1.day.ago.to_date, amount: 10)
+ create_transaction(account: @account, name: "Visible Purchase", date: 1.day.ago.to_date, amount: 10)
+ admin = users(:family_admin)
+
+ scoped = WeeklyCleanup::Detectors::UncategorizedTransactions.new(@family, user: admin).generate
+ unscoped = WeeklyCleanup::Detectors::UncategorizedTransactions.new(@family).generate
+
+ assert scoped.samples.any? { |s| s.include?("Visible Purchase") }
+ assert scoped.samples.none? { |s| s.include?("Hidden Purchase") }
+ assert_equal scoped.count + 1, unscoped.count
+ end
+
+ test "provider data gaps still counts a failed sync whose retry has not completed" do
+ Sync.where(syncable: @family).delete_all
+ Sync.create!(syncable: @family, status: "failed", created_at: 2.days.ago)
+ Sync.create!(syncable: @family, status: "syncing", created_at: 1.day.ago)
+
+ finding = WeeklyCleanup::Detectors::ProviderDataGaps.new(@family).generate
+
+ assert_equal 1, finding.count
+ end
+end
diff --git a/test/models/weekly_cleanup/merchant_dedup_test.rb b/test/models/weekly_cleanup/merchant_dedup_test.rb
new file mode 100644
index 0000000000..9c01cbd955
--- /dev/null
+++ b/test/models/weekly_cleanup/merchant_dedup_test.rb
@@ -0,0 +1,44 @@
+require "test_helper"
+
+class WeeklyCleanup::MerchantDedupTest < ActiveSupport::TestCase
+ MerchantStub = Data.define(:name)
+
+ test "normalizes case, punctuation, business suffixes, and store numbers" do
+ assert_equal "whole foods", WeeklyCleanup::MerchantDedup.normalize("Whole Foods, Inc.")
+ assert_equal "target", WeeklyCleanup::MerchantDedup.normalize("TARGET #1234")
+ assert_equal "at and t", WeeklyCleanup::MerchantDedup.normalize("AT&T")
+ assert_equal "shell", WeeklyCleanup::MerchantDedup.normalize("Shell LLC")
+ end
+
+ test "clusters obvious duplicates and reports coverage" do
+ merchants = [
+ "Whole Foods", "Whole Foods Market, Inc.", "WHOLE FOODS #512",
+ "Netflix", "Netflix.com",
+ "Shell", "Chevron", "Trader Joe's"
+ ].map { |n| MerchantStub.new(n) }
+
+ result = WeeklyCleanup::MerchantDedup.call(merchants)
+
+ assert_equal 8, result.total
+ cluster_sets = result.clusters.map { |c| c.members.map(&:name).sort }
+ assert cluster_sets.any? { |s| s.include?("Whole Foods") && s.include?("WHOLE FOODS #512") }
+ assert cluster_sets.any? { |s| s.include?("Netflix") && s.include?("Netflix.com") }
+ # Distinct brands never cluster together
+ assert cluster_sets.flatten.none? { |n| n == "Shell" && cluster_sets.any? { |s| s.include?("Chevron") && s.include?("Shell") } }
+ assert_equal result.clustered, result.clusters.sum { |c| c.members.size }
+ assert result.coverage_pct > 0
+ end
+
+ test "handles empty input" do
+ result = WeeklyCleanup::MerchantDedup.call([])
+ assert_equal 0, result.total
+ assert_equal 0, result.coverage_pct
+ assert_empty result.clusters
+ end
+
+ test "does not cluster unrelated short names" do
+ merchants = [ "Apple", "Applebees", "Amazon" ].map { |n| MerchantStub.new(n) }
+ result = WeeklyCleanup::MerchantDedup.call(merchants)
+ assert_empty result.clusters
+ end
+end