RevenueFlow.Commerce 0.1.0-alpha.7.2

This is a prerelease version of RevenueFlow.Commerce.
dotnet add package RevenueFlow.Commerce --version 0.1.0-alpha.7.2
                    
NuGet\Install-Package RevenueFlow.Commerce -Version 0.1.0-alpha.7.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RevenueFlow.Commerce" Version="0.1.0-alpha.7.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RevenueFlow.Commerce" Version="0.1.0-alpha.7.2" />
                    
Directory.Packages.props
<PackageReference Include="RevenueFlow.Commerce" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add RevenueFlow.Commerce --version 0.1.0-alpha.7.2
                    
#r "nuget: RevenueFlow.Commerce, 0.1.0-alpha.7.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package RevenueFlow.Commerce@0.1.0-alpha.7.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RevenueFlow.Commerce&version=0.1.0-alpha.7.2&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=RevenueFlow.Commerce&version=0.1.0-alpha.7.2&prerelease
                    
Install as a Cake Tool

RevenueFlow.Commerce

PurchaseFulfillmentService commits the order, independent entitlement grants, append-only resource credit entries, balance replacements, immutable business history, per-consumer outbox and command receipt in one AtomicCommitBatch against one IRevenueDocumentQueryStore. No provider operation runs inside fulfillment.

var commerce = new PurchaseFulfillmentService(documents, users,
    eventConsumerIds: ["receipt-notifications", "analytics"]);
var result = await commerce.FulfillAsync(confirmedPurchase, cancellationToken);
var balance = await commerce.FindResourceBalanceAsync(scope, userId, "tokens", cancellationToken);

Orders retain the frozen catalog revisions and source identity. Separate purchases create independent grants. Fixed-duration access begins at the supplied confirmation time and ends exclusively; IsActiveAt checks timestamps directly without requiring an expiry worker.

Replay checks the stored command receipt before current user or balance state. The SHA-256 request fingerprint includes the command type/version, full scope, owner, source, frozen snapshot, timestamps and exact attached completion writes. Bounded nested fingerprints bind the snapshot, raw event and every completion payload and identity without duplicating large source JSON into one fingerprint input. Changing a command's content raises a command conflict.

Optional ConfirmedPurchase.RawEvent JSON is captured independently of caller document lifetimes and retained as the business event's RawPayload beside normalized history data. It participates in the command fingerprint, so a changed raw event under the same command conflicts. Different evidence commands may carry different raw envelopes for the same economic purchase; they retain the original business history and never issue new benefits. Provider inbox storage retains each accepted evidence envelope independently. Raw provider JSON is never included in ToString output or exception messages.

Economic deduplication uses the structured origin store/account/per-purchase transaction tuple within the complete scope when supplied; otherwise it uses the integration provider/account/transaction tuple. The same canonical tuple converges across direct-store and intermediary adapters. New envelope commands for the same source return the original fulfillment and atomically record a new receipt and any completion writes. Economic identity includes the owner and frozen local offer; integration attribution, provider mappings and capture/observation times do not issue new benefits. Changed ownership or local terms raise an economic conflict. The first order retains both its integration and origin attribution. Origin subscription-chain identity is lineage only; renewals must use distinct per-purchase transaction IDs.

Providers are selected independently for every purchase. Different users in the same scope, and different purchases by the same user, can use Stripe, RevenueCat, direct stores or other adapters. Trusted adapters normalize origin store/account names and per-purchase identifiers consistently; absent or inconsistent canonical provenance cannot be deduplicated across integrations automatically.

Canonical recurring sources retain one benefit authority: monetary fulfillment or access-only evidence. The kind remains exclusive across user/billing-account ownership epochs and across integration aliases; an ownership fence does not permit a second benefit authority. This includes direct purchases linked to an existing recurring parent. Gift subscriptions additionally retain a private issuance owner. Generic subscription reconciliation cannot mutate or adopt that owner's source, and the issuance engine rejects a stale projection before committing benefits or advancing its cursor.

Personal paid grants link to subscriptions only within the same canonical ownership epoch, original payer, product, complete scope and mode. Returning from a billing account to the same user creates a distinct epoch; it cannot reactivate a prior epoch's fixed-duration or permanent grants, transfer those grants through the current subscription, or authorize a family grant from them. Earlier invoices within one epoch remain linked after renewal. Evaluation caches one exact scoped ownership-registry lookup per canonical lineage and validates the subscription's retained epoch key. Snapshot callers must include these registries; missing registry evidence for an epoched source fails closed. Legacy default-epoch records retain their canonical-key fallback.

A first finite recurring trial with no payment, price, quantity or paid-period evidence retains provisional trial provenance. After its original end, a newer confirmed paid period can atomically replace that trial's access authority with monetary authority, deactivate the old trial and fulfill its first payment. The integration, native product mapping when supplied, mode and original user must match, with no access or subscription ownership transfers. Ordinary access cannot acquire trial provenance later, and contradictory or nontrial evidence permanently removes this eligibility. Exact delayed evidence for a superseded trial records its completion without changing the inactive trial, paid subscription, resources or refund state.

Resource balance updates use checked integer arithmetic, a scoped user/resource unique key and expected-revision comparisons. Competing commands reread after definite revision or unique-key conflicts, with a bounded retry count (16 by default, maximum 64). A retry-limit conflict can be retried with the identical command. Transport errors or cancellation after submission may leave the commit outcome unknown: retry the identical request to recover its durable receipt. The service never assumes a lost response means rollback.

Paid-order refunds distinguish naturally expired units from consumed or reserved liability. Each lot retains cumulative natural expiry; refund preparation expires elapsed free units atomically when housekeeping has not run. Exact order/resource discovery includes transferred and rolled-over descendants and supports at most 120 retained lots per resource, within the existing 256-write transaction limit. No ledger-history scan is needed. Each adjustment claims its own expired-unit offset under the order accounting fence, including deferred manual resolution. Partial, cumulative and dispute adjustments cannot reuse an active offset. Reversal releases only its own offset and keeps natural expiry permanent; restored value retains its original expiry. Consumed/reserved shortfalls keep the selected debt/freeze/manual policy and unrelated debt or freeze reasons remain intact.

Definite-conflict retries use cancellation-aware randomized exponential delays to reduce synchronized work across processes. The first six upper bounds are 2/4/8/16/32/64 ms. Explicit AdaptiveAdmission advice then extends persistent-conflict bounds to 128/256/512/1,024 ms and caps each later wait at 1,024 ms; RetryOnly, unknown advice and absent advice retain the 64-ms cap. Every sampled wait is between one millisecond and its bound. The default remains 16 attempts, allowing at most fifteen scheduled waits: 7.166 seconds total for Adaptive and 0.702 seconds for RetryOnly. At the maximum configured 64 attempts those totals are 56.318 and 3.774 seconds. Store I/O and admission queueing are additional; application cancellation remains authoritative. Longer backoff trades latency for fewer exhausted commands and less retry work in the measured shared-account workload. It does not guarantee cross-process fairness or eliminate bounded retry exhaustion.

Within one process, purchase and lifecycle requests also share 4,096 fixed admission stripes keyed by the full scope and user UUID. The optional IRevenueCommandPreparationStore role supplies a receipt and scheduling advice through the existing initial lookup. AdaptiveAdmission lets a definite conflict activate owner admission for new commands, preventing them from bypassing waiting retries. RetryOnly, an unknown mode, or an absent role keeps fresh preparation optimistic and gates only retries; those requests neither join nor maintain another store's active cohort. Active admission persists until every interested request leaves, including queued fresh commands. Every admitted request contributes interest while waiting, preparing and submitting, and releases its gates before unregistering or delaying another attempt. All known owner stripes are acquired in sorted order; additional owners discovered during preparation join the next retry without acquiring new gates mid-attempt. Unknown reservation/adjustment owners retain optimistic discovery and bounded retry handling. Cancellation, preparation errors and unknown submissions release both gates and registrations; no timer or permanent hot-account mark is retained. Hash collisions can serialize unrelated requests; the registry does not grow with user count. This is a local scheduling optimization, not a distributed lock, authorization cache or replacement for atomic store revisions/claims. Receipt scope/command identity, attempt limits and unknown-outcome recovery remain authoritative.

The completion-writes overload allows an adapter to include durable inbox completion in the purchase transaction. These writes become part of the command fingerprint and cannot target commerce-owned document kinds. They must be trusted, expected-revision writes from the same store. Command replay returns the original receipt, so adapters should preserve the original completion write or recognize an already completed intake before reconstructing a command.

Fulfillment is bounded by AtomicCommitBatch.MaximumWrites (256) and the shared 64 KiB JSON limit. One order plus one write per grant, three per credited resource (ledger, balance and source lot), one history record, one outbox per configured consumer and all completion writes must fit the batch. Configure at most 32 distinct consumers. Consumers are captured at first fulfillment; changing configuration does not add deliveries to a replayed purchase.

The user store is consulted for an existing scoped immutable user. User creation remains separate from purchase fulfillment. A durable document adapter supplies recovery guarantees; the in-memory examples provide process-local behavior only.

Lifecycle services

RevenueLifecycleService implements IRevenueLifecycleService. All its mutation methods accept optional trusted completion writes, which join the receipt, domain effects, history and selected consumer outboxes in one atomic batch. Identical commands replay the original result before re-reading current state. No provider operation is performed by this service.

ApplySubscriptionAsync consumes an application-authorized SubscriptionChange with a positive monotonic provider revision. An equal revision with different normalized facts conflicts; older revisions cannot replace current state. A separately confirmed historical renewal can still issue its own economic benefits exactly once while its obsolete lifecycle projection is ignored. A renewal uses a distinct purchase transaction, an explicit period start/end, and OriginSubscriptionId matching the subscription's canonical identity. Trial observations create no payment, order or resource allocation. Paid-through, access end and renewal intent are independent fields. Cancellation preserves explicitly authorized access until its end; pause and expiry deny immediately; past-due grace is an explicit access-end policy. Trial access also ends at the trial timestamp. Scheduled terms remain pending until authoritative reconciliation supplies the effective plan; a timer cannot invent a billing change.

CreditAsync, SpendAsync, ReserveAsync, CaptureAsync, ReleaseAsync, TransferAsync, ExpireAsync and RolloverAsync use source allocation lots plus the original balance CAS. Spending consumes the earliest-expiring unreserved allocations. Expired units cannot be spent even when no expiration worker has run. Reservations retain their original allocation units through expiry until captured or released; releasing an expired reservation does not make its units spendable. Capture/release is economically terminal, including under different command IDs. Transfers and rollover preserve the originating order/entry and expiry provenance; transfer targets must be existing users in the same complete scope. Rollover explicitly extends remaining unreserved units into the supplied future expiry. New credits offset resource debt when computing available units; they do not erase the debt ledger. Capture requires the current unreserved, unexpired balance to cover all retained debt, allowing fully backed holds even when every net available unit is reserved. Expired free units cannot cover debt. A freeze denies spending and capture until explicitly reversed or operationally resolved.

SpendAsync(requiredEntitlement: ...) checks access and resource availability in the same transaction. An entitlement fence coordinates concurrent subscription changes, refunds and disputes, so a revocation cannot race a successful spend. CheckEntitlementAsync retains independent grant sources, applies each source's revocations/suspensions and timestamps, and respects subscription access policy. Public reads are live views; they are not multi-request snapshots.

ApplyAdjustmentAsync tracks cumulative monetary refunds independently of their resource targets. Resource proportions use exact integer arithmetic and cumulative rounding, including out-of-order partial-refund reversals. Only the selected order's remaining lots and grants are affected. Transferred and rolled-over lots retain source ownership for reversals. Consumed allocations follow an explicit ConsumedResourcePolicy: forgive unavailable units (ReverseRemaining), create debt, freeze with debt, or defer all resource/grant effects for manual review. ResolveManualAdjustmentAsync records one explicit operator policy without repeating money. ReverseAdjustmentAsync appends compensating entries, restores that adjustment's own units/revocations/debt and retains the original history. Adjustment and dispute keys must include the provider/account identity when necessary; they are unique within the full scope and cannot be moved to another order.

ApplyDisputeAsync uses monotonic revisions. Opening a dispute suspends only its source grants and freezes the resource accounts currently holding its source lots. Winning releases that dispute's own holds. Losing applies one economic adjustment under the selected consumed-credit policy. Terminal results cannot be reopened by changed or stale evidence.

Every purchase resource credit creates a source lot. Older E2 credit rows are materialized into lots within the first resource mutation. Stores implementing optional IRevenueResourceLotQueryStore can return exact scalar totals and a bounded expiry-ordered working set after that materialization; PostgreSQL and MongoDB provide native indexed implementations. Commerce still validates preparation through aggregate revision checks. Optional document filters narrow other queries before pagination; stores without these roles retain scoped compatibility paging. Legacy materialization and compatibility paths may scan history, so bounded returned pages alone do not guarantee bounded database work. One mutation remains bounded by 256 document writes and the shared JSON limits; operations that would exceed that atomic boundary fail without effects. Expiration processes a bounded set of due lots, so repeat it with a fresh command ID while FindResourceAsync reports expired units. Durable production guarantees depend on a conforming transaction-capable store and actual-database recovery/concurrency validation.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on RevenueFlow.Commerce:

Package Downloads
RevenueFlow.Customers

Provider-neutral scoped commerce building blocks for .NET.

RevenueFlow

RevenueFlow commerce composition with internal administrative issuance. External providers and stores are explicit opt-ins.

RevenueFlow.Teams

Provider-neutral scoped commerce building blocks for .NET.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0-alpha.7.2 66 11/10/2026