Ir para o conteúdo

tempest_fastapi_sdk.wallet

Carteira: saldo, extrato, retenções e saque Pix em centavos inteiros.

« Integrações e pagamentos


wallet

Wallet module — balance, ledger, holds and Pix withdrawals in integer cents.

Reusable building blocks over the SDK primitives: a balance column mixin and an abstract ledger table with a make_* factory, a :class:WalletService whose every balance change is one SQL UPDATE plus its ledger line in the same transaction, a withdrawal that debits before it pays and gives the money back only when the provider refused, :func:claim_once for settlements that must run once, fee and split arithmetic in basis points, and an opt-in :func:make_wallet_router.

The decisions that go wrong the same way in every product, and are made here once:

  • a balance read in Python and written back loses credits under concurrency — the service never does that;
  • a hold checked before the debit can be drained by two withdrawals at once — the hold is part of the debit's WHERE;
  • a payout that failed ambiguously must keep its debit — returning it could pay twice;
  • money is never a float.

MANUAL_PAYOUT_PROVIDER module-attribute

MANUAL_PAYOUT_PROVIDER: Final[str] = 'manual'

Default :attr:ManualPayoutProvider.provider_name.

MANUAL_REVIEW_STATUS module-attribute

MANUAL_REVIEW_STATUS: Final[str] = 'manual_review'

The provider_status every manual payout answers with.

DEFAULT_REFUND_DESCRIPTION module-attribute

DEFAULT_REFUND_DESCRIPTION: Final[str] = 'Estorno: saque recusado'

Statement text of the WITHDRAW_REFUND line a rejection writes.

MAX_REJECTION_REASON_LENGTH module-attribute

MAX_REJECTION_REASON_LENGTH: Final[int] = 512

Longest reason :meth:ManualPayoutService.reject takes — the column's size.

BASIS_POINTS_PER_UNIT module-attribute

BASIS_POINTS_PER_UNIT: Final[int] = 10000

Basis points in 100 %.

OPENPIX_FEE_TIERS module-attribute

OPENPIX_FEE_TIERS: Final[OpenPixFeeTiers] = OpenPixFeeTiers(
    low_tier_max_cents=6250,
    low_tier_cents=50,
    mid_tier_max_cents=62500,
    mid_tier_per_mille=8,
    high_tier_cents=500,
    fixed_cents=100,
)

The schedule both Tempest services charge against today.

Ported from alofans-api's src/core/constants/money.py (OPENPIX_FEE_* and FIXED_TRANSACTION_FEE_CENTS), which transport-backend's src/core/constants/money.py repeats in reais: up to R$ 62,50 the fee is R$ 0,50; up to R$ 625,00 it is 0,8 %; above that, R$ 5,00; plus a fixed R$ 1,00 on every transaction. The values are the contract a service negotiated with the provider, not something the SDK can know — pass your own :class:OpenPixFeeTiers when yours differ.

PAYOUT_REFERENCE_TYPE module-attribute

PAYOUT_REFERENCE_TYPE: str = 'payout'

reference_type of the ledger lines a withdrawal writes.

WalletLedger

WalletLedger(
    *,
    balances: BaseRepository[Any],
    entries: BaseRepository[Any],
    balance_attribute: str = "wallet_cents",
)

Credit, debit, reverse and read wallets backed by a ledger.

Both repositories must share one session: a balance update and its ledger line commit together or not at all. Each move opens entries.transaction(), which is re-entrant: inside a caller's :func:~tempest_fastapi_sdk.db.transaction.transaction block it joins that block and does not commit on its own, so the move and the caller's own writes commit together when the outer block exits — or roll back together when it raises.

Attributes:

Name Type Description
balances BaseRepository[Any]

Repository of the model that holds the balance (usually the application's user model).

entries BaseRepository[Any]

Repository of the concrete :class:~tempest_fastapi_sdk.wallet.BaseWalletEntryModel.

balance_attribute str

Name of the balance column on balances.model.

Initialize the ledger.

Parameters:

Name Type Description Default
balances BaseRepository[Any]

Repository of the balance owner model.

required
entries BaseRepository[Any]

Repository of the ledger model.

required
balance_attribute str

The balance column's attribute name. "wallet_cents" matches :class:~tempest_fastapi_sdk.wallet.WalletBalanceMixin; an existing model passes its own ("wallet").

'wallet_cents'

Raises:

Type Description
ValueError

If the repositories do not share a session, or the balance model has no balance_attribute.

credit async

credit(
    user_id: UUID,
    amount_cents: int,
    *,
    kind: str,
    description: str = "",
    reference_type: str | None = None,
    reference_id: str | None = None,
    hold: timedelta = timedelta(0),
) -> WalletEntrySchema

Add amount_cents to a wallet and write the ledger line.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
amount_cents int

Amount to add, in cents.

required
kind str

Ledger kind, in the application's vocabulary.

required
description str

Statement text.

''
reference_type str | None

What the credit refers to.

None
reference_id str | None

Id of that reference.

None
hold timedelta

How long before the credit is withdrawable. timedelta(0) releases it at once.

timedelta(0)

Returns:

Name Type Description
WalletEntrySchema WalletEntrySchema

The ledger line.

Raises:

Type Description
ValueError

If amount_cents is not positive or hold is negative.

LookupError

If no balance row has user_id.

debit_available async

debit_available(
    user_id: UUID,
    amount_cents: int,
    *,
    kind: str,
    description: str = "",
    reference_type: str | None = None,
    reference_id: str | None = None,
) -> WalletEntrySchema

Take amount_cents out of the withdrawable part of a wallet.

The hold is enforced inside the UPDATE: the statement only matches when balance - amount stays at or above the sum of credits not yet released. Computing "available" first and then debiting with a plain balance >= amount guard lets two concurrent withdrawals both pass and drain held money — the gap this closes.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
amount_cents int

Amount to take, in cents.

required
kind str

Ledger kind.

required
description str

Statement text.

''
reference_type str | None

What the debit refers to.

None
reference_id str | None

Id of that reference.

None

Returns:

Name Type Description
WalletEntrySchema WalletEntrySchema

The ledger line, with a negative amount.

Raises:

Type Description
ValueError

If amount_cents is not positive.

InsufficientBalanceException

If the available balance is smaller than amount_cents.

reverse async

reverse(
    user_id: UUID,
    amount_cents: int,
    *,
    description: str = "",
    reference_type: str | None = None,
    reference_id: str | None = None,
) -> WalletEntrySchema | None

Take back a credit, held or not, if the balance still covers it.

For a refund to the payer after the payee was credited. Unlike :meth:debit_available, money on hold counts: it is exactly the money a reversal is supposed to reach first.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
amount_cents int

Amount to take back, in cents.

required
description str

Statement text.

''
reference_type str | None

What the reversal refers to.

None
reference_id str | None

Id of that reference.

None

Returns:

Type Description
WalletEntrySchema | None

WalletEntrySchema | None: The REVERSAL line, or None

WalletEntrySchema | None

when the balance no longer covers the amount (the payee already

WalletEntrySchema | None

withdrew it). None is a loss for the platform and should be

WalletEntrySchema | None

escalated by the caller; nothing was changed.

Raises:

Type Description
ValueError

If amount_cents is not positive.

balance async

balance(user_id: UUID, *, now: datetime | None = None) -> WalletBalanceSchema

Split a wallet into held and available.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
now datetime | None

The instant to evaluate holds at; defaults to the current UTC time.

None

Returns:

Name Type Description
WalletBalanceSchema WalletBalanceSchema

Total, held (capped at the total),

WalletBalanceSchema

available, and the next release.

Raises:

Type Description
LookupError

If no balance row has user_id.

statement async

statement(user_id: UUID, *, page: int = 1, page_size: int = 20) -> dict[str, Any]

Return a page of a wallet's ledger, newest first.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
page int

1-indexed page number.

1
page_size int

Lines per page.

20

Returns:

Type Description
dict[str, Any]

dict[str, Any]: items (:class:WalletEntrySchema),

dict[str, Any]

total, page, page_size and pages.

AdminMailer

Bases: Protocol

What an SDK component needs from a mailer to write to an admin.

:class:~tempest_fastapi_sdk.EmailUtils satisfies it as is, and so does :class:~tempest_fastapi_sdk.testing.fakes.FakeEmailUtils. Parameters are positional-only so an implementation may name them anything.

send

send(to: list[str], subject: str, body: str) -> Awaitable[None]

Send one plain-text message.

Parameters:

Name Type Description Default
to list[str]

Recipients.

required
subject str

Subject line.

required
body str

Plain-text body.

required

Returns:

Type Description
Awaitable[None]

Awaitable[None]: Completes once the message is handed over.

ManualPayoutProvider

ManualPayoutProvider(
    mailer: AdminMailer,
    *,
    admin_emails: Sequence[str],
    provider_name: str = MANUAL_PAYOUT_PROVIDER,
    subject_prefix: str = "[Saque manual]",
    records: BaseRepository[Any] | None = None,
    record_url: str | None = None,
    hooks: ManualPayoutHooks | None = None,
)

Pay a withdrawal out by e-mailing the administrators the Pix to send.

Error contract, as :class:~tempest_fastapi_sdk.integrations.payment.PayoutProvider asks:

  • the mailer raises :class:~tempest_fastapi_sdk.exceptions.EmailDeliveryException or :class:~tempest_fastapi_sdk.exceptions.IntegrationDisabledException -> :class:~tempest_fastapi_sdk.exceptions.PayoutRejectedException. No administrator received the order, so no one will send the money, and the wallet gets its debit back. EmailUtils raises the first one for every SMTP transport failure, including a timeout; a server that accepted the message and then lost the connection is the one case where that is wrong, and the correlation id in the next attempt's e-mail is what reconciles it;
  • anything else propagates, and the wallet keeps the debit and logs it CRITICAL — the outcome is unknown.

The e-mail carries the whole Pix key, because a person has to type it. The log line names it masked (:func:mask_pix_key).

With records, every payout is also written as a :class:~tempest_fastapi_sdk.wallet.BaseManualPayoutModel row (PENDING) before the e-mail goes out — the wallet debit has already committed by then. A row that cannot be written refuses the payout (the debit comes back and no e-mail is sent); an e-mail that fails turns the row CANCELED before the refusal. So a debit the wallet keeps always has a row the panel shows, except when the process dies between the debit's commit and this write — the WITHDRAW ledger line, whose reference_id is the correlation id, is what reconciles that case.

hooks (:class:~tempest_fastapi_sdk.wallet.ManualPayoutHooks) runs on_requested in the transaction that writes the row, and on_canceled in the one that cancels it. An on_requested that raises counts as a row that cannot be written (the payout is refused and the debit returned); an on_canceled that raises leaves the row PENDING and the debit held, and the withdrawal answers :class:~tempest_fastapi_sdk.exceptions.PayoutUncertainException. Settling the row afterwards is :class:~tempest_fastapi_sdk.wallet.ManualPayoutService's job.

Attributes:

Name Type Description
provider_name str

Copied into :attr:PayoutResult.provider.

admin_emails tuple[str, ...]

Who receives the order.

Store the mailer and the recipients.

Parameters:

Name Type Description Default
mailer AdminMailer

Sends the order — :class:~tempest_fastapi_sdk.EmailUtils built from EmailSettings, or a fake in development.

required
admin_emails Sequence[str]

The administrators' addresses.

required
provider_name str

The name the result and the ledger carry.

MANUAL_PAYOUT_PROVIDER
subject_prefix str

Prefixed to the subject line.

'[Saque manual]'
records BaseRepository[Any] | None

Repository of the project's concrete :class:~tempest_fastapi_sdk.wallet.BaseManualPayoutModel, on the request's session. None sends the e-mail only.

None
record_url str | None

A link to the row in the admin panel, with {id} where the row id goes ("https://api.example.com/admin/m/manual_payouts/{id}"). Written into the e-mail when records is set.

None
hooks ManualPayoutHooks | None

Transition callbacks; only on_requested and on_canceled run here, and only with records.

None

Raises:

Type Description
ValueError

If admin_emails is empty or holds an empty address — the order would go nowhere and the debit would sit without anyone told to pay it.

render

render(request: PayoutRequest, link: str | None = None) -> tuple[str, str]

Write the subject and body of the order for one payout.

The last instruction names both ways out of a payout the administrator cannot make — the panel's "Recusar e devolver" action and a refund by hand — because the provider cannot tell which one the service has: the action exists only when :func:~tempest_fastapi_sdk.admin.manual_payout_admin was given a ledger_factory.

Parameters:

Name Type Description Default
request PayoutRequest

The transfer to make.

required
link str | None

The row in the admin panel, when known.

None

Returns:

Type Description
tuple[str, str]

tuple[str, str]: The subject and the plain-text body.

transfer_to_pix_key async

transfer_to_pix_key(request: PayoutRequest) -> PayoutResult

E-mail the administrators the Pix to send.

Parameters:

Name Type Description Default
request PayoutRequest

The transfer.

required

Returns:

Name Type Description
PayoutResult PayoutResult

PENDING with provider_status="manual_review".

Raises:

Type Description
PayoutRejectedException

If the row could not be written, or the mailer could not deliver the order (see the class docstring).

BaseManualPayoutModel

Bases: BaseModel

Abstract row: one withdrawal waiting for, or paid by, a person.

Attributes:

Name Type Description
user_id UUID

FK to the wallet owner (set by subclass).

amount_cents int

The amount debited and to be sent.

pix_key_masked str

The destination key, masked. The full key is in the e-mail and in the owner's profile, not here.

pix_key_type str

The kind of key (email, cpf...).

correlation_id str

The withdrawal's id — also the ledger line's reference_id. Unique.

status str

A :class:ManualPayoutStatusEnum value.

receipt_key str | None

Storage key of the receipt PDF.

completed_at datetime | None

When it was marked paid.

completed_by str | None

Who marked it paid (the admin's id).

end_to_end_id str | None

The Pix end-to-end id of the transfer, when whoever marked it paid informed it.

rejection_reason str | None

Why the payout was refused. The panel lets an operator type it while the row is PENDING; :meth:~tempest_fastapi_sdk.wallet.ManualPayoutService.reject writes it.

rejected_at datetime | None

When it was refused.

rejected_by str | None

Who refused it (the admin's id).

ManualPayoutStatusEnum

Bases: BaseStrEnum

Where a manual payout stands.

Attributes:

Name Type Description
PENDING

Debited and e-mailed; nobody has marked it paid yet.

COMPLETED

An administrator marked it paid (the admin panel requires the receipt first; the service does so only with require_receipt=True). Final.

CANCELED

The e-mail to the administrators failed, so the payout was refused and the wallet debit given back. Final.

REJECTED

An administrator refused the payout (:meth:~tempest_fastapi_sdk.wallet.ManualPayoutService.reject) and the amount went back to the wallet as a WITHDRAW_REFUND line in the same commit. Final.

ManualPayoutHook

Bases: Protocol

A callback run inside a manual payout's transition.

It receives the session the transition runs on and the row as it is after the transition. Whatever it writes on that session commits with the transition; if it raises, the transition, the refund and its own writes roll back together. Parameters are positional-only so an implementation may name them anything.

ManualPayoutHooks dataclass

ManualPayoutHooks(
    on_requested: ManualPayoutHook | None = None,
    on_canceled: ManualPayoutHook | None = None,
    on_paid: ManualPayoutHook | None = None,
    on_rejected: ManualPayoutHook | None = None,
)

The callbacks a manual payout runs on each transition.

Pass the same instance to :class:~tempest_fastapi_sdk.wallet.ManualPayoutProvider (which writes the row and runs on_requested / on_canceled) and to :class:ManualPayoutService (on_paid / on_rejected).

Attributes:

Name Type Description
on_requested ManualPayoutHook | None

After the PENDING row is written, in its transaction. Raising refuses the payout: the row is not written, no e-mail goes out, the wallet gets its debit back.

on_canceled ManualPayoutHook | None

After the row turns CANCELED because the e-mail to the administrators failed, in that update's transaction. Raising leaves the row PENDING and the outcome unknown to the withdrawal, which keeps the debit and answers :class:~tempest_fastapi_sdk.exceptions.PayoutUncertainException.

on_paid ManualPayoutHook | None

After the row turns COMPLETED, in that transaction.

on_rejected ManualPayoutHook | None

After the row turns REJECTED and the refund line is written, in that transaction.

ManualPayoutService

ManualPayoutService(
    *,
    records: BaseRepository[PayoutModelT],
    ledger: WalletLedger | None = None,
    hooks: ManualPayoutHooks | None = None,
    refund_description: str = DEFAULT_REFUND_DESCRIPTION,
)

Bases: Generic[PayoutModelT]

Mark a manual payout paid, or refuse it and give the money back.

Each method is one transaction on the repository's session: the conditional UPDATE over PENDING, the refund (for a rejection) and the hook. Inside a caller's :func:~tempest_fastapi_sdk.db.transaction.transaction block it joins that block and commits with it.

Attributes:

Name Type Description
records BaseRepository[PayoutModelT]

Repository of the project's concrete :class:~tempest_fastapi_sdk.wallet.BaseManualPayoutModel.

ledger WalletLedger | None

The wallet the refund goes to.

hooks ManualPayoutHooks

The transition callbacks.

Store the repositories and the hooks.

Parameters:

Name Type Description Default
records BaseRepository[PayoutModelT]

Repository of the manual payout model.

required
ledger WalletLedger | None

The wallet ledger the refund of :meth:reject is credited through — WalletService.ledger when the project already has a service. None allows :meth:mark_paid only.

None
hooks ManualPayoutHooks | None

Transition callbacks.

None
refund_description str

Statement text of the refund line.

DEFAULT_REFUND_DESCRIPTION

Raises:

Type Description
ValueError

If ledger is on another session than records — the refund and the status change would commit apart.

mark_paid async

mark_paid(
    row_id: UUID,
    end_to_end_id: str | None = None,
    *,
    actor: str | None = None,
    require_receipt: bool = False,
) -> PayoutModelT

Move a PENDING payout to COMPLETED and run on_paid.

Parameters:

Name Type Description Default
row_id UUID

The payout row.

required
end_to_end_id str | None

The Pix end-to-end id of the transfer the administrator made, when known.

None
actor str | None

Who marked it paid, stored in completed_by.

None
require_receipt bool

Refuse a row without receipt_key. The admin panel passes True; a route that does not take receipts keeps the default.

False

Returns:

Name Type Description
PayoutModelT PayoutModelT

The row after the transition.

Raises:

Type Description
ManualPayoutNotFoundException

If no row has the id.

ManualPayoutNotPendingException

If the row is no longer PENDING.

ManualPayoutReceiptMissingException

If require_receipt and the row has no receipt.

reject async

reject(row_id: UUID, reason: str, *, actor: str | None = None) -> PayoutModelT

Refuse a PENDING payout and credit the amount back.

The row turns REJECTED with the reason, the wallet gets a WITHDRAW_REFUND line for the amount (reference_id is the correlation id, as in the WITHDRAW line), and on_rejected runs — all in one commit.

Parameters:

Name Type Description Default
row_id UUID

The payout row.

required
reason str

Why it was refused; stored in rejection_reason.

required
actor str | None

Who refused it, stored in rejected_by.

None

Returns:

Name Type Description
PayoutModelT PayoutModelT

The row after the transition.

Raises:

Type Description
ValueError

If reason is blank or longer than :data:MAX_REJECTION_REASON_LENGTH, or the service has no ledger. Nothing was written.

ManualPayoutNotFoundException

If no row has the id.

ManualPayoutNotPendingException

If the row is no longer PENDING.

BaseWalletEntryModel

Bases: BaseModel

Abstract ledger row: one credit or debit of a user's wallet.

Attributes:

Name Type Description
user_id UUID

FK to the wallet owner (set by subclass).

kind str

What the movement is ("SALE", "WITHDRAW"...). The service writes the values in :class:~tempest_fastapi_sdk.wallet.WalletEntryKindEnum; the application writes its own for credits.

amount_cents int

Signed amount — positive credits, negative debits.

balance_after_cents int

The balance right after this movement.

available_at datetime

When a credit becomes withdrawable. Equal to the creation time for a credit with no hold, and for every debit.

description str

Human-readable line for the statement.

reference_type str | None

What the movement refers to ("order", "payout"...).

reference_id str | None

The id of that reference, as text so a provider correlation id fits as well as a UUID.

WalletBalanceMixin

Integer-cents balance column for a user model.

Mix into the application's concrete user model. The attribute name wallet_cents is what :class:~tempest_fastapi_sdk.wallet.WalletService reads by default.

Attributes:

Name Type Description
wallet_cents int

Current balance in cents. Never negative when every write goes through the service.

NetSplit dataclass

NetSplit(
    total_cents: int,
    platform_cents: int,
    gateway_fee_cents: int,
    net_cents: int,
    shares: Mapping[str, int] = dict(),
)

How one transaction total divides between platform, gateway and payees.

platform_cents + gateway_fee_cents + sum(shares.values()) equals the total whenever the fees fit inside it; when they do not, net_cents is 0 and every share is 0.

Attributes:

Name Type Description
total_cents int

The amount split.

platform_cents int

The platform's cut.

gateway_fee_cents int

The payment gateway's fee.

net_cents int

What is left for the payees.

shares Mapping[str, int]

Each payee's cents, the residual recipient included.

OpenPixFeeTiers dataclass

OpenPixFeeTiers(
    low_tier_max_cents: int,
    low_tier_cents: int,
    mid_tier_max_cents: int,
    mid_tier_per_mille: int,
    high_tier_cents: int,
    fixed_cents: int,
)

The OpenPix per-transaction fee schedule, in integer cents.

Attributes:

Name Type Description
low_tier_max_cents int

Totals up to this pay low_tier_cents.

low_tier_cents int

Flat fee of the low tier.

mid_tier_max_cents int

Totals up to this (and above the low tier) pay mid_tier_per_mille of the total.

mid_tier_per_mille int

Rate of the middle tier, per thousand.

high_tier_cents int

Flat fee above the middle tier.

fixed_cents int

Added to every transaction, on top of the tier.

PixDestinationSchema

Bases: BaseSchema

Where a user's withdrawals go, as read from their profile.

Attributes:

Name Type Description
pix_key str

The registered key.

pix_key_type PixKeyType

Its kind.

WalletBalanceSchema

Bases: BaseSchema

How much of a wallet is withdrawable now.

Attributes:

Name Type Description
user_id UUID

The wallet owner.

total_cents int

The whole balance.

held_cents int

Credits not yet released, capped at the total.

available_cents int

total_cents - held_cents.

next_release_at datetime | None

When the next held credit is released, or None when nothing is held.

WalletEntryKindEnum

Bases: BaseStrEnum

Ledger kinds the wallet service writes on its own.

Credits for a sale, a tip or a commission are the application's vocabulary and go in as plain strings; these are the movements the service itself creates.

Attributes:

Name Type Description
WITHDRAW

Debit for a payout.

WITHDRAW_REFUND

The payout was refused, the debit came back.

REVERSAL

A previous credit was taken back (a refund to the payer).

OPENING_BALANCE

First line of a wallet that already had money before the ledger existed.

WalletEntrySchema

Bases: BaseSchema

One ledger line, as a statement shows it.

Attributes:

Name Type Description
id UUID

The line id.

user_id UUID

The wallet owner.

kind str

What the movement is.

amount_cents int

Signed amount in cents.

balance_after_cents int

Balance right after the movement.

available_at datetime

When the credit becomes withdrawable.

description str

Statement text.

reference_type str | None

What the movement refers to.

reference_id str | None

Id of that reference.

created_at datetime

When the movement happened.

WithdrawalSchema

Bases: BaseSchema

A completed withdrawal: the debit and what the provider answered.

Attributes:

Name Type Description
entry WalletEntrySchema

The WITHDRAW ledger line.

payout PayoutResult

The provider's answer.

WithdrawRequestSchema

Bases: BaseSchema

Body of POST {prefix}/withdraw.

Attributes:

Name Type Description
amount_cents int | None

Amount to withdraw; None takes the whole available balance.

WalletService

WalletService(
    *,
    ledger: WalletLedger | None = None,
    balances: BaseRepository[Any] | None = None,
    entries: BaseRepository[Any] | None = None,
    balance_attribute: str = "wallet_cents",
)

Withdraw wallets to Pix, and every ledger operation by delegation.

The writes and reads belong to :attr:ledger, a :class:~tempest_fastapi_sdk.wallet.WalletLedger. A service of the project that has to credit or debit inside its own transaction receives the ledger, not this class — a service never receives another service. This class is what the wallet router and a withdrawal use.

Attributes:

Name Type Description
ledger WalletLedger

The data layer the moves go through.

Initialize the service over a ledger, or build one.

Parameters:

Name Type Description Default
ledger WalletLedger | None

The ledger to delegate to. Pass it, or balances and entries — the form every service before #617 used, which builds the ledger here.

None
balances BaseRepository[Any] | None

Repository of the balance owner model, when no ledger is given.

None
entries BaseRepository[Any] | None

Repository of the ledger model, when no ledger is given.

None
balance_attribute str

The balance column's attribute name, used only when building the ledger here.

'wallet_cents'

Raises:

Type Description
ValueError

If both a ledger and repositories are given, if neither is, or if the ledger refuses the repositories (no shared session, no balance_attribute).

balances property

balances: BaseRepository[Any]

The ledger's balance repository, as before #617.

Returns:

Type Description
BaseRepository[Any]

BaseRepository[Any]: Repository of the balance owner model.

entries property

entries: BaseRepository[Any]

The ledger's entry repository, as before #617.

Returns:

Type Description
BaseRepository[Any]

BaseRepository[Any]: Repository of the ledger model.

balance_attribute property

balance_attribute: str

The balance column's attribute name, as before #617.

Returns:

Name Type Description
str str

The attribute name.

credit async

credit(
    user_id: UUID,
    amount_cents: int,
    *,
    kind: str,
    description: str = "",
    reference_type: str | None = None,
    reference_id: str | None = None,
    hold: timedelta = timedelta(0),
) -> WalletEntrySchema

Delegate to :meth:WalletLedger.credit.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
amount_cents int

Amount to add, in cents.

required
kind str

Ledger kind, in the application's vocabulary.

required
description str

Statement text.

''
reference_type str | None

What the credit refers to.

None
reference_id str | None

Id of that reference.

None
hold timedelta

How long before the credit is withdrawable.

timedelta(0)

Returns:

Name Type Description
WalletEntrySchema WalletEntrySchema

The ledger line.

debit_available async

debit_available(
    user_id: UUID,
    amount_cents: int,
    *,
    kind: str,
    description: str = "",
    reference_type: str | None = None,
    reference_id: str | None = None,
) -> WalletEntrySchema

Delegate to :meth:WalletLedger.debit_available.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
amount_cents int

Amount to take, in cents.

required
kind str

Ledger kind.

required
description str

Statement text.

''
reference_type str | None

What the debit refers to.

None
reference_id str | None

Id of that reference.

None

Returns:

Name Type Description
WalletEntrySchema WalletEntrySchema

The ledger line, with a negative amount.

reverse async

reverse(
    user_id: UUID,
    amount_cents: int,
    *,
    description: str = "",
    reference_type: str | None = None,
    reference_id: str | None = None,
) -> WalletEntrySchema | None

Delegate to :meth:WalletLedger.reverse.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
amount_cents int

Amount to take back, in cents.

required
description str

Statement text.

''
reference_type str | None

What the reversal refers to.

None
reference_id str | None

Id of that reference.

None

Returns:

Type Description
WalletEntrySchema | None

WalletEntrySchema | None: The REVERSAL line, or None

WalletEntrySchema | None

when the balance no longer covers the amount.

withdraw async

withdraw(
    user_id: UUID,
    *,
    payout: PayoutProvider,
    pix_key: str,
    pix_key_type: PixKeyType,
    amount_cents: int | None = None,
    correlation_id: str | None = None,
    description: str = "Saque Pix",
) -> WithdrawalSchema

Pay a wallet out to a Pix key: debit first, then transfer.

The order is the safety property. The debit commits before the provider is called, so a second withdrawal racing this one sees the reduced balance. Then:

  • the provider refuses (:class:~tempest_fastapi_sdk.exceptions.PayoutRejectedException) -> the debit is given back as a WITHDRAW_REFUND line, and the exception is re-raised;
  • anything else goes wrong -> the outcome is unknown, so the debit is kept, the case is logged CRITICAL with the correlation id, and :class:~tempest_fastapi_sdk.exceptions.PayoutUncertainException is raised. Giving the money back here could pay it twice.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
payout PayoutProvider

Who sends the Pix.

required
pix_key str

Destination key — read it from the owner's profile, never from the request body.

required
pix_key_type PixKeyType

Kind of key.

required
amount_cents int | None

Amount to withdraw. None takes the whole available balance.

None
correlation_id str | None

Id for the provider; a UUID is generated when omitted.

None
description str

Statement text, also sent as the comment.

'Saque Pix'

Returns:

Name Type Description
WithdrawalSchema WithdrawalSchema

The WITHDRAW line and the provider's

WithdrawalSchema

answer.

Raises:

Type Description
InsufficientBalanceException

If nothing (or not enough) is available.

PayoutRejectedException

If the provider refused; the debit was returned.

PayoutUncertainException

If the outcome is unknown; the debit was kept.

balance async

balance(user_id: UUID, *, now: datetime | None = None) -> WalletBalanceSchema

Delegate to :meth:WalletLedger.balance.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
now datetime | None

The instant to evaluate holds at.

None

Returns:

Name Type Description
WalletBalanceSchema WalletBalanceSchema

Total, held, available and next release.

statement async

statement(user_id: UUID, *, page: int = 1, page_size: int = 20) -> dict[str, Any]

Delegate to :meth:WalletLedger.statement.

Parameters:

Name Type Description Default
user_id UUID

The wallet owner.

required
page int

1-indexed page number.

1
page_size int

Lines per page.

20

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A page of :class:WalletEntrySchema lines.

format_brl

format_brl(cents: int) -> str

Write an amount of cents the way a Brazilian reads it.

Parameters:

Name Type Description Default
cents int

The amount, in cents.

required

Returns:

Name Type Description
str str

R$ 1.234,56 — dot for thousands, comma for decimals, and a

str

leading - for a negative amount.

mask_pix_key

mask_pix_key(key: str) -> str

Hide most of a Pix key, for a log line.

Parameters:

Name Type Description Default
key str

The key.

required

Returns:

Name Type Description
str str

The first two and the last two characters around ***; a key

str

of six characters or fewer becomes ***.

make_manual_payout_model

make_manual_payout_model(
    *,
    user_table: str = "users",
    tablename: str = "manual_payouts",
    class_name: str = "ManualPayoutModel",
    ondelete: str = "RESTRICT",
) -> type[BaseManualPayoutModel]

Build a concrete ManualPayoutModel subclass at runtime.

Parameters:

Name Type Description Default
user_table str

Table name of the concrete user model the FK references.

'users'
tablename str

__tablename__ for the generated class.

'manual_payouts'
class_name str

Python class name.

'ManualPayoutModel'
ondelete str

ON DELETE action of the user FK. RESTRICT by default, for the reason the wallet ledger uses it: the row is a money record.

'RESTRICT'

Returns:

Type Description
type[BaseManualPayoutModel]

type[BaseManualPayoutModel]: A concrete mapped class.

make_wallet_entry_model

make_wallet_entry_model(
    *,
    user_table: str = "users",
    tablename: str = "wallet_entries",
    class_name: str = "WalletEntryModel",
    ondelete: str = "RESTRICT",
) -> type[BaseWalletEntryModel]

Build a concrete WalletEntryModel subclass at runtime.

Parameters:

Name Type Description Default
user_table str

Table name of the concrete user model the FK references.

'users'
tablename str

__tablename__ for the generated class.

'wallet_entries'
class_name str

Python class name.

'WalletEntryModel'
ondelete str

ON DELETE action of the user FK. Defaults to "RESTRICT": a user with ledger lines cannot be hard-deleted, because CASCADE would erase the money history with them. Deactivate or anonymize the user instead; pass "CASCADE" only if losing that history is acceptable.

'RESTRICT'

Returns:

Type Description
type[BaseWalletEntryModel]

type[BaseWalletEntryModel]: A concrete mapped class.

openpix_fee_cents

openpix_fee_cents(
    total_cents: int, *, tiers: OpenPixFeeTiers = OPENPIX_FEE_TIERS
) -> int

Return the OpenPix fee for a transaction, in cents.

The middle tier rounds down (total * per_mille // 1000), as alofans-api does.

Parameters:

Name Type Description Default
total_cents int

The transaction total, in cents.

required
tiers OpenPixFeeTiers

The fee schedule.

OPENPIX_FEE_TIERS

Returns:

Name Type Description
int int

Tier fee plus fixed_cents.

Raises:

Type Description
ValueError

If total_cents is negative.

split_net

split_net(
    total_cents: int,
    *,
    platform_bps: int,
    gateway_fee_cents: int,
    residual_recipient: str,
    shares_bps: Mapping[str, int] | None = None,
) -> NetSplit

Split a transaction total into platform cut, gateway fee and payees.

The platform takes platform_bps of the gross total, rounded down. The gateway fee comes off next. What remains is the net, and every entry of shares_bps takes its basis points of the net, rounded down. residual_recipient takes the rest of the net, so the rounding of every share lands on one known payee instead of disappearing — the rule alofans-api uses for the producer (get_producer_profit), and the only payee transport-backend has (the driver, with no shares_bps).

Parameters:

Name Type Description Default
total_cents int

The transaction total, in cents.

required
platform_bps int

Platform cut, in basis points of the total.

required
gateway_fee_cents int

Gateway fee, in cents (for OpenPix, :func:openpix_fee_cents).

required
residual_recipient str

The payee who takes the net minus every other share.

required
shares_bps Mapping[str, int] | None

Other payees, each with basis points of the net.

None

Returns:

Name Type Description
NetSplit NetSplit

The split, with residual_recipient included in

NetSplit

shares.

Raises:

Type Description
ValueError

If an amount is negative, a basis-point value is out of 0..10000, the shares add up to more than 10 000 bp, or residual_recipient also appears in shares_bps.

make_wallet_router

make_wallet_router(
    *,
    service_factory: Callable[[AsyncSession], WalletService],
    session_factory: Callable[..., AsyncIterator[AsyncSession]],
    current_user_id: Callable[..., Any],
    payout_provider: Callable[..., Any],
    pix_destination: Callable[..., Any],
    prefix: str = "/api/wallet",
    tags: list[str] | None = None,
    docs_locale: str | None = None,
) -> APIRouter

Build the wallet router.

Endpoints, all for the authenticated user:

  • GET {prefix}/balance -> :class:WalletBalanceSchema.
  • GET {prefix}/statement -> a page of ledger lines, newest first.
  • POST {prefix}/withdraw -> pays the available balance (or amount_cents of it) to the user's registered Pix key.

Parameters:

Name Type Description Default
service_factory Callable[[AsyncSession], WalletService]

Builds a request-scoped :class:WalletService from the session.

required
session_factory Callable[..., AsyncIterator[AsyncSession]]

Yields a request-scoped DB session.

required
current_user_id Callable[..., Any]

FastAPI dependency resolving the authenticated user's :class:~uuid.UUID.

required
payout_provider Callable[..., Any]

FastAPI dependency resolving the :class:~tempest_fastapi_sdk.integrations.payment.PayoutProvider.

required
pix_destination Callable[..., Any]

FastAPI dependency resolving the current user's :class:PixDestinationSchema from their profile. Raise from it when the user has no key registered.

required
prefix str

URL prefix. Defaults to "/api/wallet".

'/api/wallet'
tags list[str] | None

OpenAPI tags. Defaults to ["wallet"].

None
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

Ready to mount with app.include_router.

claim_once async

claim_once(session: AsyncSession, model: type[Any], row_id: UUID, column: str) -> bool

Stamp column with now, only if it is still NULL.

The guard that makes a settlement run once: UPDATE ... WHERE id = :id AND column IS NULL. Two concurrent callers (a webhook retry and a manual confirmation, say) both issue it; only one finds the column still empty. The loser gets False and must not repeat the effects.

It does not commit. Call it inside the same :func:~tempest_fastapi_sdk.db.transaction.transaction block as the effects it guards, so a failure in those effects rolls the claim back too.

Parameters:

Name Type Description Default
session AsyncSession

The session the effects run on.

required
model type[Any]

The mapped class that owns the claim column (the product, the order, the charge).

required
row_id UUID

The row to claim.

required
column str

A nullable timestamp column, such as "wallet_credited_at".

required

Returns:

Name Type Description
bool bool

True if this call claimed the row.