shop

package
v0.0.0-...-963cf5d Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: GPL-3.0 Imports: 30 Imported by: 0

Documentation

Overview

Package shop implements the Ğ1 shop module (see CWUP/tasks/g1_shop.md).

Index

Constants

View Source
const (
	TypePhysical = "physical"
	TypeDigital  = "digital"
)

Product types.

View Source
const (
	DownloadLimit    = 5
	DownloadValidity = 30 * 24 * time.Hour
)

Download rules for digital products.

View Source
const (
	StatusOpen    = "open"
	StatusPaid    = "paid"
	StatusExpired = "expired"
)

Order states as stored on disk. "expired" is never stored: an open order past ExpiresAt reports StatusExpired, but stays payable (late payment).

View Source
const (
	CurrencyG1  = "G1"
	CurrencyEUR = "EUR"
	// PayCard is the order form's choice "card / SEPA via Stripe"; the
	// order itself is in EUR with Method MethodStripe.
	PayCard = "CARD"
)

Currencies of an order. Order files written before EUR support have no currency and are Ğ1 orders.

View Source
const HoneypotField = "website"

HoneypotField is a form field hidden from people; bots that fill it in are ignored.

View Source
const MaxFulfilAttempts = 5

MaxFulfilAttempts limits automatic fulfilment retries of one order.

View Source
const MaxQuantity = 99

MaxQuantity caps the quantity of one order.

View Source
const MethodStripe = "stripe"

MethodStripe marks EUR orders paid through Stripe Checkout (instead of a bank transfer).

Variables

View Source
var (
	ErrDownloadExpired = errors.New("download link expired")
	ErrDownloadUsedUp  = errors.New("download limit reached")
)

Download errors. ErrNotFound (unknown order or wrong token) is used for everything that must not reveal whether an order exists.

View Source
var ErrAlreadyPaid = errors.New("order already paid")

ErrAlreadyPaid is returned when a paid order is confirmed again.

View Source
var ErrNotFound = errors.New("order not found")

ErrNotFound is returned for unknown or malformed order IDs.

Functions

func ConfirmPayment

func ConfirmPayment(o *Order, token string, now time.Time) error

ConfirmPayment marks a EUR order as paid after the seller has seen the money on the bank account. It is the EUR counterpart of the Ğ1 watcher booking a transfer.

func Currencies

func Currencies(p Product, pay Payments) []string

Currencies returns the currencies product p can be paid in: Ğ1 if it has a Ğ1 price and the shop has a wallet, EUR if it has a EUR price and the shop accepts bank transfers, card if it has a EUR price and Stripe is ready.

func EmailField

func EmailField(fields []config.ContactField) string

EmailField returns the name of the first email field, or "" if none.

func FormatPrices

func FormatPrices(p Product, currencies []string) string

FormatPrices renders all prices of p for the given currencies, e.g. "12.50 Ğ1 / 9.90 EUR".

func IsDonation

func IsDonation(comment string, keywords []string) bool

IsDonation reports whether comment contains one of keywords as a whole word, ignoring case.

func IssueConfirmToken

func IssueConfirmToken(o *Order) (string, error)

IssueConfirmToken gives an open EUR order the secret the seller uses to confirm the bank transfer. It returns the token, which exists only in the seller's order mail from then on (like download tokens, only the hash is stored).

func IssueDelivery

func IssueDelivery(o *Order, now time.Time) (string, error)

IssueDelivery gives a paid digital order its license key and a fresh download token. It returns the token, which exists only in the buyer's email from then on. Calling it again issues a new token (re-issue by the seller) and keeps the license key.

func OrderIDsInComment

func OrderIDsInComment(comment string) []string

OrderIDsInComment returns the normalised order IDs found in a comment.

func PriceCurrencies

func PriceCurrencies(currencies []string) []string

PriceCurrencies drops the card option when EUR is listed too: both show the same euro price.

func RenderConfirmPage

func RenderConfirmPage(d ConfirmPageData) (template.HTML, error)

RenderConfirmPage renders the confirm page fragment.

func RenderDownloadProblem

func RenderDownloadProblem(lang, message string) (template.HTML, error)

RenderDownloadProblem renders the page for an expired or used-up link.

func RenderOrderForm

func RenderOrderForm(d OrderFormData) (template.HTML, error)

RenderOrderForm renders the order form fragment.

func RenderPayPage

func RenderPayPage(d PayPageData) (template.HTML, error)

RenderPayPage renders the payment page fragment.

func ResolveDeliveryFile

func ResolveDeliveryFile(baseDir, rel string) (string, error)

ResolveDeliveryFile returns the absolute path of a Delivery file below baseDir. The file must be a regular file, and neither the path nor any symlink on the way may lead outside baseDir.

func T

func T(lang, key string) string

T returns the shop text for key in lang, falling back to English.

func ValidDownloadToken

func ValidDownloadToken(t string) bool

ValidDownloadToken reports whether t has the download token format.

func ValidOrderID

func ValidOrderID(id string) bool

ValidOrderID reports whether id has the order ID format. Checked before any file access, so an ID can never become a path.

func VisibleFields

func VisibleFields(p Product, fields []config.ContactField) []config.ContactField

VisibleFields returns the form fields shown for product p: fields marked physical are left out for digital products.

Types

type Catalog

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

Catalog holds a site's products in file order.

func ParseCatalog

func ParseCatalog(source string) (*Catalog, error)

ParseCatalog parses a Catalog { Product { ... } } SML document. Only a broken document or a wrong root is an error; invalid products are skipped with a warning so one typo never takes the whole shop down.

func (*Catalog) Product

func (c *Catalog) Product(id string) (Product, bool)

Product looks a product up by id.

func (*Catalog) Products

func (c *Catalog) Products() []Product

Products returns all valid products in catalog order.

type ConfirmPageData

type ConfirmPageData struct {
	Lang      string
	ID        string
	Title     string
	Quantity  int
	Currency  string
	Amount    int64
	CreatedAt time.Time
	Status    string
	Action    string // form target: the confirm link itself
	Done      bool   // just confirmed by this request
}

ConfirmPageData is the input of the seller's page to confirm a EUR bank transfer. Only someone with the secret link from the seller mail sees it.

func NewConfirmPageData

func NewConfirmPageData(o *Order, action, lang string, done bool) ConfirmPageData

NewConfirmPageData prepares the confirm page for order o.

type FormField

type FormField struct {
	config.ContactField
	Value string
}

FormField is a form field with its current value, for re-rendering.

type FormInput

type FormInput struct {
	Quantity string
	Values   map[string]string // field name -> submitted value
	Consent  bool              // digital products: immediate delivery accepted
}

FormInput is the raw order form submission.

type FormResult

type FormResult struct {
	Quantity   int
	Buyer      map[string]string
	BuyerEmail string
	Errors     []string
}

FormResult is the validated submission. Errors are user-facing texts in the requested language; if there are any, nothing else is meaningful.

func ValidateOrder

func ValidateOrder(p Product, fields []config.ContactField, in FormInput, lang string) FormResult

ValidateOrder checks an order form for product p. The price is not part of the form at all; only quantity and buyer data are taken from it.

type Indexer

type Indexer struct {
	URL    string
	Client *http.Client
}

Indexer queries a Duniter v2 GraphQL indexer (duniter-squid).

func NewIndexer

func NewIndexer(url string) *Indexer

NewIndexer returns a client with a 10 s timeout.

func (*Indexer) FirstBlockSince

func (ix *Indexer) FirstBlockSince(ctx context.Context, wallet string, since time.Time) (int64, error)

FirstBlockSince returns the block of the first transfer to wallet at or after since, or 0 if there is none.

func (*Indexer) Head

func (ix *Indexer) Head(ctx context.Context) (int64, error)

Head returns the highest block the indexer has processed.

func (*Indexer) Identity

func (ix *Indexer) Identity(ctx context.Context, wallet string) (name string, member bool, err error)

Identity returns the Web of Trust identity linked to wallet: its name and whether it is a certified member. A plain wallet without identity gives "", false and no error.

func (*Indexer) Transfers

func (ix *Indexer) Transfers(ctx context.Context, wallet string, from, to int64) ([]Transfer, error)

Transfers returns all transfers to wallet in blocks (from, to], oldest first, following the indexer's pagination.

func (*Indexer) TransfersToAny

func (ix *Indexer) TransfersToAny(ctx context.Context, wallets []string, from, to int64) ([]Transfer, error)

TransfersToAny returns all transfers to any of wallets in blocks (from, to], oldest first (the market watches many vendor wallets).

type Legal struct {
	Terms, Withdrawal, Privacy string
	TermsHTML, WithdrawalHTML  template.HTML // trusted: compiled site content
}

Legal holds the site's legal pages: links for the order form and the buyer's order mail, and for the mail also the pages' HTML (Terms and Withdrawal), the contract confirmation on a durable medium. Links are site paths in the form and absolute URLs in the mail.

type Limiter

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

Limiter allows at most max events per key within window (sliding).

func NewLimiter

func NewLimiter(max int, window time.Duration) *Limiter

NewLimiter returns a limiter for max events per window and key.

func (*Limiter) Allow

func (l *Limiter) Allow(key string) bool

Allow records an event for key and reports whether it is within the limit.

type Mail

type Mail struct {
	Subject string
	HTML    string
}

Mail is a rendered email.

func BuyerOrderMail

func BuyerOrderMail(o *Order, to PayTo, payURL, siteName string, legal Legal) (Mail, error)

BuyerOrderMail is sent to the buyer right after ordering: how to pay, and as the contract confirmation the consent to immediate delivery (digital products) and the site's legal pages.

func DonationMail

func DonationMail(t Transfer, lang string) (Mail, error)

DonationMail tells the seller about a donation.

func PaidBuyerMail

func PaidBuyerMail(o *Order, downloadURL, siteName string) (Mail, error)

PaidBuyerMail confirms the payment to the buyer. For digital orders downloadURL (with the one-time token) and the license key are included.

func PaidSellerMail

func PaidSellerMail(o *Order, fields []config.ContactField, lang string) (Mail, error)

PaidSellerMail tells the seller that an order is paid, in language lang.

func SellerOrderMail

func SellerOrderMail(o *Order, fields []config.ContactField, payURL, confirmURL, lang string) (Mail, error)

SellerOrderMail notifies the seller of a new (unpaid) order, in the site's default language lang. For EUR orders confirmURL is the secret link to confirm the bank transfer.

func UnassignedMail

func UnassignedMail(t Transfer, reason, lang string) (Mail, error)

UnassignedMail tells the seller about a transfer the watcher could not match to an open order.

type Order

type Order struct {
	ID        string
	ProductID string
	Title     string
	Digital   bool
	Currency  string
	UnitPrice int64
	Quantity  int
	Amount    int64
	Lang      string
	Buyer     map[string]string
	CreatedAt time.Time
	ExpiresAt time.Time
	Status    string
	PaidAt    *time.Time
	Late      bool
	Payments  []Payment

	// DigitalConsent records that the buyer agreed in the order form to
	// immediate delivery and the loss of the right of withdrawal (§ 356
	// Abs. 5 BGB); the order mail confirms it.
	DigitalConsent bool

	// Digital delivery (see delivery.go). Only the token's hash is stored.
	LicenseKey        string
	DownloadTokenHash string
	DownloadExpiresAt *time.Time
	Downloads         int

	// Fulfilment (delivery + paid mails) after payment; retried by the
	// watcher until it succeeds or MaxFulfilAttempts is reached.
	FulfilledAt    *time.Time
	FulfilAttempts int

	// EUR orders: the seller confirms the bank transfer with a secret link
	// from the order mail. Only the token's SHA-256 is stored.
	ConfirmTokenHash string
	ConfirmedBy      string // "seller" once confirmed by hand

	// Stripe orders (Method MethodStripe): the Checkout Session and its
	// payment page URL (to resume an abandoned checkout).
	Method        string
	StripeSession string
	StripeURL     string
	PaymentIntent string
}

Order is one order, stored as SML in <dir>/<ID>.sml. Amounts are in centimes of Currency (Ğ1 centimes or euro cents).

func (*Order) Card

func (o *Order) Card() bool

Card reports whether the order is paid through Stripe.

func (*Order) CheckConfirmToken

func (o *Order) CheckConfirmToken(token string) error

CheckConfirmToken reports ErrNotFound for anything but a EUR order with exactly this confirm token, so the confirm page reveals nothing to someone who only knows the order ID.

func (*Order) CheckDownload

func (o *Order) CheckDownload(token string, now time.Time) error

CheckDownload verifies token for o at time now: ErrNotFound for a wrong token or an order without delivery, ErrDownloadExpired/ErrDownloadUsedUp for a valid token that can no longer be used.

func (*Order) Eur

func (o *Order) Eur() bool

Eur reports whether the order is paid by euro bank transfer.

func (*Order) HasTransfer

func (o *Order) HasTransfer(transferID string) bool

HasTransfer reports whether a transfer was already counted.

func (*Order) Received

func (o *Order) Received() int64

Received sums all payments counted towards the order.

func (*Order) StatusAt

func (o *Order) StatusAt(now time.Time) string

StatusAt returns the status as shown to buyers at time now.

type OrderFormData

type OrderFormData struct {
	Lang       string
	ProductID  string
	Title      string
	Text       string
	Image      string // product image as given in the catalog; the server resolves it to a URL
	Prices     map[string]int64
	Currencies []string // payable currencies, Ğ1 first
	Currency   string   // pre-selected currency
	Digital    bool
	Orderable  bool
	Quantity   int
	Fields     []FormField
	Errors     []string
	Legal      Legal // set by the server
}

OrderFormData is the input of the order form page.

func NewOrderFormData

func NewOrderFormData(p Product, fields []config.ContactField, orderable bool, pay Payments, lang string, quantity int, currency string, values map[string]string, errors []string) OrderFormData

NewOrderFormData prepares the form for product p; values/errors come from a rejected submission (both may be nil). currency is the pre-selected payment currency ("" = the first one available).

type PayPageData

type PayPageData struct {
	Lang      string
	ID        string
	Title     string
	Quantity  int
	Digital   bool
	Status    string // open, paid, expired
	Currency  string
	Due       int64 // still to pay, in centimes of Currency
	To        PayTo
	ExpiresAt time.Time
	Card      bool   // paid through Stripe
	StripeURL string // resume an abandoned checkout
	Cancelled bool   // back from Stripe with "cancel"
}

PayPageData is the input of the payment page.

func NewPayPageData

func NewPayPageData(o *Order, to PayTo, lang string, now time.Time) PayPageData

NewPayPageData prepares the payment page for order o at time now. It never includes buyer data: knowing an order ID reveals nothing personal.

type PayTo

type PayTo struct {
	Wallet        string
	IBAN          string
	BIC           string
	AccountHolder string
}

PayTo is where buyers send the money: the Ğ1 wallet, and for EUR orders the seller's bank account.

type Payment

type Payment struct {
	TransferID  string
	BlockNumber int64
	From        string
	Amount      int64
}

Payment is one Ğ1 transfer counted towards an order.

type Payments

type Payments struct {
	G1   bool // a Ğ1 wallet is configured
	EUR  bool // bank transfer (IBAN) is configured
	Card bool // Stripe is ready
}

Payments are the payment methods a shop offers.

type Product

type Product struct {
	ID       string
	Title    string
	Text     string
	Image    string
	Type     string
	Price    int64
	PriceEur int64
	Titles   map[string]string // title_<lang>
	Texts    map[string]string // text_<lang>
}

Product is one entry of a site's Catalog {}. Price (Ğ1 centimes) and PriceEur (euro cents) are the only prices the shop ever charges — never a value from a form. A price of 0 means "not sold in that currency".

func (Product) Digital

func (p Product) Digital() bool

Digital reports whether the product is delivered as a download.

func (Product) LocalText

func (p Product) LocalText(lang string) string

LocalText returns the text for lang, falling back to the default text.

func (Product) LocalTitle

func (p Product) LocalTitle(lang string) string

LocalTitle returns the title for lang, falling back to the default title.

func (Product) PriceIn

func (p Product) PriceIn(currency string) int64

PriceIn returns the price in currency (CurrencyG1 or CurrencyEUR), 0 if the product is not sold in it.

type Store

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

Store keeps orders as one SML file each (mode 0600) in a single directory. Writes are atomic (temp file + rename) and serialised by a mutex; one forgecms process owns a store directory.

func NewStore

func NewStore(dir string) (*Store, error)

NewStore opens (and creates, mode 0700) the order directory.

func (*Store) Create

func (s *Store) Create(p Product, currency string, quantity int, buyer map[string]string, lang string, ttl time.Duration) (*Order, error)

Create stores a new open order for quantity × product, paid in currency. The price comes from the product (the catalog), never from the caller's form data.

func (*Store) Get

func (s *Store) Get(id string) (*Order, error)

Get loads one order.

func (*Store) PendingFulfilment

func (s *Store) PendingFulfilment() ([]*Order, error)

PendingFulfilment returns paid orders whose fulfilment has not succeeded yet and may still be retried.

func (*Store) Unpaid

func (s *Store) Unpaid() ([]*Order, error)

Unpaid returns all Ğ1 orders with status open, expired ones included (they can still be paid late), oldest first. EUR orders are left out: the Ğ1 watcher has nothing to do with them. Unreadable files are skipped with a warning.

func (*Store) Update

func (s *Store) Update(id string, fn func(*Order) error) (*Order, error)

Update loads an order, applies fn and writes the result atomically. If fn returns an error nothing is written.

type Transfer

type Transfer struct {
	ID          string
	BlockNumber int64
	Timestamp   time.Time
	Amount      int64 // centimes
	From        string
	To          string
	Comment     string
}

Transfer is one incoming Ğ1 transfer as reported by the indexer.

type Watcher

type Watcher struct {
	Store         *Store
	Indexer       *Indexer
	Wallet        string
	Confirmations int
	StatePath     string        // SML file holding the last processed block
	Interval      time.Duration // normal polling interval
	MaxBackoff    time.Duration // longest wait after repeated errors

	// OnPaid is called after an order became paid, and again for paid
	// orders whose fulfilment failed earlier (see Store.PendingFulfilment).
	OnPaid func(orderID string) error
	// OnUnassigned is called for a transfer to the wallet that matches no
	// open order (missing or wrong order ID, or a payment for an order that
	// was already paid).
	OnUnassigned func(t Transfer, reason string)
	// DonationKeywords mark a transfer without order number as a donation;
	// OnDonation is then called instead of OnUnassigned.
	DonationKeywords []string
	OnDonation       func(t Transfer)
	// Ignore reports whether a transfer without a shop order number belongs
	// to another module on the same wallet (e.g. a market order "MK-…");
	// such transfers are skipped without a warning or a mail.
	Ignore func(t Transfer) bool
	// contains filtered or unexported fields
}

Watcher polls the Ğ1 indexer for transfers to the shop wallet, matches them to orders by the order ID in the transfer comment and marks orders paid. It never moves money and holds no keys: it only reads.

func (*Watcher) Run

func (w *Watcher) Run(ctx context.Context)

Run polls until ctx is cancelled. Errors are logged and retried with exponential backoff up to MaxBackoff; they never mark anything.

func (*Watcher) Tick

func (w *Watcher) Tick(ctx context.Context) error

Tick runs one polling round.

Jump to

Keyboard shortcuts

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