diff --git a/backend/src/auth/RIGHTS.ts b/backend/src/auth/RIGHTS.ts index 3b3f7580c..6bcd3fa43 100644 --- a/backend/src/auth/RIGHTS.ts +++ b/backend/src/auth/RIGHTS.ts @@ -18,6 +18,8 @@ export enum RIGHTS { SET_PASSWORD = 'SET_PASSWORD', UPDATE_USER_INFOS = 'UPDATE_USER_INFOS', HAS_ELOPAGE = 'HAS_ELOPAGE', + CREATE_TRANSACTION_LINK = 'CREATE_TRANSACTION_LINK', + QUERY_TRANSACTION_LINK = 'QUERY_TRANSACTION_LINK', // Admin SEARCH_USERS = 'SEARCH_USERS', CREATE_PENDING_CREATION = 'CREATE_PENDING_CREATION', diff --git a/backend/src/auth/ROLES.ts b/backend/src/auth/ROLES.ts index ada6a2cef..37a4e3a67 100644 --- a/backend/src/auth/ROLES.ts +++ b/backend/src/auth/ROLES.ts @@ -18,6 +18,7 @@ export const ROLE_USER = new Role('user', [ RIGHTS.LOGOUT, RIGHTS.UPDATE_USER_INFOS, RIGHTS.HAS_ELOPAGE, + RIGHTS.CREATE_TRANSACTION_LINK, ]) export const ROLE_ADMIN = new Role('admin', Object.values(RIGHTS)) // all rights diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index 82fb9ff2b..4cd428153 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -10,7 +10,7 @@ Decimal.set({ }) const constants = { - DB_VERSION: '0029-clean_transaction_table', + DB_VERSION: '0030-transaction_link', DECAY_START_TIME: new Date('2021-05-13 17:46:31'), // GMT+0 } diff --git a/backend/src/graphql/arg/TransactionLinkArgs.ts b/backend/src/graphql/arg/TransactionLinkArgs.ts new file mode 100644 index 000000000..5ccb967d3 --- /dev/null +++ b/backend/src/graphql/arg/TransactionLinkArgs.ts @@ -0,0 +1,14 @@ +import { ArgsType, Field } from 'type-graphql' +import Decimal from 'decimal.js-light' + +@ArgsType() +export default class TransactionLinkArgs { + @Field(() => Decimal) + amount: Decimal + + @Field(() => String) + memo: string + + @Field(() => Boolean, { nullable: true }) + showEmail?: boolean +} diff --git a/backend/src/graphql/model/TransactionLink.ts b/backend/src/graphql/model/TransactionLink.ts new file mode 100644 index 000000000..98f86a772 --- /dev/null +++ b/backend/src/graphql/model/TransactionLink.ts @@ -0,0 +1,50 @@ +import { ObjectType, Field } from 'type-graphql' +import Decimal from 'decimal.js-light' +import { TransactionLink as dbTransactionLink } from '@entity/TransactionLink' +import { User } from './User' + +@ObjectType() +export class TransactionLink { + constructor(transactionLink: dbTransactionLink, user: User) { + this.id = transactionLink.id + this.user = user + this.amount = transactionLink.amount + this.memo = transactionLink.memo + this.code = transactionLink.code + this.createdAt = transactionLink.createdAt + this.validUntil = transactionLink.validUntil + this.showEmail = transactionLink.showEmail + this.redeemedAt = null + this.redeemedBy = null + } + + @Field(() => Number) + id: number + + @Field(() => User) + user: User + + @Field(() => Decimal) + amount: Decimal + + @Field(() => String) + memo: string + + @Field(() => String) + code: string + + @Field(() => Date) + createdAt: Date + + @Field(() => Date) + validUntil: Date + + @Field(() => Boolean) + showEmail: boolean + + @Field(() => Date, { nullable: true }) + redeemedAt: Date | null + + @Field(() => User, { nullable: true }) + redeemedBy: User | null +} diff --git a/backend/src/graphql/resolver/TransactionLinkResolver.test.ts b/backend/src/graphql/resolver/TransactionLinkResolver.test.ts new file mode 100644 index 000000000..51790502d --- /dev/null +++ b/backend/src/graphql/resolver/TransactionLinkResolver.test.ts @@ -0,0 +1,14 @@ +import { transactionLinkCode } from './TransactionLinkResolver' + +describe('transactionLinkCode', () => { + const date = new Date() + + it('returns a string of length 96', () => { + expect(transactionLinkCode(date)).toHaveLength(96) + }) + + it('returns a string that ends with the hex value of date', () => { + const regexp = new RegExp(date.getTime().toString(16) + '$') + expect(transactionLinkCode(date)).toEqual(expect.stringMatching(regexp)) + }) +}) diff --git a/backend/src/graphql/resolver/TransactionLinkResolver.ts b/backend/src/graphql/resolver/TransactionLinkResolver.ts new file mode 100644 index 000000000..3091465d5 --- /dev/null +++ b/backend/src/graphql/resolver/TransactionLinkResolver.ts @@ -0,0 +1,74 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ + +import { Resolver, Args, Authorized, Ctx, Mutation, Query, Arg } from 'type-graphql' +import { getCustomRepository } from '@dbTools/typeorm' +import { TransactionLink } from '@model/TransactionLink' +import { TransactionLink as dbTransactionLink } from '@entity/TransactionLink' +import TransactionLinkArgs from '@arg/TransactionLinkArgs' +import { UserRepository } from '@repository/User' +import { calculateBalance } from '@/util/validate' +import { RIGHTS } from '@/auth/RIGHTS' +import { randomBytes } from 'crypto' +import { User } from '@model/User' + +// TODO: do not export, test it inside the resolver +export const transactionLinkCode = (date: Date): string => { + const time = date.getTime().toString(16) + return ( + randomBytes(48) + .toString('hex') + .substring(0, 96 - time.length) + time + ) +} + +const transactionLinkExpireDate = (date: Date): Date => { + // valid for 14 days + return new Date(date.setDate(date.getDate() + 14)) +} + +@Resolver() +export class TransactionLinkResolver { + @Authorized([RIGHTS.CREATE_TRANSACTION_LINK]) + @Mutation(() => TransactionLink) + async createTransactionLink( + @Args() { amount, memo, showEmail = false }: TransactionLinkArgs, + @Ctx() context: any, + ): Promise { + const userRepository = getCustomRepository(UserRepository) + const user = await userRepository.findByPubkeyHex(context.pubKey) + + // validate amount + // TODO taken from transaction resolver, duplicate code + const createdDate = new Date() + const sendBalance = await calculateBalance(user.id, amount.mul(-1), createdDate) + if (!sendBalance) { + throw new Error("user hasn't enough GDD or amount is < 0") + } + + // TODO!!!! Test balance for pending transaction links + + const transactionLink = dbTransactionLink.create() + transactionLink.userId = user.id + transactionLink.amount = amount + transactionLink.memo = memo + transactionLink.code = transactionLinkCode(createdDate) + transactionLink.createdAt = createdDate + transactionLink.validUntil = transactionLinkExpireDate(createdDate) + transactionLink.showEmail = showEmail + await dbTransactionLink.save(transactionLink).catch((error) => { + throw error + }) + + return new TransactionLink(transactionLink, new User(user)) + } + + @Authorized([RIGHTS.QUERY_TRANSACTION_LINK]) + @Query(() => TransactionLink) + async queryTransactionLink(@Arg('code') code: string): Promise { + const transactionLink = await dbTransactionLink.findOneOrFail({ code }) + const userRepository = getCustomRepository(UserRepository) + const user = await userRepository.findOneOrFail({ id: transactionLink.userId }) + return new TransactionLink(transactionLink, new User(user)) + } +} diff --git a/database/entity/0030-transaction_link/TransactionLink.ts b/database/entity/0030-transaction_link/TransactionLink.ts new file mode 100644 index 000000000..a3ab5cd1a --- /dev/null +++ b/database/entity/0030-transaction_link/TransactionLink.ts @@ -0,0 +1,58 @@ +import Decimal from 'decimal.js-light' +import { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from 'typeorm' +import { DecimalTransformer } from '../../src/typeorm/DecimalTransformer' + +@Entity('transaction_links') +export class TransactionLink extends BaseEntity { + @PrimaryGeneratedColumn('increment', { unsigned: true }) + id: number + + @Column({ unsigned: true, nullable: false }) + userId: number + + @Column({ + type: 'decimal', + precision: 40, + scale: 20, + nullable: false, + transformer: DecimalTransformer, + }) + amount: Decimal + + @Column({ length: 255, nullable: false, collation: 'utf8mb4_unicode_ci' }) + memo: string + + @Column({ length: 96, nullable: false, collation: 'utf8mb4_unicode_ci' }) + code: string + + @Column({ + type: 'datetime', + default: () => 'CURRENT_TIMESTAMP', + nullable: false, + }) + createdAt: Date + + @Column({ + type: 'datetime', + default: () => 'CURRENT_TIMESTAMP', + nullable: false, + }) + validUntil: Date + + @Column({ + type: 'boolean', + default: () => false, + nullable: false, + }) + showEmail: boolean + + @Column({ + type: 'datetime', + default: () => 'CURRENT_TIMESTAMP', + nullable: true, + }) + redeemedAt?: Date | null + + @Column({ type: 'int', unsigned: true, nullable: true }) + redeemedBy?: number | null +} diff --git a/database/entity/TransactionLink.ts b/database/entity/TransactionLink.ts new file mode 100644 index 000000000..fde2ba9e0 --- /dev/null +++ b/database/entity/TransactionLink.ts @@ -0,0 +1 @@ +export { TransactionLink } from './0030-transaction_link/TransactionLink' diff --git a/database/entity/index.ts b/database/entity/index.ts index bee4e2b77..cb6f56ab0 100644 --- a/database/entity/index.ts +++ b/database/entity/index.ts @@ -3,6 +3,7 @@ import { LoginEmailOptIn } from './LoginEmailOptIn' import { Migration } from './Migration' import { ServerUser } from './ServerUser' import { Transaction } from './Transaction' +import { TransactionLink } from './TransactionLink' import { User } from './User' import { UserSetting } from './UserSetting' import { AdminPendingCreation } from './AdminPendingCreation' @@ -14,6 +15,7 @@ export const entities = [ Migration, ServerUser, Transaction, + TransactionLink, User, UserSetting, ] diff --git a/database/migrations/0030-transaction_link.ts b/database/migrations/0030-transaction_link.ts new file mode 100644 index 000000000..59eba1090 --- /dev/null +++ b/database/migrations/0030-transaction_link.ts @@ -0,0 +1,26 @@ +/* MIGRATION TO CREATE TRANSACTION_LINK TABLE */ + +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +export async function upgrade(queryFn: (query: string, values?: any[]) => Promise>) { + await queryFn(` + CREATE TABLE \`transaction_links\` ( + \`id\` int UNSIGNED NOT NULL AUTO_INCREMENT, + \`userId\` int UNSIGNED NOT NULL, + \`amount\` DECIMAL(40,20) NOT NULL, + \`memo\` varchar(255) NOT NULL, + \`code\` varchar(96) NOT NULL, + \`createdAt\` datetime NOT NULL, + \`validUntil\` datetime NOT NULL, + \`showEmail\` boolean NOT NULL DEFAULT false, + \`redeemedAt\` datetime, + \`redeemedBy\` int UNSIGNED, + PRIMARY KEY (\`id\`) + ) ENGINE = InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + `) +} + +export async function downgrade(queryFn: (query: string, values?: any[]) => Promise>) { + await queryFn(`DROP TABLE \`transaction_links\`;`) +} diff --git a/frontend/src/components/DecayInformations/DecayInformation-Decay.vue b/frontend/src/components/DecayInformations/DecayInformation-Decay.vue index 0dc00a79a..80d45e242 100644 --- a/frontend/src/components/DecayInformations/DecayInformation-Decay.vue +++ b/frontend/src/components/DecayInformations/DecayInformation-Decay.vue @@ -13,9 +13,9 @@
- {{ $n(Number(balance) - Number(decay.decay), 'decimal') }} - GDD − {{ $n(Number(decay.decay) * -1, 'decimal') }} GDD = - {{ $n(Number(balance), 'decimal') }} GDD + {{ (Number(balance) - Number(decay.decay)) | GDD }} + {{ decay.decay | GDD }} = + {{ balance | GDD }}
diff --git a/frontend/src/components/DecayInformations/DecayInformation-DecayStartblock.vue b/frontend/src/components/DecayInformations/DecayInformation-DecayStartblock.vue index 678fc9f09..2ee9ecc2c 100644 --- a/frontend/src/components/DecayInformations/DecayInformation-DecayStartblock.vue +++ b/frontend/src/components/DecayInformations/DecayInformation-DecayStartblock.vue @@ -17,12 +17,8 @@ - -
{{ $t('decay.decay') }}
-
- -
− {{ $n(decay.decay * -1, 'decimal') }}
-
+ {{ $t('decay.decay') }} + {{ decay.decay | GDD }}

@@ -32,39 +28,19 @@ - -
{{ $t('decay.sent') }}
-
{{ $t('decay.received') }}
-
- -
− {{ $n(amount * -1, 'decimal') }}
-
{{ $n(amount, 'decimal') }}
-
+ {{ $t(`decay.${typeId.toLowerCase()}`) }} + {{ amount | GDD }}
- -
{{ $t('decay.decay') }}
-
- -
− {{ $n(decay.decay * -1, 'decimal') }}
-
+ {{ $t('decay.decay') }} + {{ decay.decay | GDD }}
- -
{{ $t('decay.total') }}
-
+ {{ $t('decay.total') }} -
- − {{ $n((Number(amount) + Number(decay.decay)) * -1, 'decimal') }} -
-
- {{ $n(Number(amount) + Number(decay.decay), 'decimal') }} -
-
- {{ $n(Number(amount) + Number(decay.decay), 'decimal') }} -
+ {{ (Number(amount) + Number(decay.decay)) | GDD }}
diff --git a/frontend/src/components/DecayInformations/DecayInformation-Long.vue b/frontend/src/components/DecayInformations/DecayInformation-Long.vue index ac53b77b7..6a0b6a1c1 100644 --- a/frontend/src/components/DecayInformations/DecayInformation-Long.vue +++ b/frontend/src/components/DecayInformations/DecayInformation-Long.vue @@ -25,14 +25,7 @@
{{ $t('decay.past_time') }}
- - {{ duration.years }} {{ $t('decay.year') }}, - {{ duration.months }} {{ $t('decay.months') }}, - {{ duration.days }} {{ $t('decay.days') }}, - {{ duration.hours }} {{ $t('decay.hours') }}, - {{ duration.minutes }} {{ $t('decay.minutes') }}, - {{ duration.seconds }} {{ $t('decay.seconds') }} - + {{ durationText }} @@ -41,9 +34,7 @@
{{ $t('decay.decay') }}
- -
− {{ $n(decay.decay * -1, 'decimal') }}
-
+ {{ decay.decay | GDD }}
@@ -53,23 +44,13 @@ - -
{{ $t('decay.sent') }}
-
{{ $t('decay.received') }}
-
- -
− {{ $n(amount * -1, 'decimal') }}
-
{{ $n(amount, 'decimal') }}
-
+ {{ $t(`decay.${typeId.toLowerCase()}`) }} + {{ amount | GDD }}
- -
{{ $t('decay.decay') }}
-
- -
− {{ $n(decay.decay * -1, 'decimal') }}
-
+ {{ $t('decay.decay') }} + {{ decay.decay | GDD }}
@@ -77,15 +58,7 @@
{{ $t('decay.total') }}
-
- − {{ $n((Number(amount) + Number(decay.decay)) * -1, 'decimal') }} -
-
- {{ $n(Number(amount) + Number(decay.decay), 'decimal') }} -
-
- {{ $n(Number(amount) + Number(decay.decay), 'decimal') }} -
+ {{ (Number(amount) + Number(decay.decay)) | GDD }}
@@ -104,6 +77,17 @@ export default { duration() { return this.$moment.duration(new Date(this.decay.end) - new Date(this.decay.start))._data }, + durationText() { + const order = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'] + const result = [] + order.forEach((timeSpan) => { + if (this.duration[timeSpan] > 0) { + const locale = this.$t(`decay.${timeSpan}`) + result.push(`${this.duration[timeSpan]} ${locale}`) + } + }) + return result.join(', ') + }, }, } diff --git a/frontend/src/components/DecayInformations/DecayInformation-Short.vue b/frontend/src/components/DecayInformations/DecayInformation-Short.vue index 8dba700d5..3bed4b9cc 100644 --- a/frontend/src/components/DecayInformations/DecayInformation-Short.vue +++ b/frontend/src/components/DecayInformations/DecayInformation-Short.vue @@ -1,6 +1,6 @@