armory

package
v0.0.0-...-95891f2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 40 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

copies.go is what single copies of an item remember: marks ("moonlit"), a quality (fine or poor), who made or harvested them and when, and when they go off. A holder's count of an item stays one number; a Copy is part of it that remembers something, and the rest of the count is plain. Plain copies are always used, given and moved first, unless someone picks a remembered one, so a hero never loses a fine potion to a careless move.

copies_repository.go holds the SQL for remembered copies (copies.go) and the copy a waiting move request picked. Every statement is scoped by campaign_id, so an id from another campaign matches nothing.

copies_service.go keeps remembered copies with their count as items move, get used and are made. Every function runs under the campaign lock its caller holds, and does nothing when the copy store is off (the armory plugin's own table did not migrate): items are then plain, as before.

handler.go provides HTTP endpoints for the Armory gallery. Thin handlers that bind request parameters, call the Armory service, and render templ components or JSON responses.

hero_log.go is the hero's log under the pack: one list, newest first and grouped by game night, of what happened to the hero and what their player wrote. The facts (an item gained or given, something crafted) are read from the move history, never copied; only the written lines are stored.

instance_handler.go provides HTTP endpoints for inventory instance CRUD. Thin handlers that bind request, call service, and return HTMX or JSON.

instance_repository.go provides data access for inventory instances. Instances are standalone named item collections within a campaign.

instance_service.go contains business logic for inventory instances. Handles creation, validation, and IDOR protection for instance operations.

Package armory provides a gallery/hub view for item-type entities in a campaign. Items are pages of an item category (entities.IsItemType): a system preset with preset_category "item", or the campaign's own Items category. This plugin is a view layer on top of the entities system — it does not own any database tables beyond the preset_category column on entity_types.

money_history.go keeps a history line for money that changes on a character's sheet outside a stash move (typed in on the page, pushed from Foundry, changed by an extension). Without it, a balance would change with no trace while moves are fully logged.

The line is an item_moves row from the character to itself, so the existing history views show it with no new table.

onclick_handlers.go builds the inline IIFE click handlers for the armory's HTMX-swapped fragments (item card menu, collection rename, the Give box). Templ script helpers emit a sibling <script> that browsers do not reliably run after an innerHTML swap, so each handler is a self-contained expression rendered straight into the onclick attribute. The JS uses single quotes only (the attribute is double-quoted) and string values go through jsStr, so a collection name with quotes cannot break out of the attribute.

places.go is where a hero carries each item: in hand, worn, a belt pouch or the backpack. It only arranges the hero page; counts, moves and what an item remembers are unchanged by it.

purse.go holds the D&D 5e coin arithmetic for shop purchases: converting a listed price into copper, choosing which coins pay it, and making change. Everything here is pure so the rounding rules are pinned by table tests.

repository.go provides data access for the Armory gallery. Queries the existing entities + entity_types tables — no separate table is needed because items are entities of an item category (entities.IsItemType).

SECURITY: this repository applies NO visibility predicate of its own. A hand-rolled `role < 2 AND e.is_private = false` check here never consulted entities.visibility or entity_permissions, so a visibility='custom' entity (which doesn't clear is_private) stayed listed to Players and anonymous visitors. The visibility decision belongs to the service layer, which narrows the ID list returned here through the entities plugin's canonical FilterViewableEntityIDs — see service.go's visibleItemIDs.

routes.go registers Armory gallery endpoints on the Echo router. The gallery page is readable by Players; all routes are gated behind the "armory" addon.

service.go contains business logic for the Armory gallery. Resolves the campaign's item-category entity types and delegates listing to the repository.

share.go lets a player share a hidden item their character holds with the rest of the party: the "Share..." link on a line of the character panel.

Sharing only ever adds or takes back plain view grants on the item's allow list, and only for players of the campaign's other characters. Every grant it adds is recorded (ShareStore) so taking a share back removes exactly what sharing added: never the holder's own access, a grant the GM set by hand, or the access a give or another holder's share relies on.

share_repository.go holds the SQL for item shares: which view grants on a hidden item came from a holder sharing it (armory_item_shares, a plugin migration). Every statement is scoped by campaign_id.

shop_buy_model.go holds the wire and domain types for buying from a shop's wares with a character's coins.

shop_buy_service.go lets a player spend a character's coins on a shop's wares. One basket is applied as a unit under the same per-campaign lock the stash moves use, so a purchase and a move can never both spend the same coins. Stock, coins and items change in a fixed order and every step that already happened is undone if a later one fails, so a basket is never applied in part.

Prices and currency come only from the shop's listing (the relation metadata); the client names goods and quantities, never amounts.

shop_request_handler.go answers waiting purchase requests from the stashes page. It is the sibling of the move approve/decline handlers and answers the same way (an HTMX signal that reloads the page, or a redirect); the service enforces that only Owner visibility may answer.

shop_request_model.go holds the types for purchase requests: a basket a player asked for while downtime was closed, waiting for the GM.

shop_request_repository.go provides data access for purchase requests. All SQL for the table lives here, and every statement is scoped by campaign_id so an id from another campaign matches nothing.

shop_request_service.go holds a player's basket for the GM while downtime is closed, and applies it later through the same applyBasket path a live buy uses, so a request is never judged by looser rules than a purchase.

A request stores listing ids and quantities only. Everything that decides the outcome (prices, currency, stock, the buyer's coins, who owns the character, whether the shop is still visible) is read again when the request is applied, under the campaign lock. The apply runs as the requester with player visibility: the approval lifts only the downtime gate, never the requester's other limits.

shop_roll_model.go holds the types of the shop counter rolls: Haggle and Look closer. The server throws the dice, so the page only shows them.

shop_roll_service.go lets a player haggle over a shop's good or look closer at it, with one of their characters. The server throws the dice; the page only shows them landing. A haggle changes the price the buy route charges that character for that good on that shelf day, and a look can uncover the owner's hidden note, which stays uncovered for that character.

The rules that must not drift: one try per good, character, action and shelf day (the table's unique key is the arbiter, so two fast taps cannot both roll); the hidden note and extra are read only through a reveal and never reach the layout or the roll log.

shop_stock_service.go fills a shop's shelves from a Director's draft. The draft is made and edited in the browser; nothing is saved until Keep, which lands the whole batch or none of it, and Undo removes exactly that batch.

A good with no page becomes a real page marked as a shop good, so buying, packs, stashes, today's shelf and the shop room work on it unchanged. The mark keeps such pages out of lists and search (entities plugin).

stash_api.go is the stash surface for the sync API. Foundry holds one GM key but speaks for whichever player is at the table, so every call can name the member it acts for and is then answered under THAT member's rules.

Why a named member is safe: only a caller who is Owner or co-DM may name someone else, and such a caller can already do anything here. Naming a player can only narrow what the call may do (their stashes, their characters, their need for approval). A name that is not a current member is refused as not found, so the call cannot be steered at an outsider.

stash_count.go lets the GM set how many of an Armory item a character carries in one step, for changes that arrive as a number rather than a give: an AI import the owner approved. Raising the count is a give, with its history line and the player's bell; lowering it takes plain copies first and then the oldest remembered ones, as every Armory take does, and writes a line saying the GM took them away. A hand edit of the inventory widget leaves no line; this does.

stash_craft.go is the Armory's side of crafting: what a character carries and how they pay, taking a project's materials and cost when it starts, and putting the made item in their pack. The crafting plugin reaches it through an adapter in internal/app and decides who may craft what; these methods still check that the actor may act for the character, as every move does.

stash_events.go announces finished stash and downtime changes to live clients. Payloads carry ids and statuses only: a hidden character's or stash's name must never ride on a broadcast, so a listener that wants names fetches them through the API as the person it is acting for.

stash_give.go lets the GM hand a character an Armory item or a map.

A give credits the character's "Has Item" relation exactly as a stash move that credits a character does (adjustCarried), under the same campaign lock, so the relation events that already reach Foundry fire unchanged. It is recorded in item_moves as an applied item row whose two ends are the same character: the table's ENUMs stay as they are, and every history reader sees it through Move.IsGive instead of treating it as a move between two places.

A map is given as an item. The map itself is not an item, so a handout entity called "Map: <name>" stands for it; it points at the map and is shown only to the players who hold it.

stash_handler.go provides the HTTP endpoints for stashes, moves and the downtime switch. Thin handlers: bind the request, call the service, render a fragment or answer with an HTMX trigger. Every rule — who may see, move or answer — is in the service; the handler only hands it the caller.

stash_model.go holds the domain types for stashes and item/money moves.

Money is carried as whole cents (Cents) everywhere inside the plugin so a sum or a comparison never meets float rounding; it is converted to the game system's own numeric field value only at the character boundary.

stash_moves.go moves items and money between characters and stashes.

One function (run) applies a move and is used by an immediate move, by a GM's approval and by the sweep that happens when downtime opens, so the three paths cannot drift apart. Every apply holds the campaign lock and debits the source first with a check that it holds enough; only then does it credit the destination, and a failed credit puts the source back. A move is therefore never applied in part.

stash_repository.go provides data access for stashes, the move history and the downtime switch. All SQL lives here. Every statement that touches a stash is scoped by campaign_id so an id from another campaign matches nothing, and every balance change is a conditional UPDATE so a debit can never take more than is there even if two writers race.

stash_service.go holds the business rules for stashes: who can see one, who can change one, and the queries behind the stashes page and the character panel. Moving things between holders lives in stash_moves.go.

The service never imports Echo or another plugin. Everything it needs from the entities and relations plugins arrives through the small interfaces below, wired in internal/app/routes.go.

stash_view.go holds the small presentation helpers the stash templates use: plain-English history lines, relative times and URLs. They live in Go, not in the templates, so they can be tested and so no template needs a script.

transaction_handler.go provides HTTP endpoints for shop transactions. Thin handlers: bind request, call service, return JSON. No business logic.

transaction_model.go defines data structures for shop transactions. Transactions record purchases, sales, transfers, and gifts between entities.

transaction_reader.go is the viewer-aware read path for transaction lists. The repository joins entity names for display without any visibility check, so this layer blanks the name of every entity the viewer may not see before a list leaves the plugin.

transaction_repository.go provides data access for shop transactions. All SQL lives here — services never construct queries directly.

transaction_service.go contains business logic for shop transactions. Handles purchase validation, stock management, and currency deduction.

Index

Constants

View Source
const (
	HolderCharacter = EndpointCharacter
	HolderStash     = EndpointStash
)

Where a copy is held.

View Source
const (
	QualityFine = "fine"
	QualityPoor = "poor"
)

Quality words a copy may carry.

View Source
const (
	BuyStatusBought    = "bought"
	BuyStatusRequested = "requested"
)

Buy statuses reported to the client.

View Source
const (
	// BuyKindCoins is one number on the sheet (gp, or another single field).
	BuyKindCoins = "coins"
	// BuyKindPurse is a 5e sheet with several coin fields.
	BuyKindPurse = "purse"
	// BuyKindWealth is Draw Steel's Wealth: a threshold, never spent.
	BuyKindWealth = "wealth"
)

How a buyer pays, reported to the widget as Buyer.Kind.

View Source
const (
	PurchasePending  = MovePending
	PurchaseApplied  = MoveApplied
	PurchaseDeclined = MoveDeclined
	PurchaseFailed   = MoveFailed
)

A purchase request reuses the move statuses because the stashes page and the history lines show both kinds side by side.

View Source
const (
	RollHaggle = "haggle"
	RollLook   = "look"
)

The two counter actions.

View Source
const (
	EventStashMoved        = "stash.moved"
	EventStashRequested    = "stash.requested"
	EventStashSettled      = "stash.settled"
	EventStashMoneyChanged = "stash.money_changed"
	EventDowntimeChanged   = "downtime.changed"
)

Event types, as sent to live clients. The websocket adapter in internal/app accepts exactly these.

View Source
const (
	MoveKindItem  = "item"
	MoveKindMoney = "money"

	EndpointCharacter = "character"
	EndpointStash     = "stash"

	MoveApplied  = "applied"
	MovePending  = "pending"
	MoveDeclined = "declined"
	MoveFailed   = "failed"
)

Move kinds, endpoint kinds and statuses. The strings are the stored ENUM values of item_moves, so they must not be renamed without a migration.

View Source
const (
	TxPurchase = "purchase" // Character buys from shop.
	TxSale     = "sale"     // Character sells to shop.
	TxTransfer = "transfer" // Item moves between characters.
	TxGift     = "gift"     // Free item transfer.
	TxRestock  = "restock"  // Shop restocking (no buyer).
)

TransactionType enumerates the kinds of shop transactions.

View Source
const AddonSlug = "armory"

AddonSlug is the addon that gates every Armory feature; other plugins check it through this constant rather than repeating the name.

View Source
const DefaultFoodPrice = 1.0

DefaultFoodPrice is what a day's food costs in the campaign's main coin until a Director says otherwise.

View Source
const MoneyKeyWealth = "wealth"

MoneyKeyWealth is the money field key of a sheet that keeps Wealth, the one the shop treats as a threshold. It is exported so callers that need the same test do not repeat the literal.

View Source
const (

	// NotifItemGiven is the notification type a player gets when a GM gives
	// their character something.
	NotifItemGiven = "item_given"
)

Variables

View Source
var LookShapes = map[string]bool{"potion": true, "vial": true, "blade": true, "shield": true, "ring": true, "bundle": true}

LookShapes are the shapes craft_results.js draws; a look may also name one of the painted items (internal/madeitems).

View Source
var MigrationsFS embed.FS

MigrationsFS holds the armory's own plugin migrations (its older tables are core migrations). Embedded so the binary carries them whatever its working directory.

View Source
var MoneyFieldKeys = []string{"gp", "coins", "gold", "money", "wealth"}

MoneyFieldKeys is the order in which a character type's money field is looked for: the first numeric field whose key is one of these. Both the directory adapter and the history recorder rely on the same list.

Places lists the containers in the order the hero page draws them.

Functions

func CheckStockPrice

func CheckStockPrice(price float64) error

CheckStockPrice is the Armory's rule for a price on a stock row: not negative or non-numeric, and no larger than a sale can charge. Zero is allowed: it is a good left for the Director to price, and buying already refuses it until one is set. It is exported so a plan can refuse what the shop would, without copying the limits.

func FirstLookJSON

func FirstLookJSON(copies []Copy) string

FirstLookJSON is the first copy's look that has one: a tile stacking several made copies shows the oldest.

func IconColumns

func IconColumns() []database.IconColumn

IconColumns lists this plugin's stored icon columns and the default that replaces an unusable value, for the boot-time icon reconciler.

func LookJSON

func LookJSON(l *CraftLook) string

LookJSON is a look as the pack's tile and card carry it for craft_results.js, "" for none.

func MoveRequestText

func MoveRequestText(l MoveLine) string

MoveRequestText is a waiting move as one line for a list that already names the requester: "move 2 × Healing potion from Bren to Party stash".

func MoveSummary

func MoveSummary(l MoveLine) string

MoveSummary renders one history row as a sentence a player can read.

func NewStashService

func NewStashService(deps StashDeps) *stashService

NewStashService creates the stash service. It returns the concrete type so the shop-buy service can take the same per-campaign lock as the stash moves.

func NewTransactionService

func NewTransactionService(repo TransactionRepository) *transactionService

NewTransactionService creates a new transaction service. Returns the concrete type so callers can inject optional dependencies via Set* methods.

func NormalizeItemLook

func NormalizeItemLook(raw []byte) (doc json.RawMessage, cleared bool, err error)

NormalizeItemLook validates a saved look and returns its canonical JSON. A look of "" with no MadeFrom clears the item, reported as cleared with a nil document. Whether MadeFrom names a real page is the service's check.

func NormalizeShopFront

func NormalizeShopFront(raw []byte) (json.RawMessage, error)

NormalizeShopFront validates a storefront and returns its canonical JSON.

func NormalizeShopRoomCounter

func NormalizeShopRoomCounter(raw []byte) (json.RawMessage, error)

NormalizeShopRoomCounter validates one counter theme on its own and returns its canonical JSON. The saved-designs library keeps counter themes as designs of kind room-theme, and this is its authority for them: the same rules a room's `counter` field is held to, so a design can never hold a part the counter look would refuse.

func NormalizeShopRoomLayout

func NormalizeShopRoomLayout(raw []byte) (json.RawMessage, error)

NormalizeShopRoomLayout validates a client-supplied layout and returns the canonical JSON to store. Every violation is a BadRequest; nothing the client sent is stored verbatim.

func PlainCount

func PlainCount(total int, copies []Copy) int

PlainCount is how many of a holder's total remember nothing.

func PurchaseRequestSentence

func PurchaseRequestSentence(p PurchaseRequestLine) string

PurchaseRequestSentence is a waiting purchase as one line that already names the requester: "buy 3 items at The Gilded Cup (12 gp)".

func RegisterRoutes

RegisterRoutes sets up Armory gallery routes on the Echo instance. Public-capable routes use AllowPublicCampaignAccess so public campaigns show items to unauthenticated visitors. All routes are gated behind the "armory" addon — campaign owners can enable/disable via the Plugin Hub.

func RegisterShelfRoutes

func RegisterShelfRoutes(e *echo.Echo, h *ShopTodayHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)

RegisterShelfRoutes sets up today's shelf: anyone who can view the shop reads it (the service checks the shop is visible to them), and only the campaign Owner sets how many places it has.

func RegisterShopRollRoutes

func RegisterShopRollRoutes(e *echo.Echo, h *ShopRollHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)

RegisterShopRollRoutes sets up the counter rolls and the owner's hidden notes. Players reach the rolls at Player+; what a caller may roll for is decided in the service (the buyers rule), and only the campaign Owner reads or writes a note, so a player can never fetch one except through a reveal.

func RegisterShopStockRoutes

func RegisterShopStockRoutes(e *echo.Echo, h *ShopStockHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)

RegisterShopStockRoutes sets up Fill the shelves. Director only (the owner or a co-DM granted DM access): a draft is never shown to anyone else, and the service checks again.

func RegisterStreetRoutes

func RegisterStreetRoutes(e *echo.Echo, h *ShopStreetHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)

RegisterStreetRoutes sets up the Shops street: anyone who can view the campaign reads the street (the service lists only shops they can see), and only the campaign Owner dresses a storefront.

func ShopPurchaseSource

func ShopPurchaseSource(ctx context.Context, userID, label string) context.Context

ShopPurchaseSource marks writes made under ctx as a shop purchase by userID, so a money change they cause reads "<label>" in the character's history. A shop calls this around the sheet write it makes.

func ShopRoomCounterStarter

func ShopRoomCounterStarter(roomType string) json.RawMessage

ShopRoomCounterStarter is the theme a shop of this type is drawn with until someone saves its own, so an edit of an unsaved counter starts from what the room already looks like.

func ShopRoomCounterStarterNamed

func ShopRoomCounterStarterNamed(name string) json.RawMessage

ShopRoomCounterStarterNamed is the starter theme with this name, nil when there is none, for the starters no shop type begins from.

Types

type APICharacter

type APICharacter struct {
	ID       string    `json:"id"`
	Name     string    `json:"name"`
	MoneyKey string    `json:"moneyKey"`
	Money    float64   `json:"money"`
	Items    []APIItem `json:"items"`
}

APICharacter is the acting member's view of one character.

type APIDestination

type APIDestination struct {
	Kind string `json:"kind"`
	ID   string `json:"id"`
	Name string `json:"name"`
}

APIDestination is a place a move can go.

type APIDowntime

type APIDowntime struct {
	Open    bool `json:"open"`
	Applied int  `json:"applied,omitempty"`
	Failed  int  `json:"failed,omitempty"`
}

APIDowntime is the downtime switch; Applied and Failed appear after a change that opened it and swept the waiting requests.

type APIEndpoint

type APIEndpoint struct {
	Kind string `json:"kind"`
	ID   string `json:"id"`
}

APIEndpoint names one side of a move.

type APIHistory

type APIHistory struct {
	History []APIMoveLine `json:"history"`
}

APIHistory is a list of move lines.

type APIItem

type APIItem struct {
	ItemID   string `json:"itemId"`
	Name     string `json:"name"`
	Quantity int    `json:"quantity"`
}

APIItem is one item line.

type APIMove

type APIMove struct {
	ID          int64       `json:"id"`
	Kind        string      `json:"kind"`
	ItemID      string      `json:"itemId,omitempty"`
	Quantity    int         `json:"quantity,omitempty"`
	Amount      float64     `json:"amount,omitempty"`
	From        APIEndpoint `json:"from"`
	To          APIEndpoint `json:"to"`
	Status      string      `json:"status"`
	Reason      string      `json:"reason,omitempty"`
	RequestedBy string      `json:"requestedBy"`
	DecidedBy   string      `json:"decidedBy,omitempty"`
	CreatedAt   time.Time   `json:"createdAt"`
}

APIMove is one move row.

type APIMoveLine

type APIMoveLine struct {
	APIMove
	ItemName      string `json:"itemName,omitempty"`
	FromName      string `json:"fromName"`
	ToName        string `json:"toName"`
	RequesterName string `json:"requesterName"`
	Summary       string `json:"summary"`
}

APIMoveLine is a move with names resolved (and redacted) for the actor.

type APIMoveRequest

type APIMoveRequest struct {
	ActingUserID string
	Kind         string
	ItemID       string
	Quantity     int
	Amount       string
	From         APIEndpoint
	To           APIEndpoint
}

APIMoveRequest is the body of POST /stashes/moves.

type APIMoveResult

type APIMoveResult struct {
	Status string  `json:"status"`
	Move   APIMove `json:"move"`
}

APIMoveResult answers a move, an approval or a decline.

type APIRequests

type APIRequests struct {
	Requests []APIMoveLine `json:"requests"`
}

APIRequests is the pending-request list.

type APIStash

type APIStash struct {
	ID    string    `json:"id"`
	Name  string    `json:"name"`
	Money float64   `json:"money"`
	Items []APIItem `json:"items"`
}

APIStash is a stash the acting member can see.

type APIStashView

type APIStashView struct {
	DowntimeOpen bool             `json:"downtimeOpen"`
	Character    APICharacter     `json:"character"`
	Stashes      []APIStash       `json:"stashes"`
	Destinations []APIDestination `json:"destinations"`
	CanApprove   bool             `json:"canApprove"`
}

APIStashView is the answer to GET /stashes/view.

type Actor

type Actor struct {
	UserID string
	Role   int
}

Actor is the calling user as the service sees them. Role is the campaign's VisibilityRole (a DM-granted co-DM counts as Owner), so every rule below is the same promotion the entity paths apply.

func (Actor) IsGM

func (a Actor) IsGM() bool

IsGM reports Owner or Scribe, who can already edit anything.

func (Actor) IsOwner

func (a Actor) IsOwner() bool

IsOwner reports Owner visibility: the Owner or a DM-granted co-DM. Only these answer requests; a Scribe does not.

func (Actor) SeesDmOnly

func (a Actor) SeesDmOnly() bool

SeesDmOnly reports whether the actor may see and move DM-only inventory lines. It follows Chronicle's DM-only rule (Owner or co-DM), not IsGM: a Scribe manages stashes but does not see DM-only content anywhere else.

type ArmoryRepository

type ArmoryRepository interface {
	// ListItemIDs returns ALL item entity IDs matching the campaign + optional
	// type/search/tag/instance filters (excluding templates), in the gallery's
	// sort order, with NO visibility restriction and NO pagination applied.
	// The service layer narrows this list to what the viewer may see (via the
	// canonical entities visibility policy) BEFORE paginating, so the visible
	// list and its count are always derived from the exact same filtered ID
	// set and can never disagree.
	ListItemIDs(ctx context.Context, campaignID string, itemTypeIDs []int, opts ItemListOptions) ([]string, error)

	// GetItemCardsByIDs returns full item card data for exactly the given IDs
	// (in that order), scoped to campaignID. Used to fetch one page's worth of
	// cards after the service has already narrowed and paginated the ID list.
	GetItemCardsByIDs(ctx context.Context, campaignID string, ids []string) ([]ItemCard, error)
}

ArmoryRepository defines the data access contract for Armory gallery queries.

func NewArmoryRepository

func NewArmoryRepository(db *sql.DB) ArmoryRepository

NewArmoryRepository creates a new Armory repository backed by the given database.

type ArmoryService

type ArmoryService interface {
	// ListItems returns item entities for the Armory gallery.
	ListItems(ctx context.Context, campaignID string, role int, userID string, opts ItemListOptions) ([]ItemCard, int, error)

	// CountItems returns the number of visible items for badge/nav display.
	CountItems(ctx context.Context, campaignID string, role int, userID string) (int, error)

	// GetItemTypes returns all item-category entity types for filter dropdowns.
	GetItemTypes(ctx context.Context, campaignID string) ([]ItemTypeInfo, error)

	// ListTagOptions returns the distinct tags on the items the viewer may
	// see, for the gallery's tag filter. GM-only tags are excluded below
	// Scribe, so the filter can never reveal a hidden tag's existence.
	ListTagOptions(ctx context.Context, campaignID string, role int, userID string) ([]ItemTagInfo, error)

	// SetTagLister injects the tag batch fetcher that decorates item cards.
	SetTagLister(tl TagLister)
}

ArmoryService handles business logic for the Armory gallery.

func NewArmoryService

func NewArmoryService(repo ArmoryRepository, typeFinder ItemTypeFinder, entityVisibility EntityVisibilityFilter) ArmoryService

NewArmoryService creates a new Armory service. entityVisibility is the canonical visibility gate (see EntityVisibilityFilter), required so a Player/anonymous viewer's list can never fall back to "everything visible" — see visibleItemIDs's fail-closed branch.

type BuyInput

type BuyInput struct {
	BuyerEntityID string         `json:"buyerEntityId"`
	Items         []BuyItemInput `json:"items"`
}

BuyInput is the buy request body.

type BuyItemInput

type BuyItemInput struct {
	RelationID RelationRef `json:"relationId"`
	Quantity   int         `json:"quantity"`
}

BuyItemInput is one basket line. It carries no price: the price always comes from the listing.

type BuyResult

type BuyResult struct {
	Status    string   `json:"status"`
	Spent     *float64 `json:"spent,omitempty"`
	Currency  string   `json:"currency,omitempty"`
	MoneyLeft *float64 `json:"moneyLeft,omitempty"`
	// PurseLeft is the whole purse after a purse buy ("9 gp 7 sp 3 cp") and
	// Change the coins handed back, empty when there was none.
	PurseLeft string `json:"purseLeft,omitempty"`
	Change    string `json:"change,omitempty"`
}

BuyResult is the buy response. A bought basket reports what was charged; a request reports only its status. A Wealth buy spends nothing, so Spent and Currency are absent and MoneyLeft is the unchanged Wealth.

type Buyer

type Buyer struct {
	ID       string             `json:"id"`
	Name     string             `json:"name"`
	MoneyKey string             `json:"moneyKey"`
	Money    *float64           `json:"money"`
	Purse    map[string]float64 `json:"purse,omitempty"`
	MoneyCp  *int64             `json:"moneyCp,omitempty"`
	Kind     string             `json:"kind,omitempty"`
	// Own marks a character the caller has claimed, so the widget can start
	// its "Paying" picker on the viewer's own character even when the Owner's
	// name-sorted list puts someone else first.
	Own bool `json:"own,omitempty"`
}

Buyer is one character the caller may buy for. Money is null when the sheet has no money field (or holds a non-number); for a purse it is the gp equivalent of every coin. MoneyCp is the same value in copper, set only for sheets whose money is 5e coin (gp or a purse).

type BuyerAccessChecker

type BuyerAccessChecker interface {
	// CanUserActAsBuyer is false for an entity outside campaignID, whatever
	// the role: a campaign role grants nothing in another campaign.
	CanUserActAsBuyer(ctx context.Context, campaignID, entityID, userID string, role int) (bool, error)
}

BuyerAccessChecker validates that the calling user can act on the buyer entity (i.e. the character making the purchase belongs to them, or is shared/visible per the campaign's per-entity ACL).

Implemented by an adapter over entities.EntityService.CheckEntityAccess — wired in routes.go. Without this guard, Foundry — which authenticates with a single per-campaign API key — could spoof `buyer_entity_id` to purchase on behalf of any character in the campaign.

type BuyersView

type BuyersView struct {
	DowntimeOpen bool    `json:"downtimeOpen"`
	CanBuyNow    bool    `json:"canBuyNow"`
	Buyers       []Buyer `json:"buyers"`
}

BuyersView is the response of the buyers endpoint.

type CarriedCount

type CarriedCount struct {
	Before, After int
}

CarriedCount is what SetCarried did: how many the character held before and holds now.

type Cents

type Cents int64

Cents is a money amount in hundredths of the game system's currency unit.

func CraftCharge

func CraftCharge(p *CraftPack, total Cents, currency string) Cents

CraftCharge is what a cost of total in currency comes to against the pack: the Wealth a hero needs, the copper a purse pays, or the coins a single money field pays. Compare it with Have.

func ParseCents

func ParseCents(s string) (Cents, error)

ParseCents reads a plain decimal amount ("12", "12.5", "12.50") into cents. It rejects anything that is not a positive number with at most two decimals, so an exponent, a sign, a thousands separator or a third decimal can never slip a different amount past the check.

func (Cents) Decimal

func (c Cents) Decimal() string

Decimal renders cents as the exact "12.50" string MariaDB DECIMAL expects.

func (Cents) String

func (c Cents) String() string

String renders cents for people: whole amounts without decimals.

type CharacterPanelView

type CharacterPanelView struct {
	CampaignID   string
	Character    EntityRef
	DowntimeOpen bool
	// CanGive is true for Owner visibility, who may hand the character items
	// and maps.
	CanGive bool
	// CanPlace lets the viewer drag items between the hero's containers.
	CanPlace bool
	// CanCraft says the viewer may work crafting for this hero (the Director
	// or the claiming player) with crafting on; Bench says the page asked for
	// the bench, which only a game system's hero page does.
	CanCraft bool
	// HasLog turns the hero's log on; CanDirect lets the viewer mark a line
	// Director only.
	HasLog      bool
	CanDirect   bool
	Log         []LogNight
	Bench       bool
	Items       []HeldItem
	HasMoney    bool
	Money       Cents
	History     []MoveLine
	HistoryMore bool
}

CharacterPanelView feeds the "Items and money" panel on a character page.

type Copy

type Copy struct {
	ID       int64
	ItemID   string
	Quantity int
	Memory   Memory
}

Copy is a number of copies of one item, at one holder, that remember the same thing.

type CopyPick

type CopyPick struct {
	ID int64
	N  int
}

CopyPick asks for N of a remembered copy row (0 for as many as needed).

type CopyStore

type CopyStore interface {
	// List returns a holder's copies; itemID "" lists every item's.
	List(ctx context.Context, campaignID, holderKind, holderID, itemID string) ([]Copy, error)
	// Add stores copies at a holder and returns the row's id.
	Add(ctx context.Context, campaignID, holderKind, holderID string, c Copy) (int64, error)
	// SetQuantity changes a row's count; 0 removes it.
	SetQuantity(ctx context.Context, campaignID string, id int64, qty int) error
	// Rehome moves a row to another holder.
	Rehome(ctx context.Context, campaignID string, id int64, holderKind, holderID string) error
	// Remember sets a row's memory.
	Remember(ctx context.Context, campaignID string, id int64, m Memory) error
	// DueOff lists every copy in the campaign that goes off on or before day.
	DueOff(ctx context.Context, campaignID string, day int64) ([]HeldCopy, error)
	// Pick keeps the copy a waiting move asked for; Picked reads it back (0
	// for none).
	Pick(ctx context.Context, moveID, copyID int64) error
	Picked(ctx context.Context, moveID int64) (int64, error)
}

CopyStore is the data access for remembered copies. Copies come oldest first.

func NewCopyRepository

func NewCopyRepository(db *sql.DB) CopyStore

NewCopyRepository returns the SQL copy store.

type CopyTag

type CopyTag struct {
	Label string
	Kind  string
}

CopyTag is one word a copy wears in the pack: its quality, a mark, an enchantment, or that it has gone off. Kind picks the tag's look ("", "poor", "enchant", "off").

type CraftGate

type CraftGate interface {
	CanCraft(ctx context.Context, campaignID, characterID string, a Actor) bool
}

CraftGate answers whether the viewer may work crafting for a character and the campaign has crafting on. It keeps the armory from importing the crafting plugin; the answer is the Crafting block's own rule.

type CraftItem

type CraftItem struct {
	ItemID   string
	Quantity int
	Pick     []CopyPick
}

CraftItem is one Armory item and how many. Pick names remembered copies to use first (copies.go); without it plain ones go first.

type CraftLook

type CraftLook struct {
	Shape  string     `json:"shape"`
	Body   string     `json:"body"`
	Trim   string     `json:"trim"`
	Detail string     `json:"detail"`
	Mark   *CraftMark `json:"mark,omitempty"`
}

CraftLook is a made copy's picture: a result shape and its tints.

type CraftMark

type CraftMark struct {
	Picture string `json:"picture"`
	Tint    string `json:"tint"`
}

CraftMark is the one material picture a look shows on its label or boss.

type CraftPack

type CraftPack struct {
	Name       string
	Items      []HeldItem
	PayKind    string
	Have       Cents
	MoneyKey   string
	MoneyLabel string
}

CraftPack is what a character carries and how they pay, as the actor may see it. PayKind is "" when the sheet has no money field, else BuyKindWealth, BuyKindPurse or BuyKindCoins; Have is the Wealth level, the coins, or for a purse its whole value in copper (gp-cents are copper), all in cents.

type CraftSpendInput

type CraftSpendInput struct {
	CharacterID string
	Items       []CraftItem
	Cost        Cents
	Currency    string
	Label       string
	// Purpose, when set, says what the items went to in the history in
	// place of "to make <Label>": "in an experiment".
	Purpose string
}

CraftSpendInput is what starting a project takes from a character. Label names what is being made, for the history lines.

type CraftSpendOutcome

type CraftSpendOutcome struct {
	Paid string
	Used []Copy
}

CraftSpendOutcome says what was paid ("25 gp", "1.50 gp"); empty when no coins changed hands, as for a Wealth threshold. Used is every remembered copy that went into the project, so the roll can read their marks.

type CreateInstanceInput

type CreateInstanceInput struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Icon        string `json:"icon"`
	Color       string `json:"color"`
}

CreateInstanceInput is the request payload for creating/updating an instance.

type CreateStashInput

type CreateStashInput struct {
	Name     string
	Location string
}

CreateStashInput creates a stash.

type CreateTransactionInput

type CreateTransactionInput struct {
	InstanceID      int     `json:"instance_id"`
	ShopEntityID    string  `json:"shop_entity_id"`
	ItemEntityID    string  `json:"item_entity_id"`
	BuyerEntityID   string  `json:"buyer_entity_id"`
	RelationID      int     `json:"relation_id"`
	Quantity        int     `json:"quantity"`
	PricePaid       string  `json:"price_paid"`
	Currency        string  `json:"currency"`
	PriceNumeric    float64 `json:"price_numeric"`
	TransactionType string  `json:"transaction_type"`
	Notes           string  `json:"notes"`
}

CreateTransactionInput is the request payload for creating a transaction.

type Downtime

type Downtime struct {
	IsOpen    bool
	ChangedBy string
	ChangedAt time.Time
}

Downtime is the per-campaign switch that decides whether moves apply at once.

type DowntimeReader

type DowntimeReader interface {
	IsDowntimeOpen(ctx context.Context, campaignID string) (bool, error)
}

DowntimeReader reports whether the campaign's shops are open (downtime).

type DowntimeResult

type DowntimeResult struct {
	Applied int
	Failed  int
}

DowntimeResult counts what opening downtime did to waiting requests.

type Endpoint

type Endpoint struct {
	Kind string
	ID   string
}

Endpoint names one side of a move: a character entity or a stash.

func StashEndpoint

func StashEndpoint(id int) Endpoint

StashEndpoint builds the endpoint for a stash id.

func (Endpoint) StashID

func (e Endpoint) StashID() (int, bool)

StashID returns the numeric stash id for a stash endpoint.

func (Endpoint) Valid

func (e Endpoint) Valid() bool

Valid reports whether the endpoint names a known kind with an id.

type EntityCampaignChecker

type EntityCampaignChecker interface {
	EntityBelongsToCampaign(ctx context.Context, entityID, campaignID string) (bool, error)
}

EntityCampaignChecker reports whether an entity belongs to a campaign. Implemented in routes.go over the entities service so this plugin never reaches into another plugin's repository.

type EntityFieldUpdater

type EntityFieldUpdater interface {
	GetEntityFields(ctx context.Context, entityID string) (map[string]any, error)
	UpdateEntityFields(ctx context.Context, entityID string, fields map[string]any) error
}

EntityFieldUpdater updates entity fields. The legacy purchase route does not charge coins; shop buys take them through the stash service instead. Implemented by entities.EntityService.

type EntityRef

type EntityRef struct {
	ID          string
	Name        string
	TypeID      int
	OwnerUserID string // Empty when unclaimed.
	// IsCharacter is true for the whole character family, player characters
	// included. IsItem is true for item-category entities.
	IsCharacter bool
	IsItem      bool
	// MoneyKey is the character's money field key, empty when its entity type
	// has no usable numeric money field.
	MoneyKey string
	// Restricted is set on an item players cannot all see: private, or with a
	// custom allow list.
	Restricted bool
	// HandoutMapID is the map an item stands for when it is a map handout
	// (see HandoutStore), else empty.
	HandoutMapID string
	// MoneyLabel is that field's display label, empty when it has none.
	MoneyLabel string
	// Purse maps each 5e coin (cp, sp, ep, gp, pp) to the sheet field that
	// holds it. It is set only when the type has numeric gp, sp and cp, so
	// change can always be given; MoneyKey stays "gp" so stash moves keep treating gp as the
	// character's money.
	Purse map[string]string
}

EntityRef is the little the plugin needs to know about a character or item entity. The adapter in internal/app fills it so the service never touches the entities plugin.

type EntityVisibilityFilter

type EntityVisibilityFilter interface {
	FilterViewableEntityIDs(ctx context.Context, campaignID string, entityIDs []string, role int, userID string) (map[string]bool, error)
}

EntityVisibilityFilter resolves which of a set of entity IDs a viewer (role + userID) may see, applying the entities plugin's own canonical visibility policy (default is_private, custom per-subject grants, tag grants). Wraps entities.EntityService.FilterViewableEntityIDs — the SAME method sessions and the relations widget use — so the Armory gallery never hand-rolls its own copy of that predicate, which used to miss visibility='custom' items (is_private untouched by SetEntityPermissions) and leave them listed to Players and anonymous visitors.

type FillItem

type FillItem struct {
	ID       string  `json:"id"`
	Name     string  `json:"name"`
	Price    float64 `json:"price"`
	Currency string  `json:"currency,omitempty"`
}

FillItem is a campaign item page a fill may stock, with the price a shop already lists it at (Price 0 means none yet).

type FillListed

type FillListed struct {
	ItemID string `json:"itemId"`
	Name   string `json:"name"`
}

FillListed is a page the shop already sells, so a fill leaves it alone.

type FillSources

type FillSources struct {
	FoodPrice   float64      `json:"foodPrice"`
	Items       []FillItem   `json:"items"`
	Listed      []FillListed `json:"listed"`
	System      []SystemGood `json:"system"`
	SystemName  string       `json:"systemName,omitempty"`
	RarityLabel string       `json:"rarityLabel,omitempty"`
}

FillSources is everything a draft may draw on, for one shop.

type GiveCharacter

type GiveCharacter struct {
	ID     string
	Name   string
	Player string
}

GiveCharacter is one character in the item flow's list, with its player's name (empty when unclaimed) shown at the right of the row.

type GiveDialogView

type GiveDialogView struct {
	CampaignID string
	Character  *NamedRef
	// Player is the fixed character's player's name, empty when nobody has
	// claimed the character; the box's hint names them.
	Player string
	Item   *NamedRef
	// Items is the page of Armory items matching Query (at most
	// giveListPageSize); ItemTotal counts every match so the box can say
	// when it is showing only some.
	Items     []NamedRef
	ItemTotal int
	Query     string
	// Characters is the pick-list of the item flow.
	Characters []GiveCharacter
	// MapsOn is true when maps can be given at all (the box shows the map
	// tab); Maps lists them and HeldMaps marks those the character holds.
	MapsOn   bool
	Maps     []NamedRef
	HeldMaps map[string]bool
}

GiveDialogView feeds the Give box. Opened from a character page the character is fixed and the item (or map) is picked; opened from an item card the item is fixed and the character is picked.

func (*GiveDialogView) MoreItems

func (v *GiveDialogView) MoreItems() bool

MoreItems reports whether the list shows only some of the matches.

type GiveInput

type GiveInput struct {
	CharacterID string
	ItemID      string
	MapID       string
	Quantity    int
}

GiveInput is what the GM asks for. Exactly one of ItemID and MapID is set.

type GiveNotifier

type GiveNotifier interface {
	// ItemGiven notifies the users, with a link to where to look. detail is
	// the short line under the message ("On Bren").
	ItemGiven(ctx context.Context, campaignID string, userIDs []string, message, detail, link string) error
}

GiveNotifier tells players they were given something. Optional.

type GiveOutcome

type GiveOutcome struct {
	Move          Move
	ItemName      string
	CharacterName string
}

GiveOutcome reports what Give did, for the confirmation toast.

type GoodHaggleView

type GoodHaggleView struct {
	Tier  int     `json:"tier"`
	Pct   int     `json:"pct"`
	Price float64 `json:"price"`
	Was   float64 `json:"was"`
}

GoodHaggleView is a haggle made today. Price and Was are unit prices in the listing's own units.

type GoodLookView

type GoodLookView struct {
	Tier  int    `json:"tier"`
	Note  string `json:"note"`
	Extra string `json:"extra"`
	Today bool   `json:"today"`
}

GoodLookView is what a character has uncovered about a good. Note and Extra are empty at tier 1 and where nothing was written. Today says a look was made today, so another is refused.

type GoodSecret

type GoodSecret struct {
	Note  string `json:"note"`
	Extra string `json:"extra"`
}

GoodSecret is the owner's hidden note on a shop good, and the extra a great look reveals as well. Players read it only through a reveal.

type HaggleReader

type HaggleReader interface {
	Haggles(ctx context.Context, campaignID, shopEntityID, characterID string, shelfDay int64) (map[int]int, error)
}

HaggleReader reads the price changes a character has won at a shop on one shelf day, in percent by relation id. Implemented by ShopRollRepository.

type Handler

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

Handler serves Armory gallery endpoints.

func NewHandler

func NewHandler(svc ArmoryService) *Handler

NewHandler creates a new Armory gallery handler.

func (*Handler) CountAPI

func (h *Handler) CountAPI(c *echo.Context) error

CountAPI returns the item count as JSON at GET /campaigns/:id/armory/count. Used by the sidebar badge and layout blocks.

func (*Handler) GalleryBlock

func (h *Handler) GalleryBlock(ctx context.Context, campaignID string, role int, userID string, limit int) ([]ItemCard, error)

GalleryBlock fetches item cards for embedding in entity page layout blocks. Returns a compact card list limited by the block config.

func (*Handler) Index

func (h *Handler) Index(c *echo.Context) error

Index renders the Armory gallery page at GET /campaigns/:id/armory. Returns a full page or an HTMX fragment depending on the request header.

func (*Handler) ManageInstances

func (h *Handler) ManageInstances(c *echo.Context) error

ManageInstances renders the instance management panel (HTMX fragment). GET /campaigns/:id/armory/instances/manage (Scribe+).

func (*Handler) SetInstanceService

func (h *Handler) SetInstanceService(svc InstanceService)

SetInstanceService injects the instance service for gallery filtering.

type HandoutStore

type HandoutStore interface {
	// ListMaps returns the campaign's maps, by name.
	ListMaps(ctx context.Context, campaignID string) ([]NamedRef, error)
	// FindMap returns the map, or nil (and no error) when it does not exist in
	// campaignID, so a foreign id and a missing id look the same.
	FindMap(ctx context.Context, campaignID, mapID string) (*NamedRef, error)
	// FindHandout returns the item entity called name that is assigned mapID,
	// or nil when there is none.
	FindHandout(ctx context.Context, campaignID, name, mapID string) (*EntityRef, error)
	// CreateHandout makes an item entity called name, hidden from players,
	// assigned to the map, whose entry links the map's page.
	CreateHandout(ctx context.Context, campaignID, createdBy, name string, m NamedRef) (*EntityRef, error)
	// AllowViewers adds the users to the entity's allow list so they, besides
	// the GM, can open it. Existing grants stay; a public entity is left alone.
	// It returns the users it added, leaving out those who already had a
	// grant of their own.
	AllowViewers(ctx context.Context, campaignID, entityID string, userIDs []string) ([]string, error)
	// RevokeViewers takes the users' view grants off the entity's allow list.
	// A grant above view (set by hand) and every other grant stay.
	RevokeViewers(ctx context.Context, campaignID, entityID string, userIDs []string) error
}

HandoutStore is what giving a map needs from the maps and entities plugins. Implemented in internal/app over their services; nil means maps cannot be given, and the dialog leaves that tab out.

type HasItemRelation

type HasItemRelation struct {
	ID           int
	ItemEntityID string
	ItemName     string
	Metadata     []byte
	DmOnly       bool
}

HasItemRelation is one "Has Item" relation from a character to an item.

type HasItemStore

type HasItemStore interface {
	// ListByCharacter returns the character's "Has Item" relations.
	ListByCharacter(ctx context.Context, campaignID, characterID string) ([]HasItemRelation, error)
	// Create adds a Has Item relation (and its In Inventory Of reverse).
	Create(ctx context.Context, campaignID, characterID, itemID, createdBy string, metadata []byte) (int, error)
	// UpdateMetadata overwrites a relation's metadata.
	UpdateMetadata(ctx context.Context, id int, metadata []byte) error
	// UpdateMetadataIf overwrites metadata only while it still equals expected.
	UpdateMetadataIf(ctx context.Context, id int, expected, metadata []byte) (bool, error)
	// Delete removes a relation and its reverse.
	Delete(ctx context.Context, id int) error
}

HasItemStore reads and writes the "Has Item" relations that hold a character's inventory. Implemented over the relations widget service.

type HeldCopy

type HeldCopy struct {
	Copy
	HolderKind string
	HolderID   string
}

HeldCopy is a copy with its holder.

type HeldItem

type HeldItem struct {
	ItemID   string
	Name     string
	Quantity int
	// IsMap marks a map handout, which the panel shows with a map icon.
	IsMap bool
	// CanShare gives the line a "Share..." link: the viewer is the holder's
	// player and not everyone can see the item.
	CanShare bool
	// SharedWith names the characters whose players the holder shared the
	// item with.
	SharedWith []string
	// Copies are the ones that remember something (copies.go), oldest
	// first; the rest of Quantity is plain.
	Copies []Copy
	// Place is the container the hero carries it in.
	Place Place
}

HeldItem is one line of what a character carries.

type HeroLogStore

type HeroLogStore interface {
	List(ctx context.Context, campaignID, characterID string, limit int) ([]LogNote, error)
	Add(ctx context.Context, n LogNote, campaignID string) error
	// Delete removes a line of this character; it reports whether one went.
	Delete(ctx context.Context, campaignID, characterID string, id int64) (LogNote, bool, error)
}

HeroLogStore keeps the written lines.

func NewHeroLogRepository

func NewHeroLogRepository(db *sql.DB) HeroLogStore

NewHeroLogRepository returns the SQL store for written log lines.

type InstanceHandler

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

InstanceHandler serves inventory instance endpoints.

func NewInstanceHandler

func NewInstanceHandler(svc InstanceService) *InstanceHandler

NewInstanceHandler creates a new instance handler.

func (*InstanceHandler) AddItem

func (h *InstanceHandler) AddItem(c *echo.Context) error

AddItem adds an entity to an instance (POST /campaigns/:id/armory/instances/:iid/items).

func (*InstanceHandler) CreateInstance

func (h *InstanceHandler) CreateInstance(c *echo.Context) error

CreateInstance creates a new inventory instance (POST /campaigns/:id/armory/instances).

func (*InstanceHandler) DeleteInstance

func (h *InstanceHandler) DeleteInstance(c *echo.Context) error

DeleteInstance removes an instance (DELETE /campaigns/:id/armory/instances/:iid).

func (*InstanceHandler) ItemCollections

func (h *InstanceHandler) ItemCollections(c *echo.Context) error

ItemCollections lists every collection with whether it holds one item (GET /campaigns/:id/armory/items/:eid/collections). Feeds the card menu.

func (*InstanceHandler) ListInstances

func (h *InstanceHandler) ListInstances(c *echo.Context) error

ListInstances returns all instances for a campaign (GET /campaigns/:id/armory/instances).

func (*InstanceHandler) RemoveItem

func (h *InstanceHandler) RemoveItem(c *echo.Context) error

RemoveItem removes an entity from an instance (DELETE /campaigns/:id/armory/instances/:iid/items/:eid).

func (*InstanceHandler) UpdateInstance

func (h *InstanceHandler) UpdateInstance(c *echo.Context) error

UpdateInstance modifies an instance (PUT /campaigns/:id/armory/instances/:iid).

type InstanceRepository

type InstanceRepository interface {
	// Create inserts a new inventory instance and returns it with the generated ID.
	Create(ctx context.Context, campaignID, name, slug, description, icon, color string) (*InventoryInstance, error)

	// FindByID retrieves an instance by ID.
	FindByID(ctx context.Context, id int) (*InventoryInstance, error)

	// ListByCampaign returns all instances for a campaign with item counts.
	ListByCampaign(ctx context.Context, campaignID string) ([]InventoryInstance, error)

	// Update modifies an instance's mutable fields.
	Update(ctx context.Context, id int, name, slug, description, icon, color string) error

	// Delete removes an instance (cascade deletes inventory_items).
	Delete(ctx context.Context, id int) error

	// AddItem adds an entity to an inventory instance.
	AddItem(ctx context.Context, instanceID int, entityID string, quantity int) error

	// RemoveItem removes an entity from an inventory instance.
	RemoveItem(ctx context.Context, instanceID int, entityID string) error

	// CountInstanceItems returns the number of items in an instance.
	CountInstanceItems(ctx context.Context, instanceID int) (int, error)

	// ListItemEntityIDsByInstance returns, per instance of the campaign, the
	// IDs of the non-template entities in that same campaign linked to it.
	// No visibility is applied; the service narrows per viewer.
	ListItemEntityIDsByInstance(ctx context.Context, campaignID string) (map[int][]string, error)
}

InstanceRepository defines the data access contract for inventory instances.

func NewInstanceRepository

func NewInstanceRepository(db *sql.DB) InstanceRepository

NewInstanceRepository creates a new instance repository.

type InstanceService

type InstanceService interface {
	// ListInstances returns all instances for a campaign, with each ItemCount
	// narrowed to the items the viewer (role + userID) may see.
	ListInstances(ctx context.Context, campaignID string, role int, userID string) ([]InventoryInstance, error)

	// ListCollectionsForItem returns every collection with whether it holds
	// the entity, after confirming the entity belongs to the campaign.
	ListCollectionsForItem(ctx context.Context, campaignID string, role int, userID string, entityID string) ([]ItemCollection, error)

	// GetInstance retrieves an instance by ID with campaign IDOR check.
	GetInstance(ctx context.Context, campaignID string, instanceID int) (*InventoryInstance, error)

	// CreateInstance creates a new inventory instance.
	CreateInstance(ctx context.Context, campaignID string, input CreateInstanceInput) (*InventoryInstance, error)

	// UpdateInstance modifies an instance after IDOR validation.
	UpdateInstance(ctx context.Context, campaignID string, instanceID int, input UpdateInstanceInput) error

	// DeleteInstance removes an instance after IDOR validation.
	DeleteInstance(ctx context.Context, campaignID string, instanceID int) error

	// AddItem adds an entity to an instance after IDOR validation.
	AddItem(ctx context.Context, campaignID string, instanceID int, entityID string) error

	// RemoveItem removes an entity from an instance after IDOR validation.
	RemoveItem(ctx context.Context, campaignID string, instanceID int, entityID string) error
}

InstanceService handles business logic for inventory instances.

func NewInstanceService

func NewInstanceService(repo InstanceRepository, visibility EntityVisibilityFilter, entityCampaign EntityCampaignChecker) InstanceService

NewInstanceService creates a new instance service. visibility is the same canonical gate the gallery uses, so a collection's count can never exceed what its gallery view lists; entityCampaign guards AddItem against linking another campaign's entity.

type InventoryInstance

type InventoryInstance struct {
	ID          int       `json:"id"`
	CampaignID  string    `json:"campaign_id"`
	Name        string    `json:"name"`
	Slug        string    `json:"slug"`
	Description *string   `json:"description,omitempty"`
	Icon        string    `json:"icon"`
	Color       string    `json:"color"`
	SortOrder   int       `json:"sort_order"`
	ItemCount   int       `json:"item_count"` // Viewer-visible items; set by the service, not the raw SQL count.
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

InventoryInstance is a named item collection within a campaign. Standalone — not tied to a specific entity.

type ItemCard

type ItemCard struct {
	ID        string         `json:"id"`
	Name      string         `json:"name"`
	Slug      string         `json:"slug"`
	ImagePath *string        `json:"image_path,omitempty"`
	TypeLabel *string        `json:"type_label,omitempty"` // Freeform subtype (e.g., "Weapon", "Potion").
	TypeName  string         `json:"type_name"`
	TypeIcon  string         `json:"type_icon"`
	TypeColor string         `json:"type_color"`
	Fields    map[string]any `json:"fields_data"`
	IsPrivate bool           `json:"is_private"`
	Tags      []ItemTagInfo  `json:"tags,omitempty"`
}

ItemCard is a lightweight view model for the Armory gallery grid. Fields are sourced from the entities table with joined entity_type info.

func (*ItemCard) FieldString

func (c *ItemCard) FieldString(key string) string

FieldString returns a string field value from the item's fields_data, or empty string if the key is missing or not a string.

type ItemCollection

type ItemCollection struct {
	ID        int    `json:"id"`
	Name      string `json:"name"`
	Icon      string `json:"icon"`
	Color     string `json:"color"`
	ItemCount int    `json:"itemCount"`
	HasItem   bool   `json:"hasItem"`
}

ItemCollection describes one collection from the viewpoint of a single item, so the card menu can tick the collections that already hold it.

type ItemListOptions

type ItemListOptions struct {
	Page       int    // 1-indexed page number.
	PerPage    int    // Items per page (default 24).
	Sort       string // "name" (default), "updated", "created".
	Search     string // Optional name search (substring match).
	Tag        string // Optional tag slug filter.
	TypeID     int    // Optional entity type ID filter (0 = all item types).
	InstanceID int    // Optional inventory instance filter (0 = all items).
	// ShopGoods lists the pages kept out of Items because they exist only
	// to be sold. Only the Director's Shop goods tab sets it.
	ShopGoods bool
}

ItemListOptions controls filtering and pagination for the Armory gallery.

func DefaultItemListOptions

func DefaultItemListOptions() ItemListOptions

DefaultItemListOptions returns sensible defaults for the Armory gallery.

func (ItemListOptions) Offset

func (o ItemListOptions) Offset() int

Offset returns the SQL offset for the current page.

func (ItemListOptions) OrderByClause

func (o ItemListOptions) OrderByClause() string

OrderByClause returns a safe SQL ORDER BY clause based on the Sort field.

type ItemLook

type ItemLook struct {
	// Look names a gallery look. "" means the item has no look of its own,
	// which is allowed only when it is made from a page that has one.
	Look string `json:"look"`
	// Tint replaces the look's own colour; "" keeps it.
	Tint string `json:"tint,omitempty"`
	// Sound replaces the look's own sound; "" keeps it, "none" is silent.
	Sound string `json:"sound,omitempty"`
	// Words float up from the target when the item is used.
	Words string `json:"words,omitempty"`
	// Spots places gallery looks on named spots of the stage (the item, its
	// trail, the point of impact, the target's body, the ground), each
	// playing at its own moment. Empty spots stay quiet.
	Spots map[string]ItemLookSpot `json:"spots,omitempty"`
	// MadeFrom is the page (a Remnant, say) the item was made from. The item
	// carries that page's look: as its look when it has none of its own,
	// added on top when it has. One hop only, so a chain of pages never loops.
	MadeFrom string `json:"madeFrom,omitempty"`
}

ItemLook is how an item shows its magic: one look from a fixed gallery, optionally recoloured, with its sound swapped and words that float up when it is used. Every value comes from a fixed list (or is short plain text), so nothing saved here can run code; the item_look widget draws it. The lists are mirrored in static/js/widgets/item_look_fx.js, and test/js/item_look.test.mjs fails when the two drift.

type ItemLookHandler

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

ItemLookHandler serves the look endpoints, which answer {"look": …, "source": …} (see LookView). Thin: the service owns validation and visibility.

func NewItemLookHandler

func NewItemLookHandler(svc ItemLookService) *ItemLookHandler

NewItemLookHandler creates the handler.

func (*ItemLookHandler) Get

func (h *ItemLookHandler) Get(c *echo.Context) error

Get handles GET /campaigns/:id/armory/items/:eid/look.

func (*ItemLookHandler) Put

func (h *ItemLookHandler) Put(c *echo.Context) error

Put handles PUT /campaigns/:id/armory/items/:eid/look.

type ItemLookRepository

type ItemLookRepository interface {
	// Get returns the stored look, or (nil, nil) when the item has none.
	Get(ctx context.Context, campaignID, itemEntityID string) (json.RawMessage, error)
	// Upsert replaces the item's look, recording who saved it.
	Upsert(ctx context.Context, campaignID, itemEntityID, userID string, look json.RawMessage) error
	// Delete removes the item's look; removing a look that is not there is fine.
	Delete(ctx context.Context, campaignID, itemEntityID string) error
	// List returns up to limit looks in the campaign, keyed by page id, and
	// whether more were left unread.
	List(ctx context.Context, campaignID string, limit int) (map[string]json.RawMessage, bool, error)
}

ItemLookRepository stores at most one look per item entity.

func NewItemLookRepository

func NewItemLookRepository(db *sql.DB) ItemLookRepository

NewItemLookRepository creates the repository.

type ItemLookService

type ItemLookService interface {
	// GetLook returns the page's look for a viewer who can see the page. A
	// page that is missing or hidden from the viewer is NotFound, so a
	// hidden page is not confirmed.
	GetLook(ctx context.Context, campaignID, entityID string, role int, userID string) (*LookView, error)
	// SaveLook validates raw and stores it, or clears the look when raw
	// names none, returning what the page now shows. Who may save is
	// decided by the route (Owner).
	SaveLook(ctx context.Context, campaignID, entityID, userID string, raw []byte) (*LookView, error)
	// CheckLook runs SaveLook's checks without saving, so a change can be
	// reviewed before it is made. cleared says raw would clear the look.
	CheckLook(ctx context.Context, campaignID, entityID string, raw []byte) (cleared bool, err error)
	// ListLooks returns the looks on pages the viewer can see, by page name,
	// and whether the campaign has more than were read.
	ListLooks(ctx context.Context, campaignID string, role int, userID string) ([]PageLook, bool, error)
}

ItemLookService reads and saves looks. A look can sit on any page in the campaign: items carry them, and a Remnant's page holds the look the items made from it inherit.

func NewItemLookService

func NewItemLookService(repo ItemLookRepository, entities LookEntityFinder, visibility EntityVisibilityFilter) ItemLookService

NewItemLookService creates the service. With a nil visibility filter every non-Owner viewer is treated as unable to see the page (fail closed).

type ItemLookSpot

type ItemLookSpot struct {
	Look string `json:"look"`
	Tint string `json:"tint,omitempty"`
}

ItemLookSpot is one gallery look placed on a spot, optionally recoloured.

type ItemPrice

type ItemPrice struct {
	Price    float64
	Currency string
}

ItemPrice is a price an item page already sells at in some shop.

type ItemShare

type ItemShare struct {
	CampaignID  string
	CharacterID string
	ItemID      string
	UserID      string
	MadeGrant   bool
	SharedBy    string
}

ItemShare is one holder sharing one item with one player. MadeGrant is set on the row whose share added the player's view grant, so taking the share back knows the grant is sharing's to remove.

type ItemTagInfo

type ItemTagInfo struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Slug  string `json:"slug"`
	Color string `json:"color"`
}

ItemTagInfo holds tag display info for item cards.

type ItemTypeFinder

type ItemTypeFinder interface {
	FindItemTypeIDs(ctx context.Context, campaignID string) ([]int, error)
	FindItemTypes(ctx context.Context, campaignID string) ([]ItemTypeInfo, error)
}

ItemTypeFinder resolves item-category entity types for a campaign. Implemented by the entities.EntityService — injected to avoid circular imports.

type ItemTypeInfo

type ItemTypeInfo struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Icon  string `json:"icon"`
	Color string `json:"color"`
}

ItemTypeInfo holds basic info about an item-category entity type for the type filter dropdown.

type KeepGood

type KeepGood struct {
	Name string `json:"name"`
	// ItemID is the page of a good that has one; empty makes a shop good.
	ItemID   string  `json:"itemId,omitempty"`
	Price    float64 `json:"price"`
	Currency string  `json:"currency,omitempty"`
	// Quantity nil is unlimited.
	Quantity *int `json:"quantity,omitempty"`
	Today    bool `json:"today,omitempty"`
}

KeepGood is one drafted good, as the Director left it.

type KeepInput

type KeepInput struct {
	Goods []KeepGood `json:"goods"`
	// HiddenFromPlayers lists the goods as Director-only, with pages hidden
	// from players too.
	HiddenFromPlayers bool `json:"hiddenFromPlayers,omitempty"`
}

KeepInput is the body of a Keep.

type KeepResult

type KeepResult struct {
	Batch     string `json:"batch"`
	Relations []int  `json:"relations"`
	// Skipped counts goods the shop already sold.
	Skipped int `json:"skipped"`
}

KeepResult names what a Keep wrote, for Undo.

type ListablePage

type ListablePage struct {
	TypeID     int
	IsTemplate bool
	ShopGood   bool
}

ListablePage is what Keep needs to know about a page it is asked to sell.

type ListingActivity

type ListingActivity interface {
	// Active returns the relation ids among ids that have any record.
	Active(ctx context.Context, campaignID, shopEntityID string, ids []int) (map[int]bool, error)
}

ListingActivity finds which listings of a shop have a player's record attached: a counter roll, a purchase, or a Director's note on the good. Removing such a listing would delete the roll and the note with it (they follow the listing), so Undo leaves it in place.

func NewListingActivity

func NewListingActivity(db *sql.DB) ListingActivity

NewListingActivity reads the armory's own tables.

type LogEntry

type LogEntry struct {
	Note         bool
	NoteID       int64
	Before       string
	Bold         string
	After        string
	About        string
	DirectorOnly bool
	CanDelete    bool
	At           time.Time
}

LogEntry is one line of the log as drawn. A fact is a sentence with the item's name set apart (Before, Bold, After); a note carries its words in Before alone.

type LogNight

type LogNight struct {
	// Name is "" for lines no game night had started for yet.
	Name    string
	Tonight bool
	Entries []LogEntry
}

LogNight is a run of entries under one game night.

type LogNote

type LogNote struct {
	ID           int64
	CharacterID  string
	AuthorID     string
	Body         string
	ItemID       string
	DirectorOnly bool
	CreatedAt    time.Time
}

LogNote is one written line.

type LogNoteInput

type LogNoteInput struct {
	Body         string
	ItemID       string
	DirectorOnly bool
}

LogNoteInput is a line to write. ItemID, when set, must be something the hero carries.

type LookEntityFinder

type LookEntityFinder interface {
	EntityName(ctx context.Context, campaignID, entityID string) (name string, ok bool, err error)
}

LookEntityFinder finds the pages a look can sit on. Implemented in internal/app over the entities service. A missing entity, or one in another campaign, is a clean ok=false.

type LookSource

type LookSource struct {
	ID   string          `json:"id,omitempty"`
	Name string          `json:"name,omitempty"`
	URL  string          `json:"url,omitempty"`
	Look json.RawMessage `json:"look"`
}

LookSource is the page an item was made from, as one viewer may see it. ID, Name and URL are empty when the viewer cannot see that page, so the item still carries its look without naming a hidden page.

type LookView

type LookView struct {
	Look   json.RawMessage `json:"look"`
	Source *LookSource     `json:"source"`
}

LookView is what the Look block reads: the page's own look (nil when it has none) and the look it carries from the page it was made from (nil when it was made from nothing, or from a page with no look).

type MemberDirectory

type MemberDirectory interface {
	// MemberRole returns the member's campaign role (permissions.Role* level);
	// ok is false when the user is not a current member.
	MemberRole(ctx context.Context, campaignID, userID string) (role int, ok bool, err error)
	// IsDmGranted reports whether the user holds a co-DM grant.
	IsDmGranted(ctx context.Context, campaignID, userID string) (bool, error)
}

MemberDirectory answers the membership questions acting-as needs. Implemented over the campaigns service in internal/app.

type Memory

type Memory struct {
	Marks []string `json:"marks,omitempty"`
	// Enchants are the enchantments a crafting recipe added to this copy,
	// oldest first. They stay with the copy wherever it moves.
	Enchants []string `json:"enchants,omitempty"`
	Quality  string   `json:"quality,omitempty"`
	// Quirk is the words of a quirk the copy came out with.
	Quirk string `json:"quirk,omitempty"`
	// How is "made" or "harvested"; By and On name who and when, in words.
	How string `json:"how,omitempty"`
	By  string `json:"by,omitempty"`
	On  string `json:"on,omitempty"`
	// OffDay is the calendar day (its absolute count) it goes off, 0 never;
	// OffOn names it in words, and Becomes is the item it turns into then.
	OffDay      int64  `json:"offDay,omitempty"`
	OffOn       string `json:"offOn,omitempty"`
	Becomes     string `json:"becomes,omitempty"`
	BecomesName string `json:"becomesName,omitempty"`
	// Off is set at the respite after OffDay for a copy that becomes
	// nothing: it stays in the pack, marked gone off.
	Off bool `json:"off,omitempty"`
	// Look is how a made copy is drawn (static/js/widgets/craft_results.js),
	// taken from what went into it. It holds a shape, colours and a picture
	// key only, never what the materials were, because what a project took
	// is the Director's.
	Look *CraftLook `json:"look,omitempty"`
}

Memory is what one copy remembers. Every field is optional; a Memory with nothing in it is a plain copy and is never stored.

func (Memory) Clean

func (m Memory) Clean() Memory

Clean keeps what a copy may remember within its limits: marks are trimmed, deduplicated case-blind and capped, and an unknown quality or way of coming by it is dropped.

func (Memory) Empty

func (m Memory) Empty() bool

Empty reports a memory with nothing in it: a plain copy.

func (Memory) HasMark

func (m Memory) HasMark(mark string) bool

HasMark reports whether the copy carries mark, case-blind.

func (Memory) Tags

func (m Memory) Tags() []CopyTag

Tags are the words a copy wears, quality first.

func (Memory) Words

func (m Memory) Words() string

Words say what else a copy remembers, in a line: who made or harvested it and when, its quirk, and when it goes off.

type MoneyHistory

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

MoneyHistory writes the history line for a sheet money edit.

func NewMoneyHistory

func NewMoneyHistory(repo StashRepository, directory StashDirectory, enabled func(ctx context.Context, campaignID string) bool, events StashEventPublisher) *MoneyHistory

NewMoneyHistory creates the recorder. enabled says whether the plugin is on for a campaign (nil means always); events is optional.

func (*MoneyHistory) RecordFieldChange

func (h *MoneyHistory) RecordFieldChange(ctx context.Context, campaignID, entityID string, oldFields, newFields map[string]any) error

RecordFieldChange logs a money change between oldFields and newFields on the entity, when it is a character with a money field. Writes that carry no source, or come from a stash move (which logs itself), are not logged.

type Move

type Move struct {
	ID           int64
	CampaignID   string
	Kind         string
	ItemEntityID string // Empty for money.
	Quantity     int    // 0 for money.
	Amount       Cents  // 0 for items.
	From         Endpoint
	To           Endpoint
	Status       string
	Reason       string
	RequestedBy  string
	DecidedBy    string
	CreatedAt    time.Time
	DecidedAt    *time.Time
	// contains filtered or unexported fields
}

Move is one row of the move history; a pending row is a request.

func (Move) IsGive

func (m Move) IsGive() bool

IsGive reports whether the row records the GM handing an item to a character: an item row whose two ends are the same character. It was applied the moment it was written and never runs again, so no apply path may debit or credit it a second time.

func (Move) IsMoneyEdit

func (m Move) IsMoneyEdit() bool

IsMoneyEdit reports whether the row records a character's money being changed on its sheet rather than a move: a money row whose two ends are the same character.

type MoveDestination

type MoveDestination struct {
	Endpoint Endpoint
	Label    string
	Group    string // "Stashes" or "Characters".
}

MoveDestination is one choice in the "To" select.

type MoveDialogView

type MoveDialogView struct {
	CampaignID   string
	Kind         string
	ItemID       string
	ItemName     string
	From         Endpoint
	FromName     string
	Max          int   // Most of an item that can be moved.
	MaxMoney     Cents // Most money that can be moved.
	Destinations []MoveDestination
	Immediate    bool // True when the move happens at once.
	// Copies are the source's copies of the item that remember something;
	// with any, the box asks which ones go.
	Copies []Copy
}

MoveDialogView feeds the move dialog.

type MoveFilter

type MoveFilter struct {
	// Endpoint, when set, keeps moves that touch it on either side.
	Endpoint *Endpoint
	// RequestedBy, when set, keeps only that user's moves.
	RequestedBy string
	// Status, when set, keeps only that status.
	Status string
	Limit  int
}

MoveFilter narrows a history query. Zero values mean "no restriction".

type MoveInput

type MoveInput struct {
	Kind         string
	ItemEntityID string
	Quantity     int
	Amount       string // Plain decimal text; parsed by ParseCents.
	From         Endpoint
	To           Endpoint
	// Pick is a remembered copy to send first (copies.go); 0 sends plain
	// copies first.
	Pick int64
}

MoveInput is what a player (or the GM) asks for.

type MoveLine

type MoveLine struct {
	Move
	ItemName      string
	FromName      string
	ToName        string
	RequesterName string
	// Summary, when set, is the whole sentence for the row. Purchase requests
	// share the history list and carry their own wording here.
	Summary string
	// Purchase marks a row that is a shop purchase request, whose ID is a
	// request id rather than a move id. CanWithdraw is set only for a waiting
	// one the viewer may take back (its requester, or the Owner).
	Purchase    bool
	CanWithdraw bool
}

MoveLine is a history row with names resolved for display.

type MoveOutcome

type MoveOutcome struct {
	Move    Move
	Applied bool // False when it became a request.
}

MoveOutcome reports what Move did.

type NamedRef

type NamedRef struct {
	ID   string
	Name string
	// Restricted marks an item players cannot all see; giving it adds the
	// holder's player to who can.
	Restricted bool
}

NamedRef is an id with a display name.

type Night

type Night struct {
	ID, Name, Date string
}

Night is a game night as the log groups by it. Date is YYYY-MM-DD.

type NightLister

type NightLister interface {
	Nights(ctx context.Context, campaignID string) ([]Night, error)
}

NightLister names a campaign's game nights. It keeps the armory from importing the sessions plugin.

type PageLook

type PageLook struct {
	EntityID, Name string
	Look           ItemLook
	MadeFromName   string
}

PageLook is one page's own look as ListLooks returns it. Look.MadeFrom is always empty: MadeFromName names that page instead, or is "" when the viewer cannot see it.

type PayInput

type PayInput struct {
	CharacterID string
	Amount      Cents
	Reason      string
}

PayInput is coins the GM adds to one character's sheet. Amount is in the sheet's main unit (gold on a 5e sheet), in hundredths. Reason labels the line in the character's money history ("as a quest reward").

type PayOutcome

type PayOutcome struct {
	CharacterName string `json:"characterName"`
	Paid          string `json:"paid"`
}

PayOutcome names who was paid, for the caller's confirmation.

type Place

type Place string

Place is one of a hero's containers.

const (
	PlaceHand Place = "hand"
	PlaceWorn Place = "worn"
	PlaceBelt Place = "belt"
	PlacePack Place = "pack"
)

func ParsePlace

func ParsePlace(s string) (Place, bool)

ParsePlace reads a submitted place; anything unknown is refused.

func (Place) Label

func (p Place) Label() string

Label is the container's name on the page.

type PlaceStore

type PlaceStore interface {
	// List returns the character's placed items by item id; an item not in
	// the map is in the backpack.
	List(ctx context.Context, campaignID, characterID string) (map[string]Place, error)
	// Set puts an item in a container; the backpack removes the row.
	Set(ctx context.Context, campaignID, characterID, itemID string, p Place) error
}

PlaceStore keeps where a character carries each item.

func NewPlaceRepository

func NewPlaceRepository(db *sql.DB) PlaceStore

NewPlaceRepository returns the SQL place store.

type PurchaseRequest

type PurchaseRequest struct {
	ID            int64
	CampaignID    string
	ShopEntityID  string
	BuyerEntityID string
	RequestedBy   string
	Basket        []BuyItemInput
	// QuotedTotal and QuotedCurrency are the server-computed basket total at
	// request time. Apply refuses a request whose repriced total exceeds it.
	QuotedTotal    Cents
	QuotedCurrency string
	Status         string
	Reason         string
	DecidedBy      string
	CreatedAt      time.Time
	DecidedAt      *time.Time
}

PurchaseRequest is one stored basket. It holds listing ids and quantities only: prices, currency and stock are read from the listings when the request is applied, so a stale figure can never be charged.

func (PurchaseRequest) ItemCount

func (r PurchaseRequest) ItemCount() int

ItemCount is the total quantity across the basket.

type PurchaseRequestLine

type PurchaseRequestLine struct {
	PurchaseRequest
	ShopName      string
	BuyerName     string
	RequesterName string
	Total         *Cents
	Currency      string
	// PriceRose means today's prices add up to more than the player was
	// quoted, so approving will fail; the row shows the quote and says so.
	PriceRose bool
}

PurchaseRequestLine is a request with names resolved for display. Total is nil when the basket can no longer be priced from the listings (a listing was removed or edited to have no price); the row then simply omits the price.

type PurchaseRequestRepository

type PurchaseRequestRepository interface {
	// Insert stores a pending request and sets its ID.
	Insert(ctx context.Context, r *PurchaseRequest) error
	// Get returns one request in the campaign, or NotFound.
	Get(ctx context.Context, campaignID string, id int64) (*PurchaseRequest, error)
	// Settle moves a request from one status to another and reports false when
	// it was not in `from`, so two answers can't both win.
	Settle(ctx context.Context, campaignID string, id int64, from, to, reason, decidedBy string) (bool, error)
	// DeletePending removes a request only while it is still pending and
	// reports whether it did, so a withdrawal cannot race an approval or the
	// downtime sweep: whichever statement runs second matches no row.
	DeletePending(ctx context.Context, campaignID string, id int64) (bool, error)
	// ListPending returns the campaign's pending requests, oldest first.
	ListPending(ctx context.Context, campaignID string) ([]PurchaseRequest, error)
	// CountPendingBy counts one player's pending requests.
	CountPendingBy(ctx context.Context, campaignID, userID string) (int, error)
	// ListForBuyer returns a character's requests, newest first.
	ListForBuyer(ctx context.Context, campaignID, buyerEntityID string, limit int) ([]PurchaseRequest, error)
}

PurchaseRequestRepository defines the data access contract for requests.

func NewPurchaseRequestRepository

func NewPurchaseRequestRepository(db *sql.DB) PurchaseRequestRepository

NewPurchaseRequestRepository creates a purchase request repository.

type PurchaseResult

type PurchaseResult struct {
	Transaction    *Transaction `json:"transaction"`
	StockRemaining int          `json:"stock_remaining"` // -1 means unlimited.
}

PurchaseResult is returned after a successful purchase to inform the caller of the outcome.

type RelationFinder

type RelationFinder interface {
	GetByID(ctx context.Context, id int) (*RelationInfo, error)
}

RelationFinder retrieves a relation by ID. Implemented by the relations widget service.

type RelationInfo

type RelationInfo struct {
	ID             int
	Metadata       json.RawMessage
	CampaignID     string
	SourceEntityID string
	TargetEntityID string
	// RelationType is the stored forward type ("sells" for a shop good).
	RelationType string
	// DmOnly marks a relation hidden from players.
	DmOnly bool
}

RelationInfo is a minimal view of a relation, used by the transaction service. Avoids importing the full relations package.

type RelationMetadataUpdater

type RelationMetadataUpdater interface {
	UpdateMetadata(ctx context.Context, id int, metadata json.RawMessage) error
	// UpdateMetadataIf writes metadata only while the stored value still
	// equals expected, reporting whether it wrote.
	UpdateMetadataIf(ctx context.Context, id int, expected, metadata json.RawMessage) (bool, error)
}

RelationMetadataUpdater updates relation metadata by ID. Implemented by the relations widget service — injected to avoid circular imports.

type RelationRef

type RelationRef int

RelationRef is a shop relation id as the client sends it. The widget may send the id as a JSON number or as a numeral string (relation ids are integers server-side but travel as either in the widget's data).

func (*RelationRef) UnmarshalJSON

func (r *RelationRef) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts a whole number or a string holding one.

type RollDefaults

type RollDefaults struct {
	Haggle string `json:"haggle"`
	Look   string `json:"look"`
}

RollDefaults are the system's own stat keys for each action.

type RollDie

type RollDie struct {
	Sides int `json:"sides"`
	Value int `json:"value"`
}

RollDie is one die as it fell.

type RollGoodView

type RollGoodView struct {
	Haggle *GoodHaggleView `json:"haggle"`
	Look   *GoodLookView   `json:"look"`
}

RollGoodView is one good's counter state for the character.

type RollHaggleResult

type RollHaggleResult struct {
	Pct      int     `json:"pct"`
	Price    float64 `json:"price"`
	Was      float64 `json:"was"`
	Currency string  `json:"currency"`
}

RollHaggleResult is a haggle's effect. Price and Was are numbers in the listing's units; Currency is the listing's currency.

type RollInput

type RollInput struct {
	RelationID  RelationRef `json:"relationId"`
	CharacterID string      `json:"characterId"`
	Action      string      `json:"action"`
}

RollInput is the body of a counter roll.

type RollLookResult

type RollLookResult struct {
	Note  string `json:"note"`
	Extra string `json:"extra"`
}

RollLookResult is what a look uncovered. Both are empty at tier 1.

type RollResult

type RollResult struct {
	Action      string            `json:"action"`
	Dice        []RollDie         `json:"dice"`
	Modifier    int               `json:"modifier"`
	Total       int               `json:"total"`
	Tier        int               `json:"tier"`
	Label       string            `json:"label"`
	Outcome     string            `json:"outcome"`
	StatMissing bool              `json:"statMissing"`
	Haggle      *RollHaggleResult `json:"haggle,omitempty"`
	Look        *RollLookResult   `json:"look,omitempty"`
	RollID      string            `json:"rollId"`
}

RollResult is the response of POST .../rolls.

type RollStatChoice

type RollStatChoice struct {
	Key   string `json:"key"`
	Label string `json:"label"`
}

RollStatChoice is a stat the owner may pick for an action.

type RollStatView

type RollStatView struct {
	Stat    string `json:"stat"`
	Label   string `json:"label"`
	Value   *int   `json:"value,omitempty"`
	Missing *bool  `json:"missing,omitempty"`
	Mod     *int   `json:"mod,omitempty"`
}

RollStatView says what a test adds from the sheet. Value, Missing and Mod are absent when no character is chosen (the owner's settings view).

type RollTestView

type RollTestView struct {
	Dice   string       `json:"dice"`
	Style  string       `json:"style"`
	Haggle RollStatView `json:"haggle"`
	Look   RollStatView `json:"look"`
	// Against is "Easy", "Usual" or "Hard" under style tiers, "DC 15" under dc.
	Against string `json:"against"`
	// StubbornMod is what the keeper's stubbornness adds under style tiers
	// (the edge, 0 or the bane); 0 under dc, where it moves the DC instead.
	StubbornMod int `json:"stubbornMod"`
}

RollTestView describes the test: the dice, what each action adds, and what the total is held against.

type RollsView

type RollsView struct {
	Haggle   bool                    `json:"haggle"`
	Look     bool                    `json:"look"`
	Test     RollTestView            `json:"test"`
	Stats    []RollStatChoice        `json:"stats"`
	Defaults RollDefaults            `json:"defaults"`
	Goods    map[string]RollGoodView `json:"goods"`
}

RollsView is the response of GET .../rolls. Goods is keyed by relation id.

type ShareAuditor

type ShareAuditor interface {
	LogEvent(ctx context.Context, campaignID, userID, action string, details map[string]any) error
}

ShareAuditor records shares in the campaign's activity log. Optional.

type ShareBoxView

type ShareBoxView struct {
	CampaignID string
	Character  NamedRef
	Item       NamedRef
	// IsMap marks a map handout, whose hint says the map opens too.
	IsMap bool
	Party []ShareMember
	// PartyTruncated is true when the campaign has more characters than the
	// listing could walk, so Party may be missing players.
	PartyTruncated bool
}

ShareBoxView feeds the "Who else can see <item>?" box.

type ShareMember

type ShareMember struct {
	UserID    string
	Character string
	Player    string
	Checked   bool
}

ShareMember is one other player in the Share box: their character, their name, and whether the item is already shared with them.

type ShareOutcome

type ShareOutcome struct {
	// Character is the holder, named in the toast when nothing is shared.
	Character  string
	SharedWith []string
}

ShareOutcome reports who the item is shared with after a save, by character name, for the toast and the panel line.

type ShareStore

type ShareStore interface {
	// ListByCharacter returns every share the character's holdings carry.
	ListByCharacter(ctx context.Context, campaignID, characterID string) ([]ItemShare, error)
	// ListByItem returns every holder's shares of the item.
	ListByItem(ctx context.Context, campaignID, itemID string) ([]ItemShare, error)
	// Add records a share; recording one that exists changes nothing.
	Add(ctx context.Context, s ItemShare) error
	// Remove forgets one share.
	Remove(ctx context.Context, campaignID, characterID, itemID, userID string) error
	// SetMadeGrant hands the grant's ownership to another share of the same
	// item and player when the one that made it goes.
	SetMadeGrant(ctx context.Context, campaignID, characterID, itemID, userID string) error
}

ShareStore is the data access contract for item shares.

func NewShareRepository

func NewShareRepository(db *sql.DB) ShareStore

NewShareRepository creates the item share repository.

type SheetStatReader

type SheetStatReader interface {
	Stat(ctx context.Context, campaignID, characterID, key string) (value int, ok bool, err error)
}

SheetStatReader reads one number off a character's sheet. ok is false when the field is missing or holds no number. Implemented in internal/app over the same sheet reader crafting uses.

type ShelfDay

type ShelfDay struct {
	// Index counts shelf days; consecutive days differ by one.
	Index int64
	// HoursToDawn is the whole calendar hours until the shelf changes, or -1
	// when there is no calendar to count them on.
	HoursToDawn int
}

ShelfDay is the day today's shelf is set for. The shelf changes at dawn, so the hours before dawn still belong to the previous day.

type ShelfDayReader

type ShelfDayReader interface {
	ShelfDay(ctx context.Context, campaignID string, role int, userID string) (*ShelfDay, error)
}

ShelfDayReader reads the campaign calendar's current shelf day. Implemented in internal/app over the calendar service. (nil, nil) means the campaign has no calendar, and the real date is used instead. The day is the same for every viewer; HoursToDawn is -1 for a viewer the calendar is hidden from, since it tells the time of day.

type ShopBuyHandler

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

ShopBuyHandler serves the shop-room buy endpoints. Thin: the service owns every rule.

func NewShopBuyHandler

func NewShopBuyHandler(svc ShopRequestService) *ShopBuyHandler

NewShopBuyHandler creates the handler.

func (*ShopBuyHandler) ApproveRequest

func (h *ShopBuyHandler) ApproveRequest(c *echo.Context) error

ApproveRequest handles POST /armory/purchase-requests/:rid/approve.

func (*ShopBuyHandler) Buy

func (h *ShopBuyHandler) Buy(c *echo.Context) error

Buy handles POST /campaigns/:id/armory/shops/:eid/buy.

func (*ShopBuyHandler) Buyers

func (h *ShopBuyHandler) Buyers(c *echo.Context) error

Buyers handles GET /campaigns/:id/armory/shops/:eid/buyers.

func (*ShopBuyHandler) DeclineRequest

func (h *ShopBuyHandler) DeclineRequest(c *echo.Context) error

DeclineRequest handles POST /armory/purchase-requests/:rid/decline.

func (*ShopBuyHandler) WithdrawRequest

func (h *ShopBuyHandler) WithdrawRequest(c *echo.Context) error

WithdrawRequest handles POST /armory/purchase-requests/:rid/withdraw. The service lets only the requester or the Owner through.

type ShopBuyOption

type ShopBuyOption func(*shopBuyService)

ShopBuyOption adds an optional part to the buy flow.

func WithHaggles

func WithHaggles(h HaggleReader) ShopBuyOption

WithHaggles makes the buy flow charge a haggled price on the day it was won.

type ShopBuyService

type ShopBuyService interface {
	// Buyers lists the characters the caller may buy for and whether a buy
	// would apply at once. A shop the caller cannot see is NotFound.
	Buyers(ctx context.Context, campaignID, shopEntityID string, a Actor) (*BuyersView, error)
	// Buy charges the buyer's coins, takes the stock, gives the items and
	// records the purchases. While downtime is closed a player's basket is
	// stored as a request instead (status "requested") and nothing is spent.
	Buy(ctx context.Context, campaignID, shopEntityID string, a Actor, in BuyInput) (*BuyResult, error)
}

ShopBuyService reads who can buy at a shop and applies a basket.

type ShopEntityChecker

type ShopEntityChecker interface {
	IsShopInCampaign(ctx context.Context, campaignID, entityID string) (bool, error)
}

ShopEntityChecker reports whether an entity is a shop in the given campaign. Implemented in internal/app over the entities service so this plugin never touches the entities repository. A missing entity, one in another campaign, or one of another type is a clean false, not an error.

type ShopFront

type ShopFront struct {
	Style  string `json:"style"`
	Colour string `json:"colour"`
	Trim   string `json:"trim,omitempty"`
	// Awning is "none", "plain" or "stripe"; AwningColour colours it.
	Awning       string `json:"awning"`
	AwningColour string `json:"awningColour,omitempty"`
	// Sign is how the name hangs: a swinging board, a fascia board or a banner.
	Sign string `json:"sign"`
	// Words replaces the shop's name on the sign; "" uses the name.
	Words string `json:"words,omitempty"`
	// Icon is the picture on a hanging sign; "" shows none.
	Icon string `json:"icon,omitempty"`
	// Wares are up to three things shown in the windows.
	Wares []string `json:"wares"`
	Lamp  bool     `json:"lamp"`
	// Closed is the look the front takes when the shop is shut.
	Closed        string `json:"closed"`
	ShutterColour string `json:"shutterColour,omitempty"`
	CurtainColour string `json:"curtainColour,omitempty"`
	// ClosedNote is written on the board when Closed is "board".
	ClosedNote string `json:"closedNote,omitempty"`
}

ShopFront is how a shop's storefront is drawn on the Shops street. Every value is from a fixed list, a #rrggbb colour or short plain text, so nothing saved here can run code. The lists are mirrored in static/js/widgets/shop_storefront.js; test/js/shop_storefront.test.mjs fails when the two drift.

func DefaultShopFront

func DefaultShopFront() ShopFront

DefaultShopFront is what a shop with no saved storefront shows.

type ShopFrontRepository

type ShopFrontRepository interface {
	// Get returns the stored storefront, or (nil, nil) when the shop has none.
	Get(ctx context.Context, campaignID, shopEntityID string) (json.RawMessage, error)
	// ListFor returns the stored storefronts of the given shops, keyed by shop.
	ListFor(ctx context.Context, campaignID string, shopEntityIDs []string) (map[string]json.RawMessage, error)
	Upsert(ctx context.Context, campaignID, shopEntityID, userID string, front json.RawMessage) error
}

ShopFrontRepository stores one storefront per shop entity.

func NewShopFrontRepository

func NewShopFrontRepository(db *sql.DB) ShopFrontRepository

NewShopFrontRepository creates the repository.

type ShopGoodPages

type ShopGoodPages interface {
	// EnsureShopGood returns the id of the shop good page called name,
	// making it in the item type when there is none.
	EnsureShopGood(ctx context.Context, campaignID, userID string, typeID int, name string, hiddenFromPlayers bool) (string, error)
	// PageInfo describes a live page of the campaign; nil when there is none.
	PageInfo(ctx context.Context, campaignID, id string) (*ListablePage, error)
	// Names maps page ids to names; ids that are gone are left out.
	Names(ctx context.Context, campaignID string, ids []string) (map[string]string, error)
}

ShopGoodPages finds or makes the page behind a good and reads page names. Implemented in internal/app over the entities service, so this plugin never reaches the entities tables for writes.

type ShopLister

type ShopLister interface {
	ListShops(ctx context.Context, campaignID string, role int, userID string) (shops []StreetShop, truncated bool, err error)
}

ShopLister lists the shop pages a viewer can see. Implemented in internal/app over the entities service, which applies page visibility, so a hidden shop is never listed. truncated is true when the campaign has more shops than one street shows.

type ShopListing

type ShopListing struct {
	RelationID     int
	TargetEntityID string
	DmOnly         bool
	Metadata       json.RawMessage
}

ShopListing is one "sells" listing of a shop, as today's shelf reads it.

type ShopListingLister

type ShopListingLister interface {
	ListSells(ctx context.Context, campaignID, shopEntityID string) ([]ShopListing, error)
}

ShopListingLister lists a shop's "sells" listings. Implemented in internal/app over the relations service.

type ShopPriceRepository

type ShopPriceRepository interface {
	// FoodPrice is a day's food in the main coin; DefaultFoodPrice with no row.
	FoodPrice(ctx context.Context, campaignID string) (float64, error)
	SaveFoodPrice(ctx context.Context, campaignID, userID string, price float64) error
	// ItemPrices maps item page ids to the newest positive price a shop lists
	// them at, so a fill reuses what the Director already decided.
	ItemPrices(ctx context.Context, campaignID string) (map[string]ItemPrice, error)
}

ShopPriceRepository stores the one number everyday prices scale from and reads prices the campaign has already set on listings.

func NewShopPriceRepository

func NewShopPriceRepository(db *sql.DB) ShopPriceRepository

NewShopPriceRepository creates the repository.

type ShopRequestService

type ShopRequestService interface {
	ShopBuyService
	// ApproveRequest applies a waiting purchase request now. Owner visibility only.
	ApproveRequest(ctx context.Context, campaignID string, a Actor, requestID int64) (*PurchaseRequest, error)
	// DeclineRequest turns a waiting purchase request down. Owner visibility only.
	DeclineRequest(ctx context.Context, campaignID string, a Actor, requestID int64) (*PurchaseRequest, error)
	// WithdrawRequest deletes a waiting request on the requester's or the
	// Owner's say. A request that has been answered is a Conflict.
	WithdrawRequest(ctx context.Context, campaignID string, a Actor, requestID int64) error
}

ShopRequestService is the buy flow plus the GM's answers to waiting purchase requests. It is separate so callers that only buy, like the sync API, depend on the smaller interface.

func NewShopBuyService

func NewShopBuyService(stash *stashService, tx *transactionService, shops ShopEntityChecker, requests PurchaseRequestRepository, today ShopTodayService, opts ...ShopBuyOption) ShopRequestService

NewShopBuyService wires the buy flow. It takes the concrete stash and transaction services because it must share the stash service's campaign lock and its money and inventory helpers; a second copy of those would let the two paths drift apart.

It also hands the stash service the two hooks that need purchase requests: the downtime-open sweep and the stashes page. Opening downtime lives in the stash service and runs under the campaign lock, so the sweep must be reachable from there without the stash service importing this one.

type ShopRoll

type ShopRoll struct {
	ID           int64
	CampaignID   string
	ShopEntityID string
	RelationID   int
	CharacterID  string
	Action       string
	ShelfDay     int64
	Tier         int
	// Pct is a haggle's price change in percent (negative is a discount).
	Pct   int
	Total int
}

ShopRoll is one stored counter roll.

type ShopRollDeps

type ShopRollDeps struct {
	Repo     ShopRollRepository
	Rooms    ShopRoomRepository
	Stash    *stashService
	Shops    ShopEntityChecker
	Rels     RelationFinder
	Listings ShopListingLister
	Today    ShopTodayService
	Rules    ShopTestRulesReader
	Sheets   SheetStatReader
	// Log is optional; without it rolls are made but not logged.
	Log ShopRollLog
}

ShopRollDeps are what the service needs.

type ShopRollHandler

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

ShopRollHandler serves the counter roll endpoints and the owner's hidden notes. Thin: the service owns every rule.

func NewShopRollHandler

func NewShopRollHandler(svc ShopRollService) *ShopRollHandler

NewShopRollHandler creates the handler.

func (*ShopRollHandler) PutSecret

func (h *ShopRollHandler) PutSecret(c *echo.Context) error

PutSecret handles PUT /campaigns/:id/armory/shops/:eid/secrets/:rel.

func (*ShopRollHandler) Roll

func (h *ShopRollHandler) Roll(c *echo.Context) error

Roll handles POST /campaigns/:id/armory/shops/:eid/rolls.

func (*ShopRollHandler) Rolls

func (h *ShopRollHandler) Rolls(c *echo.Context) error

Rolls handles GET /campaigns/:id/armory/shops/:eid/rolls?character=<id>.

func (*ShopRollHandler) Secrets

func (h *ShopRollHandler) Secrets(c *echo.Context) error

Secrets handles GET /campaigns/:id/armory/shops/:eid/secrets.

type ShopRollLog

type ShopRollLog interface {
	Rolled(ctx context.Context, campaignID string, e ShopRollLogEntry) string
}

ShopRollLog adds a roll to the campaign's public roll log and returns the log's id for it ("" when it could not be logged). A failed log never fails the roll. Implemented in internal/app over the rolls plugin.

type ShopRollLogEntry

type ShopRollLogEntry struct {
	RollerID   string
	RollerName string
	Label      string
	Formula    string
	Dice       []RollDie
	Modifier   int
	Total      int
	Outcome    string
	From       string
}

ShopRollLogEntry is a counter roll as the Table's log shows it. It never carries a hidden note or extra.

type ShopRollRepository

type ShopRollRepository interface {
	// Secrets returns every hidden note of a shop by relation id.
	Secrets(ctx context.Context, campaignID, shopEntityID string) (map[int]GoodSecret, error)
	// SaveSecret stores a good's note and extra; both empty deletes the row.
	SaveSecret(ctx context.Context, campaignID, shopEntityID string, relationID int, s GoodSecret) error
	// InsertRoll records a roll. The table's unique key is the one-try-a-day
	// rule, so a repeat is errAlreadyTried and nothing is stored.
	InsertRoll(ctx context.Context, r ShopRoll) (int64, error)
	// CharacterRolls returns every roll a character has made at a shop, on any day.
	CharacterRolls(ctx context.Context, campaignID, shopEntityID, characterID string) ([]ShopRoll, error)
	// Haggles returns the price change in percent of each good the character
	// haggled over on one shelf day, by relation id. It is the buy route's read.
	Haggles(ctx context.Context, campaignID, shopEntityID, characterID string, shelfDay int64) (map[int]int, error)
}

ShopRollRepository stores the owner's hidden notes and the counter rolls. Every query is scoped by campaign and shop, so an id from another campaign or shop matches nothing.

func NewShopRollRepository

func NewShopRollRepository(db *sql.DB) ShopRollRepository

NewShopRollRepository creates the repository.

type ShopRollService

type ShopRollService interface {
	// Rolls describes the test and the caller's character's state at a shop.
	// With no character only the Owner may ask, for the settings view.
	Rolls(ctx context.Context, campaignID, shopEntityID string, a Actor, characterID string) (*RollsView, error)
	// Roll throws one haggle or look for a character and applies the result.
	Roll(ctx context.Context, campaignID, shopEntityID string, a Actor, in RollInput) (*RollResult, error)
	// Secrets lists the shop's hidden notes by relation id. Owner only.
	Secrets(ctx context.Context, campaignID, shopEntityID string, a Actor) (map[string]GoodSecret, error)
	// SaveSecret sets one good's note and extra; both empty deletes them.
	// Owner only.
	SaveSecret(ctx context.Context, campaignID, shopEntityID string, relationID int, a Actor, in GoodSecret) (*GoodSecret, error)
}

ShopRollService is the counter rolls and the owner's hidden notes.

func NewShopRollService

func NewShopRollService(d ShopRollDeps) ShopRollService

NewShopRollService creates the service. Dice come from the system's secure random source.

type ShopRoomCounter

type ShopRoomCounter struct {
	Name     string                  `json:"name"`
	Version  int                     `json:"version"`
	Skeleton ShopRoomCounterSkeleton `json:"skeleton"`
	Theme    ShopRoomCounterTheme    `json:"theme"`
	Props    []string                `json:"props"`
}

ShopRoomCounter is the counter look's room as three layers: the skeleton (back wall, opening, how goods are shown, the counter), the theme (wall material, colours, light, outside) and the props. The widget draws every part from these values, so each enum must match CM_OPT and CM_PROPS in static/js/widgets/shop_room_counter.js.

type ShopRoomCounterSkeleton

type ShopRoomCounterSkeleton struct {
	Shape   string `json:"shape"`
	Opening string `json:"opening"`
	Display string `json:"display"`
	Counter string `json:"counter"`
}

ShopRoomCounterSkeleton is the room's shape, before any paint.

type ShopRoomCounterTheme

type ShopRoomCounterTheme struct {
	Wall    string  `json:"wall"`
	Wood    string  `json:"wood"`
	Cloth   string  `json:"cloth"`
	Accent  string  `json:"accent"`
	Trim    string  `json:"trim"`
	Light   string  `json:"light"`
	Warmth  float64 `json:"warmth"`
	Outside string  `json:"outside"`
}

ShopRoomCounterTheme is the paint and the light. Colours are #rrggbb; Warmth runs 0 (cool) to 1 (warm).

type ShopRoomDecor

type ShopRoomDecor struct {
	Piece int    `json:"piece"`
	Spot  int    `json:"spot"`
	Icon  string `json:"icon"`
}

ShopRoomDecor is a decoration the GM placed by hand: an icon standing on one of a furniture piece's spots (Spot indexes that piece's spots in drawing order). It is dropped when its piece is gone.

type ShopRoomEffects

type ShopRoomEffects struct {
	Shadows  int  `json:"shadows"`
	Warmth   int  `json:"warmth"`
	Window   int  `json:"window"`
	Haze     int  `json:"haze"`
	Vignette int  `json:"vignette"`
	Dust     bool `json:"dust"`
	Flicker  bool `json:"flicker"`
	Embers   bool `json:"embers"`
	Smoke    bool `json:"smoke"`
	// Weather and Time are "" for none/default.
	Weather string `json:"weather"`
	Time    string `json:"time"`
}

ShopRoomEffects is the room's atmosphere. The int fields are percentages of the default look (100 = unchanged), so a GM can dim or boost each one.

func (*ShopRoomEffects) UnmarshalJSON

func (e *ShopRoomEffects) UnmarshalJSON(b []byte) error

UnmarshalJSON starts from the default look, so a field the body leaves out keeps its default instead of becoming zero (no shadows, no dust).

type ShopRoomHandler

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

ShopRoomHandler serves the shop room layout endpoints. Thin: the service owns validation and visibility.

func NewShopRoomHandler

func NewShopRoomHandler(svc ShopRoomService) *ShopRoomHandler

NewShopRoomHandler creates the handler.

func (*ShopRoomHandler) Get

func (h *ShopRoomHandler) Get(c *echo.Context) error

Get handles GET /campaigns/:id/armory/shops/:eid/room.

func (*ShopRoomHandler) Put

func (h *ShopRoomHandler) Put(c *echo.Context) error

Put handles PUT /campaigns/:id/armory/shops/:eid/room.

type ShopRoomItemLook

type ShopRoomItemLook struct {
	Icon  string `json:"icon"`
	Color string `json:"color"`
}

ShopRoomItemLook is how one shop good (a "sells" relation) is drawn. Both fields may be empty, meaning the widget picks a default.

type ShopRoomLayout

type ShopRoomLayout struct {
	Version     int    `json:"version"`
	RoomType    string `json:"roomType"`
	Setting     string `json:"setting"`
	Size        string `json:"size"`
	Furniture   string `json:"furniture"`
	Decorations string `json:"decorations"`
	Palette     string `json:"palette"`
	// Look is how the room is drawn: "counter" (standing at the counter, able
	// to turn round to the shop floor) or "paper" (a pop-up book, under
	// construction). "lit" and empty are accepted from older layouts and open
	// at the counter: the lit room is retired.
	Look string `json:"look"`
	// Mood themes the room's furniture and atmosphere. Empty, from layouts
	// saved before moods existed, is no mood.
	Mood string `json:"mood"`
	// Effects tunes the atmosphere. Nil, from older layouts, means the widget's
	// defaults; a pointer keeps "never set" distinct from "all zero".
	Effects  *ShopRoomEffects            `json:"effects"`
	Seeds    ShopRoomSeeds               `json:"seeds"`
	Pieces   []ShopRoomPiece             `json:"pieces"`
	Decor    []ShopRoomDecor             `json:"decor"`
	Items    map[string]ShopRoomItemLook `json:"items"`
	Portrait *ShopRoomPortrait           `json:"portrait"`
	Lines    []string                    `json:"lines"`
	// Manner is the keeper's manner, which supplies starting lines for each
	// moment of a visit; empty means none. Moments holds the GM's own lines
	// per moment (keys in shopRoomMoments), which win over the manner's.
	Manner  string              `json:"manner,omitempty"`
	Moments map[string][]string `json:"moments,omitempty"`
	// KeeperSpot is where the paper look's keeper stands behind the counter:
	// "left", "middle" or "right". Empty is the middle, as before there was a choice.
	KeeperSpot string `json:"keeperSpot,omitempty"`
	// Counter is the counter look's theme. Nil means the starter for the
	// shop's type, so a shop that never opened the builder is drawn as before.
	Counter *ShopRoomCounter `json:"counter,omitempty"`
	// Rolls is what players may roll at this shop's counter and how hard the
	// owner makes it. Nil means both rolls are off. Nothing a roll can reveal
	// lives here: the layout is read by every player who can see the shop.
	Rolls *ShopRoomRolls `json:"rolls,omitempty"`
	// Furnish asks the widget to lay out the furniture when the room opens,
	// because something other than Arrange changed what the room is (the AI
	// connection): "room" rebuilds it around pieces moved by hand, as
	// rerolling the room does, and "mood" swaps the mood's pieces only. The
	// widget never sends it, so the owner's next save in Arrange clears it.
	Furnish string `json:"furnish,omitempty"`
}

ShopRoomLayout is the typed form of a saved shop room. Layouts are decoded into this and re-marshalled, never stored as the client sent them, so the stored document can only contain fields and values validated here.

type ShopRoomPiece

type ShopRoomPiece struct {
	ID     int     `json:"id"`
	Kind   string  `json:"kind"`
	Wall   string  `json:"wall"`
	X      float64 `json:"x"`
	Y      float64 `json:"y"`
	Off    float64 `json:"off"`
	Len    float64 `json:"len"`
	W      float64 `json:"w"`
	D      float64 `json:"d"`
	Pinned bool    `json:"pinned"`
}

ShopRoomPiece is one placed furniture piece. Coordinates are in room tiles.

type ShopRoomPortrait

type ShopRoomPortrait struct {
	Left float64 `json:"left"`
	Top  float64 `json:"top"`
}

ShopRoomPortrait positions the shopkeeper portrait, as percentages.

type ShopRoomRepository

type ShopRoomRepository interface {
	// Get returns the stored layout, or (nil, nil) when the shop has none.
	Get(ctx context.Context, campaignID, shopEntityID string) (json.RawMessage, error)
	// Upsert replaces the shop's layout, recording who saved it.
	Upsert(ctx context.Context, campaignID, shopEntityID, userID string, layout json.RawMessage) error
}

ShopRoomRepository stores one saved room layout per shop entity.

func NewShopRoomRepository

func NewShopRoomRepository(db *sql.DB) ShopRoomRepository

NewShopRoomRepository creates the repository.

type ShopRoomRolls

type ShopRoomRolls struct {
	Haggle bool `json:"haggle"`
	Look   bool `json:"look"`
	// Stubborn is how hard the keeper is to move: "easy", "usual" or "hard".
	Stubborn string `json:"stubborn"`
	// HaggleStat and LookStat are sheet field keys; empty is the game
	// system's own choice.
	HaggleStat string `json:"haggleStat"`
	LookStat   string `json:"lookStat"`
	Great      int    `json:"great"`
	Middling   int    `json:"middling"`
	Poor       int    `json:"poor"`
}

ShopRoomRolls is the owner's settings for the counter rolls. Every number is a default the owner may change. Great, Middling and Poor are percentages of a good's price: a great haggle takes Great off, a middling one Middling, a poor one adds Poor.

func (*ShopRoomRolls) UnmarshalJSON

func (r *ShopRoomRolls) UnmarshalJSON(b []byte) error

UnmarshalJSON starts from the defaults, so a body that leaves out a number keeps its default instead of becoming a free haggle (0%) or an unreadable keeper; the two switches still default to off.

type ShopRoomSeeds

type ShopRoomSeeds struct {
	Room  int `json:"room"`
	Goods int `json:"goods"`
	Deco  int `json:"deco"`
}

ShopRoomSeeds drive the widget's deterministic procedural layout, so a room looks the same for every viewer.

type ShopRoomService

type ShopRoomService interface {
	// GetRoom returns the stored layout for a shop the viewer can see, or
	// (nil, nil) when none is saved yet. A shop that is missing, not a shop,
	// or hidden from the viewer is NotFound, so a hidden shop is not confirmed.
	GetRoom(ctx context.Context, campaignID, shopEntityID string, role int, userID string) (json.RawMessage, error)
	// SaveRoom validates raw, stores the normalized layout and returns it.
	// Who may save is decided by the route (Owner); the service only checks
	// the shop belongs to the campaign.
	SaveRoom(ctx context.Context, campaignID, shopEntityID, userID string, raw []byte) (json.RawMessage, error)
}

ShopRoomService reads and saves shop room layouts.

func NewShopRoomService

func NewShopRoomService(repo ShopRoomRepository, shops ShopEntityChecker, visibility EntityVisibilityFilter) ShopRoomService

NewShopRoomService creates the service. With a nil visibility filter every non-Owner viewer is treated as unable to see the shop (fail closed).

type ShopShelfRepository

type ShopShelfRepository interface {
	// GetSpots returns the stored number, or 0 when the shop has none.
	GetSpots(ctx context.Context, campaignID, shopEntityID string) (int, error)
	UpsertSpots(ctx context.Context, campaignID, shopEntityID, userID string, spots int) error
}

ShopShelfRepository stores how many places a shop's today's shelf has.

func NewShopShelfRepository

func NewShopShelfRepository(db *sql.DB) ShopShelfRepository

NewShopShelfRepository creates the repository.

type ShopStockHandler

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

ShopStockHandler serves Fill the shelves. Thin: the service owns every rule.

func NewShopStockHandler

func NewShopStockHandler(svc ShopStockService) *ShopStockHandler

NewShopStockHandler creates the handler.

func (*ShopStockHandler) Keep

func (h *ShopStockHandler) Keep(c *echo.Context) error

Keep handles POST /campaigns/:id/armory/shops/:eid/stock.

func (*ShopStockHandler) PutFoodPrice

func (h *ShopStockHandler) PutFoodPrice(c *echo.Context) error

PutFoodPrice handles PUT /campaigns/:id/armory/food-price.

func (*ShopStockHandler) Sources

func (h *ShopStockHandler) Sources(c *echo.Context) error

Sources handles GET /campaigns/:id/armory/shops/:eid/fill-sources.

func (*ShopStockHandler) Undo

func (h *ShopStockHandler) Undo(c *echo.Context) error

Undo handles POST /campaigns/:id/armory/shops/:eid/stock/undo.

type ShopStockService

type ShopStockService interface {
	Sources(ctx context.Context, campaignID, shopEntityID string, a Actor) (*FillSources, error)
	Keep(ctx context.Context, campaignID, shopEntityID string, a Actor, in KeepInput) (*KeepResult, error)
	// Undo removes the listings of one Keep and returns how many it removed
	// and which it left because a roll, purchase or note is attached.
	Undo(ctx context.Context, campaignID, shopEntityID string, a Actor, batch string, relationIDs []int) (removed int, kept []int, err error)
	SaveFoodPrice(ctx context.Context, campaignID string, a Actor, price float64) (float64, error)
}

ShopStockService drafts and keeps stock. Every method is Director-only (Owner visibility); the route checks too.

func NewShopStockService

func NewShopStockService(shops ShopEntityChecker, pages ShopGoodPages, writer ShopStockWriter, listings ShopListingLister, finder RelationFinder, prices ShopPriceRepository, items ArmoryService, types ItemTypeFinder, system SystemGoodsSource, tx StockTx, activity ListingActivity) ShopStockService

NewShopStockService wires the service. system, tx and activity may be nil (tests): without tx the batch is not atomic.

type ShopStockWriter

type ShopStockWriter interface {
	CreateSells(ctx context.Context, campaignID, shopEntityID, itemEntityID, userID string, metadata json.RawMessage, dmOnly bool) (int, error)
	DeleteSells(ctx context.Context, relationID int) error
}

ShopStockWriter creates and removes "sells" listings. Implemented in internal/app over the relations service.

type ShopStreetHandler

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

ShopStreetHandler serves the Shops street and storefront saves. Thin: the service owns validation and visibility.

func NewShopStreetHandler

func NewShopStreetHandler(svc ShopStreetService) *ShopStreetHandler

NewShopStreetHandler creates the handler.

func (*ShopStreetHandler) PutFront

func (h *ShopStreetHandler) PutFront(c *echo.Context) error

PutFront handles PUT /campaigns/:id/armory/shops/:eid/front.

func (*ShopStreetHandler) Street

func (h *ShopStreetHandler) Street(c *echo.Context) error

Street handles GET /campaigns/:id/armory/shops/street.

type ShopStreetService

type ShopStreetService interface {
	Street(ctx context.Context, campaignID string, role int, userID string) (*StreetView, error)
	// SaveFront validates raw and stores it as the shop's storefront. Who may
	// save is decided by the route (Owner).
	SaveFront(ctx context.Context, campaignID, shopEntityID, userID string, raw []byte) (json.RawMessage, error)
	// Front is one shop's storefront, or DefaultShopFront with saved false
	// while it has none. A page that is not a shop of the campaign is
	// NotFound. Callers check who may read it, as the AI connection does.
	Front(ctx context.Context, campaignID, shopEntityID string) (front json.RawMessage, saved bool, err error)
}

ShopStreetService reads the street and saves storefronts.

func NewShopStreetService

func NewShopStreetService(repo ShopFrontRepository, shops ShopEntityChecker, lister ShopLister, downtime DowntimeReader) ShopStreetService

NewShopStreetService creates the service.

type ShopTestRules

type ShopTestRules struct {
	Dice   string
	Style  string // "tiers" or "dc"
	Stats  []ShopTestStat
	Haggle string // default stat keys; empty adds nothing
	Look   string
	Tiers  []int // style tiers: totals up to Tiers[0] are tier 1, up to Tiers[1] tier 2
	Edge   int   // style tiers: what an easy keeper adds
	Bane   int   // style tiers: what a hard keeper adds
	// DCEasy, DCUsual and DCHard are the difficulties of style dc.
	DCEasy, DCUsual, DCHard int
}

ShopTestRules is how a shop test is thrown under the campaign's game system. It mirrors the systems package's resolved rules so this plugin never imports it; internal/app converts.

type ShopTestRulesReader

type ShopTestRulesReader interface {
	ShopTestRules(ctx context.Context, campaignID string) ShopTestRules
}

ShopTestRulesReader decides the rules for a campaign: its enabled game system's, else the defaults. Implemented in internal/app.

type ShopTestStat

type ShopTestStat struct {
	Key   string
	Label string
	Score bool
}

ShopTestStat is one sheet number a shop test may add. Score marks a D&D ability score, where the test adds floor((value-10)/2).

type ShopTodayHandler

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

ShopTodayHandler serves today's shelf. Thin: the service owns the pick and visibility.

func NewShopTodayHandler

func NewShopTodayHandler(svc ShopTodayService) *ShopTodayHandler

NewShopTodayHandler creates the handler.

func (*ShopTodayHandler) Get

func (h *ShopTodayHandler) Get(c *echo.Context) error

Get handles GET /campaigns/:id/armory/shops/:eid/today.

func (*ShopTodayHandler) Put

func (h *ShopTodayHandler) Put(c *echo.Context) error

Put handles PUT /campaigns/:id/armory/shops/:eid/today.

type ShopTodayService

type ShopTodayService interface {
	Today(ctx context.Context, campaignID, shopEntityID string, a Actor) (*TodayView, error)
	// SaveSpots stores the number of places, clamped to the allowed range.
	// Who may save is decided by the route (Owner).
	SaveSpots(ctx context.Context, campaignID, shopEntityID, userID string, spots int) (*TodayView, error)
	// OnShelf reports whether a listing may be bought today: true for every
	// good that is not flagged for today's shelf.
	OnShelf(ctx context.Context, campaignID, shopEntityID string, relationID int, meta shopMeta) (bool, error)
	// ShelfDayIndex is the day number today's shelf is set for, the same for
	// every viewer. Counter rolls hold for one such day.
	ShelfDayIndex(ctx context.Context, campaignID string) (int64, error)
}

ShopTodayService works out today's shelf and saves its number of places.

func NewShopTodayService

func NewShopTodayService(repo ShopShelfRepository, shops ShopEntityChecker, visibility EntityVisibilityFilter, listings ShopListingLister, days ShelfDayReader) ShopTodayService

NewShopTodayService creates the service. days may be nil (no calendar plugin), and the real date is used.

type Stash

type Stash struct {
	ID         int
	CampaignID string
	Name       string
	Location   string // Empty when none is set.
	Money      Cents
	CreatedBy  string
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

Stash is a named holding place shared by a campaign.

type StashAPI

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

StashAPI adapts StashService to the sync API's wire shapes. It holds no rules of its own beyond choosing who the caller acts as.

func NewStashAPI

func NewStashAPI(svc StashService, members MemberDirectory) *StashAPI

NewStashAPI creates the sync API facade.

func (*StashAPI) ActorFor

func (a *StashAPI) ActorFor(ctx context.Context, campaignID, keyUserID, actingUserID string) (Actor, error)

ActorFor builds the Actor a call runs as: the named member when actingUserID is set, else the caller. Roles are real campaign roles, promoted to Owner visibility only by a real co-DM grant, exactly as the web layer's VisibilityRole does. A non-member is NotFound.

Only a caller who is themselves Owner or co-DM may name someone else: the same routes also answer browser sessions, where the caller can be a player, and naming the GM must never lift a player to the GM's rights.

func (*StashAPI) Approve

func (a *StashAPI) Approve(ctx context.Context, campaignID, keyUserID, actingUserID string, moveID int64) (*APIMoveResult, error)

Approve answers a pending request with a yes, as the acting member.

func (*StashAPI) Decline

func (a *StashAPI) Decline(ctx context.Context, campaignID, keyUserID, actingUserID string, moveID int64) (*APIMoveResult, error)

Decline answers a pending request with a no, as the acting member.

func (*StashAPI) Downtime

func (a *StashAPI) Downtime(ctx context.Context, campaignID string) (*APIDowntime, error)

Downtime reports the switch. It is campaign-wide and not secret, so no acting member is needed.

func (*StashAPI) History

func (a *StashAPI) History(ctx context.Context, campaignID, keyUserID, actingUserID, characterID, stashID string) (*APIHistory, error)

History returns the move history of one character or one stash, as the acting member may see it. Exactly one of characterID and stashID is needed.

func (*StashAPI) Move

func (a *StashAPI) Move(ctx context.Context, campaignID, keyUserID string, req APIMoveRequest) (*APIMoveResult, error)

Move applies or queues a move as the acting member.

func (*StashAPI) Requests

func (a *StashAPI) Requests(ctx context.Context, campaignID, keyUserID, actingUserID string) (*APIRequests, error)

Requests lists the pending requests; the acting member must be able to answer them.

func (*StashAPI) SetDowntime

func (a *StashAPI) SetDowntime(ctx context.Context, campaignID, keyUserID, actingUserID string, open bool) (*APIDowntime, error)

SetDowntime opens or closes downtime; only an approver may.

func (*StashAPI) View

func (a *StashAPI) View(ctx context.Context, campaignID, keyUserID, actingUserID, characterID string) (*APIStashView, error)

View returns what the acting member sees for one character: it is the web panel and stashes page computed for that member, so the same rules and the same redaction apply.

type StashDeps

type StashDeps struct {
	Repo       StashRepository
	Directory  StashDirectory
	Visibility EntityVisibilityFilter
	// Actor says whether a user may act as (move things out of) a character.
	Actor     BuyerAccessChecker
	Fields    EntityFieldUpdater
	Relations HasItemStore
	UserNames UserNamer
	// Events announces finished moves and downtime changes; optional.
	Events StashEventPublisher
	// Handouts lets the GM give a map; without it only items can be given.
	Handouts HandoutStore
	// Notifier tells a player their character was given something; optional.
	Notifier GiveNotifier
	// Shares records the grants players add by sharing a hidden item; nil
	// (the armory plugin's own table did not migrate) turns sharing off.
	Shares ShareStore
	// Auditor writes shares to the campaign's activity log; optional.
	Auditor ShareAuditor
	// Copies keeps what single copies remember (copies.go); nil (the armory
	// plugin's own table did not migrate) leaves every item plain.
	Copies CopyStore
	// Places keeps which container a hero carries each item in (places.go);
	// nil leaves everything in the backpack and the page can't rearrange.
	Places PlaceStore
	// Members re-checks that a waiting request's author is still in the
	// campaign when it is finally settled; nil skips that check.
	Members MemberDirectory
}

StashDeps are the collaborators a stash service needs.

type StashDirectory

type StashDirectory interface {
	// GetEntity returns the entity, or nil (and no error) when it does not
	// exist in campaignID, so a foreign id and a missing id look the same.
	GetEntity(ctx context.Context, campaignID, entityID string) (*EntityRef, error)
	// ListCharacters returns the character-family entities in the campaign
	// that the viewer may see.
	ListCharacters(ctx context.Context, campaignID string, role int, userID string) ([]EntityRef, error)
	// ListCharactersChecked is ListCharacters plus whether a safety bound cut
	// the walk short, for callers (the Share box) that must not drop players
	// silently.
	ListCharactersChecked(ctx context.Context, campaignID string, role int, userID string) (chars []EntityRef, truncated bool, err error)
	// ListItems returns up to limit item entities the viewer may see.
	ListItems(ctx context.Context, campaignID string, role int, userID string, limit int) ([]EntityRef, error)
	// OwnedCharacterIDs returns the entities the user has claimed.
	OwnedCharacterIDs(ctx context.Context, campaignID, userID string) (map[string]bool, error)
}

StashDirectory answers the entity questions the stash rules need. Implemented by an adapter over entities.EntityService.

type StashEventPublisher

type StashEventPublisher interface {
	PublishStashEvent(eventType, campaignID, resourceID string, payload map[string]any)
}

StashEventPublisher delivers one event to the campaign's live clients. Implemented over the websocket event bus in internal/app; optional, so tests and a bus-less setup simply publish nothing.

type StashHandler

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

StashHandler serves the stash, move and downtime endpoints.

func NewStashHandler

func NewStashHandler(svc StashService) *StashHandler

NewStashHandler creates the stash handler.

func (*StashHandler) AddItem

func (h *StashHandler) AddItem(c *echo.Context) error

AddItem handles POST /armory/stashes/:sid/items.

func (*StashHandler) AddLogNote

func (h *StashHandler) AddLogNote(c *echo.Context) error

AddLogNote handles POST /armory/characters/:eid/log: a line in the hero's log. The panel reloads itself on the armory-moved signal.

func (*StashHandler) Approve

func (h *StashHandler) Approve(c *echo.Context) error

Approve handles POST /armory/moves/:mid/approve.

func (*StashHandler) CharacterHistory

func (h *StashHandler) CharacterHistory(c *echo.Context) error

CharacterHistory handles GET /armory/characters/:eid/history.

func (*StashHandler) CharacterPanel

func (h *StashHandler) CharacterPanel(c *echo.Context) error

CharacterPanel handles GET /armory/characters/:eid/panel. A character the viewer has no business with answers with an empty fragment, so the page that asked for it simply shows nothing there.

func (*StashHandler) CreateStash

func (h *StashHandler) CreateStash(c *echo.Context) error

CreateStash handles POST /armory/stashes.

func (*StashHandler) Decline

func (h *StashHandler) Decline(c *echo.Context) error

Decline handles POST /armory/moves/:mid/decline.

func (*StashHandler) DeleteLogNote

func (h *StashHandler) DeleteLogNote(c *echo.Context) error

DeleteLogNote handles POST /armory/characters/:eid/log/:nid/delete.

func (*StashHandler) DeleteStash

func (h *StashHandler) DeleteStash(c *echo.Context) error

DeleteStash handles DELETE /armory/stashes/:sid.

func (*StashHandler) Give

func (h *StashHandler) Give(c *echo.Context) error

Give handles POST /armory/give. Besides the usual reload signal it answers with armory-given, which the Give box reads for its toast and to flash the line the item landed on.

func (*StashHandler) GiveDialog

func (h *StashHandler) GiveDialog(c *echo.Context) error

GiveDialog handles GET /armory/give: the Give box. ?character= fixes the recipient (the character page's box), ?item= fixes the item (the Armory card's box); ?list=items&q= answers the box's search with the list alone.

func (*StashHandler) Move

func (h *StashHandler) Move(c *echo.Context) error

Move handles POST /armory/moves.

func (*StashHandler) MoveDialog

func (h *StashHandler) MoveDialog(c *echo.Context) error

MoveDialog handles GET /armory/move: the dialog for one item or money line.

func (*StashHandler) Page

func (h *StashHandler) Page(c *echo.Context) error

Page renders GET /campaigns/:id/armory/stashes.

func (*StashHandler) Pay

func (h *StashHandler) Pay(c *echo.Context) error

Pay handles POST /armory/pay: form character_id, amount (the sheet's main unit, up to two decimals) and an optional reason. It answers JSON so a widget can say who was paid what.

func (*StashHandler) SetDowntime

func (h *StashHandler) SetDowntime(c *echo.Context) error

SetDowntime handles POST /armory/downtime (Owner visibility). There is no page control for it yet; the service and this endpoint are the backend.

func (*StashHandler) SetPlace

func (h *StashHandler) SetPlace(c *echo.Context) error

SetPlace handles POST /armory/characters/:eid/items/:iid/place: the hero page's containers, when an item is dragged or sent to another one. The page has already drawn the item there, so the answer is empty.

func (*StashHandler) SetViewers

func (h *StashHandler) SetViewers(c *echo.Context) error

SetViewers handles PUT /armory/stashes/:sid/viewers. The body is the full set of characters that may see the stash, so an unchecked box is a removal.

func (*StashHandler) Share

func (h *StashHandler) Share(c *echo.Context) error

Share handles POST /armory/characters/:eid/items/:iid/share. The body is the full set of players ("user"), so an unticked box is a take-back.

func (*StashHandler) ShareBox

func (h *StashHandler) ShareBox(c *echo.Context) error

ShareBox handles GET /armory/characters/:eid/items/:iid/share: the box that lets the holder's player choose who else can see a hidden item.

func (*StashHandler) StashHistory

func (h *StashHandler) StashHistory(c *echo.Context) error

StashHistory handles GET /armory/stashes/:sid/history.

func (*StashHandler) UpdateStash

func (h *StashHandler) UpdateStash(c *echo.Context) error

UpdateStash handles PUT /armory/stashes/:sid.

type StashItemRow

type StashItemRow struct {
	ItemEntityID string
	Quantity     int
}

StashItemRow is one item line in a stash.

type StashItemView

type StashItemView struct {
	ItemID   string
	Name     string
	Quantity int
	// Copies are the ones that remember something, oldest first.
	Copies []Copy
}

StashItemView is one item line in a stash with its name resolved.

type StashRepository

type StashRepository interface {
	// CreateStash inserts a stash and sets its ID. A duplicate name in the
	// campaign is a Conflict.
	CreateStash(ctx context.Context, s *Stash) error
	// GetStash returns one stash in the campaign, or NotFound.
	GetStash(ctx context.Context, campaignID string, id int) (*Stash, error)
	// ListStashes returns every stash in the campaign by name.
	ListStashes(ctx context.Context, campaignID string) ([]Stash, error)
	// UpdateStash writes name and location. A duplicate name is a Conflict.
	UpdateStash(ctx context.Context, s *Stash) error
	// DeleteStash removes a stash; its items and viewers go with it.
	DeleteStash(ctx context.Context, campaignID string, id int) error

	// SetViewers replaces the characters that can see a stash, atomically.
	SetViewers(ctx context.Context, campaignID string, stashID int, characterIDs []string) error
	// ListViewers returns every stash's viewer character ids in the campaign.
	ListViewers(ctx context.Context, campaignID string) (map[int][]string, error)

	// ListItems returns every stash's item lines in the campaign.
	ListItems(ctx context.Context, campaignID string) (map[int][]StashItemRow, error)
	// CreditItem adds quantity of an item to a stash.
	CreditItem(ctx context.Context, campaignID string, stashID int, itemID string, quantity int) error
	// DebitItem removes quantity of an item, reporting false (and changing
	// nothing) when the stash holds less.
	DebitItem(ctx context.Context, campaignID string, stashID int, itemID string, quantity int) (bool, error)
	// CreditMoney adds money to a stash.
	CreditMoney(ctx context.Context, campaignID string, stashID int, amount Cents) error
	// DebitMoney removes money, reporting false when the stash holds less.
	DebitMoney(ctx context.Context, campaignID string, stashID int, amount Cents) (bool, error)

	// InsertMove writes a history row and sets its ID.
	InsertMove(ctx context.Context, m *Move) error
	// GetMove returns one move in the campaign, or NotFound.
	GetMove(ctx context.Context, campaignID string, id int64) (*Move, error)
	// SettleMove records the outcome of a PENDING move. It reports false when
	// the move was no longer pending, so two decisions can't both win.
	SettleMove(ctx context.Context, campaignID string, id int64, status, reason, decidedBy string) (bool, error)
	// ListMoves returns history rows newest first.
	ListMoves(ctx context.Context, campaignID string, f MoveFilter) ([]Move, error)
	// ListPending returns the campaign's pending requests, oldest first.
	ListPending(ctx context.Context, campaignID string) ([]Move, error)

	// GetDowntime returns the switch; a campaign with no row is closed.
	GetDowntime(ctx context.Context, campaignID string) (*Downtime, error)
	// SetDowntime writes the switch.
	SetDowntime(ctx context.Context, campaignID string, open bool, by string) error
}

StashRepository defines the data access contract for stashes and moves.

func NewStashRepository

func NewStashRepository(db *sql.DB) StashRepository

NewStashRepository creates a stash repository backed by db.

type StashService

type StashService interface {
	StashesPage(ctx context.Context, campaignID string, a Actor) (*StashesPageView, error)
	CreateStash(ctx context.Context, campaignID string, a Actor, in CreateStashInput) (*Stash, error)
	UpdateStash(ctx context.Context, campaignID string, a Actor, id int, in UpdateStashInput) error
	DeleteStash(ctx context.Context, campaignID string, a Actor, id int) error
	SetStashViewers(ctx context.Context, campaignID string, a Actor, id int, characterIDs []string) error
	AddStashItem(ctx context.Context, campaignID string, a Actor, id int, itemID string, quantity int) error

	MoveDialog(ctx context.Context, campaignID string, a Actor, kind string, from Endpoint, itemID string) (*MoveDialogView, error)
	Move(ctx context.Context, campaignID string, a Actor, in MoveInput) (*MoveOutcome, error)
	Approve(ctx context.Context, campaignID string, a Actor, moveID int64) (*Move, error)
	Decline(ctx context.Context, campaignID string, a Actor, moveID int64) (*Move, error)

	// GiveDialog feeds the Give box. Owner visibility only.
	GiveDialog(ctx context.Context, campaignID string, a Actor, characterID, itemID, query string) (*GiveDialogView, error)
	// Give hands a character an Armory item or a map. Owner visibility only.
	Give(ctx context.Context, campaignID string, a Actor, in GiveInput) (*GiveOutcome, error)
	// SetCarried sets how many of an Armory item a character carries, as a
	// give or a take with its history line. Owner visibility only.
	SetCarried(ctx context.Context, campaignID string, a Actor, characterID, itemID string, qty int) (*CarriedCount, error)
	// Pay adds coins to a character's sheet. Owner visibility only.
	Pay(ctx context.Context, campaignID string, a Actor, in PayInput) (*PayOutcome, error)

	// ShareBox feeds the "Who else can see <item>?" box for an item the
	// character holds. The holder's player or Owner visibility only.
	ShareBox(ctx context.Context, campaignID string, a Actor, characterID, itemID string) (*ShareBoxView, error)
	// Share lets exactly userIDs (other players of the campaign) see the
	// item, adding and taking back only grants sharing made.
	Share(ctx context.Context, campaignID string, a Actor, characterID, itemID string, userIDs []string) (*ShareOutcome, error)

	// Destinations lists the places the actor may send a move to from `from`.
	Destinations(ctx context.Context, campaignID string, a Actor, kind string, from Endpoint) ([]MoveDestination, error)
	// PendingRequests lists the requests waiting for an answer, with names
	// redacted for the actor. Only Owner visibility may ask.
	PendingRequests(ctx context.Context, campaignID string, a Actor) ([]MoveLine, error)

	IsDowntimeOpen(ctx context.Context, campaignID string) (bool, error)
	SetDowntime(ctx context.Context, campaignID string, a Actor, open bool) (DowntimeResult, error)

	// CharacterPanel returns nil when the viewer has no business with the
	// character's items and money (not a character, or not theirs).
	CharacterPanel(ctx context.Context, campaignID string, a Actor, characterID string) (*CharacterPanelView, error)
	CharacterHistory(ctx context.Context, campaignID string, a Actor, characterID string) ([]MoveLine, error)
	AddLogNote(ctx context.Context, campaignID string, a Actor, characterID string, in LogNoteInput) error
	DeleteLogNote(ctx context.Context, campaignID string, a Actor, characterID string, id int64) error
	// SetPlace puts an item the character holds in one of their containers.
	// The character's player or a GM only; it changes no count.
	SetPlace(ctx context.Context, campaignID string, a Actor, characterID, itemID string, p Place) error
	StashHistory(ctx context.Context, campaignID string, a Actor, stashID int) ([]MoveLine, error)

	// CraftPack reads what a character carries and how they pay, for a
	// crafting project. The character's player or a GM only.
	CraftPack(ctx context.Context, campaignID string, a Actor, characterID string) (*CraftPack, error)
	// CraftSpend takes a project's materials and cost, all or nothing.
	CraftSpend(ctx context.Context, campaignID string, a Actor, in CraftSpendInput) (*CraftSpendOutcome, error)
	// CraftGive puts a finished project's item in the character's pack.
	CraftGive(ctx context.Context, campaignID string, a Actor, characterID, itemID string, qty int, label string, m Memory) error
	// CraftGiveFor puts an item in a character's pack for a hero the actor
	// may act for, with the history line given.
	CraftGiveFor(ctx context.Context, campaignID string, a Actor, actingFor, characterID, itemID string, qty int, why string, m Memory) error
	// SpoilGive puts what a hero took or harvested from the spoils tray in
	// their pack.
	SpoilGive(ctx context.Context, campaignID string, a Actor, characterID, itemID string, qty int, harvested bool, m Memory) error
	// GoOff turns the remembered copies due by day into what they become.
	GoOff(ctx context.Context, campaignID string, a Actor, day int64) (int, error)
}

StashService defines the contract the handlers call.

type StashView

type StashView struct {
	Stash
	Viewers []NamedRef
	Items   []StashItemView
}

StashView is a stash as one viewer sees it.

func (StashView) Hidden

func (v StashView) Hidden() bool

Hidden reports whether only the GM can see the stash.

type StashesPageView

type StashesPageView struct {
	CampaignID   string
	DowntimeOpen bool
	CanManage    bool // Owner or Scribe.
	CanApprove   bool // Owner visibility.
	Pending      []MoveLine
	// PendingPurchases are shop baskets waiting for the Owner, listed beside
	// the move requests.
	PendingPurchases []PurchaseRequestLine
	Stashes          []StashView
	Characters       []NamedRef // Character-family entities, for the viewer picker.
	Items            []NamedRef // Catalogue items the GM can drop into a stash.
}

StashesPageView feeds the stashes page.

func (*StashesPageView) WaitingCount

func (v *StashesPageView) WaitingCount() int

WaitingCount is every request waiting on the Owner: moves and purchases.

type StockTx

type StockTx interface {
	Atomic(ctx context.Context, fn func(ctx context.Context) error) error
}

StockTx runs fn as one all-or-nothing unit: every page and listing fn writes through the context is kept together or not at all. Implemented in internal/app over the database handle.

type StreetFront

type StreetFront struct {
	StreetShop
	Front json.RawMessage `json:"front"`
	// Saved is false while the shop still shows the default storefront.
	Saved bool `json:"saved"`
}

StreetFront is a listed shop with the storefront it is drawn with.

type StreetShop

type StreetShop struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	URL      string `json:"url"`
	TownID   string `json:"townId,omitempty"`
	TownName string `json:"townName,omitempty"`
}

StreetShop is one shop page as the street lists it: its town is the page it sits under, if the viewer can see that page.

type StreetView

type StreetView struct {
	// Open is the campaign's downtime switch: closed shops draw their
	// closed look, and buying needs the GM's OK.
	Open      bool          `json:"open"`
	Shops     []StreetFront `json:"shops"`
	Truncated bool          `json:"truncated"`
}

StreetView is everything the Shops street draws.

type SystemGood

type SystemGood struct {
	Slug     string  `json:"slug"`
	Name     string  `json:"name"`
	Kind     string  `json:"kind,omitempty"`
	Rarity   int     `json:"rarity"`
	Price    float64 `json:"price"`
	HasPrice bool    `json:"hasPrice"`
	Summary  string  `json:"summary,omitempty"`
}

SystemGood is one stockable entry of the campaign's game system.

type SystemGoodsSource

type SystemGoodsSource interface {
	Goods(ctx context.Context, campaignID string) (goods []SystemGood, systemName, rarityLabel string, err error)
}

SystemGoodsSource reads the goods the campaign's system names in its manifest. Implemented in internal/app; (nil, "", "", nil) means none.

type TagInfo

type TagInfo struct {
	ID    int
	Name  string
	Slug  string
	Color string
}

TagInfo holds tag display data returned by TagLister.

type TagLister

type TagLister interface {
	ListTagsForEntities(ctx context.Context, entityIDs []string, includeDmOnly bool) (map[string][]TagInfo, error)
}

TagLister fetches tags for a set of entity IDs in batch. Implemented by tags.TagService — injected to decorate item cards with tags. includeDmOnly is true only at Owner visibility (the Owner or a DM-granted co-DM via VisibilityRole), the same rule the tags widget applies: Players and Scribes never see GM-only tags.

type TodayView

type TodayView struct {
	// Spots is how many places change each day.
	Spots int `json:"spots"`
	// HoursToDawn is nil when there is no calendar to count on.
	HoursToDawn *int `json:"hoursToDawn"`
	// Pool is every good that can turn up; Today is the ones out today. A
	// good in Pool but not in Today is not for sale today.
	Pool  []int `json:"pool"`
	Today []int `json:"today"`
}

TodayView is today's shelf of one shop, as the shop room and stock list draw it. Ids are "sells" relation ids.

type Transaction

type Transaction struct {
	ID              int       `json:"id"`
	CampaignID      string    `json:"campaign_id"`
	InstanceID      *int      `json:"instance_id,omitempty"`
	ShopEntityID    string    `json:"shop_entity_id"`
	ItemEntityID    string    `json:"item_entity_id"`
	BuyerEntityID   *string   `json:"buyer_entity_id,omitempty"`
	RelationID      *int      `json:"relation_id,omitempty"`
	Quantity        int       `json:"quantity"`
	PricePaid       *string   `json:"price_paid,omitempty"`
	Currency        string    `json:"currency"`
	PriceNumeric    *float64  `json:"price_numeric,omitempty"`
	TransactionType string    `json:"transaction_type"`
	Notes           *string   `json:"notes,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
	CreatedBy       *string   `json:"created_by,omitempty"`

	// Joined display fields (populated by list queries).
	ShopName  string `json:"shop_name,omitempty"`
	ItemName  string `json:"item_name,omitempty"`
	BuyerName string `json:"buyer_name,omitempty"`
}

Transaction represents a single shop transaction record.

type TransactionHandler

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

TransactionHandler serves transaction REST endpoints.

func NewTransactionHandler

func NewTransactionHandler(svc TransactionService) *TransactionHandler

NewTransactionHandler creates a new transaction handler. List endpoints go through a visibility-aware reader that fails closed until SetEntityVisibility wires the canonical filter.

func (*TransactionHandler) CreateTransaction

func (h *TransactionHandler) CreateTransaction(c *echo.Context) error

CreateTransaction handles POST /campaigns/:id/armory/transactions. Records a manual transaction (gift, transfer, restock).

func (*TransactionHandler) ListShopTransactions

func (h *TransactionHandler) ListShopTransactions(c *echo.Context) error

ListShopTransactions handles GET /campaigns/:id/armory/shops/:eid/transactions. Returns transactions for a specific shop entity.

func (*TransactionHandler) ListTransactions

func (h *TransactionHandler) ListTransactions(c *echo.Context) error

ListTransactions handles GET /campaigns/:id/armory/transactions. Returns paginated transactions with optional filters.

func (*TransactionHandler) SetEntityVisibility

func (h *TransactionHandler) SetEntityVisibility(v EntityVisibilityFilter)

SetEntityVisibility injects the entity visibility filter the list endpoints use to hide names of entities the viewer cannot see.

type TransactionListOptions

type TransactionListOptions struct {
	Page            int    // 1-indexed page number.
	PerPage         int    // Items per page (default 20).
	ShopEntityID    string // Filter by shop entity.
	BuyerEntityID   string // Filter by buyer entity.
	ItemEntityID    string // Filter by item entity.
	TransactionType string // Filter by type (purchase, sale, etc.).
}

TransactionListOptions controls filtering and pagination for transaction queries.

func DefaultTransactionListOptions

func DefaultTransactionListOptions() TransactionListOptions

DefaultTransactionListOptions returns sensible defaults.

func (TransactionListOptions) Offset

func (o TransactionListOptions) Offset() int

Offset returns the SQL offset for the current page.

type TransactionReader

type TransactionReader interface {
	// ListTransactions returns a campaign's transactions with names redacted.
	ListTransactions(ctx context.Context, campaignID string, role int, userID string, opts TransactionListOptions) ([]Transaction, int, error)

	// ListShopTransactions returns a shop's transactions with names redacted,
	// or a not-found error when the viewer cannot see the shop itself, so a
	// private shop's existence is not confirmed to them.
	ListShopTransactions(ctx context.Context, campaignID, shopEntityID string, role int, userID string, opts TransactionListOptions) ([]Transaction, int, error)
}

TransactionReader lists transactions for a specific viewer. role must be the visibility role (a co-DM already promoted), as the gallery uses.

func NewTransactionReader

func NewTransactionReader(svc TransactionService, vis EntityVisibilityFilter) TransactionReader

NewTransactionReader creates a reader. With a nil filter every non-Owner viewer is treated as unable to see any entity (fail closed).

type TransactionRepository

type TransactionRepository interface {
	// Create inserts a new transaction and sets the auto-generated ID.
	Create(ctx context.Context, tx *Transaction) error

	// ListByCampaign returns transactions with entity name joins,
	// filtered by the given options.
	ListByCampaign(ctx context.Context, campaignID string, opts TransactionListOptions) ([]Transaction, int, error)

	// ListByShop returns transactions for a specific shop entity, scoped to the
	// given campaign so a shop id from another campaign yields nothing (SEC-IDOR-3).
	ListByShop(ctx context.Context, campaignID, shopEntityID string, opts TransactionListOptions) ([]Transaction, int, error)

	// ListByBuyer returns transactions for a specific buyer entity.
	ListByBuyer(ctx context.Context, buyerEntityID string, opts TransactionListOptions) ([]Transaction, int, error)
}

TransactionRepository defines the data access contract for shop transactions.

func NewTransactionRepository

func NewTransactionRepository(db *sql.DB) TransactionRepository

NewTransactionRepository creates a new transaction repository.

type TransactionService

type TransactionService interface {
	// Purchase executes a purchase: validates stock, creates transaction,
	// decrements stock, and optionally deducts buyer currency. The role is
	// the caller's campaign role — passed through to the buyer access check.
	Purchase(ctx context.Context, campaignID, userID string, role int, input CreateTransactionInput) (*PurchaseResult, error)

	// CreateTransaction records a transaction without stock/currency logic.
	// Used for manual logging (gifts, transfers, restocks).
	CreateTransaction(ctx context.Context, campaignID, userID string, input CreateTransactionInput) (*Transaction, error)

	// ListTransactions returns paginated transactions for a campaign.
	ListTransactions(ctx context.Context, campaignID string, opts TransactionListOptions) ([]Transaction, int, error)

	// ListShopTransactions returns transactions for a specific shop, scoped to
	// the caller's campaign so a foreign shop id leaks nothing (SEC-IDOR-3).
	ListShopTransactions(ctx context.Context, campaignID, shopEntityID string, opts TransactionListOptions) ([]Transaction, int, error)

	// ListBuyerTransactions returns transactions for a specific buyer.
	ListBuyerTransactions(ctx context.Context, buyerEntityID string, opts TransactionListOptions) ([]Transaction, int, error)
}

TransactionService defines the business logic contract for shop transactions.

type UpdateInstanceInput

type UpdateInstanceInput struct {
	Name        patch.Field[string] `json:"name"`
	Description patch.Field[string] `json:"description"`
	Icon        patch.Field[string] `json:"icon"`
	Color       patch.Field[string] `json:"color"`
}

UpdateInstanceInput is a PARTIAL update: an absent field keeps the stored value, an explicit null clears a nullable one (description), a present value replaces it. Renaming a collection must never revert a description, icon or colour changed elsewhere in the meantime. A present blank icon or colour resets to the default, as it does on create.

type UpdateStashInput

type UpdateStashInput struct {
	Name     patch.Field[string]
	Location patch.Field[string]
}

UpdateStashInput is a PARTIAL update: an absent field keeps the stored value, an explicit null clears a nullable one, a present value replaces it. A rename must never wipe the location.

type UserNamer

type UserNamer interface {
	DisplayNames(ctx context.Context, campaignID string, userIDs []string) (map[string]string, error)
}

UserNamer resolves campaign members' display names.

Jump to

Keyboard shortcuts

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