From 08229711095e95794ff401b75d89470becc538ce Mon Sep 17 00:00:00 2001 From: Bilthon Date: Mon, 31 Jul 2023 09:06:57 -0500 Subject: [PATCH] Displays counterparty age when a user's order is taken (#411) While a previous feature exposed the order maker's age in the order itself, this information has been absent for the maker --- bot/commands.js | 9 ++------- bot/messages.js | 17 +++++++++++++++-- bot/ordersActions.js | 7 ++----- locales/de.yaml | 4 ++-- locales/en.yaml | 4 ++-- locales/es.yaml | 4 ++-- locales/fr.yaml | 4 ++-- locales/it.yaml | 4 ++-- locales/pt.yaml | 4 ++-- locales/ru.yaml | 4 ++-- locales/uk.yaml | 4 ++-- util/index.js | 11 +++++++++++ 12 files changed, 46 insertions(+), 30 deletions(-) diff --git a/bot/commands.js b/bot/commands.js index 96a87f23..acfe66e7 100644 --- a/bot/commands.js +++ b/bot/commands.js @@ -15,8 +15,6 @@ const { deleteOrderFromChannel, getUserI18nContext, getFee, - getEmojiRate, - decimalRound, } = require('../util'); const ordersActions = require('./ordersActions'); @@ -69,11 +67,8 @@ const waitPayment = async (ctx, bot, buyer, seller, order, buyerInvoice) => { // We monitor the invoice to know when the seller makes the payment await subscribeInvoice(bot, hash); - // We need the buyer rate + // We pass the buyer for rate and age calculations const buyer = await User.findById(order.buyer_id); - const stars = getEmojiRate(buyer.total_rating); - const roundedRating = decimalRound(buyer.total_rating, -1); - const rate = `${roundedRating} ${stars} (${buyer.total_reviews})`; // We send the hold invoice to the seller await messages.invoicePaymentRequestMessage( ctx, @@ -81,7 +76,7 @@ const waitPayment = async (ctx, bot, buyer, seller, order, buyerInvoice) => { request, order, i18nCtx, - rate + buyer ); await messages.takeSellWaitingSellerToPayMessage(ctx, bot, buyer, order); } diff --git a/bot/messages.js b/bot/messages.js index 42f76f22..40c58568 100644 --- a/bot/messages.js +++ b/bot/messages.js @@ -8,6 +8,9 @@ const { getOrderChannel, holdInvoiceExpirationInSecs, sanitizeMD, + getEmojiRate, + decimalRound, + getUserAge } = require('../util'); const logger = require('../logger'); @@ -56,7 +59,7 @@ const invoicePaymentRequestMessage = async ( request, order, i18n, - rate + buyer ) => { try { let currency = getCurrency(order.fiat_code); @@ -66,11 +69,19 @@ const invoicePaymentRequestMessage = async ( : order.fiat_code; const expirationTime = parseInt(process.env.HOLD_INVOICE_EXPIRATION_WINDOW) / 60; + // We need the buyer rating + const stars = getEmojiRate(buyer.total_rating); + const roundedRating = decimalRound(buyer.total_rating, -1); + const rate = `${roundedRating} ${stars} (${buyer.total_reviews})`; + // Extracting the buyer's days in the platform + const ageInDays = getUserAge(buyer); + const message = i18n.t('invoice_payment_request', { currency, order, expirationTime, rate, + days: ageInDays }); await ctx.telegram.sendMessage(user.tg_id, message); // Create QR code @@ -387,9 +398,11 @@ const onGoingTakeBuyMessage = async ( let expirationTime = time.hours + ' ' + i18nBuyer.t('hours'); expirationTime += time.minutes > 0 ? ' ' + time.minutes + ' ' + i18nBuyer.t('minutes') : ''; + // Extracting the buyer's days in the platform + const ageInDays = getUserAge(seller); await bot.telegram.sendMessage( buyer.tg_id, - i18nBuyer.t('someone_took_your_order', { expirationTime, rate }) + i18nBuyer.t('someone_took_your_order', { expirationTime, rate, days: ageInDays }) ); await bot.telegram.sendMessage(buyer.tg_id, order._id, { reply_markup: { diff --git a/bot/ordersActions.js b/bot/ordersActions.js index d67ad1fa..b0c071eb 100644 --- a/bot/ordersActions.js +++ b/bot/ordersActions.js @@ -8,6 +8,7 @@ const { getEmojiRate, decimalRound, getFee, + getUserAge } = require('../util'); const logger = require('../logger'); @@ -181,11 +182,7 @@ const buildDescription = ( rateText = `${roundedRating} ${stars} (${totalReviews})\n`; } - const userCreationDate = new Date(user.created_at); - const today = new Date(); - const ageInDays = Math.floor( - (today.getTime() - userCreationDate.getTime()) / (1000 * 3600 * 24) - ); + const ageInDays = getUserAge(user); let description = `${username}${action} ${amountText}` + i18n.t('sats') + `\n`; diff --git a/locales/de.yaml b/locales/de.yaml index 8dbc5055..078d2960 100644 --- a/locales/de.yaml +++ b/locales/de.yaml @@ -33,7 +33,7 @@ non_handle_error: 👤 Um diesen Bot zu nutzen, musst du deinen Telegram-Benutze invoice_payment_request: | Jemand möchte ${order.amount} Sats für ${currency} ${order.fiat_amount} kaufen. - Buyer Reputation: ${rate} + Buyer Reputation: ${rate}, Tage mit dem Bot: ${days} Bitte bezahle diese LN-Rechnung, um deinen Verkaufsprozess zu starten. Diese LN-Rechnung läuft in ${expirationTime} Minuten ab pending_sell: | @@ -111,7 +111,7 @@ someone_took_your_order: | Wenn dein Zahlungsabwickler die Zahlung aus irgendeinem Grund pausiert und das Geld nicht innerhalb von ${expirationTime} eintrifft, gehen die Sats an den Verkäufer zurück, wodurch der Käufer einem Risiko ausgesetzt ist und ich nicht in der Lage bin, den Verkäufer zu zwingen, die Sats erneut zu senden. - Verkäufer Ruf: ${rate} + Verkäufer Ruf: ${rate}, Tage mit dem Bot: ${days} Wenn du mit den obigen Angaben einverstanden bist, drücke den Button, um fortzufahren 👇 you_took_someone_order: | diff --git a/locales/en.yaml b/locales/en.yaml index bb9a14a4..4d019b13 100644 --- a/locales/en.yaml +++ b/locales/en.yaml @@ -37,7 +37,7 @@ non_handle_error: 👤 To use this bot, you need to activate your Telegram Usern invoice_payment_request: | Somebody wants to buy you ${order.amount} sats for ${currency} ${order.fiat_amount}. - Buyer Reputation: ${rate} + Buyer Reputation: ${rate}, days using the bot: ${days} Please pay this invoice to start up your selling process, it will expire in ${expirationTime} minutes pending_sell: | @@ -115,7 +115,7 @@ someone_took_your_order: | If, for any reason, your payment processor puts the payment on pause and the funds do not arrive in less than ${expirationTime}, the sats will return to the seller, putting the buyer at risk. I cannot force the seller to send the sats again. - Seller Reputation: ${rate} + Seller Reputation: ${rate}, days using the bot: ${days} If you agree with the above, press the button to continue 👇 you_took_someone_order: | diff --git a/locales/es.yaml b/locales/es.yaml index 5b95d76e..c064a023 100644 --- a/locales/es.yaml +++ b/locales/es.yaml @@ -33,7 +33,7 @@ non_handle_error: 👤 Para usar este bot debes activar tu username de telegram, invoice_payment_request: | Un usuario quiere comprarte ${order.amount} sats por ${currency} ${order.fiat_amount}. - Reputación del comprador: ${rate} + Reputación del comprador: ${rate}, días utilizando el bot: ${days} Si deseas continuar por favor paga esta factura, esta factura expira en ${expirationTime} minutos pending_sell: | @@ -111,7 +111,7 @@ someone_took_your_order: | Si por alguna razón tu procesador de pagos pusiera el pago en pausa y los fondos no llegasen en un lapso menor a ${expirationTime}, los sats regresarán al vendedor, poniendo al comprador en riesgo y yo no podré obligar al vendedor a enviar nuevamente los sats. - Reputación del vendedor: ${rate} + Reputación del vendedor: ${rate}, días utilizando el bot: ${days} Si estás de acuerdo con lo arriba expresado presiona el botón para continuar 👇 you_took_someone_order: | diff --git a/locales/fr.yaml b/locales/fr.yaml index ae89876f..db4d9d84 100644 --- a/locales/fr.yaml +++ b/locales/fr.yaml @@ -37,7 +37,7 @@ non_handle_error: 👤 Pour utiliser ce bot, tu dois d'abord activer ton nom d'u invoice_payment_request: | Quelqu'un veut t'acheter ${order.amount} sats à ${order.fiat_amount} ${currency}. - Buyer Reputation: ${rate} + Buyer Reputation: ${rate}, jours d'utilisation du bot: ${days} Merci de régler cette facture pour démarrer le processus de vente, elle expirera dans ${expirationTime} minutes pending_sell: | @@ -115,7 +115,7 @@ someone_took_your_order: | Si pour une raison quelconque le processeur de paiement met le paiement en pause et que les fonds ne sont pas arrivés en moins de ${expirationTime}, les sats seront retournés au vendeur, mettant l'acheteur dans une position risquée. Je ne peux pas obliger le vendeur à vendre ses sats de nouveau. - Seller Reputation: ${rate} + Seller Reputation: ${rate}, jours d'utilisation du bot: ${days} Si tu es d'accord avec ce qui précède, clique sur le bouton pour continuer 👇 you_took_someone_order: | diff --git a/locales/it.yaml b/locales/it.yaml index bf946ad5..dcfaa5f8 100644 --- a/locales/it.yaml +++ b/locales/it.yaml @@ -33,7 +33,7 @@ non_handle_error: 👤 Per utilizzare questo bot è necessario impostare il prop invoice_payment_request: | Qualcuno richiede di comprare da te ${order.amount} sats per ${currency} ${order.fiat_amount}. - Reputazione del compratore: ${rate} + Reputazione del compratore: ${rate}, giorni di utilizzo del bot: ${days} Si prega di procedere al pagamento di questa invoice per avviare il processo di vendita, la invoice scadrà tra ${expirationTime} minuti pending_sell: | @@ -111,7 +111,7 @@ someone_took_your_order: | Se per qualche motivo il metodo di pagamento mette in pausa il trasferimento e i fondi non arrivano in meno di ${expirationTime}, i satoshi torneranno al venditore, mettendo a rischio l'acquirente e non potrò costringere il venditore a inviare di nuovo i fondi. - Reputazione del venditore: ${rate} + Reputazione del venditore: ${rate}, giorni di utilizzo del bot: ${days} Se accetti le condizioni, premi per continuare 👇 you_took_someone_order: | diff --git a/locales/pt.yaml b/locales/pt.yaml index f2b33475..95543323 100644 --- a/locales/pt.yaml +++ b/locales/pt.yaml @@ -33,7 +33,7 @@ non_handle_error: 👤 Para usar este bot, você precisa ativar seu nome de usu invoice_payment_request: | Alguém quer te comprar ${order.amount} sats por ${currency} ${order.fiat_amount}. - Reputação do comprador: ${rate} + Reputação do comprador: ${rate}, dias usando o bot: ${days} Por favor, pague esta fatura para iniciar seu processo de venda, esta fatura expirará ${expirationTime} minutos pending_sell: | @@ -111,7 +111,7 @@ someone_took_your_order: | Se por algum motivo o seu processador de pagamento coloca o pagamento em pausa e os fundos não chegam em menos de ${expirationTime}, Os SATs retornarão ao vendedor, colocando o comprador em risco e não poderei forçar o vendedor a enviar os sats novamente. - Reputação do vendedor: ${rate} + Reputação do vendedor: ${rate}, dias usando o bot: ${days} Se você concorda com o exposto acima, pressione o botão para continuar 👇 you_took_someone_order: | diff --git a/locales/ru.yaml b/locales/ru.yaml index bb60569a..37ddb840 100644 --- a/locales/ru.yaml +++ b/locales/ru.yaml @@ -33,7 +33,7 @@ non_handle_error: 👤 Для пользования этим ботом нуж invoice_payment_request: | Кто-то хочет купить ваши ${order.amount} сатоши за ${currency} ${order.fiat_amount}. - Buyer Reputation: ${rate} + Репутация продавца: ${rate}, дней использования бота: ${days} Пожалуйста, оплатите этот счет, чтобы начать продажу. Срок действия этого счета истекает через ${expirationTime} минут pending_sell: | @@ -110,7 +110,7 @@ someone_took_your_order: | Если по какой-либо причине Ваша платежная система задержит перевод, и средства не поступят в течение ${expirationTime}, сатоши будут автоматически возвращены продавцу. В этом случае покупатель несет риск, что мы не сможем убедить продавца выслать сатоши заново. - Seller Reputation: ${rate} + Репутация продавца: ${rate}, дней использования бота: ${days} Если Вы согласны с таким условием, нажмите кнопку Продолжить 👇 you_took_someone_order: | diff --git a/locales/uk.yaml b/locales/uk.yaml index c1bf8d53..865027bc 100644 --- a/locales/uk.yaml +++ b/locales/uk.yaml @@ -33,7 +33,7 @@ non_handle_error: 👤 Для користування цим ботом пот invoice_payment_request: | Хтось хоче купити Ваші ${order.amount} Сатоші за ${currency} ${order.fiat_amount}. - Buyer Reputation: ${rate} + Репутація продавця: ${rate}, днів використання бота: ${days} Будь ласка, сплатіть цей рахунок, щоб почати продаж. Термін дії цього рахунку закінчується через ${expirationTime} хвилин pending_sell: | @@ -111,7 +111,7 @@ someone_took_your_order: | Якщо з будь-якої причини Ваша платіжна система затримає переказ і кошти не надійдуть протягом ${expirationTime}, сатоші будуть автоматично повернені продавцю. У цьому випадку покупець несе ризик, що ми не зможемо переконати продавця вислати сатоші знову. - Seller Reputation: ${rate} + Репутація продавця: ${rate}, днів використання бота: ${days} Якщо Ви погоджуєтеся з такою умовою, натисніть кнопку Продовжити 👇 you_took_someone_order: | diff --git a/util/index.js b/util/index.js index 44b3a2dc..a658d49f 100644 --- a/util/index.js +++ b/util/index.js @@ -418,6 +418,16 @@ const holdInvoiceExpirationInSecs = () => { }; }; +// Returns the user age in days +const getUserAge = (user) => { + const userCreationDate = new Date(user.created_at); + const today = new Date(); + const ageInDays = Math.floor( + (today.getTime() - userCreationDate.getTime()) / (1000 * 3600 * 24) + ); + return ageInDays +} + module.exports = { isIso4217, plural, @@ -446,4 +456,5 @@ module.exports = { getLanguageFlag, delay, holdInvoiceExpirationInSecs, + getUserAge };