mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 03:37:18 +00:00
store: record refunds and close failed orders from the group (#8142)
* store: limit group name codes to single 2-year codes, 10 a day * store: exclude console name codes from the group's daily cap * store: hold managed group joiners for a moderator's review * store: drop the years option from group name codes * store: order the group code migration after the terms migration * store: hold group joiners for review from the join request * store: name the owner recovery command for a member pending review * store: read the group info in the joiner test by position * store: hold for review only the joiners of the managed group * store: restore member review in the group profile on every join * store: state the service's member review duties as they hold * store: rename a joiner test value that shadowed hspec's pending * store: note why the first group joiner is not held for review * store: keep the group code column in the names migration * store: point the group lane references past the approved comment * store: record refunds and close failed orders from the group * store: allow 2 to 10 years for group name codes * store: let group moderators issue name codes * store: state the group money commands' locking and delay --------- Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>
This commit is contained in:
1 parent
53b375d7f3
commit
aa313e51b8
10 files changed
+226
-106
No files matched your search
@@ -25,8 +25,8 @@ At this stage the service:
|
||||
- listens for service requests (`CEvtServiceRequest`) on that address, rejects a request whose `purchaseKey` is not the key the agent verified the signature against, and answers `redeemBadgeCode`,
|
||||
- issues redemption codes, storing only their `SHA-256` in its code table,
|
||||
- does not accept contact requests: the address is for RPC only,
|
||||
- in service mode with `[group]` in the ini, manages one SimpleX group and serves `/issue`, `/bulk`
|
||||
and `/revoke` in it (see [Issuing codes](#issuing-codes)),
|
||||
- in service mode with `[group]` in the ini, manages one SimpleX group and serves `/issue`, `/bulk`,
|
||||
`/revoke`, `/balance`, `/record_refund` and `/close` in it (see [Issuing codes](#issuing-codes)),
|
||||
- in service mode with `--service-config`, also serves the built web app (`npm run build` in `web/`) on `badges_port` and, with `[names]`, the names site on `names_port` (see [Two sites](#two-sites)), `POST /api/invoice` and `GET /api/invoice/:id`, the BTCPay and Stripe webhook routes, and a payment poller, seeding its price/offer catalog on every start,
|
||||
- owns the `sx_badge_service_`-prefixed tables and its own migrations table (`sx_badge_service_migrations`).
|
||||
|
||||
@@ -1350,14 +1350,16 @@ were already given out, and the command answers with an error. A multi-use code
|
||||
be revoked, which stops the uses that remain.
|
||||
|
||||
Core parses `//...` into `CustomChatCommand` and leaves it to the service's `preCmdHook`, which is
|
||||
why issuing codes lives in the service rather than in core. `//refund` and `//close`, the other
|
||||
commands of this console, are in [Refunding a name balance](#refunding-a-name-balance) and
|
||||
why issuing codes lives in the service rather than in core. `//balance`, `//record_refund` and
|
||||
`//close`, the other commands of this console, are in [Refunding a name balance](#refunding-a-name-balance) and
|
||||
[Closing a failed order](#closing-a-failed-order).
|
||||
|
||||
### From the group
|
||||
|
||||
With `[group]` in `store_service.ini`, the service manages one group and serves three commands in
|
||||
it: `/issue` and `/bulk` for moderators and above, `/revoke <code>` for admins and owners. Each name code
|
||||
With `[group]` in `store_service.ini`, the service manages one group and serves six commands in
|
||||
it: `/issue` and `/bulk` for moderators and above, `/revoke <code>` for admins and owners, and
|
||||
`/balance`, `/record_refund` and `/close` for owners (see [Balances and failed orders in the
|
||||
group](#balances-and-failed-orders-in-the-group)). Each name code
|
||||
registers at the sponsor allowance's and the gas key's cost, so the group issues at most 10 of them
|
||||
in 24 hours (`//issue name` in `--run-cli` has no limit, and
|
||||
its codes are not counted). The code commands take these forms:
|
||||
@@ -1376,7 +1378,7 @@ bounds, a length for a badge, `months` or `uses` for a name, or `name` in `/bulk
|
||||
lists the form, each kind's bounds and an example of each. The group's command menu shows the kinds
|
||||
of each command in its hint and fills the hint into the message box. Without `[names]`, `/issue name`
|
||||
gets a reply that names are not enabled, and issues nothing. `/revoke` takes badge and name codes, so
|
||||
a name code issued before names were turned off can still be withdrawn. The group has no `/refund`. A member's role
|
||||
a name code issued before names were turned off can still be withdrawn. A member's role
|
||||
is checked as the service last saw it, so a command sent by a moderator just demoted or removed can still run if it
|
||||
reaches the service first; revoke any code the service posts for them after the change. `uses`
|
||||
above 1 makes a multi-use code, tracked by a group message showing its remaining uses and the time
|
||||
@@ -1466,18 +1468,19 @@ from `/api/invoice/:id`, or from `/api/registration/:id` for a registration id.
|
||||
safe on the reference alone, as Stripe returns it to
|
||||
the card that paid; a crypto refund goes to an address the buyer gives, which nothing here ties to
|
||||
the order. Support records each refund in `--run-cli` mode with the service stopped, like the other
|
||||
`//` commands:
|
||||
`//` commands, or in the group while the service runs (see [Balances and failed orders in the
|
||||
group](#balances-and-failed-orders-in-the-group)):
|
||||
|
||||
```
|
||||
//refund <reference>
|
||||
//refund <reference> <cents>
|
||||
//balance <reference>
|
||||
//record_refund <reference> <cents>
|
||||
```
|
||||
|
||||
1. Run `//refund <reference>` with the reference the buyer sent. It records nothing and answers the
|
||||
balance, what paid for it and the command that refunds it:
|
||||
1. Run `//balance <reference>` with the reference the buyer sent. It records nothing and answers the
|
||||
balance, what paid for it and the command that records its refund:
|
||||
|
||||
```
|
||||
Order <id>: balance $100.00 (credited $100.00, refunded $0.00). Paid by: order <id>: $100.00 by btc on invoice <invoice id>. To record its refund: //refund <reference> 10000
|
||||
Order <id>: balance $100.00 (credited $100.00, refunded $0.00). Paid by: order <id>: $100.00 by btc on invoice <invoice id>. To record its refund: //record_refund <reference> 10000
|
||||
```
|
||||
|
||||
`Paid by` starts at this order and follows every balance the money came through back to the
|
||||
@@ -1504,12 +1507,14 @@ expiry unless money reached the invoice:
|
||||
- `its invoice expired at <time>; start the service so the poller closes that order, 10 minutes
|
||||
after the expiry at the earliest, then stop it and run the command again`: the poller runs only in
|
||||
service mode. Its first pass from 10 minutes after the expiry closes the order and releases the
|
||||
hold; a card order closes only once Stripe accepts the cancel.
|
||||
hold; a card order closes only once Stripe accepts the cancel. In the group, where the service
|
||||
runs, the answer is `its invoice expired at <time>; the poller closes that order 10 minutes after
|
||||
the expiry at the earliest; run the command again then`.
|
||||
- `whose invoice holds money`: a payment reached the invoice, before or after its expiry; the hold
|
||||
stays until that payment settles, which spends the balance, or the provider closes the invoice,
|
||||
which releases it.
|
||||
|
||||
The command also answers when the reference matches no order, when the order has no balance, and
|
||||
The commands also answer when the reference matches no order, when the order has no balance, and
|
||||
when the cents are not the balance. A refunded balance shows `amount` 0 and its `refunded` total in
|
||||
Your names; a later late payment credits it again, and a second refund adds to `refunded`.
|
||||
|
||||
@@ -1517,7 +1522,7 @@ Your names; a later late payment credits it again, and a second refund adds to `
|
||||
|
||||
A failed paid order stays live and keeps its money uncredited, so its wallet cannot order the name
|
||||
again. When Try again cannot register it, as after 5 sends of a kind or refused links, support closes
|
||||
it in `--run-cli` mode with the service stopped:
|
||||
it in `--run-cli` mode with the service stopped, or with `/close` in the group while it runs:
|
||||
|
||||
```
|
||||
//close <reference>
|
||||
@@ -1532,11 +1537,11 @@ enabled. It:
|
||||
change is logged at note with its registration id;
|
||||
2. otherwise, in one transaction, sets the order `taken`, credits its price to its balance, which may
|
||||
already hold a move's difference or an overpayment, and records all of that balance as refunded,
|
||||
as `//refund` does.
|
||||
as `//record_refund` does.
|
||||
|
||||
The answer, `Closed order <id>, failed at <time>, as taken and recorded a refund of $100.00. Check at
|
||||
the provider that it was not refunded by hand before; if not, refund it now, by: …`, lists what paid
|
||||
for the order, as the answer of `//refund` does. Before this command existed, support refunded failed
|
||||
for the order, as the answer of `//record_refund` does. Before this command existed, support refunded failed
|
||||
orders at the provider by hand, so look for a refund of that payment after the failure time first, and
|
||||
pay the amount back by those methods only if none is found. The service logs each closed order at
|
||||
note with its registration id and the cents.
|
||||
@@ -1552,13 +1557,39 @@ psql "$BADGE_DB_CONN" -Atc "SELECT r.registration_id, r.phase, r.failed_at, r.re
|
||||
```
|
||||
|
||||
A closed order reads `taken` in Your names, with its refund. Try again and a move answer
|
||||
`400 bad_request`, `//refund` finds nothing to refund, and the wallet can order the name again.
|
||||
`400 bad_request`, `//balance` finds nothing to refund, and the wallet can order the name again.
|
||||
|
||||
The command records nothing for an order that is not failed or was paid with a prepaid code, whose
|
||||
code is released 30 days after the order failed; for a failed chain read; for a balance an order
|
||||
holds, worded as for `//refund`; and for an order or a balance that changed meanwhile. Run the
|
||||
holds, worded as for `//record_refund`; and for an order or a balance that changed meanwhile. Run the
|
||||
command again after the last three.
|
||||
|
||||
## Balances and failed orders in the group
|
||||
|
||||
With `[group]`, the group's owners run the same three commands while the service runs, with one
|
||||
slash:
|
||||
|
||||
```
|
||||
/balance <reference>
|
||||
/record_refund <reference> <cents>
|
||||
/close <reference>
|
||||
```
|
||||
|
||||
The service answers each in the group with the console's answer, which names `/record_refund` and
|
||||
`/close` in place of `//record_refund` and `//close`, and says that the running poller closes an
|
||||
overdue holder rather than asking to start the service. A command takes the same per-name and
|
||||
per-balance locks as Try again, moves and spends, and writes a balance only while it still holds the
|
||||
amount read and no order holds it, so a payment settled or an invoice cancelled meanwhile makes it
|
||||
refuse rather than write. The group's commands run one at a time, so a `/close` waiting on a slow
|
||||
chain node delays the group's other replies by up to its three reads' timeouts. `/close` reads the chain through the client the console uses, made at
|
||||
start with `[names]`, and without `[names]` answers that names are not enabled.
|
||||
|
||||
A member below owner gets no reply and nothing runs; a malformed command from an owner gets the usage
|
||||
reply. The reference and the answer, with the orders and invoice ids that paid, are read by every
|
||||
member and kept in the service's chat database, as codes are, so the group's members must be people
|
||||
who may see them. A command the service received but had not run when it stopped is dropped with no
|
||||
reply; run it again.
|
||||
|
||||
## Running the webapp's cases against the service
|
||||
|
||||
`scripts/store-service/dev/contract-run.sh` runs the names webapp's end-to-end cases that need no
|
||||
|
||||
@@ -105,8 +105,8 @@ How a request flows:
|
||||
| In-memory coordination | Waiters: invoice status and payments. Phases: registration versions. Locks: one writer at a time per label hash, prepaid code and balance. Read hints: up to 256 webhook reads queued for the poller. | [`Waiters.hs:14-91`](../src/StoreService/Waiters.hs#L14-L91), [`Names/Phases.hs:15-65`](../src/StoreService/Names/Phases.hs#L15-L65), [`Names/Turns.hs:3-69`](../src/StoreService/Names/Turns.hs#L3-L69), [`Poller.hs:88-108`](../src/StoreService/Poller.hs#L88-L108) |
|
||||
| Chat core | The SimpleX chat controller with the bot user: the bot address for badge requests, the managed group's messages, and connect plans for link profiles. Every chat event is read from `outputQ` by one reader. | [`Service.hs:293-313`](../src/StoreService/Service.hs#L293-L313), [`Service.hs:636-645`](../src/StoreService/Service.hs#L636-L645), [`Names/Profiles.hs:269-274`](../src/StoreService/Names/Profiles.hs#L269-L274) |
|
||||
| Badge request lanes | Badge requests on the bot address, present before this PR: three lanes, each answer sent as `APISendServiceResponse`. | [`Service.hs:572-657`](../src/StoreService/Service.hs#L572-L657) |
|
||||
| Group lane | With `[group]`: one managed group. `/issue`, `/issue name` included, and `/bulk` are taken from moderators, `/revoke` from admins; `/bulk` issues badge codes only. A name code command is refused once the name codes the group issued in the last 24 hours would pass 10. Once the first promotion was attempted, every joiner waits for a moderator's review, decided when the join request arrives. | [`Group.hs:89-340`](../src/StoreService/Group.hs#L89-L340), [`Group/Command.hs:58-71`](../src/StoreService/Group/Command.hs#L58-L71), [`Group/Command.hs:220-224`](../src/StoreService/Group/Command.hs#L220-L224) |
|
||||
| Console | The same binary under `--run-cli`, while the service is stopped: the terminal chat and the badge request lanes only, with `//issue`, `//issue name`, `//revoke`, `//refund` and `//close`. `//close` reads the chain through a client of its own, made at start with `[names]`. | [`Main.hs:25-28`](../Main.hs#L25-L28), [`Service.hs:383-540`](../src/StoreService/Service.hs#L383-L540) |
|
||||
| Group lane | With `[group]`: one managed group. `/issue`, `/issue name` included, and `/bulk` are taken from moderators, `/revoke` from admins, `/balance`, `/record_refund` and `/close` from owners; `/bulk` issues badge codes only. A name code command is refused once the name codes the group issued in the last 24 hours would pass 10. `/balance`, `/record_refund` and `/close` run the console's handlers in the service's locks, with the console's chain client. Once the first promotion was attempted, every joiner waits for a moderator's review, decided when the join request arrives. | [`Group.hs:89-341`](../src/StoreService/Group.hs#L89-L341), [`Group/Command.hs:66-79`](../src/StoreService/Group/Command.hs#L66-L79), [`Group/Command.hs:243-250`](../src/StoreService/Group/Command.hs#L243-L250), [`Service.hs:453-467`](../src/StoreService/Service.hs#L453-L467) |
|
||||
| Console | The same binary under `--run-cli`, while the service is stopped: the terminal chat and the badge request lanes only, with `//issue`, `//issue name`, `//revoke`, `//balance`, `//record_refund` and `//close`. `//close` reads the chain through a client of its own, made at start with `[names]`. | [`Main.hs:25-28`](../Main.hs#L25-L28), [`Service.hs:385-576`](../src/StoreService/Service.hs#L385-L576) |
|
||||
| PostgreSQL | One database (`BADGE_DB_CONN`) with the chat core's schema and the `sx_badge_service_` tables. Names tables: prepaid codes, registrations, balances, name invoices, late credits, record edits and their changes, transactions, terms texts. Partial unique indexes admit one active order (`live = 1`) per commitment and per owner and label hash. | [`Store/Postgres/Migrations.hs:276-479`](../src/StoreService/Store/Postgres/Migrations.hs#L276-L479), [`compose.yml:16`](../../../scripts/store-service/compose.yml#L16) |
|
||||
| Names page | simplex.domains, in the submodule `apps/simplex-domains`, outside this checkout. `/api/*` is called on its own origin, and the owner's EIP-191 and EIP-712 signatures are sent from it. | [`.gitmodules:4-7`](../../../.gitmodules#L4-L7), [`Web/Names.hs:28-44`](../src/StoreService/Web/Names.hs#L28-L44) |
|
||||
| BTCPay | Bitcoin and Monero invoices through Greenfield: create, read, list, cancel (status `Invalid`), store rates; webhooks signed with `BTCPay-Sig`. | [`Providers/BTCPay.hs:267-367`](../src/StoreService/Providers/BTCPay.hs#L267-L367), [`Providers/BTCPay.hs:524-538`](../src/StoreService/Providers/BTCPay.hs#L524-L538), [`Providers/BTCPay.hs:555-578`](../src/StoreService/Providers/BTCPay.hs#L555-L578) |
|
||||
@@ -506,10 +506,10 @@ sequenceDiagram
|
||||
participant D as PostgreSQL
|
||||
B--)O: asks for a refund with the order's reference (outside the service)
|
||||
Note over O,C: the service is stopped, then run with --run-cli
|
||||
O->>C: //refund REFERENCE
|
||||
O->>C: //balance REFERENCE
|
||||
C->>D: order, balance, hold, the orders its money came through
|
||||
C-->>O: balance, credited, refunded, paid by, the command to record it
|
||||
O->>C: //refund REFERENCE CENTS
|
||||
O->>C: //record_refund REFERENCE CENTS
|
||||
C->>D: under the balance's lock: amount 0, refunded raised by the cents
|
||||
C-->>O: Recorded a refund ... Refund it now, by: ORDERS.
|
||||
O--)B: money paid back by hand (outside the service)
|
||||
@@ -517,9 +517,10 @@ sequenceDiagram
|
||||
|
||||
Notes:
|
||||
|
||||
- The refund must equal the whole balance, and a held balance is refused, overdue or not. `//refund` closes no holder: its answer asks support to start the service, whose poller closes an overdue holder 10 minutes after its expiry, then to run the command again ([`Names/Balances.hs:40-65`](../src/StoreService/Names/Balances.hs#L40-L65), [`Names/Store.hs:1046-1056`](../src/StoreService/Names/Store.hs#L1046-L1056), [`Service.hs:532-540`](../src/StoreService/Service.hs#L532-L540)).
|
||||
- The refund must equal the whole balance, and a held balance is refused, overdue or not. `//record_refund` closes no holder: its answer asks support to start the service, whose poller closes an overdue holder 10 minutes after its expiry, then to run the command again ([`Names/Balances.hs:40-65`](../src/StoreService/Names/Balances.hs#L40-L65), [`Names/Store.hs:1046-1056`](../src/StoreService/Names/Store.hs#L1046-L1056), [`Service.hs:537-549`](../src/StoreService/Service.hs#L537-L549)).
|
||||
- The provider interface offers create, read, cancel, list, rate and webhook verification, so the money is paid back by hand ([`Providers.hs:120-130`](../src/StoreService/Providers.hs#L120-L130)). The buyer's email to chat@simplex.chat is described in the README; the page code is in the submodule ([`README.md:1371-1411`](../README.md#L1371-L1411)).
|
||||
- The console starts only while the service is stopped, as the database lock is held by one process ([`Store/Migrate.hs:46-54`](../src/StoreService/Store/Migrate.hs#L46-L54)).
|
||||
- While the service runs, a group owner sends the same commands with one slash, `/balance`, `/record_refund` and `/close`. The group lane runs the console's handlers in the service's per-name and per-balance locks and answers in the group; the answers name the one-slash commands, and a held balance's answer names the running poller ([`Service.hs:453-467`](../src/StoreService/Service.hs#L453-L467), [`Group.hs:320`](../src/StoreService/Group.hs#L320)).
|
||||
|
||||
A failed paid order has no balance until it is closed. Support closes it with `//close`, which checks the chain first and records the refund in the same transaction that ends the order.
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ where
|
||||
|
||||
import StoreService.Codes (issueFailedText, issueOneCode, revokeBadgeCode, singleUse)
|
||||
import StoreService.Config (GroupConfig (..))
|
||||
import StoreService.Group.Command (CmdAction (..), GroupCmd (..), groupCmdAction, groupCommands)
|
||||
import StoreService.Group.Command (CmdAction (..), GroupCmd (..), MoneyCmd, groupCmdAction, groupCommands)
|
||||
import StoreService.Names.Codes (issueNameCode, revokeNameCode)
|
||||
import StoreService.Names.Store (CodeIssuer (..), groupNameCodesIssuedSince)
|
||||
import StoreService.Names.Turns (Turns)
|
||||
@@ -229,8 +229,8 @@ coalesceTrackerRefreshes = snd . foldr keepLast (S.empty, [])
|
||||
logUncaught :: HasCallStack => IO () -> IO ()
|
||||
logUncaught a = a `catchOwn'` withFrozenCallStack (logError . tshow)
|
||||
|
||||
handleGroupEvent :: ChatController -> Turns -> Bool -> GroupId -> GroupEvent -> IO ()
|
||||
handleGroupEvent cc turns namesOn groupId ev = logUncaught (handle ev)
|
||||
handleGroupEvent :: ChatController -> Turns -> Bool -> (MoneyCmd -> IO (Either Text Text)) -> GroupId -> GroupEvent -> IO ()
|
||||
handleGroupEvent cc turns namesOn runMoney groupId ev = logUncaught (handle ev)
|
||||
where
|
||||
handle = \case
|
||||
GEInGroup gid action
|
||||
@@ -239,7 +239,7 @@ handleGroupEvent cc turns namesOn groupId ev = logUncaught (handle ev)
|
||||
GAJoined -> promoteOwner cc groupId
|
||||
GAProfileUpdated -> restoreServiceProfile cc groupId
|
||||
GACommand role t -> case groupCmdAction role t of
|
||||
RunCmd cmd -> runGroupCmd cc turns namesOn groupId cmd
|
||||
RunCmd cmd -> runGroupCmd cc turns namesOn runMoney groupId cmd
|
||||
ReplyText txt -> void $ sendGroupText cc groupId "command reply" txt
|
||||
IgnoreMsg -> pure ()
|
||||
GETracker badgeCodeId code -> updateTracker cc groupId badgeCodeId code
|
||||
@@ -257,15 +257,15 @@ promoteFirstOwner cc g@GroupInfo {groupId, groupProfile} member =
|
||||
_ -> pure ()
|
||||
|
||||
-- Nothing is a group that is not served, so its events are drained.
|
||||
runGroupLane :: ChatController -> Turns -> Bool -> TQueue GroupEvent -> Maybe GroupId -> IO ()
|
||||
runGroupLane cc turns namesOn q groupId_ = case groupId_ of
|
||||
runGroupLane :: ChatController -> Turns -> Bool -> (MoneyCmd -> IO (Either Text Text)) -> TQueue GroupEvent -> Maybe GroupId -> IO ()
|
||||
runGroupLane cc turns namesOn runMoney q groupId_ = case groupId_ of
|
||||
Just groupId -> do
|
||||
promoteOwner cc groupId
|
||||
-- Reconciling precedes the first batch, so queued events write after the correction.
|
||||
reconcileTrackers cc groupId
|
||||
forever $ do
|
||||
evs <- atomically $ (:) <$> readTQueue q <*> flushTQueue q
|
||||
mapM_ (handleGroupEvent cc turns namesOn groupId) (coalesceTrackerRefreshes evs)
|
||||
mapM_ (handleGroupEvent cc turns namesOn runMoney groupId) (coalesceTrackerRefreshes evs)
|
||||
Nothing -> forever $ void $ atomically (readTQueue q)
|
||||
|
||||
-- The earliest joined member is promoted, not the one who just joined, so a join the lane never handled
|
||||
@@ -295,8 +295,8 @@ noOwnerHint gName =
|
||||
"the badge group has no member owner, make one with /mr #" <> viewName gName <> " <member> owner in --run-cli mode"
|
||||
<> ", or a member pending review with /accept member #" <> viewName gName <> " @<member> owner in --run-cli mode"
|
||||
|
||||
runGroupCmd :: ChatController -> Turns -> Bool -> GroupId -> GroupCmd -> IO ()
|
||||
runGroupCmd cc turns namesOn groupId = \case
|
||||
runGroupCmd :: ChatController -> Turns -> Bool -> (MoneyCmd -> IO (Either Text Text)) -> GroupId -> GroupCmd -> IO ()
|
||||
runGroupCmd cc turns namesOn runMoney groupId = \case
|
||||
GCIssue bt months uses ->
|
||||
issueOneCode cc bt months CPSFree uses >>= \case
|
||||
Left _ -> reply issueFailedText
|
||||
@@ -317,6 +317,7 @@ runGroupCmd cc turns namesOn groupId = \case
|
||||
GCRevokeName code -> do
|
||||
outcome <- either id id <$> revokeNameCode turns cc code
|
||||
reply (formatNameCode (NCPrepaid code) <> ": " <> outcome)
|
||||
GCMoney cmd -> runMoney cmd >>= void . sendGroupText cc groupId "money reply, /balance shows what was recorded" . either id id
|
||||
where
|
||||
reply = void . sendGroupText cc groupId "reply, any codes in it are lost"
|
||||
withinNameCodes issue = do
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
module StoreService.Group.Command
|
||||
( GroupCmd (..),
|
||||
MoneyCmd (..),
|
||||
CmdAction (..),
|
||||
groupCmdAction,
|
||||
groupCommands,
|
||||
@@ -12,6 +13,9 @@ module StoreService.Group.Command
|
||||
badgeTypeP,
|
||||
nameCodeP,
|
||||
prepaidCodeP,
|
||||
balanceArgsP,
|
||||
recordRefundArgsP,
|
||||
closeArgsP,
|
||||
textTokenP,
|
||||
maxMonths,
|
||||
maxUses,
|
||||
@@ -47,6 +51,10 @@ data GroupCmd
|
||||
| GCIssueName Int Int
|
||||
| GCRevoke BadgeCode
|
||||
| GCRevokeName NamePrepaidCode
|
||||
| GCMoney MoneyCmd
|
||||
deriving (Eq, Show)
|
||||
|
||||
data MoneyCmd = MCBalance Text | MCRecordRefund Text Int | MCClose Text
|
||||
deriving (Eq, Show)
|
||||
|
||||
data CmdAction
|
||||
@@ -76,18 +84,22 @@ cmdArgsP = \case
|
||||
CTIssue -> uncurry GCIssueName <$> nameCodeP <|> GCIssue <$> badgeTypeP <*> optP monthsOpt <*> optP usesOpt
|
||||
CTBulk -> GCBulk <$> badgeTypeP <*> optP monthsOpt <*> countP
|
||||
CTRevoke -> GCRevoke <$> codeP <|> GCRevokeName <$> prepaidCodeP
|
||||
CTBalance -> GCMoney <$> balanceArgsP
|
||||
CTRecordRefund -> GCMoney <$> recordRefundArgsP
|
||||
CTClose -> GCMoney <$> closeArgsP
|
||||
where
|
||||
countP = A.space *> optValueP countOpt
|
||||
|
||||
-- | An option's keyword, its placeholder in the usage reply and its bounds; an omitted option takes the lowest value.
|
||||
data CmdOpt = CmdOpt {optKey :: Text, optVar :: Text, optMin :: Int, optMax :: Int}
|
||||
|
||||
lengthOpt, yearsOpt, monthsOpt, usesOpt, countOpt :: CmdOpt
|
||||
lengthOpt, yearsOpt, monthsOpt, usesOpt, countOpt, centsOpt :: CmdOpt
|
||||
lengthOpt = CmdOpt "length" "<length>" minNameLength maxNameLength
|
||||
yearsOpt = CmdOpt "years" "<Y>" minNameYears maxNameYears
|
||||
monthsOpt = CmdOpt "months" "<M>" 1 maxMonths
|
||||
usesOpt = CmdOpt "uses" "<N>" 1 maxUses
|
||||
countOpt = CmdOpt "count" "<N>" 1 maxBulk
|
||||
centsOpt = CmdOpt "cents" "<cents>" 1 maxBound
|
||||
|
||||
optP :: CmdOpt -> A.Parser Int
|
||||
optP opt = fromMaybe (optMin opt) <$> optional (A.space *> optValueP opt)
|
||||
@@ -120,6 +132,14 @@ prepaidCodeP =
|
||||
Just (NCPrepaid code) -> pure code
|
||||
_ -> fail "not a prepaid name code"
|
||||
|
||||
balanceArgsP, recordRefundArgsP, closeArgsP :: A.Parser MoneyCmd
|
||||
balanceArgsP = MCBalance <$> referenceP
|
||||
recordRefundArgsP = MCRecordRefund <$> referenceP <* A.space <*> boundedInt centsOpt
|
||||
closeArgsP = MCClose <$> referenceP
|
||||
|
||||
referenceP :: A.Parser Text
|
||||
referenceP = safeDecodeUtf8 <$> A.takeWhile1 (not . isSpace)
|
||||
|
||||
-- attoparsec's decimal wraps silently at Int, so the bound is checked on the wider Integer.
|
||||
boundedInt :: CmdOpt -> A.Parser Int
|
||||
boundedInt CmdOpt {optKey, optMin, optMax} = do
|
||||
@@ -147,7 +167,7 @@ textTokenP = do
|
||||
maybe (fail "invalid value") pure $ textDecode $ safeDecodeUtf8 t
|
||||
|
||||
-- The advertised menu lists the commands in this order.
|
||||
data CmdTag = CTIssue | CTBulk | CTRevoke
|
||||
data CmdTag = CTIssue | CTBulk | CTRevoke | CTBalance | CTRecordRefund | CTClose
|
||||
deriving (Bounded, Enum)
|
||||
|
||||
cmdName :: CmdTag -> Text
|
||||
@@ -155,12 +175,18 @@ cmdName = \case
|
||||
CTIssue -> "issue"
|
||||
CTBulk -> "bulk"
|
||||
CTRevoke -> "revoke"
|
||||
CTBalance -> "balance"
|
||||
CTRecordRefund -> "record_refund"
|
||||
CTClose -> "close"
|
||||
|
||||
cmdLabel :: CmdTag -> Text
|
||||
cmdLabel = \case
|
||||
CTIssue -> "Generate a code"
|
||||
CTBulk -> "Generate many codes"
|
||||
CTRevoke -> "Revoke a code"
|
||||
CTBalance -> "Show an order's balance"
|
||||
CTRecordRefund -> "Record a balance refund"
|
||||
CTClose -> "Close a failed order"
|
||||
|
||||
-- The menu hints and the usage replies are built from the same kinds, options and bounds, so they cannot drift apart.
|
||||
cmdParams :: CmdTag -> Text
|
||||
@@ -168,7 +194,11 @@ cmdParams = \case
|
||||
CTIssue -> kindParams (nameArg : badgeKinds) [yearsOpt, monthsOpt] <> " [" <> optArg usesOpt <> "]"
|
||||
CTBulk -> kindParams badgeKinds [monthsOpt] <> " " <> optArg countOpt
|
||||
CTRevoke -> "<code>"
|
||||
CTBalance -> referenceArg
|
||||
CTRecordRefund -> referenceArg <> " " <> optVar centsOpt
|
||||
CTClose -> referenceArg
|
||||
where
|
||||
referenceArg = "<reference>"
|
||||
kindParams kinds opts = "<" <> T.intercalate "|" kinds <> "> [" <> T.intercalate "|" (map optKey opts) <> " <N>]"
|
||||
|
||||
cmdUsage :: CmdTag -> Text
|
||||
@@ -180,8 +210,12 @@ cmdUsage = \case
|
||||
[(nameArg, [lengthOpt, yearsOpt]), (badgeKindsText, [monthsOpt, usesOpt])]
|
||||
["name 6 years 5", "supporter months 12"]
|
||||
CTBulk -> kindUsage CTBulk ("[" <> optArg monthsOpt <> "] " <> optArg countOpt) [(badgeKindsText, [monthsOpt, countOpt])] ["legend months 3 count 10"]
|
||||
CTRevoke -> "Usage: " <> cmdText CTRevoke (cmdParams CTRevoke)
|
||||
CTRevoke -> plainUsage CTRevoke
|
||||
CTBalance -> plainUsage CTBalance
|
||||
CTRecordRefund -> plainUsage CTRecordRefund
|
||||
CTClose -> plainUsage CTClose
|
||||
where
|
||||
plainUsage tag = "Usage: " <> cmdText tag (cmdParams tag)
|
||||
badgeKindsText = T.intercalate ", " badgeKinds
|
||||
|
||||
kindUsage :: CmdTag -> Text -> [(Text, [CmdOpt])] -> [Text] -> Text
|
||||
@@ -211,6 +245,9 @@ cmdMinRole = \case
|
||||
CTIssue -> GRModerator
|
||||
CTBulk -> GRModerator
|
||||
CTRevoke -> GRAdmin
|
||||
CTBalance -> GROwner
|
||||
CTRecordRefund -> GROwner
|
||||
CTClose -> GROwner
|
||||
|
||||
-- | This is the reply to a well-formed command from a sender who may not run it; Nothing means silence.
|
||||
cmdRefusal :: CmdTag -> Maybe Text
|
||||
@@ -219,3 +256,6 @@ cmdRefusal = \case
|
||||
CTBulk -> Nothing
|
||||
-- The sender has just published a code that stays redeemable, so they must learn it was not revoked.
|
||||
CTRevoke -> Just "Only admins can revoke codes. This code is now visible to all members."
|
||||
CTBalance -> Nothing
|
||||
CTRecordRefund -> Nothing
|
||||
CTClose -> Nothing
|
||||
@@ -39,6 +39,7 @@ module StoreService.Service
|
||||
survive,
|
||||
IssueCodeOpts (..),
|
||||
issueBadgeCode,
|
||||
CmdSource (..),
|
||||
heldText,
|
||||
chainText,
|
||||
)
|
||||
@@ -48,7 +49,7 @@ import StoreService.Catalog (StoreProduct (..), defaultCatalog, storeProduct)
|
||||
import StoreService.Codes (issueFailedText, issueOneCode, singleUse)
|
||||
import StoreService.Config (AppleStoreConfig (..), BadgeIssuerKey (..), ChainConfig (..), NamesConfig (..), PlayStoreConfig (..), ServiceConfig (..), minNameYears, readServiceConfig)
|
||||
import StoreService.Group (GroupEvent, ensureManagedGroup, fmtTime, groupEvent, hasTracker, joinerAcceptance, refreshTracker, revokeWithTracker, runGroupLane)
|
||||
import StoreService.Group.Command (badgeTypeP, codeP, maxMonths, maxNameYears, nameCodeP, prepaidCodeP, textTokenP)
|
||||
import StoreService.Group.Command (MoneyCmd (..), badgeTypeP, balanceArgsP, closeArgsP, codeP, maxMonths, maxNameYears, nameCodeP, prepaidCodeP, recordRefundArgsP, textTokenP)
|
||||
import StoreService.Names.Abi (hex)
|
||||
import StoreService.Names.Balances (RefundRecord (..), RefundRefusal (..), recordRefund)
|
||||
import StoreService.Names.Chain (ChainClient, newChainClient, nodeChainId)
|
||||
@@ -78,7 +79,7 @@ import StoreService.StoreReceipts.Mock (newMockStoreVerifier)
|
||||
import StoreService.Waiters (Waiters, newWaiters)
|
||||
import StoreService.Web.Http (Bucket, takeFrom)
|
||||
import StoreService.Web.Server (checkSiteDirs, exportWebapp, newWebEnv, runWebListeners)
|
||||
import Control.Applicative (optional)
|
||||
import Control.Applicative (optional, (<|>))
|
||||
import Control.Concurrent.STM
|
||||
import Control.Logger.Simple (logError, logNote, logWarn)
|
||||
import Control.Monad
|
||||
@@ -88,7 +89,6 @@ import qualified Data.Aeson.KeyMap as KM
|
||||
import qualified Data.Attoparsec.ByteString.Char8 as A
|
||||
import Data.Bifunctor (first)
|
||||
import Data.ByteString.Char8 (ByteString)
|
||||
import Data.Char (isSpace)
|
||||
import Data.Either (fromRight, isRight)
|
||||
import Data.Functor (($>), (<&>))
|
||||
import Data.Int (Int64)
|
||||
@@ -303,7 +303,7 @@ storeService opts serviceCfg baseCfg env = do
|
||||
startLanes cc = do
|
||||
lanes <- maybe (pure []) (serviceLanes waiters turns cc) serviceCfg
|
||||
-- The group is resolved before the other lanes start, so a failed lookup exits at once rather than waiting for them to end.
|
||||
groupLane_ <- forM groupCfg $ \gc -> runGroupLane cc turns namesOn (groupEventQ env) <$> ensureManagedGroup cc gc
|
||||
groupLane_ <- forM groupCfg $ \gc -> runGroupLane cc turns namesOn (runMoneyCmd FromGroup turns consoleChain cc) (groupEventQ env) <$> ensureManagedGroup cc gc
|
||||
raceAny_ $ processQueuedRequests key trackerQ_ requestEnv : maybeToList groupLane_ <> lanes
|
||||
chatHooks =
|
||||
defaultChatHooks
|
||||
@@ -429,13 +429,12 @@ runBadgeCmd turns chain_ cc cmd
|
||||
issuedReply (formatNameCode . NCPrepaid) <$> issueNameCode cc IssuedInConsole len years paymentStatus
|
||||
| Right code <- A.parseOnly revokeCmdP cmd = textReply <$> revokeWithTracker cc code
|
||||
| Right code <- A.parseOnly revokeNameCmdP cmd = textReply <$> revokeNameCode turns cc code
|
||||
| Right (ref, cents_) <- A.parseOnly refundCmdP cmd = textReply <$> maybe (showRefund cc ref) (refundBalanceCmd turns cc ref) cents_
|
||||
| Right ref <- A.parseOnly closeCmdP cmd = textReply <$> maybe (pure $ Left "Names are not enabled on this service.") (\chain -> closeOrderCmd turns chain cc ref) chain_
|
||||
| Right moneyCmd <- A.parseOnly moneyCmdP cmd = textReply <$> runMoneyCmd FromConsole turns chain_ cc moneyCmd
|
||||
| otherwise =
|
||||
pure $ chatCmdError $
|
||||
"Usage: //issue supporter|legend|investor [months 1-" <> show maxMonths <> "] [paid|unpaid|free], //issue name <length "
|
||||
<> show minNameLength <> "-" <> show maxNameLength <> "> [years " <> show minNameYears <> "-" <> show maxNameYears
|
||||
<> "] [paid|free], //revoke <code>, //refund <reference> [<cents>], or //close <reference>"
|
||||
<> "] [paid|free], //revoke <code>, //balance <reference>, //record_refund <reference> <cents>, or //close <reference>"
|
||||
where
|
||||
issuedReply :: (c -> T.Text) -> Either String c -> Either ChatError ChatResponse
|
||||
issuedReply format = \case
|
||||
@@ -451,23 +450,25 @@ revokeCmdP = "revoke " *> codeP <* (A.skipSpace *> A.endOfInput)
|
||||
revokeNameCmdP :: A.Parser NamePrepaidCode
|
||||
revokeNameCmdP = "revoke " *> prepaidCodeP <* (A.skipSpace *> A.endOfInput)
|
||||
|
||||
-- | The reference, and the cents of the balance to refund; without them the balance is shown.
|
||||
refundCmdP :: A.Parser (T.Text, Maybe Int)
|
||||
refundCmdP = do
|
||||
ref <- "refund " *> (safeDecodeUtf8 <$> A.takeWhile1 (not . isSpace))
|
||||
cents_ <- optional (A.space *> (A.decimal :: A.Parser Integer))
|
||||
A.skipSpace
|
||||
A.endOfInput
|
||||
(ref,) <$> mapM checkCents cents_
|
||||
where
|
||||
-- Integer, as in issueCmdP, so a figure past Int is refused rather than wrapped.
|
||||
checkCents n
|
||||
| n >= 1 && n <= toInteger (maxBound :: Int) = pure (fromInteger n)
|
||||
| otherwise = fail "cents out of range"
|
||||
moneyCmdP :: A.Parser MoneyCmd
|
||||
moneyCmdP = ("balance " *> balanceArgsP <|> "record_refund " *> recordRefundArgsP <|> "close " *> closeArgsP) <* (A.skipSpace *> A.endOfInput)
|
||||
|
||||
data CmdSource = FromConsole | FromGroup
|
||||
|
||||
runMoneyCmd :: CmdSource -> Turns -> Maybe (SimplexTLD, Int, ChainClient) -> ChatController -> MoneyCmd -> IO (Either T.Text T.Text)
|
||||
runMoneyCmd source turns chain_ cc = \case
|
||||
MCBalance ref -> showRefund source cc ref
|
||||
MCRecordRefund ref cents -> refundBalanceCmd source turns cc ref cents
|
||||
MCClose ref -> maybe (pure $ Left "Names are not enabled on this service.") (\chain -> closeOrderCmd source turns chain cc ref) chain_
|
||||
|
||||
spelledCmd :: CmdSource -> T.Text -> T.Text
|
||||
spelledCmd = \case
|
||||
FromConsole -> ("//" <>)
|
||||
FromGroup -> ("/" <>)
|
||||
|
||||
-- | Left is a refusal or a failure; both sides are the text to show the operator.
|
||||
showRefund :: ChatController -> T.Text -> IO (Either T.Text T.Text)
|
||||
showRefund cc ref = do
|
||||
showRefund :: CmdSource -> ChatController -> T.Text -> IO (Either T.Text T.Text)
|
||||
showRefund source cc ref = do
|
||||
now <- getCurrentTime
|
||||
withDB' "showRefund" cc (\db -> balanceByReference db ref now >>= mapM (withChain db)) <&> \case
|
||||
Right Nothing -> Left $ "No order has the reference " <> ref <> "."
|
||||
@@ -480,14 +481,14 @@ showRefund cc ref = do
|
||||
where
|
||||
withChain db (rid, balance_) = (rid,) <$> mapM (\balance -> (balance,) <$> balanceChain db rid) balance_
|
||||
nextStep Balance {blAmount, blHold} = case blHold of
|
||||
Just hold -> "It cannot be refunded now: " <> heldText hold <> "."
|
||||
Just hold -> "It cannot be refunded now: " <> heldText source hold <> "."
|
||||
Nothing
|
||||
| blAmount > 0 -> "To record its refund: //refund " <> ref <> " " <> tshow blAmount
|
||||
| blAmount > 0 -> "To record its refund: " <> spelledCmd source "record_refund" <> " " <> ref <> " " <> tshow blAmount
|
||||
| otherwise -> "Nothing to refund."
|
||||
|
||||
-- | The refund is recorded before support pays it, so the balance cannot be spent meanwhile.
|
||||
refundBalanceCmd :: Turns -> ChatController -> T.Text -> Int -> IO (Either T.Text T.Text)
|
||||
refundBalanceCmd turns ChatController {chatStore} ref cents = do
|
||||
refundBalanceCmd :: CmdSource -> Turns -> ChatController -> T.Text -> Int -> IO (Either T.Text T.Text)
|
||||
refundBalanceCmd source turns ChatController {chatStore} ref cents = do
|
||||
now <- getCurrentTime
|
||||
((Right <$> recordRefund turns chatStore ref cents now) `catchOwn` (pure . Left)) >>= \case
|
||||
Right (Right RefundRecord {rdRegistration = RegistrationId rid, rdCents, rdChain}) -> do
|
||||
@@ -501,18 +502,15 @@ refundBalanceCmd turns ChatController {chatStore} ref cents = do
|
||||
RefundNoOrder -> "no order has the reference " <> ref
|
||||
RefundNoBalance -> "the order of " <> ref <> " has no balance"
|
||||
RefundAmount amount -> "the balance is " <> dollars amount <> " now, not " <> dollars cents
|
||||
RefundHeld hold -> heldText hold
|
||||
|
||||
closeCmdP :: A.Parser T.Text
|
||||
closeCmdP = "close " *> (safeDecodeUtf8 <$> A.takeWhile1 (not . isSpace)) <* (A.skipSpace *> A.endOfInput)
|
||||
RefundHeld hold -> heldText source hold
|
||||
|
||||
newConsoleChain :: NamesConfig -> IO (SimplexTLD, Int, ChainClient)
|
||||
newConsoleChain NamesConfig {nTLD, nMinPriceCentsPerYear, nChain} = do
|
||||
chain <- C.newRandom >>= (`newChainClient` nChain)
|
||||
pure (nTLD, nMinPriceCentsPerYear, chain)
|
||||
|
||||
closeOrderCmd :: Turns -> (SimplexTLD, Int, ChainClient) -> ChatController -> T.Text -> IO (Either T.Text T.Text)
|
||||
closeOrderCmd turns (tld, minPriceCentsPerYear, chain) ChatController {chatStore} ref = do
|
||||
closeOrderCmd :: CmdSource -> Turns -> (SimplexTLD, Int, ChainClient) -> ChatController -> T.Text -> IO (Either T.Text T.Text)
|
||||
closeOrderCmd source turns (tld, minPriceCentsPerYear, chain) ChatController {chatStore} ref = do
|
||||
ct <- newContracts chatStore tld minPriceCentsPerYear chain
|
||||
((Right <$> closeRegistration chatStore ct turns getCurrentTime ref) `catchOwn` (pure . Left)) >>= \case
|
||||
Right (CLRefunded failedAt RefundRecord {rdRegistration = RegistrationId rid, rdCents, rdChain}) -> do
|
||||
@@ -521,7 +519,7 @@ closeOrderCmd turns (tld, minPriceCentsPerYear, chain) ChatController {chatStore
|
||||
"Closed order " <> rid <> maybe "" (\t -> ", failed at " <> fmtTime t <> ",") failedAt <> " as taken and recorded a refund of " <> dollars rdCents
|
||||
<> ". Check at the provider that it was not refunded by hand before; if not, refund it now, by: " <> chainText rdChain <> "."
|
||||
Right (CLRegistered (RegistrationId rid)) -> do
|
||||
logNote $ "names: order " <> rid <> " set registered by //close, as its register went through"
|
||||
logNote $ "names: order " <> rid <> " set registered by " <> spelledCmd source "close" <> ", as its register went through"
|
||||
pure $ Left $ "Nothing refunded: the register of order " <> rid <> " went through, so the order is registered now."
|
||||
Right (CLRefused refusal) -> pure $ Left $ "Nothing recorded: " <> refusalText refusal <> "."
|
||||
Left e -> Left "The order could not be closed." <$ logError ("names: closing an order failed: " <> tshow e)
|
||||
@@ -529,19 +527,24 @@ closeOrderCmd turns (tld, minPriceCentsPerYear, chain) ChatController {chatStore
|
||||
refusalText = \case
|
||||
CFNoOrder -> "no order has the reference " <> ref
|
||||
CFNotFailedPaid -> "the order of " <> ref <> " is not a failed order paid by invoice or balance"
|
||||
CFUnread -> "the chain could not be read; run //close again"
|
||||
CFChanged -> "the order of " <> ref <> " changed meanwhile; run //close again"
|
||||
CFWriteRefused _ -> "the order of " <> ref <> " could not be set taken; run //close again"
|
||||
CFHeld hold -> heldText hold
|
||||
CFBalanceChanged -> "the balance of the order of " <> ref <> " changed meanwhile; run //close again"
|
||||
CFUnread -> "the chain could not be read; " <> again
|
||||
CFChanged -> "the order of " <> ref <> " changed meanwhile; " <> again
|
||||
CFWriteRefused _ -> "the order of " <> ref <> " could not be set taken; " <> again
|
||||
CFHeld hold -> heldText source hold
|
||||
CFBalanceChanged -> "the balance of the order of " <> ref <> " changed meanwhile; " <> again
|
||||
again = "run " <> spelledCmd source "close" <> " again"
|
||||
|
||||
heldText :: BalanceHold -> T.Text
|
||||
heldText BalanceHold {bhHolder = RegistrationId holder, bhUntil, bhOverdue, bhFunded}
|
||||
| bhOverdue = heldBy <> "its invoice expired at " <> fmtTime bhUntil <> "; start the service so the poller closes that order, " <> tshow graceMinutes <> " minutes after the expiry at the earliest, then stop it and run the command again"
|
||||
heldText :: CmdSource -> BalanceHold -> T.Text
|
||||
heldText source BalanceHold {bhHolder = RegistrationId holder, bhUntil, bhOverdue, bhFunded}
|
||||
| bhOverdue = heldBy <> "its invoice expired at " <> fmtTime bhUntil <> "; " <> closedByPoller
|
||||
| bhFunded = heldBy <> "whose invoice holds money; it holds until that payment settles or the invoice closes; run the command again then"
|
||||
| otherwise = heldBy <> "its invoice open until " <> fmtTime bhUntil <> "; run the command again then"
|
||||
where
|
||||
heldBy = "held by order " <> holder <> ", "
|
||||
closedByPoller = case source of
|
||||
FromConsole -> "start the service so the poller closes that order, " <> afterGrace <> ", then stop it and run the command again"
|
||||
FromGroup -> "the poller closes that order " <> afterGrace <> "; run the command again then"
|
||||
afterGrace = tshow graceMinutes <> " minutes after the expiry at the earliest"
|
||||
graceMinutes = round (expiryGrace / minute) :: Int
|
||||
minute = 60 :: NominalDiffTime
|
||||
|
||||
|
||||
@@ -1885,7 +1885,7 @@ testRevokeRejectsTrailingInput ps =
|
||||
|
||||
-- The text is spelled out rather than taken from the service, so a change there fails here.
|
||||
badgeCmdUsage :: Text
|
||||
badgeCmdUsage = "Usage: //issue supporter|legend|investor [months 1-255] [paid|unpaid|free], //issue name <length 6-63> [years 2-10] [paid|free], //revoke <code>, //refund <reference> [<cents>], or //close <reference>"
|
||||
badgeCmdUsage = "Usage: //issue supporter|legend|investor [months 1-255] [paid|unpaid|free], //issue name <length 6-63> [years 2-10] [paid|free], //revoke <code>, //balance <reference>, //record_refund <reference> <cents>, or //close <reference>"
|
||||
|
||||
purchaseCmd :: BadgeMasterKey -> ServicePayment -> StoreServiceCommand
|
||||
purchaseCmd masterKey payment = STCPurchaseBadge {masterKey, payment, upgrade = Nothing}
|
||||
|
||||
@@ -12,7 +12,7 @@ module Bots.StoreService.GroupIntegrationTests (badgeGroupIntegrationTests, name
|
||||
|
||||
import StoreService.Config (BadgeIssuerKey (..), ChainConfig (cController, cServiceKey), GroupConfig (..), NamesConfig (nChain), ServiceConfig (devAcceptUnverifiedStoreReceipts, names), readServiceConfig)
|
||||
import StoreService.Group (GroupAction (..), GroupEvent (..), codeInTracker, ensureManagedGroup, joinerAcceptance)
|
||||
import StoreService.Group.Command (CmdAction (..), groupCmdAction, maxUses)
|
||||
import StoreService.Group.Command (maxUses)
|
||||
import StoreService.Names.Abi (addressWord, selector, uint256)
|
||||
import StoreService.Names.Codes (issueNameCode, reserveCode, revokeNameCode)
|
||||
import StoreService.Names.Phases (RegistrationId (..))
|
||||
@@ -514,12 +514,15 @@ namesRefundChatTests = describe "StoreService names: operator refund" $ do
|
||||
it "shows a balance with what paid for it, and records refunds by registration or invoice id, adding them up" testRefundRecorded
|
||||
it "refuses an unknown reference, an order without a balance and another amount, and answers the usage to a malformed command" testRefundRefusals
|
||||
it "refuses a balance held by an open order, naming it and its expiry, and records it once that order's invoice is cancelled" testRefundOpenHolder
|
||||
it "is not a group command" $ \_ -> groupCmdAction GROwner "/refund s 10000" `shouldBe` IgnoreMsg
|
||||
it "answers an owner's /balance, /record_refund and /close in the group, worded for the group, refusing as the console does" testGroupMoneyCmds
|
||||
it "closes a failed paid order by its invoice id, recording the refund of its price, and refuses an unknown reference and an order no longer failed" testCloseRecorded
|
||||
it "refuses //close without [names], and answers the usage to a malformed one" testCloseNamesOff
|
||||
|
||||
refundRaw :: HasCallStack => ChatController -> Text -> IO (Either Text Text)
|
||||
refundRaw cc args = operatorCmd cc ("//refund " <> args)
|
||||
balanceRaw :: HasCallStack => ChatController -> Text -> IO (Either Text Text)
|
||||
balanceRaw cc args = operatorCmd cc ("//balance " <> args)
|
||||
|
||||
recordRefundRaw :: HasCallStack => ChatController -> Text -> IO (Either Text Text)
|
||||
recordRefundRaw cc args = operatorCmd cc ("//record_refund " <> args)
|
||||
|
||||
closeRaw :: HasCallStack => ChatController -> Text -> IO (Either Text Text)
|
||||
closeRaw cc args = operatorCmd cc ("//close " <> args)
|
||||
@@ -549,7 +552,7 @@ testCloseRecorded ps = withFakeEthNode $ \node@FakeEthNode {fnUrl} -> do
|
||||
logs `shouldSatisfy` T.isInfixOf "names: closed order f and recorded a refund of 10000 cents"
|
||||
closeRaw cc "f" `shouldReturn` Left "Nothing recorded: the order of f is not a failed order paid by invoice or balance."
|
||||
Balances.figures st "f" t0 `shouldReturn` Just (0, 10000, 10000, Nothing)
|
||||
refundRaw cc "f" `shouldReturn` Right ("Order f: balance $0.00 (credited $100.00, refunded $100.00). Paid by: " <> paidBy <> ". Nothing to refund.")
|
||||
balanceRaw cc "f" `shouldReturn` Right ("Order f: balance $0.00 (credited $100.00, refunded $100.00). Paid by: " <> paidBy <> ". Nothing to refund.")
|
||||
Balances.placeOrderRow st "g" False 10000 (addUTCTime 3600 now)
|
||||
unpaidG <- reg st "g"
|
||||
write st unpaidG {nrPhase = PFailed, nrFailedAt = Just t0} `shouldReturn` Written 2
|
||||
@@ -559,6 +562,27 @@ testCloseRecorded ps = withFakeEthNode $ \node@FakeEthNode {fnUrl} -> do
|
||||
registeredLogs `shouldSatisfy` T.isInfixOf "names: order g set registered by //close, as its register went through"
|
||||
Balances.figures st "g" t0 `shouldReturn` Nothing
|
||||
|
||||
testGroupMoneyCmds :: HasCallStack => TestParams -> IO ()
|
||||
testGroupMoneyCmds ps = withFakeEthNode $ \node@FakeEthNode {fnUrl} -> do
|
||||
svc <- prepareGroupService ps
|
||||
let registrar = address $ encodeUtf8 registrarAddr
|
||||
runWithOwner svc {gsIniSections = "" : namesSection <> withRpcUrl (T.pack fnUrl)} $ \cc _ _ alice -> do
|
||||
let st = chatStore cc
|
||||
now <- getCurrentTime
|
||||
Balances.placeOrderRow st "s" False 10000 (addUTCTime 3600 now)
|
||||
unpaid <- reg st "s"
|
||||
write st unpaid {nrPhase = PFailed, nrFailedAt = Just t0} `shouldReturn` Written 2
|
||||
answerCall node registrar (ownerOfSelector <> labelBytes "s") $ Reverts ""
|
||||
replyTo cc alice "/close nothing" `shouldReturn` "Nothing recorded: no order has the reference nothing."
|
||||
replyTo cc alice "/close inv-s"
|
||||
`shouldReturn` ("Closed order s, failed at " <> minuteText t0 <> ", as taken and recorded a refund of $100.00. Check at the provider that it was not refunded by hand before; if not, refund it now, by: order s: $100.00 by btc on invoice inv-s.")
|
||||
Balances.credit st "s" 2505
|
||||
replyTo cc alice "/balance s"
|
||||
`shouldReturn` "Order s: balance $25.05 (credited $125.05, refunded $100.00). Paid by: order s: $100.00 by btc on invoice inv-s. To record its refund: /record_refund s 2505"
|
||||
replyTo cc alice "/record_refund inv-s 2500" `shouldReturn` "Nothing recorded: the balance is $25.05 now, not $25.00."
|
||||
replyTo cc alice "/record_refund inv-s 2505" `shouldReturn` "Recorded a refund of $25.05 for order s. Refund it now, by: order s: $100.00 by btc on invoice inv-s."
|
||||
Balances.figures st "s" t0 `shouldReturn` Just (0, 12505, 12505, Nothing)
|
||||
|
||||
testCloseNamesOff :: HasCallStack => TestParams -> IO ()
|
||||
testCloseNamesOff ps = withStoreService ps $ \_ _ cc -> do
|
||||
Balances.source (chatStore cc) "s" 10000
|
||||
@@ -574,13 +598,13 @@ testRefundRecorded ps = withStoreService ps $ \_ _ cc -> do
|
||||
let st = chatStore cc
|
||||
paidBy = "order s: $100.00 by btc on invoice inv-s"
|
||||
Balances.source st "s" 10000
|
||||
refundRaw cc "inv-s" `shouldReturn` Right ("Order s: balance $100.00 (credited $100.00, refunded $0.00). Paid by: " <> paidBy <> ". To record its refund: //refund inv-s 10000")
|
||||
logs <- capturingStderr $ refundRaw cc "inv-s 10000" `shouldReturn` Right ("Recorded a refund of $100.00 for order s. Refund it now, by: " <> paidBy <> ".")
|
||||
balanceRaw cc "inv-s" `shouldReturn` Right ("Order s: balance $100.00 (credited $100.00, refunded $0.00). Paid by: " <> paidBy <> ". To record its refund: //record_refund inv-s 10000")
|
||||
logs <- capturingStderr $ recordRefundRaw cc "inv-s 10000" `shouldReturn` Right ("Recorded a refund of $100.00 for order s. Refund it now, by: " <> paidBy <> ".")
|
||||
logs `shouldSatisfy` T.isInfixOf "names: recorded a refund of 10000 cents for order s"
|
||||
Balances.figures st "s" t0 `shouldReturn` Just (0, 10000, 10000, Nothing)
|
||||
refundRaw cc "inv-s" `shouldReturn` Right ("Order s: balance $0.00 (credited $100.00, refunded $100.00). Paid by: " <> paidBy <> ". Nothing to refund.")
|
||||
balanceRaw cc "inv-s" `shouldReturn` Right ("Order s: balance $0.00 (credited $100.00, refunded $100.00). Paid by: " <> paidBy <> ". Nothing to refund.")
|
||||
Balances.credit st "s" 2505
|
||||
refundRaw cc "s 2505" `shouldReturn` Right ("Recorded a refund of $25.05 for order s. Refund it now, by: " <> paidBy <> ".")
|
||||
recordRefundRaw cc "s 2505" `shouldReturn` Right ("Recorded a refund of $25.05 for order s. Refund it now, by: " <> paidBy <> ".")
|
||||
Balances.figures st "s" t0 `shouldReturn` Just (0, 12505, 12505, Nothing)
|
||||
|
||||
testRefundRefusals :: HasCallStack => TestParams -> IO ()
|
||||
@@ -588,14 +612,16 @@ testRefundRefusals ps = withStoreService ps $ \_ _ cc -> do
|
||||
let st = chatStore cc
|
||||
Balances.placeOrderRow st "plain" False 20000 t0
|
||||
Balances.source st "s" 10000
|
||||
refundRaw cc "nothing" `shouldReturn` Left "No order has the reference nothing."
|
||||
refundRaw cc "nothing 10000" `shouldReturn` Left "Nothing recorded: no order has the reference nothing."
|
||||
refundRaw cc "inv-plain" `shouldReturn` Left "Order plain has no balance."
|
||||
refundRaw cc "inv-plain 20000" `shouldReturn` Left "Nothing recorded: the order of inv-plain has no balance."
|
||||
refundRaw cc "s 9000" `shouldReturn` Left "Nothing recorded: the balance is $100.00 now, not $90.00."
|
||||
refundRaw cc "s 10001" `shouldReturn` Left "Nothing recorded: the balance is $100.00 now, not $100.01."
|
||||
forM_ ["", "s 0", "s -5", "s 100.00", "s 10000 junk", "s 99999999999999999999"] $ \args ->
|
||||
(args,) <$> refundRaw cc args `shouldReturn` (args, Left badgeCmdUsage)
|
||||
balanceRaw cc "nothing" `shouldReturn` Left "No order has the reference nothing."
|
||||
recordRefundRaw cc "nothing 10000" `shouldReturn` Left "Nothing recorded: no order has the reference nothing."
|
||||
balanceRaw cc "inv-plain" `shouldReturn` Left "Order plain has no balance."
|
||||
recordRefundRaw cc "inv-plain 20000" `shouldReturn` Left "Nothing recorded: the order of inv-plain has no balance."
|
||||
recordRefundRaw cc "s 9000" `shouldReturn` Left "Nothing recorded: the balance is $100.00 now, not $90.00."
|
||||
recordRefundRaw cc "s 10001" `shouldReturn` Left "Nothing recorded: the balance is $100.00 now, not $100.01."
|
||||
forM_ ["", "s", "s 0", "s -5", "s 100.00", "s 10000 junk", "s 99999999999999999999"] $ \args ->
|
||||
(args,) <$> recordRefundRaw cc args `shouldReturn` (args, Left badgeCmdUsage)
|
||||
forM_ ["", "s 10000"] $ \args -> (args,) <$> balanceRaw cc args `shouldReturn` (args, Left badgeCmdUsage)
|
||||
operatorCmd cc "//refund s 10000" `shouldReturn` Left badgeCmdUsage
|
||||
Balances.figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Nothing)
|
||||
|
||||
-- | The source with a balance of $100.00 and the holder holding it, whose invoice expires at the given time.
|
||||
@@ -606,8 +632,8 @@ heldSource cc src holder expiry = do
|
||||
|
||||
heldRefusals :: HasCallStack => ChatController -> Text -> Text -> IO ()
|
||||
heldRefusals cc src held = do
|
||||
refundRaw cc src `shouldReturn` Right ("Order " <> src <> ": balance $100.00 (credited $100.00, refunded $0.00). Paid by: order " <> src <> ": $100.00 by btc on invoice inv-" <> src <> ". It cannot be refunded now: " <> held <> ".")
|
||||
refundRaw cc ("inv-" <> src <> " 10000") `shouldReturn` Left ("Nothing recorded: " <> held <> ".")
|
||||
balanceRaw cc src `shouldReturn` Right ("Order " <> src <> ": balance $100.00 (credited $100.00, refunded $0.00). Paid by: order " <> src <> ": $100.00 by btc on invoice inv-" <> src <> ". It cannot be refunded now: " <> held <> ".")
|
||||
recordRefundRaw cc ("inv-" <> src <> " 10000") `shouldReturn` Left ("Nothing recorded: " <> held <> ".")
|
||||
Balances.figures (chatStore cc) src t0 >>= (`shouldSatisfy` \case Just (10000, 10000, 0, Just _) -> True; _ -> False)
|
||||
|
||||
recordedS :: Either Text Text
|
||||
@@ -621,7 +647,7 @@ testRefundOpenHolder ps = withStoreService ps $ \_ _ cc -> do
|
||||
heldRefusals cc "s" $ "held by order h, its invoice open until " <> minuteText expiry <> "; run the command again then"
|
||||
waiters <- newWaiters
|
||||
cancelOpenInvoice (chatStore cc) waiters Nothing (InvoiceId "inv-h") now `shouldReturn` True
|
||||
refundRaw cc "s 10000" `shouldReturn` recordedS
|
||||
recordRefundRaw cc "s 10000" `shouldReturn` recordedS
|
||||
|
||||
data TurnHolder a = TurnHolder {thAction :: Async a, thRelease :: MVar ()}
|
||||
|
||||
@@ -1807,7 +1833,10 @@ expectedCommands :: [ChatBotCommand]
|
||||
expectedCommands =
|
||||
[ CBCCommand "issue" "Generate a code" (Just "<name <length>|supporter|legend|investor> [years|months <N>] [uses <N>]"),
|
||||
CBCCommand "bulk" "Generate many codes" (Just "<supporter|legend|investor> [months <N>] count <N>"),
|
||||
CBCCommand "revoke" "Revoke a code" (Just "<code>")
|
||||
CBCCommand "revoke" "Revoke a code" (Just "<code>"),
|
||||
CBCCommand "balance" "Show an order's balance" (Just "<reference>"),
|
||||
CBCCommand "record_refund" "Record a balance refund" (Just "<reference> <cents>"),
|
||||
CBCCommand "close" "Close a failed order" (Just "<reference>")
|
||||
]
|
||||
|
||||
advertisedCommands :: HasCallStack => ChatController -> Int64 -> IO (Maybe [ChatBotCommand])
|
||||
|
||||
@@ -116,6 +116,19 @@ badgeGroupTests = describe "badge group" $ do
|
||||
it "runs a name code command for a moderator and above, saying nothing to a member" $ do
|
||||
map (`groupCmdAction` "/issue name 6") [GRMember, GRModerator, GRAdmin, GROwner]
|
||||
`shouldBe` [IgnoreMsg, RunCmd (GCIssueName 6 2), RunCmd (GCIssueName 6 2), RunCmd (GCIssueName 6 2)]
|
||||
it "runs /balance, /record_refund and /close only for an owner, saying nothing to others" $ do
|
||||
let roles = [GRMember, GRModerator, GRAdmin, GROwner]
|
||||
ownerOnly cmd = replicate 3 IgnoreMsg <> [RunCmd (GCMoney cmd)]
|
||||
map (`groupCmdAction` "/balance s") roles `shouldBe` ownerOnly (MCBalance "s")
|
||||
map (`groupCmdAction` "/record_refund inv-s 10000") roles `shouldBe` ownerOnly (MCRecordRefund "inv-s" 10000)
|
||||
map (`groupCmdAction` "/close inv-f") roles `shouldBe` ownerOnly (MCClose "inv-f")
|
||||
groupCmdAction GRAdmin "/record_refund s" `shouldBe` IgnoreMsg
|
||||
p "/refund s 10000" `shouldBe` IgnoreMsg
|
||||
it "answers a malformed /balance, /record_refund or /close with its usage" $
|
||||
map p ["/balance", "/balance s junk", "/record_refund s", "/record_refund s 0", "/record_refund s -5", "/record_refund s 100.00", "/record_refund s 99999999999999999999", "/close", "/close s junk"]
|
||||
`shouldBe` replicate 2 (ReplyText "Usage: /balance <reference>")
|
||||
<> replicate 5 (ReplyText "Usage: /record_refund <reference> <cents>")
|
||||
<> replicate 2 (ReplyText "Usage: /close <reference>")
|
||||
it "accepts a command padded with whitespace" $ do
|
||||
p " /issue supporter " `shouldBe` RunCmd (GCIssue BTSupporter 1 1)
|
||||
p "\t/bulk supporter count 1" `shouldBe` RunCmd (GCBulk BTSupporter 1 1)
|
||||
|
||||
@@ -37,7 +37,7 @@ import StoreService.Names.Store
|
||||
import StoreService.Names.Turns (balanceTurnCount, newTurns, turnsCount, withBalanceTurn, withLabelTurn)
|
||||
import StoreService.Orders (cancelOpenInvoice, expireOverdue, settleOrder)
|
||||
import StoreService.Poller (cleanupUnpaid, newPollerEnv, unpaidRetention)
|
||||
import StoreService.Service (chainText, heldText)
|
||||
import StoreService.Service (CmdSource (..), chainText, heldText)
|
||||
import StoreService.Providers (Funded (..), PaymentSignal (..))
|
||||
import StoreService.Waiters (newWaiters)
|
||||
import StoreService.Web.Server (WebEnv (..))
|
||||
@@ -580,9 +580,11 @@ testRecordRefund = withServiceStore $ \st -> do
|
||||
|
||||
testHeldText :: IO ()
|
||||
testHeldText = do
|
||||
let held overdue funded = heldText BalanceHold {bhHolder = RegistrationId "h", bhUntil = UTCTime (fromGregorian 2027 1 2) 3600, bhOverdue = overdue, bhFunded = funded}
|
||||
let heldFrom cmdSource overdue funded = heldText cmdSource BalanceHold {bhHolder = RegistrationId "h", bhUntil = UTCTime (fromGregorian 2027 1 2) 3600, bhOverdue = overdue, bhFunded = funded}
|
||||
held = heldFrom FromConsole
|
||||
held False False `shouldBe` "held by order h, its invoice open until 2027-01-02 01:00 UTC; run the command again then"
|
||||
held True False `shouldBe` "held by order h, its invoice expired at 2027-01-02 01:00 UTC; start the service so the poller closes that order, 10 minutes after the expiry at the earliest, then stop it and run the command again"
|
||||
heldFrom FromGroup True False `shouldBe` "held by order h, its invoice expired at 2027-01-02 01:00 UTC; the poller closes that order 10 minutes after the expiry at the earliest; run the command again then"
|
||||
held False True `shouldBe` "held by order h, whose invoice holds money; it holds until that payment settles or the invoice closes; run the command again then"
|
||||
|
||||
testChainText :: IO ()
|
||||
|
||||
@@ -653,7 +653,7 @@ testSpendTurns = withSpend $ \ctx@Ctx {cOrders} -> do
|
||||
-- end to end
|
||||
|
||||
-- | The real BTCPay adapter against the fake, read by the poller when BTCPay's webhook asks, over the running service's store, so
|
||||
-- //refund reads what the routes wrote; the clock is the wall clock, which the poller and //refund read.
|
||||
-- //balance reads what the routes wrote; the clock is the wall clock, which the poller and //balance read.
|
||||
withBTCPaySpend :: TestParams -> (ChatController -> FakeBTCPay -> PollerEnv -> Ctx -> IO ()) -> IO ()
|
||||
withBTCPaySpend ps action = withStoreService ps $ \_ _ cc -> withFakeBTCPay $ \fake -> do
|
||||
btcpay <- btcpayProvider (fbConfig fake)
|
||||
@@ -772,7 +772,7 @@ testSpendEndToEnd ps = withBTCPaySpend ps $ \cc fake poller ctx@Ctx {cClock} ->
|
||||
covering <- registrationAnswer . snd <$> spend ctx dearer (timedAt now $ (covered 20000) {sbOrder = aliceOrder {oCommitment = commitmentOf 4}})
|
||||
(\r -> (nrPhase r, nrBalanceSource r, nrBalanceUsed r)) <$> registrationById ctx covering `shouldReturn` (PQueued, Just dearer, 10000)
|
||||
let paidBy = "order " <> d <> ": $100.00 by btc on invoice " <> dearerInvText <> ", $100.00 from the balance of order " <> s <> "; order " <> s <> ": $100.00 by btc on invoice " <> srcInvText
|
||||
operatorCmd cc ("//refund " <> d)
|
||||
`shouldReturn` Right ("Order " <> d <> ": balance $100.00 (credited $200.00, refunded $0.00). Paid by: " <> paidBy <> ". To record its refund: //refund " <> d <> " 10000")
|
||||
operatorCmd cc ("//refund " <> dearerInvText <> " 10000") `shouldReturn` Right ("Recorded a refund of $100.00 for order " <> d <> ". Refund it now, by: " <> paidBy <> ".")
|
||||
operatorCmd cc ("//balance " <> d)
|
||||
`shouldReturn` Right ("Order " <> d <> ": balance $100.00 (credited $200.00, refunded $0.00). Paid by: " <> paidBy <> ". To record its refund: //record_refund " <> d <> " 10000")
|
||||
operatorCmd cc ("//record_refund " <> dearerInvText <> " 10000") `shouldReturn` Right ("Recorded a refund of $100.00 for order " <> d <> ". Refund it now, by: " <> paidBy <> ".")
|
||||
balanceView ctx dearer `shouldReturn` balanceObject 0 10000
|
||||
Reference in new issue
Block a user