Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Read statement periods printed with two-digit years (#5648)

jaysbeekay1c2503288635
diff --git a/app/models/account_statement/text_metadata_parser.rb b/app/models/account_statement/text_metadata_parser.rb
index abe57381da..dd0aad803f 100644
--- a/app/models/account_statement/text_metadata_parser.rb
+++ b/app/models/account_statement/text_metadata_parser.rb
@@ -30,6 +30,8 @@ class AccountStatement::TextMetadataParser
# Month tokens are matched in full, then on their first four and three
# letters, which covers abbreviations ("Sept.", "févr.") and full names.
+ # The two-digit-year format matches them in full only, here or in
+ # FULL_MONTHS.
MONTHS = {
"jan" => 1, "gen" => 1, "ene" => 1, "janv" => 1,
"feb" => 2, "fév" => 2, "fev" => 2, "févr" => 2, "fevr" => 2,
@@ -39,11 +41,26 @@ class AccountStatement::TextMetadataParser
"jun" => 6, "giu" => 6, "juin" => 6,
"jul" => 7, "lug" => 7, "juil" => 7,
"aug" => 8, "ago" => 8, "aoû" => 8, "aou" => 8,
- "sep" => 9, "set" => 9,
+ "sep" => 9, "sept" => 9, "set" => 9,
"oct" => 10, "ott" => 10, "okt" => 10, "out" => 10,
"nov" => 11,
"dec" => 12, "dic" => 12, "dez" => 12, "déc" => 12
}.freeze
+ # Full names in the same languages, for formats that match a month exactly.
+ FULL_MONTHS = [
+ %w[january gennaio januar janvier enero januari janeiro],
+ %w[february febbraio februar février fevrier febrero februari fevereiro],
+ %w[march marzo märz maerz mars maart março marco],
+ %w[april aprile avril abril],
+ %w[may maggio mai mayo mei maio],
+ %w[june giugno juni juin junio junho],
+ %w[july luglio juli juillet julio julho],
+ %w[august agosto août aout augustus],
+ %w[september settembre septembre septiembre setembro],
+ %w[october ottobre oktober octobre octubre outubro],
+ %w[november novembre noviembre novembro],
+ %w[december dicembre dezember décembre decembre diciembre dezembro]
+ ].each_with_index.flat_map { |names, index| names.map { |name| [ name, index + 1 ] } }.to_h.freeze
ORDINAL = /(?:st|nd|rd|th)?/i
MONTH_NAME = /[[:alpha:]]{3,10}/
@@ -55,8 +72,16 @@ class AccountStatement::TextMetadataParser
month_name_day: /(?<month_name>#{MONTH_NAME})\.?\s+(?<day>\d{1,2})#{ORDINAL},?\s+(?<year>\d{4})/
}.freeze
DATE = Regexp.union(DATE_FORMATS.values.map { |format| Regexp.new(format.source.gsub(/\(\?<\w+>/, "(?:"), format.options) })
- RANGE_SEPARATOR = /\s*(?:[-–—]|\b(?:to|through|until|bis|al|au|tot|a|até|hasta)\b)\s*/i
+ RANGE_WORD = /(?:[-–—]|\b(?:to|through|until|bis|al|au|tot|a|até|hasta)\b)/i
+ RANGE_SEPARATOR = /\s*#{RANGE_WORD}\s*/
PERIOD_PATTERN = /(?<start>#{DATE})#{RANGE_SEPARATOR}(?<end>#{DATE})/
+ # "3 Sep 21 - 1 Oct 21". Read only when no four-digit-year period is found.
+ # The month must be a whole MONTHS or FULL_MONTHS token ("2 Marketing 21" is
+ # not a date), and any space counts, as PDF extractors may emit
+ # non-breaking ones.
+ TWO_DIGIT_YEAR_DATE = /(?<!\d)(?<day>\d{1,2})#{ORDINAL}[[:space:]]+(?<month_name>[[:alpha:]]+)\.?[[:space:]]+(?<year>\d{2})(?!\d)/
+ TWO_DIGIT_YEAR = TWO_DIGIT_YEAR_DATE.source.gsub(/\(\?<\w+>/, "(?:")
+ TWO_DIGIT_YEAR_PERIOD = /(?<start>#{TWO_DIGIT_YEAR})[[:space:]]*#{RANGE_WORD}[[:space:]]*(?<end>#{TWO_DIGIT_YEAR})/
# Annual statements span a year; anything longer isn't one period.
MAX_PERIOD_DAYS = 400
@@ -200,9 +225,14 @@ class AccountStatement::TextMetadataParser
end
def range_period
- @text.to_enum(:scan, PERIOD_PATTERN).each do
+ first_period(PERIOD_PATTERN) { |raw| parse_date(raw) } ||
+ first_period(TWO_DIGIT_YEAR_PERIOD) { |raw| parse_two_digit_year_date(raw) }
+ end
+
+ def first_period(pattern)
+ @text.to_enum(:scan, pattern).each do
match = Regexp.last_match
- period = valid_period(parse_date(match[:start]), parse_date(match[:end]))
+ period = valid_period(yield(match[:start]), yield(match[:end]))
return period if period
end
nil
@@ -242,6 +272,18 @@ class AccountStatement::TextMetadataParser
nil
end
+ def parse_two_digit_year_date(raw)
+ match = raw.match(/\A#{TWO_DIGIT_YEAR_DATE}\z/)
+ token = match[:month_name].downcase
+ month = MONTHS[token] || FULL_MONTHS[token]
+ return nil unless month
+
+ date = Date.new(2000 + match[:year].to_i, month, match[:day].to_i)
+ date if AccountStatement::MetadataDetector.reasonable_date?(date)
+ rescue Date::Error
+ nil
+ end
+
def month_number(name)
token = name.to_s.downcase
MONTHS[token] || MONTHS[token[0, 4]] || MONTHS[token[0, 3]]
diff --git a/test/fixtures/files/account_statements/two_digit_year_period.pdf b/test/fixtures/files/account_statements/two_digit_year_period.pdf
new file mode 100644
index 0000000000..c330d625f5
--- /dev/null
+++ b/test/fixtures/files/account_statements/two_digit_year_period.pdf
@@ -0,0 +1,50 @@
+%PDF-1.4
+1 0 obj
+<< /Type /Catalog /Pages 2 0 R >>
+endobj
+2 0 obj
+<< /Type /Pages /Kids [3 0 R] /Count 1 >>
+endobj
+3 0 obj
+<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>
+endobj
+4 0 obj
+<< /Length 603 >>
+stream
+BT
+/F1 10 Tf
+1 0 0 1 50 780 Tm (Statement of Account) Tj
+1 0 0 1 50 750 Tm (Account Number) Tj
+1 0 0 1 300 750 Tm (302-985 1234567) Tj
+1 0 0 1 50 730 Tm (Period) Tj
+1 0 0 1 300 730 Tm (3 Sep 21 - 1 Oct 21) Tj
+1 0 0 1 50 690 Tm (OPENING BALANCE) Tj
+1 0 0 1 400 690 Tm ($1,250.00) Tj
+1 0 0 1 50 670 Tm (TOTAL CREDITS) Tj
+1 0 0 1 400 670 Tm ($3,100.00) Tj
+1 0 0 1 50 650 Tm (TOTAL DEBITS) Tj
+1 0 0 1 400 650 Tm ($2,350.00) Tj
+1 0 0 1 50 630 Tm (CLOSING BALANCE) Tj
+1 0 0 1 400 630 Tm ($2,000.00) Tj
+1 0 0 1 50 590 Tm (06 Sep 21) Tj
+1 0 0 1 120 590 Tm (EFTPOS PURCHASE) Tj
+1 0 0 1 400 590 Tm ($21.00) Tj
+ET
+endstream
+endobj
+5 0 obj
+<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>
+endobj
+xref
+0 6
+0000000000 65535 f
+0000000009 00000 n
+0000000058 00000 n
+0000000115 00000 n
+0000000241 00000 n
+0000000894 00000 n
+trailer
+<< /Size 6 /Root 1 0 R >>
+startxref
+991
+%%EOF
diff --git a/test/models/account_statement/text_metadata_parser_test.rb b/test/models/account_statement/text_metadata_parser_test.rb
index b9fb30007b..a42e814ae7 100644
--- a/test/models/account_statement/text_metadata_parser_test.rb
+++ b/test/models/account_statement/text_metadata_parser_test.rb
@@ -397,6 +397,60 @@ class AccountStatement::TextMetadataParserTest < ActiveSupport::TestCase
assert_equal BigDecimal("435.88"), card_balances(text, classification: "liability").closing_balance
end
+ TWO_DIGIT_YEAR_TEXT = <<~TEXT
+ Period 3 Sep 21 - 1 Oct 21
+ OPENING BALANCE $1,250.00
+ CLOSING BALANCE $2,000.00
+ TEXT
+
+ def period_of(text)
+ result = AccountStatement::TextMetadataParser.parse(text)
+ result && [ result.period_start_on, result.period_end_on ]
+ end
+
+ test "reads a period printed with two-digit years" do
+ assert_equal [ Date.new(2021, 9, 3), Date.new(2021, 10, 1) ], period_of(TWO_DIGIT_YEAR_TEXT)
+ end
+
+ test "reads a two-digit-year period across a year end" do
+ assert_equal [ Date.new(2021, 12, 4), Date.new(2022, 1, 3) ], period_of("Period 4 Dec 21 - 3 Jan 22")
+ end
+
+ test "reads a two-digit-year period separated by Unicode spaces" do
+ text = "Period\u00A03\u00A0Sep\u00A021\u202F-\u202F1\u00A0Oct\u00A021"
+
+ assert_equal [ Date.new(2021, 9, 3), Date.new(2021, 10, 1) ], period_of(text)
+ end
+
+ test "reads a two-digit-year period with full month names" do
+ assert_equal [ Date.new(2021, 4, 3), Date.new(2021, 5, 1) ], period_of("Period 3 April 21 - 1 May 21")
+ assert_equal [ Date.new(2021, 12, 4), Date.new(2022, 1, 3) ], period_of("Period 4 December 21 - 3 January 22")
+ end
+
+ test "reads a two-digit-year period with Sept as the month" do
+ assert_equal [ Date.new(2021, 9, 3), Date.new(2021, 10, 1) ], period_of("Period 3 Sept 21 - 1 Oct 21")
+ assert_equal [ Date.new(2021, 9, 3), Date.new(2021, 10, 1) ], period_of("Période 3 sept. 21 au 1 oct. 21")
+ end
+
+ test "reads a two-digit-year period separated by a word" do
+ assert_equal [ Date.new(2021, 9, 3), Date.new(2021, 10, 1) ], period_of("Period 3 Sep 21 to 1 Oct 21")
+ end
+
+ test "prefers a four-digit-year period to an earlier two-digit one" do
+ text = "Previous period 3 Sep 21 - 1 Oct 21\nStatement period 1 Apr 2026 - 30 Apr 2026"
+
+ assert_equal [ Date.new(2026, 4, 1), Date.new(2026, 4, 30) ], period_of(text)
+ end
+
+ test "does not read numeric two-digit years, other words or times as a period" do
+ assert_equal [ nil, nil ], period_of(TWO_DIGIT_YEAR_TEXT.sub("3 Sep 21 - 1 Oct 21", "03/09/21 - 01/10/21"))
+ assert_equal [ nil, nil ], period_of(TWO_DIGIT_YEAR_TEXT.sub("3 Sep 21 - 1 Oct 21", "2 Marketing 21 - 5 Marketing 21"))
+ assert_equal [ nil, nil ], period_of(TWO_DIGIT_YEAR_TEXT.sub("3 Sep 21 - 1 Oct 21", "2 Marketing 21 - 3 Marketing 21"))
+ assert_equal [ nil, nil ], period_of(TWO_DIGIT_YEAR_TEXT.sub("3 Sep 21 - 1 Oct 21", "Ref 5123 Sep 21 - 1 Oct 21"))
+ assert_equal [ nil, nil ], period_of(TWO_DIGIT_YEAR_TEXT.sub("3 Sep 21 - 1 Oct 21", "1 Sep 20 - 1 Sep 2021"))
+ assert_equal [ nil, nil ], period_of(TWO_DIGIT_YEAR_TEXT.sub("3 Sep 21 - 1 Oct 21", "11:28PM 14NOV - 11:30PM 15NOV $21.00"))
+ end
+
test "ignores text without a period or balances" do
assert_nil AccountStatement::TextMetadataParser.parse("Invoice 2026-04 total 1.234,56 EUR due 15.05.2026")
assert_nil AccountStatement::TextMetadataParser.parse("")
diff --git a/test/models/account_statement_test.rb b/test/models/account_statement_test.rb
index 45dd1fc012..5fba500838 100644
--- a/test/models/account_statement_test.rb
+++ b/test/models/account_statement_test.rb
@@ -581,6 +581,34 @@ class AccountStatementTest < ActiveSupport::TestCase
assert_nil statement.sanitized_parser_output.dig("pdf", "balances_source")
end
+ test "reads a two-digit-year period from a statement pdf with a dateless filename" do
+ statement = AccountStatement.create_from_upload!(
+ family: @family,
+ account: @account,
+ file: Rack::Test::UploadedFile.new(
+ file_fixture("account_statements/two_digit_year_period.pdf"),
+ "application/pdf",
+ true,
+ original_filename: "eStatement_XXXXXXXXXX630_20.pdf"
+ )
+ )
+
+ assert_equal Date.new(2021, 9, 3), statement.period_start_on
+ assert_equal Date.new(2021, 10, 1), statement.period_end_on
+ end
+
+ test "takes a printed two-digit-year period over a filename date" do
+ Pdf::TextExtractor.stubs(:pages).returns([ CARD_STATEMENT_TEXT.sub("12 Apr 2024 - 15 May 2024", "12 Apr 24 - 15 May 24") ])
+ statement = AccountStatement.create_from_upload!(
+ family: @family,
+ account: accounts(:credit_card),
+ file: uploaded_file(filename: "card_2024-05.pdf", content_type: "application/pdf", content: "%PDF-1.4 card statement")
+ )
+
+ assert_equal Date.new(2024, 4, 12), statement.period_start_on
+ assert_equal Date.new(2024, 5, 15), statement.period_end_on
+ end
+
CARD_STATEMENT_TEXT = <<~TEXT
Statement period 12 Apr 2024 - 15 May 2024
Opening balance $1,066.47