# ⚖️ Auction House

Documentation related to the `jo_auction_house` script.

`jo_auction_house` gives players a market run from auction houses across the map. Players sell items at a fixed price or at auction, post buy orders for items they want and check the median price exchanged before trading. Purchased items, unsold lots and money earned wait in a private chest at the auction house.

RedM auction house script for VORP and RSG: fixed price sales, auctions, buy orders, item trades and market prices set by your players.

[Buy Auction House on the Jump On Studios store](https://jumpon-studios.com/redm/auction-house)

[Trailer](https://www.youtube.com/watch?v=V2oKx_0hLyU)

## 1. Installation

`jo_auction_house` works on all frameworks compatible with `jo_libs` ([the list](/jo_libs/modules/framework-bridge/#compatible-frameworks)). It requires `jo_libs` 2.18.0 or later and [oxmysql](https://overextended.dev/oxmysql).

To install `jo_auction_house`:

1. Download the latest [`jo_libs`](https://github.com/Jump-On-Studios/RedM-jo_libs/releases/latest/download/jo_libs.zip) release.
2. Unzip it and place the `jo_libs` folder in your resources folder.
3. Download `jo_auction_house` from your [account](https://jumpon-studios.com/account).
4. Unzip it and place the `jo_auction_house` folder in your resources folder.
5. Start the resources in this order in your `server.cfg`, after your framework and inventory:

```cfg
ensure oxmysql
ensure jo_libs
ensure jo_auction_house
```

:::tip 💡 No SQL file
The script creates its database tables on its first startup. Your database must use the InnoDB engine.
:::

:::warning Choose the market mode before the first start
`Config.marketMode` decides whether each auction house has its own market (`"local"`, default) or all of them share one (`"global"`). The mode is saved in the database on the first start and cannot be changed afterwards: the resource refuses to start if the configuration no longer matches.
:::

To let administrators use the removal commands, grant them the `jo_auction_house.admin` permission:

```cfg
add_ace group.admin jo_auction_house.admin allow
```

The **Auction House** script is now ready to use.

## 2. Usage

Each auction house has a clerk and a chest next to it, and usually a blip on the map. The script ships with auction houses in Valentine, Saint Denis and Blackwater. A location can also have no visible clerk (`npc.model = false`): its prompt still shows at the clerk position.

- In **local** mode, each auction house has its own lots, buy orders and prices. Items and money are collected at the auction house where the trade happened.
- In **global** mode, every auction house shows the same market. Items and money can be collected at any chest.

Approach the clerk and press `ENTER` to open the auction house. The interface is split into counters: **Market**, **Wanted**, **Sell**, **My sales** and **History**. Press `Q` and `E` to change counter and `ESC` to close.

### For players

:::: tabs
::: tab 🛒 Buy
1. Open the **Market** counter. Filter by category, search by name (`F`), choose between fixed prices and auctions, keep the auctions with a buy-now price, hide your own lots, and sort by newest, price or ending time.
2. Select a lot to open its sheet. It shows the price per unit, the seller's remaining quantity and a market verdict against the median price exchanged.
3. Choose the quantity, then select **Buy** and confirm.

The price is taken from your wallet at once. For a lot tagged **Trade**, the items asked are taken from your satchel instead. The items you bought wait in the chest of the auction house: open it to receive them.

A lot priced in money can be bought in parts when partial trades are enabled (`Config.allowPartialTrades`). Trade lots and auctions are bought whole. Your own fixed-price lots cannot be bought unless the server allows it (`Config.canBuyOwnListing`). You can never bid on your own auction.
:::

::: tab 💰 Sell
1. Open the **Sell** counter. It lists the items of your satchel that can be traded.
2. Select an item, then the quantity and the category.
3. Under **Fixed price**, enter a price per unit in dollars, gold or both. When barter is enabled (`Config.allowBarter`), switch the price to **Items** to ask for one catalogue item instead.
4. Select the sale button and check the receipt: gross price, commission and what you receive.
5. Confirm to publish the lot.

The items leave your satchel at once. A lot cannot be edited: cancel it from **My sales** and publish it again.

The commission is deducted from what the seller receives. Trade lots pay no commission. A lot that is not sold before it expires returns to your chest.
:::

::: tab 🔨 Auction
##### Start an auction

1. In the **Sell** counter, select an item and switch the form to **Auction**.
2. Choose the currency, the starting price, an optional buy-now price and the duration.
3. Confirm the receipt to publish the auction.

An auction can be cancelled only while nobody has bid on it.

##### Bid

1. In the **Market** counter, select a lot tagged **Auction**.
2. Select **Place a bid**. The amount is prefilled with the next minimum bid.
3. Confirm the receipt.

The bid is taken from your wallet when you place it. Raising your own bid only charges the difference. When another player outbids you, your bid is returned as money to collect at the chest, never directly to your wallet. Bidders stay anonymous, and late bids do not extend the auction.

##### Buy now and closing

**Buy now** closes the auction at once, as long as no bid has reached the buy-now price. When an auction ends, the highest bidder wins: the lot waits in their chest and the seller collects the money at theirs. An auction without bids returns to the seller's chest.
:::

::: tab 📜 Buy orders
##### Post a buy order

1. Open the **Wanted** counter and select **Post a buy order**.
2. Search for the item. You do not need to own it.
3. Choose the quantity and the price per unit in dollars, gold or both. When barter is enabled, switch to **Items** to offer a stack from your satchel for the whole order.
4. Choose the duration and confirm the receipt.

The total is taken from your wallet (or the items from your satchel) when the order is posted and held until it is supplied. Supplied items wait in your chest. Cancel an order from its sheet or from **My sales → My orders**: what remains held is returned at the chest. An expired order is refunded the same way.

##### Supply an order

1. Open the **Wanted** counter. **Only those I can supply** keeps the orders matching your satchel.
2. Select an order, choose the quantity and confirm.

The items are taken from one stack of your satchel. The money, after commission, waits at the chest. For an order paid in items, the offered items wait in your chest instead, with no commission. Buy orders priced in money can be supplied in parts when partial trades are enabled. You cannot supply your own order unless the server allows it (`Config.canFulfillOwnOrder`).
:::

::: tab 📦 Chest & money
The chest next to the clerk is private to each character.

- Press `ENTER` near the chest to open it. Purchased items, won auctions, supplied orders, cancelled or expired lots, items received from a trade and items offered in an order that closed unsupplied are added before it opens.
- Press `R` to **Collect your money**. The prompt appears only when money is owed and shows the amount.

Money from sales, supplied orders and refunds (outbid, cancelled or expired orders, removed lots) is never paid automatically: it is collected at the chest. In local mode, collect it at the auction house where the trade happened.

When the chest is full, the remaining items stay waiting until there is room. Online players are notified of their sales; reminders of what waits at which auction house are sent at character selection.
:::

::: tab 📈 Market prices
Lot sheets, order sheets and both forms show a market line: the median price per unit exchanged over the default period, its trend when the previous period has enough exchanges, and a verdict on the price. The forms also suggest prices you can apply with one click.

Open the **Item sheet** with its button or with `I` to see:

- the lots for sale and the orders wanted for that item, with the best offer of each;
- the median exchanged price per currency, its trend and the volume over 7, 30 or 90 days;
- a chart of the price and the units exchanged, or the figures as a table.

From two letters typed in the **Market** or **Wanted** search, an **Item sheets** row opens the sheet of any tradable item, even one nobody sells.

Prices come from concluded exchanges only and are computed separately for dollars and gold. A price appears once an item has 5 exchanges in that currency (`Config.statsMinTrades`). In local mode, prices come from the exchanges of that auction house only. Trades for items and mixed dollar-and-gold exchanges count in the volume, not in the price.
:::

::: tab 🗂️ My sales & history
**My sales** has three views:

- **My lots**: your open lots, with cancellation, then your closed lots (sold, cancelled or expired).
- **My bids**: the auctions you bid on, leading or outbid.
- **My orders**: your buy orders, with cancellation, then the closed ones.

**History** lists your completed trades: purchases, sales, auctions and supplied orders. Switch to **All trades** to see every exchange of this market, without names.
:::
::::

#### Default controls

| Key | Context | Action |
| --- | --- | --- |
| `ENTER` | Clerk | Open the auction house |
| `ENTER` | Chest | Open the chest |
| `R` | Chest | Collect the money owed |
| `Q` / `E` | Interface | Change counter |
| `F` | Interface | Search |
| `I` | Interface | Open the item sheet of the selected lot, order or item |
| `ENTER` | Interface | Run the main action of the selected line |
| `ESC` | Interface | Close the receipt, the item sheet, then the interface |

The prompt keys are set in `keys.lua`.

### For administrators

| Command | Who | Effect |
| --- | --- | --- |
| `/auctionHouse [id]` | Players allowed by the server | Opens an auction house without walking to it. In local mode, pass the auction house `id`; in global mode, it opens the first configured auction house. Nobody can use it remotely until the [`canUseAuctionHouseRemotely`](#canuseauctionhouseremotely) filter allows them. The name is set by `Config.auctionHouseCommand`; `false` removes the command. |
| `/auctionremove <listing id>` | Console or `jo_auction_house.admin` | Returns an active lot to its seller's chest. The leader of an auction gets their bid back at the chest. |
| `/orderremove <order id>` | Console or `jo_auction_house.admin` | Closes an active buy order and returns what it held to the buyer's chest. |

The chest is never remote: items and money are always collected at an auction house.

## 3. Configuration

The configuration files are located in the `config` folder within the resource. This folder contains two subfolders:

- **`_default.lock/`** - Contains the default configuration files. **Do not edit these files directly** as they may be overwritten during updates.
- **`custom/`** - This is where you place your custom configuration files to override the defaults.

### How to customize the configuration

1. Navigate to `jo_auction_house/config/_default.lock/`
2. Copy the file you want to modify (e.g., `prices.lua`)
3. Paste it into `jo_auction_house/config/custom/`
4. Edit the copied file in the `custom` folder

The script automatically loads files from `custom/` first, and only uses `_default.lock/` as a fallback. This system ensures your customizations are preserved when updating the script.

### Default configuration files

`jo_auction_house/config/_default.lock/global.lua`

```lua
-- * ======================================
-- *  MARKET MODE
-- * ======================================

-- Choose once before the first start. The database remembers this mode; changing it later is not
-- supported and prevents startup because local and global chests hold different inventories.
--   "local"  each auction house has its own market, and items and money are collected where they were traded
--   "global" every auction house shares one market, and items and money can be collected at any chest
Config.marketMode = "local"

-- * ======================================
-- *  CHEST
-- * ======================================

-- Capacity of the auction house chest. VORP counts every unit, not slots: keep it well above
-- listingMaxQuantity (market.lua), or a large lot cannot be delivered until the player empties the chest.
Config.chestMaxSlots = 500

-- * ======================================
-- *  INTERFACE
-- * ======================================

Config.marketPageSize = 30 -- Maximum lots, orders or history entries per page
Config.soundVolume = 0.5   -- Interface sounds, the ones of jo.menu, from 0.0 to 1.0; 0 mutes them

-- * ======================================
-- *  COMMANDS
-- * ======================================

-- Opens an auction house from anywhere: /auctionHouse in global mode, /auctionHouse <id> in local mode.
-- Nobody can use it until a server filter `canUseAuctionHouseRemotely` allows them. false removes it.
-- Administrators also have /auctionremove <listing id> and /orderremove <order id> (ACE jo_auction_house.admin).
Config.auctionHouseCommand = "auctionHouse"

-- * ======================================
-- *  DEBUG
-- * ======================================

Config.debugMode = false   -- Master switch: no debug log is printed when false
Config.debugCategories = { -- Categories to print when debug mode is on; `all` prints every category
    all = false,
    location = false,      -- NPC, chest, prompts and blips
    nui = false,           -- Auction house interface
    listing = false,       -- Publish, buy and cancel
    chest = false,         -- Items waiting in the chest and the stash
    payment = false,       -- Money owed to the sellers
    auction = false,       -- Bids, buy-now and auction settlement
    order = false,         -- Buy orders: creation, supply, cancellation and expiry
    stats = false,         -- Market statistics
    database = false,
}
```

`jo_auction_house/config/_default.lock/items.lua`

```lua
-- * ======================================
-- *  TRADABLE ITEMS
-- * ======================================

-- Items players can sell or order. Inventory entries of type weapon are not offered; jo_gunsmith weapons
-- represented as ordinary items are allowed subject to this filter.
--   mode = "all"       every item
--   mode = "whitelist" only the items listed below
--   mode = "blacklist" every item except the ones listed below
Config.itemFilter = {
    mode = "blacklist",
    items = {
        -- money_bag = true,
    },
}

-- * ======================================
-- *  CATEGORIES
-- * ======================================

-- Categories offered when publishing, in display order. Their names are in lang.lua (`category_<id>`).
-- `icon` (optional) is shown on the category filters: a jo.menu icon name from
-- jo_libs/nui/menu/assets/images/icons, or a full nui:// URL.
Config.categories = {
    { id = "food",      icon = "satchels" },        -- meals, drinks, raw food (a provision bag)
    { id = "herbs",     icon = "horse_tails" },     -- plants, flowers, berries, remedies (a sheaf)
    { id = "hunting",   icon = "toast_mp_animal" }, -- pelts, hides, meat, feathers, horns
    { id = "resources", icon = "wagon" },           -- wood, ore, coal, nuggets, crafting goods
    { id = "tools",     icon = "horse_outfits" },   -- axes, pickaxes, kits, horse care (a shovel)
    { id = "other",     icon = "propsets" },
}

Config.defaultCategory = "other" -- Category of an item missing from Config.itemCategories

-- Category preselected when publishing an item; the player can change it.
-- Item names depend on the framework and the server: these are VORP examples, adapt them.
Config.itemCategories = {
    consumable_coffee = "food",
    consumable_peach = "food",
    venison = "food",
    Oregano = "herbs",
    Alaskan_Ginseng = "herbs",
    Wintergreen_Berry = "herbs",
    provision_ro_flower_lady_slipper = "herbs",
    herbal_tonic = "herbs",
    bisonhorn = "hunting",
    SnakeSkin = "hunting",
    Feather = "hunting",
    gold_nugget = "resources",
    wood = "resources",
    coal = "resources",
    iron = "resources",
    lumberaxe = "tools",
    pickaxe = "tools",
    hatchet = "tools",
    horsebrush = "tools",
}
```

`jo_auction_house/config/_default.lock/keys.lua`

```lua
-- * ======================================
-- *  PROMPT KEYS
-- * ======================================

Config.keys = {
    openAuctionHouse = "ENTER", -- NPC prompt: opens the auction house
    openChest = "ENTER",        -- Chest prompt: opens the chest
    collectMoney = "R",         -- Chest prompt: collects the money owed, shown only when some is owed
}
```

`jo_auction_house/config/_default.lock/lang.lua`

```lua
-- * ======================================
-- *  PROMPTS
-- * ======================================

Lang.npcPromptGroupLabel = "Auction House"
Lang.npcPromptInteract = "Browse the market"
Lang.chestPromptGroupLabel = "Auction House chest"
Lang.chestPromptInteract = "Open the chest"
Lang.chestPromptCollectMoney = "Collect your money"
Lang.chestLabel = "Auction House chest"

-- * ======================================
-- *  CURRENCIES
-- * ======================================

Lang.priceMoney = "$%s"
Lang.priceGold = "%s gold"
Lang.priceFree = "Free"
Lang.priceItem = "%d %s"                -- Items asked in a barter: quantity, item name
Lang.priceSeparator = " + "

-- * ======================================
-- *  CATEGORIES
-- * ======================================

Lang.category_food = "Food"
Lang.category_herbs = "Herbs"
Lang.category_hunting = "Hunting"
Lang.category_resources = "Resources"
Lang.category_tools = "Tools"
Lang.category_other = "Other"

-- * ======================================
-- *  NOTIFICATIONS
-- * ======================================

Lang.listingSoldCollect = "Your lot of %d %s was sold for %s: collect it at an auction house chest"
Lang.listingSoldCollectLocal = "Your lot of %d %s was sold for %s: collect it at %s"
Lang.moneyCollected = "You collected %s"
Lang.moneyWaiting = "%s is waiting for you at an auction house chest"
Lang.moneyWaitingLocal = "%s is waiting for you at %s"
Lang.listingSoldFree = "Your free lot of %d %s was taken"
Lang.listingSoldNoProceeds = "Your lot of %d %s was sold; no money is owed after commission"
Lang.chestItemsWaiting = "Your items are waiting in the chest next to the auction house"
Lang.chestItemsWaitingLocal = "Your items are waiting at %s"
Lang.auctionOutbid = "You were outbid on %d %s: your %s is waiting at an auction house chest"
Lang.auctionOutbidLocal = "You were outbid on %d %s: your %s is waiting at %s"
Lang.auctionWon = "You won the auction of %d %s for %s: it is waiting in an auction house chest"
Lang.auctionWonLocal = "You won the auction of %d %s for %s: it is waiting at %s"
Lang.auctionNoBid = "No one bid on your %d %s: the lot is waiting in an auction house chest"
Lang.auctionNoBidLocal = "No one bid on your %d %s: the lot is waiting at %s"
Lang.orderSupplied = "Your order of %d %s was supplied: it is waiting in an auction house chest"
Lang.orderSuppliedLocal = "Your order of %d %s was supplied: it is waiting at %s"
Lang.orderRefunded = "Your order of %d %s closed without being supplied: your %s is waiting at an auction house chest"
Lang.orderRefundedLocal = "Your order of %d %s closed without being supplied: your %s is waiting at %s"

-- * ======================================
-- *  ERRORS
-- * ======================================

Lang.errorNotReady = "The auction house is not ready yet, try again in a moment"
Lang.errorTooFar = "You are too far from the auction house"
Lang.errorInvalidData = "Invalid request"
Lang.errorInvalidQuantity = "Invalid quantity"
Lang.errorItemNotAllowed = "This item cannot be sold here"
Lang.errorItemNotFound = "This item is no longer in your inventory"
Lang.errorNotEnoughItems = "You do not have enough of this item"
Lang.errorInvalidPrice = "Invalid price"
Lang.errorCurrencyNotAllowed = "This currency is not accepted"
Lang.errorPriceTooHigh = "This price is too high"
Lang.errorGoldWhole = "Gold amounts must be whole numbers"
Lang.errorFreeNotAllowed = "A lot needs a price"
Lang.errorTooManyListings = "You already have too many lots for sale"
Lang.errorListingUnavailable = "This lot is no longer available"
Lang.errorOwnListing = "You cannot buy your own lot"
Lang.errorNotOwner = "This lot is not yours"
Lang.errorNotEnoughMoney = "You cannot afford this lot"
Lang.errorRefused = "You cannot do this here"
Lang.errorServer = "Something went wrong, nothing was changed"
Lang.errorChestFull = "Your chest is full: some items are still waiting"
Lang.errorNothingToCollect = "No money is waiting for you"
Lang.errorCommissionChanged = "The commission has changed. Please confirm again"
Lang.errorInvalidCommission = "The commission is invalid"
Lang.errorBidTooLow = "Your bid is below the minimum"
Lang.errorBidReachesBuyNow = "This bid reaches the buy-now price: buy it now instead"
Lang.errorOwnAuction = "You cannot bid on your own auction"
Lang.errorAuctionHasBids = "This auction has bids and can no longer be cancelled"
Lang.errorBuyNowTooLow = "The buy-now price must be higher than the starting price"
Lang.errorItemNotOrderable = "This item cannot be ordered here"
Lang.errorBarterNotAllowed = "Item trades are not accepted here"
Lang.errorBarterItemNotAllowed = "This item cannot be asked in exchange"
Lang.errorTooManyOrders = "You already have too many buy orders"
Lang.errorOrdersDisabled = "Buy orders are disabled"
Lang.errorOrderUnavailable = "This order is no longer available"
Lang.errorOwnOrder = "You cannot supply your own order"
Lang.errorNotOrderOwner = "This order is not yours"
Lang.errorUnknownAuctionHouse = "Unknown auction house: %s"
Lang.commandAuctionHouseUsage = "Usage: /%s <auction house id>"

-- * ======================================
-- *  INTERFACE
-- * ======================================

-- ° Navigation
Lang.nuiTabMarket = "Market"
Lang.nuiTabSell = "Sell"
Lang.nuiTabMySales = "My sales"
Lang.nuiTabHistory = "History"
Lang.nuiCounterMarket = "Browse the market"
Lang.nuiCounterSell = "List an item"
Lang.nuiCounterMySales = "Manage your lots"
Lang.nuiCounterHistory = "Completed trades"
Lang.nuiCounterKeys = "Change counter"
Lang.nuiCounterMotto = "Goods change hands,\nthe word remains."
Lang.nuiSignSubtitle = "Public sales"
Lang.nuiSignSubtitleLots = "Fixed price and auctions"
Lang.nuiMarketLocal = "Local market"
Lang.nuiMarketGlobal = "Global market"
Lang.nuiPurse = "Your purse"
Lang.nuiReceipt = "Deposit receipt"
Lang.nuiReceiptStampBuy = "Paid"
Lang.nuiReceiptStampPublish = "Recorded"
Lang.nuiReceiptStampCancel = "Cancelled"
Lang.nuiReceiptStampError = "Refused"
Lang.nuiClose = "Close"
Lang.nuiKeySearch = "Search"
Lang.nuiKeyCounter = "Counter"
Lang.nuiKeyEscape = "Esc"
Lang.nuiKeyEnter = "Enter"
Lang.nuiKeyBuy = "Buy"
Lang.nuiKeyBid = "Bid"
Lang.nuiKeySupply = "Supply"
Lang.nuiKeyPublish = "Publish"
Lang.nuiKeyPost = "Post"
Lang.nuiConfirmPay = "Pay %s"
Lang.nuiFilterBuyNow = "Buy now"
Lang.nuiFilterHideMine = "Hide my lots"
Lang.nuiTabCount = "%s (%d)"
Lang.nuiStatusSold = "Sold"
Lang.nuiStatusCancelled = "Cancelled"
Lang.nuiStatusExpired = "Expired"
Lang.nuiDetailClosedAt = "Closed"
Lang.nuiClosedSold = "Sold: the money was sent to the chest."
Lang.nuiClosedReturned = "Closed: the remaining items were sent back to the chest."
Lang.nuiChestHint = "Purchases and cancelled lots go to the chest next to the auction house"
Lang.nuiReceiptMoney = "at the chest"
Lang.nuiReceiptNoMoney = "No sale money waiting"
Lang.nuiReceiptLocal = "Collect at this counter's chest"
Lang.nuiReceiptGlobal = "Collect at any counter's chest"

-- ° Market
Lang.nuiSearchPlaceholder = "Search an item"
Lang.nuiAllCategories = "All categories"
Lang.nuiSortLabel = "Sort by"
Lang.nuiSortNewest = "Newest"
Lang.nuiSortPriceAsc = "Lowest price"
Lang.nuiSortPriceDesc = "Highest price"
Lang.nuiSortEndingSoon = "Ending soon"
Lang.nuiTypeLabel = "Type of offer"
Lang.nuiTypeAll = "All offers"
Lang.nuiTypeDirect = "Fixed price"
Lang.nuiTypeAuction = "Auctions"
Lang.nuiAuctionTag = "Auction"
Lang.nuiBidCount = "%d bids"
Lang.nuiBidCountOne = "1 bid"
Lang.nuiEndsIn = "ends in %s"
Lang.nuiTimeDays = "%dd %dh"
Lang.nuiTimeHours = "%dh %dm"
Lang.nuiTimeMinutes = "%dm"
Lang.nuiTimeEnded = "ended"
-- Past moments, in words: no calendar date or clock time (they break role-play)
Lang.nuiAgoJustNow = "just now"
Lang.nuiAgoMinutes = "%d min ago"
Lang.nuiAgoHours = "%d h ago"
Lang.nuiAgoToday = "Today"
Lang.nuiAgoYesterday = "yesterday"
Lang.nuiAgoDays = "%d days ago"
Lang.nuiAgoLastWeek = "last week"
Lang.nuiAgoWeeks = "%d weeks ago"
Lang.nuiAgoMonths = "%d months ago"
Lang.nuiYouLead = "You lead"
Lang.nuiYouAreOutbid = "Outbid"
Lang.nuiColumnItem = "Item"
Lang.nuiColumnQuantity = "Quantity"
Lang.nuiColumnUnitPrice = "Unit price"
Lang.nuiColumnPrice = "Price"
Lang.nuiMarketEmpty = "Nothing is for sale here yet"
Lang.nuiNoResult = "No lot matches your search"
Lang.nuiYourListing = "Your lot"
Lang.nuiRefresh = "Refresh"
Lang.nuiPagination = "Pages"
Lang.nuiPreviousPage = "Previous"
Lang.nuiNextPage = "Next"
Lang.nuiPage = "Page %d"
Lang.nuiResultCount = "%d lots"
Lang.nuiResultCountOne = "1 lot"

-- ° Listing detail
Lang.nuiDetailTitle = "Lot"
Lang.nuiDetailQuantity = "Quantity"
Lang.nuiDetailUnitPrice = "Unit price"
Lang.nuiDetailTotalPrice = "Total price"
Lang.nuiDetailCategory = "Category"
Lang.nuiDetailListedAt = "Listed"
Lang.nuiDetailNone = "Select a lot"
Lang.nuiDetailMine = "This is your lot: you can cancel the remaining items."
Lang.nuiBuy = "Buy the lot"
Lang.nuiBack = "Back"
Lang.nuiConfirmBuyTitle = "Buy this lot?"
Lang.nuiConfirmBuyText = "%d %s for %s. The lot will wait for you in the chest."
Lang.nuiConfirm = "Confirm"
Lang.nuiCancel = "Cancel"
Lang.nuiDetailStartPrice = "Starting price"
Lang.nuiDetailCurrentBid = "Current bid"
Lang.nuiDetailBids = "Bids"
Lang.nuiDetailMinimumBid = "Next bid from"
Lang.nuiDetailBuyNow = "Buy now"
Lang.nuiDetailEndsIn = "Ends in"
Lang.nuiYouLeadHelp = "You lead this auction: your bid is held until it ends."
Lang.nuiPlaceBid = "Place a bid"
Lang.nuiRaiseBid = "Raise my bid"
Lang.nuiAuctionMineHasBids = "Your auction has bids: it can no longer be cancelled."
Lang.nuiConfirmBidTitle = "Place this bid?"
Lang.nuiConfirmBuyNowTitle = "Buy it now?"
Lang.nuiBidAmount = "Your bid for the lot"
Lang.nuiBidAlreadyHeld = "Already held for you"
Lang.nuiBidYouPay = "Debited now"
Lang.nuiBidHeldHelp = "The amount is held until the end. If someone outbids you, it waits for you at the chest."
Lang.nuiBuyNowHelp = "The auction closes at once and the lot will wait for you in the chest."

-- ° Sell
Lang.nuiSellTitle = "Sell an item"
Lang.nuiSellEmpty = "You have nothing to sell"
Lang.nuiSellQuantity = "Quantity"
Lang.nuiSellCategory = "Category"
Lang.nuiSellOwned = "Owned: %d"
Lang.nuiSellSelectItem = "Choose an item from your inventory"
Lang.nuiSellSatchel = "Your satchel"
Lang.nuiSellSlots = "%d items"
Lang.nuiSellFormTitle = "New fixed-price sale"
Lang.nuiSellDecrease = "Decrease"
Lang.nuiSellIncrease = "Increase"
Lang.nuiSellPriceHelp = "The commission and the amount you receive are shown before you confirm."
Lang.nuiSellPriceKind = "Total price"
Lang.nuiPricePerUnit = "Price per unit"
Lang.nuiTotal = "Total"
Lang.nuiSellPriceMoney = "Money & Gold"
Lang.nuiSellPriceBarter = "Items"
Lang.nuiSellBarterAsked = "Asked in exchange"
Lang.nuiSellBarterSearch = "Search an item to ask for"
Lang.nuiSellBarterHelp = "No commission on an item trade: once the lot is sold, the items you asked for wait for you in the chest."
Lang.nuiPublishBarterPrice = "Asked in exchange"
Lang.nuiBarterTag = "Trade"
Lang.nuiConfirmPublishTitle = "Publish this lot?"
Lang.nuiConfirmPublishText = "%d %s"
Lang.nuiPublishCommission = "Commission"
Lang.nuiPublishNet = "You receive"
Lang.nuiSellMode = "Type of sale"
Lang.nuiSellModeDirect = "Fixed price"
Lang.nuiSellModeAuction = "Auction"
Lang.nuiSellFormAuctionTitle = "New auction"
Lang.nuiSellCurrency = "Currency"
Lang.nuiCurrencyMoney = "Dollars"
Lang.nuiCurrencyGold = "Gold"
Lang.nuiSellStartPrice = "Starting price"
Lang.nuiSellBuyNow = "Buy-now price"
Lang.nuiSellOptional = "Optional"
Lang.nuiSellDuration = "Duration"
Lang.nuiDurationHours = "%d h"
Lang.nuiDurationDays = "%d days"
Lang.nuiSellStartInvalid = "Enter a starting price"
Lang.nuiSellBuyNowInvalid = "The buy-now price must be higher than the starting price"
Lang.nuiSellDurationInvalid = "Choose a duration"
Lang.nuiSellAuctionHelp = "The lot leaves your satchel now. Bids are final, and you can cancel only while there is no bid."
Lang.nuiSellPublishAuction = "Publish the auction"
Lang.nuiConfirmAuctionTitle = "Publish this auction?"

-- ° My sales
Lang.nuiMySalesEmpty = "You have no lot for sale here"
Lang.nuiMySalesLots = "My lots"
Lang.nuiMySalesBids = "My bids"
Lang.nuiSoldQuantity = "%d of %d sold"
Lang.nuiSuppliedQuantity = "%d of %d supplied"
Lang.nuiMyBidsEmpty = "You have no bid on an active auction here"
Lang.nuiCancelListing = "Cancel the lot"
Lang.nuiConfirmCancelTitle = "Cancel this lot?"
Lang.nuiConfirmCancelText = "%d %s will wait for you in the chest."
Lang.nuiHistoryEmpty = "No completed exchanges yet"
Lang.nuiHistorySold = "Sold"
Lang.nuiHistoryBought = "Bought"
Lang.nuiHistoryTraded = "Exchanged"
Lang.nuiHistoryScope = "Whose exchanges"
Lang.nuiHistoryMine = "My trades"
Lang.nuiHistoryAll = "All trades"
Lang.nuiHistoryChest = "At the chest"
Lang.nuiHistoryChestMoney = "Sale money waiting"

-- ° Results
Lang.nuiPending = "The auction house is checking..."
Lang.nuiPurchaseSuccess = "Lot bought: it is waiting for you in the chest"
Lang.nuiPublishSuccess = "Your lot is for sale"
Lang.nuiCancelSuccess = "Lot cancelled: it is waiting for you in the chest"
Lang.nuiBidSuccess = "Your bid is recorded: you lead"
Lang.nuiOrderCreated = "Your order is posted: the funds are held"
Lang.nuiOrderSuppliedSuccess = "Order supplied: your money is waiting at the chest"
Lang.nuiOrderCancelled = "Order cancelled: your money is waiting at the chest"

-- ° Buy orders
Lang.nuiTabWanted = "Wanted"
Lang.nuiCounterWanted = "Buy orders"
Lang.nuiOrderTag = "Buy order"
Lang.nuiOrdersEmpty = "No one is looking for anything here yet"
Lang.nuiOrdersNoResult = "No order matches your search"
Lang.nuiOrdersSupplyOnly = "Only those I can supply"
Lang.nuiOrderPost = "Post a buy order"
Lang.nuiOrderYouHave = "You have %d"
Lang.nuiOrderYours = "Your order"
Lang.nuiOrderCount = "%d orders"
Lang.nuiOrderCountOne = "1 order"
Lang.nuiOrderFundsHeld = "Funds held"
Lang.nuiOrderNotEnough = "You need %d in one stack of your satchel to supply it."
Lang.nuiStatusFulfilled = "Supplied"
Lang.nuiOrderClosedSupplied = "Supplied: the items were sent to the chest."
Lang.nuiOrderClosedRefunded = "Closed: the remaining offer was returned to the chest."
Lang.nuiOrderCancel = "Cancel the order"
Lang.nuiConfirmSupplyTitle = "Supply this order?"
Lang.nuiConfirmSupplyText = "Taken from your satchel now: %d %s. The money will wait for you at the chest."
Lang.nuiConfirmCancelOrderTitle = "Cancel this order?"
Lang.nuiConfirmCancelOrderText = "Your %s will wait for you at the chest."
Lang.nuiOrderFormTitle = "New buy order"
Lang.nuiOrderSearch = "Search an item to order"
Lang.nuiOrderSearchHint = "Type at least two letters"
Lang.nuiOrderSearchEmpty = "No item matches"
Lang.nuiOrderTotal = "Debited now"
Lang.nuiOrderPriceInvalid = "Enter a price per unit"
Lang.nuiOrderHelp = "The total is debited now and held. If no one supplies the order, it waits for you at the chest."
Lang.nuiOrderOffer = "Offered in exchange"
Lang.nuiOrderOfferPick = "Pick the items to offer from your satchel"
Lang.nuiOrderOfferInvalid = "Choose an item to offer"
Lang.nuiOrderOfferTotal = "Taken from your satchel now"
Lang.nuiOrderBarterHelp = "No commission on an item trade: the items are taken from your satchel now and go to the supplier. If no one supplies the order, they wait for you at the chest."
Lang.nuiConfirmSupplyBarterText = "Taken from your satchel now: %d %s. The items offered will wait for you at the chest."
Lang.nuiOrderPublish = "Post the order"
Lang.nuiConfirmOrderTitle = "Post this order?"
Lang.nuiMySalesOrders = "My orders"
Lang.nuiMyOrdersEmpty = "You have no active buy order here"

-- ° Market statistics
Lang.nuiStatsTitle = "Market price"
Lang.nuiStatsNotEnough = "Not enough exchanges"
Lang.nuiStatsBestSale = "Best sale"
Lang.nuiStatsBestOrder = "Best order"
Lang.nuiTrendUp = "Rising"
Lang.nuiTrendDown = "Falling"
Lang.nuiTrendFlat = "Stable"
Lang.nuiStatsSheet = "Item sheet"
Lang.nuiStatsSell = "Sell yours"
Lang.nuiStatsBook = "Current offers"
Lang.nuiStatsForSale = "For sale"
Lang.nuiStatsNothingForSale = "Nothing for sale: post a buy order and sellers will see it"
Lang.nuiStatsWanted = "Wanted"
Lang.nuiStatsNoOrder = "No one is looking for this item"
Lang.nuiStatsPrices = "Item prices"
Lang.nuiStatsPeriod = "Period"
Lang.nuiStatsDays = "%d d"
Lang.nuiStatsMedian = "Median exchanged"
Lang.nuiStatsVolume = "Quantity exchanged"
Lang.nuiStatsExchanges = "%d exchanges"
Lang.nuiStatsExchangesColumn = "Exchanges"
Lang.nuiStatsDay = "Day"
Lang.nuiStatsToday = "Today"
Lang.nuiStatsDaysAgo = "%d d ago"
Lang.nuiStatsShowTable = "Show the figures"
Lang.nuiStatsShowChart = "Show the chart"
Lang.nuiStatsChartLabel = "Price chart, %d points: left and right arrows read each one"
Lang.nuiStatsNoExchange = "no exchange"
Lang.nuiStatsNotEnoughText = "%d exchanges in %d days: %d in one currency are needed to set a price."
Lang.nuiStatsLastExchange = "Last exchange: %d for %s, %s"
Lang.nuiStatsNoExchangeYet = "No exchange concluded for this item yet."
Lang.nuiStatsSuggestions = "Item sheets:"
Lang.nuiStatsPerUnit = "per unit"
Lang.nuiStatsTrendNote = "Trend: this median against the previous %d days"
Lang.nuiStatsChartTitle = "Price per unit, every %d days"
Lang.nuiStatsChartTitleDaily = "Price per unit, day by day"
Lang.nuiStatsChartCurrency = "Currency shown on the chart"
Lang.nuiStatsLegendPrice = "Median price per unit"
Lang.nuiStatsLegendUnits = "Units exchanged (highest bar: %d)"
Lang.nuiStatsUnits = "%d units"
Lang.nuiStatsUnitsOne = "1 unit"
Lang.nuiStatsExchanged = "Exchanged, median per unit"
Lang.nuiStatsAuctionsOnly = "Auctions only"
Lang.nuiStatsBarterOnly = "Item trades only"
Lang.nuiStatsExchangesOne = "1 exchange"
Lang.nuiStatsLots = "%d lots"
Lang.nuiStatsLotsOne = "1 lot"

-- * ======================================
-- *  RIGHT-HAND PANELS
-- * ======================================

Lang.nuiKickerLot = "Lot for sale"
Lang.nuiKickerAuction = "Auction"
Lang.nuiKickerOrder = "Buy order"
Lang.nuiChooseItem = "Choose an item"
Lang.nuiChange = "Change"
Lang.nuiWanted = "Wanted"
Lang.nuiWantedCount = "%d wanted"
Lang.nuiWantedQuantity = "Quantity wanted"
Lang.nuiWholeLot = "whole lot"
Lang.nuiWholeOrder = "whole order"
Lang.nuiUnit = "per unit"
Lang.nuiAll = "All"
Lang.nuiFrom = "from"
Lang.nuiBuyCount = "Buy %d"
Lang.nuiSupplyCount = "Supply %d"
Lang.nuiSellCount = "Sell %d"
Lang.nuiPlaceOrderCount = "Order %d"
Lang.nuiAfterCommission = "after %d%% commission"
Lang.nuiCommissionNote = "Commission shown before you confirm"
Lang.nuiAuctionNote = "Bids are final"
Lang.nuiOrderHeldNote = "Debited now, held until supplied"
Lang.nuiOrderBarterNote = "Taken from your satchel now"
Lang.nuiBarterAskHint = "No commission on an item trade."
Lang.nuiYouGive = "You give"
Lang.nuiYouPay = "You pay"
Lang.nuiYouSupply = "You supply"
Lang.nuiSetPriceHint = "Set a price per unit, or use a market price above"
Lang.nuiYouReceive = "You receive"
Lang.nuiYouAsk = "You ask"
Lang.nuiYouOffer = "You offer"
Lang.nuiMedian = "Median"
Lang.nuiSuggest = "Use:"
Lang.nuiSuggestMedian = "Median"
Lang.nuiSuggestUndercut = "Under best lot"
Lang.nuiSuggestOutbid = "Above best order"
Lang.nuiVerdictFair = "In line with the market price"
Lang.nuiVerdictEnterPrice = "Enter a price to compare it with the market"
Lang.nuiVerdictBuyNow = "Set a buy-now price to compare"
Lang.nuiVerdict_listing_low = "%d%% below the market: a good deal"
Lang.nuiVerdict_listing_high = "%d%% above the market price"
Lang.nuiVerdict_order_high = "Pays %d%% above the market"
Lang.nuiVerdict_order_low = "Pays %d%% below the market"
Lang.nuiVerdict_sellForm_high = "%d%% above the market: it may sell slowly"
Lang.nuiVerdict_sellForm_low = "%d%% below the market: it should sell fast"
Lang.nuiVerdict_orderForm_high = "%d%% above the market: likely supplied soon"
Lang.nuiVerdict_orderForm_low = "%d%% below the market: it may wait"
```

`jo_auction_house/config/_default.lock/locations.lua`

```lua
-- * ======================================
-- *  AUCTION HOUSES
-- * ======================================

-- `id` is saved in the database with every lot: keep it unique and never rename it once players
-- have used the auction house, or their lots and the items waiting in their chest are lost from view.
Config.locations = {
    {
        id = "valentine",
        name = "Valentine Auction House",
        npc = {
            location = vec4(-359.344, 736.387, 115.5, 120), -- Also where the prompt shows when there is no NPC
            model = "casp_coachrobbery_lenny_males_01",     -- false: no visible NPC, only the prompt at `location`
            spawnDistance = 30.0,                           -- The NPC appears within this distance (m)
            promptDistance = 2.0,                           -- The prompt shows within this distance (m)
        },
        chest = {
            location = vec4(-358.681, 735.142, 115.882, 288.704), -- Next to the NPC; set down on the ground at spawn
            model = "p_chest01x",
            promptDistance = 1.5,
        },
        blip = {
            name = "Auction House",
            sprite = "blip_shop_store",
            color = "BLIP_MODIFIER_MP_COLOR_32",
        },
    },
    {
        id = "st-denis",
        name = "St Denis Auction House",
        npc = {
            location = vec4(2836.308, -1306.663, 45.512, 294.192),
            model = "casp_coachrobbery_lenny_males_01",
            spawnDistance = 30.0,
            promptDistance = 2.0,
        },
        chest = {
            location = vec4(2834.003, -1304.439, 46.746, 42),
            model = "p_chest01x",
            promptDistance = 1.5,
        },
        blip = {
            name = "Auction House",
            sprite = "blip_shop_store",
            color = "BLIP_MODIFIER_MP_COLOR_32",
        },
    },
    {
        id = "blackwater",
        name = "Blackwater Auction House",
        npc = {
            location = vec4(-738.265, -1253.067, 43.834, 6.598),
            model = "casp_coachrobbery_lenny_males_01",
            spawnDistance = 30.0,
            promptDistance = 2.0,
        },
        chest = {
            location = vec4(-740.819, -1257.490, 44.734, 89.572),
            model = "p_chest01x",
            promptDistance = 1.5,
        },
        blip = {
            name = "Auction House",
            sprite = "blip_shop_store",
            color = "BLIP_MODIFIER_MP_COLOR_32",
        },
    },
}
```

`jo_auction_house/config/_default.lock/market.lua`

```lua
-- * ======================================
-- *  PRICES AND LIMITS
-- * ======================================

-- Apply to fixed-price lots, auctions and buy orders alike
Config.allowedCurrencies = { -- Currencies a seller can ask for and a buyer can offer
    money = true,
    gold = true,
}
Config.commissionPercent = 5     -- Percentage deducted from the seller's proceeds (never on barter)
Config.allowBarter = true        -- A fixed-price lot or a buy order can ask for items instead of money (one item, no commission)
Config.allowFreeListing = false  -- A lot can be published without a price
Config.allowPartialTrades = true -- Money lots and buy orders can be bought or supplied in parts
Config.listingMaxQuantity = 100  -- Most units in one lot or one buy order
Config.listingMaxPrice = {       -- Highest price of one lot or one buy order, per currency
    money = 100000,
    gold = 1000,
}

-- * ======================================
-- *  LOTS
-- * ======================================

Config.maxActiveListingsPerCharacter = 20        -- Most lots for sale at once per character, auctions included; nil for no limit
Config.listingDurationSeconds = 7 * 24 * 60 * 60 -- Fixed-price lots: 7 days (days x 24 hours x 60 minutes x 60 seconds)
Config.canBuyOwnListing = false                  -- A player can buy their own fixed-price lot

-- * ======================================
-- *  AUCTIONS
-- * ======================================

-- Durations a seller can choose for an auction, in seconds; the end is fixed, late bids do not extend it.
-- Each line reads hours x 60 minutes x 60 seconds: add, remove or change lines to offer other choices.
Config.auctionDurations = {
    12 * 60 * 60, -- 12 hours
    24 * 60 * 60, -- 24 hours (1 day)
    48 * 60 * 60, -- 48 hours (2 days)
    72 * 60 * 60, -- 72 hours (3 days)
}
-- Next bid: current bid plus the larger of this percentage and the floor of its currency
Config.auctionMinIncrementPercent = 5
Config.auctionMinIncrement = {
    money = 1,
    gold = 0.1,
}

-- * ======================================
-- *  BUY ORDERS
-- * ======================================

Config.enableBuyOrders = true -- false hides buy orders and disables their server operations, including expiry

-- Durations a buyer can choose for a buy order, in seconds.
-- Each line reads hours x 60 minutes x 60 seconds: add, remove or change lines to offer other choices.
Config.orderDurations = {
    12 * 60 * 60, -- 12 hours
    24 * 60 * 60, -- 24 hours (1 day)
    48 * 60 * 60, -- 48 hours (2 days)
    72 * 60 * 60, -- 72 hours (3 days)
}
Config.maxActiveOrdersPerCharacter = 10 -- Most buy orders open at once per character; nil for no limit
Config.canFulfillOwnOrder = false       -- A player can supply their own buy order

-- * ======================================
-- *  MARKET STATISTICS
-- * ======================================

-- Reference prices come from concluded exchanges only: the median unit price, per currency
Config.statsPeriods = { 7, 30, 90 } -- Periods a player can choose on the item sheet, in days
Config.statsDefaultPeriod = 30      -- Period shown first; must be one of statsPeriods
Config.statsMinTrades = 5           -- Exchanges in one currency needed to show a price and a trend
Config.statsStableThreshold = 0.05  -- Below this change against the previous period, the trend is stable (5%)
Config.statsCacheSeconds = 300      -- 5 minutes: how long computed prices are reused; supply and demand are always live
```

To change a setting, copy its file from `config/_default.lock/` into `config/custom/` and keep only the settings you change: the others keep their default value. Then run `refresh` and `ensure jo_auction_house`.

| File | Settings |
| --- | --- |
| `global.lua` | Market mode, chest capacity, page size, interface sounds, the remote command and debug logs |
| `market.lua` | Currencies, commission, barter, partial trades, free lots, price and quantity limits, durations of lots, auctions and buy orders, market statistics |
| `items.lua` | Which items can be traded, the categories and the category preselected for each item |
| `locations.lua` | Auction houses: id, clerk, chest and blip of each one |
| `keys.lua` | Prompt keys at the clerk and the chest |
| `lang.lua` | Every text shown to players: translate the script here |

A few points to check for your server:

- `Config.itemCategories` (`items.lua`) ships with VORP item names. Adapt them to your inventory.
- On VORP, the chest capacity counts every unit, not slots: keep `Config.chestMaxSlots` well above `Config.listingMaxQuantity`.
- On RSG, gold amounts must be whole numbers. Gold bid steps are rounded up to a whole unit.
- Every new category needs a `Lang.category_<id>` name. A lot whose category no longer exists is shown under `Config.defaultCategory`.

## 4. FAQ

:::details The prompts are not working!
1. **Keyboard layout**: the script uses the [raw keys](/jo_libs/modules/raw-keys/) module: [set the keyboard layout](/jo_libs/modules/raw-keys/client#setting-keyboard-layout).
2. **Key conflicts**: another resource may use the same key. Change the keys in `keys.lua` (copy it into `config/custom/`).
3. **Distance**: get closer. The clerk prompt shows within 2 meters and the chest prompts within 1.5 meters (`promptDistance` of each auction house in `locations.lua`).
4. **Installation**: check that your framework is [compatible with jo_libs](/jo_libs/modules/framework-bridge/#compatible-frameworks) and that `jo_libs` starts before `jo_auction_house`.
:::

:::details The resource refuses to start after I changed the market mode
The market mode is recorded in the database on the first start because local and global chests hold different contents. Restore the recorded `Config.marketMode`. Switching modes on an existing database is not supported.
:::

:::details Lots or chest contents disappeared after I edited an auction house
Every lot and waiting item is saved with the auction house `id`. Renaming or removing a location hides its lots and chest contents. Restore the previous `id`. Each `id` must be unique and use lowercase letters, digits, `_` or `-` (50 characters at most), or the resource stops at startup.
:::

:::details My money was not added to my wallet after a sale
Money from sales and refunds is never paid automatically. Go to the chest and press `R` to collect it. In local mode, use the chest of the auction house where the trade happened.
:::

:::details I cannot find an item in the Sell counter
The item must be allowed by `Config.itemFilter`. Inventory entries of type weapon are never offered. Items already listed have left your satchel.
:::

:::details I cannot open the auction house with the command
The command works near the clerk by default. To use it from anywhere, register the [`canUseAuctionHouseRemotely`](#canuseauctionhouseremotely) filter, as in the [integration examples](#allow-the-remote-command-with-an-ace-permission). In local mode, also pass the auction house `id`.
:::

:::details What happens to buy orders when I disable them?
With `Config.enableBuyOrders = false`, the **Wanted** counter and every order action disappear, and expiry pauses. Existing orders stay in the database: they are not cancelled or refunded automatically. Settle them before disabling the feature.
:::

## 5. For developers

Every hook is registered from your own resource with the exports of `jo_auction_house`: `exports.jo_auction_house:registerAction(name, callback)` and `exports.jo_auction_house:registerFilter(name, callback)`, on the side shown by the badge of each hook. `source` is the player who triggered the operation. Hook arguments are copied tables: use their fields (`listing.item`, `listing.quantity`, `order.locationId`…), not class methods. Prices are copies of `jo.pricing` tables. The callbacks and network events used by the interface are not part of the public API.

:::warning Restarting jo_auction_house
The hooks are stored by `jo_auction_house`: they are lost when `jo_auction_house` restarts alone. With `jo_libs` in your resource, register them in `jo.onResourceStart("jo_auction_house", function() ... end)`, as in the [integration examples](#integration-examples), so they are registered again. The examples that use `jo.framework` need `jo_libs` in your resource (`@jo_libs/init.lua` and the `framework-bridge` module).
:::

:::warning Hooks never bypass server checks
Identity, distance, ownership, quantities and payment are always checked by the server, whatever a filter returns.
:::

### Actions

[Actions](/DeveloperResources/actions) run after an operation has been saved. Their callbacks do not return a replacement value.

#### `[Client]` auctionHouseOpened
After the interface opens for the local player.

```lua
-- @param location - table: the configured auction house (id, name, npc, chest, blip)
exports.jo_auction_house:registerAction("auctionHouseOpened", function(location)
end)
```

#### `[Server]` auctionSettled
After an auction closes for a buyer: when it ends with bids, or when a player uses buy-now. An auction ending without bids does not trigger it.

```lua
-- @param listing - table: the closed auction; listing.price is the final price
-- @param buyer - table: { identifier = string, charid = string } of the winner
-- @param buyNow - boolean: closed by buy-now
exports.jo_auction_house:registerAction("auctionSettled", function(listing, buyer, buyNow)
end)
```

#### `[Server]` bidPlaced
After a bid was paid and saved.

```lua
-- @param listing - table: the auction with its new current bid
-- @param source - serverID of the bidder
-- @param amount - number: the bid, in the auction currency
exports.jo_auction_house:registerAction("bidPlaced", function(listing, source, amount)
end)
```

#### `[Server]` listingCancelled
After the seller cancelled a lot. Expiry and `/auctionremove` do not trigger it.

```lua
-- @param listing - table: the cancelled lot
-- @param source - serverID of the seller
exports.jo_auction_house:registerAction("listingCancelled", function(listing, source)
end)
```

#### `[Server]` listingPublished
After a fixed-price lot or an auction was saved and its items left the seller's inventory.

```lua
-- @param listing - table: the published lot; listing.type is "direct" or "auction"
-- @param source - serverID of the seller
exports.jo_auction_house:registerAction("listingPublished", function(listing, source)
end)
```

#### `[Server]` listingSold
After each purchase of a fixed-price lot. On a partial purchase, `listing` holds the remaining quantity; its `status` becomes `"sold"` when nothing remains. Auctions trigger `auctionSettled` instead.

```lua
-- @param listing - table: the lot after the purchase
-- @param buyerSource - serverID of the buyer
-- @param quantity - integer: units bought
exports.jo_auction_house:registerAction("listingSold", function(listing, buyerSource, quantity)
end)
```

#### `[Server]` moneyCollected
After the money owed was credited to the player's wallet at a chest.

```lua
-- @param source - serverID of the player
-- @param collected - table: jo.pricing copy of the amount paid
exports.jo_auction_house:registerAction("moneyCollected", function(source, collected)
end)
```

#### `[Server]` orderClosed
When a buy order closes before being fully supplied. What it still held is returned to the buyer's chest.

```lua
-- @param order - table: the closed buy order
-- @param reason - "cancelled", "expired" or "removed" (/orderremove)
exports.jo_auction_house:registerAction("orderClosed", function(order, reason)
end)
```

#### `[Server]` orderCreated
After a buy order was saved and its total or offered items were taken.

```lua
-- @param order - table: the posted buy order
-- @param source - serverID of the buyer
exports.jo_auction_house:registerAction("orderCreated", function(order, source)
end)
```

#### `[Server]` orderFulfilled
After each supply. On a partial supply, `order` holds the remaining quantity; its `status` becomes `"fulfilled"` when nothing remains.

```lua
-- @param order - table: the buy order after the supply
-- @param supplierSource - serverID of the supplier
-- @param quantity - integer: units supplied
exports.jo_auction_house:registerAction("orderFulfilled", function(order, supplierSource, quantity)
end)
```

### Filters

[Filters](/DeveloperResources/filters) synchronously control permissions or replace values. Return the value expected by each filter. The `can…` filters receive `true` (`false` for `canUseAuctionHouseRemotely`): return `false` to refuse, return the value received to keep it. Another resource may have refused before yours, so keep its refusal (`if not allowed then return false end`). A filter may run several times for one operation: do not rely on side effects.

#### `[Server]` canBuyListing
Before a fixed-price lot is paid. Also called before an auction buy-now, with the whole quantity.

```lua
-- @param allowed - boolean: true
-- @param source - serverID of the buyer
-- @param listing - table: copy of the lot
-- @param quantity - integer: units to buy
-- @return boolean
exports.jo_auction_house:registerFilter("canBuyListing", function(allowed, source, listing, quantity)
    return allowed
end)
```

#### `[Server]` canCollectMoney
Before the money owed is collected at a chest. Refusing keeps the money owed; the filter cannot change the amount.

```lua
-- @param allowed - boolean: true
-- @param source - serverID of the player
-- @param owed - table: jo.pricing copy of the amount owed at this chest
-- @return boolean
exports.jo_auction_house:registerFilter("canCollectMoney", function(allowed, source, owed)
    return allowed
end)
```

#### `[Server]` canCreateOrder
Before a buy order is posted and its total taken.

```lua
-- @param allowed - boolean: true
-- @param source - serverID of the buyer
-- @param data - table: { locationId, item, quantity, price, barter, duration }
--   price: jo.pricing copy of the total held, or of the offered items when barter is true
--   duration: integer, in seconds
-- @return boolean
exports.jo_auction_house:registerFilter("canCreateOrder", function(allowed, source, data)
    return allowed
end)
```

#### `[Server]` canFulfillOrder
Before a buy order is supplied and the supplier's items taken.

```lua
-- @param allowed - boolean: true
-- @param source - serverID of the supplier
-- @param order - table: copy of the buy order
-- @param quantity - integer: units to supply
-- @return boolean
exports.jo_auction_house:registerFilter("canFulfillOrder", function(allowed, source, order, quantity)
    return allowed
end)
```

#### `[Client]` canOpenAuctionHouse
Before the interface opens for the local player. This is a client-side convenience: the server still checks every request.

```lua
-- @param allowed - boolean: true
-- @param location - table: the configured auction house
-- @return boolean
exports.jo_auction_house:registerFilter("canOpenAuctionHouse", function(allowed, location)
    return allowed
end)
```

#### `[Server]` canPlaceBid
Before a bid is paid.

```lua
-- @param allowed - boolean: true
-- @param source - serverID of the bidder
-- @param listing - table: copy of the auction
-- @param amount - number: the bid, in the auction currency
-- @return boolean
exports.jo_auction_house:registerFilter("canPlaceBid", function(allowed, source, listing, amount)
    return allowed
end)
```

#### `[Server]` canPublishListing
Before a lot or an auction is published and its items leave the seller's inventory.

```lua
-- @param allowed - boolean: true
-- @param source - serverID of the seller
-- @param data - table: { locationId, item, quantity, metadata, category, price, type, buyNowPrice }
--   price: jo.pricing copy of the lot total (or of the items asked), or the starting price of an auction
--   type: "direct" or "auction"
--   buyNowPrice: number|nil, the buy-now price of an auction
-- @return boolean
exports.jo_auction_house:registerFilter("canPublishListing", function(allowed, source, data)
    return allowed
end)
```

#### `[Client]` canSeeAuctionHouseBlip
When the blips are created, for each auction house that has one.

```lua
-- @param allowed - boolean: true
-- @param location - table: the configured auction house
-- @return boolean
exports.jo_auction_house:registerFilter("canSeeAuctionHouseBlip", function(allowed, location)
    return allowed
end)
```

#### `[Server]` canUseAuctionHouseRemotely
When a player farther than 10 meters from the clerk uses the auction house: by the `/auctionHouse` command and by each interface request made from a distance. It never applies to the chest.

```lua
-- @param allowed - boolean: false
-- @param source - serverID of the player
-- @param locationId - string: id of the auction house
-- @return boolean
exports.jo_auction_house:registerFilter("canUseAuctionHouseRemotely", function(allowed, source, locationId)
    return allowed
end)
```

#### `[Server]` overwriteCommission
Replaces the commission rate of a fixed-price lot, an auction or a buy order. Called when the receipt is quoted and again at confirmation; the operation is refused if the two rates differ. The rate is rounded to three decimals, then stored with the lot or order. Lots and orders paid in items pay no commission and never call it.

```lua
-- @param rate - number: percentage, Config.commissionPercent by default
-- @param source - serverID of the seller, or of the buyer for a buy order
-- @param locationId - string: id of the auction house
-- @param item - string: item name
-- @param quantity - integer: units
-- @param price - table: jo.pricing copy of the lot total, the auction starting price or the order total
-- @return number: percentage from 0 to 100; any other value refuses the operation
exports.jo_auction_house:registerFilter("overwriteCommission", function(rate, source, locationId, item, quantity, price)
    return rate
end)
```

### Integration examples

#### Allow the remote command with an ACE permission
Players with the `jo_auction_house.remote` permission can use `/auctionHouse` from anywhere. Add `add_ace group.vip jo_auction_house.remote allow` (or another group) to your `server.cfg`.

```lua
-- server side
jo.onResourceStart("jo_auction_house", function()
    exports.jo_auction_house:registerFilter("canUseAuctionHouseRemotely", function(allowed, source, locationId)
        return allowed or IsPlayerAceAllowed(source, "jo_auction_house.remote")
    end)
end)
```

#### Lower the commission for a job
Traders pay half the commission. The same rate is returned at quote and at confirmation, so the receipt stays valid.

```lua
-- server side
jo.onResourceStart("jo_auction_house", function()
    exports.jo_auction_house:registerFilter("overwriteCommission", function(rate, source, locationId, item, quantity, price)
        if jo.framework:getJob(source) == "trader" then
            return rate / 2
        end
        return rate
    end)
end)
```

#### Keep buy orders for one job
Only merchants can post buy orders. Earlier refusals are kept.

```lua
-- server side
jo.onResourceStart("jo_auction_house", function()
    exports.jo_auction_house:registerFilter("canCreateOrder", function(allowed, source, data)
        if not allowed then return false end
        return jo.framework:getJob(source) == "merchant"
    end)
end)
```
