Skip to content

Commit

Permalink
Displays counterparty age when a user's order is taken (lnp2pBot#411)
Browse files Browse the repository at this point in the history
While a previous feature exposed the order maker's age in the order
itself, this information has been absent for the maker
  • Loading branch information
bilthon authored and dolchi21 committed Sep 3, 2023
1 parent 816b23c commit 0822971
Show file tree
Hide file tree
Showing 12 changed files with 46 additions and 30 deletions.
9 changes: 2 additions & 7 deletions bot/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ const {
deleteOrderFromChannel,
getUserI18nContext,
getFee,
getEmojiRate,
decimalRound,
} = require('../util');
const ordersActions = require('./ordersActions');

Expand Down Expand Up @@ -69,19 +67,16 @@ 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,
seller,
request,
order,
i18nCtx,
rate
buyer
);
await messages.takeSellWaitingSellerToPayMessage(ctx, bot, buyer, order);
}
Expand Down
17 changes: 15 additions & 2 deletions bot/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ const {
getOrderChannel,
holdInvoiceExpirationInSecs,
sanitizeMD,
getEmojiRate,
decimalRound,
getUserAge
} = require('../util');
const logger = require('../logger');

Expand Down Expand Up @@ -56,7 +59,7 @@ const invoicePaymentRequestMessage = async (
request,
order,
i18n,
rate
buyer
) => {
try {
let currency = getCurrency(order.fiat_code);
Expand All @@ -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
Expand Down Expand Up @@ -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: {
Expand Down
7 changes: 2 additions & 5 deletions bot/ordersActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const {
getEmojiRate,
decimalRound,
getFee,
getUserAge
} = require('../util');
const logger = require('../logger');

Expand Down Expand Up @@ -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`;
Expand Down
4 changes: 2 additions & 2 deletions locales/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down Expand Up @@ -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: |
Expand Down
4 changes: 2 additions & 2 deletions locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down Expand Up @@ -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: |
Expand Down
4 changes: 2 additions & 2 deletions locales/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down Expand Up @@ -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: |
Expand Down
4 changes: 2 additions & 2 deletions locales/fr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down Expand Up @@ -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: |
Expand Down
4 changes: 2 additions & 2 deletions locales/it.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down Expand Up @@ -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: |
Expand Down
4 changes: 2 additions & 2 deletions locales/pt.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down Expand Up @@ -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: |
Expand Down
4 changes: 2 additions & 2 deletions locales/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ non_handle_error: 👤 Для пользования этим ботом нуж
invoice_payment_request: |
Кто-то хочет купить ваши ${order.amount} сатоши за ${currency} ${order.fiat_amount}.
Buyer Reputation: ${rate}
Репутация продавца: ${rate}, дней использования бота: ${days}
Пожалуйста, оплатите этот счет, чтобы начать продажу. Срок действия этого счета истекает через ${expirationTime} минут
pending_sell: |
Expand Down Expand Up @@ -110,7 +110,7 @@ someone_took_your_order: |
Если по какой-либо причине Ваша платежная система задержит перевод, и средства не поступят в течение ${expirationTime}, сатоши будут автоматически возвращены продавцу. В этом случае покупатель несет риск, что мы не сможем убедить продавца выслать сатоши заново.
Seller Reputation: ${rate}
Репутация продавца: ${rate}, дней использования бота: ${days}
Если Вы согласны с таким условием, нажмите кнопку Продолжить 👇
you_took_someone_order: |
Expand Down
4 changes: 2 additions & 2 deletions locales/uk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ non_handle_error: 👤 Для користування цим ботом пот
invoice_payment_request: |
Хтось хоче купити Ваші ${order.amount} Сатоші за ${currency} ${order.fiat_amount}.
Buyer Reputation: ${rate}
Репутація продавця: ${rate}, днів використання бота: ${days}
Будь ласка, сплатіть цей рахунок, щоб почати продаж. Термін дії цього рахунку закінчується через ${expirationTime} хвилин
pending_sell: |
Expand Down Expand Up @@ -111,7 +111,7 @@ someone_took_your_order: |
Якщо з будь-якої причини Ваша платіжна система затримає переказ і кошти не надійдуть протягом ${expirationTime}, сатоші будуть автоматично повернені продавцю. У цьому випадку покупець несе ризик, що ми не зможемо переконати продавця вислати сатоші знову.
Seller Reputation: ${rate}
Репутація продавця: ${rate}, днів використання бота: ${days}
Якщо Ви погоджуєтеся з такою умовою, натисніть кнопку Продовжити 👇
you_took_someone_order: |
Expand Down
11 changes: 11 additions & 0 deletions util/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -446,4 +456,5 @@ module.exports = {
getLanguageFlag,
delay,
holdInvoiceExpirationInSecs,
getUserAge
};

0 comments on commit 0822971

Please sign in to comment.