sequenceDiagram
autonumber
participant K as Kafka (bpds.inventory.in.receipt.import)
participant Bill as billing-service (FINANCE)
participant DB as DB_BILLING (PostgreSQL)
K->>Bill: 1. Consume Event [ProcessB2BFinancials()]
activate Bill
Bill->>DB: 2. SQL SELECT id WHERE receipt_number = :id (Idempotency Check)
activate DB
DB-->>Bill: 3. Result (Unique Record/No Matches Found)
deactivate DB
note over Bill: 4. Internal Method: CalculateReceiptTotal()<br/>Formula: total = ∑(quantity * price)
Bill->>DB: 5. ACID Transaction: SQL INSERT INTO b2b_transactions
activate DB
DB-->>Bill: 6. Response (COMMIT / Financial Log Saved)
deactivate DB
deactivate Bill
B2B Receipt Financial Processing
billing-service / Async Inbound Flow
Functional Purpose / Функциональное назначение
The method operates as an asynchronous event handler (Kafka Consumer) within the billing-service financial microservice. It is engineered to maintain automated accounting of user B2B expenditures and generate spending analytics based on dataset streams ingested via the retail network fiscal webhook.
The method solves the following architectural objectives:
- Asynchronous Financial Audit: Consumes trusted events indicating successful receipt imports from the message broker, iterates through the items matrix, and calculates the exact total cost of the entire basket, factoring in the fractional weight (
float/double) of specific inventory items. - Fiscal History Maintenance (Multi-Tenancy): Persists aggregated transaction data and raw receipt logs inside an isolated PostgreSQL Billing DB storage perimeter. This architecture allows end-users to access transparent spending analytics categorized by store brands, departments, and timestamps without inducing query performance degradation on core transactional tables of physical food inventory.
- Financial Perimeter Idempotency Enforcement: Shields the user space financial balance and historical metrics from double-accounting and redundant computation caused by duplicate messages within the Kafka broker by applying rigid uniqueness validations on the incoming fiscal receipt number.
Метод представляет собой асинхронный обработчик событий (Kafka Consumer) внутри финансового микросервиса billing-service. Он предназначен для ведения автоматического учета B2B-расходов пользователей и формирования аналитики трат на основе данных, поступающих из фискального вебхука торговой сети.
Метод решает следующие архитектурные задачи:
- Асинхронный финансовый аудит: Вычитывает доверенное событие успешного импорта чека из брокера сообщений, итерируется по массиву товаров и рассчитывает точную суммарную стоимость всей корзины с учетом дробного веса позиций.
- Ведение фискальной истории (Multi-Tenancy): Сохраняет агрегированные данные транзакции и сырой лог чека в изолированную базу данных PostgreSQL Billing DB. Это позволяет пользователям видеть прозрачную аналитику расходов в разрезе магазинов, категорий и дат, не нагружая транзакционные таблицы инвентаря физической еды.
- Обеспечение идемпотентности фин-контура: Защищает баланс аккаунта и исторические метрики от повторного начисления сумм при дублировании сообщений в брокере Kafka за счет жесткой проверки фискального номера чека на уникальность.
Схема обработки / Processing Schema (Mermaid)
Спецификация шагов / Step Specification
| Step | Action | Parameters | Errors |
|---|---|---|---|
| 1 | Worker reads B2B receipt message from Kafka topic. | Topic: bpds.inventory.in.receipt.import |
Kafka: CommitFailedException |
| 2 | Idempotency check: Service verifies receipt uniqueness. | SELECT id FROM b2b_transactions... |
PostgreSQL: ConnectionPoolTimeout |
| 3 | DB confirms document is unique. If duplicate, processing aborts. | Log: BILLING_DUPLICATE_IGNORE |
metric: billing_idempotency_blocks_total |
| 4 | Total sum calculation loop based on item weights. | Formula: total = sum(qty * price) |
NumericOverflowException |
| 5 | Transaction commit: System writes expense data to ledger. | INSERT INTO b2b_transactions... |
PostgreSQL: DeadlockDetected |
| 6 | DB confirms atomic commit and closes transaction. | Status: COMMIT |
PostgreSQL: DatabaseIsShuttingDown |
| Шаг | Действие | Параметры / Запросы | Ошибки (Исключения / Статусы) |
|---|---|---|---|
| 1 | Воркер вычитывает доверенное сообщение из топика Kafka. | Топик: bpds.inventory.in.receipt.import |
Kafka: CommitFailedException |
| 2 | Проверка идемпотентности фискального документа в СУБД. | SELECT id FROM b2b_transactions... |
PostgreSQL: ConnectionPoolTimeout |
| 3 | Подтверждение уникальности. При дублировании транзакция прерывается. | Лог: BILLING_DUPLICATE_IGNORE |
metric: billing_idempotency_blocks_total |
| 4 | Расчет аналитики и общей суммы трат с учетом веса. | Формула: total = sum(qty * price) |
NumericOverflowException |
| 5 | Открытие атомарной транзакции и запись лога расходов. | INSERT INTO b2b_transactions... |
PostgreSQL: DeadlockDetected |
| 6 | Фиксация изменений в таблице и закрытие транзакции. | Статус: COMMIT |
PostgreSQL: DatabaseIsShuttingDown |