Documentation
¶
Overview ¶
Package shop implements the Ğ1 shop module (see CWUP/tasks/g1_shop.md).
Index ¶
- Constants
- Variables
- func ConfirmPayment(o *Order, token string, now time.Time) error
- func Currencies(p Product, pay Payments) []string
- func EmailField(fields []config.ContactField) string
- func FormatPrices(p Product, currencies []string) string
- func IsDonation(comment string, keywords []string) bool
- func IssueConfirmToken(o *Order) (string, error)
- func IssueDelivery(o *Order, now time.Time) (string, error)
- func OrderIDsInComment(comment string) []string
- func PriceCurrencies(currencies []string) []string
- func RenderConfirmPage(d ConfirmPageData) (template.HTML, error)
- func RenderDownloadProblem(lang, message string) (template.HTML, error)
- func RenderOrderForm(d OrderFormData) (template.HTML, error)
- func RenderPayPage(d PayPageData) (template.HTML, error)
- func ResolveDeliveryFile(baseDir, rel string) (string, error)
- func T(lang, key string) string
- func ValidDownloadToken(t string) bool
- func ValidOrderID(id string) bool
- func VisibleFields(p Product, fields []config.ContactField) []config.ContactField
- type Catalog
- type ConfirmPageData
- type FormField
- type FormInput
- type FormResult
- type Indexer
- func (ix *Indexer) FirstBlockSince(ctx context.Context, wallet string, since time.Time) (int64, error)
- func (ix *Indexer) Head(ctx context.Context) (int64, error)
- func (ix *Indexer) Identity(ctx context.Context, wallet string) (name string, member bool, err error)
- func (ix *Indexer) Transfers(ctx context.Context, wallet string, from, to int64) ([]Transfer, error)
- func (ix *Indexer) TransfersToAny(ctx context.Context, wallets []string, from, to int64) ([]Transfer, error)
- type Legal
- type Limiter
- type Mail
- func BuyerOrderMail(o *Order, to PayTo, payURL, siteName string, legal Legal) (Mail, error)
- func DonationMail(t Transfer, lang string) (Mail, error)
- func PaidBuyerMail(o *Order, downloadURL, siteName string) (Mail, error)
- func PaidSellerMail(o *Order, fields []config.ContactField, lang string) (Mail, error)
- func SellerOrderMail(o *Order, fields []config.ContactField, payURL, confirmURL, lang string) (Mail, error)
- func UnassignedMail(t Transfer, reason, lang string) (Mail, error)
- type Order
- func (o *Order) Card() bool
- func (o *Order) CheckConfirmToken(token string) error
- func (o *Order) CheckDownload(token string, now time.Time) error
- func (o *Order) Eur() bool
- func (o *Order) HasTransfer(transferID string) bool
- func (o *Order) Received() int64
- func (o *Order) StatusAt(now time.Time) string
- type OrderFormData
- type PayPageData
- type PayTo
- type Payment
- type Payments
- type Product
- type Store
- func (s *Store) Create(p Product, currency string, quantity int, buyer map[string]string, lang string, ...) (*Order, error)
- func (s *Store) Get(id string) (*Order, error)
- func (s *Store) PendingFulfilment() ([]*Order, error)
- func (s *Store) Unpaid() ([]*Order, error)
- func (s *Store) Update(id string, fn func(*Order) error) (*Order, error)
- type Transfer
- type Watcher
Constants ¶
const ( TypePhysical = "physical" TypeDigital = "digital" )
Product types.
const ( DownloadLimit = 5 DownloadValidity = 30 * 24 * time.Hour )
Download rules for digital products.
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).
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.
const HoneypotField = "website"
HoneypotField is a form field hidden from people; bots that fill it in are ignored.
const MaxFulfilAttempts = 5
MaxFulfilAttempts limits automatic fulfilment retries of one order.
const MaxQuantity = 99
MaxQuantity caps the quantity of one order.
const MethodStripe = "stripe"
MethodStripe marks EUR orders paid through Stripe Checkout (instead of a bank transfer).
Variables ¶
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.
var ErrAlreadyPaid = errors.New("order already paid")
ErrAlreadyPaid is returned when a paid order is confirmed again.
var ErrNotFound = errors.New("order not found")
ErrNotFound is returned for unknown or malformed order IDs.
Functions ¶
func ConfirmPayment ¶
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 ¶
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 ¶
FormatPrices renders all prices of p for the given currencies, e.g. "12.50 Ğ1 / 9.90 EUR".
func IsDonation ¶
IsDonation reports whether comment contains one of keywords as a whole word, ignoring case.
func IssueConfirmToken ¶
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 ¶
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 ¶
OrderIDsInComment returns the normalised order IDs found in a comment.
func PriceCurrencies ¶
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 ¶
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 ¶
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 ValidDownloadToken ¶
ValidDownloadToken reports whether t has the download token format.
func ValidOrderID ¶
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 ¶
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.
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 ¶
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 ¶
Indexer queries a Duniter v2 GraphQL indexer (duniter-squid).
func NewIndexer ¶
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) 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.
type Legal ¶
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 ¶
NewLimiter returns a limiter for max events per window and key.
type Mail ¶
Mail is a rendered email.
func BuyerOrderMail ¶
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 ¶
DonationMail tells the seller about a donation.
func PaidBuyerMail ¶
PaidBuyerMail confirms the payment to the buyer. For digital orders downloadURL (with the one-time token) and the license key are included.
func PaidSellerMail ¶
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.
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) CheckConfirmToken ¶
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 ¶
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) HasTransfer ¶
HasTransfer reports whether a transfer was already counted.
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 ¶
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 ¶
PayTo is where buyers send the money: the Ğ1 wallet, and for EUR orders the seller's bank account.
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) LocalTitle ¶
LocalTitle returns the title for lang, falling back to the default title.
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 (*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) PendingFulfilment ¶
PendingFulfilment returns paid orders whose fulfilment has not succeeded yet and may still be retried.
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.