Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement wizard on /setinvoice #504

Merged
merged 1 commit into from
Apr 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 25 additions & 75 deletions bot/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ interface OrderQuery {

const askForConfirmation = async (user: UserDocument, command: string) => {
try {
let orders = [];
if (command === '/cancel') {
const where: FilterQuery<OrderQuery> = {
$and: [
Expand All @@ -97,14 +98,12 @@ const askForConfirmation = async (user: UserDocument, command: string) => {
},
]
};
const orders = await Order.find(where);
return orders;
orders = await Order.find(where);
} else if (command === '/fiatsent') {
const where: FilterQuery<OrderQuery> = {
$and: [{ buyer_id: user._id }, { status: 'ACTIVE' }]
};
const orders = await Order.find(where);
return orders;
orders = await Order.find(where);
} else if (command === '/release') {
const where: FilterQuery<OrderQuery> = {
$and: [
Expand All @@ -118,11 +117,18 @@ const askForConfirmation = async (user: UserDocument, command: string) => {
},
]
};
const orders = await Order.find(where);
return orders;
orders = await Order.find(where);
} else if (command === '/setinvoice') {
const where: FilterQuery<OrderQuery> = {
$and: [
{ buyer_id: user._id },
{ status: 'PAID_HOLD_INVOICE' },
]
};
orders = await Order.find(where);
}

return [];
return orders;
} catch (error) {
logger.error(error);
}
Expand Down Expand Up @@ -689,75 +695,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
// Only buyers can use this command
bot.command('setinvoice', userMiddleware, async (ctx: MainContext) => {
try {
const [orderId, lnInvoice] = await validateParams(
ctx,
3,
'\\<_order id_\\> \\<_lightning invoice_\\>'
);
const command = '/setinvoice';
const orders = await askForConfirmation(ctx.user, command);
if (!orders.length) return await ctx.reply(ctx.i18n.t('setinvoice_no_response'));

if (!orderId) return;
if (!(await validateObjectId(ctx, orderId))) return;
const invoice = await validateInvoice(ctx, lnInvoice);
if (!invoice) return;
const order = await Order.findOne({
_id: orderId,
buyer_id: ctx.user.id,
});
if (!order) return await messages.notActiveOrderMessage(ctx);
// We check if the old payment is on flight
const isPendingOldPayment = await isPendingPayment(order.buyer_invoice);

// We check if this new payment is on flight
const isPending = await isPendingPayment(lnInvoice);

// If one of the payments is on flight we don't do anything
if (isPending || isPendingOldPayment) {
logger.info(
`Buyer Id: ${order.buyer_id} is trying to add a new invoice when have a pending payment on Order id: ${order._id}`
);
return await messages.invoiceAlreadyUpdatedMessage(ctx);
}
if (order.status === 'SUCCESS')
return await messages.successCompleteOrderMessage(ctx, order);

if (invoice.tokens && invoice.tokens !== order.amount)
return await messages.incorrectAmountInvoiceMessage(ctx);

order.buyer_invoice = lnInvoice;
// When a seller release funds but the buyer didn't get the invoice paid
if (order.status === 'PAID_HOLD_INVOICE') {
const isScheduled = await PendingPayment.findOne({
order_id: order._id,
attempts: { $lt: process.env.PAYMENT_ATTEMPTS },
is_invoice_expired: false,
});

if (isScheduled)
return await messages.invoiceAlreadyUpdatedMessage(ctx);

if (!order.paid_hold_buyer_invoice_updated) {
order.paid_hold_buyer_invoice_updated = true;
const pp = new PendingPayment({
amount: order.amount,
payment_request: lnInvoice,
user_id: ctx.user.id,
description: order.description,
hash: order.hash,
order_id: order._id,
});
await pp.save();
await messages.invoiceUpdatedPaymentWillBeSendMessage(ctx);
} else {
await messages.invoiceAlreadyUpdatedMessage(ctx);
}
} else if (order.status === 'WAITING_BUYER_INVOICE') {
const seller = await User.findOne({ _id: order.seller_id });
await waitPayment(ctx, bot, ctx.user, seller, order, lnInvoice);
} else {
await messages.invoiceUpdatedMessage(ctx);
}

await order.save();
return await messages.showConfirmationButtons(ctx, orders, command);
} catch (error) {
logger.error(error);
}
Expand Down Expand Up @@ -795,6 +737,14 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
await addInvoicePHI(ctx, bot, ctx.match[1]);
});

bot.action(/^setinvoice_([0-9a-f]{24})$/, userMiddleware, async (ctx: MainContext) => {
if (ctx.match === null) {
throw new Error("ctx.match should not be null");
}
ctx.deleteMessage();
await addInvoicePHI(ctx, bot, ctx.match[1]);
});

bot.action(/^cancel_([0-9a-f]{24})$/, userMiddleware, async (ctx: MainContext) => {
if (ctx.match === null) {
throw new Error("ctx.match should not be null");
Expand Down
8 changes: 4 additions & 4 deletions locales/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,7 @@ min_expiration_time: Die Ablaufzeit für die LN-Rechnung muss mindestens ${expir
invoice_expired: Die LN-Rechnung ist abgelaufen
invoice_expired_long: |
Die LN-Rechnung ist abgelaufen. Du kannst mir mit folgendem Befehl eine neue LN-Rechnung schicken, um die sats zu erhalten 👇
setinvoice_cmd_order: |
/setinvoice ${orderId} \\<Lightning Invoice\\>
setinvoice_cmd_order: /setinvoice
invoice_require_destination: Die LN-Rechnung braucht eine Empfängeradresse
invoice_require_hash: LN-Rechnung braucht einen Hash
order_id_invalid: Ungültige Auftrags-ID
Expand Down Expand Up @@ -212,7 +211,7 @@ help: |
/info - Zeigt zusätzliche Informationen über das Bot an
/showusername - Schaltet die Anzeige des Benutzernamens in jedem neu erstellten Auftrag aus. Der Standardwert ist *nein* (false)
/showvolume - zeigt das Handelsvolumen an, wenn eine Auftrag erstellt wird, Standardwert ist *nein* (false)
/setinvoice <_order id_> <_lightning LN-Rechnung_> - Mit diesem Befehl kann der Käufer die Ligthning-Rechnung aktualisieren, mit welcher er die Sats empfangen will
/setinvoice - Mit diesem Befehl kann der Käufer die Ligthning-Rechnung aktualisieren, mit welcher er die Sats empfangen will
/setaddress <_lightning Adresse / off_> - Ermöglicht es dem Käufer, eine statische Zahlungsadresse (Lightning-Adresse) einzurichten, _off_ zum Deaktivieren
/setlang - Ermöglicht dem Benutzer, die Sprache zu ändern
/settings - Zeigt die aktuellen Einstellungen des Benutzers an
Expand Down Expand Up @@ -311,7 +310,7 @@ wizard_add_invoice_init: |
wizard_add_invoice_exit: |
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:

`/setinvoice ${orderId} `\\<Lightning LN-Rechnung mit oder ohne Betrag\\>
/setinvoice
wizard_community_enter_name: Wähle einen Namen für deine Community
wizard_community_too_long_name: Der Name kann eine maximale Länge von ${length} Zeichen haben.
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.
Expand Down Expand Up @@ -593,3 +592,4 @@ disclaimer: |
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.
order_frozen: Sie haben die Bestellung eingefroren
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
setinvoice_no_response: Sie haben keine zu bezahlenden Aufträge
8 changes: 4 additions & 4 deletions locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,7 @@ min_expiration_time: Time expiration for the invoice should be of at least ${exp
invoice_expired: The invoice has expired
invoice_expired_long: |
The invoice has expired. You can use the following command to send me a new invoice to receive the satoshis 👇
setinvoice_cmd_order: |
/setinvoice ${orderId} \\<Lightning Invoice\\>
setinvoice_cmd_order: /setinvoice
invoice_require_destination: Invoice needs a receiver address
invoice_require_hash: Invoice needs a hash
order_id_invalid: Invalid order ID
Expand Down Expand Up @@ -214,7 +213,7 @@ help: |
/info - Shows additional info about the bot
/showusername - Toggles off the username display in each new order created. Default value is set to false
/showvolume - Shows trade volume when each order is created, default value is false
/setinvoice <_order id_> <_lightning invoice_> - This command allows the buyer to update the lightning invoice where to receive the sats
/setinvoice - This command allows the buyer to update the lightning invoice where to receive the sats
/setaddress <_lightning address / off_> - Allows the buyer to establish a static payment address (lightning address), _off_ to deactivate
/setlang - Allows the user to change the language
/settings - Displays the user's current settings
Expand Down Expand Up @@ -313,7 +312,7 @@ wizard_add_invoice_init: |
wizard_add_invoice_exit: |
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:

`/setinvoice ${orderId} `\\<lightning invoice with or without amount\\>
/setinvoice
wizard_community_enter_name: Pick a name for your community
wizard_community_too_long_name: The name can have a maximum length of ${length} characters.
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.
Expand Down Expand Up @@ -593,3 +592,4 @@ disclaimer: |
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.
order_frozen: You have frozen the order
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
setinvoice_no_response: You have no orders to be paid
8 changes: 4 additions & 4 deletions locales/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,7 @@ min_expiration_time: El tiempo de expiración de la factura debe ser de al menos
invoice_expired: La factura ha expirado
invoice_expired_long: |
La factura ha expirado. Si deseas puedes enviarme una nueva factura para recibir los satoshis con el comando 👇
setinvoice_cmd_order: |
/setinvoice ${orderId} \\<factura lightning\\>
setinvoice_cmd_order: /setinvoice
invoice_require_destination: La factura necesita una dirección destino
invoice_require_hash: La factura necesita un hash
order_id_invalid: Id de orden incorrecto
Expand Down Expand Up @@ -212,7 +211,7 @@ help: |
/info - Muestra información sobre el bot
/showusername - Permite mostrar u ocultar el username en cada nueva orden creada, el valor predeterminado es no (falso)
/showvolume - Permite mostrar el volumen de comercio en cada nueva orden creada, el valor predeterminado es no (falso)
/setinvoice <_id orden_> <_factura lightning_> - Le permite al comprador actualizar la factura lightning en la que recibirá sats
/setinvoice - Le permite al comprador actualizar la factura lightning en la que recibirá sats
/setaddress <_lightning address / off_> - Permite al comprador indicar una dirección de pago estática (lightning address), _off_ para desactivarla
/setlang - Le permite al usuario cambiar el idioma
/settings - Muestra la configuración actual del usuario
Expand Down Expand Up @@ -314,7 +313,7 @@ wizard_add_invoice_init: |
wizard_add_invoice_exit: |
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:

/setinvoice ${orderId} \\<factura lightning con o sin monto\\>
/setinvoice
wizard_community_enter_name: Ingresa el nombre de tu comunidad
wizard_community_too_long_name: El nombre debe tener un máximo de ${length} caracteres.
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.
Expand Down Expand Up @@ -595,3 +594,4 @@ disclaimer: |
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.
order_frozen: Has congelado la orden
dispute_solver: 👮‍♂️ El solver @${solver} estará atendiendo tu disputa, puedes escribirle o esperar que te escriba
setinvoice_no_response: No tienes ordenes a ser pagadas
8 changes: 4 additions & 4 deletions locales/fa.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,7 @@ min_expiration_time: زمان منقضی شدن فاکتور باید حداقل
invoice_expired: فاکتور منقضی شده
invoice_expired_long: |
فاکتور منقضی شده است. جهت گرفتن فاکتور جدید برای دریافت ساتوشی می توانید از دستور زیر استفاده کنید 👇
setinvoice_cmd_order: |
/setinvoice ${orderId} \\<Lightning Invoice\\>
setinvoice_cmd_order: setinvoice
invoice_require_destination: فاکتور به آدرس گیرنده نیاز دارد
invoice_require_hash: فاکتور نیاز به هش دارد
order_id_invalid: شناسه سفارش نامعتبر است
Expand Down Expand Up @@ -214,7 +213,7 @@ help: |
/info - اطلاعات اضافی درباره ربات را نشان می دهد
/showusername - در هر سفارش جدید ایجاد شده، نمایش نام‌کاربری را خاموش می کند. مقدار پیش فرض روی false تنظیم شده است(نمایش داده نمیشود)
/showvolume - حجم معاملات را هنگام ایجاد هر سفارش نشان می‌دهد، مقدار پیش فرض نادرست است
/setinvoice <_order id_> <_lightning invoice_> - این دستور به خریدار اجازه می‌دهد تا فاکتور لایتنینگ را برای دریافت ساتوشی‌ها آپدیت کند
/setinvoice - این دستور به خریدار اجازه می‌دهد تا فاکتور لایتنینگ را برای دریافت ساتوشی‌ها آپدیت کند
/setaddress <_lightning address / off_> - به خریدار امکان می‌دهد یک آدرس پرداخت ثابت (لایتنینگ آدرس) ایجاد کند، برای غیرفعال کردن عبارت_off_را جلو آن وارد کنید
/setlang - به کاربر امکان تغییر زبان را می‌دهد
/settings - تنظیمات فعلی کاربر را نمایش می‌دهد
Expand Down Expand Up @@ -313,7 +312,7 @@ wizard_add_invoice_init: |
wizard_add_invoice_exit: |
شما از حالت wizard خارج شده اید، اکنون می توانید دستورات را یادداشت کرده و با دستور /setinvoice که نشان دهنده شناسه سفارش و فاکتور است، یک فاکتور به سفارش اضافه کنید. می توانید برای ما فاکتوری برای ${amount} ساتوشی بفرستید، اما ما فاکتورها را بدون مبلغ مشخص نیز می پذیریم:

`/setinvoice ${orderId} `\\<lightning invoice with or without amount\\>
/setinvoice
wizard_community_enter_name: نامی برای کامیونیتی خود انتخاب کنید
wizard_community_too_long_name: این نام می‌تواند حداکثر طول ${length} کاراکتر داشته باشد.
wizard_community_enter_currency: کد ارز(های) فیات را که کاربران می توانند با آن در این کامیونیتی فعالیت کنند، وارد کنید، اگر بیش از یک ارز وجود دارد، باید هر کد را با یک فاصله خالی از بقیه جدا کنید.
Expand Down Expand Up @@ -592,3 +591,4 @@ disclaimer: |
نه توسعه‌دهندگان و نه حل‌کننده‌های اختلاف، مسئولیتی در قبال ضرر و زیان‌هایی که ممکن است کاربر در اثر استفاده از ربات متحمل شود، ندارند.
order_frozen: شما سفارش را مسدود کردید
dispute_solver: 👮‍♂️ حل‌کننده @${solver} به اختلاف شما رسیدگی می‌کند، می‌توانید به او نامه بنویسید یا منتظر بمانید تا برای شما بنویسد.
setinvoice_no_response: هیچ سفارشی برای پرداخت ندارید
8 changes: 4 additions & 4 deletions locales/fr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,7 @@ min_expiration_time: Le délai d'expiration de la facture devrait être au minim
invoice_expired: La facture a expiré
invoice_expired_long: |
La facture a expiré. Tu peux utiliser la commande ci-dessous pour m'envoyer une nouvelle facture sur laquelle recevoir les satoshis 👇
setinvoice_cmd_order: |
/setinvoice ${orderId} \\<Facture Lightning\\>
setinvoice_cmd_order: /setinvoice
invoice_require_destination: La facture doit inclure l'adresse du bénéficiaire
invoice_require_hash: La facture a besoin d'un hash
order_id_invalid: ID de facture invalide
Expand Down Expand Up @@ -214,7 +213,7 @@ help: |
/info - Affiche des informations additionnelles à propos du bot
/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
/showvolume - Affiche le volume de transactions dans chaque offre nouvellement créée, la valeur par défaut est false
/setinvoice <_ID d'offre_> <_facture lightning_> - Cette commande permet à l'acheteur d'actualiser la facture lightning pour recevoir les sats
/setinvoice - Cette commande permet à l'acheteur d'actualiser la facture lightning pour recevoir les sats
/setaddress <_addresse lightning / off_> - Permet à l'acheteur de définir une adresse de paiement statique (adresse lightning), _off_ pour désactiver
/setlang - Change la langue de l'interface
/settings - Affiche tes réglages actuels
Expand Down Expand Up @@ -313,7 +312,7 @@ wizard_add_invoice_init: |
wizard_add_invoice_exit: |
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é :

`/setinvoice ${orderId} `\\<facture Lightning avec ou sans montant\\>
/setinvoice
wizard_community_enter_name: Choisissez un nom pour votre communauté
wizard_community_too_long_name: Le nom doit avoir une longueur maximale de ${length} caractères.
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.
Expand Down Expand Up @@ -593,3 +592,4 @@ disclaimer: |
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.
order_frozen: Vous avez gelé la commande
dispute_solver: 👮‍♂️ Le solveur @${solver} s'occupera de votre litige, vous pouvez lui écrire ou attendre qu'il vous écrive
setinvoice_no_response : Vous n'avez pas d'ordre à payer
Loading
Loading