Skip to content

Commit ca92a05

Browse files
authored
Implement wizard on /setinvoice (#504)
This facilitate the process of adding a new invoice when the first attempt of a buyer failed
1 parent 2c6e268 commit ca92a05

File tree

11 files changed

+65
-114
lines changed

11 files changed

+65
-114
lines changed

Diff for: bot/start.ts

+25-75
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ interface OrderQuery {
8383

8484
const askForConfirmation = async (user: UserDocument, command: string) => {
8585
try {
86+
let orders = [];
8687
if (command === '/cancel') {
8788
const where: FilterQuery<OrderQuery> = {
8889
$and: [
@@ -97,14 +98,12 @@ const askForConfirmation = async (user: UserDocument, command: string) => {
9798
},
9899
]
99100
};
100-
const orders = await Order.find(where);
101-
return orders;
101+
orders = await Order.find(where);
102102
} else if (command === '/fiatsent') {
103103
const where: FilterQuery<OrderQuery> = {
104104
$and: [{ buyer_id: user._id }, { status: 'ACTIVE' }]
105105
};
106-
const orders = await Order.find(where);
107-
return orders;
106+
orders = await Order.find(where);
108107
} else if (command === '/release') {
109108
const where: FilterQuery<OrderQuery> = {
110109
$and: [
@@ -118,11 +117,18 @@ const askForConfirmation = async (user: UserDocument, command: string) => {
118117
},
119118
]
120119
};
121-
const orders = await Order.find(where);
122-
return orders;
120+
orders = await Order.find(where);
121+
} else if (command === '/setinvoice') {
122+
const where: FilterQuery<OrderQuery> = {
123+
$and: [
124+
{ buyer_id: user._id },
125+
{ status: 'PAID_HOLD_INVOICE' },
126+
]
127+
};
128+
orders = await Order.find(where);
123129
}
124130

125-
return [];
131+
return orders;
126132
} catch (error) {
127133
logger.error(error);
128134
}
@@ -689,75 +695,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
689695
// Only buyers can use this command
690696
bot.command('setinvoice', userMiddleware, async (ctx: MainContext) => {
691697
try {
692-
const [orderId, lnInvoice] = await validateParams(
693-
ctx,
694-
3,
695-
'\\<_order id_\\> \\<_lightning invoice_\\>'
696-
);
698+
const command = '/setinvoice';
699+
const orders = await askForConfirmation(ctx.user, command);
700+
if (!orders.length) return await ctx.reply(ctx.i18n.t('setinvoice_no_response'));
697701

698-
if (!orderId) return;
699-
if (!(await validateObjectId(ctx, orderId))) return;
700-
const invoice = await validateInvoice(ctx, lnInvoice);
701-
if (!invoice) return;
702-
const order = await Order.findOne({
703-
_id: orderId,
704-
buyer_id: ctx.user.id,
705-
});
706-
if (!order) return await messages.notActiveOrderMessage(ctx);
707-
// We check if the old payment is on flight
708-
const isPendingOldPayment = await isPendingPayment(order.buyer_invoice);
709-
710-
// We check if this new payment is on flight
711-
const isPending = await isPendingPayment(lnInvoice);
712-
713-
// If one of the payments is on flight we don't do anything
714-
if (isPending || isPendingOldPayment) {
715-
logger.info(
716-
`Buyer Id: ${order.buyer_id} is trying to add a new invoice when have a pending payment on Order id: ${order._id}`
717-
);
718-
return await messages.invoiceAlreadyUpdatedMessage(ctx);
719-
}
720-
if (order.status === 'SUCCESS')
721-
return await messages.successCompleteOrderMessage(ctx, order);
722-
723-
if (invoice.tokens && invoice.tokens !== order.amount)
724-
return await messages.incorrectAmountInvoiceMessage(ctx);
725-
726-
order.buyer_invoice = lnInvoice;
727-
// When a seller release funds but the buyer didn't get the invoice paid
728-
if (order.status === 'PAID_HOLD_INVOICE') {
729-
const isScheduled = await PendingPayment.findOne({
730-
order_id: order._id,
731-
attempts: { $lt: process.env.PAYMENT_ATTEMPTS },
732-
is_invoice_expired: false,
733-
});
734-
735-
if (isScheduled)
736-
return await messages.invoiceAlreadyUpdatedMessage(ctx);
737-
738-
if (!order.paid_hold_buyer_invoice_updated) {
739-
order.paid_hold_buyer_invoice_updated = true;
740-
const pp = new PendingPayment({
741-
amount: order.amount,
742-
payment_request: lnInvoice,
743-
user_id: ctx.user.id,
744-
description: order.description,
745-
hash: order.hash,
746-
order_id: order._id,
747-
});
748-
await pp.save();
749-
await messages.invoiceUpdatedPaymentWillBeSendMessage(ctx);
750-
} else {
751-
await messages.invoiceAlreadyUpdatedMessage(ctx);
752-
}
753-
} else if (order.status === 'WAITING_BUYER_INVOICE') {
754-
const seller = await User.findOne({ _id: order.seller_id });
755-
await waitPayment(ctx, bot, ctx.user, seller, order, lnInvoice);
756-
} else {
757-
await messages.invoiceUpdatedMessage(ctx);
758-
}
759-
760-
await order.save();
702+
return await messages.showConfirmationButtons(ctx, orders, command);
761703
} catch (error) {
762704
logger.error(error);
763705
}
@@ -795,6 +737,14 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
795737
await addInvoicePHI(ctx, bot, ctx.match[1]);
796738
});
797739

740+
bot.action(/^setinvoice_([0-9a-f]{24})$/, userMiddleware, async (ctx: MainContext) => {
741+
if (ctx.match === null) {
742+
throw new Error("ctx.match should not be null");
743+
}
744+
ctx.deleteMessage();
745+
await addInvoicePHI(ctx, bot, ctx.match[1]);
746+
});
747+
798748
bot.action(/^cancel_([0-9a-f]{24})$/, userMiddleware, async (ctx: MainContext) => {
799749
if (ctx.match === null) {
800750
throw new Error("ctx.match should not be null");

Diff for: locales/de.yaml

+4-4
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,7 @@ min_expiration_time: Die Ablaufzeit für die LN-Rechnung muss mindestens ${expir
9090
invoice_expired: Die LN-Rechnung ist abgelaufen
9191
invoice_expired_long: |
9292
Die LN-Rechnung ist abgelaufen. Du kannst mir mit folgendem Befehl eine neue LN-Rechnung schicken, um die sats zu erhalten 👇
93-
setinvoice_cmd_order: |
94-
/setinvoice ${orderId} \\<Lightning Invoice\\>
93+
setinvoice_cmd_order: /setinvoice
9594
invoice_require_destination: Die LN-Rechnung braucht eine Empfängeradresse
9695
invoice_require_hash: LN-Rechnung braucht einen Hash
9796
order_id_invalid: Ungültige Auftrags-ID
@@ -212,7 +211,7 @@ help: |
212211
/info - Zeigt zusätzliche Informationen über das Bot an
213212
/showusername - Schaltet die Anzeige des Benutzernamens in jedem neu erstellten Auftrag aus. Der Standardwert ist *nein* (false)
214213
/showvolume - zeigt das Handelsvolumen an, wenn eine Auftrag erstellt wird, Standardwert ist *nein* (false)
215-
/setinvoice <_order id_> <_lightning LN-Rechnung_> - Mit diesem Befehl kann der Käufer die Ligthning-Rechnung aktualisieren, mit welcher er die Sats empfangen will
214+
/setinvoice - Mit diesem Befehl kann der Käufer die Ligthning-Rechnung aktualisieren, mit welcher er die Sats empfangen will
216215
/setaddress <_lightning Adresse / off_> - Ermöglicht es dem Käufer, eine statische Zahlungsadresse (Lightning-Adresse) einzurichten, _off_ zum Deaktivieren
217216
/setlang - Ermöglicht dem Benutzer, die Sprache zu ändern
218217
/settings - Zeigt die aktuellen Einstellungen des Benutzers an
@@ -311,7 +310,7 @@ wizard_add_invoice_init: |
311310
wizard_add_invoice_exit: |
312311
Du hast den Assistentenmodus verlassen, du kannst die Befehle aufschreiben. Du kannst immer noch eine LN-Rechnung zum Auftrag hinzufügen mit dem Befehl /setinvoice, der die Auftrags\-ID und die LN-Rechnung angibt, du kannst mir eine LN-Rechnung über ${Betrag} Sats schicken, aber ich akzeptiere auch LN-Rechnungen ohne Betrag:
313312
314-
`/setinvoice ${orderId} `\\<Lightning LN-Rechnung mit oder ohne Betrag\\>
313+
/setinvoice
315314
wizard_community_enter_name: Wähle einen Namen für deine Community
316315
wizard_community_too_long_name: Der Name kann eine maximale Länge von ${length} Zeichen haben.
317316
wizard_community_enter_currency: Gib den Code der FIAT-Währung(en) ein, welche die Nutzer dieser Community verwenden können. Gibt es mehr als einen, musst du jeden Code durch ein Leerzeichen getrennt eingeben.
@@ -593,3 +592,4 @@ disclaimer: |
593592
Weder die Entwickler noch die Streitschlichter sind für Verluste oder Schäden verantwortlich, die dem Benutzer durch die Nutzung des Bots entstehen können.
594593
order_frozen: Sie haben die Bestellung eingefroren
595594
dispute_solver: 👮‍♂️ Der Solver @${solver} kümmert sich um Ihren Streit. Sie können ihm/ihr schreiben oder darauf warten, dass er/sie Ihnen schreibt
595+
setinvoice_no_response: Sie haben keine zu bezahlenden Aufträge

Diff for: locales/en.yaml

+4-4
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,7 @@ min_expiration_time: Time expiration for the invoice should be of at least ${exp
9292
invoice_expired: The invoice has expired
9393
invoice_expired_long: |
9494
The invoice has expired. You can use the following command to send me a new invoice to receive the satoshis 👇
95-
setinvoice_cmd_order: |
96-
/setinvoice ${orderId} \\<Lightning Invoice\\>
95+
setinvoice_cmd_order: /setinvoice
9796
invoice_require_destination: Invoice needs a receiver address
9897
invoice_require_hash: Invoice needs a hash
9998
order_id_invalid: Invalid order ID
@@ -214,7 +213,7 @@ help: |
214213
/info - Shows additional info about the bot
215214
/showusername - Toggles off the username display in each new order created. Default value is set to false
216215
/showvolume - Shows trade volume when each order is created, default value is false
217-
/setinvoice <_order id_> <_lightning invoice_> - This command allows the buyer to update the lightning invoice where to receive the sats
216+
/setinvoice - This command allows the buyer to update the lightning invoice where to receive the sats
218217
/setaddress <_lightning address / off_> - Allows the buyer to establish a static payment address (lightning address), _off_ to deactivate
219218
/setlang - Allows the user to change the language
220219
/settings - Displays the user's current settings
@@ -313,7 +312,7 @@ wizard_add_invoice_init: |
313312
wizard_add_invoice_exit: |
314313
You have exited wizard mode, you can now write down the commands and add an invoice to the order with the command /setinvoice indicating Order ID and Invoice. You may send me an invoice for ${amount} satoshis, but I also accept invoices with no amount specified:
315314
316-
`/setinvoice ${orderId} `\\<lightning invoice with or without amount\\>
315+
/setinvoice
317316
wizard_community_enter_name: Pick a name for your community
318317
wizard_community_too_long_name: The name can have a maximum length of ${length} characters.
319318
wizard_community_enter_currency: Enter the code of the fiat currency(ies) with which users can operate in this community, if there is more than one you must enter each code separated by a blank space.
@@ -593,3 +592,4 @@ disclaimer: |
593592
Neither the developers nor the dispute resolvers are responsible for any losses or damages that the user may suffer as a result of using the bot.
594593
order_frozen: You have frozen the order
595594
dispute_solver: 👮‍♂️ The solver @${solver} will be attending to your dispute, you can write to him/her or wait for him/her to write to you
595+
setinvoice_no_response: You have no orders to be paid

Diff for: locales/es.yaml

+4-4
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,7 @@ min_expiration_time: El tiempo de expiración de la factura debe ser de al menos
9090
invoice_expired: La factura ha expirado
9191
invoice_expired_long: |
9292
La factura ha expirado. Si deseas puedes enviarme una nueva factura para recibir los satoshis con el comando 👇
93-
setinvoice_cmd_order: |
94-
/setinvoice ${orderId} \\<factura lightning\\>
93+
setinvoice_cmd_order: /setinvoice
9594
invoice_require_destination: La factura necesita una dirección destino
9695
invoice_require_hash: La factura necesita un hash
9796
order_id_invalid: Id de orden incorrecto
@@ -212,7 +211,7 @@ help: |
212211
/info - Muestra información sobre el bot
213212
/showusername - Permite mostrar u ocultar el username en cada nueva orden creada, el valor predeterminado es no (falso)
214213
/showvolume - Permite mostrar el volumen de comercio en cada nueva orden creada, el valor predeterminado es no (falso)
215-
/setinvoice <_id orden_> <_factura lightning_> - Le permite al comprador actualizar la factura lightning en la que recibirá sats
214+
/setinvoice - Le permite al comprador actualizar la factura lightning en la que recibirá sats
216215
/setaddress <_lightning address / off_> - Permite al comprador indicar una dirección de pago estática (lightning address), _off_ para desactivarla
217216
/setlang - Le permite al usuario cambiar el idioma
218217
/settings - Muestra la configuración actual del usuario
@@ -314,7 +313,7 @@ wizard_add_invoice_init: |
314313
wizard_add_invoice_exit: |
315314
Has salido del modo asistente, ahora puedes escribir comandos, aún puedes ingresar una factura a la orden con el comando /setinvoice indicando Id de orden y factura, puedes enviarme una factura con un monto de ${amount} satoshis, pero tambien acepto facturas sin monto:
316315
317-
/setinvoice ${orderId} \\<factura lightning con o sin monto\\>
316+
/setinvoice
318317
wizard_community_enter_name: Ingresa el nombre de tu comunidad
319318
wizard_community_too_long_name: El nombre debe tener un máximo de ${length} caracteres.
320319
wizard_community_enter_currency: Ingresa el código de la(s) moneda(s) fiat con las que los usuarios podrán operar en esta comunidad, si hay más de una debes ingresar cada código separado por un espacio en blanco.
@@ -595,3 +594,4 @@ disclaimer: |
595594
Ni los desarrolladores ni los árbitros de disputas son responsables de las pérdidas o daños que el usuario pueda sufrir como resultado del uso del bot.
596595
order_frozen: Has congelado la orden
597596
dispute_solver: 👮‍♂️ El solver @${solver} estará atendiendo tu disputa, puedes escribirle o esperar que te escriba
597+
setinvoice_no_response: No tienes ordenes a ser pagadas

Diff for: locales/fa.yaml

+4-4
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,7 @@ min_expiration_time: زمان منقضی شدن فاکتور باید حداقل
9292
invoice_expired: فاکتور منقضی شده
9393
invoice_expired_long: |
9494
فاکتور منقضی شده است. جهت گرفتن فاکتور جدید برای دریافت ساتوشی می توانید از دستور زیر استفاده کنید 👇
95-
setinvoice_cmd_order: |
96-
/setinvoice ${orderId} \\<Lightning Invoice\\>
95+
setinvoice_cmd_order: setinvoice
9796
invoice_require_destination: فاکتور به آدرس گیرنده نیاز دارد
9897
invoice_require_hash: فاکتور نیاز به هش دارد
9998
order_id_invalid: شناسه سفارش نامعتبر است
@@ -214,7 +213,7 @@ help: |
214213
/info - اطلاعات اضافی درباره ربات را نشان می دهد
215214
/showusername - در هر سفارش جدید ایجاد شده، نمایش نام‌کاربری را خاموش می کند. مقدار پیش فرض روی false تنظیم شده است(نمایش داده نمیشود)
216215
/showvolume - حجم معاملات را هنگام ایجاد هر سفارش نشان می‌دهد، مقدار پیش فرض نادرست است
217-
/setinvoice <_order id_> <_lightning invoice_> - این دستور به خریدار اجازه می‌دهد تا فاکتور لایتنینگ را برای دریافت ساتوشی‌ها آپدیت کند
216+
/setinvoice - این دستور به خریدار اجازه می‌دهد تا فاکتور لایتنینگ را برای دریافت ساتوشی‌ها آپدیت کند
218217
/setaddress <_lightning address / off_> - به خریدار امکان می‌دهد یک آدرس پرداخت ثابت (لایتنینگ آدرس) ایجاد کند، برای غیرفعال کردن عبارت_off_را جلو آن وارد کنید
219218
/setlang - به کاربر امکان تغییر زبان را می‌دهد
220219
/settings - تنظیمات فعلی کاربر را نمایش می‌دهد
@@ -313,7 +312,7 @@ wizard_add_invoice_init: |
313312
wizard_add_invoice_exit: |
314313
شما از حالت wizard خارج شده اید، اکنون می توانید دستورات را یادداشت کرده و با دستور /setinvoice که نشان دهنده شناسه سفارش و فاکتور است، یک فاکتور به سفارش اضافه کنید. می توانید برای ما فاکتوری برای ${amount} ساتوشی بفرستید، اما ما فاکتورها را بدون مبلغ مشخص نیز می پذیریم:
315314
316-
`/setinvoice ${orderId} `\\<lightning invoice with or without amount\\>
315+
/setinvoice
317316
wizard_community_enter_name: نامی برای کامیونیتی خود انتخاب کنید
318317
wizard_community_too_long_name: این نام می‌تواند حداکثر طول ${length} کاراکتر داشته باشد.
319318
wizard_community_enter_currency: کد ارز(های) فیات را که کاربران می توانند با آن در این کامیونیتی فعالیت کنند، وارد کنید، اگر بیش از یک ارز وجود دارد، باید هر کد را با یک فاصله خالی از بقیه جدا کنید.
@@ -592,3 +591,4 @@ disclaimer: |
592591
نه توسعه‌دهندگان و نه حل‌کننده‌های اختلاف، مسئولیتی در قبال ضرر و زیان‌هایی که ممکن است کاربر در اثر استفاده از ربات متحمل شود، ندارند.
593592
order_frozen: شما سفارش را مسدود کردید
594593
dispute_solver: 👮‍♂️ حل‌کننده @${solver} به اختلاف شما رسیدگی می‌کند، می‌توانید به او نامه بنویسید یا منتظر بمانید تا برای شما بنویسد.
594+
setinvoice_no_response: هیچ سفارشی برای پرداخت ندارید

Diff for: locales/fr.yaml

+4-4
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,7 @@ min_expiration_time: Le délai d'expiration de la facture devrait être au minim
9292
invoice_expired: La facture a expiré
9393
invoice_expired_long: |
9494
La facture a expiré. Tu peux utiliser la commande ci-dessous pour m'envoyer une nouvelle facture sur laquelle recevoir les satoshis 👇
95-
setinvoice_cmd_order: |
96-
/setinvoice ${orderId} \\<Facture Lightning\\>
95+
setinvoice_cmd_order: /setinvoice
9796
invoice_require_destination: La facture doit inclure l'adresse du bénéficiaire
9897
invoice_require_hash: La facture a besoin d'un hash
9998
order_id_invalid: ID de facture invalide
@@ -214,7 +213,7 @@ help: |
214213
/info - Affiche des informations additionnelles à propos du bot
215214
/showusername - Désactive l'affichage du nom d'utilisateur dans chaque offre nouvellement créée. La valeur par défaut est définie sur false
216215
/showvolume - Affiche le volume de transactions dans chaque offre nouvellement créée, la valeur par défaut est false
217-
/setinvoice <_ID d'offre_> <_facture lightning_> - Cette commande permet à l'acheteur d'actualiser la facture lightning pour recevoir les sats
216+
/setinvoice - Cette commande permet à l'acheteur d'actualiser la facture lightning pour recevoir les sats
218217
/setaddress <_addresse lightning / off_> - Permet à l'acheteur de définir une adresse de paiement statique (adresse lightning), _off_ pour désactiver
219218
/setlang - Change la langue de l'interface
220219
/settings - Affiche tes réglages actuels
@@ -313,7 +312,7 @@ wizard_add_invoice_init: |
313312
wizard_add_invoice_exit: |
314313
Vous avez quitté le mode assistant, vous pouvez maintenant écrire les commandes et ajouter une facture à l'offre avec la commande /setinvoice indiquant l'ID de la commande et la facture. Vous pouvez m'envoyer une facture de ${amount} satoshis, mais j'accepte également les factures sans montant spécifié :
315314
316-
`/setinvoice ${orderId} `\\<facture Lightning avec ou sans montant\\>
315+
/setinvoice
317316
wizard_community_enter_name: Choisissez un nom pour votre communauté
318317
wizard_community_too_long_name: Le nom doit avoir une longueur maximale de ${length} caractères.
319318
wizard_community_enter_currency: Saisissez le code de la ou des monnaies FIAT avec lesquelles les utilisateurs peuvent opérer dans cette communauté. S'il y en a plusieurs, vous devez saisir chaque code en le séparant par un espace.
@@ -593,3 +592,4 @@ disclaimer: |
593592
Ni les développeurs ni les responsables de la résolution des litiges ne sont responsables des pertes ou des dommages que l'utilisateur pourrait subir à la suite de l'utilisation du bot.
594593
order_frozen: Vous avez gelé la commande
595594
dispute_solver: 👮‍♂️ Le solveur @${solver} s'occupera de votre litige, vous pouvez lui écrire ou attendre qu'il vous écrive
595+
setinvoice_no_response : Vous n'avez pas d'ordre à payer

0 commit comments

Comments
 (0)