billing

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 35 Imported by: 0

README

Arandu

Arandu Billing

Billing management for an Arandu application: a catalogue of plans and coupons, the subscriptions of each account and the date each one is paid until, and the invoices a payment gateway collects -- with the admin's screens and the customer's, in English and Brazilian Portuguese.

It ships no payment gateway. The application implements the Provider interface as a service of its own, over its gateway's client and its own merchant account, and hands it to New. The package asks it for a checkout page, believes a notification only after asking it again, and confirms each invoice once. Balances are not kept here: a plan that sells credits deposits them in arandu-wallet through the optional walletcredit listener.

Install

go get github.com/hyz-is/arandu-billing@v0.1.0

Wire it

An Arandu application registers a module explicitly, in bootstrap/app.go. These are the lines, and there are no others.

The imports:

import (
	billing "github.com/hyz-is/arandu-billing"

	"your/module/path/app/Services/payments"
)

The construction, in Build, after the session store, the activity log and the gateway service exist and before k.Register:

	gateway, err := payments.NewCheckout(cfg.Payments) // the application's own Provider
	if err != nil {
		return App{}, err
	}
	billingModule, err := billing.New(billing.Config{
		Prefix:      "/painel",
		AdminPrefix: "/admin/cobranca",
		Paths:       billing.PortuguesePaths,
		Providers:   []billing.Provider{gateway, billing.ManualProvider{Instructions: cfg.PixInstructions}},
		PublicURL:   cfg.App.URL,
		Locale:      "pt-BR",
		Activity:    activityModule.Logger(),
		Listener:    onBilling, // optional: the application's reaction to each event
		Customer:    customerOf, // optional: who pays, for the gateway's page
		Middleware:  []func(http.Handler) http.Handler{permissionModule.Roles()},
	}, db, sessions)
	if err != nil {
		return App{}, err
	}

And the registration, inside the k.Register(...) call already there:

		billingModule,

Then, once, before the application serves:

aru migrate
aru vendor:publish --tag=view --apply
aru view:build

and import the compiled views beside the other imports:

	_ "your/module/path/storage/framework/views/modules/billing"
	_ "your/module/path/storage/framework/views/modules/billing/admin"

Without them the module refuses to boot, and the refusal names the views, the command and the imports. An application that mounts the account's routes in its customer panel and the admin's in its operator console, each with its own guards, calls billingModule.AccountRoutes(panel), billingModule.AdminRoutes(console) and billingModule.NotificationRoutes(api) instead of registering the module's Routes whole.

Implement a Provider

A gateway is four methods, written in the application:

// app/Services/payments/checkout.go
type Checkout struct{ client *gatewayclient.Client }

func (c *Checkout) Name() string { return "gateway" } // the last segment of its notification address

// CreateCheckout asks the gateway for a payment page for one invoice.
func (c *Checkout) CreateCheckout(ctx context.Context, req billing.CheckoutRequest) (billing.Checkout, error) {
	order, err := c.client.CreateOrder(ctx, gatewayclient.Order{
		Number: req.InvoiceID, Description: req.Description, Amount: req.Total,
		MaxInstallments: req.MaxInstallments, ReturnURL: req.ReturnURL,
	})
	if err != nil {
		return billing.Checkout{}, err
	}
	return billing.Checkout{URL: order.PaymentURL, Reference: order.ID}, nil
}

// ParseNotification reads what the gateway posted. Nothing in it is trusted:
// it only names the order.
func (c *Checkout) ParseNotification(r *http.Request) (billing.Notification, error) {
	if err := r.ParseForm(); err != nil || r.PostForm.Get("order_number") == "" {
		return billing.Notification{}, billing.ErrBadNotification
	}
	return billing.Notification{InvoiceID: r.PostForm.Get("order_number"), Reference: r.PostForm.Get("checkout_id")}, nil
}

// QueryStatus asks the gateway itself where the payment stands.
func (c *Checkout) QueryStatus(ctx context.Context, q billing.StatusQuery) (billing.PaymentStatus, error) {
	p, err := c.client.Payment(ctx, q.InvoiceID)
	if err != nil {
		return billing.PaymentStatus{}, err
	}
	state := billing.StatePending
	switch {
	case p.Paid:
		state = billing.StatePaid
	case p.Denied:
		state = billing.StateFailed
	}
	return billing.PaymentStatus{State: state, Amount: p.Amount, Method: p.Method,
		Installments: p.Installments, Reference: p.ID, PaidAt: p.PaidAt, Raw: p.Status}, nil
}

What the package does with the answers is the contract:

  • CreateCheckout is called once per invoice, after the invoice is saved, with the amount computed here from the catalogue. The customer is sent to Checkout.URL; an empty URL shows the invoice page, where a provider that implements PaymentInstructions() string tells the customer how to pay.
  • ParseNotification runs on POST NotificationPrefix + "/" + Name(), with no session and no CSRF token. Its answer only names the invoice (by InvoiceID, the order number the checkout was given, or by the gateway's Reference); a request it does not understand wraps ErrBadNotification and the address answers 400.
  • QueryStatus is asked before anything is confirmed. Only StatePaid with Amount equal to the invoice's total confirms it; another amount answers 409 and is kept on the invoice for the admin. StateFailed marks the invoice failed.
  • Confirmation is idempotent: the invoice is claimed by a conditional update, and the unique invoice_id of the payments holds the same line in the database, so one invoice is paid once however many notifications arrive, in whatever order, racing or not. A repeated notification answers 200.

The customer's return address (PublicURL + /faturas/{id}/retorno with the Portuguese paths) asks the gateway again too, so a payment counts even before the notification arrives.

ManualProvider is the gateway-free one: no page and no notification; the invoice page shows its Instructions and the admin confirms the payment on the admin's invoices screen. For tests, billingtest.New("fake") is an in-memory gateway: Pay, Fail and Refund say what happened, and Notification builds the post.

Configuration

field required meaning
Providers yes the gateways, the application's own; the first is the default
DefaultProvider no the Name of the provider a checkout uses
Prefix no where the account's routes are mounted. Defaults to /billing
AdminPrefix no where the admin's routes are mounted. Defaults to Prefix + /admin
Paths no the segments of every route; PortuguesePaths is the Brazilian set
NotificationPrefix no where the gateways post. Defaults to /api/billing/notifications
PageSize no rows per page, 25 by default, refused above 200
Listener no told about each event, inside the act's transaction
Customer no who pays, for the gateway's page
PublicURL no the application's address, for the return address
Location no the timezone dates are shown in. Defaults to America/Sao_Paulo
Activity no arandu-activitylog's logger: every act is recorded under its Grant
Translator, Locale, TitleSeparator no the sentences and the document title
Middleware, AdminMiddleware, Chrome no the application's guards and layout
Clock no the time, for a test that holds it still

There is no tenant to set and there are no prices to set: the tenant of every statement is the one on the Grant, and every number a business person changes is a plan's or a coupon's row, written by the application's seeder or on the admin's screen.

Routes

With PortuguesePaths, the account's side under Prefix:

method path name
GET /planos billing.plans.index
POST /planos/{id}/assinar billing.plans.checkout
POST /planos/{id}/teste-gratis billing.plans.trial
GET /assinaturas billing.subscriptions.index
POST /assinaturas/{id}/renovacao billing.subscriptions.renew
POST /assinaturas/{id}/cancelamento billing.subscriptions.cancel
DELETE /assinaturas/{id}/cancelamento billing.subscriptions.resume
GET /faturas billing.invoices.index
GET /faturas/{id} billing.invoices.show
GET /faturas/{id}/retorno billing.invoices.return

the admin's under AdminPrefix: GET/POST /planos, GET/POST /planos/{id}, GET/POST /cupons, POST /cupons/{id}, GET /assinaturas, POST /assinaturas/{id}/cancelamento, GET /faturas, POST /faturas/{id}/pagamento and POST /faturas/{id}/cancelamento; and POST NotificationPrefix/{provider}, billing.notifications.

Every route but the notification sits behind RequireAuth: a visitor with no session is sent to /auth/login (or wherever the application's guard sends one), and a handler reads who is asking with ctx.User(). A client that asks for JSON gets JSON from every route.

Who may do what

subject how the application says so may
a member of an account signed in to that account read the plans, the account's subscriptions and invoices
the account's manager billing.AccountRole, or the action billing.account through arandu-permission pay for a plan, start a trial, renew, cancel at the period's end
the platform's admin billing.AdminRole, or the action billing.admin keep the plans and coupons, read every account's subscriptions and invoices, confirm a payment by hand, void an invoice, cancel a subscription at once

A subject inside somebody else's account through arandu-impersonate is never the platform's admin there: it acts as the account. A gateway's notification and the clock's sweep run as this package's own system subject, inside the invoice's or the subscription's own account.

The rules

  • Price. A plan's Price is in centavos and buys IntervalMonths. A percent coupon takes Value basis points off, rounded down to the centavo; a fixed one takes Value centavos, never more than the price. A coupon is refused when it is inactive, not yet valid, expired, out of uses, for another plan or above the price (MinPurchase). A price taken to zero is confirmed at once, with no gateway.
  • Recurring coupons. Renewals is how many renewals after the first payment keep the discount; a renewal keeps it even if the coupon was deactivated afterwards. MaxUses counts first payments.
  • Installments. A plan offers installments from InstallmentsFrom months on, one per month of the period, never above InstallmentsCap or 12; every checkout tells the gateway its MaxInstallments.
  • Periods. A first payment buys [paid, paid + months); an early renewal is added to the day already paid until; a payment during the grace (GraceDays) extends from the day the period ended; a subscription that ended starts again on the day it is paid. One month after January 31 is the last day of February.
  • The clock. Schedule runs SweepDue every fifteen minutes: a period that ended goes past due inside the grace and expires after it; a subscription whose cancellation was asked for is canceled at the end of its period; a trial that ended without a payment expires.

Events

Config.Listener is told, inside the transaction of the act, about subscription.trial_started, invoice.paid, subscription.activated, subscription.renewed, subscription.past_due, subscription.expired and subscription.canceled. Each Event carries the subscription, the plan with its Meta, the invoice when there is one, and the Grant scoped to the account. A listener's error rolls the act back, and a gateway's notification is then answered with an error and sent again.

A plan that sells credits writes wallet_slug and wallet_amount in its Meta, and the application wraps its listener:

	Listener: walletcredit.Listener(walletModule.Service(), walletcredit.Options{Next: onBilling}),

The deposit runs as the wallet's operator of the invoice's own account, under the idempotency key billing:invoice:<id>.

From the application's own code

billingModule.Service() is the use cases, each asking the policy: ServingSubscriptions(ctx, who) is what a screen asks before opening what a plan pays for; SubscriptionsOf(ctx, g) answers the same for a Grant the application's own policy issued for an account (a job, a sync); Subscribe(ctx, who, billing.SubscribeRequest{PlanID, Reference: "camera:42"}) starts a checkout for something inside the account, named by the application.

The data path

Each entity embeds model.Model, and its table is declared once in model.go: planTable, couponTable, subscriptionTable, invoiceTable, paymentTable and couponUsageTable. aru model:build generates Plans(db) and its PlanQuery into PlanQuery.go, and the same for the others; the files are committed, never edited by hand, and aru model:build --check fails when one is stale. BillingService owns the *data.DB and follows validate -> security.Authorize -> Grant -> Model terminal; handlers never hold the database. The lists of every account read internal/everytenant, Global read models no application can import, after the policy allowed the admin.

Migrations

20261023_0001_create_billing_plans, 20261023_0002_create_billing_coupons, 20261023_0003_create_billing_subscriptions, 20261023_0004_create_billing_invoices, 20261023_0005_create_billing_payments and 20261023_0006_create_billing_coupon_usages, applied by aru migrate, never at boot.

Tests

GOWORK=off go test -race -p 2 ./...
ARANDU_TEST_POSTGRES_DSN="postgres://localhost:5432/arandu_billing_test?sslmode=disable" GOWORK=off go test -race -p 2 ./tests/Feature/

Licence

MIT. See LICENSE.md. Copyright Paulo R. Lima.

Documentation

Overview

Package billing is an Arandu module for billing management: a catalogue of plans and coupons, the subscriptions of each account and the date each one is paid until, and the invoices a payment gateway collects.

It ships no gateway. An application implements Provider as a service of its own -- over its gateway's client and its own merchant account -- and hands it to New; the package asks it for a checkout page, believes a notification only after asking it again, and confirms each invoice once. Balances are not kept here: an application that turns a payment into credits deposits them in arandu-wallet from its Listener.

The files are laid out by role rather than by layer:

module.go         -> registration, routes, handlers and migrations
notifications.go  -> the gateways' notification address
config.go         -> what the application passes in
paths.go          -> the addresses, and the route table
model.go          -> the entities, and their own rules
pricing.go        -> what a period costs, and what the clock does to it
provider.go       -> the gateway contract, and the gateway-free provider
policy.go         -> who may do what
*_service.go      -> the use cases, and Model access after authorization
listing.go        -> the server-side pages the data tables read
views.go          -> the files the application takes ownership of

An application registers it explicitly. There is no service provider, no container and no discovery.

Index

Constants

View Source
const (
	// DefaultPrefix is where the account's routes are mounted when Config
	// leaves Prefix empty.
	DefaultPrefix = "/billing"
	// DefaultNotificationPrefix is where the gateways post their
	// notifications when Config leaves NotificationPrefix empty: one address
	// per provider, NotificationPrefix + "/" + Provider.Name().
	DefaultNotificationPrefix = "/api/billing/notifications"
	// DefaultPageSize is how many records one page answers with when Config
	// leaves PageSize at zero.
	DefaultPageSize = 25
	// MaxPageSize is the ceiling PageSize is refused above.
	MaxPageSize = 200
	// DefaultLocation is the timezone dates are shown in when Config leaves
	// Location nil.
	DefaultLocation = "America/Sao_Paulo"
)

The defaults for the optional settings. They are constants rather than literals inside Config.withDefaults, so the value a reader finds here is the value the package uses.

View Source
const (
	// PlansView is reading the active plans of the catalogue.
	PlansView security.Action = "billing.plans.view"
	// PlansManage is keeping the catalogue's plans: the platform's admin.
	PlansManage security.Action = "billing.plans.manage"
	// CouponsManage is keeping the coupons: the platform's admin.
	CouponsManage security.Action = "billing.coupons.manage"
	// Subscribe is an account paying for a plan or starting its trial.
	Subscribe security.Action = "billing.subscribe"
	// SubscriptionsView is an account reading its own subscriptions.
	SubscriptionsView security.Action = "billing.subscriptions.view"
	// SubscriptionsCancel is an account asking its own subscription to stop at
	// the end of the period, or taking that back.
	SubscriptionsCancel security.Action = "billing.subscriptions.cancel"
	// SubscriptionsManage is the platform's admin reading every account's
	// subscriptions and canceling one at once.
	SubscriptionsManage security.Action = "billing.subscriptions.manage"
	// InvoicesView is an account reading its own invoices and paying one.
	InvoicesView security.Action = "billing.invoices.view"
	// InvoicesManage is the platform's admin reading every account's invoices,
	// confirming a payment by hand and canceling an open invoice.
	InvoicesManage security.Action = "billing.invoices.manage"
	// PaymentsConfirm is confirming a payment a gateway reported. It is
	// answered for this package's own system subject alone, after the gateway
	// was asked again.
	PaymentsConfirm security.Action = "billing.payments.confirm"
	// SubscriptionsSweep is moving the subscriptions whose period ended. It is
	// answered for this package's own system subject alone.
	SubscriptionsSweep security.Action = "billing.subscriptions.sweep"
	// AdminAction is being this package's admin, held as an action: what an
	// application whose permissions arandu-permission administers puts in a
	// group. It opens what AdminRole opens, and nothing more.
	AdminAction security.Action = "billing.admin"
	// AccountAction is managing an account's billing, held as an action. It
	// opens what AccountRole opens, and nothing more.
	AccountAction security.Action = "billing.account"
)

The actions of this package. Constants rather than strings at the call site: a typo in an action name would silently authorize nothing, or worse, everything.

View Source
const (
	// TranslationGroup is the file every key of this package lives in, and the
	// prefix of every key: "billing.screen.plans_title".
	TranslationGroup = "billing"
	// FallbackLocale answers a request that negotiated no locale, when
	// Config.Locale names none either, and every line a locale does not have.
	// It is English, as in the other hyz-is modules; an application that
	// speaks one language sets Config.Locale.
	FallbackLocale = "en"
)
View Source
const (
	ViewPlans              = "modules.billing.plans"
	ViewSubscriptions      = "modules.billing.subscriptions"
	ViewInvoices           = "modules.billing.invoices"
	ViewInvoice            = "modules.billing.invoice"
	ViewAdminPlans         = "modules.billing.admin.plans"
	ViewAdminPlan          = "modules.billing.admin.plan"
	ViewAdminCoupons       = "modules.billing.admin.coupons"
	ViewAdminSubscriptions = "modules.billing.admin.subscriptions"
	ViewAdminInvoices      = "modules.billing.admin.invoices"
)

The screens this package renders, by the name their path gives them.

View Source
const AccountRole = "billing.account"

AccountRole is the role an application grants, inside an account, to whoever may pay for it and cancel it: the account's owner, its finance. Any member of the account reads its plans, subscriptions and invoices without it.

View Source
const ActivityLogName = "billing"

ActivityLogName is the log every entry of this package is recorded in.

View Source
const AdminRole = "billing.admin"

AdminRole is the role an application grants to whoever runs the platform's billing: the catalogue, the coupons, and every account's subscriptions and invoices. It is the platform's team, not any customer's staff.

View Source
const ManualProviderName = "manual"

ManualProviderName is the name of ManualProvider, and of the payments the admin confirms by hand.

View Source
const MaxInstallments = 12

MaxInstallments is the most installments any plan may offer.

View Source
const MaxIntervalMonths = 120

MaxIntervalMonths is the longest period one payment may buy.

View Source
const PublishCommand = "aru vendor:publish --apply"

PublishCommand is what an application runs to take ownership of the views this package offers.

Variables

View Source
var (
	ErrCouponInactive    = errors.New("billing: the coupon is not active")
	ErrCouponNotStarted  = errors.New("billing: the coupon is not valid yet")
	ErrCouponExpired     = errors.New("billing: the coupon has expired")
	ErrCouponExhausted   = errors.New("billing: the coupon has no uses left")
	ErrCouponWrongPlan   = errors.New("billing: the coupon does not apply to this plan")
	ErrCouponMinPurchase = errors.New("billing: the price is below the coupon's minimum purchase")
)

The reasons a coupon is refused. Each one is a sentence of the catalogue ("validation.coupon_expired"), so a screen says why in the customer's language; the service turns them into validation.Errors on the field "coupon".

View Source
var DefaultPaths = Paths{
	Plans: "/plans", Checkout: "/checkout", Trial: "/trial", Subscriptions: "/subscriptions",
	Renewal: "/renewal", Cancellation: "/cancellation", Invoices: "/invoices", Return: "/return",
	Admin: "/admin", Coupons: "/coupons", Payment: "/payment",
}

DefaultPaths are the English segments.

View Source
var ErrAmountMismatch = errors.New("billing: the amount paid is not the invoice's total")

ErrAmountMismatch is the refusal of a payment whose amount is not the invoice's Total: nothing is confirmed, and the gateway's answer is kept on the invoice for the admin.

View Source
var ErrBadNotification = errors.New("billing: the request is not a notification this provider understands")

ErrBadNotification is what a Provider wraps when a posted request is not a notification it understands.

View Source
var ErrNotFound = fmt.Errorf("billing: record not found: %w", model.ErrModelNotFound)

ErrNotFound is the answer for a record that is not there, or that belongs to another tenant: the two are one answer, so a probe learns nothing. It wraps model.ErrModelNotFound, which the router answers with 404.

InvoiceStatuses are every status, in the order a screen lists them.

View Source
var PortuguesePaths = Paths{
	Plans: "/planos", Checkout: "/assinar", Trial: "/teste-gratis", Subscriptions: "/assinaturas",
	Renewal: "/renovacao", Cancellation: "/cancelamento", Invoices: "/faturas", Return: "/retorno",
	Admin: "/admin", Coupons: "/cupons", Payment: "/pagamento",
}

PortuguesePaths are the segments in Brazilian Portuguese, for an application whose addresses are written in it: /planos/{id}/assinar, /assinaturas/{id}/cancelamento, /faturas/{id}/retorno, and the admin's /cupons and /faturas/{id}/pagamento.

SubscriptionStatuses are every status, in the order a screen lists them.

Functions

func AddMonths

func AddMonths(t time.Time, n int) time.Time

AddMonths moves an instant n months on, keeping the time of day and holding the day of the month where the target month has it: January 31 plus one month is the last day of February, not March 3.

func CheckCoupon

func CheckCoupon(c Coupon, p Plan, at time.Time) error

CheckCoupon says whether a coupon may be used now on a plan, for a first payment.

func Code

func Code(raw string) string

Code normalizes a coupon code as it is stored and looked up: trimmed, upper case.

func DiscountOf

func DiscountOf(c Coupon, price int64) int64

DiscountOf is what a coupon takes off a price, in centavos: a percentage rounded down to the centavo, or a fixed amount, never more than the price and never less than zero.

func IsAccountManager

func IsAccountManager(s security.Subject) bool

IsAccountManager says whether the subject may pay for its account and cancel its subscriptions: it holds AccountRole, or AccountAction.

func IsAdmin

func IsAdmin(s security.Subject) bool

IsAdmin says whether the subject runs the platform's billing: it holds AdminRole, or AdminAction among the actions arandu-permission resolved for it. A subject inside somebody else's account is not, whatever it holds: an admin acting there acts as the account.

func Lines

func Lines(locale string) translation.Lines

Lines are the sentences this package ships for one locale, keyed the way a translator asks for them ("billing.validation.required"), and nil for a locale it does not ship. An application reads them to see what there is to override, or to check a catalogue of its own against them.

func Locales

func Locales() []string

Locales are the languages the package ships.

func PublishedPaths

func PublishedPaths() []string

PublishedPaths are the files in the archive, each relative to the root of the application, sorted.

func Slugify

func Slugify(slug, name string) string

Slugify is the slug a plan is stored under: the one given, or one derived from the name -- lower case ASCII letters and digits joined by "-".

func ViewNames

func ViewNames() []string

ViewNames are the names the published views are rendered by, sorted.

The name is the path under the view root with its separators turned into dots, which is what the view compiler writes into the registration call. It is derived from the same archive the publication carries, so a view that was renamed cannot keep an old name here.

func ViewPackages

func ViewPackages() []string

ViewPackages are the directories the compiled views land in, each relative to the root of the application, sorted and without repeats.

Importing one is what puts its views in the binary: a compiled view calls the registry from init(), and a package nothing imports is not linked at all. The import is named rather than written into bootstrap/app.go, because one line somebody reads beats a file that changed while they were not looking.

Types

type Account

type Account struct {
	// TenantID is the account's tenant, empty for the catalogue.
	TenantID string
}

Account is what the policy decides about: the account (the tenant) an act touches. The empty Account is the catalogue, which belongs to no account.

type AdminCouponsPageData

type AdminCouponsPageData struct {
	Screen
	Rows        []CouponRow
	Table       TableState
	StoreURL    string
	PlanOptions []components.SelectOption
}

AdminCouponsPageData is the coupons, for the admin.

type AdminInvoicesPageData

type AdminInvoicesPageData struct {
	Screen
	Rows  []InvoiceRow
	Table TableState
}

AdminInvoicesPageData is every account's invoices.

type AdminPlanPageData

type AdminPlanPageData struct {
	Screen
	Plan               PlanForm
	UpdateURL, BackURL string
}

AdminPlanPageData is one plan, with the form that changes it.

type AdminPlansPageData

type AdminPlansPageData struct {
	Screen
	Rows     []PlanRow
	Table    TableState
	StoreURL string
	// NewPlan is what the new plan's form starts with.
	NewPlan PlanForm
}

AdminPlansPageData is the catalogue, for the admin.

type AdminSubscriptionsPageData

type AdminSubscriptionsPageData struct {
	Screen
	Rows  []SubscriptionRow
	Table TableState
}

AdminSubscriptionsPageData is every account's subscriptions.

type BillingPolicy

type BillingPolicy struct{}

BillingPolicy is the only authority over who does what in this package.

It denies unless a rule below says otherwise, and the rules are written around three subjects: an account's member, who reads the account's own billing, and its manager, who pays for it; the platform's admin, who keeps the catalogue and acts on every account; and this package's own system subject, which confirms what a gateway reported and moves the periods the clock ended.

func (BillingPolicy) Can

Can decides whether the subject may perform the action on the account.

func (BillingPolicy) Writes

func (BillingPolicy) Writes(a security.Action) bool

Writes says which actions change something: every one but the three that read. A Grant issued to read cannot save.

type BillingService

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

BillingService orchestrates the use cases of this package: it validates the request, asks the policy for a Grant, applies the rules the entities and the pricing hold, and persists with that Grant.

It receives its collaborators through the constructor and the module's configuration. Everything a handler is allowed to do goes through here: the service is the only owner of the database handle, so the request layer cannot reach a Model before the policy has answered.

func NewBillingService

func NewBillingService(db *data.DB) *BillingService

NewBillingService wires the service over the application's database handle, with no provider and no listener: New wires the module's from its Config.

func (*BillingService) ActivePlans

func (s *BillingService) ActivePlans(ctx context.Context, actor security.Subject) ([]*Plan, error)

ActivePlans are the plans the catalogue offers, in their order: what an account reads before it subscribes.

func (*BillingService) AllInvoicesPage

func (s *BillingService) AllInvoicesPage(ctx context.Context, actor security.Subject, q PageQuery, perPage int) (Page[Invoice], error)

AllInvoicesPage is a page of every account's invoices, for the platform's admin. The rows are copies that hold no connection.

func (*BillingService) AllSubscriptionsPage

func (s *BillingService) AllSubscriptionsPage(ctx context.Context, actor security.Subject, q PageQuery, perPage int) (Page[Subscription], error)

AllSubscriptionsPage is a page of every account's subscriptions, for the platform's admin. The rows are copies that hold no connection.

func (*BillingService) CancelAtPeriodEnd

func (s *BillingService) CancelAtPeriodEnd(ctx context.Context, actor security.Subject, id string) (*Subscription, error)

CancelAtPeriodEnd asks one of the account's subscriptions to stop when the period it is paid for ends: it is served until then and not renewed.

func (*BillingService) CancelNow

func (s *BillingService) CancelNow(ctx context.Context, actor security.Subject, id string) (*Subscription, error)

CancelNow is the admin canceling one account's subscription at once.

func (*BillingService) ConfirmManually

func (s *BillingService) ConfirmManually(ctx context.Context, actor security.Subject, id string, in ManualPayment) (*Invoice, error)

ConfirmManually is the admin recording that one account's invoice was paid. It confirms exactly as a gateway's notification does: once.

func (*BillingService) CouponsPage

func (s *BillingService) CouponsPage(ctx context.Context, actor security.Subject, q PageQuery, perPage int) (Page[*Coupon], error)

CouponsPage is a page of the coupons, for the admin.

func (*BillingService) CreateCoupon

func (s *BillingService) CreateCoupon(ctx context.Context, actor security.Subject, in CouponRequest) (*Coupon, error)

CreateCoupon adds a coupon.

func (*BillingService) CreatePlan

func (s *BillingService) CreatePlan(ctx context.Context, actor security.Subject, in PlanRequest) (*Plan, error)

CreatePlan adds a plan to the catalogue.

func (*BillingService) HandleNotification

func (s *BillingService) HandleNotification(ctx context.Context, providerName string, r *http.Request) (*Invoice, error)

HandleNotification is what a gateway's post to its notification address does: the provider named reads the request, the invoice it names is looked up across every account, the gateway is asked again where the payment stands, and only then is anything confirmed -- once, however many times the gateway posts.

It answers the invoice as it stands afterwards. A request the provider does not recognise wraps ErrBadNotification; an invoice that is not there, or a provider that is not configured, is ErrNotFound.

func (*BillingService) Invoice

func (s *BillingService) Invoice(ctx context.Context, actor security.Subject, id string) (*Invoice, error)

Invoice is one of the asking account's invoices.

func (*BillingService) InvoicesPage

func (s *BillingService) InvoicesPage(ctx context.Context, actor security.Subject, q PageQuery, perPage int) (Page[*Invoice], error)

InvoicesPage is a page of the asking account's invoices.

func (*BillingService) Plan

func (s *BillingService) Plan(ctx context.Context, actor security.Subject, id string) (*Plan, error)

Plan is one plan of the catalogue, active or not, for the admin.

func (*BillingService) PlanBySlug

func (s *BillingService) PlanBySlug(ctx context.Context, actor security.Subject, slug string) (*Plan, error)

PlanBySlug is one plan by the name the application's code refers to it by, active or not, for any signed-in subject: what an application's seeder or its own screens look a plan up by.

func (*BillingService) PlanNames

func (s *BillingService) PlanNames(ctx context.Context, actor security.Subject) (map[string]string, error)

PlanNames are the names of the plans, by id, for a screen that lists subscriptions.

func (*BillingService) PlansPage

func (s *BillingService) PlansPage(ctx context.Context, actor security.Subject, q PageQuery, perPage int) (Page[*Plan], error)

PlansPage is a page of the catalogue, active or not, for the admin.

func (*BillingService) RefreshInvoice

func (s *BillingService) RefreshInvoice(ctx context.Context, actor security.Subject, id string) (*Invoice, error)

RefreshInvoice asks the gateway again where one of the account's invoices stands, and confirms it when it is paid: what the page the gateway sends the customer back to does, so a payment counts even before the notification arrives.

func (*BillingService) Renew

func (s *BillingService) Renew(ctx context.Context, actor security.Subject, subscriptionID, provider string) (*CheckoutResult, error)

Renew issues the invoice of a subscription's next period. A subscription that still has renewals of its coupon gets the discount again; one that ended is paid for as a new period from the day it is paid.

func (*BillingService) ResumeSubscription

func (s *BillingService) ResumeSubscription(ctx context.Context, actor security.Subject, id string) (*Subscription, error)

ResumeSubscription takes back a cancellation asked for, while the period is still being served.

func (*BillingService) ServingSubscriptions

func (s *BillingService) ServingSubscriptions(ctx context.Context, actor security.Subject) ([]*Subscription, error)

ServingSubscriptions are the asking account's subscriptions that still give access -- trialing, active, or past due inside the grace -- which is what an application asks before it opens what a plan pays for.

func (*BillingService) SetCouponActive

func (s *BillingService) SetCouponActive(ctx context.Context, actor security.Subject, id string, active bool) (*Coupon, error)

SetCouponActive switches a coupon on or off, keeping everything else.

func (*BillingService) StartTrial

func (s *BillingService) StartTrial(ctx context.Context, actor security.Subject, planID, reference string) (*Subscription, error)

StartTrial starts the trial of a plan for the asking account: once per plan and reference, and only for a plan that offers one.

func (*BillingService) Subscribe

Subscribe issues the invoice of a plan for the asking account and asks the gateway for its page. When the account already has a subscription to the plan, for the same reference, that is still served, the invoice extends it.

func (*BillingService) SubscriptionsOf

func (s *BillingService) SubscriptionsOf(ctx context.Context, g security.Grant) ([]*Subscription, error)

SubscriptionsOf are the serving subscriptions of an account, for the application's own code acting under a Grant its own policy issued for that account -- a job, the engine's sync -- rather than for a session.

func (*BillingService) SubscriptionsPage

func (s *BillingService) SubscriptionsPage(ctx context.Context, actor security.Subject, q PageQuery, perPage int) (Page[*Subscription], error)

SubscriptionsPage is a page of the asking account's subscriptions.

func (*BillingService) SweepDue

func (s *BillingService) SweepDue(ctx context.Context, now time.Time) (int, error)

SweepDue moves every subscription whose period ended by now, in every account: a trial or a period that ended goes past due, expires, or is canceled when its cancellation was asked for (see Due). It is what the module's scheduled task runs; it answers how many it moved.

func (*BillingService) UpdateCoupon

func (s *BillingService) UpdateCoupon(ctx context.Context, actor security.Subject, id string, in CouponRequest) (*Coupon, error)

UpdateCoupon changes a coupon. The code stays; a coupon is retired by deactivating it, never by renaming it.

func (*BillingService) UpdatePlan

func (s *BillingService) UpdatePlan(ctx context.Context, actor security.Subject, id string, in PlanRequest) (*Plan, error)

UpdatePlan changes a plan. The subscriptions already sold keep the period they were sold; the next invoice charges the new price.

func (*BillingService) VoidInvoice

func (s *BillingService) VoidInvoice(ctx context.Context, actor security.Subject, id string) (*Invoice, error)

VoidInvoice is the admin canceling one account's open invoice. A paid invoice is never voided here.

type CellInput

type CellInput struct {
	Name, Type, Placeholder, Value, Label string
	Required                              bool
}

CellInput is one field of a form drawn inside a table cell.

type Checkout

type Checkout struct {
	// URL is the gateway's payment page. Empty sends the customer to the
	// invoice page of this package, where the application's instructions are.
	URL string
	// Reference is the gateway's identifier of the order, empty when it gives
	// none until it is paid.
	Reference string
}

Checkout is what a Provider answered for one invoice.

type CheckoutRequest

type CheckoutRequest struct {
	// InvoiceID is the order number: what the notification will name.
	InvoiceID string
	// Tenant is the account that pays.
	Tenant string
	// Description is the line the customer reads on the gateway's page: the
	// plan's name and its months.
	Description string
	// PlanID and PlanSlug are the plan charged for.
	PlanID, PlanSlug string
	// Months is how many months the payment buys.
	Months int
	// Subtotal, Discount and Total are in centavos of BRL; Total is what is
	// charged.
	Subtotal, Discount, Total int64
	// CouponCode is the coupon applied, empty for none.
	CouponCode string
	// MaxInstallments is the most installments the page may offer.
	MaxInstallments int
	// Customer is who pays, as the application filled it in.
	Customer Customer
	// ReturnURL is where the gateway sends the customer back, when the
	// application configured one.
	ReturnURL string
	// Meta is what the consumer attached to the checkout and the plan.
	Meta Meta
}

CheckoutRequest is what a Provider is asked to collect.

type CheckoutResult

type CheckoutResult struct {
	// Invoice is the invoice, open -- or paid already, when a coupon took the
	// whole price off.
	Invoice *Invoice
	// URL is the gateway's page; empty means the invoice page.
	URL string
}

CheckoutResult is an issued invoice and where the customer pays it.

type ChromeRequest

type ChromeRequest struct {
	// Title is the screen's title, in the request's language.
	Title string
	// Admin says the screen is one of the admin's.
	Admin bool
	// Subject is who is asking.
	Subject security.Subject
	// Page is the page hesape's view.New built for the request.
	Page hview.Page
}

ChromeRequest is what Config.Chrome is asked about one screen.

type Config

type Config struct {
	// Prefix is the path the account's routes are mounted under. Empty means
	// DefaultPrefix.
	Prefix string

	// AdminPrefix is where the admin's routes are mounted. Empty means Prefix
	// followed by Paths.Admin. An application whose team works on another
	// side of the site -- an operator console at /admin -- mounts them there.
	AdminPrefix string

	// Paths are the segments every route is built from. A field left empty
	// keeps its DefaultPaths value; PortuguesePaths is the whole set in
	// Brazilian Portuguese.
	Paths Paths

	// NotificationPrefix is where the gateways post. Empty means
	// DefaultNotificationPrefix. It is exempt from the CSRF check, and no
	// session is asked for: a notification is believed only after the
	// gateway is asked again.
	NotificationPrefix string

	// PageSize is how many records one page answers with. Zero means
	// DefaultPageSize; above MaxPageSize is refused.
	PageSize int

	// Providers are the gateways the application implemented, each a service
	// of the application's own (see Provider). At least one is required; the
	// first is the one a checkout uses unless DefaultProvider names another.
	// ManualProvider is the gateway-free one this package ships.
	Providers []Provider

	// DefaultProvider is the Name of the provider a checkout uses. Empty means
	// the first of Providers.
	DefaultProvider string

	// Listener is told what happened to an account's billing -- a
	// subscription activated, renewed, past due, expired or canceled, an
	// invoice paid -- inside the transaction that did it, so what it writes
	// commits or rolls back with it. An error rolls the act back; a gateway's
	// notification is then answered with an error and sent again. Nil tells
	// nobody.
	Listener Listener

	// Customer fills in who pays, for the gateway's page: the account's name,
	// e-mail and document, read by the application. Nil sends an empty
	// Customer.
	Customer func(ctx context.Context, who security.Subject) (Customer, error)

	// PublicURL is the application's address as the gateway reaches it,
	// "https://alpr.sh", from which the return address of a checkout is
	// built. Empty sends no return address.
	PublicURL string

	// Clock is the time, for a test that holds it still. Nil is the system's
	// clock, which is what an application wants.
	Clock func() time.Time

	// Location is the timezone dates are shown in. Nil means DefaultLocation.
	Location *time.Location

	// Activity is arandu-activitylog's logger, the application's one instance
	// (activityModule.Logger()). Every act that changes something is recorded
	// under the Grant it was authorized with, in the log named
	// ActivityLogName. Nil records nothing.
	Activity *activitylog.Logger

	// Translator is the application's own catalogue, asked before the one this
	// package ships, key by key: "billing.screen.plans_title". Optional.
	Translator *translation.Translator

	// Locale is the language every screen, message and activity description
	// is written in: "pt-BR" for an application that speaks Brazilian
	// Portuguese and nothing else. Empty means the locale the request
	// negotiated, and FallbackLocale when there is none.
	Locale string

	// TitleSeparator joins a screen's title to the application's name in the
	// document title: " — " titles the plans "Planos — Alpr.sh". Empty titles a
	// screen with its own title alone.
	TitleSeparator string

	// Middleware runs on every route of an account and of the admin after
	// RequireAuth, and AdminMiddleware after it on the admin's routes only:
	// arandu-permission's Roles(), the operator console's own guard. A guard
	// answers "is this request on the right side" and stops; the policy still
	// decides.
	Middleware      []func(http.Handler) http.Handler
	AdminMiddleware []func(http.Handler) http.Handler

	// Chrome is what the application's layout draws around a screen of this
	// package: its sidebar, its navigation. It is called once per screen and
	// carried as Screen.Chrome. Nil draws the screens with hesape's page alone.
	Chrome func(ctx *fhttp.Context, req ChromeRequest) (any, error)
}

Config is what the application passes when it wires this package.

It names no tenant, and that is deliberate. Every route of an account sits behind RequireAuth, so the tenant of every statement is the one the Grant carries, from the session of whoever is asking; a notification's tenant is the invoice's own.

func (Config) Validate

func (c Config) Validate() error

Validate reports what the configuration cannot be used with. New calls it, so a setting that cannot work fails where it is wired.

type Coupon

type Coupon struct {
	model.Model

	// ID is the identifier, written by the application.
	ID string `db:"id"`
	// Code is what the customer types, upper case. Unique.
	Code string `db:"code"`
	// Description is a note for the admin.
	Description string `db:"description"`
	// Kind is CouponPercent or CouponFixed.
	Kind CouponKind `db:"kind"`
	// Value is the discount: basis points for CouponPercent (1000 is 10%),
	// centavos for CouponFixed.
	Value int64 `db:"value"`
	// MaxUses is how many payments may use the coupon. Zero is unlimited.
	MaxUses int `db:"max_uses"`
	// Uses is how many payments have used it.
	Uses int `db:"uses"`
	// ValidFrom is the first instant it may be used. Nil is always.
	ValidFrom *time.Time `db:"valid_from"`
	// ValidUntil is the instant it stops being usable. Nil is never.
	ValidUntil *time.Time `db:"valid_until"`
	// Renewals is how many renewals after the first payment keep the discount.
	// Zero discounts the first payment alone.
	Renewals int `db:"renewals"`
	// MinPurchase is the smallest price, in centavos, the coupon applies to.
	MinPurchase int64 `db:"min_purchase"`
	// PlanID restricts the coupon to one plan. Empty is every plan.
	PlanID string `db:"plan_id"`
	// Active says the coupon is accepted. An inactive coupon still discounts
	// the renewals it was already granted to.
	Active Flag `db:"active"`
	// CreatedAt is when the row was written, in UTC.
	CreatedAt time.Time `db:"created_at"`
	// UpdatedAt is when the row last changed, in UTC.
	UpdatedAt time.Time `db:"updated_at"`
}

Coupon is a discount a customer types at checkout.

Like the plans, the coupons are the platform's catalogue, Global, written by the platform's admin.

func (*Coupon) Fresh

func (row *Coupon) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Coupon, error)

Fresh reads the row again, as a new Coupon; it shadows the untyped one the embedded model promotes.

func (*Coupon) Replicate

func (row *Coupon) Replicate(except ...string) (*Coupon, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

type CouponCollection

type CouponCollection []*Coupon

CouponCollection is rows of Coupon, as a query returns them.

func CouponCollectionOf

func CouponCollectionOf(rows model.Rows) CouponCollection

CouponCollectionOf converts rows of the table of Coupon. A nil input is a nil collection.

func (CouponCollection) Contains

func (c CouponCollection) Contains(key any) bool

func (CouponCollection) Except

func (c CouponCollection) Except(keys ...any) CouponCollection

func (CouponCollection) Find

func (c CouponCollection) Find(key any) *Coupon

func (CouponCollection) FindOrFail

func (c CouponCollection) FindOrFail(key any) (*Coupon, error)

func (CouponCollection) Fresh

func (c CouponCollection) Fresh(ctx context.Context, g auth.Grant, with ...string) (CouponCollection, error)

func (CouponCollection) Load

func (c CouponCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (CouponCollection) LoadCount

func (c CouponCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (CouponCollection) LoadMissing

func (c CouponCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (CouponCollection) ModelKeys

func (c CouponCollection) ModelKeys() []any

func (CouponCollection) Only

func (c CouponCollection) Only(keys ...any) CouponCollection

func (CouponCollection) Pluck

func (c CouponCollection) Pluck(column string) []any

func (CouponCollection) Rows

func (c CouponCollection) Rows() model.Rows

Rows converts the collection back to the core's rows.

func (CouponCollection) ToArray

func (c CouponCollection) ToArray() []map[string]any

func (CouponCollection) Unique

type CouponKind

type CouponKind string

CouponKind is how a coupon's Value is read.

const (
	// CouponPercent takes Value basis points of the price off: 1000 is 10%.
	CouponPercent CouponKind = "percent"
	// CouponFixed takes Value centavos off, never more than the price.
	CouponFixed CouponKind = "fixed"
)

type CouponQuery

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

CouponQuery is a query on the table of Coupon.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Coupon rows or a value; there is no way to run one without a Grant.

func Coupons

func Coupons(db model.DB) *CouponQuery

Coupons starts a query on the table of Coupon, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*CouponQuery) AddSelect

func (q *CouponQuery) AddSelect(columns ...any) *CouponQuery

func (*CouponQuery) Avg

func (q *CouponQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CouponQuery) Base

func (q *CouponQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*CouponQuery) Chunk

func (q *CouponQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(CouponCollection, int) (bool, error)) error

func (*CouponQuery) Clone

func (q *CouponQuery) Clone() *CouponQuery

Clone returns an independent copy of the query.

func (*CouponQuery) Count

func (q *CouponQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*CouponQuery) Create

func (q *CouponQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Coupon, error)

func (*CouponQuery) Cursor

func (q *CouponQuery) Cursor(ctx context.Context, g auth.Grant) iter.Seq2[*Coupon, error]

func (*CouponQuery) CursorPaginate

func (q *CouponQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (CouponCollection, *pagination.CursorPage, error)

func (*CouponQuery) Decrement

func (q *CouponQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*CouponQuery) Delete

func (q *CouponQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*CouponQuery) DoesntExist

func (q *CouponQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*CouponQuery) DoesntHave

func (q *CouponQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *CouponQuery

func (*CouponQuery) Each

func (q *CouponQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*Coupon, int) (bool, error)) error

func (*CouponQuery) Exists

func (q *CouponQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*CouponQuery) Find

func (q *CouponQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Coupon, error)

func (*CouponQuery) FindMany

func (q *CouponQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (CouponCollection, error)

func (*CouponQuery) FindOrFail

func (q *CouponQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Coupon, error)

func (*CouponQuery) FindOrNew

func (q *CouponQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Coupon, error)

func (*CouponQuery) First

func (q *CouponQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Coupon, error)

First returns the first row, or nil and no error when there is none.

func (*CouponQuery) FirstOrCreate

func (q *CouponQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Coupon, error)

func (*CouponQuery) FirstOrFail

func (q *CouponQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Coupon, error)

func (*CouponQuery) FirstOrNew

func (q *CouponQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Coupon, error)

func (*CouponQuery) FirstWhere

func (q *CouponQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Coupon, error)

func (*CouponQuery) ForPage

func (q *CouponQuery) ForPage(page, perPage int) *CouponQuery

func (*CouponQuery) ForceCreate

func (q *CouponQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Coupon, error)

func (*CouponQuery) Get

func (q *CouponQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (CouponCollection, error)

Get runs the query and returns the rows.

func (*CouponQuery) GroupBy

func (q *CouponQuery) GroupBy(groups ...any) *CouponQuery

func (*CouponQuery) Has

func (q *CouponQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *CouponQuery

func (*CouponQuery) Increment

func (q *CouponQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*CouponQuery) Insert

func (q *CouponQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*CouponQuery) InsertOrIgnore

func (q *CouponQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*CouponQuery) Join

func (q *CouponQuery) Join(table any, first any, args ...any) *CouponQuery

func (*CouponQuery) Latest

func (q *CouponQuery) Latest(column ...string) *CouponQuery

func (*CouponQuery) Limit

func (q *CouponQuery) Limit(value int) *CouponQuery

func (*CouponQuery) Max

func (q *CouponQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CouponQuery) Min

func (q *CouponQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CouponQuery) New

func (q *CouponQuery) New() (*Coupon, error)

New returns an empty Coupon on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*CouponQuery) Offset

func (q *CouponQuery) Offset(value int) *CouponQuery

func (*CouponQuery) Oldest

func (q *CouponQuery) Oldest(column ...string) *CouponQuery

func (*CouponQuery) OrDoesntHave

func (q *CouponQuery) OrDoesntHave(relation string) *CouponQuery

func (*CouponQuery) OrHas

func (q *CouponQuery) OrHas(relation, operator string, count int) *CouponQuery

func (*CouponQuery) OrWhere

func (q *CouponQuery) OrWhere(column any, args ...any) *CouponQuery

OrWhere adds an or-where clause; a func(*CouponQuery) in place of the column adds a group.

func (*CouponQuery) OrWhereDoesntHave

func (q *CouponQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *CouponQuery

func (*CouponQuery) OrWhereHas

func (q *CouponQuery) OrWhereHas(relation string, callback func(*query.Builder)) *CouponQuery

func (*CouponQuery) OrWhereNot

func (q *CouponQuery) OrWhereNot(column any, args ...any) *CouponQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*CouponQuery) OrWhereRelation

func (q *CouponQuery) OrWhereRelation(relation string, column any, args ...any) *CouponQuery

func (*CouponQuery) OrderBy

func (q *CouponQuery) OrderBy(column any, direction ...string) *CouponQuery

func (*CouponQuery) OrderByDesc

func (q *CouponQuery) OrderByDesc(column any) *CouponQuery

func (*CouponQuery) Paginate

func (q *CouponQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (CouponCollection, *pagination.LengthAwarePage, error)

func (*CouponQuery) Pluck

func (q *CouponQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*CouponQuery) Select

func (q *CouponQuery) Select(columns ...any) *CouponQuery

func (*CouponQuery) SelectRaw

func (q *CouponQuery) SelectRaw(expression string, bindings ...any) *CouponQuery

func (*CouponQuery) SimplePaginate

func (q *CouponQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (CouponCollection, *pagination.Page, error)

func (*CouponQuery) Sole

func (q *CouponQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Coupon, error)

func (*CouponQuery) SoleValue

func (q *CouponQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*CouponQuery) Sum

func (q *CouponQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CouponQuery) Touch

func (q *CouponQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*CouponQuery) Update

func (q *CouponQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*CouponQuery) UpdateOrCreate

func (q *CouponQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Coupon, error)

func (*CouponQuery) Upsert

func (q *CouponQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*CouponQuery) Value

func (q *CouponQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*CouponQuery) ValueOrFail

func (q *CouponQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*CouponQuery) Where

func (q *CouponQuery) Where(column any, args ...any) *CouponQuery

Where adds a where clause; a func(*CouponQuery) in place of the column adds a group.

func (*CouponQuery) WhereBelongsTo

func (q *CouponQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *CouponQuery

func (*CouponQuery) WhereBetween

func (q *CouponQuery) WhereBetween(column any, from, to any) *CouponQuery

func (*CouponQuery) WhereColumn

func (q *CouponQuery) WhereColumn(first any, args ...any) *CouponQuery

func (*CouponQuery) WhereDoesntHave

func (q *CouponQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *CouponQuery

func (*CouponQuery) WhereExists

func (q *CouponQuery) WhereExists(callback func(*query.Builder)) *CouponQuery

func (*CouponQuery) WhereHas

func (q *CouponQuery) WhereHas(relation string, callback func(*query.Builder)) *CouponQuery

func (*CouponQuery) WhereHasCount

func (q *CouponQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *CouponQuery

func (*CouponQuery) WhereIn

func (q *CouponQuery) WhereIn(column any, values []any) *CouponQuery

func (*CouponQuery) WhereKey

func (q *CouponQuery) WhereKey(id any) *CouponQuery

func (*CouponQuery) WhereNot

func (q *CouponQuery) WhereNot(column any, args ...any) *CouponQuery

WhereNot adds a negated where clause, or a negated group.

func (*CouponQuery) WhereNotExists

func (q *CouponQuery) WhereNotExists(callback func(*query.Builder)) *CouponQuery

func (*CouponQuery) WhereNotIn

func (q *CouponQuery) WhereNotIn(column any, values []any) *CouponQuery

func (*CouponQuery) WhereNotNull

func (q *CouponQuery) WhereNotNull(columns ...any) *CouponQuery

func (*CouponQuery) WhereNull

func (q *CouponQuery) WhereNull(columns ...any) *CouponQuery

func (*CouponQuery) WhereRelation

func (q *CouponQuery) WhereRelation(relation string, column any, args ...any) *CouponQuery

func (*CouponQuery) With

func (q *CouponQuery) With(relations ...string) *CouponQuery

func (*CouponQuery) WithAvg

func (q *CouponQuery) WithAvg(relation, column string) *CouponQuery

func (*CouponQuery) WithCount

func (q *CouponQuery) WithCount(relations ...string) *CouponQuery

func (*CouponQuery) WithExists

func (q *CouponQuery) WithExists(relation string) *CouponQuery

func (*CouponQuery) WithMax

func (q *CouponQuery) WithMax(relation, column string) *CouponQuery

func (*CouponQuery) WithMin

func (q *CouponQuery) WithMin(relation, column string) *CouponQuery

func (*CouponQuery) WithSum

func (q *CouponQuery) WithSum(relation, column string) *CouponQuery

func (*CouponQuery) Without

func (q *CouponQuery) Without(relations ...string) *CouponQuery

func (*CouponQuery) WithoutGlobalScope

func (q *CouponQuery) WithoutGlobalScope(identifier string) *CouponQuery

func (*CouponQuery) WithoutGlobalScopes

func (q *CouponQuery) WithoutGlobalScopes(identifiers ...string) *CouponQuery

type CouponRequest

type CouponRequest struct {
	// Code is what the customer types; it is stored upper case.
	Code string
	// Description is a note for the admin.
	Description string
	// Kind is CouponPercent or CouponFixed.
	Kind CouponKind
	// Value is basis points for CouponPercent, centavos for CouponFixed.
	Value int64
	// MaxUses is how many first payments may use it; zero is unlimited.
	MaxUses int
	// Renewals is how many renewals keep the discount.
	Renewals int
	// MinPurchase is the smallest price it applies to, in centavos.
	MinPurchase int64
	// PlanID restricts it to one plan; empty is every plan.
	PlanID string
	// ValidFrom and ValidUntil bound when it is accepted; nil is unbounded.
	ValidFrom, ValidUntil *time.Time
	// Active says it is accepted.
	Active bool
}

CouponRequest is the input contract for a coupon.

func (CouponRequest) Validate

func (r CouponRequest) Validate() validation.Errors

Validate reports the errors per field.

type CouponResource

type CouponResource struct {
	ID, Code, Description, PlanID string
	Kind                          CouponKind
	Value, MinPurchase            int64
	MaxUses, Uses, Renewals       int
	ValidFrom, ValidUntil         *time.Time
	Active                        bool
}

CouponResource is one coupon as it may leave.

func NewCouponResource

func NewCouponResource(c Coupon) CouponResource

NewCouponResource copies a coupon.

func (CouponResource) ToArray

func (r CouponResource) ToArray() map[string]any

ToArray is the coupon's fields, by name.

func (CouponResource) With

func (CouponResource) With() map[string]any

With is nothing beside the coupon.

type CouponRow

type CouponRow struct {
	ID, Code, Description, Discount, Uses, Validity, Renewals, Plan, Minimum, Status string
	Active                                                                           bool
	ToggleURL                                                                        string
}

CouponRow is one coupon in the admin's list.

type CouponUsage

type CouponUsage struct {
	model.Model

	// ID is the identifier, written by the application.
	ID string `db:"id"`
	// TenantID is the account that used it.
	TenantID string `db:"tenant_id"`
	// CouponID is the coupon used.
	CouponID string `db:"coupon_id"`
	// InvoiceID is the invoice it discounted.
	InvoiceID string `db:"invoice_id"`
	// PaymentID is the payment that confirmed that invoice.
	PaymentID string `db:"payment_id"`
	// Discount is what it took off, in centavos.
	Discount int64 `db:"discount"`
	// RenewalNumber is which payment of the subscription it discounted.
	RenewalNumber int `db:"renewal_number"`
	// UsedAt is when the payment was confirmed, in UTC.
	UsedAt time.Time `db:"used_at"`
	// CreatedAt is when the row was written, in UTC.
	CreatedAt time.Time `db:"created_at"`
	// UpdatedAt is when the row last changed, in UTC.
	UpdatedAt time.Time `db:"updated_at"`
}

CouponUsage is one payment that used a coupon, with the discount it got.

func (*CouponUsage) Fresh

func (row *CouponUsage) Fresh(ctx context.Context, g auth.Grant, with ...string) (*CouponUsage, error)

Fresh reads the row again, as a new CouponUsage; it shadows the untyped one the embedded model promotes.

func (*CouponUsage) Replicate

func (row *CouponUsage) Replicate(except ...string) (*CouponUsage, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

type CouponUsageCollection

type CouponUsageCollection []*CouponUsage

CouponUsageCollection is rows of CouponUsage, as a query returns them.

func CouponUsageCollectionOf

func CouponUsageCollectionOf(rows model.Rows) CouponUsageCollection

CouponUsageCollectionOf converts rows of the table of CouponUsage. A nil input is a nil collection.

func (CouponUsageCollection) Contains

func (c CouponUsageCollection) Contains(key any) bool

func (CouponUsageCollection) Except

func (CouponUsageCollection) Find

func (c CouponUsageCollection) Find(key any) *CouponUsage

func (CouponUsageCollection) FindOrFail

func (c CouponUsageCollection) FindOrFail(key any) (*CouponUsage, error)

func (CouponUsageCollection) Fresh

func (CouponUsageCollection) Load

func (c CouponUsageCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (CouponUsageCollection) LoadCount

func (c CouponUsageCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (CouponUsageCollection) LoadMissing

func (c CouponUsageCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (CouponUsageCollection) ModelKeys

func (c CouponUsageCollection) ModelKeys() []any

func (CouponUsageCollection) Only

func (CouponUsageCollection) Pluck

func (c CouponUsageCollection) Pluck(column string) []any

func (CouponUsageCollection) Rows

func (c CouponUsageCollection) Rows() model.Rows

Rows converts the collection back to the core's rows.

func (CouponUsageCollection) ToArray

func (c CouponUsageCollection) ToArray() []map[string]any

func (CouponUsageCollection) Unique

type CouponUsageQuery

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

CouponUsageQuery is a query on the table of CouponUsage.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return CouponUsage rows or a value; there is no way to run one without a Grant.

func CouponUsages

func CouponUsages(db model.DB) *CouponUsageQuery

CouponUsages starts a query on the table of CouponUsage, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*CouponUsageQuery) AddSelect

func (q *CouponUsageQuery) AddSelect(columns ...any) *CouponUsageQuery

func (*CouponUsageQuery) Avg

func (q *CouponUsageQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CouponUsageQuery) Base

func (q *CouponUsageQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*CouponUsageQuery) Chunk

func (q *CouponUsageQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(CouponUsageCollection, int) (bool, error)) error

func (*CouponUsageQuery) Clone

func (q *CouponUsageQuery) Clone() *CouponUsageQuery

Clone returns an independent copy of the query.

func (*CouponUsageQuery) Count

func (q *CouponUsageQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*CouponUsageQuery) Create

func (q *CouponUsageQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*CouponUsage, error)

func (*CouponUsageQuery) Cursor

func (*CouponUsageQuery) CursorPaginate

func (q *CouponUsageQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (CouponUsageCollection, *pagination.CursorPage, error)

func (*CouponUsageQuery) Decrement

func (q *CouponUsageQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*CouponUsageQuery) Delete

func (q *CouponUsageQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*CouponUsageQuery) DoesntExist

func (q *CouponUsageQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*CouponUsageQuery) DoesntHave

func (q *CouponUsageQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *CouponUsageQuery

func (*CouponUsageQuery) Each

func (q *CouponUsageQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*CouponUsage, int) (bool, error)) error

func (*CouponUsageQuery) Exists

func (q *CouponUsageQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*CouponUsageQuery) Find

func (q *CouponUsageQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*CouponUsage, error)

func (*CouponUsageQuery) FindMany

func (q *CouponUsageQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (CouponUsageCollection, error)

func (*CouponUsageQuery) FindOrFail

func (q *CouponUsageQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*CouponUsage, error)

func (*CouponUsageQuery) FindOrNew

func (q *CouponUsageQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*CouponUsage, error)

func (*CouponUsageQuery) First

func (q *CouponUsageQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*CouponUsage, error)

First returns the first row, or nil and no error when there is none.

func (*CouponUsageQuery) FirstOrCreate

func (q *CouponUsageQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*CouponUsage, error)

func (*CouponUsageQuery) FirstOrFail

func (q *CouponUsageQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*CouponUsage, error)

func (*CouponUsageQuery) FirstOrNew

func (q *CouponUsageQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*CouponUsage, error)

func (*CouponUsageQuery) FirstWhere

func (q *CouponUsageQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*CouponUsage, error)

func (*CouponUsageQuery) ForPage

func (q *CouponUsageQuery) ForPage(page, perPage int) *CouponUsageQuery

func (*CouponUsageQuery) ForceCreate

func (q *CouponUsageQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*CouponUsage, error)

func (*CouponUsageQuery) Get

func (q *CouponUsageQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (CouponUsageCollection, error)

Get runs the query and returns the rows.

func (*CouponUsageQuery) GroupBy

func (q *CouponUsageQuery) GroupBy(groups ...any) *CouponUsageQuery

func (*CouponUsageQuery) Has

func (q *CouponUsageQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *CouponUsageQuery

func (*CouponUsageQuery) Increment

func (q *CouponUsageQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*CouponUsageQuery) Insert

func (q *CouponUsageQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*CouponUsageQuery) InsertOrIgnore

func (q *CouponUsageQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*CouponUsageQuery) Join

func (q *CouponUsageQuery) Join(table any, first any, args ...any) *CouponUsageQuery

func (*CouponUsageQuery) Latest

func (q *CouponUsageQuery) Latest(column ...string) *CouponUsageQuery

func (*CouponUsageQuery) Limit

func (q *CouponUsageQuery) Limit(value int) *CouponUsageQuery

func (*CouponUsageQuery) Max

func (q *CouponUsageQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CouponUsageQuery) Min

func (q *CouponUsageQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CouponUsageQuery) New

func (q *CouponUsageQuery) New() (*CouponUsage, error)

New returns an empty CouponUsage on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*CouponUsageQuery) Offset

func (q *CouponUsageQuery) Offset(value int) *CouponUsageQuery

func (*CouponUsageQuery) Oldest

func (q *CouponUsageQuery) Oldest(column ...string) *CouponUsageQuery

func (*CouponUsageQuery) OrDoesntHave

func (q *CouponUsageQuery) OrDoesntHave(relation string) *CouponUsageQuery

func (*CouponUsageQuery) OrHas

func (q *CouponUsageQuery) OrHas(relation, operator string, count int) *CouponUsageQuery

func (*CouponUsageQuery) OrWhere

func (q *CouponUsageQuery) OrWhere(column any, args ...any) *CouponUsageQuery

OrWhere adds an or-where clause; a func(*CouponUsageQuery) in place of the column adds a group.

func (*CouponUsageQuery) OrWhereDoesntHave

func (q *CouponUsageQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *CouponUsageQuery

func (*CouponUsageQuery) OrWhereHas

func (q *CouponUsageQuery) OrWhereHas(relation string, callback func(*query.Builder)) *CouponUsageQuery

func (*CouponUsageQuery) OrWhereNot

func (q *CouponUsageQuery) OrWhereNot(column any, args ...any) *CouponUsageQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*CouponUsageQuery) OrWhereRelation

func (q *CouponUsageQuery) OrWhereRelation(relation string, column any, args ...any) *CouponUsageQuery

func (*CouponUsageQuery) OrderBy

func (q *CouponUsageQuery) OrderBy(column any, direction ...string) *CouponUsageQuery

func (*CouponUsageQuery) OrderByDesc

func (q *CouponUsageQuery) OrderByDesc(column any) *CouponUsageQuery

func (*CouponUsageQuery) Paginate

func (q *CouponUsageQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (CouponUsageCollection, *pagination.LengthAwarePage, error)

func (*CouponUsageQuery) Pluck

func (q *CouponUsageQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*CouponUsageQuery) Select

func (q *CouponUsageQuery) Select(columns ...any) *CouponUsageQuery

func (*CouponUsageQuery) SelectRaw

func (q *CouponUsageQuery) SelectRaw(expression string, bindings ...any) *CouponUsageQuery

func (*CouponUsageQuery) SimplePaginate

func (q *CouponUsageQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (CouponUsageCollection, *pagination.Page, error)

func (*CouponUsageQuery) Sole

func (q *CouponUsageQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*CouponUsage, error)

func (*CouponUsageQuery) SoleValue

func (q *CouponUsageQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*CouponUsageQuery) Sum

func (q *CouponUsageQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*CouponUsageQuery) Touch

func (q *CouponUsageQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*CouponUsageQuery) Update

func (q *CouponUsageQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*CouponUsageQuery) UpdateOrCreate

func (q *CouponUsageQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*CouponUsage, error)

func (*CouponUsageQuery) Upsert

func (q *CouponUsageQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*CouponUsageQuery) Value

func (q *CouponUsageQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*CouponUsageQuery) ValueOrFail

func (q *CouponUsageQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*CouponUsageQuery) Where

func (q *CouponUsageQuery) Where(column any, args ...any) *CouponUsageQuery

Where adds a where clause; a func(*CouponUsageQuery) in place of the column adds a group.

func (*CouponUsageQuery) WhereBelongsTo

func (q *CouponUsageQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *CouponUsageQuery

func (*CouponUsageQuery) WhereBetween

func (q *CouponUsageQuery) WhereBetween(column any, from, to any) *CouponUsageQuery

func (*CouponUsageQuery) WhereColumn

func (q *CouponUsageQuery) WhereColumn(first any, args ...any) *CouponUsageQuery

func (*CouponUsageQuery) WhereDoesntHave

func (q *CouponUsageQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *CouponUsageQuery

func (*CouponUsageQuery) WhereExists

func (q *CouponUsageQuery) WhereExists(callback func(*query.Builder)) *CouponUsageQuery

func (*CouponUsageQuery) WhereHas

func (q *CouponUsageQuery) WhereHas(relation string, callback func(*query.Builder)) *CouponUsageQuery

func (*CouponUsageQuery) WhereHasCount

func (q *CouponUsageQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *CouponUsageQuery

func (*CouponUsageQuery) WhereIn

func (q *CouponUsageQuery) WhereIn(column any, values []any) *CouponUsageQuery

func (*CouponUsageQuery) WhereKey

func (q *CouponUsageQuery) WhereKey(id any) *CouponUsageQuery

func (*CouponUsageQuery) WhereNot

func (q *CouponUsageQuery) WhereNot(column any, args ...any) *CouponUsageQuery

WhereNot adds a negated where clause, or a negated group.

func (*CouponUsageQuery) WhereNotExists

func (q *CouponUsageQuery) WhereNotExists(callback func(*query.Builder)) *CouponUsageQuery

func (*CouponUsageQuery) WhereNotIn

func (q *CouponUsageQuery) WhereNotIn(column any, values []any) *CouponUsageQuery

func (*CouponUsageQuery) WhereNotNull

func (q *CouponUsageQuery) WhereNotNull(columns ...any) *CouponUsageQuery

func (*CouponUsageQuery) WhereNull

func (q *CouponUsageQuery) WhereNull(columns ...any) *CouponUsageQuery

func (*CouponUsageQuery) WhereRelation

func (q *CouponUsageQuery) WhereRelation(relation string, column any, args ...any) *CouponUsageQuery

func (*CouponUsageQuery) With

func (q *CouponUsageQuery) With(relations ...string) *CouponUsageQuery

func (*CouponUsageQuery) WithAvg

func (q *CouponUsageQuery) WithAvg(relation, column string) *CouponUsageQuery

func (*CouponUsageQuery) WithCount

func (q *CouponUsageQuery) WithCount(relations ...string) *CouponUsageQuery

func (*CouponUsageQuery) WithExists

func (q *CouponUsageQuery) WithExists(relation string) *CouponUsageQuery

func (*CouponUsageQuery) WithMax

func (q *CouponUsageQuery) WithMax(relation, column string) *CouponUsageQuery

func (*CouponUsageQuery) WithMin

func (q *CouponUsageQuery) WithMin(relation, column string) *CouponUsageQuery

func (*CouponUsageQuery) WithSum

func (q *CouponUsageQuery) WithSum(relation, column string) *CouponUsageQuery

func (*CouponUsageQuery) Without

func (q *CouponUsageQuery) Without(relations ...string) *CouponUsageQuery

func (*CouponUsageQuery) WithoutGlobalScope

func (q *CouponUsageQuery) WithoutGlobalScope(identifier string) *CouponUsageQuery

func (*CouponUsageQuery) WithoutGlobalScopes

func (q *CouponUsageQuery) WithoutGlobalScopes(identifiers ...string) *CouponUsageQuery

type Customer

type Customer struct {
	// Name is the person's or the company's name.
	Name string
	// Email is where the gateway writes to.
	Email string
	// Document is the CPF or the CNPJ, digits only.
	Document string
	// Phone is a telephone with area code, digits only.
	Phone string
}

Customer is who pays, filled in by the application through Config.Customer; every field may be empty.

type Event

type Event struct {
	// Name is what happened.
	Name EventName
	// Tenant is the account it happened to.
	Tenant string
	// At is when, in UTC.
	At time.Time
	// Subscription is the subscription as it stands after the event.
	Subscription SubscriptionResource
	// Plan is the subscription's plan, with the consumer's Meta.
	Plan PlanResource
	// Invoice is the invoice that caused it, nil for the clock's events.
	Invoice *InvoiceResource
	// Grant is the Grant the act ran under, scoped to Tenant: what the
	// Listener hands arandu-wallet (wallet.OperatorFor) or its own services
	// to act inside the same account.
	Grant security.Grant
}

Event is what the Listener is told.

type EventName

type EventName string

EventName is what happened to an account's billing.

const (
	// EventTrialStarted is a trial begun.
	EventTrialStarted EventName = "subscription.trial_started"
	// EventActivated is a subscription paid for the first time, or again after
	// it ended.
	EventActivated EventName = "subscription.activated"
	// EventRenewed is a subscription paid for another period.
	EventRenewed EventName = "subscription.renewed"
	// EventPastDue is a period ended without a payment, inside the grace.
	EventPastDue EventName = "subscription.past_due"
	// EventExpired is a subscription ended without a payment.
	EventExpired EventName = "subscription.expired"
	// EventCanceled is a subscription stopped: at the end of the period the
	// customer asked it to, or at once by the admin.
	EventCanceled EventName = "subscription.canceled"
	// EventInvoicePaid is an invoice confirmed, once. It comes before the
	// subscription's own event of the same payment.
	EventInvoicePaid EventName = "invoice.paid"
)

The events the consumer's Listener is told about.

type Flag

type Flag bool

Flag is a yes-or-no a column holds as an integer, read back from whatever an engine answers with, because the engines disagree about booleans.

func (*Flag) Scan

func (f *Flag) Scan(value any) error

Scan reads the flag back. Anything it cannot read is refused rather than read as false.

func (Flag) Value

func (f Flag) Value() (driver.Value, error)

Value writes the flag as the integer the column holds.

type FormState

type FormState struct{ hview.Page }

FormState is what a form field reads from the page it is drawn on.

func (FormState) ErrorSummary

func (f FormState) ErrorSummary() []string

ErrorSummary is one line per rejected field.

func (FormState) FieldError

func (f FormState) FieldError(name string) string

FieldError is the first message for one field, empty when it was accepted.

func (FormState) FieldErrors

func (f FormState) FieldErrors(name string) []string

FieldErrors is every message for one field.

func (FormState) HasErrors

func (f FormState) HasErrors() bool

HasErrors says whether the attempt that landed here was rejected.

func (FormState) LogValue

func (f FormState) LogValue() slog.Value

LogValue is the form state as a log line carries it, the token redacted.

func (FormState) MarshalJSON

func (f FormState) MarshalJSON() ([]byte, error)

MarshalJSON writes the form state with the CSRF token redacted.

type Invoice

type Invoice struct {
	model.Model

	// ID is the identifier, and the order number the provider is given.
	ID string `db:"id"`
	// TenantID is the account that owes it.
	TenantID string `db:"tenant_id"`
	// SubscriptionID is the subscription it renews or starts after a trial;
	// empty for a first payment, which creates the subscription.
	SubscriptionID string `db:"subscription_id"`
	// PlanID is the plan it charges for.
	PlanID string `db:"plan_id"`
	// PlanName is the plan's name when the invoice was issued.
	PlanName string `db:"plan_name"`
	// Reference is the subscription's Reference.
	Reference string `db:"reference"`
	// Kind is InvoiceNew or InvoiceRenewal.
	Kind InvoiceKind `db:"kind"`
	// Status is where the invoice stands.
	Status InvoiceStatus `db:"status"`
	// Months is how many months the payment buys.
	Months int `db:"months"`
	// Subtotal is the plan's price, in centavos.
	Subtotal int64 `db:"subtotal"`
	// Discount is the coupon's discount, in centavos.
	Discount int64 `db:"discount"`
	// Total is what is charged, in centavos.
	Total int64 `db:"total"`
	// CouponID is the coupon applied, empty for none.
	CouponID string `db:"coupon_id"`
	// CouponCode is the code applied, as typed, empty for none.
	CouponCode string `db:"coupon_code"`
	// RenewalNumber is which payment of the subscription this is: 1 for the
	// first, 2 for the first renewal.
	RenewalNumber int `db:"renewal_number"`
	// MaxInstallments is the most installments the provider may offer.
	MaxInstallments int `db:"max_installments"`
	// Provider is the name of the Provider that collects it.
	Provider string `db:"provider"`
	// ProviderRef is the provider's own identifier of the order or payment.
	ProviderRef string `db:"provider_ref"`
	// ProviderStatus is the last state the provider reported, as it said it.
	ProviderStatus string `db:"provider_status"`
	// CheckoutURL is where the customer pays, empty for a provider with no
	// page of its own.
	CheckoutURL string `db:"checkout_url"`
	// Meta is what the consumer attached to the checkout.
	Meta Meta `db:"meta"`
	// PaidAt is when the payment was confirmed, nil while open.
	PaidAt *time.Time `db:"paid_at"`
	// CreatedBy is the user who issued it.
	CreatedBy string `db:"created_by"`
	// CreatedAt is when the row was written, in UTC.
	CreatedAt time.Time `db:"created_at"`
	// UpdatedAt is when the row last changed, in UTC.
	UpdatedAt time.Time `db:"updated_at"`
}

Invoice is one charge: a plan's period, its discount, and what the provider was asked to collect.

The ID is the order number a Provider is given, so a notification names the invoice it is about without naming the tenant: the tenant is read from the row.

func (*Invoice) Fresh

func (row *Invoice) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Invoice, error)

Fresh reads the row again, as a new Invoice; it shadows the untyped one the embedded model promotes.

func (*Invoice) Replicate

func (row *Invoice) Replicate(except ...string) (*Invoice, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

type InvoiceCollection

type InvoiceCollection []*Invoice

InvoiceCollection is rows of Invoice, as a query returns them.

func InvoiceCollectionOf

func InvoiceCollectionOf(rows model.Rows) InvoiceCollection

InvoiceCollectionOf converts rows of the table of Invoice. A nil input is a nil collection.

func (InvoiceCollection) Contains

func (c InvoiceCollection) Contains(key any) bool

func (InvoiceCollection) Except

func (c InvoiceCollection) Except(keys ...any) InvoiceCollection

func (InvoiceCollection) Find

func (c InvoiceCollection) Find(key any) *Invoice

func (InvoiceCollection) FindOrFail

func (c InvoiceCollection) FindOrFail(key any) (*Invoice, error)

func (InvoiceCollection) Fresh

func (InvoiceCollection) Load

func (c InvoiceCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (InvoiceCollection) LoadCount

func (c InvoiceCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (InvoiceCollection) LoadMissing

func (c InvoiceCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (InvoiceCollection) ModelKeys

func (c InvoiceCollection) ModelKeys() []any

func (InvoiceCollection) Only

func (c InvoiceCollection) Only(keys ...any) InvoiceCollection

func (InvoiceCollection) Pluck

func (c InvoiceCollection) Pluck(column string) []any

func (InvoiceCollection) Rows

func (c InvoiceCollection) Rows() model.Rows

Rows converts the collection back to the core's rows.

func (InvoiceCollection) ToArray

func (c InvoiceCollection) ToArray() []map[string]any

func (InvoiceCollection) Unique

type InvoiceKind

type InvoiceKind string

InvoiceKind says whether an invoice starts a subscription or renews one.

const (
	// InvoiceNew is the first payment of a subscription.
	InvoiceNew InvoiceKind = "new"
	// InvoiceRenewal extends a subscription that exists.
	InvoiceRenewal InvoiceKind = "renewal"
)

type InvoicePageData

type InvoicePageData struct {
	Screen
	Invoice InvoiceRow
	// Instructions are the provider's words on how to pay, empty for a
	// provider with a page of its own.
	Instructions string
}

InvoicePageData is one invoice, with how to pay it.

type InvoiceQuery

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

InvoiceQuery is a query on the table of Invoice.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Invoice rows or a value; there is no way to run one without a Grant.

func Invoices

func Invoices(db model.DB) *InvoiceQuery

Invoices starts a query on the table of Invoice, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*InvoiceQuery) AddSelect

func (q *InvoiceQuery) AddSelect(columns ...any) *InvoiceQuery

func (*InvoiceQuery) Avg

func (q *InvoiceQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*InvoiceQuery) Base

func (q *InvoiceQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*InvoiceQuery) Chunk

func (q *InvoiceQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(InvoiceCollection, int) (bool, error)) error

func (*InvoiceQuery) Clone

func (q *InvoiceQuery) Clone() *InvoiceQuery

Clone returns an independent copy of the query.

func (*InvoiceQuery) Count

func (q *InvoiceQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*InvoiceQuery) Create

func (q *InvoiceQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Invoice, error)

func (*InvoiceQuery) Cursor

func (q *InvoiceQuery) Cursor(ctx context.Context, g auth.Grant) iter.Seq2[*Invoice, error]

func (*InvoiceQuery) CursorPaginate

func (q *InvoiceQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (InvoiceCollection, *pagination.CursorPage, error)

func (*InvoiceQuery) Decrement

func (q *InvoiceQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*InvoiceQuery) Delete

func (q *InvoiceQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*InvoiceQuery) DoesntExist

func (q *InvoiceQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*InvoiceQuery) DoesntHave

func (q *InvoiceQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *InvoiceQuery

func (*InvoiceQuery) Each

func (q *InvoiceQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*Invoice, int) (bool, error)) error

func (*InvoiceQuery) Exists

func (q *InvoiceQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*InvoiceQuery) Find

func (q *InvoiceQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Invoice, error)

func (*InvoiceQuery) FindMany

func (q *InvoiceQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (InvoiceCollection, error)

func (*InvoiceQuery) FindOrFail

func (q *InvoiceQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Invoice, error)

func (*InvoiceQuery) FindOrNew

func (q *InvoiceQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Invoice, error)

func (*InvoiceQuery) First

func (q *InvoiceQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Invoice, error)

First returns the first row, or nil and no error when there is none.

func (*InvoiceQuery) FirstOrCreate

func (q *InvoiceQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Invoice, error)

func (*InvoiceQuery) FirstOrFail

func (q *InvoiceQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Invoice, error)

func (*InvoiceQuery) FirstOrNew

func (q *InvoiceQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Invoice, error)

func (*InvoiceQuery) FirstWhere

func (q *InvoiceQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Invoice, error)

func (*InvoiceQuery) ForPage

func (q *InvoiceQuery) ForPage(page, perPage int) *InvoiceQuery

func (*InvoiceQuery) ForceCreate

func (q *InvoiceQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Invoice, error)

func (*InvoiceQuery) Get

func (q *InvoiceQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (InvoiceCollection, error)

Get runs the query and returns the rows.

func (*InvoiceQuery) GroupBy

func (q *InvoiceQuery) GroupBy(groups ...any) *InvoiceQuery

func (*InvoiceQuery) Has

func (q *InvoiceQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *InvoiceQuery

func (*InvoiceQuery) Increment

func (q *InvoiceQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*InvoiceQuery) Insert

func (q *InvoiceQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*InvoiceQuery) InsertOrIgnore

func (q *InvoiceQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*InvoiceQuery) Join

func (q *InvoiceQuery) Join(table any, first any, args ...any) *InvoiceQuery

func (*InvoiceQuery) Latest

func (q *InvoiceQuery) Latest(column ...string) *InvoiceQuery

func (*InvoiceQuery) Limit

func (q *InvoiceQuery) Limit(value int) *InvoiceQuery

func (*InvoiceQuery) Max

func (q *InvoiceQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*InvoiceQuery) Min

func (q *InvoiceQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*InvoiceQuery) New

func (q *InvoiceQuery) New() (*Invoice, error)

New returns an empty Invoice on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*InvoiceQuery) Offset

func (q *InvoiceQuery) Offset(value int) *InvoiceQuery

func (*InvoiceQuery) Oldest

func (q *InvoiceQuery) Oldest(column ...string) *InvoiceQuery

func (*InvoiceQuery) OrDoesntHave

func (q *InvoiceQuery) OrDoesntHave(relation string) *InvoiceQuery

func (*InvoiceQuery) OrHas

func (q *InvoiceQuery) OrHas(relation, operator string, count int) *InvoiceQuery

func (*InvoiceQuery) OrWhere

func (q *InvoiceQuery) OrWhere(column any, args ...any) *InvoiceQuery

OrWhere adds an or-where clause; a func(*InvoiceQuery) in place of the column adds a group.

func (*InvoiceQuery) OrWhereDoesntHave

func (q *InvoiceQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *InvoiceQuery

func (*InvoiceQuery) OrWhereHas

func (q *InvoiceQuery) OrWhereHas(relation string, callback func(*query.Builder)) *InvoiceQuery

func (*InvoiceQuery) OrWhereNot

func (q *InvoiceQuery) OrWhereNot(column any, args ...any) *InvoiceQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*InvoiceQuery) OrWhereRelation

func (q *InvoiceQuery) OrWhereRelation(relation string, column any, args ...any) *InvoiceQuery

func (*InvoiceQuery) OrderBy

func (q *InvoiceQuery) OrderBy(column any, direction ...string) *InvoiceQuery

func (*InvoiceQuery) OrderByDesc

func (q *InvoiceQuery) OrderByDesc(column any) *InvoiceQuery

func (*InvoiceQuery) Paginate

func (q *InvoiceQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (InvoiceCollection, *pagination.LengthAwarePage, error)

func (*InvoiceQuery) Pluck

func (q *InvoiceQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*InvoiceQuery) Select

func (q *InvoiceQuery) Select(columns ...any) *InvoiceQuery

func (*InvoiceQuery) SelectRaw

func (q *InvoiceQuery) SelectRaw(expression string, bindings ...any) *InvoiceQuery

func (*InvoiceQuery) SimplePaginate

func (q *InvoiceQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (InvoiceCollection, *pagination.Page, error)

func (*InvoiceQuery) Sole

func (q *InvoiceQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Invoice, error)

func (*InvoiceQuery) SoleValue

func (q *InvoiceQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*InvoiceQuery) Sum

func (q *InvoiceQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*InvoiceQuery) Touch

func (q *InvoiceQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*InvoiceQuery) Update

func (q *InvoiceQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*InvoiceQuery) UpdateOrCreate

func (q *InvoiceQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Invoice, error)

func (*InvoiceQuery) Upsert

func (q *InvoiceQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*InvoiceQuery) Value

func (q *InvoiceQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*InvoiceQuery) ValueOrFail

func (q *InvoiceQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*InvoiceQuery) Where

func (q *InvoiceQuery) Where(column any, args ...any) *InvoiceQuery

Where adds a where clause; a func(*InvoiceQuery) in place of the column adds a group.

func (*InvoiceQuery) WhereBelongsTo

func (q *InvoiceQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *InvoiceQuery

func (*InvoiceQuery) WhereBetween

func (q *InvoiceQuery) WhereBetween(column any, from, to any) *InvoiceQuery

func (*InvoiceQuery) WhereColumn

func (q *InvoiceQuery) WhereColumn(first any, args ...any) *InvoiceQuery

func (*InvoiceQuery) WhereDoesntHave

func (q *InvoiceQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *InvoiceQuery

func (*InvoiceQuery) WhereExists

func (q *InvoiceQuery) WhereExists(callback func(*query.Builder)) *InvoiceQuery

func (*InvoiceQuery) WhereHas

func (q *InvoiceQuery) WhereHas(relation string, callback func(*query.Builder)) *InvoiceQuery

func (*InvoiceQuery) WhereHasCount

func (q *InvoiceQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *InvoiceQuery

func (*InvoiceQuery) WhereIn

func (q *InvoiceQuery) WhereIn(column any, values []any) *InvoiceQuery

func (*InvoiceQuery) WhereKey

func (q *InvoiceQuery) WhereKey(id any) *InvoiceQuery

func (*InvoiceQuery) WhereNot

func (q *InvoiceQuery) WhereNot(column any, args ...any) *InvoiceQuery

WhereNot adds a negated where clause, or a negated group.

func (*InvoiceQuery) WhereNotExists

func (q *InvoiceQuery) WhereNotExists(callback func(*query.Builder)) *InvoiceQuery

func (*InvoiceQuery) WhereNotIn

func (q *InvoiceQuery) WhereNotIn(column any, values []any) *InvoiceQuery

func (*InvoiceQuery) WhereNotNull

func (q *InvoiceQuery) WhereNotNull(columns ...any) *InvoiceQuery

func (*InvoiceQuery) WhereNull

func (q *InvoiceQuery) WhereNull(columns ...any) *InvoiceQuery

func (*InvoiceQuery) WhereRelation

func (q *InvoiceQuery) WhereRelation(relation string, column any, args ...any) *InvoiceQuery

func (*InvoiceQuery) With

func (q *InvoiceQuery) With(relations ...string) *InvoiceQuery

func (*InvoiceQuery) WithAvg

func (q *InvoiceQuery) WithAvg(relation, column string) *InvoiceQuery

func (*InvoiceQuery) WithCount

func (q *InvoiceQuery) WithCount(relations ...string) *InvoiceQuery

func (*InvoiceQuery) WithExists

func (q *InvoiceQuery) WithExists(relation string) *InvoiceQuery

func (*InvoiceQuery) WithMax

func (q *InvoiceQuery) WithMax(relation, column string) *InvoiceQuery

func (*InvoiceQuery) WithMin

func (q *InvoiceQuery) WithMin(relation, column string) *InvoiceQuery

func (*InvoiceQuery) WithSum

func (q *InvoiceQuery) WithSum(relation, column string) *InvoiceQuery

func (*InvoiceQuery) Without

func (q *InvoiceQuery) Without(relations ...string) *InvoiceQuery

func (*InvoiceQuery) WithoutGlobalScope

func (q *InvoiceQuery) WithoutGlobalScope(identifier string) *InvoiceQuery

func (*InvoiceQuery) WithoutGlobalScopes

func (q *InvoiceQuery) WithoutGlobalScopes(identifiers ...string) *InvoiceQuery

type InvoiceResource

type InvoiceResource struct {
	ID, TenantID, SubscriptionID, PlanID, PlanName, Reference string
	Kind                                                      InvoiceKind
	Status                                                    InvoiceStatus
	Months, RenewalNumber, MaxInstallments                    int
	Subtotal, Discount, Total                                 int64
	CouponCode, Provider, ProviderRef, CheckoutURL            string
	Meta                                                      map[string]string
	PaidAt                                                    *time.Time
	CreatedAt                                                 time.Time
}

InvoiceResource is one invoice as it may leave.

func NewInvoiceResource

func NewInvoiceResource(i Invoice) InvoiceResource

NewInvoiceResource copies an invoice.

func (InvoiceResource) ToArray

func (r InvoiceResource) ToArray() map[string]any

ToArray is the invoice's fields, by name.

func (InvoiceResource) With

func (InvoiceResource) With() map[string]any

With is nothing beside the invoice.

type InvoiceRow

type InvoiceRow struct {
	ID, Tenant, Plan, Period, Subtotal, Discount, Total, Coupon string
	Status, StatusKey, Created, Paid, Provider, ProviderStatus  string
	Installments                                                string
	Open                                                        bool
	URL, PayURL, ConfirmURL, VoidURL                            string
}

InvoiceRow is one invoice as a list shows it.

type InvoiceStatus

type InvoiceStatus string

InvoiceStatus is where an invoice stands.

const (
	// InvoiceOpen waits for its payment.
	InvoiceOpen InvoiceStatus = "open"
	// InvoicePaid was confirmed, once.
	InvoicePaid InvoiceStatus = "paid"
	// InvoiceFailed was refused by the provider; a new checkout issues a new
	// invoice.
	InvoiceFailed InvoiceStatus = "failed"
	// InvoiceCanceled was voided by the admin or replaced.
	InvoiceCanceled InvoiceStatus = "canceled"
)

type InvoicesPageData

type InvoicesPageData struct {
	Screen
	Rows  []InvoiceRow
	Table TableState
}

InvoicesPageData is a page of the account's invoices.

type Labels

type Labels struct {
	Locale string
	// contains filtered or unexported fields
}

Labels are the sentences of this package's screens in one locale.

func (Labels) Errors

func (l Labels) Errors(errs validation.Errors) validation.Errors

Errors are the messages of a rejected input in the labels' locale, field by field. The value given is not changed.

func (Labels) Field

func (l Labels) Field(name string) string

Field is what a person reads in place of an input's name, in a summary of the rejected fields: "coupon" reads "Cupom". A field with no line reads the way hesape's page would have drawn it.

func (Labels) InvoiceStatus

func (l Labels) InvoiceStatus(s InvoiceStatus) string

InvoiceStatus is the label of an invoice's status.

func (Labels) Message

func (l Labels) Message(msg string) string

Message is one validation message in the labels' locale.

The messages are written in English where they are produced -- by this package from its own English lines, by the framework's validation helpers ("is required") and by arandu-wallet -- because validation.Errors carries sentences and not keys, and an API client reads them as they always were. Here each one is read back against the English lines of the "validation" group, placeholders and all, and drawn again from the same key in the locale asked for. A message no line matches comes back as it was.

func (Labels) Months

func (l Labels) Months(n int) string

Months is a period in months as a sentence: "1 mês", "12 meses".

func (Labels) SubscriptionStatus

func (l Labels) SubscriptionStatus(s SubscriptionStatus) string

SubscriptionStatus is the label of a subscription's status.

func (Labels) Summary

func (l Labels) Summary(errs validation.Errors) []string

Summary is one line per rejected message, the field named before it, for the banner above a form: "Cupom: Preencha este campo.". Nil when nothing was rejected, so a layout that ranges over it draws no banner.

func (Labels) T

func (l Labels) T(key string) string

T reads a key of this package: "screen.dashboard_title".

type Listener

type Listener func(ctx context.Context, e Event) error

Listener is told about each Event, inside the transaction of the act.

type ManualPayment

type ManualPayment struct {
	// Method is how it was paid: "pix", "transfer".
	Method string
	// Reference is the bank's identifier: the Pix end-to-end id.
	Reference string
	// PaidAt is when it was paid; zero is now.
	PaidAt time.Time
}

ManualPayment is what the admin records when a payment arrived outside a gateway: a Pix seen on the bank statement, a transfer.

type ManualProvider

type ManualProvider struct {
	// Instructions is what the invoice page tells the customer to do, in the
	// application's words. Empty draws the catalogue's general sentence.
	Instructions string
}

ManualProvider is the gateway-free provider: no page, no notification. The checkout sends the customer to the invoice page, where the application's Instructions say how to pay -- a Pix key, a bank transfer -- and the admin confirms the payment by hand on the admin's invoices screen.

func (ManualProvider) CreateCheckout

CreateCheckout answers no page: the customer is shown the invoice.

func (ManualProvider) Name

func (ManualProvider) Name() string

Name is ManualProviderName.

func (ManualProvider) ParseNotification

func (ManualProvider) ParseNotification(*http.Request) (Notification, error)

ParseNotification refuses every request: a manual payment is confirmed by the admin, never posted.

func (ManualProvider) PaymentInstructions

func (p ManualProvider) PaymentInstructions() string

PaymentInstructions is the text the invoice page shows.

func (ManualProvider) QueryStatus

QueryStatus answers pending: only the admin knows a manual payment arrived.

type Meta

type Meta map[string]string

Meta is a set of names and values the consumer attaches, held as JSON text.

func (*Meta) Scan

func (m *Meta) Scan(value any) error

Scan reads the set back from its JSON text.

func (Meta) Value

func (m Meta) Value() (driver.Value, error)

Value writes the set as a JSON object; an empty set is "{}".

type Module

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

Module is what the application registers.

func New

func New(cfg Config, db *data.DB, sessions *security.SessionStore) (*Module, error)

New returns the module, or the reason it cannot be built.

func (*Module) AccountRoutes

func (m *Module) AccountRoutes(r *fhttp.Router)

AccountRoutes registers the account's routes alone, under Prefix, for an application that mounts them inside its own customer panel with that side's guards on r.

func (*Module) AdminRoutes

func (m *Module) AdminRoutes(r *fhttp.Router)

AdminRoutes registers the admin's routes alone, under AdminPrefix, for an application that mounts them inside its operator console.

func (*Module) Boot

func (m *Module) Boot(context.Context) error

Boot refuses to serve when a view this package renders is not in the binary, or when the archive would publish a file outside the module's directory.

func (*Module) CSRFExemptPaths

func (m *Module) CSRFExemptPaths() []string

CSRFExemptPaths exempts the notification address from the CSRF check: a gateway posts from its own servers, with no token to send.

func (*Module) Labels

func (m *Module) Labels(locale string) Labels

Labels answers the sentences in a locale: the one given, else Config.Locale, else FallbackLocale.

func (*Module) Migrations

func (m *Module) Migrations() []foundation.Migration

Migrations declares the schema this module owns, in the order the names sort in, which is the order they apply in.

func (*Module) Name

func (m *Module) Name() string

Name is the module identifier.

func (*Module) NotificationRoutes

func (m *Module) NotificationRoutes(r *fhttp.Router)

NotificationRoutes registers the notification address alone: POST NotificationPrefix + "/{provider}", one per configured provider, for an application that mounts it on its own API side.

func (*Module) Publishes

func (m *Module) Publishes() []foundation.Publication

Publishes declares the files this package offers, each at the path it takes relative to the root of the project.

One tree, under one tag. A publication may carry a page, a component, a configuration file, a migration, a catalogue of sentences or an asset, and this package offers the first of those and nothing else. Each absence is a decision rather than an omission:

  • configuration is the Config struct New is handed, checked by the compiler and validated before the module exists. A file copied into the project beside it would be a second place to say the same thing, and only one of the two could be the one the code reads.
  • a stylesheet, a script or any other asset is registered with the view layer and served from an address derived from its own bytes. Copying one into the project would put a second copy of those bytes under a second address, and a page can only reference one of them.
  • translations are overridden by writing the lines the application wants into its own override tree, which the catalogue loader already reads. A copy of every line this package ships is a copy that goes stale, and it goes stale without saying so.
  • migrations are declared and collected, never copied. A copy in the project's own migration directory is found by the runner as well, so one schema change applies twice under two names.

What is left is the markup, and it is here for the reason the others are not: it is the one thing the project is expected to edit. A package cannot know what a screen should say in a product it has never seen.

func (*Module) Routes

func (m *Module) Routes(r *fhttp.Router)

Routes registers every route of the module: the account's, the admin's and the gateways' notification address.

func (*Module) Schedule

func (m *Module) Schedule() []foundation.Task

Schedule declares the sweep that moves the subscriptions whose period ended: every fifteen minutes, on one replica.

func (*Module) Service

func (m *Module) Service() *BillingService

Service is the use cases, for an application that calls them from its own code: its own pages, a job, the engine's sync. Every method asks the policy, so handing it out opens nothing.

func (*Module) URLs

func (m *Module) URLs() URLs

URLs answers the addresses the module is mounted at, for an application that links to them from its own pages.

type Notification

type Notification struct {
	// InvoiceID is the order number the checkout was given. Either it or
	// Reference is required.
	InvoiceID string
	// Reference is the gateway's own identifier of the order or payment.
	Reference string
	// Fields are whatever else the Provider wants QueryStatus to see.
	Fields map[string]string
}

Notification is what a gateway posted, as its Provider read it.

type Page

type Page[T any] struct {
	// Rows are the page's rows.
	Rows []T
	// Total is how many rows the whole list holds.
	Total int
	// Page is the page shown, from 1.
	Page int
	// PerPage is how many rows a page holds.
	PerPage int
	// Pages is how many pages the list has.
	Pages int
}

Page is one page of a list, with what a data table draws around it.

type PageQuery

type PageQuery struct {
	// Search is the text typed in the search box.
	Search string
	// Status narrows the list to one status; empty is every one.
	Status string
	// Sort is a column key of the list's allowlist; empty is its default.
	Sort string
	// Dir is "asc" or "desc"; empty is the list's default.
	Dir string
	// Page is the page asked for, from 1.
	Page int
	// PerPage is how many rows a page holds; zero or above MaxPageSize is the
	// module's page size.
	PerPage int
}

PageQuery is what a data table asks for.

type Paths

type Paths struct {
	Plans, Checkout, Trial, Subscriptions, Renewal, Cancellation string
	Invoices, Return, Admin, Coupons, Payment                    string
}

Paths are the segments the routes of this package are built from. Each one starts with "/", ends without one and holds no wildcard.

GET    Prefix + Plans                                the catalogue
POST   Prefix + Plans + /{id} + Checkout             pay for a plan
POST   Prefix + Plans + /{id} + Trial                start its trial
GET    Prefix + Subscriptions                        the account's subscriptions
POST   Prefix + Subscriptions + /{id} + Renewal      pay the next period
POST   Prefix + Subscriptions + /{id} + Cancellation stop at the period's end
DELETE Prefix + Subscriptions + /{id} + Cancellation take that back
GET    Prefix + Invoices                             the account's invoices
GET    Prefix + Invoices + /{id}                     one invoice
GET    Prefix + Invoices + /{id} + Return            back from the gateway

and under AdminPrefix: Plans (with /{id}), Coupons (with /{id}), Subscriptions (with Cancellation) and Invoices (with Payment and Cancellation).

type Payment

type Payment struct {
	model.Model

	// ID is the identifier, written by the application.
	ID string `db:"id"`
	// TenantID is the account that paid.
	TenantID string `db:"tenant_id"`
	// InvoiceID is the invoice paid.
	InvoiceID string `db:"invoice_id"`
	// Provider is the provider that collected it, or ManualProviderName.
	Provider string `db:"provider"`
	// ProviderRef is the provider's identifier of the payment.
	ProviderRef string `db:"provider_ref"`
	// Method is how it was paid, in the provider's words: "credit_card",
	// "pix".
	Method string `db:"method"`
	// Installments is how many installments the customer chose.
	Installments int `db:"installments"`
	// Amount is what was paid, in centavos.
	Amount int64 `db:"amount"`
	// PaidAt is when it was paid, in UTC.
	PaidAt time.Time `db:"paid_at"`
	// ConfirmedBy is who confirmed it: "provider:<name>" or the admin's id.
	ConfirmedBy string `db:"confirmed_by"`
	// CreatedAt is when the row was written, in UTC.
	CreatedAt time.Time `db:"created_at"`
	// UpdatedAt is when the row last changed, in UTC.
	UpdatedAt time.Time `db:"updated_at"`
}

Payment is the confirmation of one invoice. There is one per invoice at most, and the unique index on invoice_id is what makes a confirmation happen once however many notifications arrive.

func (*Payment) Fresh

func (row *Payment) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Payment, error)

Fresh reads the row again, as a new Payment; it shadows the untyped one the embedded model promotes.

func (*Payment) Replicate

func (row *Payment) Replicate(except ...string) (*Payment, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

type PaymentCollection

type PaymentCollection []*Payment

PaymentCollection is rows of Payment, as a query returns them.

func PaymentCollectionOf

func PaymentCollectionOf(rows model.Rows) PaymentCollection

PaymentCollectionOf converts rows of the table of Payment. A nil input is a nil collection.

func (PaymentCollection) Contains

func (c PaymentCollection) Contains(key any) bool

func (PaymentCollection) Except

func (c PaymentCollection) Except(keys ...any) PaymentCollection

func (PaymentCollection) Find

func (c PaymentCollection) Find(key any) *Payment

func (PaymentCollection) FindOrFail

func (c PaymentCollection) FindOrFail(key any) (*Payment, error)

func (PaymentCollection) Fresh

func (PaymentCollection) Load

func (c PaymentCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (PaymentCollection) LoadCount

func (c PaymentCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (PaymentCollection) LoadMissing

func (c PaymentCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (PaymentCollection) ModelKeys

func (c PaymentCollection) ModelKeys() []any

func (PaymentCollection) Only

func (c PaymentCollection) Only(keys ...any) PaymentCollection

func (PaymentCollection) Pluck

func (c PaymentCollection) Pluck(column string) []any

func (PaymentCollection) Rows

func (c PaymentCollection) Rows() model.Rows

Rows converts the collection back to the core's rows.

func (PaymentCollection) ToArray

func (c PaymentCollection) ToArray() []map[string]any

func (PaymentCollection) Unique

type PaymentQuery

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

PaymentQuery is a query on the table of Payment.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Payment rows or a value; there is no way to run one without a Grant.

func Payments

func Payments(db model.DB) *PaymentQuery

Payments starts a query on the table of Payment, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*PaymentQuery) AddSelect

func (q *PaymentQuery) AddSelect(columns ...any) *PaymentQuery

func (*PaymentQuery) Avg

func (q *PaymentQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*PaymentQuery) Base

func (q *PaymentQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*PaymentQuery) Chunk

func (q *PaymentQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(PaymentCollection, int) (bool, error)) error

func (*PaymentQuery) Clone

func (q *PaymentQuery) Clone() *PaymentQuery

Clone returns an independent copy of the query.

func (*PaymentQuery) Count

func (q *PaymentQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*PaymentQuery) Create

func (q *PaymentQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Payment, error)

func (*PaymentQuery) Cursor

func (q *PaymentQuery) Cursor(ctx context.Context, g auth.Grant) iter.Seq2[*Payment, error]

func (*PaymentQuery) CursorPaginate

func (q *PaymentQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (PaymentCollection, *pagination.CursorPage, error)

func (*PaymentQuery) Decrement

func (q *PaymentQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*PaymentQuery) Delete

func (q *PaymentQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*PaymentQuery) DoesntExist

func (q *PaymentQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*PaymentQuery) DoesntHave

func (q *PaymentQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *PaymentQuery

func (*PaymentQuery) Each

func (q *PaymentQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*Payment, int) (bool, error)) error

func (*PaymentQuery) Exists

func (q *PaymentQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*PaymentQuery) Find

func (q *PaymentQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Payment, error)

func (*PaymentQuery) FindMany

func (q *PaymentQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (PaymentCollection, error)

func (*PaymentQuery) FindOrFail

func (q *PaymentQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Payment, error)

func (*PaymentQuery) FindOrNew

func (q *PaymentQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Payment, error)

func (*PaymentQuery) First

func (q *PaymentQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Payment, error)

First returns the first row, or nil and no error when there is none.

func (*PaymentQuery) FirstOrCreate

func (q *PaymentQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Payment, error)

func (*PaymentQuery) FirstOrFail

func (q *PaymentQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Payment, error)

func (*PaymentQuery) FirstOrNew

func (q *PaymentQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Payment, error)

func (*PaymentQuery) FirstWhere

func (q *PaymentQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Payment, error)

func (*PaymentQuery) ForPage

func (q *PaymentQuery) ForPage(page, perPage int) *PaymentQuery

func (*PaymentQuery) ForceCreate

func (q *PaymentQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Payment, error)

func (*PaymentQuery) Get

func (q *PaymentQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (PaymentCollection, error)

Get runs the query and returns the rows.

func (*PaymentQuery) GroupBy

func (q *PaymentQuery) GroupBy(groups ...any) *PaymentQuery

func (*PaymentQuery) Has

func (q *PaymentQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *PaymentQuery

func (*PaymentQuery) Increment

func (q *PaymentQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*PaymentQuery) Insert

func (q *PaymentQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*PaymentQuery) InsertOrIgnore

func (q *PaymentQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*PaymentQuery) Join

func (q *PaymentQuery) Join(table any, first any, args ...any) *PaymentQuery

func (*PaymentQuery) Latest

func (q *PaymentQuery) Latest(column ...string) *PaymentQuery

func (*PaymentQuery) Limit

func (q *PaymentQuery) Limit(value int) *PaymentQuery

func (*PaymentQuery) Max

func (q *PaymentQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*PaymentQuery) Min

func (q *PaymentQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*PaymentQuery) New

func (q *PaymentQuery) New() (*Payment, error)

New returns an empty Payment on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*PaymentQuery) Offset

func (q *PaymentQuery) Offset(value int) *PaymentQuery

func (*PaymentQuery) Oldest

func (q *PaymentQuery) Oldest(column ...string) *PaymentQuery

func (*PaymentQuery) OrDoesntHave

func (q *PaymentQuery) OrDoesntHave(relation string) *PaymentQuery

func (*PaymentQuery) OrHas

func (q *PaymentQuery) OrHas(relation, operator string, count int) *PaymentQuery

func (*PaymentQuery) OrWhere

func (q *PaymentQuery) OrWhere(column any, args ...any) *PaymentQuery

OrWhere adds an or-where clause; a func(*PaymentQuery) in place of the column adds a group.

func (*PaymentQuery) OrWhereDoesntHave

func (q *PaymentQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *PaymentQuery

func (*PaymentQuery) OrWhereHas

func (q *PaymentQuery) OrWhereHas(relation string, callback func(*query.Builder)) *PaymentQuery

func (*PaymentQuery) OrWhereNot

func (q *PaymentQuery) OrWhereNot(column any, args ...any) *PaymentQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*PaymentQuery) OrWhereRelation

func (q *PaymentQuery) OrWhereRelation(relation string, column any, args ...any) *PaymentQuery

func (*PaymentQuery) OrderBy

func (q *PaymentQuery) OrderBy(column any, direction ...string) *PaymentQuery

func (*PaymentQuery) OrderByDesc

func (q *PaymentQuery) OrderByDesc(column any) *PaymentQuery

func (*PaymentQuery) Paginate

func (q *PaymentQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (PaymentCollection, *pagination.LengthAwarePage, error)

func (*PaymentQuery) Pluck

func (q *PaymentQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*PaymentQuery) Select

func (q *PaymentQuery) Select(columns ...any) *PaymentQuery

func (*PaymentQuery) SelectRaw

func (q *PaymentQuery) SelectRaw(expression string, bindings ...any) *PaymentQuery

func (*PaymentQuery) SimplePaginate

func (q *PaymentQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (PaymentCollection, *pagination.Page, error)

func (*PaymentQuery) Sole

func (q *PaymentQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Payment, error)

func (*PaymentQuery) SoleValue

func (q *PaymentQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*PaymentQuery) Sum

func (q *PaymentQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*PaymentQuery) Touch

func (q *PaymentQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*PaymentQuery) Update

func (q *PaymentQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*PaymentQuery) UpdateOrCreate

func (q *PaymentQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Payment, error)

func (*PaymentQuery) Upsert

func (q *PaymentQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*PaymentQuery) Value

func (q *PaymentQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*PaymentQuery) ValueOrFail

func (q *PaymentQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*PaymentQuery) Where

func (q *PaymentQuery) Where(column any, args ...any) *PaymentQuery

Where adds a where clause; a func(*PaymentQuery) in place of the column adds a group.

func (*PaymentQuery) WhereBelongsTo

func (q *PaymentQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *PaymentQuery

func (*PaymentQuery) WhereBetween

func (q *PaymentQuery) WhereBetween(column any, from, to any) *PaymentQuery

func (*PaymentQuery) WhereColumn

func (q *PaymentQuery) WhereColumn(first any, args ...any) *PaymentQuery

func (*PaymentQuery) WhereDoesntHave

func (q *PaymentQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *PaymentQuery

func (*PaymentQuery) WhereExists

func (q *PaymentQuery) WhereExists(callback func(*query.Builder)) *PaymentQuery

func (*PaymentQuery) WhereHas

func (q *PaymentQuery) WhereHas(relation string, callback func(*query.Builder)) *PaymentQuery

func (*PaymentQuery) WhereHasCount

func (q *PaymentQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *PaymentQuery

func (*PaymentQuery) WhereIn

func (q *PaymentQuery) WhereIn(column any, values []any) *PaymentQuery

func (*PaymentQuery) WhereKey

func (q *PaymentQuery) WhereKey(id any) *PaymentQuery

func (*PaymentQuery) WhereNot

func (q *PaymentQuery) WhereNot(column any, args ...any) *PaymentQuery

WhereNot adds a negated where clause, or a negated group.

func (*PaymentQuery) WhereNotExists

func (q *PaymentQuery) WhereNotExists(callback func(*query.Builder)) *PaymentQuery

func (*PaymentQuery) WhereNotIn

func (q *PaymentQuery) WhereNotIn(column any, values []any) *PaymentQuery

func (*PaymentQuery) WhereNotNull

func (q *PaymentQuery) WhereNotNull(columns ...any) *PaymentQuery

func (*PaymentQuery) WhereNull

func (q *PaymentQuery) WhereNull(columns ...any) *PaymentQuery

func (*PaymentQuery) WhereRelation

func (q *PaymentQuery) WhereRelation(relation string, column any, args ...any) *PaymentQuery

func (*PaymentQuery) With

func (q *PaymentQuery) With(relations ...string) *PaymentQuery

func (*PaymentQuery) WithAvg

func (q *PaymentQuery) WithAvg(relation, column string) *PaymentQuery

func (*PaymentQuery) WithCount

func (q *PaymentQuery) WithCount(relations ...string) *PaymentQuery

func (*PaymentQuery) WithExists

func (q *PaymentQuery) WithExists(relation string) *PaymentQuery

func (*PaymentQuery) WithMax

func (q *PaymentQuery) WithMax(relation, column string) *PaymentQuery

func (*PaymentQuery) WithMin

func (q *PaymentQuery) WithMin(relation, column string) *PaymentQuery

func (*PaymentQuery) WithSum

func (q *PaymentQuery) WithSum(relation, column string) *PaymentQuery

func (*PaymentQuery) Without

func (q *PaymentQuery) Without(relations ...string) *PaymentQuery

func (*PaymentQuery) WithoutGlobalScope

func (q *PaymentQuery) WithoutGlobalScope(identifier string) *PaymentQuery

func (*PaymentQuery) WithoutGlobalScopes

func (q *PaymentQuery) WithoutGlobalScopes(identifiers ...string) *PaymentQuery

type PaymentState

type PaymentState string

PaymentState is where a gateway says a payment stands.

const (
	// StatePending is not paid yet.
	StatePending PaymentState = "pending"
	// StatePaid is paid; it confirms the invoice when Amount is its Total.
	StatePaid PaymentState = "paid"
	// StateFailed was refused or abandoned; the invoice is marked failed.
	StateFailed PaymentState = "failed"
	// StateRefunded was paid and given back. An invoice already paid is left
	// as it is and the state is recorded; refunds are the admin's to handle.
	StateRefunded PaymentState = "refunded"
)

type PaymentStatus

type PaymentStatus struct {
	// State is where the payment stands.
	State PaymentState
	// Amount is what was paid, in centavos.
	Amount int64
	// Method is how: "credit_card", "debit_card", "pix", "boleto".
	Method string
	// Installments is how many installments the customer chose.
	Installments int
	// Reference is the gateway's identifier of the payment.
	Reference string
	// PaidAt is when it was paid; zero is now.
	PaidAt time.Time
	// Raw is the gateway's own word for the state, recorded on the invoice.
	Raw string
}

PaymentStatus is a gateway's answer about one payment.

type Period

type Period struct {
	// Start is when the period begins.
	Start time.Time
	// End is the instant the subscription is paid until.
	End time.Time
}

Period is the stretch of time one payment buys.

func NextPeriod

func NextPeriod(s *Subscription, paidAt time.Time, months int) Period

NextPeriod is what a payment made at paidAt buys for the subscription, for months months:

  • a subscription that does not exist yet, or that ended (canceled, expired), starts again on the day of the payment;
  • a trial paid for keeps its free days and the period follows them;
  • an active subscription renewed early is extended from the day it is paid until, so no day already paid for is lost;
  • a subscription past due is extended from the day it was paid until, so the days of grace it was served are the first days of the new period -- unless even that end would already be behind the payment, and then the period starts at the payment;
  • a trial or an active subscription whose end the sweep has not reached yet, though it is behind the payment, starts again at the payment.

type Plan

type Plan struct {
	model.Model

	// ID is the identifier, written by the application.
	ID string `db:"id"`
	// Slug is the stable name an application refers to the plan by in its own
	// code and seeders: "camera-mensal". Unique across the catalogue.
	Slug string `db:"slug"`
	// Name is what a customer reads.
	Name string `db:"name"`
	// Description is the sentence under the name.
	Description string `db:"description"`
	// Features are the lines listed under the price, in order.
	Features StringList `db:"features"`
	// Price is what one period costs, in centavos of BRL.
	Price int64 `db:"price"`
	// IntervalMonths is how many months one payment buys.
	IntervalMonths int `db:"interval_months"`
	// TrialDays is how long a trial lasts. Zero offers none.
	TrialDays int `db:"trial_days"`
	// GraceDays is how long a subscription stays past due after its period
	// ends without a payment, before it expires. Zero expires it at once.
	GraceDays int `db:"grace_days"`
	// InstallmentsFrom is the smallest IntervalMonths that may be paid in
	// installments. Zero never offers installments.
	InstallmentsFrom int `db:"installments_from"`
	// InstallmentsCap is the most installments offered, never above
	// MaxInstallments. Zero means MaxInstallments.
	InstallmentsCap int `db:"installments_cap"`
	// Meta is what the consuming application attaches to the plan: the
	// cameras it covers, the credits it deposits. This package stores it and
	// hands it back in every event, and decides nothing from it.
	Meta Meta `db:"meta"`
	// Active says the plan is offered. An inactive plan keeps its
	// subscriptions and takes no new one.
	Active Flag `db:"active"`
	// Position orders the plans on the customer's screen, smallest first.
	Position int `db:"position"`
	// CreatedAt is when the row was written, in UTC.
	CreatedAt time.Time `db:"created_at"`
	// UpdatedAt is when the row last changed, in UTC.
	UpdatedAt time.Time `db:"updated_at"`
}

Plan is one offer of the catalogue: what a customer subscribes to, for how many months, at what price.

The catalogue is the platform's and not a customer's, so the table is Global: every tenant reads the same plans, and only the platform's admin writes them. The price, the months and every other number a business person changes live in these rows -- an application fills them from its own seeder or from the admin's screen, never from a constant in code.

Plans, PlanQuery and PlanCollection are generated beside this file, in PlanQuery.go, by aru model:build.

func (*Plan) Fresh

func (row *Plan) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Plan, error)

Fresh reads the row again, as a new Plan; it shadows the untyped one the embedded model promotes.

func (Plan) Installments

func (p Plan) Installments() int

Installments is how many installments the plan may be paid in: one unless its period is at least InstallmentsFrom months, and then up to one per month of the period, never more than InstallmentsCap or MaxInstallments.

InstallmentsFrom 6, IntervalMonths 3  -> 1
InstallmentsFrom 6, IntervalMonths 6  -> 6
InstallmentsFrom 6, IntervalMonths 24 -> 12

func (*Plan) Replicate

func (row *Plan) Replicate(except ...string) (*Plan, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

type PlanCard

type PlanCard struct {
	ID, Name, Description, Price, Period, Installments string
	Features                                           []string
	TrialDays                                          int
	CheckoutURL, TrialURL                              string
}

PlanCard is one plan as the catalogue shows it.

type PlanCollection

type PlanCollection []*Plan

PlanCollection is rows of Plan, as a query returns them.

func PlanCollectionOf

func PlanCollectionOf(rows model.Rows) PlanCollection

PlanCollectionOf converts rows of the table of Plan. A nil input is a nil collection.

func (PlanCollection) Contains

func (c PlanCollection) Contains(key any) bool

func (PlanCollection) Except

func (c PlanCollection) Except(keys ...any) PlanCollection

func (PlanCollection) Find

func (c PlanCollection) Find(key any) *Plan

func (PlanCollection) FindOrFail

func (c PlanCollection) FindOrFail(key any) (*Plan, error)

func (PlanCollection) Fresh

func (c PlanCollection) Fresh(ctx context.Context, g auth.Grant, with ...string) (PlanCollection, error)

func (PlanCollection) Load

func (c PlanCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (PlanCollection) LoadCount

func (c PlanCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (PlanCollection) LoadMissing

func (c PlanCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (PlanCollection) ModelKeys

func (c PlanCollection) ModelKeys() []any

func (PlanCollection) Only

func (c PlanCollection) Only(keys ...any) PlanCollection

func (PlanCollection) Pluck

func (c PlanCollection) Pluck(column string) []any

func (PlanCollection) Rows

func (c PlanCollection) Rows() model.Rows

Rows converts the collection back to the core's rows.

func (PlanCollection) ToArray

func (c PlanCollection) ToArray() []map[string]any

func (PlanCollection) Unique

func (c PlanCollection) Unique() PlanCollection

type PlanForm

type PlanForm struct {
	Name, Slug, Description, Features, Price, IntervalMonths, TrialDays string
	GraceDays, InstallmentsFrom, InstallmentsCap, Position, Meta        string
	Active                                                              bool
}

PlanForm is a plan's form, as text the fields draw.

type PlanQuery

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

PlanQuery is a query on the table of Plan.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Plan rows or a value; there is no way to run one without a Grant.

func Plans

func Plans(db model.DB) *PlanQuery

Plans starts a query on the table of Plan, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*PlanQuery) AddSelect

func (q *PlanQuery) AddSelect(columns ...any) *PlanQuery

func (*PlanQuery) Avg

func (q *PlanQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*PlanQuery) Base

func (q *PlanQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*PlanQuery) Chunk

func (q *PlanQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(PlanCollection, int) (bool, error)) error

func (*PlanQuery) Clone

func (q *PlanQuery) Clone() *PlanQuery

Clone returns an independent copy of the query.

func (*PlanQuery) Count

func (q *PlanQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*PlanQuery) Create

func (q *PlanQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Plan, error)

func (*PlanQuery) Cursor

func (q *PlanQuery) Cursor(ctx context.Context, g auth.Grant) iter.Seq2[*Plan, error]

func (*PlanQuery) CursorPaginate

func (q *PlanQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (PlanCollection, *pagination.CursorPage, error)

func (*PlanQuery) Decrement

func (q *PlanQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*PlanQuery) Delete

func (q *PlanQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*PlanQuery) DoesntExist

func (q *PlanQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*PlanQuery) DoesntHave

func (q *PlanQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *PlanQuery

func (*PlanQuery) Each

func (q *PlanQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*Plan, int) (bool, error)) error

func (*PlanQuery) Exists

func (q *PlanQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*PlanQuery) Find

func (q *PlanQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Plan, error)

func (*PlanQuery) FindMany

func (q *PlanQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (PlanCollection, error)

func (*PlanQuery) FindOrFail

func (q *PlanQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Plan, error)

func (*PlanQuery) FindOrNew

func (q *PlanQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Plan, error)

func (*PlanQuery) First

func (q *PlanQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Plan, error)

First returns the first row, or nil and no error when there is none.

func (*PlanQuery) FirstOrCreate

func (q *PlanQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Plan, error)

func (*PlanQuery) FirstOrFail

func (q *PlanQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Plan, error)

func (*PlanQuery) FirstOrNew

func (q *PlanQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Plan, error)

func (*PlanQuery) FirstWhere

func (q *PlanQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Plan, error)

func (*PlanQuery) ForPage

func (q *PlanQuery) ForPage(page, perPage int) *PlanQuery

func (*PlanQuery) ForceCreate

func (q *PlanQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Plan, error)

func (*PlanQuery) Get

func (q *PlanQuery) Get(ctx context.Context, g auth.Grant, columns ...any) (PlanCollection, error)

Get runs the query and returns the rows.

func (*PlanQuery) GroupBy

func (q *PlanQuery) GroupBy(groups ...any) *PlanQuery

func (*PlanQuery) Has

func (q *PlanQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *PlanQuery

func (*PlanQuery) Increment

func (q *PlanQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*PlanQuery) Insert

func (q *PlanQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*PlanQuery) InsertOrIgnore

func (q *PlanQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*PlanQuery) Join

func (q *PlanQuery) Join(table any, first any, args ...any) *PlanQuery

func (*PlanQuery) Latest

func (q *PlanQuery) Latest(column ...string) *PlanQuery

func (*PlanQuery) Limit

func (q *PlanQuery) Limit(value int) *PlanQuery

func (*PlanQuery) Max

func (q *PlanQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*PlanQuery) Min

func (q *PlanQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*PlanQuery) New

func (q *PlanQuery) New() (*Plan, error)

New returns an empty Plan on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*PlanQuery) Offset

func (q *PlanQuery) Offset(value int) *PlanQuery

func (*PlanQuery) Oldest

func (q *PlanQuery) Oldest(column ...string) *PlanQuery

func (*PlanQuery) OrDoesntHave

func (q *PlanQuery) OrDoesntHave(relation string) *PlanQuery

func (*PlanQuery) OrHas

func (q *PlanQuery) OrHas(relation, operator string, count int) *PlanQuery

func (*PlanQuery) OrWhere

func (q *PlanQuery) OrWhere(column any, args ...any) *PlanQuery

OrWhere adds an or-where clause; a func(*PlanQuery) in place of the column adds a group.

func (*PlanQuery) OrWhereDoesntHave

func (q *PlanQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *PlanQuery

func (*PlanQuery) OrWhereHas

func (q *PlanQuery) OrWhereHas(relation string, callback func(*query.Builder)) *PlanQuery

func (*PlanQuery) OrWhereNot

func (q *PlanQuery) OrWhereNot(column any, args ...any) *PlanQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*PlanQuery) OrWhereRelation

func (q *PlanQuery) OrWhereRelation(relation string, column any, args ...any) *PlanQuery

func (*PlanQuery) OrderBy

func (q *PlanQuery) OrderBy(column any, direction ...string) *PlanQuery

func (*PlanQuery) OrderByDesc

func (q *PlanQuery) OrderByDesc(column any) *PlanQuery

func (*PlanQuery) Paginate

func (q *PlanQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (PlanCollection, *pagination.LengthAwarePage, error)

func (*PlanQuery) Pluck

func (q *PlanQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*PlanQuery) Select

func (q *PlanQuery) Select(columns ...any) *PlanQuery

func (*PlanQuery) SelectRaw

func (q *PlanQuery) SelectRaw(expression string, bindings ...any) *PlanQuery

func (*PlanQuery) SimplePaginate

func (q *PlanQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (PlanCollection, *pagination.Page, error)

func (*PlanQuery) Sole

func (q *PlanQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Plan, error)

func (*PlanQuery) SoleValue

func (q *PlanQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*PlanQuery) Sum

func (q *PlanQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*PlanQuery) Touch

func (q *PlanQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*PlanQuery) Update

func (q *PlanQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*PlanQuery) UpdateOrCreate

func (q *PlanQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Plan, error)

func (*PlanQuery) Upsert

func (q *PlanQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*PlanQuery) Value

func (q *PlanQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*PlanQuery) ValueOrFail

func (q *PlanQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*PlanQuery) Where

func (q *PlanQuery) Where(column any, args ...any) *PlanQuery

Where adds a where clause; a func(*PlanQuery) in place of the column adds a group.

func (*PlanQuery) WhereBelongsTo

func (q *PlanQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *PlanQuery

func (*PlanQuery) WhereBetween

func (q *PlanQuery) WhereBetween(column any, from, to any) *PlanQuery

func (*PlanQuery) WhereColumn

func (q *PlanQuery) WhereColumn(first any, args ...any) *PlanQuery

func (*PlanQuery) WhereDoesntHave

func (q *PlanQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *PlanQuery

func (*PlanQuery) WhereExists

func (q *PlanQuery) WhereExists(callback func(*query.Builder)) *PlanQuery

func (*PlanQuery) WhereHas

func (q *PlanQuery) WhereHas(relation string, callback func(*query.Builder)) *PlanQuery

func (*PlanQuery) WhereHasCount

func (q *PlanQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *PlanQuery

func (*PlanQuery) WhereIn

func (q *PlanQuery) WhereIn(column any, values []any) *PlanQuery

func (*PlanQuery) WhereKey

func (q *PlanQuery) WhereKey(id any) *PlanQuery

func (*PlanQuery) WhereNot

func (q *PlanQuery) WhereNot(column any, args ...any) *PlanQuery

WhereNot adds a negated where clause, or a negated group.

func (*PlanQuery) WhereNotExists

func (q *PlanQuery) WhereNotExists(callback func(*query.Builder)) *PlanQuery

func (*PlanQuery) WhereNotIn

func (q *PlanQuery) WhereNotIn(column any, values []any) *PlanQuery

func (*PlanQuery) WhereNotNull

func (q *PlanQuery) WhereNotNull(columns ...any) *PlanQuery

func (*PlanQuery) WhereNull

func (q *PlanQuery) WhereNull(columns ...any) *PlanQuery

func (*PlanQuery) WhereRelation

func (q *PlanQuery) WhereRelation(relation string, column any, args ...any) *PlanQuery

func (*PlanQuery) With

func (q *PlanQuery) With(relations ...string) *PlanQuery

func (*PlanQuery) WithAvg

func (q *PlanQuery) WithAvg(relation, column string) *PlanQuery

func (*PlanQuery) WithCount

func (q *PlanQuery) WithCount(relations ...string) *PlanQuery

func (*PlanQuery) WithExists

func (q *PlanQuery) WithExists(relation string) *PlanQuery

func (*PlanQuery) WithMax

func (q *PlanQuery) WithMax(relation, column string) *PlanQuery

func (*PlanQuery) WithMin

func (q *PlanQuery) WithMin(relation, column string) *PlanQuery

func (*PlanQuery) WithSum

func (q *PlanQuery) WithSum(relation, column string) *PlanQuery

func (*PlanQuery) Without

func (q *PlanQuery) Without(relations ...string) *PlanQuery

func (*PlanQuery) WithoutGlobalScope

func (q *PlanQuery) WithoutGlobalScope(identifier string) *PlanQuery

func (*PlanQuery) WithoutGlobalScopes

func (q *PlanQuery) WithoutGlobalScopes(identifiers ...string) *PlanQuery

type PlanRequest

type PlanRequest struct {
	// Slug is the stable name; empty is derived from Name.
	Slug string
	// Name is what a customer reads.
	Name string
	// Description is the sentence under the name.
	Description string
	// Features are the lines under the price.
	Features []string
	// Price is what one period costs, in centavos.
	Price int64
	// IntervalMonths is how many months one payment buys.
	IntervalMonths int
	// TrialDays is the trial's length; zero offers none.
	TrialDays int
	// GraceDays is how long a lapsed subscription stays past due.
	GraceDays int
	// InstallmentsFrom is the smallest period paid in installments; zero
	// never.
	InstallmentsFrom int
	// InstallmentsCap is the most installments; zero is MaxInstallments.
	InstallmentsCap int
	// Meta is the consumer's own facts about the plan.
	Meta Meta
	// Active says the plan is offered.
	Active bool
	// Position orders the plans.
	Position int
}

PlanRequest is the input contract for a plan of the catalogue.

The fields are explicit and there is no mass assignment, so a request body cannot write a column nobody meant to expose.

func (PlanRequest) Validate

func (r PlanRequest) Validate() validation.Errors

Validate reports the errors per field.

type PlanResource

type PlanResource struct {
	ID, Slug, Name, Description      string
	Features                         []string
	Price                            int64
	IntervalMonths, TrialDays        int
	GraceDays, InstallmentsFrom      int
	InstallmentsCap, MaxInstallments int
	Meta                             map[string]string
	Active                           bool
	Position                         int
	CreatedAt, UpdatedAt             time.Time
}

PlanResource is one plan as it may leave.

func NewPlanResource

func NewPlanResource(p Plan) PlanResource

NewPlanResource copies a plan.

func (PlanResource) ToArray

func (r PlanResource) ToArray() map[string]any

ToArray is the plan's fields, by name.

func (PlanResource) With

func (PlanResource) With() map[string]any

With is nothing beside the plan.

type PlanRow

type PlanRow struct {
	ID, Name, Slug, Price, Period, Installments, Trial, Status string
	Active                                                     bool
	URL                                                        string
}

PlanRow is one plan in the admin's catalogue.

type PlansPageData

type PlansPageData struct {
	Screen
	Plans []PlanCard
	// CanSubscribe says the subject may pay for the account; a member who
	// may not reads the plans without the buttons.
	CanSubscribe bool
}

PlansPageData is the catalogue, as an account reads it.

type Provider

type Provider interface {
	// Name is the provider's stable name: what Invoice.Provider records, and
	// the last segment of its notification address. Lowercase letters,
	// digits, - and _.
	Name() string

	// CreateCheckout asks the gateway for a payment page for one invoice.
	CreateCheckout(ctx context.Context, req CheckoutRequest) (Checkout, error)

	// ParseNotification reads the request the gateway posted to the
	// notification address. A request it does not recognise returns an error
	// that wraps ErrBadNotification, and the address answers 400.
	ParseNotification(r *http.Request) (Notification, error)

	// QueryStatus asks the gateway where the payment of one invoice stands.
	QueryStatus(ctx context.Context, q StatusQuery) (PaymentStatus, error)
}

Provider is a payment gateway, as this package uses one.

The package ships no gateway. Each application writes its own as a service of its own -- an app/Services type over the gateway's client -- and hands it to New in Config.Providers. That keeps the gateway's credentials, its client and its contract in the application that holds the merchant account, and keeps every application that installs this package free of gateways it does not use: a gateway built in here could never be removed without breaking them.

The package's side of the contract is what it does with the answers:

  • CreateCheckout is called once per invoice, after the invoice is saved, with the amount this package computed from the catalogue. The customer is sent to Checkout.URL; an empty URL shows the invoice page instead.
  • ParseNotification reads what the gateway posted. Nothing in it is trusted: it only names the invoice (by its ID, the order number the checkout was given) or the gateway's own reference.
  • QueryStatus is asked before anything is confirmed, with the invoice as this package has it, so a forged notification confirms nothing. Only StatePaid with the invoice's Total confirms.
  • Confirmation is idempotent: an invoice is paid once, however many notifications arrive and in whatever order, and a repeated one answers success without doing anything again.

type Quote

type Quote struct {
	// Subtotal is the plan's price, in centavos.
	Subtotal int64
	// Discount is what the coupon takes off, in centavos; never more than
	// Subtotal.
	Discount int64
	// Total is what is charged, in centavos: Subtotal minus Discount.
	Total int64
	// MaxInstallments is the most installments the period may be paid in.
	MaxInstallments int
	// CouponApplied says a coupon took part.
	CouponApplied bool
}

Quote is what one period of a plan costs with a coupon.

func Price

func Price(p Plan, c *Coupon, renewal bool, at time.Time) (Quote, error)

Price is what one period of the plan costs, with the coupon when one is given: checked with CheckCoupon for a first payment, taken as granted for a renewal the subscription still has coupon renewals for.

type Screen

type Screen struct {
	hview.Page
	// Labels are the sentences, in the request's language.
	Labels Labels
	// URLs are the addresses of the package's routes.
	URLs URLs
	// contains filtered or unexported fields
}

Screen is what every page of this package carries: the page hesape's view.New builds, the application's chrome, the sentences, and where the package is mounted. It embeds hesape's view.Page, so it is the hesape/view.Layout an application's layout asserts.

func (Screen) AccountNav

func (s Screen) AccountNav(current string) template.HTML

AccountNav is the bar on top of every screen of an account.

func (Screen) ActiveOptions

func (s Screen) ActiveOptions() []components.SelectOption

ActiveOptions are the two states of a plan or a coupon.

func (Screen) AdminNav

func (s Screen) AdminNav(current string) template.HTML

AdminNav is the bar on top of every admin screen.

func (Screen) All

func (s Screen) All() []string

All is one line per rejected message, the field named by its label.

func (Screen) CellForm

func (s Screen) CellForm(action, method, label, variant string, inputs ...CellInput) template.HTML

CellForm is a small form posted from a table cell: the CSRF token of the page, the fields given, and one button. Every value is escaped. A method other than POST is sent as the _method field the router reads.

func (Screen) Chrome

func (s Screen) Chrome() any

Chrome is what Config.Chrome answered for this screen; nil without one.

func (Screen) CouponKindOptions

func (s Screen) CouponKindOptions() []components.SelectOption

CouponKindOptions are the two kinds of coupon.

func (Screen) ErrorSummary

func (s Screen) ErrorSummary() []string

ErrorSummary is All, under framework/view.Layout's name.

func (Screen) FieldErrors

func (s Screen) FieldErrors(name string) []string

FieldErrors is every message for one field.

func (Screen) Form

func (s Screen) Form() FormState

Form is the form state of the page.

func (Screen) HasErrors

func (s Screen) HasErrors() bool

HasErrors says whether the attempt that landed here was rejected.

func (Screen) InvoiceStatusOptions

func (s Screen) InvoiceStatusOptions() []components.SelectOption

InvoiceStatusOptions are where an invoice can stand.

func (Screen) LogValue

func (s Screen) LogValue() slog.Value

LogValue is the page as a log line carries it, the token redacted.

func (Screen) MarshalJSON

func (s Screen) MarshalJSON() ([]byte, error)

MarshalJSON writes the page with the CSRF token redacted.

func (Screen) SearchLabel

func (s Screen) SearchLabel(table string) string

SearchLabel is the name a screen reader gives a table's search box.

func (Screen) StatusFilter

func (s Screen) StatusFilter(options []components.SelectOption, chosen string) []components.DataTableFilter

StatusFilter is the status filter of a data table, with the option chosen.

func (Screen) SubscriptionStatusOptions

func (s Screen) SubscriptionStatusOptions() []components.SelectOption

SubscriptionStatusOptions are where a subscription can stand.

func (Screen) TableLines

func (s Screen) TableLines() components.DataTableLines

TableLines are the sentences a data table on these screens says.

type StatusQuery

type StatusQuery struct {
	// InvoiceID is the order number.
	InvoiceID string
	// Reference is the gateway's identifier, the one Checkout or a
	// notification gave, empty when there is none yet.
	Reference string
	// Total is the amount the invoice charges, in centavos.
	Total int64
	// Notification is what was posted, when the query follows one.
	Notification *Notification
}

StatusQuery is what QueryStatus is asked about.

type StringList

type StringList []string

StringList is a list of lines held as a JSON array.

func (*StringList) Scan

func (l *StringList) Scan(value any) error

Scan reads the list back from its JSON text.

func (StringList) Value

func (l StringList) Value() (driver.Value, error)

Value writes the list as a JSON array; an empty list is "[]".

type SubscribeRequest

type SubscribeRequest struct {
	// PlanID is the plan to pay for.
	PlanID string
	// CouponCode is the coupon typed, empty for none.
	CouponCode string
	// Reference is what inside the account the subscription pays for, in the
	// application's words; empty is the account itself. It is set by the
	// application's own code, never read from a customer's form by this
	// package.
	Reference string
	// Meta is the application's facts about this checkout.
	Meta Meta
	// Provider is the Name of the provider to collect with; empty is the
	// default.
	Provider string
}

SubscribeRequest is what an account asks for when it pays for a plan.

There is no TenantID here and there must never be one: the account is the one on the Grant, which came from the session.

func (SubscribeRequest) Validate

func (r SubscribeRequest) Validate() validation.Errors

Validate reports the errors per field.

type Subscription

type Subscription struct {
	model.Model

	// ID is the identifier, written by the application.
	ID string `db:"id"`
	// TenantID is the account the subscription belongs to.
	TenantID string `db:"tenant_id"`
	// Reference is what inside the account the subscription pays for, in the
	// consumer's own words ("camera:42"). Empty is the account itself.
	Reference string `db:"reference"`
	// PlanID is the plan subscribed to.
	PlanID string `db:"plan_id"`
	// Status is where the subscription stands.
	Status SubscriptionStatus `db:"status"`
	// CurrentPeriodStart is when the period being served began, in UTC.
	CurrentPeriodStart time.Time `db:"current_period_start"`
	// CurrentPeriodEnd is the instant the subscription is paid until -- "pago
	// até" -- in UTC: the end of the trial while it is trialing.
	CurrentPeriodEnd time.Time `db:"current_period_end"`
	// TrialEndsAt is when the trial ends, nil for a subscription that never
	// had one.
	TrialEndsAt *time.Time `db:"trial_ends_at"`
	// CancelAtPeriodEnd says the customer asked to stop: the subscription is
	// served until CurrentPeriodEnd and then canceled instead of renewed.
	CancelAtPeriodEnd Flag `db:"cancel_at_period_end"`
	// CanceledAt is when the cancellation was asked for, nil when it never was.
	CanceledAt *time.Time `db:"canceled_at"`
	// EndedAt is when the subscription stopped being served, nil while it is.
	EndedAt *time.Time `db:"ended_at"`
	// GraceDays is the plan's grace, copied when the subscription began, so a
	// plan changed later does not move a period already sold.
	GraceDays int `db:"grace_days"`
	// CouponID is the coupon whose discount the renewals keep, empty for none.
	CouponID string `db:"coupon_id"`
	// CouponRenewalsLeft is how many renewals still get that discount.
	CouponRenewalsLeft int `db:"coupon_renewals_left"`
	// Renewals is how many times it was renewed after the first payment.
	Renewals int `db:"renewals"`
	// Meta is what the consumer attached when it started the subscription.
	Meta Meta `db:"meta"`
	// CreatedBy is the user who started it.
	CreatedBy string `db:"created_by"`
	// CreatedAt is when the row was written, in UTC.
	CreatedAt time.Time `db:"created_at"`
	// UpdatedAt is when the row last changed, in UTC.
	UpdatedAt time.Time `db:"updated_at"`
}

Subscription is one account's plan, and the date it is paid until.

It belongs to the tenant -- the customer's Organization -- written from the Grant of whoever subscribed. Reference is the consumer's name for what the subscription pays for inside the account, empty for the account itself.

func (Subscription) Ended

func (s Subscription) Ended() bool

Ended says the subscription stopped and a payment starts a new period from the day it is made.

func (*Subscription) Fresh

func (row *Subscription) Fresh(ctx context.Context, g auth.Grant, with ...string) (*Subscription, error)

Fresh reads the row again, as a new Subscription; it shadows the untyped one the embedded model promotes.

func (*Subscription) Replicate

func (row *Subscription) Replicate(except ...string) (*Subscription, error)

Replicate returns an unsaved copy of the row without its key; it shadows the untyped one the embedded model promotes.

func (Subscription) Serving

func (s Subscription) Serving() bool

Serving says the subscription still gives access: trialing, active, or past due inside the grace.

type SubscriptionCollection

type SubscriptionCollection []*Subscription

SubscriptionCollection is rows of Subscription, as a query returns them.

func SubscriptionCollectionOf

func SubscriptionCollectionOf(rows model.Rows) SubscriptionCollection

SubscriptionCollectionOf converts rows of the table of Subscription. A nil input is a nil collection.

func (SubscriptionCollection) Contains

func (c SubscriptionCollection) Contains(key any) bool

func (SubscriptionCollection) Except

func (SubscriptionCollection) Find

func (SubscriptionCollection) FindOrFail

func (c SubscriptionCollection) FindOrFail(key any) (*Subscription, error)

func (SubscriptionCollection) Fresh

func (SubscriptionCollection) Load

func (c SubscriptionCollection) Load(ctx context.Context, g auth.Grant, relations ...string) error

func (SubscriptionCollection) LoadCount

func (c SubscriptionCollection) LoadCount(ctx context.Context, g auth.Grant, relations ...string) error

func (SubscriptionCollection) LoadMissing

func (c SubscriptionCollection) LoadMissing(ctx context.Context, g auth.Grant, relations ...string) error

func (SubscriptionCollection) ModelKeys

func (c SubscriptionCollection) ModelKeys() []any

func (SubscriptionCollection) Only

func (SubscriptionCollection) Pluck

func (c SubscriptionCollection) Pluck(column string) []any

func (SubscriptionCollection) Rows

Rows converts the collection back to the core's rows.

func (SubscriptionCollection) ToArray

func (c SubscriptionCollection) ToArray() []map[string]any

func (SubscriptionCollection) Unique

type SubscriptionQuery

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

SubscriptionQuery is a query on the table of Subscription.

The methods that build return the query, so they chain. The methods that run take a context and an auth.Grant, and return Subscription rows or a value; there is no way to run one without a Grant.

func Subscriptions

func Subscriptions(db model.DB) *SubscriptionQuery

Subscriptions starts a query on the table of Subscription, through db.

Global scopes are on and, unless the table is Global, every statement is filtered by the tenant of the Grant its terminal takes.

func (*SubscriptionQuery) AddSelect

func (q *SubscriptionQuery) AddSelect(columns ...any) *SubscriptionQuery

func (*SubscriptionQuery) Avg

func (q *SubscriptionQuery) Avg(ctx context.Context, g auth.Grant, column any) (any, error)

func (*SubscriptionQuery) Base

func (q *SubscriptionQuery) Base() *model.Builder

Base returns the core builder the query forwards to. It is for code in this package -- a local scope in the custom block of model.go -- and for the factory, which builds rows through it.

func (*SubscriptionQuery) Chunk

func (q *SubscriptionQuery) Chunk(ctx context.Context, g auth.Grant, count int, callback func(SubscriptionCollection, int) (bool, error)) error

func (*SubscriptionQuery) Clone

Clone returns an independent copy of the query.

func (*SubscriptionQuery) Count

func (q *SubscriptionQuery) Count(ctx context.Context, g auth.Grant, columns ...any) (int64, error)

func (*SubscriptionQuery) Create

func (q *SubscriptionQuery) Create(ctx context.Context, g auth.Grant, attributes map[string]any) (*Subscription, error)

func (*SubscriptionQuery) Cursor

func (*SubscriptionQuery) CursorPaginate

func (q *SubscriptionQuery) CursorPaginate(ctx context.Context, g auth.Grant, perPage int, cursor *pagination.Cursor, opts pagination.Options, columns ...any) (SubscriptionCollection, *pagination.CursorPage, error)

func (*SubscriptionQuery) Decrement

func (q *SubscriptionQuery) Decrement(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*SubscriptionQuery) Delete

func (q *SubscriptionQuery) Delete(ctx context.Context, g auth.Grant) (int64, error)

func (*SubscriptionQuery) DoesntExist

func (q *SubscriptionQuery) DoesntExist(ctx context.Context, g auth.Grant) (bool, error)

func (*SubscriptionQuery) DoesntHave

func (q *SubscriptionQuery) DoesntHave(relation, boolean string, callback func(*query.Builder)) *SubscriptionQuery

func (*SubscriptionQuery) Each

func (q *SubscriptionQuery) Each(ctx context.Context, g auth.Grant, count int, callback func(*Subscription, int) (bool, error)) error

func (*SubscriptionQuery) Exists

func (q *SubscriptionQuery) Exists(ctx context.Context, g auth.Grant) (bool, error)

func (*SubscriptionQuery) Find

func (q *SubscriptionQuery) Find(ctx context.Context, g auth.Grant, id any, columns ...any) (*Subscription, error)

func (*SubscriptionQuery) FindMany

func (q *SubscriptionQuery) FindMany(ctx context.Context, g auth.Grant, ids []any, columns ...any) (SubscriptionCollection, error)

func (*SubscriptionQuery) FindOrFail

func (q *SubscriptionQuery) FindOrFail(ctx context.Context, g auth.Grant, id any, columns ...any) (*Subscription, error)

func (*SubscriptionQuery) FindOrNew

func (q *SubscriptionQuery) FindOrNew(ctx context.Context, g auth.Grant, id any, columns ...any) (*Subscription, error)

func (*SubscriptionQuery) First

func (q *SubscriptionQuery) First(ctx context.Context, g auth.Grant, columns ...any) (*Subscription, error)

First returns the first row, or nil and no error when there is none.

func (*SubscriptionQuery) FirstOrCreate

func (q *SubscriptionQuery) FirstOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Subscription, error)

func (*SubscriptionQuery) FirstOrFail

func (q *SubscriptionQuery) FirstOrFail(ctx context.Context, g auth.Grant, columns ...any) (*Subscription, error)

func (*SubscriptionQuery) FirstOrNew

func (q *SubscriptionQuery) FirstOrNew(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Subscription, error)

func (*SubscriptionQuery) FirstWhere

func (q *SubscriptionQuery) FirstWhere(ctx context.Context, g auth.Grant, column any, args ...any) (*Subscription, error)

func (*SubscriptionQuery) ForPage

func (q *SubscriptionQuery) ForPage(page, perPage int) *SubscriptionQuery

func (*SubscriptionQuery) ForceCreate

func (q *SubscriptionQuery) ForceCreate(ctx context.Context, g auth.Grant, attributes map[string]any) (*Subscription, error)

func (*SubscriptionQuery) Get

Get runs the query and returns the rows.

func (*SubscriptionQuery) GroupBy

func (q *SubscriptionQuery) GroupBy(groups ...any) *SubscriptionQuery

func (*SubscriptionQuery) Has

func (q *SubscriptionQuery) Has(relation, operator string, count int, boolean string, callback func(*query.Builder)) *SubscriptionQuery

func (*SubscriptionQuery) Increment

func (q *SubscriptionQuery) Increment(ctx context.Context, g auth.Grant, column string, amount any, extra map[string]any) (int64, error)

func (*SubscriptionQuery) Insert

func (q *SubscriptionQuery) Insert(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*SubscriptionQuery) InsertOrIgnore

func (q *SubscriptionQuery) InsertOrIgnore(ctx context.Context, g auth.Grant, values ...map[string]any) (bool, error)

func (*SubscriptionQuery) Join

func (q *SubscriptionQuery) Join(table any, first any, args ...any) *SubscriptionQuery

func (*SubscriptionQuery) Latest

func (q *SubscriptionQuery) Latest(column ...string) *SubscriptionQuery

func (*SubscriptionQuery) Limit

func (q *SubscriptionQuery) Limit(value int) *SubscriptionQuery

func (*SubscriptionQuery) Max

func (q *SubscriptionQuery) Max(ctx context.Context, g auth.Grant, column any) (any, error)

func (*SubscriptionQuery) Min

func (q *SubscriptionQuery) Min(ctx context.Context, g auth.Grant, column any) (any, error)

func (*SubscriptionQuery) New

func (q *SubscriptionQuery) New() (*Subscription, error)

New returns an empty Subscription on the query's connection, not yet saved, filled with what WithAttributes recorded on the query.

func (*SubscriptionQuery) Offset

func (q *SubscriptionQuery) Offset(value int) *SubscriptionQuery

func (*SubscriptionQuery) Oldest

func (q *SubscriptionQuery) Oldest(column ...string) *SubscriptionQuery

func (*SubscriptionQuery) OrDoesntHave

func (q *SubscriptionQuery) OrDoesntHave(relation string) *SubscriptionQuery

func (*SubscriptionQuery) OrHas

func (q *SubscriptionQuery) OrHas(relation, operator string, count int) *SubscriptionQuery

func (*SubscriptionQuery) OrWhere

func (q *SubscriptionQuery) OrWhere(column any, args ...any) *SubscriptionQuery

OrWhere adds an or-where clause; a func(*SubscriptionQuery) in place of the column adds a group.

func (*SubscriptionQuery) OrWhereDoesntHave

func (q *SubscriptionQuery) OrWhereDoesntHave(relation string, callback func(*query.Builder)) *SubscriptionQuery

func (*SubscriptionQuery) OrWhereHas

func (q *SubscriptionQuery) OrWhereHas(relation string, callback func(*query.Builder)) *SubscriptionQuery

func (*SubscriptionQuery) OrWhereNot

func (q *SubscriptionQuery) OrWhereNot(column any, args ...any) *SubscriptionQuery

OrWhereNot adds an or-joined negated where clause, or a negated group.

func (*SubscriptionQuery) OrWhereRelation

func (q *SubscriptionQuery) OrWhereRelation(relation string, column any, args ...any) *SubscriptionQuery

func (*SubscriptionQuery) OrderBy

func (q *SubscriptionQuery) OrderBy(column any, direction ...string) *SubscriptionQuery

func (*SubscriptionQuery) OrderByDesc

func (q *SubscriptionQuery) OrderByDesc(column any) *SubscriptionQuery

func (*SubscriptionQuery) Paginate

func (q *SubscriptionQuery) Paginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (SubscriptionCollection, *pagination.LengthAwarePage, error)

func (*SubscriptionQuery) Pluck

func (q *SubscriptionQuery) Pluck(ctx context.Context, g auth.Grant, column string) ([]any, error)

func (*SubscriptionQuery) Select

func (q *SubscriptionQuery) Select(columns ...any) *SubscriptionQuery

func (*SubscriptionQuery) SelectRaw

func (q *SubscriptionQuery) SelectRaw(expression string, bindings ...any) *SubscriptionQuery

func (*SubscriptionQuery) SimplePaginate

func (q *SubscriptionQuery) SimplePaginate(ctx context.Context, g auth.Grant, perPage, page int, opts pagination.Options, columns ...any) (SubscriptionCollection, *pagination.Page, error)

func (*SubscriptionQuery) Sole

func (q *SubscriptionQuery) Sole(ctx context.Context, g auth.Grant, columns ...any) (*Subscription, error)

func (*SubscriptionQuery) SoleValue

func (q *SubscriptionQuery) SoleValue(ctx context.Context, g auth.Grant, column string) (any, error)

func (*SubscriptionQuery) Sum

func (q *SubscriptionQuery) Sum(ctx context.Context, g auth.Grant, column any) (any, error)

func (*SubscriptionQuery) Touch

func (q *SubscriptionQuery) Touch(ctx context.Context, g auth.Grant, column ...string) (int64, error)

func (*SubscriptionQuery) Update

func (q *SubscriptionQuery) Update(ctx context.Context, g auth.Grant, values map[string]any) (int64, error)

func (*SubscriptionQuery) UpdateOrCreate

func (q *SubscriptionQuery) UpdateOrCreate(ctx context.Context, g auth.Grant, attributes, values map[string]any) (*Subscription, error)

func (*SubscriptionQuery) Upsert

func (q *SubscriptionQuery) Upsert(ctx context.Context, g auth.Grant, values []map[string]any, uniqueBy, update []string) (int64, error)

func (*SubscriptionQuery) Value

func (q *SubscriptionQuery) Value(ctx context.Context, g auth.Grant, column string) (any, error)

func (*SubscriptionQuery) ValueOrFail

func (q *SubscriptionQuery) ValueOrFail(ctx context.Context, g auth.Grant, column string) (any, error)

func (*SubscriptionQuery) Where

func (q *SubscriptionQuery) Where(column any, args ...any) *SubscriptionQuery

Where adds a where clause; a func(*SubscriptionQuery) in place of the column adds a group.

func (*SubscriptionQuery) WhereBelongsTo

func (q *SubscriptionQuery) WhereBelongsTo(relationshipName string, related ...model.Entity) *SubscriptionQuery

func (*SubscriptionQuery) WhereBetween

func (q *SubscriptionQuery) WhereBetween(column any, from, to any) *SubscriptionQuery

func (*SubscriptionQuery) WhereColumn

func (q *SubscriptionQuery) WhereColumn(first any, args ...any) *SubscriptionQuery

func (*SubscriptionQuery) WhereDoesntHave

func (q *SubscriptionQuery) WhereDoesntHave(relation string, callback func(*query.Builder)) *SubscriptionQuery

func (*SubscriptionQuery) WhereExists

func (q *SubscriptionQuery) WhereExists(callback func(*query.Builder)) *SubscriptionQuery

func (*SubscriptionQuery) WhereHas

func (q *SubscriptionQuery) WhereHas(relation string, callback func(*query.Builder)) *SubscriptionQuery

func (*SubscriptionQuery) WhereHasCount

func (q *SubscriptionQuery) WhereHasCount(relation string, callback func(*query.Builder), operator string, count int) *SubscriptionQuery

func (*SubscriptionQuery) WhereIn

func (q *SubscriptionQuery) WhereIn(column any, values []any) *SubscriptionQuery

func (*SubscriptionQuery) WhereKey

func (q *SubscriptionQuery) WhereKey(id any) *SubscriptionQuery

func (*SubscriptionQuery) WhereNot

func (q *SubscriptionQuery) WhereNot(column any, args ...any) *SubscriptionQuery

WhereNot adds a negated where clause, or a negated group.

func (*SubscriptionQuery) WhereNotExists

func (q *SubscriptionQuery) WhereNotExists(callback func(*query.Builder)) *SubscriptionQuery

func (*SubscriptionQuery) WhereNotIn

func (q *SubscriptionQuery) WhereNotIn(column any, values []any) *SubscriptionQuery

func (*SubscriptionQuery) WhereNotNull

func (q *SubscriptionQuery) WhereNotNull(columns ...any) *SubscriptionQuery

func (*SubscriptionQuery) WhereNull

func (q *SubscriptionQuery) WhereNull(columns ...any) *SubscriptionQuery

func (*SubscriptionQuery) WhereRelation

func (q *SubscriptionQuery) WhereRelation(relation string, column any, args ...any) *SubscriptionQuery

func (*SubscriptionQuery) With

func (q *SubscriptionQuery) With(relations ...string) *SubscriptionQuery

func (*SubscriptionQuery) WithAvg

func (q *SubscriptionQuery) WithAvg(relation, column string) *SubscriptionQuery

func (*SubscriptionQuery) WithCount

func (q *SubscriptionQuery) WithCount(relations ...string) *SubscriptionQuery

func (*SubscriptionQuery) WithExists

func (q *SubscriptionQuery) WithExists(relation string) *SubscriptionQuery

func (*SubscriptionQuery) WithMax

func (q *SubscriptionQuery) WithMax(relation, column string) *SubscriptionQuery

func (*SubscriptionQuery) WithMin

func (q *SubscriptionQuery) WithMin(relation, column string) *SubscriptionQuery

func (*SubscriptionQuery) WithSum

func (q *SubscriptionQuery) WithSum(relation, column string) *SubscriptionQuery

func (*SubscriptionQuery) Without

func (q *SubscriptionQuery) Without(relations ...string) *SubscriptionQuery

func (*SubscriptionQuery) WithoutGlobalScope

func (q *SubscriptionQuery) WithoutGlobalScope(identifier string) *SubscriptionQuery

func (*SubscriptionQuery) WithoutGlobalScopes

func (q *SubscriptionQuery) WithoutGlobalScopes(identifiers ...string) *SubscriptionQuery

type SubscriptionResource

type SubscriptionResource struct {
	ID, TenantID, Reference, PlanID      string
	Status                               SubscriptionStatus
	CurrentPeriodStart, CurrentPeriodEnd time.Time
	TrialEndsAt, CanceledAt, EndedAt     *time.Time
	CancelAtPeriodEnd                    bool
	GraceDays, Renewals                  int
	CouponID                             string
	CouponRenewalsLeft                   int
	Meta                                 map[string]string
	CreatedAt                            time.Time
}

SubscriptionResource is one subscription as it may leave.

func NewSubscriptionResource

func NewSubscriptionResource(s Subscription) SubscriptionResource

NewSubscriptionResource copies a subscription.

func (SubscriptionResource) ToArray

func (r SubscriptionResource) ToArray() map[string]any

ToArray is the subscription's fields, by name. The tenant stays out: the caller already knows its own, and the admin reads it on the screen.

func (SubscriptionResource) With

func (SubscriptionResource) With() map[string]any

With is nothing beside the subscription.

type SubscriptionRow

type SubscriptionRow struct {
	ID, Tenant, Plan, Reference, Status, StatusKey, PaidUntil, Started string
	Serving, Cancelling, Ended                                         bool
	RenewURL, CancelURL, AdminCancelURL                                string
}

SubscriptionRow is one subscription as a list shows it.

type SubscriptionStatus

type SubscriptionStatus string

SubscriptionStatus is where a subscription stands.

const (
	// SubscriptionTrialing is served without payment until TrialEndsAt.
	SubscriptionTrialing SubscriptionStatus = "trialing"
	// SubscriptionActive is paid until CurrentPeriodEnd.
	SubscriptionActive SubscriptionStatus = "active"
	// SubscriptionPastDue is past CurrentPeriodEnd, inside the plan's grace.
	SubscriptionPastDue SubscriptionStatus = "past_due"
	// SubscriptionCanceled was stopped by the customer at the end of a period,
	// or by the admin at once.
	SubscriptionCanceled SubscriptionStatus = "canceled"
	// SubscriptionExpired ended without a payment.
	SubscriptionExpired SubscriptionStatus = "expired"
)

type SubscriptionsPageData

type SubscriptionsPageData struct {
	Screen
	Rows  []SubscriptionRow
	Table TableState
	// CanManage says the subject may renew and cancel.
	CanManage bool
}

SubscriptionsPageData is a page of subscriptions: the account's, or every account's for the admin.

type TableState

type TableState struct {
	Query, Status, Sort, Dir string
	Page, Pages, Total       int
	URL                      string
}

TableState is what a data table on these screens was asked and answers.

type Transition

type Transition struct {
	// To is the status after the instant.
	To SubscriptionStatus
	// Moved says To differs from where the subscription stood.
	Moved bool
}

Transition is what the clock does to a subscription at an instant: the status it moves to, and whether it moved.

func Due

func Due(s Subscription, now time.Time) Transition

Due is what happens to a subscription at now, with nobody paying:

  • a trial or a period that reached its end with a cancellation asked for is canceled;
  • a trial that reached its end without a payment expires;
  • a period that reached its end goes past due when the subscription has grace days, and expires when it has none;
  • a subscription past due for longer than its grace expires.

Anything else stays where it is.

type URLs

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

URLs are the addresses of this package's routes, built from Config.Prefix, Config.AdminPrefix and Config.Paths. The route table is built from the same methods with the wildcard in place of the identifier, so an address a screen links to and the pattern that answers it are one spelling.

func NewURLs

func NewURLs(prefix, adminPrefix, notificationPrefix string, paths Paths) URLs

NewURLs builds the addresses for the prefixes and the paths, as New would from a Config holding them: empty segments take DefaultPaths, an empty admin prefix is the prefix followed by Paths.Admin, and an empty notification prefix is DefaultNotificationPrefix.

func (URLs) AdminCancel

func (u URLs) AdminCancel(id string) string

AdminCancel cancels one subscription at once.

func (URLs) AdminConfirm

func (u URLs) AdminConfirm(id string) string

AdminConfirm records one invoice paid by hand.

func (URLs) AdminCoupon

func (u URLs) AdminCoupon(id string) string

AdminCoupon is one coupon, for the admin.

func (URLs) AdminCoupons

func (u URLs) AdminCoupons() string

AdminCoupons are the coupons.

func (URLs) AdminInvoices

func (u URLs) AdminInvoices() string

AdminInvoices are every account's invoices.

func (URLs) AdminPlan

func (u URLs) AdminPlan(id string) string

AdminPlan is one plan, for the admin.

func (URLs) AdminPlans

func (u URLs) AdminPlans() string

AdminPlans is the catalogue, for the admin who keeps it.

func (URLs) AdminPrefix

func (u URLs) AdminPrefix() string

AdminPrefix is where the admin's routes are mounted.

func (URLs) AdminSubscriptions

func (u URLs) AdminSubscriptions() string

AdminSubscriptions are every account's subscriptions.

func (URLs) AdminVoid

func (u URLs) AdminVoid(id string) string

AdminVoid cancels one open invoice.

func (URLs) Cancel

func (u URLs) Cancel(id string) string

Cancel asks one subscription to stop at the end of its period (POST), or takes that back (DELETE).

func (URLs) Checkout

func (u URLs) Checkout(planID string) string

Checkout pays for one plan.

func (URLs) Invoice

func (u URLs) Invoice(id string) string

Invoice is one of the account's invoices.

func (URLs) Invoices

func (u URLs) Invoices() string

Invoices are the account's invoices.

func (URLs) Notification

func (u URLs) Notification(provider string) string

Notification is where one provider posts.

func (URLs) Plans

func (u URLs) Plans() string

Plans is the catalogue, as an account reads it.

func (URLs) Prefix

func (u URLs) Prefix() string

Prefix is where the account's routes are mounted.

func (URLs) Renew

func (u URLs) Renew(id string) string

Renew pays the next period of one subscription.

func (URLs) Return

func (u URLs) Return(id string) string

Return is where the gateway sends the customer back after paying one invoice.

func (URLs) Subscriptions

func (u URLs) Subscriptions() string

Subscriptions are the account's subscriptions.

func (URLs) Trial

func (u URLs) Trial(planID string) string

Trial starts one plan's trial.

Directories

Path Synopsis
Package billingtest is an in-memory payment gateway for tests: what an application's own suite, and this package's, check its billing against without any real gateway, network or merchant account.
Package billingtest is an in-memory payment gateway for tests: what an application's own suite, and this package's, check its billing against without any real gateway, network or merchant account.
internal
everytenant
Package everytenant is the billing read without the tenant filter: the admin's lists of every account's subscriptions and invoices, the lookup of the invoice a gateway's notification names, and the clock's search for the periods that ended -- each after the billing policy allowed it.
Package everytenant is the billing read without the tenant filter: the admin's lists of every account's subscriptions and invoices, the lookup of the invoice a gateway's notification names, and the clock's search for the periods that ended -- each after the billing policy allowed it.
Package walletcredit turns a paid invoice into a deposit in arandu-wallet: the optional adapter for an application whose plans sell credits, minutes or any other balance.
Package walletcredit turns a paid invoice into a deposit in arandu-wallet: the optional adapter for an application whose plans sell credits, minutes or any other balance.

Jump to

Keyboard shortcuts

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