# API Reference

**Version:** 2.0.6

Other plugins can react to shop activity through the plugin's own event bus and can call its services through `ShopPlugin.getInstance()`. Shops is loaded as a normal plugin (`kyuubisoft:shops`); add it to your manifest's dependencies or optional dependencies so it loads first, and compile against its jar.

:::caution
These classes are the plugin's internal code, not a versioned API. Signatures can change between versions. The money and stock paths take locks and roll back on failure; prefer the high-level methods listed here over changing `ShopData` or `ShopItem` directly.
:::

---

## Event bus

```java
import com.kyuubisoft.shops.event.ShopEventBus;
import com.kyuubisoft.shops.event.ShopTransactionEvent;

ShopEventBus.getInstance().register(ShopTransactionEvent.class, event -> {
    if ("BUY".equals(event.getTransactionType())) {
        // a customer bought from a shop
    }
});
```

- `register(Class<T>, Consumer<T>)` adds a listener; `fire(event)` calls every listener of exactly that class; `clear()` removes all (the plugin calls it on shutdown).
- Listeners run on the thread that fired the event: the player's world thread for actions from windows and commands, the plugin's scheduler thread for rental expiry, auctions and the legacy rent. Do not touch entities or components from a listener without moving to the right world thread.
- An exception in a listener is logged and does not stop the other listeners.

### Shop events (`com.kyuubisoft.shops.event`)

| Event | Fired when | Getters |
|-------|-----------|---------|
| `ShopCreateEvent` | A shop row is created in game (player shop, server shop, a rental shop when a stand is rented, the placeholder shop of a free stand). Shops created from template files fire nothing | `getShopId()`, `getType()` (`ShopType.PLAYER` / `ADMIN`), `getOwnerUuid()` (null for server shops), `getShopName()` |
| `ShopDeleteEvent` | A shop row is deleted; also when the legacy rent closes a shop | `getShopId()`, `getType()`, `getOwnerUuid()`, `getReason()` (`"deleted"`, `"owner_deleted"`, `"rent_unpaid"`) |
| `ShopTransactionEvent` | A purchase (`"BUY"`) or a sale to a shop (`"SELL"`) completed | `getShopId()`, `getBuyerUuid()` (the customer in both cases), `getSellerUuid()` (shop owner, null for server shops), `getItemId()`, `getQuantity()`, `getTotalPrice()` (before tax), `getTaxAmount()`, `getTransactionType()` |

:::note
Each create and delete fires its event once. A delete by the owner (`/ksshop delete`) carries the reason `"owner_deleted"`, other deletes `"deleted"`. The legacy rent fires `ShopDeleteEvent` with `"rent_unpaid"` when it only **closes** a shop.
:::

### Rental events (`com.kyuubisoft.shops.rental.event`)

| Event | Fired when | Getters |
|-------|-----------|---------|
| `RentalStartedEvent` | A fixed-price stand was rented, or an auction winner paid | `getSlotId()`, `getShopId()`, `getRenterUuid()`, `getRenterName()`, `getSlotDisplayName()`, `getRentedUntil()`, `getTotalCost()` |
| `RentalBidPlacedEvent` | A bid was accepted | `getSlotId()`, `getSlotDisplayName()`, `getBidderUuid()`, `getBidderName()`, `getBidAmount()`, `getPreviousHighBidder()`, `getPreviousHighBidderName()`, `getPreviousHighBid()`, `getAuctionEndsAt()` |
| `RentalAuctionWonEvent` | An auction was won and paid (after `RentalStartedEvent`) | `getSlotId()`, `getShopId()`, `getSlotDisplayName()`, `getWinnerUuid()`, `getWinnerName()`, `getWinningBid()`, `getRentedUntil()` |
| `RentalExpiredEvent` | A rental ended | `getSlotId()`, `getShopId()`, `getRenterUuid()`, `getRenterName()`, `getSlotDisplayName()`, `getMailedItems()`, `getMailedBalance()`, `getReason()` (`EXPIRED`, `FORCE_EXPIRED`, `RELEASED_EARLY`) |

Times are epoch milliseconds.

---

## Services

```java
ShopPlugin plugin = ShopPlugin.getInstance();
```

| Getter | Class | Use |
|--------|-------|-----|
| `getShopManager()` | `ShopManager` | Shops in memory: `getShop(UUID)`, `getAllShops()`, `getShopsByOwner(UUID)`, `getShopsByCategory(String)`, `getShopByRentalSlotId(UUID)`, `isActive(ShopData)` (registered and not packed) |
| `getShopService()` | `ShopService` | Trading and shop life cycle (below) |
| `getRentalService()` | `RentalService` | Stands: `getSlot(UUID)`, `getAllSlots()`, `getSlotsForRenter(UUID)`, `countActiveRentalsFor(UUID)` |
| `getMailboxService()` | `MailboxService` | `createItemMail(...)`, `createMoneyMail(...)`, `getUnclaimedForPlayer(UUID)`, `countUnclaimedForPlayer(UUID)` |
| `getEconomyBridge()` | `ShopEconomyBridge` | `isAvailable()`, `getBalance(UUID)`, `has(UUID, double)`, `withdraw(UUID, double)`, `deposit(UUID, double)`, `format(double)`, `getCurrencyName()` |
| `getShopConfig()` | `ShopConfig` | `getData()` (the fields of `config.json`), `reload()`, `save()` |
| `getI18n()` | `ShopI18n` | `get(PlayerRef, key, args...)` in the player's language, `get(key, args...)` in the server language |
| `getDatabase()` | `ShopDatabase` | Direct table access (transactions, ratings, notifications, bids) |
| `getNpcManager()` | `ShopNpcManager` | Merchant NPCs: `refreshNameTag(shop, world)`, `respawnNpc(shop, world)`, `despawnNpc(shopId)`, `respawnAll(world)` |
| `getSessionManager()` | `ShopSessionManager` | Editor locks: `isEditorLocked(shopId)`, `getEditorPlayer(shopId)` |

### ShopService

| Method | What it does |
|--------|--------------|
| `purchaseItemWithReason(PlayerRef buyer, UUID shopId, int slot, int quantity)` | Buys from the offer in that grid slot. Returns `PurchaseResult` with `isSuccess()`, `getErrorKey()` (a language key such as `shop.buy.fail.out_of_stock`), `getDelivered()`, `getMailed()`, `getPaid()` |
| `purchaseItemWithReason(buyer, shopId, slot, quantity, expectedItemId, expectedPrice)` | The same, refused with `shop.buy.fail.changed` when the slot no longer holds that item at that price |
| `sellItemWithReason(PlayerRef seller, UUID shopId, String itemId, int quantity)` | Sells to a shop's buyback offer. Returns `SellResult(outcome, earned)`; outcomes `OK`, `INVALID`, `ECONOMY_UNAVAILABLE`, `SHOP_NOT_FOUND`, `SHOP_CLOSED`, `OWN_SHOP`, `NOT_BOUGHT`, `SHOP_FULL`, `QUOTA`, `SHOP_NO_FUNDS`, `NOT_IN_INVENTORY`, `FAILED` |
| `countSellable(PlayerRef, ShopItem offer)` | How many matching items (undamaged, same metadata) the player carries |
| `rateShop(PlayerRef rater, UUID shopId, int stars, String comment)` | Rates with all checks. Returns `RateResult(outcome, minutesLeft)`: `OK`, `DISABLED`, `NOT_FOUND`, `OWN_SHOP`, `NO_STARS`, `COOLDOWN` |
| `loadRatings(UUID shopId)` | All ratings of a shop, newest first |
| `createPlayerShop(PlayerRef owner, Player player, name, category, description, worldName, x, y, z)` | Creates a player shop with all checks and the creation cost; returns `CreateShopResult` (`isSuccess()`, `getShop()`, `getErrorKey()`). The merchant is not spawned; see `ShopNpcManager.spawnNpcAtPosition` |
| `createAdminShop(name, category, description, worldName, x, y, z)` | Creates a server shop |
| `purchaseListing(Player, PlayerRef owner, UUID shopId, int days)` | Buys or extends a listing; returns `ListingResult` |
| `depositToShop(PlayerRef owner, UUID shopId, double amount)` / `withdrawFromShop(...)` | Fills or empties a shop's till |
| `pickupShop(Player, PlayerRef owner, UUID shopId)` | Packs a shop up (stock and till to the mailbox, bound license back) |
| `transferShop(UUID shopId, UUID newOwner, String newOwnerName)` | Changes the owner without permission or shop-limit checks. Refuses server shops and shops on rental stands; returns `false` (owner unchanged) when the save fails |
| `countShopsTowardLimit(UUID owner)` / `isAtShopLimit(Player, UUID owner)` | The player's shops that use a slot of their shop limit (packed ones included, rental shops depending on `rentalShopsCountTowardShopLimit`), and whether the limit is reached (`ks.shop.limit.shops.N` aware) |

### RentalService

| Method | Result |
|--------|--------|
| `rentSlot(PlayerRef, Player, UUID slotId, int days)` | `RentResult`: `SUCCESS`, `SLOT_NOT_FOUND`, `NOT_VACANT`, `LIMIT_REACHED`, `NO_PERMISSION`, `INVALID_DAYS`, `NOT_ENOUGH_FUNDS`, `ECONOMY_UNAVAILABLE`, `FAILED` |
| `extendRental(PlayerRef, Player, UUID slotId, int days)` | `RentResult` |
| `placeBid(PlayerRef, Player, UUID slotId, int amount)` | `BidResult`: `SUCCESS`, `SLOT_NOT_FOUND`, `NOT_AUCTION`, `AUCTION_CLOSED`, `NO_PERMISSION`, `BID_TOO_LOW`, `NOT_ENOUGH_FUNDS`, `ECONOMY_UNAVAILABLE`, `OWN_BID`, `FAILED` |
| `releaseEarly(PlayerRef renter, UUID slotId)` | `true` when the renter's rental was ended |
| `createFixedSlot(...)`, `createAuctionSlot(...)` | New stands (the caller spawns the stand's merchant) |
| `adminUpdateSlot(...)`, `adminRestartAuction(UUID)`, `adminEndRental(UUID)`, `deleteSlot(UUID)` | The admin window's stand actions |

### MailboxService

```java
MailboxService mail = plugin.getMailboxService();
mail.createItemMail(ownerUuid, shopId, shopName, "Quest reward", "Food_Bread", 16, null);
mail.createMoneyMail(ownerUuid, shopId, shopName, "Event", 250.0);
int waiting = mail.countUnclaimedForPlayer(ownerUuid);
```

`createItemMail` takes an optional item metadata JSON (enchantments and other BSON data) as last argument. Both methods throw when the database refuses the write, so the caller can roll back. The mail shows in the player's mailbox; its "from" line depends on the sender text.

---

## Permission helper

`com.kyuubisoft.shops.util.PermissionLimits` resolves the limit and perk nodes with the wildcard guard:

```java
int maxShops   = PermissionLimits.resolveMaxShops(player, cfg.playerShops.maxShopsPerPlayer);
int maxOffers  = PermissionLimits.resolveMaxItems(player, cfg.playerShops.maxItemsPerShop);
int maxRentals = PermissionLimits.resolveMaxRentals(player, cfg.rentalStations.maxConcurrentRentalsDefault);
boolean wildcard  = PermissionLimits.hasWildcard(player);
boolean permanent = PermissionLimits.hasExplicit(player, "ks.shop.list.permanent");
```

---

## Database tables

Created on the first start (SQLite or MySQL). Columns that later versions added are added automatically.

| Table | Contents |
|-------|----------|
| `shop_shops` | One row per shop: id, name, description, type, owner, world and position, merchant facing and look, market icon, category, rating and revenue totals, till (`shop_balance`), legacy rent fields, featured until, open, name tag, packed, `listed_until` (`Long.MAX_VALUE` = permanent), `rental_slot_id`, `rental_expires_at`, created / last activity |
| `shop_items` | Offers: shop, item ID, sale price (`buy_price`), buyback price (`sell_price`), stock (`-1` = unlimited), `max_stock`, switches, grid slot, category, `daily_buy_limit` (buyback quota), item metadata |
| `shop_transactions` | Every purchase (`BUY`) and sale to a shop (`SELL`): customer, owner, item, quantity, price per unit, total, tax, time |
| `shop_ratings` | One row per rater and shop: stars, comment, time |
| `shop_notifications` | Sale notifications for offline owners (and legacy rent notices), with a read flag |
| `shop_mailbox` | Item and money mails: owner, type, item, quantity, amount, source shop and sender, metadata, claimed flag |
| `shop_rental_slots` | Stands: position, name, mode, prices, days, auction values and the current state |
| `shop_rental_bids` | Bids of the current auction rounds |
| `shop_player_flags` | Per player: whether the free first listing was used |

The plugin keeps shops and stands in memory and writes them back (most changes at once, the rest every 60 seconds and on shutdown). Edit tables only while the server is stopped.