commerce

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: AGPL-3.0 Imports: 49 Imported by: 0

Documentation

Overview

Package commerce is Shopify and WooCommerce in ReputeCast (design expansion phase 7, M30): connecting a merchant's own store through the integrations hub, syncing its products, the customers who accepted marketing, its orders and abandoned checkouts (a first import of 3, 6 or 12 months, then webhooks and a nightly reconciliation), consent (only customers who accepted marketing ever join a list; unsubscribes travel both ways), store triggers and blocks in emails, and attributing orders to the email whose link the buyer clicked last.

The store platforms are reached through internal/stores only. Webhooks are verified, stored raw and answered at once; a River job applies them. Never stored: addresses, phone numbers, payment details and order notes. Orders and store webhooks aren't audited (ROADMAP default): the orders, the store's activity log and its raw events are their record; everything a person changes is.

Index

Constants

View Source
const (
	TriggerOrderPlaced       = "order_placed"
	TriggerFirstOrder        = "first_order"
	TriggerAbandonedCheckout = "abandoned_checkout"
)

Trigger kinds a store starts (automation_events.kind and the automations' trigger kinds).

View Source
const (
	EntryEntered     = "entered"
	EntryNoEmail     = "no_email"
	EntryNoConsent   = "no_consent"
	EntrySkipRule    = "skip_rule"
	EntryNotEligible = "not_eligible"
)

Entry outcomes of an abandoned checkout in an automation.

View Source
const (
	Shopify     = "shopify"
	WooCommerce = "woocommerce"
)

Platforms.

View Source
const (
	StatusConnecting   = "connecting"
	StatusImporting    = "importing"
	StatusConnected    = "connected"
	StatusDisconnected = "disconnected"

	StepAddress  = "address"
	StepApp      = "app"
	StepKeys     = "keys"
	StepInstall  = "install"
	StepSync     = "sync"
	StepKey      = "key"
	StepWebhooks = "webhooks"
	StepPlugin   = "plugin"
	StepDone     = "done"
)

Statuses and steps of a store (stores.status, stores.step).

View Source
const (
	// HealthEvery is how often webhooks are checked, and a missing one's
	// data polled until it's registered again.
	HealthEvery = 15 * time.Minute
	// Kept is how long raw events and the activity log are kept.
	Kept = 30 * 24 * time.Hour

	// NightlyHour is the reconciliation's hour, in the workspace's timezone.
	NightlyHour = 3
)

Timings.

View Source
const ConsentSourcePrefix = "store:"

ConsentSourcePrefix starts the consent source of a store's records: "store:shopify:<store id>".

View Source
const DefaultSkipDays = 7

DefaultSkipDays is the abandoned-cart starter's skip rule.

View Source
const IssueProductRemoved = "store.product_removed"

IssueProductRemoved is the content check of a store block that names a product the store removed: the composer flags it, Send Readiness warns, and sends leave the product out.

View Source
const KindStoreProblem = notify.KindStoreProblem

KindStoreProblem is the notification kind: a store disconnected, or its webhooks missing.

View Source
const MaxWebhookBody = 2 << 20

MaxWebhookBody is the largest delivery accepted.

View Source
const OpWooCheckouts = "report-woocommerce-checkouts"

OpWooCheckouts is the plugin's checkout report (every WordPress site's key may call it, like its report).

View Source
const PeriodDays = 30

PeriodDays is the store page's period.

Variables

This section is empty.

Functions

func CheckoutBlockHTML

func CheckoutBlockHTML(sample []orderItem, total int64, currency, button string) string

CheckoutBlockHTML is the Checkout items block as an automation email carries it, in English: sample items between the markers, and the button.

func CheckoutBlockHTMLIn

func CheckoutBlockHTMLIn(l i18n.Lang, sample []orderItem, total int64, currency, button string) string

CheckoutBlockHTMLIn is CheckoutBlockHTML with its words in a language: the email's.

func CheckoutItemsHTML

func CheckoutItemsHTML(items []orderItem, total int64, currency string) string

CheckoutItemsHTML draws checkout items in English: each line with its variant and quantity and price, then the total.

func CheckoutItemsHTMLIn

func CheckoutItemsHTMLIn(l i18n.Lang, items []orderItem, total int64, currency string) string

CheckoutItemsHTMLIn draws checkout items with the total's label in a language: the email's.

func CheckoutSection

func CheckoutSection(storeID uuid.UUID, drawing string) string

CheckoutSection is the Checkout items block as the composer keeps it: a section named for the layer tree, its drawing in a raw block.

func ConsentLabel

func ConsentLabel(l i18n.Lang, platform string) string

ConsentLabel is a store consent record's source, worded ("Shopify: accepted marketing at checkout"), for the audience's consent history.

func ConsentSource

func ConsentSource(st store.Store) string

ConsentSource is a store's consent records' source.

func Erasure

func Erasure() erasure.Source

Erasure is what synced stores told ReputeCast about the contact: the customer's name and address, the landing page and free-form UTM parts of orders, abandoned-cart links and the activity feed. Orders and customers stay, without them, for revenue and customer counts (review 2026-11 DP-1).

func GridSection

func GridSection(drawing string) string

GridSection is a product grid or card as the composer keeps it: the block's settings on the section (read from its drawing's marker), its drawing in a raw block.

func Money

func Money(v int64, currency string, cents bool) string

Money writes an amount the way emails show prices: "$58", or "$58.00" with the cents always shown.

func Register

func Register(h huma.API, s *Service)

Register adds the stores' operations. A store's page reads with integrations:view; connecting, configuring and disconnecting a store need integrations:manage and a person (API keys and agents can read).

func RegisterJobs

func RegisterJobs(reg *jobs.Registry, s *Service)

RegisterJobs adds the stores' workers and their schedules: deliveries applied as they arrive, first imports and reconciliations, abandoned checkouts and unsubscribes passed back every minute, webhooks checked every 15 minutes (a missing one's data polled meanwhile), the nightly reconciliation at 03:00 in each workspace's timezone.

func SampleAddress

func SampleAddress(host string) bool

SampleAddress reports whether a store address is one of the names reserved for examples (RFC 2606): no real store answers there, so the connect dialog's sample values connect a sample store.

func SealCredentials

func SealCredentials(box *secrets.Box, storeID uuid.UUID, clientSecret, accessToken string) ([]byte, error)

SealCredentials seals a Shopify app's client secret and access token as a store keeps them.

func SourcePlatform

func SourcePlatform(source string) string

SourcePlatform reads the platform from a store consent source ("" when it isn't one).

Types

type ActivityFacts

type ActivityFacts = activity

ActivityFacts are an activity entry's facts (store_activity.data).

type ApplyArgs

type ApplyArgs struct {
	EventID string `json:"event_id"`
}

ApplyArgs applies one stored delivery.

func (ApplyArgs) InsertOpts

func (ApplyArgs) InsertOpts() river.InsertOpts

InsertOpts runs on the events queue.

func (ApplyArgs) Kind

func (ApplyArgs) Kind() string

Kind implements river.JobArgs.

type ApplyWorker

type ApplyWorker struct {
	river.WorkerDefaults[ApplyArgs]
	S *Service
}

ApplyWorker applies stored deliveries.

func (*ApplyWorker) Work

func (w *ApplyWorker) Work(ctx context.Context, job *river.Job[ApplyArgs]) error

Work implements river.Worker.

type CatalogEntry

type CatalogEntry struct {
	Platform     string
	Status       string // not_connected, waiting, connected, attention
	ConnectionID string
	Stores       int
	Name         string
	State        string
	Orders       int64
	LastEventAt  *time.Time
}

CatalogEntry is a store platform's card in Settings › Integrations (the Commerce group).

type CheckoutLine

type CheckoutLine = orderItem

CheckoutLine is a line of an order or a checkout, as stored.

type CommerceActivityItem

type CommerceActivityItem struct {
	ID   string    `json:"id"`
	At   time.Time `json:"at"`
	Kind string    `` /* 260-byte string literal not displayed */
	Tone string    `json:"tone" enum:"neutral,ok,info,warn,bad"`
	// The order ("#4421") and its amount.
	Order    string `json:"order,omitempty"`
	Amount   int64  `json:"amount"`
	Currency string `json:"currency,omitempty"`
	// The person: a contact's name, or the customer's who accepted
	// marketing; never the email of anyone else.
	Customer  string `json:"customer,omitempty"`
	ContactID string `json:"contactId,omitempty"`
	// Accepted marketing at checkout; Contact: the buyer is a contact.
	Accepted bool `json:"accepted"`
	Contact  bool `json:"contact"`
	// Lists joined and automations started.
	Lists []string `json:"lists"`
	Flows []string `json:"flows"`
	// Attribution: how the order was matched and to which email.
	Matched      string `json:"matched,omitempty" enum:"click_token,email,none,"`
	Credited     string `json:"credited,omitempty"`
	CreditedKind string `json:"creditedKind,omitempty" enum:"campaign,automation,"`
	CreditedStep int    `json:"creditedStep,omitempty"`
	Window       int    `json:"window,omitempty"`
	Recovered    bool   `json:"recovered"`
	// Topic is the webhook the event came with.
	Topic  string `json:"topic,omitempty"`
	Source string `json:"source,omitempty"`
	By     string `json:"by,omitempty"`
	// Reconciliation: orders missed, products checked.
	Missed   int `json:"missed"`
	Products int `json:"products"`
	// Abandoned checkout: the automation and its delay.
	Flow  string `json:"flow,omitempty"`
	Hours int    `json:"hours,omitempty"`
	// Webhook registered again after polling while it was missing.
	Polled bool `json:"polled"`
	// Revoked: uninstalled or revoked; RateLimited: until.
	Reason  string     `json:"reason,omitempty"`
	Until   *time.Time `json:"until,omitempty"`
	Message string     `json:"message,omitempty"`
}

CommerceActivityItem is one entry of the store's activity log. The app words it from its facts.

type CommerceActivityList

type CommerceActivityList struct {
	Items []CommerceActivityItem `json:"items"`
	Next  string                 `json:"next,omitempty"`
}

CommerceActivityList is a page of the activity log.

type CommerceAttribution

type CommerceAttribution struct {
	Days     int        `json:"days"`
	SetBy    string     `json:"setBy,omitempty"`
	SetAt    *time.Time `json:"setAt,omitempty"`
	TagLinks bool       `json:"tagLinks"`
	// TagHost is the storefront the links point to (shop.acme.io), and
	// TagExample a tagged link's query.
	TagHost    string `json:"tagHost"`
	TagExample string `json:"tagExample"`
	Param      string `json:"param"`
	// Last 30 days.
	Orders          int64                `json:"orders"`
	Revenue         int64                `json:"revenue"`
	Credited        int64                `json:"credited"`
	CreditedRevenue int64                `json:"creditedRevenue"`
	ByToken         int64                `json:"byToken"`
	ByEmail         int64                `json:"byEmail"`
	Rows            []CommerceRevenueRow `json:"rows"`
	// Others groups the campaigns past the top rows ("9 other campaigns").
	Others *CommerceRevenueRow `json:"others,omitempty"`
}

CommerceAttribution is the Attribution card.

type CommerceAutomationOptions

type CommerceAutomationOptions struct {
	Stores []CommerceTriggerStore `json:"stores"`
}

CommerceAutomationOptions are the store triggers' choices.

type CommerceBeginInput

type CommerceBeginInput struct {
	Platform string `json:"platform" enum:"shopify,woocommerce"`
	Address  string `json:"address" maxLength:"255"`
}

CommerceBeginInput starts connecting a store: its platform and address.

type CommerceBlock

type CommerceBlock struct {
	Store string `json:"store" format:"uuid"`
	// Mode: card (one product), chosen (picked products), collection (the
	// newest of a collection).
	Mode       string   `json:"mode" enum:"card,chosen,collection"`
	Products   []string `json:"products" maxItems:"12"`
	Collection string   `json:"collection,omitempty" maxLength:"64"`
	Count      int      `json:"count,omitempty" minimum:"0" maximum:"6"`
	SoldOut    string   `json:"soldOut,omitempty" enum:"hide,label,"`
	CompareAt  bool     `json:"compareAt,omitempty"`
	Button     string   `json:"button,omitempty" maxLength:"40"`
	Heading    string   `json:"heading,omitempty" maxLength:"120"`
}

CommerceBlock is a store block's settings, as the composer keeps them on the block (rc-store).

type CommerceBlockRender

type CommerceBlockRender struct {
	HTML      string                   `json:"html"`
	StoreName string                   `json:"storeName"`
	Platform  string                   `json:"platform"`
	Products  []CommerceProduct        `json:"products"`
	Removed   []CommerceRemovedProduct `json:"removed"`
	// SoldOut are products hidden or labelled because they're sold out.
	SoldOut []string `json:"soldOut"`
	// Disconnected: the store isn't connected; the block keeps its last prices.
	Disconnected bool `json:"disconnected"`
}

CommerceBlockRender is a store block drawn now, with what to flag.

type CommerceBlockRenderInput

type CommerceBlockRenderInput struct {
	Block CommerceBlock `json:"block"`
}

CommerceBlockRenderInput draws a block.

type CommerceCampaignRevenue

type CommerceCampaignRevenue struct {
	Rows []CommerceCampaignStoreRow `json:"rows"`
}

CommerceCampaignRevenue is the campaign report's store rows.

type CommerceCampaignStoreRow

type CommerceCampaignStoreRow struct {
	StoreID  string `json:"storeId"`
	Name     string `json:"name"`
	Platform string `json:"platform"`
	Orders   int64  `json:"orders"`
	Revenue  int64  `json:"revenue"`
	Currency string `json:"currency"`
	Days     int    `json:"days"`
	ByToken  int64  `json:"byToken"`
	ByEmail  int64  `json:"byEmail"`
}

CommerceCampaignStoreRow is one store's orders credited to a campaign.

type CommerceCatalog

type CommerceCatalog struct {
	Stores []CommerceCatalogStore `json:"stores"`
}

CommerceCatalog lists the stores' catalogs for the composer's picker.

type CommerceCatalogStore

type CommerceCatalogStore struct {
	ID          string               `json:"id"`
	Name        string               `json:"name"`
	Platform    string               `json:"platform"`
	Currency    string               `json:"currency"`
	Products    int64                `json:"products"`
	Collections []CommerceCollection `json:"collections"`
	Status      string               `json:"status"`
}

CommerceCatalogStore is one store's catalog.

type CommerceCheckoutBlock

type CommerceCheckoutBlock struct {
	HTML string `json:"html"`
}

CommerceCheckoutBlock is the Checkout items block's HTML, with sample items from the store, for an automation email.

type CommerceCollection

type CommerceCollection struct {
	ID       string `json:"id"`
	Title    string `json:"title"`
	Products int64  `json:"products"`
}

CommerceCollection is a collection with its products.

type CommerceConnectState

type CommerceConnectState struct {
	Store CommerceStoreSummary `json:"store"`
	Step  string               `json:"step" enum:"address,app,keys,install,sync,key,webhooks,plugin,done"`
	// Shopify: the values to paste into the app.
	AppURL        string   `json:"appUrl"`
	RedirectURL   string   `json:"redirectUrl"`
	Scopes        []string `json:"scopes"`
	OptionalScope string   `json:"optionalScope"`
	// Reachable: the instance's public URL answers from the internet.
	Reachable          bool       `json:"reachable"`
	ReachableCheckedAt *time.Time `json:"reachableCheckedAt,omitempty"`
	ClientIDHint       string     `json:"clientIdHint,omitempty"`
	InstalledAt        *time.Time `json:"installedAt,omitempty"`
	Granted            []string   `json:"granted"`
	WriteGranted       bool       `json:"writeGranted"`
	// Error: the last refused client secret or key.
	Error string `json:"error" enum:",secret_refused,state_expired,not_installed"`
	// Step 5: the lists customers can join, and the new list's name.
	Lists       []CommerceListOption `json:"lists"`
	NewListName string               `json:"newListName"`
	Months      int                  `json:"months"`
	// WooCommerce.
	KeyHint  string               `json:"keyHint,omitempty"`
	Webhooks int                  `json:"webhooks"`
	Plugin   *CommercePluginState `json:"plugin,omitempty"`
	Demo     bool                 `json:"demo"`
	// Syncs is what syncs now, for "Change what syncs" on a connected store.
	Syncs CommerceSyncChoice `json:"syncs"`
}

CommerceConnectState is the connect dialog.

type CommerceConsent

type CommerceConsent struct {
	ListID      string `json:"listId,omitempty"`
	ListName    string `json:"listName,omitempty"`
	ListMembers int64  `json:"listMembers"`
	// ListCreated: the store's connection created the list.
	ListCreated bool `json:"listCreated"`
	WriteBack   bool `json:"writeBack"`
	// WriteGranted: the app may pass unsubscribes back (Shopify's
	// write_customers); WriteBackSupported is false on WooCommerce.
	WriteGranted       bool `json:"writeGranted"`
	WriteBackSupported bool `json:"writeBackSupported"`
}

CommerceConsent is the Customers and consent card.

type CommerceContactOrder

type CommerceContactOrder struct {
	ID           string    `json:"id"`
	StoreID      string    `json:"storeId"`
	Store        string    `json:"store"`
	Platform     string    `json:"platform"`
	Name         string    `json:"name"`
	PlacedAt     time.Time `json:"placedAt"`
	Total        int64     `json:"total"`
	Refunded     int64     `json:"refunded"`
	Currency     string    `json:"currency"`
	Items        []string  `json:"items"`
	Accepted     bool      `json:"accepted"`
	Credited     string    `json:"credited,omitempty"`
	CreditedKind string    `json:"creditedKind,omitempty" enum:"campaign,automation,"`
}

CommerceContactOrder is one of the contact's store orders.

type CommerceContactStore

type CommerceContactStore struct {
	StoreID  string `json:"storeId"`
	Name     string `json:"name"`
	Platform string `json:"platform"`
	Orders   int    `json:"orders"`
	Spent    int64  `json:"spent"`
	Currency string `json:"currency"`
	// Marketing is their consent in the store; OnList: on the store's list.
	Marketing string     `json:"marketing" enum:"subscribed,not_subscribed,unsubscribed,pending,none"`
	OnList    bool       `json:"onList"`
	ListName  string     `json:"listName,omitempty"`
	ConsentAt *time.Time `json:"consentAt,omitempty"`
}

CommerceContactStore is the contact as a store's customer.

type CommerceContactStores

type CommerceContactStores struct {
	Stores []CommerceContactStore `json:"stores"`
	Orders []CommerceContactOrder `json:"orders"`
}

CommerceContactStores is the contact profile's Store orders card.

type CommerceDisconnectInput

type CommerceDisconnectInput struct {
	DeleteData bool   `json:"deleteData"`
	Confirm    string `json:"confirm,omitempty" maxLength:"200"`
}

CommerceDisconnectInput disconnects a store; DeleteData also deletes its products and orders, confirmed by typing the store's name.

type CommerceFlow

type CommerceFlow struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Status string `json:"status"`
	Kind   string `json:"kind"`
	// PauseReason says why the store paused it.
	PauseReason string `json:"pauseReason,omitempty"`
}

CommerceFlow is an automation started by the store's triggers.

type CommerceImport

type CommerceImport struct {
	StartedAt time.Time `json:"startedAt"`
	StartedBy string    `json:"startedBy"`
	// Phase: products, customers, orders, matching, done.
	Phase       string           `json:"phase" enum:"products,customers,orders,matching,done"`
	Products    CommerceProgress `json:"products"`
	Collections int              `json:"collections"`
	Customers   CommerceProgress `json:"customers"`
	// Accepted joined the list (Known were contacts already, the rest are
	// new); NotAdded didn't accept marketing.
	Accepted int `json:"accepted"`
	Known    int `json:"known"`
	NotAdded int `json:"notAdded"`
	// CustomersSkipped: the platform has no customer list (WooCommerce:
	// consent comes with each order).
	CustomersSkipped bool             `json:"customersSkipped"`
	Orders           CommerceProgress `json:"orders"`
	Months           int              `json:"months"`
	Matching         CommerceProgress `json:"matching"`
	// MinutesLeft is the estimate for the orders still to import.
	MinutesLeft int        `json:"minutesLeft"`
	FinishedAt  *time.Time `json:"finishedAt,omitempty"`
}

CommerceImport is the first import's progress.

type CommerceInstall

type CommerceInstall struct {
	URL string `json:"url"`
}

CommerceInstall is where to approve the app.

type CommerceKeysInput

type CommerceKeysInput struct {
	ClientID     string `json:"clientId" maxLength:"100"`
	ClientSecret string `json:"clientSecret" maxLength:"200"`
}

CommerceKeysInput is a Shopify app's credentials (step 3).

type CommerceListOption

type CommerceListOption struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Members int64  `json:"members"`
	Store   bool   `json:"store"`
}

CommerceListOption is a list customers can join.

type CommerceNumbers

type CommerceNumbers struct {
	Days int `json:"days"`
	// Orders and Revenue in the store (minor units of Currency).
	Orders   int64  `json:"orders"`
	Revenue  int64  `json:"revenue"`
	Currency string `json:"currency"`
	// Credited to email, and their share of the revenue (percent).
	Credited        int64   `json:"credited"`
	CreditedRevenue int64   `json:"creditedRevenue"`
	Share           float64 `json:"share"`
	// On the store's list.
	ListMembers int64 `json:"listMembers"`
}

CommerceNumbers are the page's tiles.

type CommercePluginState

type CommercePluginState struct {
	Found     bool       `json:"found"`
	Skipped   bool       `json:"skipped"`
	Host      string     `json:"host"`
	CheckedAt *time.Time `json:"checkedAt,omitempty"`
	Version   string     `json:"version,omitempty"`
	// Consent and Checkouts: the plugin's checkout checkbox and abandoned
	// checkout reporting are on.
	Consent   bool `json:"consent"`
	Checkouts bool `json:"checkouts"`
	// SiteID is the WordPress site's connection, for "Open the site".
	SiteID string `json:"siteId,omitempty"`
}

CommercePluginState is WooCommerce's ReputeCast plugin on the store's site.

type CommerceProduct

type CommerceProduct struct {
	ID        string     `json:"id"`
	Title     string     `json:"title"`
	URL       string     `json:"url"`
	ImageURL  string     `json:"imageUrl"`
	ImageAlt  string     `json:"imageAlt"`
	Price     int64      `json:"price"`
	CompareAt int64      `json:"compareAt"`
	Currency  string     `json:"currency"`
	Available bool       `json:"available"`
	Inventory *int       `json:"inventory,omitempty"`
	Removed   bool       `json:"removed"`
	RemovedAt *time.Time `json:"removedAt,omitempty"`
}

CommerceProduct is a product, with its price and availability now.

type CommerceProductList

type CommerceProductList struct {
	Items []CommerceProduct `json:"items"`
	Total int64             `json:"total"`
	Next  int               `json:"next,omitempty"`
}

CommerceProductList is a page of a catalog.

type CommerceProductRef

type CommerceProductRef struct {
	ID    string `json:"id"`
	Title string `json:"title"`
}

CommerceProductRef names a product.

type CommerceProductsInput

type CommerceProductsInput struct {
	Collection string `query:"collection" maxLength:"64"`
	Search     string `query:"search" maxLength:"100"`
	Cursor     int    `query:"cursor" minimum:"0"`
	Limit      int    `query:"limit" minimum:"0" maximum:"100"`
}

CommerceProductsInput pages a store's catalog.

type CommerceProgress

type CommerceProgress struct {
	Done  int `json:"done"`
	Total int `json:"total"`
}

CommerceProgress is "5,120 of 7,880".

type CommerceQueued

type CommerceQueued struct {
	Queued bool `json:"queued"`
}

CommerceQueued says a sync was queued.

type CommerceRecoveredOrders

type CommerceRecoveredOrders struct {
	Orders  int64      `json:"orders"`
	Revenue int64      `json:"revenue"`
	Since   *time.Time `json:"since,omitempty"`
}

CommerceRecoveredOrders are the orders abandoned-cart emails brought back.

type CommerceRemovedProduct

type CommerceRemovedProduct struct {
	ID        string     `json:"id"`
	Title     string     `json:"title"`
	RemovedAt *time.Time `json:"removedAt,omitempty"`
	Platform  string     `json:"platform"`
}

CommerceRemovedProduct is a product a block names that the store deleted.

type CommerceRevenueRow

type CommerceRevenueRow struct {
	Kind    string `json:"kind" enum:"campaign,automation,others"`
	ID      string `json:"id,omitempty"`
	Name    string `json:"name"`
	Count   int    `json:"count"`
	Orders  int64  `json:"orders"`
	Revenue int64  `json:"revenue"`
}

CommerceRevenueRow is one email's credited orders.

type CommerceRevenueSummary

type CommerceRevenueSummary struct {
	Days            int     `json:"days"`
	Stores          int     `json:"stores"`
	Orders          int64   `json:"orders"`
	Revenue         int64   `json:"revenue"`
	Credited        int64   `json:"credited"`
	CreditedRevenue int64   `json:"creditedRevenue"`
	Share           float64 `json:"share"`
	Currency        string  `json:"currency"`
}

CommerceRevenueSummary is Earn › Overview's "Store revenue from email".

type CommerceSettingsInput

type CommerceSettingsInput struct {
	// ListID is the list customers who accepted marketing join ("" leaves
	// it as it is).
	ListID          *string `json:"listId,omitempty" maxLength:"36"`
	WriteBack       *bool   `json:"writeBack,omitempty"`
	TagLinks        *bool   `json:"tagLinks,omitempty"`
	AttributionDays *int    `json:"attributionDays,omitempty" minimum:"1" maximum:"30"`
	Products        *bool   `json:"products,omitempty"`
	Customers       *bool   `json:"customers,omitempty"`
	Orders          *bool   `json:"orders,omitempty"`
	Checkouts       *bool   `json:"checkouts,omitempty"`
}

CommerceSettingsInput changes a store's settings; fields left out keep their value.

type CommerceStoreList

type CommerceStoreList struct {
	Stores []CommerceStoreSummary `json:"stores"`
	// CanManage: the caller holds integrations:manage; Helpers hold it.
	CanManage bool     `json:"canManage"`
	Helpers   []string `json:"helpers"`
}

CommerceStoreList is a workspace's stores.

type CommerceStorePage

type CommerceStorePage struct {
	Store CommerceStoreSummary `json:"store"`
	// Facts of the header: the custom app, the API version, who connected.
	AppName      string     `json:"appName"`
	APIVersion   string     `json:"apiVersion"`
	ConnectedBy  string     `json:"connectedBy"`
	ConnectedAt  *time.Time `json:"connectedAt,omitempty"`
	Capabilities []string   `json:"capabilities"`
	PublicDomain string     `json:"publicDomain"`
	// Numbers for 30 days.
	Numbers CommerceNumbers `json:"numbers"`
	// UsedBy: automations started by the store's triggers, campaigns with
	// its blocks, and revenue in reports.
	UsedBy      []CommerceUse           `json:"usedBy"`
	Sync        CommerceSyncFacts       `json:"sync"`
	Consent     CommerceConsent         `json:"consent"`
	Attribution CommerceAttribution     `json:"attribution"`
	Webhooks    []CommerceWebhook       `json:"webhooks"`
	Activity    []CommerceActivityItem  `json:"activity"`
	Flows       []CommerceFlow          `json:"flows"`
	Plugin      *CommercePluginState    `json:"plugin,omitempty"`
	CanManage   bool                    `json:"canManage"`
	Helpers     []string                `json:"helpers"`
	Lists       []CommerceListOption    `json:"lists"`
	Recovered   CommerceRecoveredOrders `json:"recovered"`
}

CommerceStorePage is a store's page in the integrations hub.

type CommerceStoreSummary

type CommerceStoreSummary struct {
	ID       string `json:"id"`
	Platform string `json:"platform" enum:"shopify,woocommerce"`
	Name     string `json:"name"`
	// Address is what was typed (shop.acme.io); Domain the canonical host
	// (acme-merch.myshopify.com).
	Address  string            `json:"address"`
	Domain   string            `json:"domain"`
	Currency string            `json:"currency"`
	Status   string            `json:"status" enum:"connecting,importing,connected,disconnected"`
	Step     string            `json:"step"`
	Sync     CommerceSyncState `json:"sync"`
	Products int64             `json:"products"`
	ListID   string            `json:"listId,omitempty"`
	ListName string            `json:"listName,omitempty"`
	Demo     bool              `json:"demo"`
}

CommerceStoreSummary is a store in lists: the catalog's cards, the composer's product sources, the automation trigger's store picker.

type CommerceSyncChoice

type CommerceSyncChoice struct {
	Products  bool   `json:"products"`
	Customers bool   `json:"customers"`
	Orders    bool   `json:"orders"`
	Checkouts bool   `json:"checkouts"`
	WriteBack bool   `json:"writeBack"`
	ListID    string `json:"listId,omitempty"`
}

CommerceSyncChoice is what a store syncs and the list customers join.

type CommerceSyncFacts

type CommerceSyncFacts struct {
	Products       int64      `json:"products"`
	Collections    []string   `json:"collections"`
	Accepted       int64      `json:"accepted"`
	Known          int        `json:"known"`
	New            int        `json:"new"`
	NotAdded       int        `json:"notAdded"`
	OrdersImported int        `json:"ordersImported"`
	Months         int        `json:"months"`
	ImportFinished *time.Time `json:"importFinished,omitempty"`
	ImportMinutes  int        `json:"importMinutes"`
	Webhooks       int        `json:"webhooks"`
	WebhooksTotal  int        `json:"webhooksTotal"`
	ReconciledAt   *time.Time `json:"reconciledAt,omitempty"`
	Missed         int        `json:"missed"`
	// CustomersFromOrders: WooCommerce, where consent comes with orders.
	CustomersFromOrders bool `json:"customersFromOrders"`
}

CommerceSyncFacts is the Sync card.

type CommerceSyncInput

type CommerceSyncInput struct {
	Products  bool `json:"products"`
	Customers bool `json:"customers"`
	// ListID is an existing list; NewList creates one named after the store.
	ListID    string `json:"listId,omitempty" maxLength:"36"`
	NewList   bool   `json:"newList,omitempty"`
	Orders    bool   `json:"orders"`
	Months    int    `json:"months" enum:"3,6,12"`
	Checkouts bool   `json:"checkouts"`
	WriteBack bool   `json:"writeBack"`
	// WithoutPlugin connects a WooCommerce store without the ReputeCast
	// plugin: products and orders only.
	WithoutPlugin bool `json:"withoutPlugin,omitempty"`
}

CommerceSyncInput is what syncs (Shopify's step 5; WooCommerce's finish).

type CommerceSyncState

type CommerceSyncState struct {
	State       string     `json:"state" enum:"connecting,importing,connected,webhook_missing,rate_limited,no_plugin,disconnected"`
	LastEventAt *time.Time `json:"lastEventAt,omitempty"`
	// Missing are the webhooks gone from the store, polled every 15 minutes.
	Missing      []string   `json:"missing"`
	MissingSince *time.Time `json:"missingSince,omitempty"`
	// RateLimitedUntil: the store throttled ReputeCast; the sync slows down.
	RateLimitedUntil *time.Time      `json:"rateLimitedUntil,omitempty"`
	Import           *CommerceImport `json:"import,omitempty"`
	// RevokedReason: uninstalled (Shopify's app/uninstalled), revoked (a
	// refused token); empty when a person disconnected.
	RevokedAt      *time.Time `json:"revokedAt,omitempty"`
	RevokedReason  string     `json:"revokedReason" enum:",uninstalled,revoked"`
	DisconnectedAt *time.Time `json:"disconnectedAt,omitempty"`
	DisconnectedBy string     `json:"disconnectedBy,omitempty"`
}

CommerceSyncState is the store sync row: "Connected · last event 2 min ago", "Importing orders · 5,120 of 7,880", "Webhook missing · polling every 15 min", "Disconnected".

type CommerceTriggerStats

type CommerceTriggerStats struct {
	Since     *time.Time `json:"since,omitempty"`
	Abandoned int64      `json:"abandoned"`
	WithEmail int64      `json:"withEmail"`
	Entered   int64      `json:"entered"`
	NoConsent int64      `json:"noConsent"`
	Skipped   int64      `json:"skipped"`
	// Recovered orders credited to the automation, and their revenue.
	Orders   int64  `json:"orders"`
	Revenue  int64  `json:"revenue"`
	Currency string `json:"currency"`
}

CommerceTriggerStats are an abandoned-checkout trigger's numbers since its automation went live.

type CommerceTriggerStore

type CommerceTriggerStore struct {
	ID          string               `json:"id"`
	Name        string               `json:"name"`
	Address     string               `json:"address"`
	Platform    string               `json:"platform"`
	Status      string               `json:"status"`
	Currency    string               `json:"currency"`
	Checkouts   bool                 `json:"checkouts"`
	Products    []CommerceProductRef `json:"products"`
	Collections []CommerceCollection `json:"collections"`
}

CommerceTriggerStore is a store a trigger can watch.

type CommerceUse

type CommerceUse struct {
	Kind   string `json:"kind" enum:"automation,campaign,reports"`
	ID     string `json:"id,omitempty"`
	Name   string `json:"name,omitempty"`
	Status string `json:"status,omitempty"`
}

CommerceUse is one thing that uses the store.

type CommerceWebhook

type CommerceWebhook struct {
	Topic        string     `json:"topic"`
	Status       string     `json:"status" enum:"pending,registered,missing,failed"`
	LastEventAt  *time.Time `json:"lastEventAt,omitempty"`
	MissingSince *time.Time `json:"missingSince,omitempty"`
	Error        string     `json:"error,omitempty"`
}

CommerceWebhook is one webhook of the store.

type CommerceWooCheckout

type CommerceWooCheckout struct {
	Token     string `json:"token" minLength:"8" maxLength:"64" doc:"The plugin's checkout token"`
	Email     string `json:"email,omitempty" maxLength:"254"`
	FirstName string `json:"firstName,omitempty" maxLength:"100"`
	LastName  string `json:"lastName,omitempty" maxLength:"100"`
	// Accepted: the consent checkbox was ticked; ConsentText is its exact
	// text and ConsentAt when it was ticked.
	Accepted    bool                      `json:"accepted"`
	ConsentText string                    `json:"consentText,omitempty" maxLength:"500"`
	ConsentAt   *time.Time                `json:"consentAt,omitempty"`
	Items       []CommerceWooCheckoutItem `json:"items" maxItems:"100"`
	// Amounts are decimal strings in the store's currency ("76.00").
	Subtotal    string     `json:"subtotal" maxLength:"20"`
	Total       string     `json:"total" maxLength:"20"`
	Currency    string     `json:"currency" maxLength:"3"`
	RecoveryURL string     `json:"recoveryUrl" maxLength:"1000"`
	ClickToken  string     `json:"clickToken,omitempty" maxLength:"200"`
	CreatedAt   time.Time  `json:"createdAt"`
	UpdatedAt   time.Time  `json:"updatedAt"`
	CompletedAt *time.Time `json:"completedAt,omitempty" doc:"When it became an order"`
}

CommerceWooCheckout is one checkout: who (when they gave their email), what they ticked, the cart and the plugin's recovery link.

type CommerceWooCheckoutItem

type CommerceWooCheckoutItem struct {
	ProductID string `json:"productId" maxLength:"40"`
	VariantID string `json:"variantId,omitempty" maxLength:"40"`
	Title     string `json:"title" maxLength:"300"`
	Variant   string `json:"variant,omitempty" maxLength:"200"`
	Quantity  int    `json:"quantity" minimum:"0" maximum:"100000"`
	Price     string `json:"price" maxLength:"20" doc:"The unit price, a decimal string"`
	ImageURL  string `json:"imageUrl,omitempty" maxLength:"1000"`
}

CommerceWooCheckoutItem is a cart line.

type CommerceWooCheckoutsInput

type CommerceWooCheckoutsInput struct {
	SiteURL   string                `json:"siteUrl" maxLength:"300" example:"https://store.example.com"`
	Checkouts []CommerceWooCheckout `json:"checkouts" maxItems:"200"`
}

CommerceWooCheckoutsInput is a batch of checkouts from the plugin.

type CommerceWooCheckoutsResult

type CommerceWooCheckoutsResult struct {
	Store    string `json:"store" doc:"The store's name"`
	Accepted int    `json:"accepted"`
	Ignored  int    `json:"ignored"`
}

CommerceWooCheckoutsResult says what the batch did.

type CommerceWooKeyInput

type CommerceWooKeyInput struct {
	Key    string `json:"key" maxLength:"100"`
	Secret string `json:"secret" maxLength:"100"`
}

CommerceWooKeyInput is a WooCommerce REST API key.

type HealthArgs

type HealthArgs struct{}

HealthArgs checks every store's webhooks.

func (HealthArgs) InsertOpts

func (HealthArgs) InsertOpts() river.InsertOpts

InsertOpts: one check at a time.

func (HealthArgs) Kind

func (HealthArgs) Kind() string

Kind implements river.JobArgs.

type HealthWorker

type HealthWorker struct {
	river.WorkerDefaults[HealthArgs]
	S *Service
}

HealthWorker checks stores' webhooks.

func (*HealthWorker) Work

func (w *HealthWorker) Work(ctx context.Context, _ *river.Job[HealthArgs]) error

Work implements river.Worker.

type ImportArgs

type ImportArgs struct {
	StoreID string `json:"store_id"`
}

ImportArgs runs (or resumes) a store's first import.

func (ImportArgs) InsertOpts

func (ImportArgs) InsertOpts() river.InsertOpts

InsertOpts: one import per store at a time.

func (ImportArgs) Kind

func (ImportArgs) Kind() string

Kind implements river.JobArgs.

type ImportWorker

type ImportWorker struct {
	river.WorkerDefaults[ImportArgs]
	S *Service
}

ImportWorker runs first imports.

func (*ImportWorker) Timeout

func (w *ImportWorker) Timeout(*river.Job[ImportArgs]) time.Duration

Timeout lets an import run long; it snoozes itself before the limit.

func (*ImportWorker) Work

func (w *ImportWorker) Work(ctx context.Context, job *river.Job[ImportArgs]) error

Work implements river.Worker.

type NightlyArgs

type NightlyArgs struct{}

NightlyArgs runs every hour: each store is reconciled once a night, at 03:00 in its workspace's timezone; old events and activity are purged.

func (NightlyArgs) InsertOpts

func (NightlyArgs) InsertOpts() river.InsertOpts

InsertOpts: one run at a time.

func (NightlyArgs) Kind

func (NightlyArgs) Kind() string

Kind implements river.JobArgs.

type NightlyWorker

type NightlyWorker struct {
	river.WorkerDefaults[NightlyArgs]
	S *Service
}

NightlyWorker schedules the reconciliations.

func (*NightlyWorker) Work

Work implements river.Worker.

type PluginSite

type PluginSite struct {
	ID            uuid.UUID
	Host          string
	PluginVersion string
	WooCommerce   string
	Consent       bool
	Checkouts     bool
	LastReportAt  *time.Time
}

PluginSite is a WordPress site running the ReputeCast plugin.

type ReconcileArgs

type ReconcileArgs struct {
	StoreID string    `json:"store_id"`
	Since   time.Time `json:"since,omitzero"`
	// By is the person who asked ("Sync now").
	By string `json:"by,omitempty"`
}

ReconcileArgs reconciles a store: what changed since a time is fetched again, and every product checked.

func (ReconcileArgs) InsertOpts

func (ReconcileArgs) InsertOpts() river.InsertOpts

InsertOpts: one reconciliation per store at a time.

func (ReconcileArgs) Kind

func (ReconcileArgs) Kind() string

Kind implements river.JobArgs.

type ReconcileWorker

type ReconcileWorker struct {
	river.WorkerDefaults[ReconcileArgs]
	S *Service
}

ReconcileWorker runs reconciliations.

func (*ReconcileWorker) Timeout

Timeout gives a big store's catalog time.

func (*ReconcileWorker) Work

Work implements river.Worker.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Box   *secrets.Box
	Links *linktoken.Signer
	URLs  publicurl.Builder
	Log   *slog.Logger
	Jobs  func() *jobs.Client
	Now   func() time.Time
	// BaseURL and HTTP send every store call to one address (tests: a
	// fake's server).
	BaseURL string
	HTTP    *http.Client
	// Demo answers the demo's sample stores from in-process fakes, and
	// DemoApprove approves their app at once (the redirect Shopify would
	// send).
	Demo        func(platform string) *http.Client
	DemoApprove func(redirect, state string) string
	// AllowPrivate lets store addresses resolve to private networks
	// (development with a local store).
	AllowPrivate func() bool
	// Kick wakes the automations engine after store events were queued.
	Kick func(ctx context.Context)
	// Sites finds the WordPress site connected for a host (the
	// WooCommerce plugin check).
	Sites func(ctx context.Context, wsID uuid.UUID, host string) (PluginSite, bool)
	// PublicCheck reports whether the instance's public URL is reachable
	// from the internet, and when it was checked (the connect dialog).
	PublicCheck func(ctx context.Context) (bool, time.Time)
	// contains filtered or unexported fields
}

Service is the commerce domain.

func (*Service) Activity

func (s *Service) Activity(ctx context.Context, ws *store.Workspace, id uuid.UUID, cursor string, kinds []string, limit int) (CommerceActivityList, error)

Activity is a page of a store's activity log, newest first (30 days).

func (*Service) AppRoutes

func (s *Service) AppRoutes(r chi.Router)

AppRoutes mounts the app's addresses.

func (*Service) AppURL

func (s *Service) AppURL() string

AppURL and CallbackURL are what the merchant pastes into their Shopify app; WebhookURL is where a store's webhooks post.

func (*Service) Apply

func (s *Service) Apply(ctx context.Context, id uuid.UUID) error

Apply applies one stored delivery: normalized by its platform's parser, then applied in one transaction. A delivery that can't be parsed fails for good; one older than what's stored is stale.

func (*Service) AutomationOptions

func (s *Service) AutomationOptions(ctx context.Context, ws *store.Workspace) (CommerceAutomationOptions, error)

AutomationOptions are the store triggers' choices: each store (a disconnected one too, so a paused flow still names it), its products and collections.

func (*Service) AutomationRevenue

func (s *Service) AutomationRevenue(ctx context.Context, wsID uuid.UUID, ids []uuid.UUID, since time.Time) map[uuid.UUID]automations.AutomationRevenue

AutomationRevenue is the credited store orders of automations since a time (the automations list's 30-day columns). Nil when the workspace has no store.

func (*Service) Begin

Begin starts connecting a store: the address is checked against the platform, and the dialog moves to the app (Shopify) or the key (WooCommerce). A store disconnected before reconnects with its data.

func (*Service) CallbackURL

func (s *Service) CallbackURL() string

func (*Service) CampaignRevenue

func (s *Service) CampaignRevenue(ctx context.Context, ws *store.Workspace, campaignID uuid.UUID) (CommerceCampaignRevenue, error)

CampaignRevenue is a campaign's credited store orders, one row per store (the Revenue section's store rows).

func (*Service) Catalog

func (s *Service) Catalog(ctx context.Context, ws *store.Workspace) (CommerceCatalog, error)

Catalog is the composer's product picker: each store with products, its collections and counts. A disconnected store isn't offered (its blocks keep their last prices).

func (*Service) CatalogEntries

func (s *Service) CatalogEntries(ctx context.Context, ws *store.Workspace) ([]CatalogEntry, error)

CatalogEntries are the Commerce group's two cards. A store disconnected by a person shows Not connected; one the platform revoked needs attention.

func (*Service) CheckPlugin

func (s *Service) CheckPlugin(ctx context.Context, ws *store.Workspace, id uuid.UUID) (CommerceConnectState, error)

CheckPlugin looks for the ReputeCast plugin on a WooCommerce store's site ("Check again").

func (*Service) CheckStore

func (s *Service) CheckStore(ctx context.Context, st store.Store) error

CheckStore checks one store's webhooks and polls the missing ones' data.

func (*Service) CheckoutBlock

func (s *Service) CheckoutBlock(ctx context.Context, ws *store.Workspace, storeID uuid.UUID) (CommerceCheckoutBlock, error)

CheckoutBlock draws the Checkout items block with sample items: a store's newest products.

func (*Service) ConnectState

func (s *Service) ConnectState(ctx context.Context, ws *store.Workspace, id uuid.UUID) (CommerceConnectState, error)

ConnectState is the connect dialog of a store.

func (*Service) ContactActivity

func (s *Service) ContactActivity(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, before *time.Time, beforeID string, limit int) ([]audience.ContactActivityItem, int64, error)

ContactActivity implements audience.ActivitySource: a contact's store orders and the abandoned checkouts a flow looked at, on their timeline.

func (*Service) ContactStores

func (s *Service) ContactStores(ctx context.Context, ws *store.Workspace, contactID uuid.UUID) (CommerceContactStores, error)

ContactStores is the contact profile's Store orders card: the stores they're a customer of, with their consent there, and their latest orders.

func (*Service) Decorate

func (s *Service) Decorate(ctx context.Context, c tracking.ClickedLink) string

Decorate implements tracking.LinkDecorator.

func (*Service) DetectAbandoned

func (s *Service) DetectAbandoned(ctx context.Context) (int, error)

DetectAbandoned finds the checkouts each live abandoned-cart automation should hear about: with no order after its delay, created after it went live and after the store's import. Only contacts who accepted marketing in the store enter (the trigger's locked filter); the skip rule keeps out anyone who got an abandoned-cart email in the last 7 days.

func (*Service) Disconnect

Disconnect removes ReputeCast's webhooks from the store, pauses the automations its triggers start (they say why), and keeps its products and orders unless DeleteData. Contacts the store added stay, with their consent.

func (*Service) FinishWoo

func (s *Service) FinishWoo(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, withoutPlugin bool) (CommerceConnectState, error)

FinishWoo connects a WooCommerce store once its key and webhooks are in: with the plugin, or without it ("Connect without the plugin").

func (*Service) Health

func (s *Service) Health(ctx context.Context) error

Health checks every connected store (the demo's are never polled): its webhooks are still there, its credentials still work. A missing webhook is marked and told about once; its data is polled every 15 minutes until it's registered again, so nothing is missed. A refused token disconnects the store.

func (*Service) Import

func (s *Service) Import(ctx context.Context, id uuid.UUID, budget time.Duration) (time.Duration, error)

Import runs a store's first import for up to budget: products and collections, customers who accepted marketing (Shopify), orders of the last 3, 6 or 12 months, then past orders matched to past clicks. It returns how long to wait before running again (0 when done).

func (*Service) Install

Install returns Shopify's approval page for the app. The state names the person who started it; it works once, for 30 minutes.

func (*Service) Installed

func (s *Service) Installed(ctx context.Context, q map[string][]string) (store.Store, string, error)

Installed finishes Shopify's approval (the redirect URL): the code is exchanged for the access token with the app's secret. A reconnecting store goes straight back to syncing; a new one to step 5.

func (*Service) MessageVars

func (s *Service) MessageVars(ctx context.Context, msgCtx map[string]string) map[string]string

MessageVars is tracking's MessageVars: an automation message's checkout_url.

func (*Service) Nightly

func (s *Service) Nightly(ctx context.Context) error

Nightly queues the reconciliations due and purges what's older than 30 days.

func (*Service) Page

Page is a store's page in the integrations hub.

func (*Service) Products

Products is a page of a store's products, newest first, with their prices and availability now.

func (*Service) Reconcile

func (s *Service) Reconcile(ctx context.Context, id uuid.UUID, since time.Time, by *uuid.UUID) error

Reconcile fetches what changed in a store since a time (the last reconciliation, an hour of overlap) and checks every product: orders that hadn't arrived count as missed; products the store no longer has are flagged removed.

func (*Service) Reconnect

Reconnect starts connecting a store again: Shopify asks for approval again (or the app's keys, when a person disconnected it), WooCommerce for a key. A connected store keeps syncing meanwhile: approving the app again is how write_customers is granted later.

func (*Service) RegisterAgain

func (s *Service) RegisterAgain(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, all bool) (CommerceStorePage, error)

RegisterAgain registers a store's missing webhooks again ("Register again", "Register all again"): the polling stops, and the log says what it covered.

func (*Service) RemovedProducts

func (s *Service) RemovedProducts(ctx context.Context, in contentcheck.Input) []contentcheck.ContentCheckIssue

RemovedProducts is a contentcheck.Extra: a store block's products the store removed since the block was made.

func (*Service) RenderBlock

RenderBlock draws a store block with its products now, for the composer's canvas: removed products are drawn, and flagged.

func (*Service) Resolve

func (s *Service) Resolve(ctx context.Context, ws uuid.UUID, h string, stable bool) string

Resolve implements the sending engine's StoreContent: every store block of an email is drawn again with what the products cost and whether they're available now. A block whose store is disconnected keeps its last drawing.

func (*Service) RevenueSummary

func (s *Service) RevenueSummary(ctx context.Context, ws *store.Workspace) (CommerceRevenueSummary, error)

RevenueSummary is Earn › Overview's "Store revenue from email": every store's orders in the last 30 days and the part credited to email.

func (*Service) Routes

func (s *Service) Routes(r chi.Router)

Routes mounts the stores' webhooks: POST /hooks/{platform}/{token}. Static paths win over the sending providers' /hooks/{adapter}/{token}.

func (*Service) SaveKeys

SaveKeys keeps a Shopify app's client ID and its secret (sealed, write-only); the dialog moves to the install step.

func (*Service) SaveWooKey

SaveWooKey checks a WooCommerce REST API key, seals it and registers the webhooks with a new secret; the dialog moves to the plugin check.

func (*Service) Splice

func (s *Service) Splice(ctx context.Context, msgCtx map[string]string, h string) string

Splice implements StoreContent: the Checkout items block gets the items of the checkout or order that started the message's run.

func (*Service) StartSync

StartSync is Shopify's step 5: what syncs, the list, then the webhooks and the first import.

func (*Service) StarterEmail

func (s *Service) StarterEmail(ctx context.Context, wsID, storeID uuid.UUID, key string) (automations.EmailContent, bool)

StarterEmail writes the Abandoned cart starter's emails in the store's voice (automations' Service.StoreEmail): the first with the Checkout items block (sample items from the catalog on the canvas, the checkout's own items when it's sent), the second with the store's newest products.

func (*Service) Stores

Stores lists a workspace's stores.

func (*Service) SyncNow

func (s *Service) SyncNow(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (CommerceQueued, error)

SyncNow queues a reconciliation ("Sync now").

func (s *Service) TagsLink(ctx context.Context, ws uuid.UUID, link string) bool

TagsLink reports whether a link is to one of the workspace's tagged stores (the composer's hint).

func (*Service) Tick

func (s *Service) Tick(ctx context.Context) error

Tick is one minute's work.

func (*Service) TriggerStats

func (s *Service) TriggerStats(ctx context.Context, ws *store.Workspace, automationID uuid.UUID) (CommerceTriggerStats, error)

TriggerStats are an abandoned-checkout trigger's numbers since its automation went live: abandoned checkouts, with an email, entered, not emailed because they didn't accept marketing, skipped by the skip rule, and the orders credited to the automation.

func (*Service) UpdateSettings

UpdateSettings changes what syncs, the list, consent write-back and attribution. Each kind of change is audited with its before and after.

func (*Service) Vars

func (s *Service) Vars(ctx context.Context, msgCtx map[string]string) map[string]string

Vars implements StoreContent: a message's checkout_url, the store's recovery link of the checkout that started its run (an order's store front page).

func (*Service) WebhookURL

func (s *Service) WebhookURL(st store.Store) string

WebhookURL is a store's webhook address.

func (*Service) WooCheckouts

WooCheckouts applies the plugin's checkouts to the WooCommerce store at the site's address.

type StoreTrigger

type StoreTrigger struct {
	Kind  string `json:"kind"`
	Store string `json:"store"`
	// AfterHours: an abandoned checkout waits 1 to 24 hours for an order.
	AfterHours int `json:"afterHours"`
	// SkipDays: the skip rule, a contact who got an abandoned-cart email in
	// the last N days doesn't enter (0: no rule).
	SkipDays *int `json:"skipDays"`
	// Order placed's filters.
	Products    []string `json:"products"`
	Collections []string `json:"collections"`
	MinTotal    *int64   `json:"minTotal"`
	FirstOnly   bool     `json:"firstOnly"`
}

StoreTrigger is a store trigger's settings, as the automation's trigger keeps them (internal/automations' AutomationTrigger fields).

func (StoreTrigger) Hours

func (t StoreTrigger) Hours() int

Hours is the delay, 1 to 24 (1 by default).

func (StoreTrigger) Skip

func (t StoreTrigger) Skip() int

Skip is the skip rule's days.

type TickArgs

type TickArgs struct{}

TickArgs runs every minute.

func (TickArgs) InsertOpts

func (TickArgs) InsertOpts() river.InsertOpts

InsertOpts: one tick at a time.

func (TickArgs) Kind

func (TickArgs) Kind() string

Kind implements river.JobArgs.

type TickWorker

type TickWorker struct {
	river.WorkerDefaults[TickArgs]
	S *Service
}

TickWorker finds abandoned checkouts, passes unsubscribes back and requeues deliveries left unapplied.

func (*TickWorker) Work

func (w *TickWorker) Work(ctx context.Context, _ *river.Job[TickArgs]) error

Work implements river.Worker.

Jump to

Keyboard shortcuts

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