tempest_fastapi_sdk.wallet¶
Carteira: saldo, extrato, retenções e saque Pix em centavos inteiros.
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
¶
Default :attr:ManualPayoutProvider.provider_name.
MANUAL_REVIEW_STATUS
module-attribute
¶
The provider_status every manual payout answers with.
DEFAULT_REFUND_DESCRIPTION
module-attribute
¶
Statement text of the WITHDRAW_REFUND line a rejection writes.
MAX_REJECTION_REASON_LENGTH
module-attribute
¶
Longest reason :meth:ManualPayoutService.reject takes — the column's size.
BASIS_POINTS_PER_UNIT
module-attribute
¶
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
¶
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: |
balance_attribute |
str
|
Name of the balance column on
|
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'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the repositories do not share a session, or the
balance model has no |
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)
|
Returns:
| Name | Type | Description |
|---|---|---|
WalletEntrySchema |
WalletEntrySchema
|
The ledger line. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
LookupError
|
If no balance row has |
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 |
InsufficientBalanceException
|
If the available balance is
smaller than |
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 |
WalletEntrySchema | None
|
when the balance no longer covers the amount (the payee already |
WalletEntrySchema | None
|
withdrew it). |
WalletEntrySchema | None
|
escalated by the caller; nothing was changed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
statement
async
¶
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]: |
dict[str, Any]
|
|
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 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.EmailDeliveryExceptionor :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.EmailUtilsraises 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: |
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: |
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: |
None
|
record_url
|
str | None
|
A link to the row in the admin panel,
with |
None
|
hooks
|
ManualPayoutHooks | None
|
Transition callbacks; only
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
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 ( |
correlation_id |
str
|
The withdrawal's id — also the ledger line's
|
status |
str
|
A :class: |
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 |
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
|
|
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: |
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 |
on_canceled |
ManualPayoutHook | None
|
After the row turns
|
on_paid |
ManualPayoutHook | None
|
After the row turns
|
on_rejected |
ManualPayoutHook | None
|
After the row turns
|
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: |
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: |
None
|
hooks
|
ManualPayoutHooks | None
|
Transition callbacks. |
None
|
refund_description
|
str
|
Statement text of the refund line. |
DEFAULT_REFUND_DESCRIPTION
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
None
|
require_receipt
|
bool
|
Refuse a row without |
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
|
ManualPayoutReceiptMissingException
|
If |
reject
async
¶
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
|
required |
actor
|
str | None
|
Who refused it, stored in |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
PayoutModelT |
PayoutModelT
|
The row after the transition. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ManualPayoutNotFoundException
|
If no row has the id. |
ManualPayoutNotPendingException
|
If the row is no longer
|
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 ( |
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
( |
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 |
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 |
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
|
|
next_release_at |
datetime | None
|
When the next held credit is
released, or |
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 |
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; |
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 |
None
|
balances
|
BaseRepository[Any] | None
|
Repository of the
balance owner model, when no |
None
|
entries
|
BaseRepository[Any] | None
|
Repository of the ledger
model, when no |
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 |
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
¶
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 |
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 aWITHDRAW_REFUNDline, and the exception is re-raised; - anything else goes wrong -> the outcome is unknown, so the debit
is kept, the case is logged
CRITICALwith the correlation id, and :class:~tempest_fastapi_sdk.exceptions.PayoutUncertainExceptionis 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
|
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 |
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
¶
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: |
format_brl
¶
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
|
|
str
|
leading |
mask_pix_key
¶
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 |
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
|
|
'manual_payouts'
|
class_name
|
str
|
Python class name. |
'ManualPayoutModel'
|
ondelete
|
str
|
|
'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
|
|
'wallet_entries'
|
class_name
|
str
|
Python class name. |
'WalletEntryModel'
|
ondelete
|
str
|
|
'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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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: |
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 |
NetSplit
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an amount is negative, a basis-point value is out
of |
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 (oramount_centsof it) to the user's registered Pix key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service_factory
|
Callable[[AsyncSession], WalletService]
|
Builds a
request-scoped :class: |
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: |
required |
payout_provider
|
Callable[..., Any]
|
FastAPI dependency resolving
the :class: |
required |
pix_destination
|
Callable[..., Any]
|
FastAPI dependency resolving
the current user's :class: |
required |
prefix
|
str
|
URL prefix. Defaults to |
'/api/wallet'
|
tags
|
list[str] | None
|
OpenAPI tags. Defaults to |
None
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |
claim_once
async
¶
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
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|