events

package
v1.49.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package events provides a thin HTTP client for the analytics collector.

Commerce fires events via HTTP to the analytics-collector sidecar rather than writing directly to ClickHouse. This decouples analytics from the commerce binary.

Index

Constants

View Source
const (
	EventSubscriptionCreated     = "subscription_created"
	EventSubscriptionRenewed     = "subscription_renewed"
	EventSubscriptionPlanChanged = "subscription_plan_changed"
	EventSubscriptionCanceled    = "subscription_canceled"
	EventInvoiceFinalized        = "invoice_finalized"
	EventInvoicePaid             = "invoice_paid"
	EventInvoiceVoid             = "invoice_void"
	EventAPIUsageDebit           = "api_usage_debit"
)

Canonical billing lifecycle event names. This is the ONE place each name is defined, so the live emitters AND the one-time backfill (which replays existing rows) post byte-identical event strings — the read side keys on these.

View Source
const (
	SubjectOrderCreated    = "commerce.order.created"
	SubjectOrderCompleted  = "commerce.order.completed"
	SubjectOrderCanceled   = "commerce.order.canceled"
	SubjectOrderRefunded   = "commerce.order.refunded"
	SubjectCheckoutStarted = "commerce.checkout.started"
	SubjectCheckoutFailed  = "commerce.checkout.failed"
	SubjectPaymentReceived = "commerce.payment.received"
	SubjectCartUpdated     = "commerce.cart.updated"
	SubjectProductViewed   = "commerce.product.viewed"

	// Catalog lifecycle. A created/updated product is what closes the
	// commerce→content loop: the content lane consumes product.created to
	// auto-render the product's ecom asset (design == slug). Prefixed
	// `commerce.` like every other subject so the COMMERCE stream
	// (StreamSubjects `commerce.>`) captures them.
	SubjectProductCreated = "commerce.product.created"
	SubjectProductUpdated = "commerce.product.updated"

	// Referral events
	SubjectReferralLinkCreated      = "commerce.referral.link_created"
	SubjectReferralClaimed          = "commerce.referral.claimed"
	SubjectReferralCreditGranted    = "commerce.referral.credit_granted"
	SubjectReferralCommissionEarned = "commerce.referral.commission_earned"
	SubjectReferralPayoutSent       = "commerce.referral.payout_sent"
	SubjectReferralTierUpgraded     = "commerce.referral.tier_upgraded"

	// Contributor events
	SubjectContributorRegistered = "commerce.contributor.registered"
	SubjectContributorPayoutCalc = "commerce.contributor.payout_calculated"
	SubjectContributorPayoutSent = "commerce.contributor.payout_sent"
)

Standard commerce event subjects for NATS/JetStream.

View Source
const StreamName = "COMMERCE"

StreamName is the JetStream stream for commerce events.

Variables

View Source
var StreamSubjects = []string{"commerce.>"}

StreamSubjects defines what subjects the COMMERCE stream captures.

Functions

func Bootstrap added in v1.36.4

func Bootstrap(ctx context.Context, pubsub *infra.PubSubClient) error

Bootstrap creates the COMMERCE JetStream stream if it doesn't exist.

func SHA256Hex added in v1.36.4

func SHA256Hex(s string) string

SHA256Hex returns the lowercase hex SHA256 hash of a trimmed, lowercased string. Facebook CAPI requires user_data fields (em, ph) to be SHA256-hashed. Returns empty string for empty input.

Types

type APIUsage added in v1.49.1

type APIUsage struct {
	OrgID        string
	UserID       string
	AmountCents  int64
	AmountMicros int64
	Model        string
	Provider     string
	Project      string
	Service      string
	RequestID    string
	TotalTokens  int
	Status       string
}

APIUsage is a metered API-usage debit event for the collector. AmountCents is the debited spend (USD cents); AmountMicros carries the exact sub-cent debit.

type Client added in v1.36.0

type Client struct {
	// contains filtered or unexported fields
}

Client sends events to the analytics-collector via HTTP.

func NewClient added in v1.36.0

func NewClient(endpoint string) *Client

NewClient creates a new analytics client. Endpoint should be the analytics-collector base URL (e.g., "http://analytics-collector.hanzo.svc:8091").

func (*Client) BackfillAPIUsage added in v1.49.2

func (c *Client) BackfillAPIUsage(ctx context.Context, eventID string, ts time.Time, u *APIUsage) error

BackfillAPIUsage replays one metered-usage debit with a deterministic id at its historical time.

func (*Client) BackfillInvoice added in v1.49.2

func (c *Client) BackfillInvoice(ctx context.Context, event, eventID string, ts time.Time, in *Invoice) error

BackfillInvoice replays one invoice-lifecycle transition with a deterministic id at its historical time. event is one of the EventInvoice* names (revenue is derived from the event + invoice, identical to the live path).

func (*Client) BackfillSubscription added in v1.49.2

func (c *Client) BackfillSubscription(ctx context.Context, event, eventID string, ts time.Time, s *Subscription) error

BackfillSubscription replays one subscription-lifecycle transition with a deterministic id at its historical time. event is one of the EventSubscription* names.

func (*Client) Close added in v1.36.0

func (c *Client) Close() error

Close is a no-op for the HTTP client.

func (*Client) EmitAPIUsageDebit added in v1.49.1

func (c *Client) EmitAPIUsageDebit(ctx context.Context, u *APIUsage) error

EmitAPIUsageDebit sends an api_usage_debit event to the collector. revenue is the debited spend (USD) — realized consumption, mirroring order.Total.

func (*Client) EmitContributorPayoutCalculated added in v1.37.0

func (c *Client) EmitContributorPayoutCalculated(ctx context.Context, orgID, userID, periodMonth string, amount float64, currency string) error

EmitContributorPayoutCalculated sends a payout calculation event to the collector.

func (*Client) EmitContributorPayoutSent added in v1.37.0

func (c *Client) EmitContributorPayoutSent(ctx context.Context, orgID, userID, payoutID, periodMonth string, amount float64, currency string) error

EmitContributorPayoutSent sends a payout sent event to the collector.

func (*Client) EmitContributorRegistered added in v1.37.0

func (c *Client) EmitContributorRegistered(ctx context.Context, orgID, userID, githubUsername string) error

EmitContributorRegistered sends a contributor registration event to the collector.

func (*Client) EmitInvoiceFinalized added in v1.49.1

func (c *Client) EmitInvoiceFinalized(ctx context.Context, in *Invoice) error

EmitInvoiceFinalized sends an invoice_finalized event to the collector.

func (*Client) EmitInvoicePaid added in v1.49.1

func (c *Client) EmitInvoicePaid(ctx context.Context, in *Invoice) error

EmitInvoicePaid sends an invoice_paid event to the collector. revenue is the amount actually paid (USD) — realized cash, mirroring order.Total.

func (*Client) EmitInvoiceVoid added in v1.49.1

func (c *Client) EmitInvoiceVoid(ctx context.Context, in *Invoice) error

EmitInvoiceVoid sends an invoice_void event to the collector.

func (*Client) EmitOrderCompleted added in v1.36.0

func (c *Client) EmitOrderCompleted(ctx context.Context, order *Order) error

EmitOrderCompleted sends an order completed event to the collector.

func (*Client) EmitRaw added in v1.36.0

func (c *Client) EmitRaw(ctx context.Context, event map[string]interface{}) error

EmitRaw sends a raw event to the collector.

func (*Client) EmitReferralClaimed added in v1.37.0

func (c *Client) EmitReferralClaimed(ctx context.Context, orgID, referrerID, refereeID, referralCode string) error

EmitReferralClaimed sends a referral claimed event to the collector.

func (*Client) EmitReferralCommissionEarned added in v1.37.0

func (c *Client) EmitReferralCommissionEarned(ctx context.Context, orgID, referrerID, orderID string, commission float64, currency string) error

EmitReferralCommissionEarned sends a referral commission event to the collector.

func (*Client) EmitReferralCreditGranted added in v1.37.0

func (c *Client) EmitReferralCreditGranted(ctx context.Context, orgID, userID, role string, amount float64, currency string) error

EmitReferralCreditGranted sends a referral credit granted event to the collector.

func (*Client) EmitReferralLinkCreated added in v1.37.0

func (c *Client) EmitReferralLinkCreated(ctx context.Context, orgID, userID, referralCode, referralURL string) error

EmitReferralLinkCreated sends a referral link creation event to the collector.

func (*Client) EmitReferralTierUpgraded added in v1.37.0

func (c *Client) EmitReferralTierUpgraded(ctx context.Context, orgID, userID, previousTier, newTier string, referralCount int) error

EmitReferralTierUpgraded sends a referral tier upgrade event to the collector.

func (*Client) EmitSubscriptionCanceled added in v1.49.1

func (c *Client) EmitSubscriptionCanceled(ctx context.Context, s *Subscription) error

EmitSubscriptionCanceled sends a subscription_canceled event to the collector.

func (*Client) EmitSubscriptionCreated added in v1.49.1

func (c *Client) EmitSubscriptionCreated(ctx context.Context, s *Subscription) error

EmitSubscriptionCreated sends a subscription_created event to the collector.

func (*Client) EmitSubscriptionPlanChanged added in v1.49.1

func (c *Client) EmitSubscriptionPlanChanged(ctx context.Context, s *Subscription) error

EmitSubscriptionPlanChanged sends a subscription_plan_changed event to the collector.

func (*Client) EmitSubscriptionRenewed added in v1.49.1

func (c *Client) EmitSubscriptionRenewed(ctx context.Context, s *Subscription) error

EmitSubscriptionRenewed sends a subscription_renewed event to the collector.

func (*Client) Flush added in v1.36.0

func (c *Client) Flush() error

Flush is a no-op for the HTTP client (collector handles batching).

type CommerceEvent added in v1.36.4

type CommerceEvent struct {
	ID             string                 `json:"id"`
	Type           string                 `json:"type"`
	Timestamp      time.Time              `json:"timestamp"`
	OrganizationID string                 `json:"organization_id"`
	UserID         string                 `json:"user_id,omitempty"`
	SessionID      string                 `json:"session_id,omitempty"`
	Data           map[string]interface{} `json:"data"`
	GA4            *GA4EcommerceEvent     `json:"ga4,omitempty"`
	FacebookCAPI   *FacebookCAPIEvent     `json:"facebook_capi,omitempty"`
}

CommerceEvent is the standard envelope for all commerce events.

type FacebookCAPIEvent added in v1.36.4

type FacebookCAPIEvent struct {
	EventName    string                 `json:"event_name"`
	EventTime    int64                  `json:"event_time"`
	ActionSource string                 `json:"action_source"`
	UserData     *FacebookUserData      `json:"user_data,omitempty"`
	CustomData   map[string]interface{} `json:"custom_data,omitempty"`
}

FacebookCAPIEvent holds Facebook Conversions API format.

type FacebookUserData added in v1.36.4

type FacebookUserData struct {
	Email           string `json:"em,omitempty"`
	Phone           string `json:"ph,omitempty"`
	ExternalID      string `json:"external_id,omitempty"`
	ClientIPAddress string `json:"client_ip_address,omitempty"`
	ClientUserAgent string `json:"client_user_agent,omitempty"`
	FBC             string `json:"fbc,omitempty"`
	FBP             string `json:"fbp,omitempty"`
}

FacebookUserData for CAPI user matching. Email and Phone are SHA256-hashed per Facebook CAPI spec.

type GA4EcommerceEvent added in v1.36.4

type GA4EcommerceEvent struct {
	EventName  string                 `json:"event_name"`
	Currency   string                 `json:"currency,omitempty"`
	Value      float64                `json:"value,omitempty"`
	Items      []GA4Item              `json:"items,omitempty"`
	Parameters map[string]interface{} `json:"parameters,omitempty"`
}

GA4EcommerceEvent holds GA4 Enhanced Ecommerce format.

type GA4Item added in v1.36.4

type GA4Item struct {
	ItemID       string  `json:"item_id"`
	ItemName     string  `json:"item_name"`
	ItemBrand    string  `json:"item_brand,omitempty"`
	ItemCategory string  `json:"item_category,omitempty"`
	Price        float64 `json:"price"`
	Quantity     int     `json:"quantity"`
	Currency     string  `json:"currency,omitempty"`
}

GA4Item represents a single item in GA4 Enhanced Ecommerce format.

type Invoice added in v1.49.1

type Invoice struct {
	ID              string
	Number          string
	OrgID           string
	UserID          string
	Status          string
	AmountCents     int64
	AmountPaidCents int64
	Currency        string
	SubscriptionID  string
	Issued          string // RFC3339
	Due             string // RFC3339
}

Invoice is an invoice-lifecycle event for the collector. AmountCents is the amount due, AmountPaidCents what was actually collected; money is USD cents.

type LineItemInfo added in v1.36.4

type LineItemInfo struct {
	ProductID   string
	ProductName string
	SKU         string
	Quantity    int
	PriceCents  int64
}

LineItemInfo holds minimal line item data for event publishing. Avoids importing the lineitem package into the events package.

type Order

type Order struct {
	ID       string
	UserID   string
	Email    string
	Total    float64
	Currency string
	Items    []OrderItem
	Status   string
	OrgID    string
}

Order represents a Commerce order for event emission.

type OrderItem

type OrderItem struct {
	ProductID   string
	ProductName string
	SKU         string
	Quantity    int
	Price       float64
}

OrderItem represents an item in an order.

func ToOrderItems added in v1.36.4

func ToOrderItems(items []LineItemInfo) []OrderItem

ToOrderItems converts LineItemInfo slices to OrderItems for event publishing.

type Publisher added in v1.36.4

type Publisher struct {
	// contains filtered or unexported fields
}

Publisher sends commerce events to NATS/JetStream.

func NewPublisher added in v1.36.4

func NewPublisher(pubsub *infra.PubSubClient) *Publisher

NewPublisher creates a new event publisher. Returns nil if pubsub is nil.

func (*Publisher) Publish added in v1.36.4

func (p *Publisher) Publish(ctx context.Context, subject string, event *CommerceEvent) error

Publish sends an event to the appropriate NATS subject via JetStream.

func (*Publisher) PublishCheckoutStarted added in v1.36.4

func (p *Publisher) PublishCheckoutStarted(ctx context.Context, sessionID, orgName string, totalCents int64, currencyCode string) error

PublishCheckoutStarted sends a checkout.started event for hosted sessions.

func (*Publisher) PublishContributorPayoutCalculated added in v1.37.0

func (p *Publisher) PublishContributorPayoutCalculated(ctx context.Context, orgID, userID, periodMonth string, amountCents int64, currencyCode string) error

PublishContributorPayoutCalculated sends a contributor.payout_calculated event.

func (*Publisher) PublishContributorPayoutSent added in v1.37.0

func (p *Publisher) PublishContributorPayoutSent(ctx context.Context, orgID, userID, payoutID, periodMonth string, amountCents int64, currencyCode string) error

PublishContributorPayoutSent sends a contributor.payout_sent event when payout is transferred.

func (*Publisher) PublishContributorRegistered added in v1.37.0

func (p *Publisher) PublishContributorRegistered(ctx context.Context, orgID, userID, githubUsername string) error

PublishContributorRegistered sends a contributor.registered event.

func (*Publisher) PublishOrderCompleted added in v1.36.4

func (p *Publisher) PublishOrderCompleted(ctx context.Context, orderID, orgName, userID, email string, totalCents int64, currencyCode string, items []OrderItem) error

PublishOrderCompleted sends an order.completed event after capture/payment.

func (*Publisher) PublishOrderCreated added in v1.36.4

func (p *Publisher) PublishOrderCreated(ctx context.Context, orderID, orgName, userID, email string, totalCents int64, currencyCode string, items []OrderItem) error

PublishOrderCreated sends an order.created event after authorization.

func (*Publisher) PublishOrderRefunded added in v1.36.4

func (p *Publisher) PublishOrderRefunded(ctx context.Context, orderID, orgName, userID string, refundedCents int64, currencyCode string) error

PublishOrderRefunded sends an order.refunded event.

func (*Publisher) PublishProductCreated added in v1.47.0

func (p *Publisher) PublishProductCreated(ctx context.Context, orgName, productID, slug, name, sku string) error

PublishProductCreated sends a product.created event after a catalog product is created. It is the reverse half of the storefront loop: the content lane consumes this to auto-render the product's ecom asset (design == slug). Fire-and-forget, no-op when no publisher/pubsub is wired — exactly like the order publishers.

func (*Publisher) PublishProductUpdated added in v1.47.0

func (p *Publisher) PublishProductUpdated(ctx context.Context, orgName, productID, slug, name, sku string) error

PublishProductUpdated sends a product.updated event after a catalog product is replaced/patched. Same envelope as product.created; published for parity, so a consumer that reconciles catalog imagery sees edits too.

func (*Publisher) PublishReferralClaimed added in v1.37.0

func (p *Publisher) PublishReferralClaimed(ctx context.Context, orgID, referrerID, refereeID, referralCode string) error

PublishReferralClaimed sends a referral.claimed event when a new user signs up via referral.

func (*Publisher) PublishReferralCommissionEarned added in v1.37.0

func (p *Publisher) PublishReferralCommissionEarned(ctx context.Context, orgID, referrerID, orderID string, commissionCents int64, currencyCode string) error

PublishReferralCommissionEarned sends a referral.commission_earned event when a revenue share fee is created.

func (*Publisher) PublishReferralCreditGranted added in v1.37.0

func (p *Publisher) PublishReferralCreditGranted(ctx context.Context, orgID, userID, role string, amountCents int64, currencyCode string) error

PublishReferralCreditGranted sends a referral.credit_granted event when credits are issued.

func (*Publisher) PublishReferralLinkCreated added in v1.37.0

func (p *Publisher) PublishReferralLinkCreated(ctx context.Context, orgID, userID, referralCode, referralURL string) error

PublishReferralLinkCreated sends a referral.link_created event.

func (*Publisher) PublishReferralTierUpgraded added in v1.37.0

func (p *Publisher) PublishReferralTierUpgraded(ctx context.Context, orgID, userID, previousTier, newTier string, referralCount int) error

PublishReferralTierUpgraded sends a referral.tier_upgraded event when a referrer reaches a new tier.

type Subscription added in v1.49.1

type Subscription struct {
	ID          string
	OrgID       string
	UserID      string
	Plan        string // plan slug / id — the byPlan / byCategory key
	PlanName    string // human plan name
	Category    string // plan category — the byCategory bucket
	Status      string // active | trialing | canceled | past_due | ...
	Interval    string // month | year | ...
	PriceCents  int64  // raw plan price (USD cents)
	MRRCents    int64  // monthly-normalized recurring revenue (USD cents)
	Seats       int
	Trial       bool
	PeriodStart string // RFC3339
	PeriodEnd   string // RFC3339
}

Subscription is a subscription-lifecycle event for the collector. Money is USD cents (exact). MRRCents is the monthly-normalized recurring revenue so annual and monthly plans are comparable in one fleet sum.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL