diff --git a/docs/README.md b/docs/README.md index 9025e5a..ef7465b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,7 +24,7 @@ OpenRP.Framework is the open-source (LGPL v3) gameplay library behind Open Rolep - [Accounts](features/accounts.md): register, log in, one login per account - [AccountSettings](features/account-settings.md): chat toggles and `/settings` - [Actors](features/actors.md): non-player characters in the world, created and edited in-game with `/editactors` -- [Banking](features/banking.md): banks, accounts with OBANs, AI bank tellers, `/bank` and `/editbanks` +- [Banking](features/banking.md): banks, accounts with OBANs, AI bank tellers, debit cards and ATMs, `/bank`, `/atm` and `/editbanks` - [ActorConversations](features/actor-conversations.md): AI conversations between actors - [ActorRoleplay](features/actor-roleplay.md): AI actors that answer players' /me, /do and /say - [Admins](features/admins.md): admin and tester commands @@ -48,6 +48,7 @@ OpenRP.Framework is the open-source (LGPL v3) gameplay library behind Open Rolep - [Jurisdictions](features/jurisdictions.md): countries and cities with tags, currency, government, tax registrations and settings; `/editjurisdictions` and `/government` - [MainMenu](features/main-menu.md): what you see after connecting - [Maps](features/maps.md): saved maps of objects, built in-game with `/editmaps` and loaded at startup +- [Payments](features/payments.md): one way for features to take cash or card payments into a bank account - [Permissions](features/permissions.md): see the Permissions guide - [Phones](features/phones.md): 1992-style mobile phones: calls, texts, phone book, call log - [Players](features/players.md): find a player's account and character diff --git a/docs/commands.md b/docs/commands.md index 3760173..46f4f29 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -83,6 +83,7 @@ All player commands of the Framework, grouped as in `/help`. `[argument]` is req | Command | Groups | Description | Feature | |---|---|---|---| +| `/atm` | Default | Use the ATM you're standing at, with a debit card. | [Banking](features/banking/cards-and-atms.md) | | `/bank` | Default | Open the bank menu at the teller you're standing at. | [Banking](features/banking.md) | ## Character @@ -212,6 +213,7 @@ All player commands of the Framework, grouped as in `/help`. `[argument]` is req | `/spawnveh [model] ` | Admin, Tester | Spawn a vehicle. Use /spawnveh followed by the vehicle name or ID to generate a new vehicle for your use. | [Admins](features/admins.md) | | `/spawnvehicle [model] ` | Admin, Tester | Spawn a vehicle. Use /sv followed by the vehicle name or ID to generate a new vehicle for your use. | [Admins](features/admins.md) | | `/sv [model] ` | Admin, Tester | Spawn a vehicle. Use /sv followed by the vehicle name or ID to generate a new vehicle for your use. | [Admins](features/admins.md) | +| `/testpayment [amount] [OBAN]` | Admin, Tester | Ask yourself to pay an amount into a bank account, to test cash and card payments. | [Payments](features/payments.md) | ## Vehicles > General diff --git a/docs/database.md b/docs/database.md index 373fae4..066a7a7 100644 --- a/docs/database.md +++ b/docs/database.md @@ -118,9 +118,11 @@ See [Radios](features/radios.md). | `Banks` (`BankModel`) | `Name` (32), `Code` (4, unique), `JurisdictionId` → jurisdictions (restrict), `RunByFactionId` → factions (set null), `MonthlyFee` decimal(18,2) | The code and the jurisdiction's tag are part of every OBAN | | `BankAccounts` (`BankAccountModel`) | `Oban` (18, unique), `BankId` (restrict), `CurrencyId` (restrict), `Balance` decimal(18,2), `OwnerType` (Character, Faction, Property, Bank), `OwnerId`, `Name` (32), `ClosedAt`, `NextFeeAt` | The balance only changes through single updates. Owner type Bank is the bank's own account, without a fee | | `BankAccountAccess` (`BankAccountAccessModel`) | `BankAccountId` (cascade), `CharacterId` (cascade), `Level` (View, Full) | Unique per account + character | -| `BankTransactions` (`BankTransactionModel`) | `BankAccountId` (cascade), `Amount` (signed), `BalanceAfter`, `Type`, `OtherOban`, `CharacterId` (set null), `CreatedOn` | An account's history | +| `BankTransactions` (`BankTransactionModel`) | `BankAccountId` (cascade), `Amount` (signed), `BalanceAfter`, `Type`, `OtherOban`, `CharacterId` (set null), `BankCardId` (set null), `Description` (64), `CreatedOn` | An account's history. `BankCardId` marks ATM and card use; the ATM limit adds up a card's withdrawals by it | | `BankBranches` (`BankBranchModel`) | `BankId` (cascade), `PropertyId` (cascade, unique) | Tellers only work inside their bank's branches | | `BankTellers` (`BankTellerModel`) | `ActorId` (cascade, unique), `BankId` (cascade) | | +| `BankCards` (`BankCardModel`) | `BankAccountId` (cascade), `CharacterId` (cascade), `Digits` (4), `Name` (32), `PinHash` (BCrypt), `WrongPinAttempts`, `BlockedAt`, `CancelledAt` | A [debit card](features/banking/cards-and-atms.md); its item stores `[BANK_CARD_ID=n]` | +| `BankPendingDeposits` (`BankPendingDepositModel`) | `BankAccountId` (restrict), `BankCardId` (set null), `CharacterId` (set null), `Amount`, `CreditAt`, `CreditedAt`, `AtmX`, `AtmY`, `AtmZ`, `AtmInterior`, `AtmVirtualWorld` | Cash put into an ATM, credited at `CreditAt`; the ATM's position says where the cash sits until then | See [Banking](features/banking.md). @@ -150,7 +152,7 @@ The item types (definitions), not the items players own. | `KeepOnDeath`, `CanDrop`, `CanDestroy`, `Stackable` | bool | | | `DropModelId` | int? | Object model shown when dropped | -The Framework seeds 67 items: +The Framework seeds 68 items: - a uniform (skin); - a wallet; - the bills and coins of the San Andreas Dollar and the Caeroyna Ruble; @@ -160,7 +162,8 @@ The Framework seeds 67 items: - twelve fish species; - a mobile phone (item 49, `UseType` Phone). Each phone item points to its row in `Phones` with `[PHONE_ID=x]`; - a handheld radio (item 50, `UseType` Radio), pointing to its row in `Radios` with `[RADIO_ID=x]`, and a radio earpiece (item 51); -- fishing gear (rod 52, bait 53, net 54), junk (55 to 57), treasures (58 to 61), four net-only fish (62 to 65) and two small saltwater fish (66 and 67). +- fishing gear (rod 52, bait 53, net 54), junk (55 to 57), treasures (58 to 61), four net-only fish (62 to 65) and two small saltwater fish (66 and 67); +- a debit card (item 68, `UseType` BankCard), pointing to its row in `BankCards` with `[BANK_CARD_ID=x]`. ### `Inventories` (`InventoryModel`) `Name`, `MaxWeight` (grams, null = unlimited). Seeded: "World Inventory", which holds items lying on the ground. diff --git a/docs/features/banking.md b/docs/features/banking.md index afc5e15..720ab1a 100644 --- a/docs/features/banking.md +++ b/docs/features/banking.md @@ -1,12 +1,13 @@ # Banking -Banks hold accounts, and each account has its own OBAN (Open Bank Account Number), which others need to send it money. Players do their banking at a bank: they talk to an AI teller, who opens the right form for them, or use `/bank` at the counter. +Banks hold accounts, and each account has its own OBAN (Open Bank Account Number), which others need to send it money. Players do their banking at a bank: they talk to an AI teller, who opens the right form for them, or use `/bank` at the counter. Away from the bank, a [debit card](banking/cards-and-atms.md) works at ATMs and for [payments](payments.md). ## How to use it | Command | Groups | Does | |---|---|---| | `/bank` | Default | Opens the bank menu at the teller you're standing at | +| `/atm` | Default | Uses the ATM you're standing at, with a debit card. See [Debit cards and ATMs](banking/cards-and-atms.md) | | `/editbanks` | Admin | Banks, their fee, branches, tellers and property accounts, and looking up an OBAN. See [Tellers](banking/tellers.md) | **Talking to a teller** opens the matching form: @@ -19,6 +20,7 @@ Banks hold accounts, and each account has its own OBAN (Open Bank Account Number | "I want to wire money to someone" | Transfer | | "What's my balance?" | Your account, or the list when you have several | | "My brother needs access" | Who has access | +| "I lost my card" | Debit card | | "I want to close my account" | Close the account | | "Show me everything" | The full bank menu | @@ -54,7 +56,7 @@ A bank's city can be annexed or become independent ("Lies in" in `/editjurisdict ## Known limitations -- **No ATMs, cheques, cards, interest or loans.** +- **No cheques, interest or loans.** - **Local currency only,** and no currency exchange. - **Property accounts** are opened by admins, because properties have no owners yet. - **No payroll** or automatic payments. @@ -66,15 +68,16 @@ A bank's city can be annexed or become independent ("Lies in" in `/editjurisdict - `IBankService`: banks, branches and tellers; - `IBankAccountService`: access rules, opening and closing, house accounts per currency (`GetOrOpenHouseAccount`), access lists, history; - `BankJurisdictionGuard`: keeps a bank's jurisdiction from being deleted (an `IJurisdictionDeletionGuard`); - - `IBankTransactionService`: deposit, withdraw, transfer and the monthly fees; + - `IBankTransactionService`: deposit, withdraw, transfer, card and cash payments, and the monthly fees; + - `IBankCardService` and `IAtmService`: see [Debit cards and ATMs](banking/cards-and-atms.md#deep-dive); - `ITellerService`: whether a teller can serve a customer right now; - `IBankEditorService`: `/editbanks`; - `IBankDialogService`: the menus. -- **Database:** `IBankingDatabase` gives each operation a fresh database context. Reads use `AsNoTracking`, and money moves with `ExecuteUpdate` inside a transaction (`UPDATE … SET Balance = Balance - x WHERE … AND Balance - x >= 0`). +- **Database:** `IBankingDatabase` gives each operation a fresh database context. Every balance change goes through `Helpers/BankLedger` (`Credit`, `Debit`), which also writes the history line. Reads use `AsNoTracking`, and money moves with `ExecuteUpdate` inside a transaction (`UPDATE … SET Balance = Balance - x WHERE … AND Balance - x >= 0`). - **Transactions** go through `UseInTransaction`, which runs them in EF's execution strategy. **Why:** a host whose connection retries on errors (`EnableRetryOnFailure`) refuses transactions opened directly; this way a dropped connection retries the whole transaction. - **Deposits** take the cash first. If crediting fails for any reason, the cash is handed back. - **The teller's actions:** registered with `AddActorAction` (see [ActorRoleplay](actor-roleplay.md#actions)), one per form, each needing its own actor permission. - **Fees:** `BankingSystem` runs every hour. Each fee is claimed by moving the account's `NextFeeAt` in one statement, so two servers never charge it twice. - **Tables:** [Banking](../database.md#banking). -Want more? → [Accounts](banking/accounts.md) · [Tellers](banking/tellers.md) · [Currencies](currencies.md) +Want more? → [Accounts](banking/accounts.md) · [Tellers](banking/tellers.md) · [Debit cards and ATMs](banking/cards-and-atms.md) · [Payments](payments.md) · [Currencies](currencies.md) diff --git a/docs/features/banking/cards-and-atms.md b/docs/features/banking/cards-and-atms.md new file mode 100644 index 0000000..a4e2b07 --- /dev/null +++ b/docs/features/banking/cards-and-atms.md @@ -0,0 +1,58 @@ +# Debit cards and ATMs + +A debit card is an item that lets whoever holds it, and knows its 4-digit PIN, use one bank account: at ATMs and to [pay](../payments.md). The bank issues it at the teller. + +## How to use it + +| Where | What | +|---|---| +| Teller, account menu: **Debit card** | Order a card (an optional name, then the PIN twice), rename it, change the PIN, block it, unblock it, or order a new one | +| `/atm` within 2 units of an ATM | Choose a card if you carry several, type the PIN, then **Balance**, **Withdraw cash** or **Deposit cash** | +| Inventory, **Use** on a card | At an ATM: the ATM with that card. Elsewhere: the card's details and **Rename the card** | + +**In the inventory** a card shows its bank, account and digits, so you can tell them apart: "SAB debit card: Savings ...4821". A named card puts its name first: "Groceries (SAB debit card: Savings ...4821)". "Blocked", "Cancelled" or "Account closed" shows under Extra Information. + +## The rules + +| Rule | Value | +|---|---| +| Cards per account per character | One working card; ordering a new one cancels the old one for good | +| Who can use a card | Whoever holds it and knows the PIN. The owner also needs full access to the account | +| Wrong PINs | 3 in a row block the card; the bank unblocks it | +| ATM withdrawals | At most 1,000 in the account's currency per card in any 24 hours | +| ATM deposits | The cash is taken at once and reaches the account **2 hours** later. At a teller it's there at once | +| Card names | Optional, at most 32 characters, no `{ }`, tabs or line breaks; anyone holding the card may rename it | + +- **Why a card item with a PIN:** cards can be stolen and PINs overheard, which is roleplay. A stolen card still needs the PIN. +- **Why ATM deposits wait 2 hours:** like a 1990s envelope deposit, the money sits in the machine until the bank collects it. That gives cash in an ATM a place and a time, so ATMs can be robbed later. +- **Why a withdrawal limit:** a stolen card with an overheard PIN can't empty an account at once. +- **Taking someone's access away** blocks their cards for that account. +- **Closing an account** is refused while an ATM deposit is still on its way to it. + +## ATMs + +Every placed [map object](../maps.md) of model **2942** (`kmb_atm1`) is an ATM. Mappers place them with `/editmaps`; there's no ATM list to keep up. + +**Why only placed objects:** GTA SA doesn't place `kmb_atm1` in the world itself, and its other ATM models (`kmb_atm2`, `kmb_atm3`) are broken variants. A separate list of ATMs would drift from the maps. + +An ATM works in the object's interior and virtual world (or all of them, when the object is set to -1). + +## Known limitations + +- **ATMs belong to no bank,** so there's no fee for using another bank's ATM. +- **A stolen faction card:** when someone other than the owner uses a card, the owner's faction membership isn't checked, only that the card isn't blocked. +- **Cash and the bank aren't saved together:** the bank side is written at once, the wallet within 60 seconds, as at the teller. + +## Deep dive + +- **Services:** + - `IBankCardService`: issuing (the card row, then the item with `[BANK_CARD_ID=n]`, saved at once), PINs, blocking, names, `GetUseError`; + - `IAtmService`: finding ATMs, withdrawals within the limit, pending deposits, `CreditDueDeposits`; + - `BankCardNameProvider`: the card's inventory name (an `IInventoryItemNameProvider`, see [Inventories](../inventories.md#deep-dive)); + - `AtmMapObjectSpawnHandler`: puts an `Atm` component on each spawned ATM object. +- **PINs** are hashed with BCrypt, like passwords. Hashing and checking run on a worker thread, so the server doesn't wait. +- **The limit** adds up the card's withdrawals of the last 24 hours (`BankTransactions.BankCardId`) in the same transaction as the debit. It locks the card row first, so two withdrawals with one card, even on two servers, can't both pass it. +- **Pending deposits:** `BankingSystem` runs every minute. Each due deposit is claimed by setting `CreditedAt` in the same transaction as the credit, so two servers never credit it twice. The row keeps the ATM's position, interior and world. +- **Tables:** [`BankCards`, `BankPendingDeposits`](../../database.md#banking). + +Want more? → [Banking](../banking.md) · [Payments](../payments.md) · [Tellers](tellers.md) diff --git a/docs/features/banking/tellers.md b/docs/features/banking/tellers.md index 823633a..5e19681 100644 --- a/docs/features/banking/tellers.md +++ b/docs/features/banking/tellers.md @@ -21,6 +21,7 @@ A teller is an AI actor that works for a bank, stands inside one of its branches | `bank.withdraw` | pay out withdrawals | | `bank.transfer` | make transfers | | `bank.manage_access` | change who has access | + | `bank.cards` | issue, block and unblock [debit cards](cards-and-atms.md), and change their PIN | | `bank.close_account` | close accounts | An actor has no permissions by default. diff --git a/docs/features/currencies.md b/docs/features/currencies.md index 63766ee..699b807 100644 --- a/docs/features/currencies.md +++ b/docs/features/currencies.md @@ -34,7 +34,7 @@ Money is physical: bills and coins, carried as items in your wallet, or loose in ## Known limitations -- **No card payments.** Bank accounts exist (see [Banking](banking.md)), but shops can't take payment from them yet. +- **Paying shops and fees** goes through [Payments](payments.md), with cash or a debit card; no feature uses it yet. - **USD has no bills seeded,** so it can't be held. - **Cancelling.** A payment is only cancelled by a disconnect or an error. Bills already handed over stay with the receiver. diff --git a/docs/features/inventories.md b/docs/features/inventories.md index 24a24dd..d931038 100644 --- a/docs/features/inventories.md +++ b/docs/features/inventories.md @@ -24,7 +24,7 @@ Picking an item offers, depending on the item: 1. **Weight.** An item's weight is its weight × amount, plus the contents if it holds an inventory. New characters get 10 kg. A stack can have its own weight, such as a caught fish. It keeps that weight and its remaining uses when it's moved or dropped. 2. **Stacking.** Stackable items join a matching stack when their extra data matches. -3. **Flags.** Each stack has extra data, such as `DEFAULT_WALLET` (where money goes), `WEARING` (the worn outfit) or the vehicle id of a key. +3. **Flags.** Each stack has extra data, such as `DEFAULT_WALLET` (where money goes), `WEARING` (the worn outfit), the vehicle id of a key or the card id of a debit card. ## Known limitations @@ -38,6 +38,7 @@ Picking an item offers, depending on the item: - `InventoryItem`: `Transfer`, `GetItemInventory`, `GetVehicleId`, `GetSkinModelId`, …; - `InventoryOpened`, while the dialog is open. - **Extra data:** `Helpers/ItemAdditionalData` parses and compares the key/value text. "Personalised" keys don't stop stacking. +- **Names of their own:** an `IInventoryItemNameProvider`, registered with `AddInventoryItemNameProvider()`, gives the items it handles their own name and Extra Information in the inventory, such as a debit card showing its account. Other items show their item type's name. **Why:** the name can come from data another feature owns, such as an account name, which can't be stored in the item's extra data. - **Services:** - `IInventoryManager`: `CreateInventory` and `LoadInventory`; - `IInventoryItemManager`; diff --git a/docs/features/items.md b/docs/features/items.md index 259ba70..24505d1 100644 --- a/docs/features/items.md +++ b/docs/features/items.md @@ -20,8 +20,9 @@ The item types that everything in an [inventory](inventories.md) is made of, suc | `Phone` | A [mobile phone](phones.md) | | `Radio` | A [handheld radio](radios.md) | | `RadioEarpiece` | Lets a radio's carrier listen without the people around them hearing it | +| `BankCard` | A [debit card](banking/cards-and-atms.md) for one bank account | -**Seeded items (67):** +**Seeded items (68):** - a uniform; - a wallet; - the SAD and CRU bills and coins; @@ -34,7 +35,8 @@ The item types that everything in an [inventory](inventories.md) is made of, suc - [fishing](fishing.md) gear: a rod (52), bait (53) and a net (54); - fishing junk (55 to 57) and treasures (58 to 61); - four net-only fish (62 to 65); -- two small saltwater fish: a sardine (66) and a mackerel (67). +- two small saltwater fish: a sardine (66) and a mackerel (67); +- a debit card (68). Some code uses these ids, so don't renumber them. diff --git a/docs/features/payments.md b/docs/features/payments.md new file mode 100644 index 0000000..2f159ac --- /dev/null +++ b/docs/features/payments.md @@ -0,0 +1,54 @@ +# Payments + +The one way features take money from a player, such as shops, rent, fines or fees. The player pays cash or with a [debit card](banking/cards-and-atms.md), and the money always lands in a bank account. + +Handing cash to another player is something else: that's `/pay`, in [Currencies](currencies.md). + +## How to use it + +```csharp +PaymentResult result = await checkoutService.RequestPaymentAsync(player, + new PaymentRequest(25m, currencyId, shopAccountId, "groceries")); +if (!player.IsComponentAlive) + return; +if (result.IsPaid) + GiveGroceries(player); +``` + +| `PaymentRequest` | Meaning | +|---|---| +| `Amount`, `CurrencyId` | What to pay | +| `ReceiverAccountId` | The bank account that receives it | +| `Description` | Shown to the player ("Pay $25.00 for groceries") and in both bank histories | +| `AllowsCash`, `AllowsCard` | Both true by default | + +| `PaymentResult.Outcome` | Meaning | +|---|---| +| `Paid` | The money is on the receiving account | +| `Cancelled` | The player chose not to pay, or left. Nothing was paid | +| `Failed` | Refused, for example a declined card. The player has been told why. Nothing was paid | + +`/testpayment [amount] [OBAN]` (Tester, Admin) asks you to pay into an account, to try it out. + +## How it works + +1. The player chooses **Cash** or **Debit card**. +2. **Cash:** the bills come from their wallet, with change, and are paid into the receiving account. If the account can't take it, the cash is handed back. +3. **Card:** they choose one of their cards in the payment's currency and type the PIN. One database transaction takes the money from the card's account and puts it on the receiving account, or does nothing. +4. The task completes with the result. A `PendingCheckout` component on the player holds it; if the player leaves, the component goes and the payment ends as cancelled. + +**Why one service:** every rule (cards, PINs, currencies, failures) is written once, and every feature behaves the same. + +**Why the receiver is always a bank account:** cash a shop takes is paid into its account straight away, so money never piles up in places nobody can see. + +## Known limitations + +- **No feature uses it yet.** Shops, rent and fines come later. +- **One payment at a time** per player. + +## Deep dive + +- **Code:** `Features/Payments/` (`ICheckoutService`, `IPaymentDialogService`, `PendingCheckout`); the money moves in Banking's `IBankTransactionService.PayWithCard` and `PayInCashAsync`. +- **Bank history:** the payer's side is a `CardPayment`, the receiver's a `PaymentReceived`, both with the description and the card. + +Want more? → [Debit cards and ATMs](banking/cards-and-atms.md) · [Banking](banking.md) diff --git a/src/OpenRP.Framework/Database/BaseDataContext.cs b/src/OpenRP.Framework/Database/BaseDataContext.cs index 86d9ec3..41de8d3 100644 --- a/src/OpenRP.Framework/Database/BaseDataContext.cs +++ b/src/OpenRP.Framework/Database/BaseDataContext.cs @@ -65,6 +65,8 @@ public class BaseDataContext : DbContext public DbSet BankTransactions { get; set; } public DbSet BankBranches { get; set; } public DbSet BankTellers { get; set; } + public DbSet BankCards { get; set; } + public DbSet BankPendingDeposits { get; set; } // Parameterless Constructor public BaseDataContext() : base() { } diff --git a/src/OpenRP.Framework/Database/Models/BankCardModel.cs b/src/OpenRP.Framework/Database/Models/BankCardModel.cs new file mode 100644 index 0000000..469e6cf --- /dev/null +++ b/src/OpenRP.Framework/Database/Models/BankCardModel.cs @@ -0,0 +1,37 @@ +using OpenRP.Framework.Database.Entities; +using System; + +namespace OpenRP.Framework.Database.Models +{ + /// + /// A debit card of one character for one account. The card item in an inventory points to it, so the card works + /// for whoever holds it and knows the PIN. + /// + public class BankCardModel : BaseModel + { + public ulong BankAccountId { get; set; } + // Whose card it is: the character it was issued to. + public ulong CharacterId { get; set; } + // The 4 digits printed on the card, so cards of one account can be told apart. + public string Digits { get; set; } + // A name the holder gave the card, or null. + public string? Name { get; set; } + // BCrypt, like passwords. + public string PinHash { get; set; } + public int WrongPinAttempts { get; set; } + // Set by the owner or by too many wrong PINs; the bank can unblock it. + public DateTime? BlockedAt { get; set; } + // Set when the card was replaced; a cancelled card never works again. + public DateTime? CancelledAt { get; set; } + + // Navigational Properties + public BankAccountModel? BankAccount { get; set; } + public CharacterModel? Character { get; set; } + + public BankCardModel() + { + Digits = string.Empty; + PinHash = string.Empty; + } + } +} diff --git a/src/OpenRP.Framework/Database/Models/BankPendingDepositModel.cs b/src/OpenRP.Framework/Database/Models/BankPendingDepositModel.cs new file mode 100644 index 0000000..3a41db9 --- /dev/null +++ b/src/OpenRP.Framework/Database/Models/BankPendingDepositModel.cs @@ -0,0 +1,32 @@ +using OpenRP.Framework.Database.Entities; +using System; + +namespace OpenRP.Framework.Database.Models +{ + /// + /// Cash put into an ATM. It reaches the account at CreditAt; until then it sits in the ATM at the stored position. + /// + public class BankPendingDepositModel : BaseModel + { + public ulong BankAccountId { get; set; } + public ulong? BankCardId { get; set; } + // Who deposited it. + public ulong? CharacterId { get; set; } + public decimal Amount { get; set; } + public DateTime CreditAt { get; set; } + // Null until the money is on the account. + public DateTime? CreditedAt { get; set; } + + // Where the cash sits until then. + public float AtmX { get; set; } + public float AtmY { get; set; } + public float AtmZ { get; set; } + public int AtmInterior { get; set; } + public int AtmVirtualWorld { get; set; } + + // Navigational Properties + public BankAccountModel? BankAccount { get; set; } + public BankCardModel? BankCard { get; set; } + public CharacterModel? Character { get; set; } + } +} diff --git a/src/OpenRP.Framework/Database/Models/BankTransactionModel.cs b/src/OpenRP.Framework/Database/Models/BankTransactionModel.cs index 6eece33..ed292b1 100644 --- a/src/OpenRP.Framework/Database/Models/BankTransactionModel.cs +++ b/src/OpenRP.Framework/Database/Models/BankTransactionModel.cs @@ -17,9 +17,14 @@ public class BankTransactionModel : BaseModel public string? OtherOban { get; set; } // Who did it, when a character did. public ulong? CharacterId { get; set; } + // The card used, for ATM withdrawals and deposits and card payments. + public ulong? BankCardId { get; set; } + // What a payment was for, for example "Card payment: groceries". + public string? Description { get; set; } // Navigational Properties public BankAccountModel? BankAccount { get; set; } public CharacterModel? Character { get; set; } + public BankCardModel? BankCard { get; set; } } } diff --git a/src/OpenRP.Framework/Extensions/ModelBuilderExtensions.cs b/src/OpenRP.Framework/Extensions/ModelBuilderExtensions.cs index 289d7a7..750ebf5 100644 --- a/src/OpenRP.Framework/Extensions/ModelBuilderExtensions.cs +++ b/src/OpenRP.Framework/Extensions/ModelBuilderExtensions.cs @@ -90,6 +90,8 @@ public static ModelBuilder ApplyOpenRoleplayFrameworkModelConfigurations(this Mo modelBuilder.ApplyConfiguration(new BankTransactionModelConfiguration()); modelBuilder.ApplyConfiguration(new BankBranchModelConfiguration()); modelBuilder.ApplyConfiguration(new BankTellerModelConfiguration()); + modelBuilder.ApplyConfiguration(new BankCardModelConfiguration()); + modelBuilder.ApplyConfiguration(new BankPendingDepositModelConfiguration()); modelBuilder.ApplyConfiguration(new PropertyModelConfiguration()); modelBuilder.ApplyConfiguration(new PropertyDoorModelConfiguration()); diff --git a/src/OpenRP.Framework/Extensions/ServiceCollectionExtensions.cs b/src/OpenRP.Framework/Extensions/ServiceCollectionExtensions.cs index 5f02ef0..1f5d5dc 100644 --- a/src/OpenRP.Framework/Extensions/ServiceCollectionExtensions.cs +++ b/src/OpenRP.Framework/Extensions/ServiceCollectionExtensions.cs @@ -25,6 +25,7 @@ using OpenRP.Framework.Features.Phones.Extensions; using OpenRP.Framework.Features.Radios.Extensions; using OpenRP.Framework.Features.Banking.Extensions; +using OpenRP.Framework.Features.Payments.Extensions; using OpenRP.Framework.Features.Properties.Extensions; using OpenRP.Framework.Features.Vehicles.Extensions; using OpenRP.Framework.Features.VirtualWorlds.Extensions; @@ -76,6 +77,7 @@ public static IServiceCollection AddOpenRoleplayFramework(this IServiceCollectio .AddPhones() .AddRadios() .AddBanking() + .AddPayments() .AddDebugSettings() .AddFlyMode() .AddBiomeGenerator() diff --git a/src/OpenRP.Framework/Features/Banking/Commands/AtmCommand.cs b/src/OpenRP.Framework/Features/Banking/Commands/AtmCommand.cs new file mode 100644 index 0000000..d5af19b --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Commands/AtmCommand.cs @@ -0,0 +1,26 @@ +using OpenRP.Framework.Features.Banking.Components; +using OpenRP.Framework.Features.Banking.Services; +using OpenRP.Framework.Features.Banking.Services.Dialogs; +using OpenRP.Framework.Features.Commands.Attributes; +using OpenRP.Framework.Shared.Chat.Enums; +using OpenRP.Framework.Shared.Chat.Extensions; +using SampSharp.Entities; +using SampSharp.Entities.SAMP; + +namespace OpenRP.Framework.Features.Banking.Commands +{ + public class AtmCommand : ISystem + { + [ServerCommand(PermissionGroups = new string[] { "Default" }, Description = "Use the ATM you're standing at, with a debit card.", CommandGroups = new string[] { "Bank" })] + public void Atm(Player player, IAtmService atmService, IBankDialogService bankDialogService) + { + Atm? atm = atmService.GetNearbyAtm(player); + if (atm == null) + { + player.SendPlayerInfoMessage(PlayerInfoMessageType.ERROR, "You aren't standing at an ATM."); + return; + } + bankDialogService.OpenAtm(player, atm, null); + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Components/Atm.cs b/src/OpenRP.Framework/Features/Banking/Components/Atm.cs new file mode 100644 index 0000000..c3a04e7 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Components/Atm.cs @@ -0,0 +1,27 @@ +using OpenRP.Framework.Features.Maps.Components; +using SampSharp.Entities; + +namespace OpenRP.Framework.Features.Banking.Components +{ + /// + /// An ATM: lives on the streamer object of a placed ATM map object, so it's gone when the object despawns. Its + /// position is read from the map object, so editor moves need nothing. + /// + public class Atm : Component + { + private readonly EntityId _mapObjectEntity; + + public Atm(EntityId mapObjectEntity) + { + _mapObjectEntity = mapObjectEntity; + } + + /// + /// The map object this ATM is, or null when it's gone. + /// + public MapObject? GetMapObject() + { + return Manager.Exists(_mapObjectEntity) ? Manager.GetComponent(_mapObjectEntity) : null; + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Components/AtmSession.cs b/src/OpenRP.Framework/Features/Banking/Components/AtmSession.cs new file mode 100644 index 0000000..35e5ab7 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Components/AtmSession.cs @@ -0,0 +1,35 @@ +using SampSharp.Entities; + +namespace OpenRP.Framework.Features.Banking.Components +{ + /// + /// On a player while they use an ATM with a card whose PIN they typed correctly. Removed when they leave the ATM menu. + /// + public class AtmSession : Component + { + private readonly ulong _cardId; + private readonly EntityId _atmEntity; + + public AtmSession(ulong cardId, EntityId atmEntity) + { + _cardId = cardId; + _atmEntity = atmEntity; + } + + /// + /// The bank card whose PIN was typed for this session. + /// + public ulong GetCardId() + { + return _cardId; + } + + /// + /// The ATM in use, or null when it despawned. + /// + public Atm? GetAtm() + { + return Manager.Exists(_atmEntity) ? Manager.GetComponent(_atmEntity) : null; + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Entities/BankCardDetails.cs b/src/OpenRP.Framework/Features/Banking/Entities/BankCardDetails.cs new file mode 100644 index 0000000..7162fe6 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Entities/BankCardDetails.cs @@ -0,0 +1,45 @@ +using OpenRP.Framework.Database.Models; +using OpenRP.Framework.Features.Banking.Enums; + +namespace OpenRP.Framework.Features.Banking.Entities +{ + /// + /// A card with what's printed on it: its account and bank. + /// + public record BankCardDetails(BankCardModel Card, BankAccountModel Account, BankModel Bank) + { + /// + /// "SAB debit card: Savings ...4821", or "Groceries (SAB debit card: Savings ...4821)" for a named card. + /// + public string GetLabel() + { + string printed = $"{Bank.Code} debit card: {Account.Name} ...{Card.Digits}"; + return string.IsNullOrEmpty(Card.Name) ? printed : $"{Card.Name} ({printed})"; + } + + public BankCardStatus GetStatus() + { + if (Card.CancelledAt != null) + return BankCardStatus.Cancelled; + if (Card.BlockedAt != null) + return BankCardStatus.Blocked; + if (Account.ClosedAt != null) + return BankCardStatus.AccountClosed; + return BankCardStatus.Active; + } + + /// + /// The status in a few words, for example "Blocked". + /// + public string GetStatusText() + { + return GetStatus() switch + { + BankCardStatus.Cancelled => "Cancelled", + BankCardStatus.Blocked => "Blocked", + BankCardStatus.AccountClosed => "Account closed", + _ => "Active" + }; + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Entities/BankingRules.cs b/src/OpenRP.Framework/Features/Banking/Entities/BankingRules.cs index 059927b..fb5d8dd 100644 --- a/src/OpenRP.Framework/Features/Banking/Entities/BankingRules.cs +++ b/src/OpenRP.Framework/Features/Banking/Entities/BankingRules.cs @@ -29,6 +29,47 @@ public static class BankingRules public const int HistoryLength = 20; public const int AccountNameMaxLength = 32; public const int BankNameMaxLength = 32; + public const int TransactionDescriptionMaxLength = 64; + + /// + /// The seeded "Debit card" item. + /// + public const int BankCardItemId = 68; + + public const int CardDigitsLength = 4; + public const int CardNameMaxLength = 32; + public const int PinLength = 4; + + /// + /// The work factor of the PIN hash, the same as passwords. + /// + public const int PinHashWorkFactor = 11; + + /// + /// Wrong PINs in a row that block a card until the bank unblocks it. + /// + public const int MaxWrongPinAttempts = 3; + + /// + /// The model of the ATM object (kmb_atm1). Every placed map object of it is an ATM. + /// + public const int AtmModelId = 2942; + + /// + /// How close a player must stand to an ATM to use it. + /// + public const float AtmRange = 2.0f; + + /// + /// The most cash one card can take from ATMs in a period, in the account's currency. + /// + public const decimal AtmWithdrawalLimit = 1000m; + public static readonly TimeSpan AtmWithdrawalLimitPeriod = TimeSpan.FromHours(24); + + /// + /// How long cash put into an ATM takes to reach the account. + /// + public static readonly TimeSpan AtmDepositDelay = TimeSpan.FromHours(2); /// /// The actor permission a teller needs for each operation. @@ -41,7 +82,8 @@ public static class BankingRules { BankOperation.Deposit, "bank.deposit" }, { BankOperation.Withdraw, "bank.withdraw" }, { BankOperation.Transfer, "bank.transfer" }, - { BankOperation.ManageAccess, "bank.manage_access" } + { BankOperation.ManageAccess, "bank.manage_access" }, + { BankOperation.ManageCards, "bank.cards" } }; /// @@ -52,7 +94,7 @@ public static BankAccessLevel GetRequiredAccess(BankOperation operation) return operation switch { BankOperation.View => BankAccessLevel.View, - BankOperation.Deposit or BankOperation.Withdraw or BankOperation.Transfer => BankAccessLevel.Full, + BankOperation.Deposit or BankOperation.Withdraw or BankOperation.Transfer or BankOperation.ManageCards => BankAccessLevel.Full, _ => BankAccessLevel.Manage }; } diff --git a/src/OpenRP.Framework/Features/Banking/Enums/BankCardStatus.cs b/src/OpenRP.Framework/Features/Banking/Enums/BankCardStatus.cs new file mode 100644 index 0000000..9239552 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Enums/BankCardStatus.cs @@ -0,0 +1,12 @@ +namespace OpenRP.Framework.Features.Banking.Enums +{ + public enum BankCardStatus + { + Active = 1, + // Replaced by a new card; never works again. + Cancelled = 2, + // By its owner or by too many wrong PINs; the bank can unblock it. + Blocked = 3, + AccountClosed = 4 + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Enums/BankOperation.cs b/src/OpenRP.Framework/Features/Banking/Enums/BankOperation.cs index 78d0b45..dd1fba2 100644 --- a/src/OpenRP.Framework/Features/Banking/Enums/BankOperation.cs +++ b/src/OpenRP.Framework/Features/Banking/Enums/BankOperation.cs @@ -11,6 +11,7 @@ public enum BankOperation Deposit = 4, Withdraw = 5, Transfer = 6, - ManageAccess = 7 + ManageAccess = 7, + ManageCards = 8 } } diff --git a/src/OpenRP.Framework/Features/Banking/Enums/BankTransactionType.cs b/src/OpenRP.Framework/Features/Banking/Enums/BankTransactionType.cs index 152e9a9..8ee6b2d 100644 --- a/src/OpenRP.Framework/Features/Banking/Enums/BankTransactionType.cs +++ b/src/OpenRP.Framework/Features/Banking/Enums/BankTransactionType.cs @@ -7,6 +7,10 @@ public enum BankTransactionType TransferIn = 3, TransferOut = 4, Fee = 5, - FeeIncome = 6 + FeeIncome = 6, + // Money out of the payer's account for a card payment. + CardPayment = 7, + // A payment received, by card or as cash paid in for the receiver. + PaymentReceived = 8 } } diff --git a/src/OpenRP.Framework/Features/Banking/Enums/PinCheckResult.cs b/src/OpenRP.Framework/Features/Banking/Enums/PinCheckResult.cs new file mode 100644 index 0000000..64c941b --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Enums/PinCheckResult.cs @@ -0,0 +1,10 @@ +namespace OpenRP.Framework.Features.Banking.Enums +{ + public enum PinCheckResult + { + Correct = 1, + Wrong = 2, + // Wrong, and that blocked the card; or the card was blocked already. + Blocked = 3 + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Extensions/ServiceCollectionExtensions.cs b/src/OpenRP.Framework/Features/Banking/Extensions/ServiceCollectionExtensions.cs index b8948e3..980cb0c 100644 --- a/src/OpenRP.Framework/Features/Banking/Extensions/ServiceCollectionExtensions.cs +++ b/src/OpenRP.Framework/Features/Banking/Extensions/ServiceCollectionExtensions.cs @@ -6,7 +6,9 @@ using OpenRP.Framework.Features.Banking.Enums; using OpenRP.Framework.Features.Banking.Services; using OpenRP.Framework.Features.Banking.Services.Dialogs; +using OpenRP.Framework.Features.Inventories.Extensions; using OpenRP.Framework.Features.Jurisdictions.Extensions; +using OpenRP.Framework.Features.Maps.Extensions; using System; namespace OpenRP.Framework.Features.Banking.Extensions @@ -25,6 +27,10 @@ public static IServiceCollection AddBanking(this IServiceCollection self) .AddSingleton() .AddSingleton() .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddMapObjectSpawnHandler() + .AddInventoryItemNameProvider() .AddJurisdictionDeletionGuard() .AddJurisdictionSetting() .AddTellerPermissions() @@ -40,7 +46,8 @@ private static IServiceCollection AddTellerPermissions(this IServiceCollection s .AddActorPermission(BankingRules.TellerPermissions[BankOperation.Deposit], "Take cash deposits") .AddActorPermission(BankingRules.TellerPermissions[BankOperation.Withdraw], "Pay out cash withdrawals") .AddActorPermission(BankingRules.TellerPermissions[BankOperation.Transfer], "Make transfers for customers") - .AddActorPermission(BankingRules.TellerPermissions[BankOperation.ManageAccess], "Change who has access to an account"); + .AddActorPermission(BankingRules.TellerPermissions[BankOperation.ManageAccess], "Change who has access to an account") + .AddActorPermission(BankingRules.TellerPermissions[BankOperation.ManageCards], "Issue, block and unblock debit cards"); } /// @@ -56,7 +63,8 @@ private static IServiceCollection AddTellerActions(this IServiceCollection self) .AddTellerAction("bank_withdraw", "pay out cash, when they want to take money out", AmountDetail, BankOperation.Withdraw) .AddTellerAction("bank_transfer", "make a transfer, when they want to send money to another account", AmountDetail, BankOperation.Transfer) .AddTellerAction("bank_access", "change who has access to their account, when they want to add or remove someone", null, BankOperation.ManageAccess) - .AddTellerAction("bank_close_account", "close an account, when they want to close one", null, BankOperation.CloseAccount); + .AddTellerAction("bank_close_account", "close an account, when they want to close one", null, BankOperation.CloseAccount) + .AddTellerAction("bank_cards", "order, block, unblock or rename a debit card, or change its PIN, when they ask about their card", null, BankOperation.ManageCards); } private static IServiceCollection AddTellerAction(this IServiceCollection self, string name, string description, string? detailDescription, BankOperation operation, bool opensFullMenu = false) diff --git a/src/OpenRP.Framework/Features/Banking/Helpers/BankCashErrors.cs b/src/OpenRP.Framework/Features/Banking/Helpers/BankCashErrors.cs new file mode 100644 index 0000000..f5e39a2 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Helpers/BankCashErrors.cs @@ -0,0 +1,22 @@ +using OpenRP.Framework.Features.Currencies.Enums; + +namespace OpenRP.Framework.Features.Banking.Helpers +{ + /// + /// What to tell a player when cash couldn't be taken from or put into their wallet, at a teller or an ATM. + /// + internal static class BankCashErrors + { + public static string Get(CurrencyChangeResult result, string currencyName, bool isTaking) + { + return result switch + { + CurrencyChangeResult.NoWallet => "You have no wallet to hold the cash.", + CurrencyChangeResult.NotEnoughFunds => $"You don't have that much cash in {currencyName}.", + CurrencyChangeResult.NotEnoughSpace => "The cash doesn't fit in your wallet.", + CurrencyChangeResult.AmountNotPayableInBills => $"That amount can't be paid in {currencyName} bills and coins.", + _ => isTaking ? "The cash couldn't be taken." : "The cash couldn't be handed over." + }; + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Helpers/BankLedger.cs b/src/OpenRP.Framework/Features/Banking/Helpers/BankLedger.cs new file mode 100644 index 0000000..c7f4e51 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Helpers/BankLedger.cs @@ -0,0 +1,70 @@ +using Microsoft.EntityFrameworkCore; +using OpenRP.Framework.Database; +using OpenRP.Framework.Database.Models; +using OpenRP.Framework.Features.Banking.Enums; +using System.Linq; + +namespace OpenRP.Framework.Features.Banking.Helpers +{ + /// + /// What one side of a money movement records in the account's history, besides the amount. + /// + internal record BankLedgerEntry(BankTransactionType Type, ulong? CharacterId, string? OtherOban = null, ulong? BankCardId = null, string? Description = null); + + /// + /// The only code that changes balances: one database update per side, run inside a transaction by the caller, and + /// a history line for it. Shared by the teller, ATMs, cards and payments. + /// + internal static class BankLedger + { + /// + /// Adds the money to an open account and logs it. False when the account is closed. + /// + public static bool Credit(BaseDataContext db, ulong accountId, decimal amount, BankLedgerEntry entry) + { + int updated = db.BankAccounts + .Where(row => row.Id == accountId && row.ClosedAt == null) + .ExecuteUpdate(setters => setters.SetProperty(row => row.Balance, row => row.Balance + amount)); + if (updated != 1) + { + return false; + } + AddTransaction(db, accountId, amount, entry); + return true; + } + + /// + /// Takes the money from an open account when the balance stays at least , + /// and logs it. False otherwise. + /// + public static bool Debit(BaseDataContext db, ulong accountId, decimal amount, decimal minimumBalanceAfter, BankLedgerEntry entry) + { + int updated = db.BankAccounts + .Where(row => row.Id == accountId && row.ClosedAt == null && row.Balance - amount >= minimumBalanceAfter) + .ExecuteUpdate(setters => setters.SetProperty(row => row.Balance, row => row.Balance - amount)); + if (updated != 1) + { + return false; + } + AddTransaction(db, accountId, -amount, entry); + return true; + } + + private static void AddTransaction(BaseDataContext db, ulong accountId, decimal amount, BankLedgerEntry entry) + { + decimal balanceAfter = db.BankAccounts.Where(row => row.Id == accountId).Select(row => row.Balance).First(); + db.BankTransactions.Add(new BankTransactionModel + { + BankAccountId = accountId, + Amount = amount, + BalanceAfter = balanceAfter, + Type = entry.Type, + OtherOban = entry.OtherOban, + CharacterId = entry.CharacterId, + BankCardId = entry.BankCardId, + Description = entry.Description + }); + db.SaveChanges(); + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Models/Configurations/BankingModelConfigurations.cs b/src/OpenRP.Framework/Features/Banking/Models/Configurations/BankingModelConfigurations.cs index 3b6d7f6..dea86aa 100644 --- a/src/OpenRP.Framework/Features/Banking/Models/Configurations/BankingModelConfigurations.cs +++ b/src/OpenRP.Framework/Features/Banking/Models/Configurations/BankingModelConfigurations.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using OpenRP.Framework.Database.Models; +using OpenRP.Framework.Features.Banking.Entities; namespace OpenRP.Framework.Features.Banking.Models.Configurations { @@ -80,6 +81,10 @@ public void Configure(EntityTypeBuilder builder) builder.Property(transaction => transaction.Amount).HasColumnType("decimal(18,2)"); builder.Property(transaction => transaction.BalanceAfter).HasColumnType("decimal(18,2)"); builder.Property(transaction => transaction.OtherOban).HasMaxLength(18); + builder.Property(transaction => transaction.Description).HasMaxLength(BankingRules.TransactionDescriptionMaxLength); + + // The ATM limit adds up a card's recent withdrawals. + builder.HasIndex(transaction => new { transaction.BankCardId, transaction.Type, transaction.CreatedOn }); builder.HasOne(transaction => transaction.BankAccount) .WithMany() @@ -91,6 +96,61 @@ public void Configure(EntityTypeBuilder builder) .WithMany() .HasForeignKey(transaction => transaction.CharacterId) .OnDelete(DeleteBehavior.SetNull); + + builder.HasOne(transaction => transaction.BankCard) + .WithMany() + .HasForeignKey(transaction => transaction.BankCardId) + .OnDelete(DeleteBehavior.SetNull); + } + } + + public class BankCardModelConfiguration : IEntityTypeConfiguration + { + public void Configure(EntityTypeBuilder builder) + { + builder.Property(card => card.Digits).HasMaxLength(BankingRules.CardDigitsLength).IsRequired(); + builder.Property(card => card.Name).HasMaxLength(BankingRules.CardNameMaxLength); + builder.Property(card => card.PinHash).HasMaxLength(60).IsRequired(); + builder.Property(card => card.WrongPinAttempts).HasDefaultValue(0); + + builder.HasIndex(card => new { card.BankAccountId, card.CharacterId }); + + builder.HasOne(card => card.BankAccount) + .WithMany() + .HasForeignKey(card => card.BankAccountId) + .OnDelete(DeleteBehavior.Cascade); + + builder.HasOne(card => card.Character) + .WithMany() + .HasForeignKey(card => card.CharacterId) + .OnDelete(DeleteBehavior.Cascade); + } + } + + public class BankPendingDepositModelConfiguration : IEntityTypeConfiguration + { + public void Configure(EntityTypeBuilder builder) + { + builder.Property(deposit => deposit.Amount).HasColumnType("decimal(18,2)"); + + // The crediting timer looks for deposits that are due. + builder.HasIndex(deposit => new { deposit.CreditedAt, deposit.CreditAt }); + + // Restrict, so an account with cash still on its way can't be deleted. + builder.HasOne(deposit => deposit.BankAccount) + .WithMany() + .HasForeignKey(deposit => deposit.BankAccountId) + .OnDelete(DeleteBehavior.Restrict); + + builder.HasOne(deposit => deposit.BankCard) + .WithMany() + .HasForeignKey(deposit => deposit.BankCardId) + .OnDelete(DeleteBehavior.SetNull); + + builder.HasOne(deposit => deposit.Character) + .WithMany() + .HasForeignKey(deposit => deposit.CharacterId) + .OnDelete(DeleteBehavior.SetNull); } } diff --git a/src/OpenRP.Framework/Features/Banking/Services/AtmMapObjectSpawnHandler.cs b/src/OpenRP.Framework/Features/Banking/Services/AtmMapObjectSpawnHandler.cs new file mode 100644 index 0000000..834f8cf --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Services/AtmMapObjectSpawnHandler.cs @@ -0,0 +1,31 @@ +using OpenRP.Framework.Features.Banking.Entities; +using OpenRP.Framework.Features.Maps.Components; +using OpenRP.Framework.Features.Maps.Entities; +using OpenRP.OpenMp.Streamer; + +namespace OpenRP.Framework.Features.Banking.Services +{ + /// + /// Makes every placed ATM map object (kmb_atm1) an ATM. The ATM lives on the object's streamer entity, so it goes + /// away when the object despawns, and it reads its position from the map object, so editor moves need nothing. + /// + public class AtmMapObjectSpawnHandler : IMapObjectSpawnHandler + { + private readonly IAtmService _atmService; + + public AtmMapObjectSpawnHandler(IAtmService atmService) + { + _atmService = atmService; + } + + public bool Handles(int modelId) + { + return modelId == BankingRules.AtmModelId; + } + + public void OnMapObjectSpawned(MapObject mapObject, DynamicObject dynamicObject) + { + _atmService.AddAtm(dynamicObject.Entity, mapObject.Entity); + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Services/AtmService.cs b/src/OpenRP.Framework/Features/Banking/Services/AtmService.cs new file mode 100644 index 0000000..b97d8a6 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Services/AtmService.cs @@ -0,0 +1,292 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using OpenRP.Framework.Database; +using OpenRP.Framework.Database.Models; +using OpenRP.Framework.Features.Banking.Components; +using OpenRP.Framework.Features.Banking.Entities; +using OpenRP.Framework.Features.Banking.Enums; +using OpenRP.Framework.Features.Banking.Helpers; +using OpenRP.Framework.Features.Characters.Components; +using OpenRP.Framework.Features.Currencies.Enums; +using OpenRP.Framework.Features.Currencies.Services; +using OpenRP.Framework.Features.Maps.Components; +using OpenRP.Framework.Features.Players.Extensions; +using SampSharp.Entities; +using SampSharp.Entities.SAMP; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace OpenRP.Framework.Features.Banking.Services +{ + public class AtmService : IAtmService + { + private const int DepositBatchSize = 500; + // Marks money put back after cash didn't fit, so it doesn't count against the withdrawal limit. + private const string WithdrawalReturnedDescription = "ATM withdrawal returned"; + private const string AtmDepositDescription = "ATM deposit"; + private const string AtmWithdrawalDescription = "ATM withdrawal"; + + private readonly IBankingDatabase _database; + private readonly IBankCardService _bankCardService; + private readonly ICurrencyService _currencyService; + private readonly IEntityManager _entityManager; + private readonly ILogger _logger; + + public AtmService(IBankingDatabase database, IBankCardService bankCardService, ICurrencyService currencyService, IEntityManager entityManager, + ILogger logger) + { + _database = database; + _bankCardService = bankCardService; + _currencyService = currencyService; + _entityManager = entityManager; + _logger = logger; + } + + public void AddAtm(EntityId objectEntity, EntityId mapObjectEntity) + { + _entityManager.AddComponent(objectEntity, new object[] { mapObjectEntity }); + } + + public Atm? GetNearbyAtm(Player player) + { + return _entityManager.GetComponents() + .Where(atm => IsPlayerAtAtm(player, atm)) + .OrderBy(atm => Vector3.Distance(atm.GetMapObject()!.GetPosition(), player.Position)) + .FirstOrDefault(); + } + + public bool IsPlayerAtAtm(Player player, Atm atm) + { + MapObject? mapObject = atm.IsComponentAlive ? atm.GetMapObject() : null; + return mapObject != null + && player.IsComponentAlive + && IsInSameSpace(mapObject.GetInterior(), player.Interior) + && IsInSameSpace(mapObject.GetVirtualWorld(), player.VirtualWorld) + && Vector3.Distance(mapObject.GetPosition(), player.Position) <= BankingRules.AtmRange; + } + + public decimal GetRemainingWithdrawal(ulong cardId) + { + decimal withdrawn = _database.Use(db => GetWithdrawnInPeriod(db, cardId)); + return Math.Max(0, BankingRules.AtmWithdrawalLimit - withdrawn); + } + + public async Task WithdrawAsync(Player player, ulong cardId, decimal amount) + { + (BankCardDetails? card, string? error) = GetUsableCard(player, cardId, amount); + if (error != null) + return error; + + Character character = player.GetPlayerCurrentlyPlayingAsCharacter(); + error = TryDebitWithinLimit(card!, amount, character.GetId()); + if (error != null) + return error; + + CurrencyChangeResult giveResult = await _currencyService.GiveCharacterCurrency(character, card!.Account.CurrencyId, amount); + if (giveResult == CurrencyChangeResult.Success) + return null; + + PutWithdrawalBack(card, amount, character.GetId()); + return GetCashError(giveResult, card.Account.CurrencyId, isTaking: false) + " The money stays in your account."; + } + + public async Task DepositAsync(Player player, ulong cardId, Atm atm, decimal amount) + { + (BankCardDetails? card, string? error) = GetUsableCard(player, cardId, amount); + if (error != null) + return error; + + Character character = player.GetPlayerCurrentlyPlayingAsCharacter(); + CurrencyChangeResult takeResult = await _currencyService.TakeCharacterCurrency(character, card!.Account.CurrencyId, amount); + if (takeResult != CurrencyChangeResult.Success) + return GetCashError(takeResult, card.Account.CurrencyId, isTaking: true); + + if (TryAddPendingDeposit(card, amount, character.GetId(), atm)) + return null; + + // The deposit couldn't be stored: the cash goes back to the player. + await _currencyService.GiveCharacterCurrency(character, card.Account.CurrencyId, amount); + return "The ATM couldn't take the deposit. Your cash was handed back."; + } + + public List GetPendingDeposits(ulong accountId) + { + return _database.Use(db => db.BankPendingDeposits.AsNoTracking() + .Where(deposit => deposit.BankAccountId == accountId && deposit.CreditedAt == null) + .OrderBy(deposit => deposit.CreditAt) + .ToList()); + } + + public void CreditDueDeposits() + { + DateTime now = DateTime.UtcNow; + List dueDeposits = _database.Use(db => db.BankPendingDeposits.AsNoTracking() + .Where(deposit => deposit.CreditedAt == null && deposit.CreditAt <= now) + .OrderBy(deposit => deposit.CreditAt) + .Take(DepositBatchSize) + .ToList()); + + foreach (BankPendingDepositModel deposit in dueDeposits) + { + try + { + CreditDeposit(deposit); + } + catch (Exception exception) + { + _logger.LogError(exception, "Crediting ATM deposit {DepositId} failed.", deposit.Id); + } + } + } + + /// + /// -1 in a map object means every interior or virtual world. + /// + private static bool IsInSameSpace(int objectSpace, int playerSpace) + { + return objectSpace == -1 || objectSpace == playerSpace; + } + + private (BankCardDetails? Card, string? Error) GetUsableCard(Player player, ulong cardId, decimal amount) + { + if (!BankAmounts.IsValid(amount)) + return (null, $"Enter an amount above 0, with at most 2 decimals, up to {BankAmounts.Maximum:N0}."); + + BankCardDetails? card = _bankCardService.GetCardDetails(cardId); + if (card == null) + return (null, "The ATM doesn't recognise this card."); + string? error = _bankCardService.GetUseError(player, card); + return error == null ? (card, null) : (null, error); + } + + /// + /// The limit check and the debit in one transaction, after locking the card row, so two withdrawals at once + /// (even on two servers) can't both pass the limit. + /// + private string? TryDebitWithinLimit(BankCardDetails card, decimal amount, ulong characterId) + { + string? error = null; + _database.UseInTransaction(db => + { + error = null; + LockCard(db, card.Card.Id); + if (GetWithdrawnInPeriod(db, card.Card.Id) + amount > BankingRules.AtmWithdrawalLimit) + { + error = $"That's over this card's ATM limit of {FormatMoney(card.Account.CurrencyId, BankingRules.AtmWithdrawalLimit)} in {BankingRules.AtmWithdrawalLimitPeriod.TotalHours:0} hours."; + return false; + } + BankLedgerEntry entry = new BankLedgerEntry(BankTransactionType.Withdrawal, characterId, BankCardId: card.Card.Id, Description: AtmWithdrawalDescription); + if (!BankLedger.Debit(db, card.Account.Id, amount, minimumBalanceAfter: 0, entry)) + { + error = "There isn't enough money in the account."; + return false; + } + return true; + }); + return error; + } + + /// + /// A no-op update still takes the row lock, so a second withdrawal with this card waits until the first commits. + /// It must come before the limit's read: MySQL takes a transaction's snapshot at its first plain read. + /// + private static void LockCard(BaseDataContext db, ulong cardId) + { + db.BankCards.Where(row => row.Id == cardId) + .ExecuteUpdate(setters => setters.SetProperty(row => row.WrongPinAttempts, row => row.WrongPinAttempts)); + } + + /// + /// Withdrawals minus money put back after cash didn't fit, in the limit period. + /// + private static decimal GetWithdrawnInPeriod(BaseDataContext db, ulong cardId) + { + DateTime since = DateTime.UtcNow - BankingRules.AtmWithdrawalLimitPeriod; + decimal net = db.BankTransactions + .Where(transaction => transaction.BankCardId == cardId && transaction.CreatedOn >= since + && (transaction.Type == BankTransactionType.Withdrawal + || (transaction.Type == BankTransactionType.Deposit && transaction.Description == WithdrawalReturnedDescription))) + .Sum(transaction => (decimal?)transaction.Amount) ?? 0; + return -net; + } + + private void PutWithdrawalBack(BankCardDetails card, decimal amount, ulong characterId) + { + try + { + BankLedgerEntry entry = new BankLedgerEntry(BankTransactionType.Deposit, characterId, BankCardId: card.Card.Id, Description: WithdrawalReturnedDescription); + if (_database.UseInTransaction(db => BankLedger.Credit(db, card.Account.Id, amount, entry))) + return; + } + catch (Exception exception) + { + _logger.LogError(exception, "Putting back an ATM withdrawal of {Amount} on bank account {Oban} failed.", amount, card.Account.Oban); + } + _logger.LogError("An ATM withdrawal of {Amount} from bank account {Oban} couldn't be handed out or put back. Refund it by hand.", amount, card.Account.Oban); + } + + private bool TryAddPendingDeposit(BankCardDetails card, decimal amount, ulong characterId, Atm atm) + { + MapObject? mapObject = atm.IsComponentAlive ? atm.GetMapObject() : null; + Vector3 position = mapObject?.GetPosition() ?? Vector3.Zero; + try + { + _database.Use(db => + { + db.BankPendingDeposits.Add(new BankPendingDepositModel + { + BankAccountId = card.Account.Id, + BankCardId = card.Card.Id, + CharacterId = characterId, + Amount = amount, + CreditAt = DateTime.UtcNow + BankingRules.AtmDepositDelay, + AtmX = position.X, + AtmY = position.Y, + AtmZ = position.Z, + AtmInterior = mapObject?.GetInterior() ?? 0, + AtmVirtualWorld = mapObject?.GetVirtualWorld() ?? 0 + }); + db.SaveChanges(); + }); + return true; + } + catch (Exception exception) + { + _logger.LogError(exception, "Storing an ATM deposit of {Amount} for bank account {Oban} failed.", amount, card.Account.Oban); + return false; + } + } + + /// + /// Claims the deposit by marking it credited in the same transaction as the credit, so two servers never credit + /// it twice. When the account can't take it, nothing changes and it's tried again later. + /// + private void CreditDeposit(BankPendingDepositModel deposit) + { + DateTime now = DateTime.UtcNow; + BankLedgerEntry entry = new BankLedgerEntry(BankTransactionType.Deposit, deposit.CharacterId, BankCardId: deposit.BankCardId, Description: AtmDepositDescription); + bool credited = _database.UseInTransaction(db => + db.BankPendingDeposits + .Where(row => row.Id == deposit.Id && row.CreditedAt == null) + .ExecuteUpdate(setters => setters.SetProperty(row => row.CreditedAt, now)) == 1 + && BankLedger.Credit(db, deposit.BankAccountId, deposit.Amount, entry)); + if (!credited) + { + _logger.LogWarning("ATM deposit {DepositId} couldn't be credited to bank account {AccountId}; it stays pending.", deposit.Id, deposit.BankAccountId); + } + } + + private string GetCashError(CurrencyChangeResult result, ulong currencyId, bool isTaking) + { + string currencyName = _currencyService.GetCurrencies().FirstOrDefault(currency => currency.Id == currencyId)?.Name ?? "this currency"; + return BankCashErrors.Get(result, currencyName, isTaking); + } + + private string FormatMoney(ulong currencyId, decimal amount) + { + return _currencyService.GetCurrencyFormat(currencyId, amount); + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Services/BankAccountService.cs b/src/OpenRP.Framework/Features/Banking/Services/BankAccountService.cs index e54218b..2c29a60 100644 --- a/src/OpenRP.Framework/Features/Banking/Services/BankAccountService.cs +++ b/src/OpenRP.Framework/Features/Banking/Services/BankAccountService.cs @@ -1,5 +1,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; +using OpenRP.Framework.Database; using OpenRP.Framework.Database.Models; using OpenRP.Framework.Features.Banking.Entities; using OpenRP.Framework.Features.Banking.Enums; @@ -138,13 +139,22 @@ public List GetFactionsToBankFor(Character character) if (GetAccessLevel(character, account) < BankAccessLevel.Manage) return "Only the owner can close this account."; + if (HasPendingDeposits(account.Id)) + return "An ATM deposit is still on its way to this account. Close it once that has arrived."; + // In one statement, so money that arrives in the meantime can't be lost by closing. int closed = _database.Use(db => db.BankAccounts - .Where(row => row.Id == account.Id && row.ClosedAt == null && row.Balance == 0) + .Where(row => row.Id == account.Id && row.ClosedAt == null && row.Balance == 0 + && !db.BankPendingDeposits.Any(deposit => deposit.BankAccountId == row.Id && deposit.CreditedAt == null)) .ExecuteUpdate(setters => setters.SetProperty(row => row.ClosedAt, DateTime.UtcNow))); return closed == 1 ? null : "An account can only be closed with a balance of exactly 0. Withdraw or transfer the rest first."; } + private bool HasPendingDeposits(ulong accountId) + { + return _database.Use(db => db.BankPendingDeposits.Any(deposit => deposit.BankAccountId == accountId && deposit.CreditedAt == null)); + } + public List GetAccessList(BankAccountModel account) { return _database.Use(db => db.BankAccountAccess.AsNoTracking() @@ -175,10 +185,28 @@ public List GetAccessList(BankAccountModel account) if (GetAccessLevel(manager, account) < BankAccessLevel.Manage) return "Only the owner can change who has access."; - _database.Use(db => db.BankAccountAccess.Where(access => access.Id == accessId && access.BankAccountId == account.Id).ExecuteDelete()); + _database.Use(db => + { + ulong? characterId = db.BankAccountAccess.Where(access => access.Id == accessId && access.BankAccountId == account.Id).Select(access => (ulong?)access.CharacterId).FirstOrDefault(); + db.BankAccountAccess.Where(access => access.Id == accessId && access.BankAccountId == account.Id).ExecuteDelete(); + BlockCardsOf(db, account.Id, characterId); + }); return null; } + /// + /// Someone who lost access can't keep using the account with a card they were given before. + /// + private static void BlockCardsOf(BaseDataContext db, ulong accountId, ulong? characterId) + { + if (characterId == null) + return; + DateTime now = DateTime.UtcNow; + db.BankCards + .Where(card => card.BankAccountId == accountId && card.CharacterId == characterId && card.BlockedAt == null && card.CancelledAt == null) + .ExecuteUpdate(setters => setters.SetProperty(card => card.BlockedAt, now)); + } + public List GetHistory(BankAccountModel account) { return _database.Use(db => db.BankTransactions.AsNoTracking() diff --git a/src/OpenRP.Framework/Features/Banking/Services/BankCardNameProvider.cs b/src/OpenRP.Framework/Features/Banking/Services/BankCardNameProvider.cs new file mode 100644 index 0000000..a478409 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Services/BankCardNameProvider.cs @@ -0,0 +1,44 @@ +using OpenRP.Framework.Features.Banking.Entities; +using OpenRP.Framework.Features.Banking.Enums; +using OpenRP.Framework.Features.Inventories.Components; +using OpenRP.Framework.Features.Inventories.Entities; + +namespace OpenRP.Framework.Features.Banking.Services +{ + /// + /// Shows a card in the inventory with its account and name, read fresh, so renaming either shows at once. + /// + public class BankCardNameProvider : IInventoryItemNameProvider + { + private readonly IBankCardService _bankCardService; + + public BankCardNameProvider(IBankCardService bankCardService) + { + _bankCardService = bankCardService; + } + + public bool Handles(InventoryItem inventoryItem) + { + return inventoryItem.GetBankCardId() != null; + } + + public string GetName(InventoryItem inventoryItem) + { + return GetCard(inventoryItem)?.GetLabel() ?? inventoryItem.GetName(); + } + + public string? GetExtraInformation(InventoryItem inventoryItem) + { + BankCardDetails? card = GetCard(inventoryItem); + if (card == null) + return "Unknown card"; + return card.GetStatus() == BankCardStatus.Active ? null : card.GetStatusText(); + } + + private BankCardDetails? GetCard(InventoryItem inventoryItem) + { + ulong? cardId = inventoryItem.GetBankCardId(); + return cardId == null ? null : _bankCardService.GetCardDetails(cardId.Value); + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Services/BankCardService.cs b/src/OpenRP.Framework/Features/Banking/Services/BankCardService.cs new file mode 100644 index 0000000..c3e4c95 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Services/BankCardService.cs @@ -0,0 +1,328 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using OpenRP.Framework.Database.Models; +using OpenRP.Framework.Features.Banking.Entities; +using OpenRP.Framework.Features.Banking.Enums; +using OpenRP.Framework.Features.Characters.Components; +using OpenRP.Framework.Features.Inventories.Components; +using OpenRP.Framework.Features.Inventories.Helpers; +using OpenRP.Framework.Features.Inventories.Services; +using OpenRP.Framework.Features.Items.Components; +using OpenRP.Framework.Features.Items.Entities; +using OpenRP.Framework.Features.Players.Extensions; +using SampSharp.Entities; +using SampSharp.Entities.SAMP; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace OpenRP.Framework.Features.Banking.Services +{ + public class BankCardService : IBankCardService + { + private readonly IBankingDatabase _database; + private readonly IBankAccountService _bankAccountService; + private readonly IEntityManager _entityManager; + private readonly IInventoryItemManager _inventoryItemManager; + private readonly ILogger _logger; + + public BankCardService(IBankingDatabase database, IBankAccountService bankAccountService, IEntityManager entityManager, IInventoryItemManager inventoryItemManager, + ILogger logger) + { + _database = database; + _bankAccountService = bankAccountService; + _entityManager = entityManager; + _inventoryItemManager = inventoryItemManager; + _logger = logger; + } + + public BankCardDetails? GetCardDetails(ulong cardId) + { + BankCardModel? card = _database.Use(db => db.BankCards.AsNoTracking() + .Include(row => row.BankAccount).ThenInclude(account => account!.Bank) + .FirstOrDefault(row => row.Id == cardId)); + return ToDetails(card); + } + + public BankCardDetails? GetCurrentCard(ulong accountId, ulong characterId) + { + BankCardModel? card = _database.Use(db => db.BankCards.AsNoTracking() + .Include(row => row.BankAccount).ThenInclude(account => account!.Bank) + .Where(row => row.BankAccountId == accountId && row.CharacterId == characterId && row.CancelledAt == null) + .OrderByDescending(row => row.Id) + .FirstOrDefault()); + return ToDetails(card); + } + + public List GetCarriedCardItems(Character character) + { + Inventory? inventory = character.GetInventory(); + return inventory == null ? new List() : GetCardItemsIn(inventory); + } + + public string? GetUseError(Player player, BankCardDetails card) + { + if (!player.IsComponentAlive || !player.IsPlayerPlayingAsCharacter()) + return "You need to be playing a character."; + + BankCardStatus status = card.GetStatus(); + if (status != BankCardStatus.Active) + return GetStatusError(status); + + Character character = player.GetPlayerCurrentlyPlayingAsCharacter(); + bool isOwner = character.GetId() == card.Card.CharacterId; + if (isOwner && _bankAccountService.GetAccessLevel(character, card.Account) < BankAccessLevel.Full) + return "You aren't allowed to use this card's account anymore."; + return null; + } + + public async Task IssueCardAsync(Player player, ulong accountId, string? name, string pin) + { + string? error = GetIssueError(player, accountId, name, pin); + if (error != null) + return error; + + string pinHash = await HashPinAsync(pin); + // The player may have left, or filled their inventory, while the PIN was hashed. + error = GetIssueError(player, accountId, name, pin); + if (error != null) + return error; + + Character character = player.GetPlayerCurrentlyPlayingAsCharacter(); + BankCardModel? card = TryInsertReplacingCard(accountId, character.GetId(), GetCleanName(name), pinHash); + if (card == null) + return "The card couldn't be made. Try again."; + + return GiveCardItem(character, card) ? null : "The card doesn't fit in your inventory."; + } + + public async Task CheckPinAsync(ulong cardId, string pin) + { + BankCardModel? card = _database.Use(db => db.BankCards.AsNoTracking().FirstOrDefault(row => row.Id == cardId)); + if (card == null || card.BlockedAt != null || card.CancelledAt != null) + return PinCheckResult.Blocked; + + bool isCorrect = GetPinError(pin) == null && await VerifyPinAsync(pin, card.PinHash); + if (isCorrect) + { + ResetWrongPinAttempts(cardId); + return PinCheckResult.Correct; + } + return CountWrongPin(cardId) ? PinCheckResult.Blocked : PinCheckResult.Wrong; + } + + public async Task ChangePinAsync(ulong cardId, string pin) + { + string? error = GetPinError(pin); + if (error != null) + return error; + + string pinHash = await HashPinAsync(pin); + int updated = _database.Use(db => db.BankCards + .Where(row => row.Id == cardId && row.CancelledAt == null) + .ExecuteUpdate(setters => setters.SetProperty(row => row.PinHash, pinHash).SetProperty(row => row.WrongPinAttempts, 0))); + return updated == 1 ? null : "That card was replaced and can't be changed anymore."; + } + + public string? BlockCard(ulong cardId) + { + DateTime now = DateTime.UtcNow; + int updated = _database.Use(db => db.BankCards + .Where(row => row.Id == cardId && row.CancelledAt == null) + .ExecuteUpdate(setters => setters.SetProperty(row => row.BlockedAt, row => row.BlockedAt ?? now))); + return updated == 1 ? null : "That card was replaced and doesn't work anymore anyway."; + } + + public string? UnblockCard(ulong cardId) + { + int updated = _database.Use(db => db.BankCards + .Where(row => row.Id == cardId && row.CancelledAt == null) + .ExecuteUpdate(setters => setters.SetProperty(row => row.BlockedAt, (DateTime?)null).SetProperty(row => row.WrongPinAttempts, 0))); + return updated == 1 ? null : "That card was replaced and can't be unblocked. Order a new one."; + } + + public string? RenameCard(ulong cardId, string name) + { + string? error = GetCardNameError(name); + if (error != null) + return error; + + string? cleanName = GetCleanName(name); + int updated = _database.Use(db => db.BankCards + .Where(row => row.Id == cardId) + .ExecuteUpdate(setters => setters.SetProperty(row => row.Name, cleanName))); + return updated == 1 ? null : "That card doesn't exist anymore."; + } + + public string? GetPinError(string pin) + { + return pin.Length == BankingRules.PinLength && pin.All(char.IsAsciiDigit) ? null : $"A PIN is exactly {BankingRules.PinLength} digits."; + } + + public string? GetCardNameError(string name) + { + string trimmed = name.Trim(); + if (trimmed.Length > BankingRules.CardNameMaxLength) + return $"A card name is at most {BankingRules.CardNameMaxLength} characters."; + // Braces would be read as colour codes and tabs or line breaks would break dialog columns. + if (trimmed.Any(character => character == '{' || character == '}' || char.IsControl(character))) + return "A card name can't contain { }, tabs or line breaks."; + return null; + } + + private static BankCardDetails? ToDetails(BankCardModel? card) + { + BankAccountModel? account = card?.BankAccount; + BankModel? bank = account?.Bank; + return card == null || account == null || bank == null ? null : new BankCardDetails(card, account, bank); + } + + private static string GetStatusError(BankCardStatus status) + { + return status switch + { + BankCardStatus.Cancelled => "This card was replaced and doesn't work anymore.", + BankCardStatus.Blocked => "This card is blocked. The bank can unblock it.", + _ => "This card's account is closed." + }; + } + + private List GetCardItemsIn(Inventory inventory) + { + List cardItems = inventory.GetInventoryItems().Where(inventoryItem => inventoryItem.GetBankCardId() != null).ToList(); + foreach (InventoryItem wallet in inventory.GetWallets()) + { + Inventory? walletInventory = wallet.GetItemInventory(); + if (walletInventory != null) + { + cardItems.AddRange(GetCardItemsIn(walletInventory)); + } + } + return cardItems; + } + + private string? GetIssueError(Player player, ulong accountId, string? name, string pin) + { + if (!player.IsComponentAlive || !player.IsPlayerPlayingAsCharacter()) + return "You need to be playing a character."; + string? inputError = GetPinError(pin) ?? (name == null ? null : GetCardNameError(name)); + if (inputError != null) + return inputError; + + Character character = player.GetPlayerCurrentlyPlayingAsCharacter(); + BankAccountModel? account = _bankAccountService.GetAccount(accountId); + if (account == null || _bankAccountService.GetAccessLevel(character, account) < BankAccessLevel.Full) + return "You aren't allowed to use that account."; + + Inventory? inventory = character.GetInventory(); + Item? cardItem = GetCardItem(); + if (inventory == null || cardItem == null) + return "The bank has no cards to hand out right now."; + return inventory.DoesItemFit(cardItem, 1) ? null : "The card doesn't fit in your inventory."; + } + + /// + /// Cancels the character's earlier card for the account and adds the new one, in one transaction, so there's + /// only ever one working card per account per character. + /// + private BankCardModel? TryInsertReplacingCard(ulong accountId, ulong characterId, string? name, string pinHash) + { + BankCardModel card = new BankCardModel + { + BankAccountId = accountId, + CharacterId = characterId, + Digits = Random.Shared.Next(0, 10000).ToString("D4"), + Name = name, + PinHash = pinHash + }; + try + { + DateTime now = DateTime.UtcNow; + bool inserted = _database.UseInTransaction(db => + { + db.BankCards + .Where(row => row.BankAccountId == accountId && row.CharacterId == characterId && row.CancelledAt == null) + .ExecuteUpdate(setters => setters.SetProperty(row => row.CancelledAt, now)); + db.BankCards.Add(card); + db.SaveChanges(); + return true; + }); + return inserted ? card : null; + } + catch (Exception exception) + { + _logger.LogError(exception, "Making a card for bank account {AccountId} failed.", accountId); + return null; + } + } + + /// + /// Saves the item at once, so a crash right after can't leave a card without its item. + /// + private bool GiveCardItem(Character character, BankCardModel card) + { + Inventory? inventory = character.GetInventory(); + Item? cardItem = GetCardItem(); + ItemAdditionalData additionalData = ItemAdditionalData.Parse(string.Empty); + additionalData.SetString(InventoryItem.BankCardIdKey, card.Id.ToString()); + if (inventory == null || cardItem == null || !inventory.AddItem(cardItem, 1, additionalData)) + { + BlockCard(card.Id); + return false; + } + _inventoryItemManager.SaveNow(); + return true; + } + + private Item? GetCardItem() + { + return _entityManager.GetComponent(ItemEntities.GetItemId(BankingRules.BankCardItemId)); + } + + private static string? GetCleanName(string? name) + { + string? trimmed = name?.Trim(); + return string.IsNullOrEmpty(trimmed) ? null : trimmed; + } + + private void ResetWrongPinAttempts(ulong cardId) + { + _database.Use(db => db.BankCards + .Where(row => row.Id == cardId && row.WrongPinAttempts > 0) + .ExecuteUpdate(setters => setters.SetProperty(row => row.WrongPinAttempts, 0))); + } + + /// + /// Adds a wrong PIN in one statement and blocks the card when that reaches the limit. True when it's blocked. + /// + private bool CountWrongPin(ulong cardId) + { + DateTime now = DateTime.UtcNow; + return _database.Use(db => + { + db.BankCards + .Where(row => row.Id == cardId) + .ExecuteUpdate(setters => setters.SetProperty(row => row.WrongPinAttempts, row => row.WrongPinAttempts + 1)); + db.BankCards + .Where(row => row.Id == cardId && row.BlockedAt == null && row.WrongPinAttempts >= BankingRules.MaxWrongPinAttempts) + .ExecuteUpdate(setters => setters.SetProperty(row => row.BlockedAt, now)); + return db.BankCards.Where(row => row.Id == cardId).Select(row => row.BlockedAt).First() != null; + }); + } + + /// + /// BCrypt takes a noticeable moment, so it runs on a worker thread; the code after the await is back on the main + /// thread. + /// + private static Task HashPinAsync(string pin) + { + return Task.Run(() => BCrypt.Net.BCrypt.HashPassword(pin, BankingRules.PinHashWorkFactor)); + } + + private static Task VerifyPinAsync(string pin, string pinHash) + { + return Task.Run(() => BCrypt.Net.BCrypt.Verify(pin, pinHash)); + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Services/BankTransactionService.Payments.cs b/src/OpenRP.Framework/Features/Banking/Services/BankTransactionService.Payments.cs new file mode 100644 index 0000000..4d13e3f --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Services/BankTransactionService.Payments.cs @@ -0,0 +1,106 @@ +using Microsoft.Extensions.Logging; +using OpenRP.Framework.Database.Models; +using OpenRP.Framework.Features.Banking.Entities; +using OpenRP.Framework.Features.Banking.Enums; +using OpenRP.Framework.Features.Banking.Helpers; +using OpenRP.Framework.Features.Characters.Components; +using OpenRP.Framework.Features.Currencies.Enums; +using OpenRP.Framework.Features.Players.Extensions; +using SampSharp.Entities.SAMP; +using System; +using System.Threading.Tasks; + +namespace OpenRP.Framework.Features.Banking.Services +{ + public partial class BankTransactionService + { + public string? PayWithCard(Player player, ulong cardId, ulong receiverAccountId, decimal amount, string description) + { + BankCardDetails? card = _bankCardService.GetCardDetails(cardId); + BankAccountModel? receiver = _bankAccountService.GetAccount(receiverAccountId); + string? error = GetCardPaymentError(player, card, receiver, amount); + if (error != null) + return error; + + ulong characterId = player.GetPlayerCurrentlyPlayingAsCharacter().GetId(); + string shortDescription = Shorten(description); + bool paid = _database.UseInTransaction(db => + BankLedger.Debit(db, card!.Account.Id, amount, minimumBalanceAfter: 0, + new BankLedgerEntry(BankTransactionType.CardPayment, characterId, receiver!.Oban, card.Card.Id, shortDescription)) + && BankLedger.Credit(db, receiver.Id, amount, + new BankLedgerEntry(BankTransactionType.PaymentReceived, characterId, card.Account.Oban, card.Card.Id, shortDescription))); + return paid ? null : "Card declined: there isn't enough money in the account."; + } + + public async Task PayInCashAsync(Player player, ulong receiverAccountId, ulong currencyId, decimal amount, string description) + { + BankAccountModel? receiver = _bankAccountService.GetAccount(receiverAccountId); + string? error = GetCashPaymentError(player, receiver, currencyId, amount); + if (error != null) + return error; + + Character character = player.GetPlayerCurrentlyPlayingAsCharacter(); + CurrencyChangeResult takeResult = await _currencyService.TakeCharacterCurrency(character, currencyId, amount); + if (takeResult != CurrencyChangeResult.Success) + return GetCashError(takeResult, currencyId, isTaking: true); + + if (TryCreditCashPayment(receiver!, amount, character.GetId(), Shorten(description))) + return null; + + await _currencyService.GiveCharacterCurrency(character, currencyId, amount); + return "The payment couldn't be taken. Your cash was handed back."; + } + + private string? GetCardPaymentError(Player player, BankCardDetails? card, BankAccountModel? receiver, decimal amount) + { + if (card == null) + return "This card isn't recognised."; + string? error = _bankCardService.GetUseError(player, card) ?? GetPaymentAmountError(amount) ?? GetReceiverError(receiver, card.Account.CurrencyId); + if (error != null) + return error; + return receiver!.Id == card.Account.Id ? "You can't pay into the card's own account." : null; + } + + private string? GetCashPaymentError(Player player, BankAccountModel? receiver, ulong currencyId, decimal amount) + { + if (!player.IsComponentAlive || !player.IsPlayerPlayingAsCharacter()) + return "You need to be playing a character."; + return GetPaymentAmountError(amount) ?? GetReceiverError(receiver, currencyId); + } + + private static string? GetPaymentAmountError(decimal amount) + { + return BankAmounts.IsValid(amount) ? null : "That isn't a valid amount to pay."; + } + + private static string? GetReceiverError(BankAccountModel? receiver, ulong currencyId) + { + if (receiver == null || receiver.ClosedAt != null) + return "The account to pay into is closed."; + return receiver.CurrencyId == currencyId ? null : "This payment is in another currency."; + } + + /// + /// False instead of throwing when the database fails, so the caller can always hand the cash back. + /// + private bool TryCreditCashPayment(BankAccountModel receiver, decimal amount, ulong characterId, string description) + { + try + { + return _database.UseInTransaction(db => BankLedger.Credit(db, receiver.Id, amount, + new BankLedgerEntry(BankTransactionType.PaymentReceived, characterId, Description: description))); + } + catch (Exception exception) + { + _logger.LogError(exception, "Paying {Amount} in cash into bank account {Oban} failed.", amount, receiver.Oban); + return false; + } + } + + private static string Shorten(string description) + { + string trimmed = description.Trim(); + return trimmed.Length <= BankingRules.TransactionDescriptionMaxLength ? trimmed : trimmed[..BankingRules.TransactionDescriptionMaxLength]; + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Services/BankTransactionService.cs b/src/OpenRP.Framework/Features/Banking/Services/BankTransactionService.cs index 3331b2d..46275aa 100644 --- a/src/OpenRP.Framework/Features/Banking/Services/BankTransactionService.cs +++ b/src/OpenRP.Framework/Features/Banking/Services/BankTransactionService.cs @@ -18,7 +18,10 @@ namespace OpenRP.Framework.Features.Banking.Services { - public class BankTransactionService : IBankTransactionService + /// + /// Teller deposits, withdrawals, transfers and fees here; payments in BankTransactionService.Payments.cs. + /// + public partial class BankTransactionService : IBankTransactionService { private const int FeeBatchSize = 500; @@ -26,15 +29,17 @@ public class BankTransactionService : IBankTransactionService private readonly IBankAccountService _bankAccountService; private readonly IBankService _bankService; private readonly ICurrencyService _currencyService; + private readonly IBankCardService _bankCardService; private readonly ILogger _logger; public BankTransactionService(IBankingDatabase database, IBankAccountService bankAccountService, IBankService bankService, ICurrencyService currencyService, - ILogger logger) + IBankCardService bankCardService, ILogger logger) { _database = database; _bankAccountService = bankAccountService; _bankService = bankService; _currencyService = currencyService; + _bankCardService = bankCardService; _logger = logger; } @@ -159,14 +164,7 @@ public void ChargeDueFees() private string GetCashError(CurrencyChangeResult result, ulong currencyId, bool isTaking) { string currencyName = _currencyService.GetCurrencies().FirstOrDefault(currency => currency.Id == currencyId)?.Name ?? "this currency"; - return result switch - { - CurrencyChangeResult.NoWallet => "You have no wallet to hold the cash.", - CurrencyChangeResult.NotEnoughFunds => $"You don't have that much cash in {currencyName}.", - CurrencyChangeResult.NotEnoughSpace => "The cash doesn't fit in your wallet.", - CurrencyChangeResult.AmountNotPayableInBills => $"That amount can't be paid in {currencyName} bills and coins.", - _ => isTaking ? "The cash couldn't be taken." : "The cash couldn't be handed over." - }; + return BankCashErrors.Get(result, currencyName, isTaking); } /// @@ -191,7 +189,7 @@ private bool TryCreditDeposit(BankAccountModel account, decimal amount, ulong ch /// private bool TryCredit(ulong accountId, decimal amount, BankTransactionType type, ulong? characterId, string? otherOban) { - return _database.UseInTransaction(db => Credit(db, accountId, amount, type, characterId, otherOban)); + return _database.UseInTransaction(db => BankLedger.Credit(db, accountId, amount, new BankLedgerEntry(type, characterId, otherOban))); } /// @@ -199,7 +197,7 @@ private bool TryCredit(ulong accountId, decimal amount, BankTransactionType type /// private bool TryDebit(ulong accountId, decimal amount, BankTransactionType type, ulong? characterId, string? otherOban) { - return _database.UseInTransaction(db => Debit(db, accountId, amount, minimumBalanceAfter: 0, type, characterId, otherOban)); + return _database.UseInTransaction(db => BankLedger.Debit(db, accountId, amount, minimumBalanceAfter: 0, new BankLedgerEntry(type, characterId, otherOban))); } /// @@ -208,8 +206,8 @@ private bool TryDebit(ulong accountId, decimal amount, BankTransactionType type, private bool TryMove(BankAccountModel fromAccount, BankAccountModel toAccount, decimal amount, ulong characterId) { return _database.UseInTransaction(db => - Debit(db, fromAccount.Id, amount, minimumBalanceAfter: 0, BankTransactionType.TransferOut, characterId, toAccount.Oban) - && Credit(db, toAccount.Id, amount, BankTransactionType.TransferIn, characterId, fromAccount.Oban)); + BankLedger.Debit(db, fromAccount.Id, amount, minimumBalanceAfter: 0, new BankLedgerEntry(BankTransactionType.TransferOut, characterId, toAccount.Oban)) + && BankLedger.Credit(db, toAccount.Id, amount, new BankLedgerEntry(BankTransactionType.TransferIn, characterId, fromAccount.Oban))); } /// @@ -232,9 +230,9 @@ private void ChargeFee(BankAccountModel account) decimal balance = db.BankAccounts.Where(row => row.Id == account.Id).Select(row => row.Balance).First(); decimal charge = Math.Min(fee, balance - BankingRules.LowestBalance); if (charge > 0 && houseAccount != null - && Debit(db, account.Id, charge, BankingRules.LowestBalance, BankTransactionType.Fee, null, houseAccount.Oban)) + && BankLedger.Debit(db, account.Id, charge, BankingRules.LowestBalance, new BankLedgerEntry(BankTransactionType.Fee, null, houseAccount.Oban))) { - Credit(db, houseAccount.Id, charge, BankTransactionType.FeeIncome, null, account.Oban); + BankLedger.Credit(db, houseAccount.Id, charge, new BankLedgerEntry(BankTransactionType.FeeIncome, null, account.Oban)); } return true; }); @@ -255,46 +253,5 @@ private static bool ClaimFee(BaseDataContext db, BankAccountModel account) .Where(row => row.Id == account.Id && row.NextFeeAt == dueAt) .ExecuteUpdate(setters => setters.SetProperty(row => row.NextFeeAt, dueAt + BankingRules.FeeInterval)) == 1; } - - private static bool Credit(BaseDataContext db, ulong accountId, decimal amount, BankTransactionType type, ulong? characterId, string? otherOban) - { - int updated = db.BankAccounts - .Where(row => row.Id == accountId && row.ClosedAt == null) - .ExecuteUpdate(setters => setters.SetProperty(row => row.Balance, row => row.Balance + amount)); - if (updated != 1) - { - return false; - } - AddTransaction(db, accountId, amount, type, characterId, otherOban); - return true; - } - - private static bool Debit(BaseDataContext db, ulong accountId, decimal amount, decimal minimumBalanceAfter, BankTransactionType type, ulong? characterId, string? otherOban) - { - int updated = db.BankAccounts - .Where(row => row.Id == accountId && row.ClosedAt == null && row.Balance - amount >= minimumBalanceAfter) - .ExecuteUpdate(setters => setters.SetProperty(row => row.Balance, row => row.Balance - amount)); - if (updated != 1) - { - return false; - } - AddTransaction(db, accountId, -amount, type, characterId, otherOban); - return true; - } - - private static void AddTransaction(BaseDataContext db, ulong accountId, decimal amount, BankTransactionType type, ulong? characterId, string? otherOban) - { - decimal balanceAfter = db.BankAccounts.Where(row => row.Id == accountId).Select(row => row.Balance).First(); - db.BankTransactions.Add(new BankTransactionModel - { - BankAccountId = accountId, - Amount = amount, - BalanceAfter = balanceAfter, - Type = type, - OtherOban = otherOban, - CharacterId = characterId - }); - db.SaveChanges(); - } } } diff --git a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Account.cs b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Account.cs index 0887f99..c9c1dc8 100644 --- a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Account.cs +++ b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Account.cs @@ -38,6 +38,8 @@ private void OpenAccountMenu(Player player, ServerActor teller, ulong accountId, int? depositRow = AddOperationRow(accountDialog, teller, level, BankOperation.Deposit, "Deposit cash"); int? withdrawRow = AddOperationRow(accountDialog, teller, level, BankOperation.Withdraw, "Withdraw cash"); int? transferRow = AddOperationRow(accountDialog, teller, level, BankOperation.Transfer, "Transfer money"); + int? pendingRow = AddPendingDepositsRow(accountDialog, account); + int? cardRow = AddOperationRow(accountDialog, teller, level, BankOperation.ManageCards, "Debit card"); int? accessRow = AddOperationRow(accountDialog, teller, level, BankOperation.ManageAccess, "Who has access"); int? closeRow = account.OwnerType == BankAccountOwnerType.Bank ? null : AddOperationRow(accountDialog, teller, level, BankOperation.CloseAccount, "Close the account"); @@ -56,6 +58,10 @@ private void OpenAccountMenu(Player player, ServerActor teller, ulong accountId, OpenCashOperation(player, teller, accountId, BankOperation.Withdraw, null, reopenAccount); else if (response.ItemIndex == transferRow) OpenTransfer(player, teller, accountId, null, reopenAccount); + else if (response.ItemIndex == pendingRow) + ShowPendingDeposits(player, account, reopenAccount); + else if (response.ItemIndex == cardRow) + OpenCardMenu(player, teller, accountId, reopenAccount); else if (response.ItemIndex == accessRow) OpenAccessList(player, teller, accountId, reopenAccount); else if (response.ItemIndex == closeRow) @@ -94,10 +100,14 @@ private void ShowHistory(Player player, ulong accountId, Action onBack) private static string GetTransactionLabel(BankTransactionModel transaction) { string other = transaction.OtherOban == null ? string.Empty : $" {Oban.Format(transaction.OtherOban)}"; + string forWhat = transaction.Description == null ? string.Empty : $": {transaction.Description}"; return transaction.Type switch { - BankTransactionType.Deposit => "Deposit", - BankTransactionType.Withdrawal => "Withdrawal", + // ATM deposits and withdrawals say so in their description. + BankTransactionType.Deposit => transaction.Description ?? "Deposit", + BankTransactionType.Withdrawal => transaction.Description ?? "Withdrawal", + BankTransactionType.CardPayment => $"Card payment to{other}{forWhat}", + BankTransactionType.PaymentReceived => $"Payment{(transaction.OtherOban == null ? string.Empty : $" from{other}")}{forWhat}", BankTransactionType.TransferIn => $"From{other}", BankTransactionType.TransferOut => $"To{other}", BankTransactionType.Fee => "Monthly fee", diff --git a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Atm.cs b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Atm.cs new file mode 100644 index 0000000..8c0ad7b --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Atm.cs @@ -0,0 +1,220 @@ +using OpenRP.Framework.Database.Models; +using OpenRP.Framework.Features.Banking.Components; +using OpenRP.Framework.Features.Banking.Entities; +using OpenRP.Framework.Features.Banking.Helpers; +using OpenRP.Framework.Shared; +using OpenRP.Framework.Shared.Dialogs; +using OpenRP.Framework.Shared.Dialogs.Enums; +using OpenRP.Framework.Shared.Dialogs.Extensions; +using SampSharp.Entities.SAMP; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OpenRP.Framework.Features.Banking.Services.Dialogs +{ + /// + /// The ATM: a card and its PIN, then balance, withdrawing and depositing. Every step checks that the player is + /// still at the ATM and the card still works. + /// + public partial class BankDialogService + { + private const string AtmTitle = "ATM"; + + public void OpenAtm(Player player, Atm atm, ulong? cardId) + { + if (!_atmService.IsPlayerAtAtm(player, atm)) + { + return; + } + + Action onCardChosen = card => AskPin(player, card, AtmTitle, () => BeginAtmSession(player, atm, card.Card.Id), () => { }); + BankCardDetails? givenCard = cardId == null ? null : _bankCardService.GetCardDetails(cardId.Value); + if (givenCard != null) + { + onCardChosen(givenCard); + return; + } + ChooseCarriedCard(player, null, AtmTitle, onCardChosen, () => { }); + } + + private void BeginAtmSession(Player player, Atm atm, ulong cardId) + { + player.DestroyComponents(); + player.AddComponent(cardId, atm.Entity); + ShowAtmMenu(player); + } + + private void EndAtmSession(Player player) + { + if (player.IsComponentAlive) + { + player.DestroyComponents(); + } + } + + private void ShowAtmMenu(Player player) + { + WithAtm(player, (atm, card) => + { + BetterListDialog atmDialog = new BetterListDialog("Choose", "Take card"); + atmDialog.SetTitle(TitleType.Children, AtmTitle, card.GetLabel()); + int balanceRow = atmDialog.AddRow("Balance"); + int withdrawRow = atmDialog.AddRow("Withdraw cash"); + int depositRow = atmDialog.AddRow("Deposit cash"); + + _dialogService.ShowIgnoringDisconnect(player, atmDialog, response => + { + if (response.Response != DialogResponse.LeftButton) + EndAtmSession(player); + else if (response.ItemIndex == balanceRow) + ShowAtmBalance(player); + else if (response.ItemIndex == withdrawRow) + OpenAtmWithdrawal(player); + else if (response.ItemIndex == depositRow) + OpenAtmDeposit(player); + else + ShowAtmMenu(player); + }); + }); + } + + /// + /// Runs the step when the player still has an ATM session at a nearby ATM with a working card; otherwise ends + /// the session and says why. + /// + private void WithAtm(Player player, Action step) + { + AtmSession? session = player.IsComponentAlive ? player.GetComponent() : null; + if (session == null) + { + return; + } + + Atm? atm = session.GetAtm(); + BankCardDetails? card = _bankCardService.GetCardDetails(session.GetCardId()); + string? error = atm == null || !_atmService.IsPlayerAtAtm(player, atm) + ? "You walked away from the ATM." + : card == null ? "The ATM doesn't recognise this card." : _bankCardService.GetUseError(player, card); + if (error != null) + { + EndAtmSession(player); + ShowMessage(player, AtmTitle, "Not possible", error, () => { }); + return; + } + step(atm!, card!); + } + + private void ShowAtmBalance(Player player) + { + WithAtm(player, (atm, card) => + { + BankAccountModel? account = _bankAccountService.GetAccount(card.Account.Id); + if (account == null) + { + ShowAtmMenu(player); + return; + } + + StringBuilder text = new StringBuilder(); + text.AppendLine($"Balance: {Highlight(FormatMoney(account.CurrencyId, account.Balance))}"); + text.AppendLine(GetPendingDepositsText(account)); + text.AppendLine($"You can still withdraw {Highlight(FormatMoney(account.CurrencyId, _atmService.GetRemainingWithdrawal(card.Card.Id)))} with this card right now."); + ShowMessage(player, AtmTitle, "Balance", text.ToString(), () => ShowAtmMenu(player)); + }); + } + + private void OpenAtmWithdrawal(Player player) + { + WithAtm(player, (atm, card) => + { + decimal remaining = _atmService.GetRemainingWithdrawal(card.Card.Id); + string prompt = $"How much? You can still withdraw {Highlight(FormatMoney(card.Account.CurrencyId, remaining))} with this card right now."; + AskAtmAmount(player, "Withdraw", prompt, amount => DoAtmWithdrawal(player, amount)); + }); + } + + private void DoAtmWithdrawal(Player player, decimal amount) + { + WithAtm(player, (atm, card) => _ = RunAsync(player, async () => + { + string? error = await _atmService.WithdrawAsync(player, card.Card.Id, amount); + if (!player.IsComponentAlive) + { + return; + } + string doneText = $"Take your cash: {Highlight(FormatMoney(card.Account.CurrencyId, amount))}."; + ShowMessage(player, AtmTitle, error == null ? "Withdraw" : "Not possible", error ?? doneText, () => ShowAtmMenu(player)); + })); + } + + private void OpenAtmDeposit(Player player) + { + string prompt = $"How much cash do you put in? An ATM deposit reaches the account after {BankingRules.AtmDepositDelay.TotalHours:0} hours; at a bank teller it's there at once."; + AskAtmAmount(player, "Deposit", prompt, amount => DoAtmDeposit(player, amount)); + } + + private void DoAtmDeposit(Player player, decimal amount) + { + WithAtm(player, (atm, card) => _ = RunAsync(player, async () => + { + string? error = await _atmService.DepositAsync(player, card.Card.Id, atm, amount); + if (!player.IsComponentAlive) + { + return; + } + DateTime arrivesAt = DateTime.UtcNow + BankingRules.AtmDepositDelay; + string doneText = $"The ATM took {Highlight(FormatMoney(card.Account.CurrencyId, amount))}. It reaches {card.Account.Name} at about {arrivesAt.ToLocalTime():HH:mm}."; + ShowMessage(player, AtmTitle, error == null ? "Deposit" : "Not possible", error ?? doneText, () => ShowAtmMenu(player)); + })); + } + + private void AskAtmAmount(Player player, string subtitle, string prompt, Action onEntered) + { + void OnEntered(string text) + { + decimal? amount = BankAmounts.Parse(text); + if (amount == null) + { + ShowMessage(player, AtmTitle, subtitle, "Enter an amount above 0, with at most 2 decimals, for example 250 or 99.50.", + () => AskAtmAmount(player, subtitle, prompt, onEntered)); + return; + } + onEntered(amount.Value); + } + + OpenTextInput(player, AtmTitle, subtitle, prompt, OnEntered, () => ShowAtmMenu(player)); + } + + /// + /// A row on the teller's account menu when ATM deposits are on their way, or null. + /// + private int? AddPendingDepositsRow(BetterListDialog dialog, BankAccountModel account) + { + List pending = _atmService.GetPendingDeposits(account.Id); + return pending.Count == 0 ? null : dialog.AddRow($"Pending ATM deposits: {Highlight(FormatMoney(account.CurrencyId, pending.Sum(deposit => deposit.Amount)))}"); + } + + private void ShowPendingDeposits(Player player, BankAccountModel account, Action onBack) + { + ShowMessage(player, account.Name, "Pending ATM deposits", GetPendingDepositsText(account), onBack); + } + + private string GetPendingDepositsText(BankAccountModel account) + { + List pending = _atmService.GetPendingDeposits(account.Id); + if (pending.Count == 0) + { + return "No ATM deposits on their way."; + } + + StringBuilder text = new StringBuilder("ATM deposits on their way:\n"); + foreach (BankPendingDepositModel deposit in pending) + { + text.AppendLine($" {FormatMoney(account.CurrencyId, deposit.Amount)} {ChatColor.LightGray}arrives at {deposit.CreditAt.ToLocalTime():dd MMM HH:mm}{ChatColor.White}"); + } + return text.ToString(); + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.CardUse.cs b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.CardUse.cs new file mode 100644 index 0000000..1b04022 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.CardUse.cs @@ -0,0 +1,148 @@ +using OpenRP.Framework.Features.Banking.Entities; +using OpenRP.Framework.Features.Banking.Enums; +using OpenRP.Framework.Features.Characters.Components; +using OpenRP.Framework.Features.Inventories.Components; +using OpenRP.Framework.Features.Players.Extensions; +using OpenRP.Framework.Shared.Dialogs; +using OpenRP.Framework.Shared.Dialogs.Enums; +using OpenRP.Framework.Shared.Dialogs.Extensions; +using SampSharp.Entities.SAMP; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace OpenRP.Framework.Features.Banking.Services.Dialogs +{ + /// + /// Using a card: choosing one of the cards the player carries, typing its PIN, and the card's own menu from the + /// inventory. + /// + public partial class BankDialogService + { + public void OpenCardAuthorisation(Player player, ulong currencyId, string title, Action onAuthorised, Action onCancelled) + { + ChooseCarriedCard(player, currencyId, title, card => AskPin(player, card, title, () => onAuthorised(card.Card.Id), onCancelled), onCancelled); + } + + public void OpenCard(Player player, ulong cardId) + { + BankCardDetails? card = _bankCardService.GetCardDetails(cardId); + if (card == null) + { + return; + } + + BetterListDialog cardDialog = new BetterListDialog("Choose", "Close"); + cardDialog.SetTitle(TitleType.Children, CardTitle); + cardDialog.AddRow($"Bank: {Highlight(card.Bank.Name)}"); + cardDialog.AddRow($"Account: {Highlight(card.Account.Name)}"); + cardDialog.AddRow($"Card number: {Highlight($"...{card.Card.Digits}")}"); + cardDialog.AddRow($"Status: {Highlight(card.GetStatusText())}"); + int renameRow = cardDialog.AddRow(string.IsNullOrEmpty(card.Card.Name) ? "Give the card a name" : $"Rename the card ({card.Card.Name})"); + + _dialogService.ShowIgnoringDisconnect(player, cardDialog, response => + { + Action reopen = () => OpenCard(player, cardId); + if (response.Response != DialogResponse.LeftButton) + return; + if (response.ItemIndex == renameRow) + OpenRenameCard(player, cardId, reopen, reopen); + else + reopen(); + }); + } + + /// + /// One of the cards the player carries, also in wallets, in the currency when one is given. With one card, it's + /// taken at once. + /// + private void ChooseCarriedCard(Player player, ulong? currencyId, string title, Action onChosen, Action onBack) + { + List cards = GetCarriedCards(player, currencyId); + if (cards.Count == 0) + { + ShowMessage(player, title, "No card", currencyId == null ? "You don't carry a debit card." : "You don't carry a debit card that pays in this currency.", onBack); + return; + } + if (cards.Count == 1) + { + onChosen(cards[0]); + return; + } + + BetterListDialog cardDialog = new BetterListDialog("Choose", "Back"); + cardDialog.SetTitle(TitleType.Children, title, "Which card?"); + Dictionary cardsByRow = new Dictionary(); + foreach (BankCardDetails card in cards) + { + string status = card.GetStatus() == BankCardStatus.Active ? string.Empty : $" {Highlight(card.GetStatusText())}"; + cardsByRow[cardDialog.AddRow(card.GetLabel() + status)] = card; + } + + _dialogService.ShowIgnoringDisconnect(player, cardDialog, response => + { + if (response.Response != DialogResponse.LeftButton) + onBack(); + else if (cardsByRow.TryGetValue(response.ItemIndex, out BankCardDetails? card)) + onChosen(card); + }); + } + + private List GetCarriedCards(Player player, ulong? currencyId) + { + if (!player.IsPlayerPlayingAsCharacter()) + { + return new List(); + } + Character character = player.GetPlayerCurrentlyPlayingAsCharacter(); + return _bankCardService.GetCarriedCardItems(character) + .Select(cardItem => cardItem.GetBankCardId()) + .OfType() + .Distinct() + .Select(cardId => _bankCardService.GetCardDetails(cardId)) + .OfType() + .Where(card => currencyId == null || card.Account.CurrencyId == currencyId) + .ToList(); + } + + /// + /// The card's PIN. A wrong PIN asks again, until the card is blocked. + /// + private void AskPin(Player player, BankCardDetails card, string title, Action onCorrect, Action onCancelled) + { + string? error = _bankCardService.GetUseError(player, card); + if (error != null) + { + ShowMessage(player, title, "Card refused", error, onCancelled); + return; + } + + OpenPinInput(player, title, card.GetLabel(), "Enter the PIN:", pin => _ = RunAsync(player, async () => + { + PinCheckResult result = await _bankCardService.CheckPinAsync(card.Card.Id, pin); + if (!player.IsComponentAlive) + { + return; + } + ContinueAfterPin(player, card, title, result, onCorrect, onCancelled); + }), onCancelled); + } + + private void ContinueAfterPin(Player player, BankCardDetails card, string title, PinCheckResult result, Action onCorrect, Action onCancelled) + { + if (result == PinCheckResult.Correct) + { + onCorrect(); + return; + } + if (result == PinCheckResult.Blocked) + { + ShowMessage(player, title, "Card blocked", "Too many wrong PINs: the card is blocked. The bank can unblock it.", onCancelled); + return; + } + + int attemptsLeft = BankingRules.MaxWrongPinAttempts - (_bankCardService.GetCardDetails(card.Card.Id)?.Card.WrongPinAttempts ?? 0); + ShowMessage(player, title, "Wrong PIN", $"Wrong PIN. {attemptsLeft} more wrong and the card is blocked.", () => AskPin(player, card, title, onCorrect, onCancelled)); + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Cards.cs b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Cards.cs new file mode 100644 index 0000000..64e78d8 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Cards.cs @@ -0,0 +1,190 @@ +using OpenRP.Framework.Database.Models; +using OpenRP.Framework.Features.Actors.Components; +using OpenRP.Framework.Features.Banking.Entities; +using OpenRP.Framework.Features.Banking.Enums; +using OpenRP.Framework.Features.Characters.Components; +using OpenRP.Framework.Features.Players.Extensions; +using OpenRP.Framework.Shared.Dialogs; +using OpenRP.Framework.Shared.Dialogs.Enums; +using OpenRP.Framework.Shared.Dialogs.Extensions; +using SampSharp.Entities.SAMP; +using System; + +namespace OpenRP.Framework.Features.Banking.Services.Dialogs +{ + public partial class BankDialogService + { + private const string CardTitle = "Debit card"; + + /// + /// The player's own card for this account at the teller: ordering one, or renaming, changing the PIN, blocking, + /// unblocking and replacing it. + /// + private void OpenCardMenu(Player player, ServerActor teller, ulong accountId, Action onBack) + { + BankAccountModel? account = _bankAccountService.GetAccount(accountId); + if (account == null || !player.IsPlayerPlayingAsCharacter()) + { + onBack(); + return; + } + Character character = player.GetPlayerCurrentlyPlayingAsCharacter(); + BankCardDetails? card = _bankCardService.GetCurrentCard(accountId, character.GetId()); + + BetterListDialog cardDialog = new BetterListDialog("Choose", "Back"); + cardDialog.SetTitle(TitleType.Children, "Bank", account.Name, CardTitle); + if (card != null) + { + cardDialog.AddRow($"{card.GetLabel()} {Highlight(card.GetStatusText())}"); + } + int? renameRow = card == null ? null : cardDialog.AddRow("Rename the card"); + int? pinRow = card == null ? null : cardDialog.AddRow("Change the PIN"); + int? blockRow = card == null || card.Card.BlockedAt != null ? null : cardDialog.AddRow("Block the card"); + int? unblockRow = card?.Card.BlockedAt == null ? null : cardDialog.AddRow("Unblock the card"); + int orderRow = cardDialog.AddRow(card == null ? "Order a card" : $"Order a new card (the card ...{card.Card.Digits} stops working)"); + + _dialogService.ShowIgnoringDisconnect(player, cardDialog, response => + { + Action reopen = () => OpenCardMenu(player, teller, accountId, onBack); + if (response.Response != DialogResponse.LeftButton) + onBack(); + else if (response.ItemIndex == orderRow) + OpenOrderCard(player, teller, account, reopen); + else if (card == null) + reopen(); + else if (response.ItemIndex == renameRow) + OpenRenameCard(player, card.Card.Id, () => WithTeller(player, teller, BankOperation.ManageCards, reopen), reopen); + else if (response.ItemIndex == pinRow) + OpenChangePin(player, teller, card.Card.Id, reopen); + else if (response.ItemIndex == blockRow) + OpenBlockCard(player, teller, card, reopen); + else if (response.ItemIndex == unblockRow) + DoCardChange(player, teller, () => _bankCardService.UnblockCard(card.Card.Id), "The card works again.", reopen); + else + reopen(); + }); + } + + /// + /// An optional name, then the PIN twice. + /// + private void OpenOrderCard(Player player, ServerActor teller, BankAccountModel account, Action onBack) + { + void OnNameEntered(string name) + { + string? error = _bankCardService.GetCardNameError(name); + if (error != null) + { + ShowMessage(player, CardTitle, "Name", error, () => OpenOrderCard(player, teller, account, onBack)); + return; + } + AskNewPin(player, pin => DoOrderCard(player, teller, account.Id, name, pin, onBack), onBack); + } + + OpenTextInput(player, account.Name, "Order a card", + $"Give the card a name if you like, for example \"Groceries\". Leave it empty for none. At most {BankingRules.CardNameMaxLength} characters.", OnNameEntered, onBack); + } + + private void DoOrderCard(Player player, ServerActor teller, ulong accountId, string name, string pin, Action onBack) + { + WithTeller(player, teller, BankOperation.ManageCards, () => _ = RunAsync(player, async () => + { + string? error = await _bankCardService.IssueCardAsync(player, accountId, name, pin); + if (!player.IsComponentAlive) + { + return; + } + ContinueAfter(player, CardTitle, error, + () => ShowMessage(player, CardTitle, "Your card", "Here's your new card. It's in your inventory. Keep the PIN to yourself.", onBack), onBack); + })); + } + + private void OpenChangePin(Player player, ServerActor teller, ulong cardId, Action onBack) + { + AskNewPin(player, pin => WithTeller(player, teller, BankOperation.ManageCards, () => _ = RunAsync(player, async () => + { + string? error = await _bankCardService.ChangePinAsync(cardId, pin); + if (!player.IsComponentAlive) + { + return; + } + ContinueAfter(player, CardTitle, error, () => ShowMessage(player, CardTitle, "PIN", "The card has its new PIN.", onBack), onBack); + })), onBack); + } + + private void OpenBlockCard(Player player, ServerActor teller, BankCardDetails card, Action onBack) + { + ShowConfirmation(player, CardTitle, "Block", + $"Block {card.GetLabel()}? Nobody can use it until the bank unblocks it. Block it when it's lost or stolen.", + () => DoCardChange(player, teller, () => _bankCardService.BlockCard(card.Card.Id), "The card is blocked.", onBack), onBack, "Block", "Back"); + } + + private void DoCardChange(Player player, ServerActor teller, Func change, string doneText, Action onBack) + { + WithTeller(player, teller, BankOperation.ManageCards, () => + { + string? error = change(); + ContinueAfter(player, CardTitle, error, () => ShowMessage(player, CardTitle, "Done", doneText, onBack), onBack); + }); + } + + /// + /// The new PIN twice, as password input, so a typing mistake doesn't lock the player out. + /// + private void AskNewPin(Player player, Action onEntered, Action onBack) + { + void OnFirstEntered(string pin) + { + string? error = _bankCardService.GetPinError(pin); + if (error != null) + { + ShowMessage(player, CardTitle, "PIN", error, () => AskNewPin(player, onEntered, onBack)); + return; + } + OpenPinInput(player, CardTitle, "PIN", "Type the PIN again:", repeated => + { + if (repeated != pin) + { + ShowMessage(player, CardTitle, "PIN", "The two PINs weren't the same. Try again.", () => AskNewPin(player, onEntered, onBack)); + return; + } + onEntered(pin); + }, onBack); + } + + OpenPinInput(player, CardTitle, "PIN", $"Choose a PIN of {BankingRules.PinLength} digits:", OnFirstEntered, onBack); + } + + private void OpenPinInput(Player player, string title, string subtitle, string prompt, Action onEntered, Action onBack) + { + BetterInputDialog pinDialog = new BetterInputDialog("Continue", "Back"); + pinDialog.SetTitle(TitleType.Children, title, subtitle); + pinDialog.SetContent(prompt); + pinDialog.IsPassword = true; + _dialogService.ShowIgnoringDisconnect(player, pinDialog, response => + { + if (response.Response != DialogResponse.LeftButton) + { + onBack(); + return; + } + onEntered(response.InputText ?? string.Empty); + }); + } + + /// + /// A new name for the card, or none. Whoever holds the card may rename it, like writing on a label. + /// + private void OpenRenameCard(Player player, ulong cardId, Action onDone, Action onBack) + { + void OnEntered(string name) + { + string? error = _bankCardService.RenameCard(cardId, name); + ContinueAfter(player, CardTitle, error, onDone, () => OpenRenameCard(player, cardId, onDone, onBack)); + } + + OpenTextInput(player, CardTitle, "Rename", + $"Enter a name for the card, for example \"Groceries\", or leave it empty to remove the name. At most {BankingRules.CardNameMaxLength} characters.", OnEntered, onBack); + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Menu.cs b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Menu.cs index 813c1a3..bd3167f 100644 --- a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Menu.cs +++ b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.Menu.cs @@ -144,6 +144,9 @@ private void OpenAccountOperation(Player player, ServerActor teller, BankAccount case BankOperation.ManageAccess: OpenAccessList(player, teller, account.Id, onBack); break; + case BankOperation.ManageCards: + OpenCardMenu(player, teller, account.Id, onBack); + break; case BankOperation.CloseAccount: OpenCloseAccount(player, teller, account.Id, onBack); break; diff --git a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.cs b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.cs index 774f557..495bdd9 100644 --- a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.cs +++ b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/BankDialogService.cs @@ -22,8 +22,9 @@ namespace OpenRP.Framework.Features.Banking.Services.Dialogs { /// - /// The bank menus. One file per flow: the menu and account picker, one account, opening, closing and access, and - /// the admin editor. Every step that does something checks the teller and the player's access again. + /// The bank menus. One file per flow: the menu and account picker, one account, opening, closing and access, cards + /// at the teller, ATMs, choosing a card and its PIN, the card item, and the admin editor. Every step that does + /// something checks the teller (or the ATM) and the player's access again. /// public partial class BankDialogService : IBankDialogService { @@ -42,12 +43,15 @@ public partial class BankDialogService : IBankDialogService private readonly IFactionService _factionService; private readonly IPropertyEditorService _propertyEditorService; private readonly IActorEditorService _actorEditorService; + private readonly IBankCardService _bankCardService; + private readonly IAtmService _atmService; private readonly ILogger _logger; public BankDialogService(IDialogService dialogService, ITellerService tellerService, IBankService bankService, IBankAccountService bankAccountService, IBankTransactionService bankTransactionService, IBankEditorService bankEditorService, ICurrencyService currencyService, IJurisdictionService jurisdictionService, IJurisdictionDialogService jurisdictionDialogService, IFactionDialogService factionDialogService, IFactionService factionService, - IPropertyEditorService propertyEditorService, IActorEditorService actorEditorService, ILogger logger) + IPropertyEditorService propertyEditorService, IActorEditorService actorEditorService, IBankCardService bankCardService, IAtmService atmService, + ILogger logger) { _factionService = factionService; _dialogService = dialogService; @@ -62,6 +66,8 @@ public BankDialogService(IDialogService dialogService, ITellerService tellerServ _factionDialogService = factionDialogService; _propertyEditorService = propertyEditorService; _actorEditorService = actorEditorService; + _bankCardService = bankCardService; + _atmService = atmService; _logger = logger; } diff --git a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/IBankDialogService.cs b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/IBankDialogService.cs index 26ef556..654d793 100644 --- a/src/OpenRP.Framework/Features/Banking/Services/Dialogs/IBankDialogService.cs +++ b/src/OpenRP.Framework/Features/Banking/Services/Dialogs/IBankDialogService.cs @@ -1,6 +1,8 @@ using OpenRP.Framework.Features.Actors.Components; +using OpenRP.Framework.Features.Banking.Components; using OpenRP.Framework.Features.Banking.Enums; using SampSharp.Entities.SAMP; +using System; namespace OpenRP.Framework.Features.Banking.Services.Dialogs { @@ -21,5 +23,23 @@ public interface IBankDialogService /// /editbanks: banks, their fees, branches and tellers, property accounts, and looking up an OBAN. /// void OpenBankEditor(Player player); + + /// + /// The ATM: the given card, or one of the cards the player carries, then its PIN, then balance, withdrawing and + /// depositing. + /// + void OpenAtm(Player player, Atm atm, ulong? cardId); + + /// + /// A card's details from the inventory, where whoever holds it can rename it. + /// + void OpenCard(Player player, ulong cardId); + + /// + /// Lets the player choose a card they carry in this currency and type its PIN. Calls back with the card when the + /// PIN is correct; cancelling, a blocked card or no card calls . A disconnect + /// calls neither. + /// + void OpenCardAuthorisation(Player player, ulong currencyId, string title, Action onAuthorised, Action onCancelled); } } diff --git a/src/OpenRP.Framework/Features/Banking/Services/IAtmService.cs b/src/OpenRP.Framework/Features/Banking/Services/IAtmService.cs new file mode 100644 index 0000000..cc0856e --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Services/IAtmService.cs @@ -0,0 +1,53 @@ +using OpenRP.Framework.Database.Models; +using OpenRP.Framework.Features.Banking.Components; +using SampSharp.Entities; +using SampSharp.Entities.SAMP; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace OpenRP.Framework.Features.Banking.Services +{ + /// + /// ATMs: where they are, cash in and out with a card, and deposits that reach the account later. Methods that + /// move money return why it didn't happen, or null. The card's PIN must have been checked before. + /// + public interface IAtmService + { + /// + /// Makes the map object on this entity an ATM. + /// + void AddAtm(EntityId objectEntity, EntityId mapObjectEntity); + + /// + /// The ATM the player stands at, or null. + /// + Atm? GetNearbyAtm(Player player); + + bool IsPlayerAtAtm(Player player, Atm atm); + + /// + /// How much the card may still take from ATMs now, within the limit per period. + /// + decimal GetRemainingWithdrawal(ulong cardId); + + /// + /// Takes the money from the card's account, within the limit, and gives the player the cash. + /// + Task WithdrawAsync(Player player, ulong cardId, decimal amount); + + /// + /// Takes the cash from the player now; it reaches the card's account after the ATM deposit delay. + /// + Task DepositAsync(Player player, ulong cardId, Atm atm, decimal amount); + + /// + /// The account's ATM deposits that haven't reached it yet, soonest first. + /// + List GetPendingDeposits(ulong accountId); + + /// + /// Puts every ATM deposit that's due on its account. + /// + void CreditDueDeposits(); + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Services/IBankCardService.cs b/src/OpenRP.Framework/Features/Banking/Services/IBankCardService.cs new file mode 100644 index 0000000..860fdfb --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Services/IBankCardService.cs @@ -0,0 +1,73 @@ +using OpenRP.Framework.Features.Banking.Entities; +using OpenRP.Framework.Features.Banking.Enums; +using OpenRP.Framework.Features.Characters.Components; +using OpenRP.Framework.Features.Inventories.Components; +using SampSharp.Entities.SAMP; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace OpenRP.Framework.Features.Banking.Services +{ + /// + /// Debit cards: issuing them as items, PINs, blocking, names, and whether a card may be used. Methods that change + /// something return why it didn't happen, or null. + /// + public interface IBankCardService + { + /// + /// The card with its account and bank, read fresh, or null. + /// + BankCardDetails? GetCardDetails(ulong cardId); + + /// + /// The character's card for the account that wasn't replaced, or null. + /// + BankCardDetails? GetCurrentCard(ulong accountId, ulong characterId); + + /// + /// The card items the character carries, also those in wallets. + /// + List GetCarriedCardItems(Character character); + + /// + /// Why the player can't use the card now, or null. The owner needs full access to the account; anyone else + /// holding the card only needs the PIN, as with a real card. + /// + string? GetUseError(Player player, BankCardDetails card); + + /// + /// A new card for the player's character and the account, as an item in their inventory. Their earlier card for + /// that account is cancelled. + /// + Task IssueCardAsync(Player player, ulong accountId, string? name, string pin); + + /// + /// Checks the PIN. A wrong one counts towards blocking the card; a correct one resets the count. + /// + Task CheckPinAsync(ulong cardId, string pin); + + Task ChangePinAsync(ulong cardId, string pin); + + string? BlockCard(ulong cardId); + + /// + /// Unblocks the card and resets the wrong PIN count. A cancelled card stays cancelled. + /// + string? UnblockCard(ulong cardId); + + /// + /// Gives the card a name, or clears it with an empty name. + /// + string? RenameCard(ulong cardId, string name); + + /// + /// Why the text isn't a valid PIN (exactly 4 digits), or null. + /// + string? GetPinError(string pin); + + /// + /// Why the text isn't a valid card name, or null. An empty name is valid and clears the name. + /// + string? GetCardNameError(string name); + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Services/IBankTransactionService.cs b/src/OpenRP.Framework/Features/Banking/Services/IBankTransactionService.cs index fc50435..23ff651 100644 --- a/src/OpenRP.Framework/Features/Banking/Services/IBankTransactionService.cs +++ b/src/OpenRP.Framework/Features/Banking/Services/IBankTransactionService.cs @@ -29,5 +29,17 @@ public interface IBankTransactionService /// Charges the monthly fee of every account that's due, into its bank's own account. /// void ChargeDueFees(); + + /// + /// Pays from the card's account to the receiving account, in one database transaction. The PIN must have been + /// checked before. The description says what it was for, in both histories. + /// + string? PayWithCard(Player player, ulong cardId, ulong receiverAccountId, decimal amount, string description); + + /// + /// Takes the cash from the player's wallet, with change, and pays it into the receiving account. Gives the cash + /// back when the account can't take it. + /// + Task PayInCashAsync(Player player, ulong receiverAccountId, ulong currencyId, decimal amount, string description); } } diff --git a/src/OpenRP.Framework/Features/Banking/Systems/BankCardServerSystem.cs b/src/OpenRP.Framework/Features/Banking/Systems/BankCardServerSystem.cs new file mode 100644 index 0000000..10fb634 --- /dev/null +++ b/src/OpenRP.Framework/Features/Banking/Systems/BankCardServerSystem.cs @@ -0,0 +1,33 @@ +using OpenRP.Framework.Features.Banking.Components; +using OpenRP.Framework.Features.Banking.Services; +using OpenRP.Framework.Features.Banking.Services.Dialogs; +using OpenRP.Framework.Shared.ServerEvents.Attributes; +using OpenRP.Framework.Shared.ServerEvents.Entities; +using OpenRP.Framework.Shared.ServerEvents.Entities.EventArgs; + +namespace OpenRP.Framework.Features.Banking.Systems +{ + public class BankCardServerSystem : IServerSystem + { + /// + /// "Use" on a debit card in the inventory: at an ATM it opens the ATM with that card, elsewhere the card's menu. + /// + [ServerEvent] + public void OnPlayerInventoryItemUsed(OnPlayerInventoryItemUsedEventArgs args, IAtmService atmService, IBankDialogService bankDialogService) + { + ulong? cardId = args.InventoryItem.GetBankCardId(); + if (cardId == null) + { + return; + } + + Atm? atm = atmService.GetNearbyAtm(args.Player); + if (atm != null) + { + bankDialogService.OpenAtm(args.Player, atm, cardId); + return; + } + bankDialogService.OpenCard(args.Player, cardId.Value); + } + } +} diff --git a/src/OpenRP.Framework/Features/Banking/Systems/BankingSystem.cs b/src/OpenRP.Framework/Features/Banking/Systems/BankingSystem.cs index a1250cf..49c991a 100644 --- a/src/OpenRP.Framework/Features/Banking/Systems/BankingSystem.cs +++ b/src/OpenRP.Framework/Features/Banking/Systems/BankingSystem.cs @@ -8,10 +8,19 @@ public class BankingSystem : ISystem // Fees are due every 30 days, so checking once an hour is precise enough. private const int FeeIntervalInMilliseconds = 60 * 60 * 1000; + // ATM deposits take hours, so a minute late doesn't matter. + private const int AtmDepositIntervalInMilliseconds = 60 * 1000; + [Timer(FeeIntervalInMilliseconds)] public void ChargeDueFees(IBankTransactionService bankTransactionService) { bankTransactionService.ChargeDueFees(); } + + [Timer(AtmDepositIntervalInMilliseconds)] + public void CreditDueAtmDeposits(IAtmService atmService) + { + atmService.CreditDueDeposits(); + } } } diff --git a/src/OpenRP.Framework/Features/Inventories/Components/InventoryItem.cs b/src/OpenRP.Framework/Features/Inventories/Components/InventoryItem.cs index 6c00d7c..f4475fd 100644 --- a/src/OpenRP.Framework/Features/Inventories/Components/InventoryItem.cs +++ b/src/OpenRP.Framework/Features/Inventories/Components/InventoryItem.cs @@ -22,6 +22,7 @@ public class InventoryItem : Component, IBaseDataComponent, IChangeable, IDeleta public const string VehicleIdKey = "VEHICLE_ID"; private const string PhoneIdKey = "PHONE_ID"; private const string RadioIdKey = "RADIO_ID"; + public const string BankCardIdKey = "BANK_CARD_ID"; private readonly InventoryItemModel _inventoryItemModel; private bool _hasChanges; @@ -227,6 +228,18 @@ public void SetAdditionalDataFlag(string key, bool value) return GetAdditionalData().GetUlong(RadioIdKey); } + /// + /// The bank card this item is, or null when the item isn't a bank card. + /// + public ulong? GetBankCardId() + { + if (!GetItem().IsItemBankCard()) + { + return null; + } + return GetAdditionalData().GetUlong(BankCardIdKey); + } + /// /// The skin model this clothing item puts on the character, or null when it isn't a skin item. /// diff --git a/src/OpenRP.Framework/Features/Inventories/Entities/IInventoryItemNameProvider.cs b/src/OpenRP.Framework/Features/Inventories/Entities/IInventoryItemNameProvider.cs new file mode 100644 index 0000000..8d08451 --- /dev/null +++ b/src/OpenRP.Framework/Features/Inventories/Entities/IInventoryItemNameProvider.cs @@ -0,0 +1,27 @@ +using OpenRP.Framework.Features.Inventories.Components; + +namespace OpenRP.Framework.Features.Inventories.Entities +{ + /// + /// Gives some items a name of their own in the inventory, built from data another feature owns, for example a bank + /// card showing its account. Registered with AddInventoryItemNameProvider. Items no provider handles show the name + /// of their item type. + /// + public interface IInventoryItemNameProvider + { + /// + /// True when this provider names the item. + /// + bool Handles(InventoryItem inventoryItem); + + /// + /// The name shown for the item in the inventory. + /// + string GetName(InventoryItem inventoryItem); + + /// + /// Extra text for the item's "Extra Information" column, or null for none. + /// + string? GetExtraInformation(InventoryItem inventoryItem) => null; + } +} diff --git a/src/OpenRP.Framework/Features/Inventories/Extensions/ServiceCollectionExtensions.cs b/src/OpenRP.Framework/Features/Inventories/Extensions/ServiceCollectionExtensions.cs index 7b4acc5..177936e 100644 --- a/src/OpenRP.Framework/Features/Inventories/Extensions/ServiceCollectionExtensions.cs +++ b/src/OpenRP.Framework/Features/Inventories/Extensions/ServiceCollectionExtensions.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.DependencyInjection; +using OpenRP.Framework.Features.Inventories.Entities; using OpenRP.Framework.Features.Inventories.Services; using OpenRP.Framework.Features.Inventories.Services.Dialogs; using OpenRP.Framework.Shared.BaseManager.Helpers; @@ -20,5 +21,13 @@ public static IServiceCollection AddInventories(this IServiceCollection self) .AddSingleton() .AddTransient(); // Transient because it uses IDroppedItemService, which uses a database context. } + + /// + /// Registers a provider that gives the items it handles their own name in the inventory. + /// + public static IServiceCollection AddInventoryItemNameProvider(this IServiceCollection self) where T : class, IInventoryItemNameProvider + { + return self.AddSingleton(); + } } } diff --git a/src/OpenRP.Framework/Features/Inventories/Services/Dialogs/InventoryDialogService.cs b/src/OpenRP.Framework/Features/Inventories/Services/Dialogs/InventoryDialogService.cs index a956972..6bb3c82 100644 --- a/src/OpenRP.Framework/Features/Inventories/Services/Dialogs/InventoryDialogService.cs +++ b/src/OpenRP.Framework/Features/Inventories/Services/Dialogs/InventoryDialogService.cs @@ -3,6 +3,7 @@ using OpenRP.Framework.Features.Characters.Components; using OpenRP.Framework.Features.DroppedItems.Services; using OpenRP.Framework.Features.Inventories.Components; +using OpenRP.Framework.Features.Inventories.Entities; using OpenRP.Framework.Features.Inventories.Enums; using OpenRP.Framework.Features.Inventories.Helpers; using OpenRP.Framework.Features.Items.Components; @@ -35,12 +36,34 @@ public class InventoryDialogService : IInventoryDialogService private IChatService _chatService; private IDroppedItemService _droppedItemService; private readonly IServerEventAggregator _serverEventAggregator; - public InventoryDialogService(IDialogService dialogService, IChatService chatService, IDroppedItemService droppedItemService, IServerEventAggregator serverEventAggregator) + private readonly IEnumerable _nameProviders; + public InventoryDialogService(IDialogService dialogService, IChatService chatService, IDroppedItemService droppedItemService, IServerEventAggregator serverEventAggregator, + IEnumerable nameProviders) { _dialogService = dialogService; _chatService = chatService; _droppedItemService = droppedItemService; _serverEventAggregator = serverEventAggregator; + _nameProviders = nameProviders; + } + + /// + /// The item's own name from a provider, such as a bank card with its account, or else its item type's name. + /// + private string GetDisplayName(InventoryItem inventoryItem) + { + IInventoryItemNameProvider? provider = GetNameProvider(inventoryItem); + return provider == null ? inventoryItem.GetName() : provider.GetName(inventoryItem); + } + + private string? GetProvidedExtraInformation(InventoryItem inventoryItem) + { + return GetNameProvider(inventoryItem)?.GetExtraInformation(inventoryItem); + } + + private IInventoryItemNameProvider? GetNameProvider(InventoryItem inventoryItem) + { + return _nameProviders.FirstOrDefault(provider => provider.Handles(inventoryItem)); } public void OpenInventory(Player player, Inventory inventory, InventoryArguments inventoryArguments = InventoryArguments.None) @@ -102,10 +125,16 @@ public void OpenInventory(Player player, Inventory inventory, InventoryArguments extraInformation.Add($"{inventoryItem.GetRemainingUses()}/{inventoryItem.GetItem().GetMaxUses()} Durability"); } + string? providedExtraInformation = GetProvidedExtraInformation(inventoryItem); + if (providedExtraInformation != null) + { + extraInformation.Add(providedExtraInformation); + } + // Fill Columns List rowColumns = new List(); - rowColumns.Add(inventoryItem.GetName()); + rowColumns.Add(GetDisplayName(inventoryItem)); rowColumns.Add(inventoryItem.GetAmount().ToString()); if (!inventoryArguments.HasFlag(InventoryArguments.HideTotalWeight)) @@ -147,7 +176,7 @@ public void OpenSelectedItemDialog(Player player, InventoryOpened inventoryOpene { Item item = inventoryOpened.SelectedInventoryItem.GetItem(); BetterListDialog listDialog = new BetterListDialog("Select", "Cancel"); - listDialog.SetTitle(TitleType.Children, inventoryOpened.SelectedInventoryItem.GetItem().GetName()); + listDialog.SetTitle(TitleType.Children, GetDisplayName(inventoryOpened.SelectedInventoryItem)); // Build a dictionary mapping action names to actions (delegates) Dictionary actions = BuildSelectedItemActions(player, inventoryOpened); @@ -236,7 +265,7 @@ private Dictionary BuildSelectedItemActions(Player player, Inven string description = String.IsNullOrEmpty(item.GetDescription()) ? "This item does not have a description." : item.GetDescription(); BetterMessageDialog messageDialog = new BetterMessageDialog("Close"); - messageDialog.SetTitle(TitleType.Children, inventoryOpened.OpenedInventory.GetName(), inventoryOpened.SelectedInventoryItem.GetName(), "Description"); + messageDialog.SetTitle(TitleType.Children, inventoryOpened.OpenedInventory.GetName(), GetDisplayName(inventoryOpened.SelectedInventoryItem), "Description"); messageDialog.SetContent(description); _dialogService.ShowIgnoringDisconnect(player, messageDialog, _ => { }); }; diff --git a/src/OpenRP.Framework/Features/Items/Components/Item.cs b/src/OpenRP.Framework/Features/Items/Components/Item.cs index b91006a..041a295 100644 --- a/src/OpenRP.Framework/Features/Items/Components/Item.cs +++ b/src/OpenRP.Framework/Features/Items/Components/Item.cs @@ -145,6 +145,11 @@ public bool IsItemFish() return _itemModel.UseType == ItemType.Fish; } + public bool IsItemBankCard() + { + return _itemModel.UseType == ItemType.BankCard; + } + public bool IsItemInventory() { return IsItemWallet(); diff --git a/src/OpenRP.Framework/Features/Items/Enums/ItemType.cs b/src/OpenRP.Framework/Features/Items/Enums/ItemType.cs index cd43a90..cbcbbed 100644 --- a/src/OpenRP.Framework/Features/Items/Enums/ItemType.cs +++ b/src/OpenRP.Framework/Features/Items/Enums/ItemType.cs @@ -18,5 +18,6 @@ public enum ItemType Phone = 8, Radio = 9, RadioEarpiece = 10, + BankCard = 11, } } diff --git a/src/OpenRP.Framework/Features/Items/Models/DefaultData/ItemModelDefaultData.cs b/src/OpenRP.Framework/Features/Items/Models/DefaultData/ItemModelDefaultData.cs index 356ffe5..92cd54b 100644 --- a/src/OpenRP.Framework/Features/Items/Models/DefaultData/ItemModelDefaultData.cs +++ b/src/OpenRP.Framework/Features/Items/Models/DefaultData/ItemModelDefaultData.cs @@ -906,6 +906,20 @@ public void Configure(EntityTypeBuilder builder) KeepOnDeath = true, Stackable = false, DropModelId = 19630 + }, + new ItemModel + { + Id = 68, + Name = "Debit card", + Description = "A plastic bank card with a magnetic strip. With the right PIN it takes cash from ATMs and pays in shops. Whoever holds it and knows the PIN can use it.", + UseType = ItemType.BankCard, + UseValue = "", + Weight = 5, + CanDrop = true, + CanDestroy = false, + KeepOnDeath = true, + Stackable = false, + DropModelId = 1581 } ); } diff --git a/src/OpenRP.Framework/Features/Payments/Commands/TestPaymentCommand.cs b/src/OpenRP.Framework/Features/Payments/Commands/TestPaymentCommand.cs new file mode 100644 index 0000000..689163c --- /dev/null +++ b/src/OpenRP.Framework/Features/Payments/Commands/TestPaymentCommand.cs @@ -0,0 +1,50 @@ +using OpenRP.Framework.Database.Models; +using OpenRP.Framework.Features.Banking.Services; +using OpenRP.Framework.Features.Commands.Attributes; +using OpenRP.Framework.Features.Currencies.Services; +using OpenRP.Framework.Features.Payments.Entities; +using OpenRP.Framework.Features.Payments.Services; +using OpenRP.Framework.Shared.Chat.Enums; +using OpenRP.Framework.Shared.Chat.Extensions; +using SampSharp.Entities; +using SampSharp.Entities.SAMP; +using System.Threading.Tasks; + +namespace OpenRP.Framework.Features.Payments.Commands +{ + /// + /// Lets testers try the payment flow before any feature uses it. + /// + public class TestPaymentCommand : ISystem + { + [ServerCommand(PermissionGroups = new string[] { "Admin", "Tester" }, + Description = "Ask yourself to pay an amount into a bank account, to test cash and card payments.", + CommandGroups = new string[] { "Tester" })] + public async Task TestPayment(Player player, ICheckoutService checkoutService, IBankAccountService bankAccountService, ICurrencyService currencyService, + int amount, string oban) + { + BankAccountModel? account = bankAccountService.GetAccountByOban(oban.Replace(" ", string.Empty).ToUpperInvariant()); + if (account == null || account.ClosedAt != null) + { + player.SendPlayerInfoMessage(PlayerInfoMessageType.ERROR, "No open account has that OBAN."); + return; + } + + PaymentResult result = await checkoutService.RequestPaymentAsync(player, new PaymentRequest(amount, account.CurrencyId, account.Id, "a test payment")); + if (!player.IsComponentAlive) + { + return; + } + string amountText = currencyService.GetCurrencyFormat(account.CurrencyId, amount); + player.SendPlayerInfoMessage(PlayerInfoMessageType.INFO, $"Test payment of {amountText}: {result.Outcome}."); + } + + [ServerCommand(PermissionGroups = new string[] { "Admin", "Tester" }, + Description = "Ask yourself to pay an amount into a bank account, to test cash and card payments.", + CommandGroups = new string[] { "Tester" })] + public void TestPayment(Player player) + { + player.SendPlayerInfoMessage(PlayerInfoMessageType.SYNTAX, "/testpayment [amount] [OBAN]"); + } + } +} diff --git a/src/OpenRP.Framework/Features/Payments/Components/PendingCheckout.cs b/src/OpenRP.Framework/Features/Payments/Components/PendingCheckout.cs new file mode 100644 index 0000000..bbf99b0 --- /dev/null +++ b/src/OpenRP.Framework/Features/Payments/Components/PendingCheckout.cs @@ -0,0 +1,45 @@ +using OpenRP.Framework.Features.Payments.Entities; +using SampSharp.Entities; +using System.Threading.Tasks; + +namespace OpenRP.Framework.Features.Payments.Components +{ + /// + /// On a player who is being asked to pay. The feature that asked awaits its result. When the player leaves, the + /// component goes with them and the payment ends as cancelled, so nobody waits forever. + /// + public class PendingCheckout : Component + { + private readonly PaymentRequest _request; + private readonly TaskCompletionSource _result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + public PendingCheckout(PaymentRequest request) + { + _request = request; + } + + public PaymentRequest GetRequest() + { + return _request; + } + + public Task GetResult() + { + return _result.Task; + } + + /// + /// Ends the payment with this result and removes the component. + /// + public void End(PaymentResult result) + { + _result.TrySetResult(result); + Destroy(); + } + + protected override void OnDestroyComponent() + { + _result.TrySetResult(PaymentResult.Cancelled); + } + } +} diff --git a/src/OpenRP.Framework/Features/Payments/Entities/PaymentRequest.cs b/src/OpenRP.Framework/Features/Payments/Entities/PaymentRequest.cs new file mode 100644 index 0000000..e2b27f8 --- /dev/null +++ b/src/OpenRP.Framework/Features/Payments/Entities/PaymentRequest.cs @@ -0,0 +1,12 @@ +namespace OpenRP.Framework.Features.Payments.Entities +{ + /// + /// What a feature asks a player to pay: how much, in which currency, into which bank account, and what for. The + /// description shows in the dialog and in both bank histories, for example "Groceries at the 24/7". + /// + public record PaymentRequest(decimal Amount, ulong CurrencyId, ulong ReceiverAccountId, string Description) + { + public bool AllowsCash { get; init; } = true; + public bool AllowsCard { get; init; } = true; + } +} diff --git a/src/OpenRP.Framework/Features/Payments/Entities/PaymentResult.cs b/src/OpenRP.Framework/Features/Payments/Entities/PaymentResult.cs new file mode 100644 index 0000000..08ee54c --- /dev/null +++ b/src/OpenRP.Framework/Features/Payments/Entities/PaymentResult.cs @@ -0,0 +1,17 @@ +using OpenRP.Framework.Features.Payments.Enums; + +namespace OpenRP.Framework.Features.Payments.Entities +{ + /// + /// How a payment ended. The error says why it failed; the player has already been told. + /// + public record PaymentResult(PaymentOutcome Outcome, string? Error = null) + { + public static readonly PaymentResult Paid = new PaymentResult(PaymentOutcome.Paid); + public static readonly PaymentResult Cancelled = new PaymentResult(PaymentOutcome.Cancelled); + + public static PaymentResult Failed(string error) => new PaymentResult(PaymentOutcome.Failed, error); + + public bool IsPaid => Outcome == PaymentOutcome.Paid; + } +} diff --git a/src/OpenRP.Framework/Features/Payments/Enums/PaymentOutcome.cs b/src/OpenRP.Framework/Features/Payments/Enums/PaymentOutcome.cs new file mode 100644 index 0000000..da5815a --- /dev/null +++ b/src/OpenRP.Framework/Features/Payments/Enums/PaymentOutcome.cs @@ -0,0 +1,11 @@ +namespace OpenRP.Framework.Features.Payments.Enums +{ + public enum PaymentOutcome + { + Paid = 1, + // The player chose not to pay, or left; nothing was paid. + Cancelled = 2, + // The payment was refused, for example a declined card; nothing was paid. + Failed = 3 + } +} diff --git a/src/OpenRP.Framework/Features/Payments/Extensions/ServiceCollectionExtensions.cs b/src/OpenRP.Framework/Features/Payments/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..96d0ba7 --- /dev/null +++ b/src/OpenRP.Framework/Features/Payments/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,16 @@ +using Microsoft.Extensions.DependencyInjection; +using OpenRP.Framework.Features.Payments.Services; +using OpenRP.Framework.Features.Payments.Services.Dialogs; + +namespace OpenRP.Framework.Features.Payments.Extensions +{ + public static partial class ServiceCollectionExtensions + { + public static IServiceCollection AddPayments(this IServiceCollection self) + { + return self + .AddSingleton() + .AddSingleton(); + } + } +} diff --git a/src/OpenRP.Framework/Features/Payments/Services/CheckoutService.cs b/src/OpenRP.Framework/Features/Payments/Services/CheckoutService.cs new file mode 100644 index 0000000..5301a13 --- /dev/null +++ b/src/OpenRP.Framework/Features/Payments/Services/CheckoutService.cs @@ -0,0 +1,89 @@ +using Microsoft.Extensions.Logging; +using OpenRP.Framework.Features.Banking.Services; +using OpenRP.Framework.Features.Banking.Services.Dialogs; +using OpenRP.Framework.Features.Payments.Components; +using OpenRP.Framework.Features.Payments.Entities; +using OpenRP.Framework.Features.Payments.Services.Dialogs; +using OpenRP.Framework.Features.Players.Extensions; +using OpenRP.Framework.Shared.Chat.Enums; +using OpenRP.Framework.Shared.Chat.Extensions; +using SampSharp.Entities.SAMP; +using System; +using System.Threading.Tasks; + +namespace OpenRP.Framework.Features.Payments.Services +{ + public class CheckoutService : ICheckoutService + { + private readonly IPaymentDialogService _paymentDialogService; + private readonly IBankDialogService _bankDialogService; + private readonly IBankTransactionService _bankTransactionService; + private readonly ILogger _logger; + + public CheckoutService(IPaymentDialogService paymentDialogService, IBankDialogService bankDialogService, IBankTransactionService bankTransactionService, + ILogger logger) + { + _paymentDialogService = paymentDialogService; + _bankDialogService = bankDialogService; + _bankTransactionService = bankTransactionService; + _logger = logger; + } + + public Task RequestPaymentAsync(Player player, PaymentRequest request) + { + if (!player.IsComponentAlive || !player.IsPlayerPlayingAsCharacter()) + return Task.FromResult(PaymentResult.Failed("The player isn't playing a character.")); + if (player.GetComponent() != null) + return Task.FromResult(Fail(player, "Finish your other payment first.")); + + PendingCheckout checkout = player.AddComponent(request); + _paymentDialogService.OpenPaymentMethodChoice(player, request, + () => _ = PayInCashAsync(player, checkout), + () => PayWithCard(player, checkout), + () => checkout.End(PaymentResult.Cancelled)); + return checkout.GetResult(); + } + + private async Task PayInCashAsync(Player player, PendingCheckout checkout) + { + PaymentRequest request = checkout.GetRequest(); + try + { + string? error = await _bankTransactionService.PayInCashAsync(player, request.ReceiverAccountId, request.CurrencyId, request.Amount, $"Cash: {request.Description}"); + EndWith(player, checkout, error); + } + catch (Exception exception) + { + _logger.LogError(exception, "A cash payment for {Description} failed.", request.Description); + EndWith(player, checkout, "The payment couldn't be made."); + } + } + + private void PayWithCard(Player player, PendingCheckout checkout) + { + PaymentRequest request = checkout.GetRequest(); + _bankDialogService.OpenCardAuthorisation(player, request.CurrencyId, "Pay", + cardId => EndWith(player, checkout, _bankTransactionService.PayWithCard(player, cardId, request.ReceiverAccountId, request.Amount, request.Description)), + () => checkout.End(PaymentResult.Cancelled)); + } + + /// + /// Paid when there's no error; otherwise the player is told why and the payment failed. + /// + private static void EndWith(Player player, PendingCheckout checkout, string? error) + { + if (!checkout.IsComponentAlive) + return; + checkout.End(error == null ? PaymentResult.Paid : Fail(player, error)); + } + + private static PaymentResult Fail(Player player, string error) + { + if (player.IsComponentAlive) + { + player.SendPlayerInfoMessage(PlayerInfoMessageType.ERROR, error); + } + return PaymentResult.Failed(error); + } + } +} diff --git a/src/OpenRP.Framework/Features/Payments/Services/Dialogs/IPaymentDialogService.cs b/src/OpenRP.Framework/Features/Payments/Services/Dialogs/IPaymentDialogService.cs new file mode 100644 index 0000000..f327a08 --- /dev/null +++ b/src/OpenRP.Framework/Features/Payments/Services/Dialogs/IPaymentDialogService.cs @@ -0,0 +1,14 @@ +using OpenRP.Framework.Features.Payments.Entities; +using SampSharp.Entities.SAMP; +using System; + +namespace OpenRP.Framework.Features.Payments.Services.Dialogs +{ + public interface IPaymentDialogService + { + /// + /// "Pay $X for ...": cash or card, as far as the request allows them. A disconnect calls nothing. + /// + void OpenPaymentMethodChoice(Player player, PaymentRequest request, Action onCash, Action onCard, Action onCancelled); + } +} diff --git a/src/OpenRP.Framework/Features/Payments/Services/Dialogs/PaymentDialogService.cs b/src/OpenRP.Framework/Features/Payments/Services/Dialogs/PaymentDialogService.cs new file mode 100644 index 0000000..7ba7a80 --- /dev/null +++ b/src/OpenRP.Framework/Features/Payments/Services/Dialogs/PaymentDialogService.cs @@ -0,0 +1,44 @@ +using OpenRP.Framework.Features.Currencies.Services; +using OpenRP.Framework.Features.Payments.Entities; +using OpenRP.Framework.Shared; +using OpenRP.Framework.Shared.Dialogs; +using OpenRP.Framework.Shared.Dialogs.Enums; +using OpenRP.Framework.Shared.Dialogs.Extensions; +using SampSharp.Entities.SAMP; +using System; + +namespace OpenRP.Framework.Features.Payments.Services.Dialogs +{ + public class PaymentDialogService : IPaymentDialogService + { + private readonly IDialogService _dialogService; + private readonly ICurrencyService _currencyService; + + public PaymentDialogService(IDialogService dialogService, ICurrencyService currencyService) + { + _dialogService = dialogService; + _currencyService = currencyService; + } + + public void OpenPaymentMethodChoice(Player player, PaymentRequest request, Action onCash, Action onCard, Action onCancelled) + { + string amount = _currencyService.GetCurrencyFormat(request.CurrencyId, request.Amount); + BetterListDialog methodDialog = new BetterListDialog("Pay", "Cancel"); + methodDialog.SetTitle(TitleType.Children, "Pay", $"{ChatColor.Highlight}{amount}{ChatColor.White} for {request.Description}"); + int? cashRow = request.AllowsCash ? methodDialog.AddRow("Cash") : null; + int? cardRow = request.AllowsCard ? methodDialog.AddRow("Debit card") : null; + + _dialogService.ShowIgnoringDisconnect(player, methodDialog, response => + { + if (response.Response != DialogResponse.LeftButton) + onCancelled(); + else if (response.ItemIndex == cashRow) + onCash(); + else if (response.ItemIndex == cardRow) + onCard(); + else + onCancelled(); + }); + } + } +} diff --git a/src/OpenRP.Framework/Features/Payments/Services/ICheckoutService.cs b/src/OpenRP.Framework/Features/Payments/Services/ICheckoutService.cs new file mode 100644 index 0000000..68c4958 --- /dev/null +++ b/src/OpenRP.Framework/Features/Payments/Services/ICheckoutService.cs @@ -0,0 +1,20 @@ +using OpenRP.Framework.Features.Payments.Entities; +using SampSharp.Entities.SAMP; +using System.Threading.Tasks; + +namespace OpenRP.Framework.Features.Payments.Services +{ + /// + /// The one way features take money from a player: shops, rent, fines, fees. The player pays cash or with a debit + /// card, and the money always lands in a bank account. (Handing cash to another player is /pay, in Currencies.) + /// + public interface ICheckoutService + { + /// + /// Asks the player to pay, and completes when they paid, cancelled, failed, or left. The player is told why a + /// payment failed; telling them what they paid for is up to the caller. After awaiting it, check that the + /// player is still alive before using them. + /// + Task RequestPaymentAsync(Player player, PaymentRequest request); + } +}