Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Search a statement's excerpts only where its statement is visible (#5701)

David Gila235dbb88a50
diff --git a/app/controllers/api/v1/account_statements_controller.rb b/app/controllers/api/v1/account_statements_controller.rb
index b1c6ddc80d..4c66626024 100644
--- a/app/controllers/api/v1/account_statements_controller.rb
+++ b/app/controllers/api/v1/account_statements_controller.rb
@@ -11,12 +11,8 @@ class Api::V1::AccountStatementsController < Api::V1::BaseController
helper_method :accessible_account_ids
def index
- # Mirrors AccountStatement#viewable_by? for a statement manager in SQL, so
- # pages are never underfilled: unlinked statements are visible, linked ones
- # follow the account.
statements = family.account_statements
- .where(account_id: nil)
- .or(family.account_statements.where(account_id: current_resource_owner.accessible_accounts.select(:id)))
+ .viewable_by(current_resource_owner)
.includes(:account, :suggested_account)
.ordered
diff --git a/app/jobs/process_pdf_job.rb b/app/jobs/process_pdf_job.rb
index 2a70aed28e..2c5e409b6d 100644
--- a/app/jobs/process_pdf_job.rb
+++ b/app/jobs/process_pdf_job.rb
@@ -65,15 +65,18 @@ class ProcessPdfJob < ApplicationJob
end
end
+ # Only statement PDFs: who finds a document follows its statement
+ # (FamilyDocument.searchable_by), and an import from before statements
+ # existed has none.
def upload_to_vector_store(pdf_import, document_type:)
+ return unless pdf_import.statement_backed?
return unless Ai.available?(:embed, family: pdf_import.family)
- file_content = pdf_import.pdf_file_content
-
family_document = pdf_import.family.upload_document(
- file_content: file_content,
+ file_content: pdf_import.pdf_file_content,
filename: pdf_import.pdf_filename,
- metadata: { "type" => document_type }
+ metadata: { "type" => document_type },
+ account_statement: pdf_import.account_statement
)
return if family_document
diff --git a/app/models/account_statement.rb b/app/models/account_statement.rb
index da7cf3f30e..e09fb23a5f 100644
--- a/app/models/account_statement.rb
+++ b/app/models/account_statement.rb
@@ -79,6 +79,13 @@ class AccountStatement < ApplicationRecord
)
}
scope :with_account, -> { where.not(account_id: nil) }
+ # viewable_by? in SQL, so lists filter before they paginate: a linked
+ # statement follows its account, an unlinked one is for statement managers.
+ scope :viewable_by, ->(user) {
+ family_statements = where(family_id: user.family_id)
+ linked = family_statements.where(account_id: user.accessible_accounts.select(:id))
+ statement_manager?(user) ? linked.or(family_statements.where(account_id: nil)) : linked
+ }
scope :unmatched, -> { where(account_id: nil).where(review_status: "unmatched") }
# Rejecting a suggestion leaves the statement accountless, so it stays in the inbox where it can be found and deleted.
scope :inbox, -> { where(account_id: nil).where(review_status: %w[unmatched rejected]) }
diff --git a/app/models/assistant/function/list_account_statements.rb b/app/models/assistant/function/list_account_statements.rb
index 8cce7f76a0..bcaa68f15b 100644
--- a/app/models/assistant/function/list_account_statements.rb
+++ b/app/models/assistant/function/list_account_statements.rb
@@ -85,11 +85,9 @@ class Assistant::Function::ListAccountStatements < Assistant::Function
# Visibility is filtered in SQL, not after the fact. Post-filtering a page
# would both underfill it and — because there is no cursor — make a statement
# permanently unreachable whenever enough newer rows the caller cannot see sit
- # in front of it. Mirrors AccountStatement#viewable_by? for a statement
- # manager: unlinked statements are visible, linked ones follow the account.
+ # in front of it.
scope = family.account_statements
- .where(account_id: nil)
- .or(family.account_statements.where(account_id: user.accessible_accounts.select(:id)))
+ .viewable_by(user)
.includes(:account, :suggested_account)
.ordered
diff --git a/app/models/assistant/function/search_family_files.rb b/app/models/assistant/function/search_family_files.rb
index f336d09ffc..202853a3d7 100644
--- a/app/models/assistant/function/search_family_files.rb
+++ b/app/models/assistant/function/search_family_files.rb
@@ -1,6 +1,10 @@
class Assistant::Function::SearchFamilyFiles < Assistant::Function
include LangfuseTraceable
+ # Excerpts asked of the store before those of documents the user may not
+ # see are dropped (OpenAI's store returns at most 50).
+ SEARCH_POOL = 50
+
class << self
def name
"search_family_files"
@@ -95,7 +99,7 @@ class Assistant::Function::SearchFamilyFiles < Assistant::Function
response = adapter.search(
store_id: store_id,
query: query,
- max_results: max_results
+ max_results: SEARCH_POOL
)
unless response.success?
@@ -113,7 +117,8 @@ class Assistant::Function::SearchFamilyFiles < Assistant::Function
}
end
- results = response.data
+ searchable_file_ids = family.family_documents.searchable_by(user).where.not(provider_file_id: nil).pluck(:provider_file_id).to_set
+ results = response.data.select { |result| searchable_file_ids.include?(result[:file_id]) }.first(max_results)
Rails.logger.debug("[SearchFamilyFiles] #{results.size} chunk(s) returned")
diff --git a/app/models/family/vector_searchable.rb b/app/models/family/vector_searchable.rb
index 73b3946c4e..21460b0e03 100644
--- a/app/models/family/vector_searchable.rb
+++ b/app/models/family/vector_searchable.rb
@@ -22,22 +22,7 @@ module Family::VectorSearchable
end
end
- def search_documents(query, max_results: 10)
- return [] unless vector_store_id.present?
-
- adapter = vector_store_adapter
- return [] unless adapter
-
- response = adapter.search(
- store_id: vector_store_id,
- query: query,
- max_results: max_results
- )
-
- response.success? ? response.data : []
- end
-
- def upload_document(file_content:, filename:, metadata: {})
+ def upload_document(file_content:, filename:, metadata: {}, account_statement: nil)
adapter = vector_store_adapter
return nil unless adapter
@@ -58,6 +43,7 @@ module Family::VectorSearchable
file_size: file_content.bytesize,
provider_file_id: response.data[:file_id],
status: "ready",
+ account_statement: account_statement,
metadata: metadata || {}
)
end
diff --git a/app/models/family_document.rb b/app/models/family_document.rb
index 8320a2a39d..3539852dab 100644
--- a/app/models/family_document.rb
+++ b/app/models/family_document.rb
@@ -1,5 +1,7 @@
class FamilyDocument < ApplicationRecord
belongs_to :family
+ # The statement a processed PDF came from (ProcessPdfJob).
+ belongs_to :account_statement, optional: true
has_one_attached :file
@@ -10,6 +12,18 @@ class FamilyDocument < ApplicationRecord
scope :ready, -> { where(status: "ready") }
+ # The documents whose excerpts +user+ may find. A statement PDF follows its
+ # statement (AccountStatement#viewable_by?), and a file uploaded straight to
+ # the store is the family's. A PDF processed before documents recorded their
+ # statement carries only its document type and could come from any account,
+ # so nobody finds it until it is linked.
+ scope :searchable_by, ->(user) {
+ where(family_id: user.family_id).merge(
+ where(account_statement_id: AccountStatement.viewable_by(user).select(:id))
+ .or(where(account_statement_id: nil).where.not(Arel.sql("family_documents.metadata ? 'type'")))
+ )
+ }
+
def mark_ready!
update!(status: "ready")
end
diff --git a/db/migrate/20261123220000_add_account_statement_to_family_documents.rb b/db/migrate/20261123220000_add_account_statement_to_family_documents.rb
new file mode 100644
index 0000000000..39f7dc47f8
--- /dev/null
+++ b/db/migrate/20261123220000_add_account_statement_to_family_documents.rb
@@ -0,0 +1,7 @@
+# A processed statement PDF is searchable by whoever may see its statement
+# (FamilyDocument.searchable_by), so its document records which one it is.
+class AddAccountStatementToFamilyDocuments < ActiveRecord::Migration[8.1]
+ def change
+ add_reference :family_documents, :account_statement, type: :uuid, foreign_key: { on_delete: :cascade }, index: true
+ end
+end
diff --git a/db/migrate/20261123220100_link_family_documents_to_their_statements.rb b/db/migrate/20261123220100_link_family_documents_to_their_statements.rb
new file mode 100644
index 0000000000..b07d056352
--- /dev/null
+++ b/db/migrate/20261123220100_link_family_documents_to_their_statements.rb
@@ -0,0 +1,36 @@
+# Documents ProcessPdfJob uploaded before they recorded their statement carry
+# only the document type it classified. Each is linked to the one statement of
+# its family with the same filename and size that a PdfImport had already
+# processed when the document was uploaded, so a PDF imported before statements
+# existed is never taken for a later statement. The rest stay unlinked, and
+# nobody finds them in a search (FamilyDocument.searchable_by).
+class LinkFamilyDocumentsToTheirStatements < ActiveRecord::Migration[8.1]
+ def up
+ execute <<~SQL.squish
+ UPDATE family_documents
+ SET account_statement_id = matches.statement_id
+ FROM (
+ SELECT documents.id AS document_id, MIN(statements.id::text)::uuid AS statement_id
+ FROM family_documents AS documents
+ JOIN account_statements AS statements
+ ON statements.family_id = documents.family_id
+ AND statements.filename = documents.filename
+ AND statements.byte_size = documents.file_size
+ WHERE documents.account_statement_id IS NULL
+ AND documents.metadata ? 'type'
+ AND EXISTS (
+ SELECT 1 FROM imports
+ WHERE imports.type = 'PdfImport'
+ AND imports.account_statement_id = statements.id
+ AND imports.created_at <= documents.created_at
+ )
+ GROUP BY documents.id
+ HAVING COUNT(DISTINCT statements.id) = 1
+ ) AS matches
+ WHERE family_documents.id = matches.document_id
+ SQL
+ end
+
+ def down
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index d6fd19e89e..a9f7304c4e 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_11_21_110000) do
+ActiveRecord::Schema[8.1].define(version: 2026_11_23_220100) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -877,6 +877,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_21_110000) do
end
create_table "family_documents", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.uuid "account_statement_id"
t.string "content_type"
t.datetime "created_at", null: false
t.uuid "family_id", null: false
@@ -886,6 +887,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_21_110000) do
t.string "provider_file_id"
t.string "status", default: "pending", null: false
t.datetime "updated_at", null: false
+ t.index ["account_statement_id"], name: "index_family_documents_on_account_statement_id"
t.index ["family_id"], name: "index_family_documents_on_family_id"
t.index ["provider_file_id"], name: "index_family_documents_on_provider_file_id"
t.index ["status"], name: "index_family_documents_on_status"
@@ -3214,6 +3216,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_21_110000) do
add_foreign_key "eval_results", "eval_samples"
add_foreign_key "eval_runs", "eval_datasets"
add_foreign_key "eval_samples", "eval_datasets"
+ add_foreign_key "family_documents", "account_statements", on_delete: :cascade
add_foreign_key "family_documents", "families"
add_foreign_key "family_exports", "families"
add_foreign_key "family_merchant_associations", "families"
diff --git a/test/jobs/process_pdf_job_test.rb b/test/jobs/process_pdf_job_test.rb
index d2a5f29c1d..eefcb6f56f 100644
--- a/test/jobs/process_pdf_job_test.rb
+++ b/test/jobs/process_pdf_job_test.rb
@@ -67,28 +67,30 @@ class ProcessPdfJobTest < ActiveJob::TestCase
assert_equal "importing", processed_import.reload.status
end
- test "uploads non-bank PDF to vector store with classified type metadata" do
- pdf_content = attach_pdf!(@import)
+ test "uploads non-bank PDF to vector store with classified type metadata and its statement" do
+ import = statement_backed_import
process_result = Struct.new(:document_type).new("financial_document")
- @import.expects(:process_with_ai).once.returns(process_result)
- @import.stubs(:send_next_steps_email)
- @import.expects(:extract_transactions).never
+ import.expects(:process_with_ai).once.returns(process_result)
+ import.stubs(:send_next_steps_email)
+ import.expects(:extract_transactions).never
- @family.expects(:upload_document).with do |file_content:, filename:, metadata:|
- assert_equal pdf_content, file_content
+ import.family.expects(:upload_document).with do |file_content:, filename:, metadata:, account_statement:|
+ assert_equal import.account_statement.original_file.download, file_content
assert_equal "sample_bank_statement.pdf", filename
assert_equal({ "type" => "financial_document" }, metadata)
+ assert_equal import.account_statement, account_statement
true
end.returns(family_documents(:tax_return))
- ProcessPdfJob.perform_now(@import)
+ ProcessPdfJob.perform_now(import)
- assert_equal "complete", @import.reload.status
+ assert_equal "complete", import.reload.status
end
- test "skips the vector store when embed is unavailable" do
- use_ai_routes(embed: [])
+ # Searching a document follows its statement (FamilyDocument.searchable_by).
+ # An import from before statements existed has none to follow.
+ test "keeps a PDF without a statement out of the vector store" do
attach_pdf!(@import)
@import.expects(:process_with_ai).once.returns(Struct.new(:document_type).new("financial_document"))
@import.stubs(:send_next_steps_email)
@@ -99,13 +101,25 @@ class ProcessPdfJobTest < ActiveJob::TestCase
assert_equal "complete", @import.reload.status
end
+ test "skips the vector store when embed is unavailable" do
+ use_ai_routes(embed: [])
+ import = statement_backed_import
+ import.expects(:process_with_ai).once.returns(Struct.new(:document_type).new("financial_document"))
+ import.stubs(:send_next_steps_email)
+ import.family.expects(:upload_document).never
+
+ ProcessPdfJob.perform_now(import)
+
+ assert_equal "complete", import.reload.status
+ end
+
test "uploads bank statement PDF to vector store with classified type metadata" do
- pdf_content = attach_pdf!(@import)
+ import = statement_backed_import
process_result = Struct.new(:document_type).new("bank_statement")
- @import.expects(:process_with_ai).once.returns(process_result)
- @import.expects(:extract_transactions).once do
- @import.update!(
+ import.expects(:process_with_ai).once.returns(process_result)
+ import.expects(:extract_transactions).once do
+ import.update!(
extracted_data: {
"transactions" => [
{
@@ -117,19 +131,20 @@ class ProcessPdfJobTest < ActiveJob::TestCase
}
)
end
- @import.expects(:sync_mappings).once
- @import.stubs(:send_next_steps_email)
+ import.expects(:sync_mappings).once
+ import.stubs(:send_next_steps_email)
- @family.expects(:upload_document).with do |file_content:, filename:, metadata:|
- assert_equal pdf_content, file_content
+ import.family.expects(:upload_document).with do |file_content:, filename:, metadata:, account_statement:|
+ assert_equal import.account_statement.original_file.download, file_content
assert_equal "sample_bank_statement.pdf", filename
assert_equal({ "type" => "bank_statement" }, metadata)
+ assert_equal import.account_statement, account_statement
true
end.returns(family_documents(:tax_return))
- ProcessPdfJob.perform_now(@import)
+ ProcessPdfJob.perform_now(import)
- assert_equal "complete", @import.reload.status
+ assert_equal "complete", import.reload.status
end
test "discards permanently and marks failed on Provider::Error" do
@@ -156,6 +171,19 @@ class ProcessPdfJobTest < ActiveJob::TestCase
private
+ def statement_backed_import
+ statement = AccountStatement.create_from_upload!(
+ family: @family,
+ account: accounts(:depository),
+ file: uploaded_file(
+ filename: "sample_bank_statement.pdf",
+ content_type: "application/pdf",
+ content: file_fixture("imports/sample_bank_statement.pdf").binread
+ )
+ )
+ PdfImport.create_from_statement!(statement: statement)
+ end
+
def attach_pdf!(import)
pdf_content = file_fixture("imports/sample_bank_statement.pdf").binread
import.pdf_file.attach(
diff --git a/test/migrations/link_family_documents_to_their_statements_migration_test.rb b/test/migrations/link_family_documents_to_their_statements_migration_test.rb
new file mode 100644
index 0000000000..635ee6b3ea
--- /dev/null
+++ b/test/migrations/link_family_documents_to_their_statements_migration_test.rb
@@ -0,0 +1,96 @@
+require "test_helper"
+require Rails.root.join("db/migrate/20261123220100_link_family_documents_to_their_statements")
+
+class LinkFamilyDocumentsToTheirStatementsMigrationTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ end
+
+ test "links a processed PDF to the statement with its filename and size" do
+ statement = create_statement("march.pdf", "%PDF-1.4 March")
+ document = processed_document("march.pdf", statement.original_file.byte_size)
+
+ run_migration
+
+ assert_equal statement, document.reload.account_statement
+ end
+
+ test "leaves a processed PDF unlinked when it predates the statement's import" do
+ document = processed_document("march.pdf", "%PDF-1.4 March".bytesize, created_at: 1.year.ago)
+ statement = create_statement("march.pdf", "%PDF-1.4 March")
+
+ run_migration
+
+ assert_equal statement.original_file.byte_size, document.file_size
+ assert_nil document.reload.account_statement
+ end
+
+ test "leaves a processed PDF unlinked when its statement was never imported" do
+ statement = AccountStatement.create_from_upload!(family: @family, account: accounts(:connected), file: pdf_upload("march.pdf", "%PDF-1.4 March"))
+ document = processed_document("march.pdf", statement.original_file.byte_size)
+
+ run_migration
+
+ assert_nil document.reload.account_statement
+ end
+
+ test "leaves a processed PDF unlinked when no statement has its size" do
+ create_statement("march.pdf", "%PDF-1.4 March")
+ document = processed_document("march.pdf", 1)
+
+ run_migration
+
+ assert_nil document.reload.account_statement
+ end
+
+ test "leaves a processed PDF unlinked when two statements could be its own" do
+ first = create_statement("march.pdf", "%PDF-1.4 March A")
+ create_statement("march.pdf", "%PDF-1.4 March B")
+ document = processed_document("march.pdf", first.original_file.byte_size)
+
+ run_migration
+
+ assert_nil document.reload.account_statement
+ end
+
+ test "leaves files uploaded straight to the store alone" do
+ statement = create_statement("notes.pdf", "%PDF-1.4 Notes")
+ document = @family.family_documents.create!(filename: "notes.pdf", file_size: statement.original_file.byte_size,
+ provider_file_id: "file-direct", status: "ready", metadata: {})
+
+ run_migration
+
+ assert_nil document.reload.account_statement
+ end
+
+ test "does not link a statement of another family" do
+ statement = AccountStatement.create_from_upload!(family: families(:empty), account: nil, file: pdf_upload("march.pdf", "%PDF-1.4 March"))
+ PdfImport.create_from_statement!(statement: statement)
+ document = processed_document("march.pdf", statement.original_file.byte_size)
+
+ run_migration
+
+ assert_nil document.reload.account_statement
+ end
+
+ private
+ def run_migration
+ ActiveRecord::Migration.suppress_messages { LinkFamilyDocumentsToTheirStatements.new.up }
+ end
+
+ # A statement ProcessPdfJob worked on: it has a PdfImport.
+ def create_statement(filename, content)
+ AccountStatement.create_from_upload!(family: @family, account: accounts(:connected), file: pdf_upload(filename, content)).tap do |statement|
+ PdfImport.create_from_statement!(statement: statement)
+ end
+ end
+
+ def pdf_upload(filename, content)
+ uploaded_file(filename: filename, content_type: "application/pdf", content: content)
+ end
+
+ def processed_document(filename, file_size, created_at: Time.current)
+ @family.family_documents.create!(filename: filename, file_size: file_size, provider_file_id: "file-#{SecureRandom.hex(4)}",
+ status: "ready", metadata: { "type" => "bank_statement" }, created_at: created_at)
+ end
+end
diff --git a/test/models/assistant/function/search_family_files_test.rb b/test/models/assistant/function/search_family_files_test.rb
index 8f0ccfd53d..5f70aabff4 100644
--- a/test/models/assistant/function/search_family_files_test.rb
+++ b/test/models/assistant/function/search_family_files_test.rb
@@ -61,8 +61,8 @@ class Assistant::Function::SearchFamilyFilesTest < ActiveSupport::TestCase
VectorStore::Response.new(
success?: true,
data: [
- { content: "Total income: $85,000", filename: "2024_tax_return.pdf", score: 0.95, file_id: "file-abc" },
- { content: "W-2 wages: $80,000", filename: "2024_tax_return.pdf", score: 0.87, file_id: "file-abc" }
+ { content: "Total income: $85,000", filename: "2024_tax_return.pdf", score: 0.95, file_id: "file-abc123" },
+ { content: "W-2 wages: $80,000", filename: "2024_tax_return.pdf", score: 0.87, file_id: "file-abc123" }
],
error: nil
)
@@ -114,19 +114,72 @@ class Assistant::Function::SearchFamilyFilesTest < ActiveSupport::TestCase
assert_equal "search_failed", result[:error]
end
- test "caps max_results at 20" do
- @user.family.update!(vector_store_id: "vs_test123")
+ test "returns at most 20 results" do
+ chunks = Array.new(30) { |i| chunk("file-abc123", "Excerpt #{i}") }
+ stub_search(chunks)
- mock_adapter = mock("vector_store_adapter")
- mock_adapter.expects(:search).with(
- store_id: "vs_test123",
- query: "test",
- max_results: 20
- ).returns(VectorStore::Response.new(success?: true, data: [], error: nil))
+ result = @function.call("query" => "test", "max_results" => 50)
- VectorStore::Registry.stubs(:adapter).returns(mock_adapter)
+ assert_equal 20, result[:result_count]
+ end
+
+ # Statement PDFs are searchable by whoever may see the statement
+ # (AccountStatement#viewable_by?); files uploaded straight to the store are
+ # the family's.
+ test "a member finds no excerpts of a statement of an account not shared with them" do
+ hidden = statement_document(account: accounts(:connected))
+ shared = statement_document(account: accounts(:depository))
+ stub_search([ chunk(hidden, "Admin private"), chunk(shared, "Shared"), chunk("file-abc123", "Family upload") ])
+
+ result = Assistant::Function::SearchFamilyFiles.new(users(:family_member)).call("query" => "statement")
+
+ assert_equal [ "Shared", "Family upload" ], result[:results].map { |r| r[:content] }
+ end
+
+ test "the owner of the account finds the excerpts of its statement" do
+ hidden = statement_document(account: accounts(:connected))
+ stub_search([ chunk(hidden, "Admin private") ])
- @function.call("query" => "test", "max_results" => 50)
+ result = @function.call("query" => "statement")
+
+ assert_equal [ "Admin private" ], result[:results].map { |r| r[:content] }
+ end
+
+ test "a statement linked to an account later follows that account" do
+ statement_file = statement_document(account: nil)
+ stub_search([ chunk(statement_file, "Inbox statement") ])
+ member_search = Assistant::Function::SearchFamilyFiles.new(users(:family_member))
+
+ assert_equal 1, member_search.call("query" => "statement")[:result_count]
+
+ FamilyDocument.find_by!(provider_file_id: statement_file).account_statement.link_to_account!(accounts(:connected))
+
+ assert_empty member_search.call("query" => "statement")[:results]
+ end
+
+ test "a guest finds no excerpts of an unlinked statement" do
+ statement_file = statement_document(account: nil)
+ stub_search([ chunk(statement_file, "Inbox statement"), chunk("file-abc123", "Family upload") ])
+
+ result = Assistant::Function::SearchFamilyFiles.new(family_guest).call("query" => "statement")
+
+ assert_equal [ "Family upload" ], result[:results].map { |r| r[:content] }
+ end
+
+ # PDFs processed before documents recorded their statement could come from
+ # any account, so nobody finds them until they are linked.
+ test "nobody finds a processed PDF whose statement is unknown" do
+ @user.family.family_documents.create!(filename: "old.pdf", provider_file_id: "file-legacy", status: "ready",
+ metadata: { "type" => "bank_statement" })
+ stub_search([ chunk("file-legacy", "Legacy statement") ])
+
+ assert_empty @function.call("query" => "statement")[:results]
+ end
+
+ test "excerpts of a file the family has no record of are left out" do
+ stub_search([ chunk("file-unknown", "Orphan") ])
+
+ assert_empty @function.call("query" => "statement")[:results]
end
test "returns the search failure when tracing finalization also fails" do
@@ -145,4 +198,28 @@ class Assistant::Function::SearchFamilyFilesTest < ActiveSupport::TestCase
assert_equal "search_failed", result[:error]
assert_equal "An error occurred while searching documents: Search unavailable", result[:message]
end
+
+ private
+ def stub_search(chunks)
+ @user.family.update!(vector_store_id: "vs_test123")
+ adapter = mock("vector_store_adapter")
+ adapter.stubs(:search).returns(VectorStore::Response.new(success?: true, data: chunks, error: nil))
+ VectorStore::Registry.stubs(:adapter).returns(adapter)
+ end
+
+ def chunk(file_id, content)
+ { content: content, filename: "statement.pdf", score: 0.9, file_id: file_id }
+ end
+
+ # The provider file id of a document uploaded for a new statement PDF.
+ def statement_document(account:)
+ family = @user.family
+ statement = AccountStatement.create_from_upload!(
+ family: family,
+ account: account,
+ file: uploaded_file(filename: "statement.pdf", content_type: "application/pdf", content: "%PDF-1.4 #{SecureRandom.hex}")
+ )
+ family.family_documents.create!(filename: statement.filename, provider_file_id: "file-#{SecureRandom.hex(4)}", status: "ready",
+ account_statement: statement, metadata: { "type" => "bank_statement" }).provider_file_id
+ end
end
diff --git a/test/models/family_test.rb b/test/models/family_test.rb
index eea94666a1..58dfc8d5a8 100644
--- a/test/models/family_test.rb
+++ b/test/models/family_test.rb
@@ -463,7 +463,7 @@ class FamilyTest < ActiveSupport::TestCase
assert_equal Money::Currency.as_options.map(&:iso_code), family.reload.enabled_currency_codes
end
- test "upload_document stores provided metadata on family document" do
+ test "upload_document stores provided metadata and statement on family document" do
family = families(:dylan_family)
family.update!(vector_store_id: nil)
@@ -481,14 +481,21 @@ class FamilyTest < ActiveSupport::TestCase
VectorStore::Registry.stubs(:adapter).returns(adapter)
+ statement = AccountStatement.create_from_upload!(
+ family: family, account: accounts(:connected),
+ file: uploaded_file(filename: "statement.pdf", content_type: "application/pdf", content: "%PDF-1.4 statement")
+ )
+
document = family.upload_document(
file_content: "hello",
filename: "notes.txt",
- metadata: { "type" => "financial_document" }
+ metadata: { "type" => "financial_document" },
+ account_statement: statement
)
assert_not_nil document
assert_equal({ "type" => "financial_document" }, document.metadata)
+ assert_equal statement, document.reload.account_statement
assert_equal "vs_test123", family.reload.vector_store_id
end