Skip to content

Commit

Permalink
Add undo function (#7)
Browse files Browse the repository at this point in the history
* Add undo function

* Change undoing db mechanism

* Stop undoing positive transactions
  • Loading branch information
christiansegercrantz authored Apr 8, 2024
1 parent 43d88ef commit a34a8c2
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 15 deletions.
4 changes: 1 addition & 3 deletions backend/src/admin/saldo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ const allHistoryCommand = bot.command('historia_all', async (ctx) => {
parsedHistory.forEach((row) => {
res +=
`\n${row.user_name.split(' ').slice(0, -1).join(' ')}, ` +
`${formatDateToString(
row.created_at
)} ${row.created_at.toLocaleTimeString('sv-fi')}, ` +
`${formatDateToString(row.created_at, true)}, ` +
`${centsToEuroString(-row.amount_cents)}, ` +
`${row.description}`
})
Expand Down
2 changes: 1 addition & 1 deletion backend/src/db_setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ await pool.query(
`CREATE TABLE IF NOT EXISTS transactions(
id SERIAL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
user_id BIGINT,
user_id BIGINT NOT NULL,
user_name TEXT,
description TEXT,
amount_cents INTEGER
Expand Down
52 changes: 48 additions & 4 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { Context, Markup, Telegraf, session } from 'telegraf'
import { config } from './config.js'
import {
TransactionInsert,
exportTransactionsForOneUser,
getBalanceForMember,
purchaseItemForMember,
Expand Down Expand Up @@ -164,7 +165,7 @@ products.forEach(({ name, description, price_cents }) => {
//#region History

bot.command('historia', async (ctx) => {
const history = await exportTransactionsForOneUser(ctx.from.id)
const history = await exportTransactionsForOneUser(ctx.from.id, 30)

const parsedHistory = history.rows.map(
({ created_at, description, amount_cents }) => {
Expand All @@ -179,9 +180,7 @@ bot.command('historia', async (ctx) => {
var res = `Ditt nuvarande saldo är ${saldo}. Här är din historia:\`\`\``
parsedHistory.forEach((row) => {
res +=
`\n${formatDateToString(
row.created_at
)} ${row.created_at.toLocaleTimeString('sv-fi')}, ` +
`\n${formatDateToString(row.created_at, true)}, ` +
`${centsToEuroString(-row.amount_cents)}, ` +
`${row.description}`
})
Expand All @@ -191,6 +190,50 @@ bot.command('historia', async (ctx) => {

//endregion

//#region Undo

bot.command('undo', async (ctx) => {
const queryResult = await exportTransactionsForOneUser(ctx.from.id, 1)
const latestTransaction = queryResult.rows[0]

const description = latestTransaction.description
if (description.includes('_undo') || description.includes('Manuell_')) {
return ctx.reply('Din senaste händelse är redan ångrad')
}

if (latestTransaction.amount_cents > 0) {
return ctx.reply('Du kan inte ångra en insättning')
}

try {
const productUndone = {
userId: latestTransaction.user_id,
userName: latestTransaction.user_name,
description: latestTransaction.description + '_undo',
amountCents: String(-latestTransaction.amount_cents),
} as TransactionInsert
await purchaseItemForMember(productUndone)

const message =
'Följande transaction har ångrats: \n' +
`\t\tTid: ${formatDateToString(latestTransaction.created_at, true)}\n` +
`\t\tProdukt: ${latestTransaction.description}\n` +
`\t\tPris: ${centsToEuroString(latestTransaction.amount_cents)}`

ctx.reply(message)
console.log(
`User id ${ctx.from.id} undid transaction id ${latestTransaction.id}`
)
} catch (e) {
ctx.reply('Kunde inte ångra din senaste transaktion, kontakta Cropieren')
console.log(
`User id ${ctx.from.id} tried to undo a transaction and faced the following problem error: ${e}`
)
}
})

//endregion

//#region Misc commands

bot.command('saldo', async (ctx) => {
Expand All @@ -217,6 +260,7 @@ bot.telegram.setMyCommands([
{ command: 'info', description: 'Visar information om bottens användning' },
{ command: 'meny', description: 'Tar upp köp menyn för alla produkter' },
{ command: 'historia', description: 'Se din egna transaktionshistorik' },
{ command: 'undo', description: 'Ångra ditt senaste köp' },
])

// Admin middleware is used for all commands added after this line!
Expand Down
9 changes: 5 additions & 4 deletions backend/src/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { QueryResult } from 'pg'
export interface Transaction {
id: number
created_at: Date
userId: number
user_id: number
user_name: string
description: string
amount_cents: number
Expand Down Expand Up @@ -60,16 +60,17 @@ export const exportTransactions = async (): Promise<
}

export const exportTransactionsForOneUser = async (
userId: number
userId: number,
transactionCount: number
): Promise<QueryResult<Transaction>> => {
const res = await pool.query(
`--sql
SELECT *
FROM transactions
WHERE user_id = $1
ORDER BY id DESC
LIMIT 30`,
[userId]
LIMIT $2`,
[userId, transactionCount]
)
return res
}
Expand Down
16 changes: 13 additions & 3 deletions backend/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,22 @@ export const createCsv = (queryResult: QueryResult<any>) => {
${rows.join('\n')}`
}

export const formatDateToString = (date: Date) => {
return `${date.toLocaleDateString('sv-fi', {
export const formatDateToString = (
date: Date,
includeTime: Boolean = false
) => {
const dateFormated = date.toLocaleDateString('sv-fi', {
year: '2-digit',
month: '2-digit',
day: '2-digit',
})} ${date.toLocaleDateString('sv-fi', { weekday: 'short' })}`
})
const dayFormated = date.toLocaleDateString('sv-fi', {
weekday: 'short',
})
const timeFormated = includeTime
? `kl. ${date.toLocaleTimeString('sv-fi')}`
: ''
return `${dateFormated} ${dayFormated} ${timeFormated}`
}

/**
Expand Down

0 comments on commit a34a8c2

Please sign in to comment.