Silver pipeline
02_invoice_silver_pipeline.py
This Lakeflow source reads bank statement and transaction observations from Bronze as streaming tables. Shared functions normalize missing string values and apply typed conversions while recording conversion failures.
Declarative expectations check required identifiers, valid dates, monetary fields and ingestion errors. Materialized views build account profiles, reconcile statement balances and check transaction-to-statement links.
The implementation retains source-document identifiers for traceability. Its Spark SQL tab isolates the actual expectation predicates embedded in the Python decorators.
The source imports normalize_source_strings and cast_with_validation from common_functions.py. Make that module importable in the Lakeflow pipeline; the spark session is supplied by the Databricks runtime.
The supplied Python source is reproduced unchanged. Deployed catalog identifiers are retained exactly as supplied. Python syntax has been checked; no Spark or Lakeflow execution was performed for this portfolio update.
"""Lakeflow Silver datasets for bank statements and transactions.
Shared transformations are imported from common_functions.py. Place both files
in the same pipeline source folder, or make the shared module importable through
the pipeline Python path. Run this source through the Lakeflow pipeline.
Existing deployed catalog references are intentionally preserved.
"""
from pyspark import pipelines as dp
from pyspark.sql import functions as F
from common_functions import normalize_source_strings, cast_with_validation
DATE_COLUMNS = [
"period_start", "period_end", "closing_date", "due_date"
]
AMOUNT_COLUMNS = [
"opening_balance", "closing_balance", "minimum_due",
"deposits_total", "other_credits_total", "checks_paid_total",
"electronic_payments_total", "fees_total", "payments_total",
"purchases_total", "balance_transfers_total",
"cash_advances_total", "interest_total",
"credit_limit", "available_credit"
]
TARGET_TYPES = {
**{c: "DATE" for c in DATE_COLUMNS},
**{c: "DECIMAL(19,4)" for c in AMOUNT_COLUMNS},
"summary_pdf_page": "INT",
"nonzero_transaction_line_count": "INT"
}
@dp.table(
name="statements",
comment="Typed statements from Bronze, with PDF traceability."
)
@dp.expect_all_or_fail({
"conversion_valid": "_conversion_errors = ''",
"document_present": "document_sha256 IS NOT NULL",
"account_present": "account_alias IS NOT NULL",
"period_valid": """
period_start IS NOT NULL
AND period_end IS NOT NULL
AND period_start <= period_end
""",
"ingestion_valid": """
_rescued_data IS NULL AND _corrupt_record IS NULL
"""
})
def statements():
source = spark.readStream.table(
"projetfactures_ws.a_bronze.statements_raw"
)
clean = normalize_source_strings(source)
typed = cast_with_validation(clean, TARGET_TYPES)
return typed.withColumn(
"_silver_processed_at", F.current_timestamp()
)
TRANSACTION_TYPES = {
"transaction_date": "DATE",
"posted_date": "DATE",
"amount_as_printed": "DECIMAL(19,4)",
"amount_abs": "DECIMAL(19,4)",
"balance_effect_amount": "DECIMAL(19,4)",
"pdf_page_number": "INT",
"native_text_line_number": "INT"
}
@dp.table(
name="bank_transactions",
comment="Typed bank transaction observations, with PDF traceability."
)
@dp.expect_all_or_fail({
"conversion_valid": "_conversion_errors = ''",
"observation_present": "observation_id IS NOT NULL",
"document_present": "document_sha256 IS NOT NULL",
"account_present": "account_alias IS NOT NULL",
"date_present": """
transaction_date IS NOT NULL OR posted_date IS NOT NULL
""",
"amount_valid": "amount_abs IS NOT NULL AND amount_abs >= 0",
"balance_effect_present": "balance_effect_amount IS NOT NULL",
"ingestion_valid": """
_rescued_data IS NULL AND _corrupt_record IS NULL
"""
})
def bank_transactions():
source = spark.readStream.table(
"projetfactures_ws.a_bronze.transactions_raw"
)
clean = normalize_source_strings(source)
typed = cast_with_validation(clean, TRANSACTION_TYPES)
return typed.withColumn(
"_silver_processed_at", F.current_timestamp()
)
from pyspark.sql.window import Window
@dp.materialized_view(
name="accounts",
comment="Accounts identified in Silver statements."
)
@dp.expect_all_or_fail({
"account_present": "account_alias IS NOT NULL",
"account_consistent": "_account_variant_count = 1"
})
def accounts():
distinct_accounts = (
spark.read.table("projetfactures_ws.a_silver.statements")
.select(
"account_alias",
"institution",
"account_type",
"product_name",
"currency_code",
"currency_code_status"
)
.distinct()
)
return distinct_accounts.withColumn(
"_account_variant_count",
F.count("*").over(Window.partitionBy("account_alias"))
)
@dp.materialized_view(
name="statement_reconciliation",
comment="Balance and observation checks for each statement."
)
@dp.expect_all_or_fail({
"transactions_present": "transaction_count > 0",
"observations_unique": """
transaction_count = distinct_observation_count
""",
"balances_present": """
opening_balance IS NOT NULL AND closing_balance IS NOT NULL
""",
"balance_reconciled": "reconciliation_difference = 0"
})
def statement_reconciliation():
movements = (
spark.read.table(
"projetfactures_ws.a_silver.bank_transactions"
)
.groupBy("document_sha256", "account_alias")
.agg(
F.count("*").alias("transaction_count"),
F.countDistinct("observation_id").alias(
"distinct_observation_count"
),
F.sum("balance_effect_amount").alias(
"total_balance_effect"
)
)
)
statements = spark.read.table(
"projetfactures_ws.a_silver.statements"
).select(
"document_sha256", "account_alias",
"opening_balance", "closing_balance"
)
return (
statements
.join(
movements,
["document_sha256", "account_alias"],
"left"
)
.withColumn(
"calculated_closing_balance",
(
F.col("opening_balance")
+ F.col("total_balance_effect")
).cast("decimal(19,4)")
)
.withColumn(
"reconciliation_difference",
(
F.col("closing_balance")
- F.col("calculated_closing_balance")
).cast("decimal(19,4)")
)
)
@dp.materialized_view(
name="transaction_statement_checks",
comment="Checks that each transaction matches exactly one statement."
)
@dp.expect_all_or_fail({
"one_matching_statement": "_matching_statement_count = 1"
})
def transaction_statement_checks():
statement_keys = (
spark.read.table("projetfactures_ws.a_silver.statements")
.groupBy("document_sha256", "account_alias")
.agg(F.count("*").alias("_matching_statement_count"))
)
return (
spark.read.table(
"projetfactures_ws.a_silver.bank_transactions"
)
.select("observation_id", "document_sha256", "account_alias")
.join(
statement_keys,
["document_sha256", "account_alias"],
"left"
)
.fillna({"_matching_statement_count": 0})
)
-- Spark SQL expression reference from 02_invoice_silver_pipeline.py
-- Embedded expressions, not a standalone SQL script.
-- Dataset: statements | Rule: conversion_valid
_conversion_errors = ''
-- Dataset: statements | Rule: document_present
document_sha256 IS NOT NULL
-- Dataset: statements | Rule: account_present
account_alias IS NOT NULL
-- Dataset: statements | Rule: period_valid
period_start IS NOT NULL
AND period_end IS NOT NULL
AND period_start <= period_end
-- Dataset: statements | Rule: ingestion_valid
_rescued_data IS NULL AND _corrupt_record IS NULL
-- Dataset: bank_transactions | Rule: conversion_valid
_conversion_errors = ''
-- Dataset: bank_transactions | Rule: observation_present
observation_id IS NOT NULL
-- Dataset: bank_transactions | Rule: document_present
document_sha256 IS NOT NULL
-- Dataset: bank_transactions | Rule: account_present
account_alias IS NOT NULL
-- Dataset: bank_transactions | Rule: date_present
transaction_date IS NOT NULL OR posted_date IS NOT NULL
-- Dataset: bank_transactions | Rule: amount_valid
amount_abs IS NOT NULL AND amount_abs >= 0
-- Dataset: bank_transactions | Rule: balance_effect_present
balance_effect_amount IS NOT NULL
-- Dataset: bank_transactions | Rule: ingestion_valid
_rescued_data IS NULL AND _corrupt_record IS NULL
-- Dataset: accounts | Rule: account_present
account_alias IS NOT NULL
-- Dataset: accounts | Rule: account_consistent
_account_variant_count = 1
-- Dataset: statement_reconciliation | Rule: transactions_present
transaction_count > 0
-- Dataset: statement_reconciliation | Rule: observations_unique
transaction_count = distinct_observation_count
-- Dataset: statement_reconciliation | Rule: balances_present
opening_balance IS NOT NULL AND closing_balance IS NOT NULL
-- Dataset: statement_reconciliation | Rule: balance_reconciled
reconciliation_difference = 0
-- Dataset: transaction_statement_checks | Rule: one_matching_statement
_matching_statement_count = 1
