Merge branch 'master' into enforce_config_version

This commit is contained in:
Ulf Gebhardt 2022-03-23 19:56:36 +01:00 committed by GitHub
commit eaed95cdf8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
76 changed files with 1425 additions and 494 deletions

View File

@ -438,7 +438,7 @@ jobs:
report_name: Coverage Frontend report_name: Coverage Frontend
type: lcov type: lcov
result_path: ./coverage/lcov.info result_path: ./coverage/lcov.info
min_coverage: 94 min_coverage: 95
token: ${{ github.token }} token: ${{ github.token }}
############################################################################## ##############################################################################

View File

@ -6,32 +6,30 @@ const localVue = global.localVue
const apolloQueryMock = jest.fn().mockResolvedValue({ const apolloQueryMock = jest.fn().mockResolvedValue({
data: { data: {
transactionList: { creationTransactionList: [
transactions: [ {
{ id: 1,
id: 1, amount: 100,
amount: 100, balanceDate: 0,
balanceDate: 0, creationDate: new Date(),
creationDate: new Date(), memo: 'Testing',
memo: 'Testing', linkedUser: {
linkedUser: { firstName: 'Gradido',
firstName: 'Gradido', lastName: 'Akademie',
lastName: 'Akademie',
},
}, },
{ },
id: 2, {
amount: 200, id: 2,
balanceDate: 0, amount: 200,
creationDate: new Date(), balanceDate: 0,
memo: 'Testing 2', creationDate: new Date(),
linkedUser: { memo: 'Testing 2',
firstName: 'Gradido', linkedUser: {
lastName: 'Akademie', firstName: 'Gradido',
}, lastName: 'Akademie',
}, },
], },
}, ],
}, },
}) })
@ -67,7 +65,6 @@ describe('CreationTransactionListFormular', () => {
currentPage: 1, currentPage: 1,
pageSize: 25, pageSize: 25,
order: 'DESC', order: 'DESC',
onlyCreations: true,
userId: 1, userId: 1,
}, },
}), }),

View File

@ -5,7 +5,7 @@
</div> </div>
</template> </template>
<script> <script>
import { transactionList } from '../graphql/transactionList' import { creationTransactionList } from '../graphql/creationTransactionList'
export default { export default {
name: 'CreationTransactionList', name: 'CreationTransactionList',
props: { props: {
@ -51,17 +51,16 @@ export default {
getTransactions() { getTransactions() {
this.$apollo this.$apollo
.query({ .query({
query: transactionList, query: creationTransactionList,
variables: { variables: {
currentPage: 1, currentPage: 1,
pageSize: 25, pageSize: 25,
order: 'DESC', order: 'DESC',
onlyCreations: true,
userId: parseInt(this.userId), userId: parseInt(this.userId),
}, },
}) })
.then((result) => { .then((result) => {
this.items = result.data.transactionList.transactions this.items = result.data.creationTransactionList
}) })
.catch((error) => { .catch((error) => {
this.toastError(error.message) this.toastError(error.message)

View File

@ -1,7 +1,7 @@
import gql from 'graphql-tag' import gql from 'graphql-tag'
export const confirmPendingCreation = gql` export const confirmPendingCreation = gql`
mutation ($id: Float!) { mutation ($id: Int!) {
confirmPendingCreation(id: $id) confirmPendingCreation(id: $id)
} }
` `

View File

@ -0,0 +1,22 @@
import gql from 'graphql-tag'
export const creationTransactionList = gql`
query ($currentPage: Int = 1, $pageSize: Int = 25, $order: Order = DESC, $userId: Int!) {
creationTransactionList(
currentPage: $currentPage
pageSize: $pageSize
order: $order
userId: $userId
) {
id
amount
balanceDate
creationDate
memo
linkedUser {
firstName
lastName
}
}
}
`

View File

@ -1,7 +1,7 @@
import gql from 'graphql-tag' import gql from 'graphql-tag'
export const deletePendingCreation = gql` export const deletePendingCreation = gql`
mutation ($id: Float!) { mutation ($id: Int!) {
deletePendingCreation(id: $id) deletePendingCreation(id: $id)
} }
` `

View File

@ -1,7 +1,7 @@
import gql from 'graphql-tag' import gql from 'graphql-tag'
export const deleteUser = gql` export const deleteUser = gql`
mutation ($userId: Float!) { mutation ($userId: Int!) {
deleteUser(userId: $userId) deleteUser(userId: $userId)
} }
` `

View File

@ -1,31 +0,0 @@
import gql from 'graphql-tag'
export const transactionList = gql`
query (
$currentPage: Int = 1
$pageSize: Int = 25
$order: Order = DESC
$onlyCreations: Boolean = false
$userId: Int = null
) {
transactionList(
currentPage: $currentPage
pageSize: $pageSize
order: $order
onlyCreations: $onlyCreations
userId: $userId
) {
transactions {
id
amount
balanceDate
creationDate
memo
linkedUser {
firstName
lastName
}
}
}
}
`

View File

@ -1,7 +1,7 @@
import gql from 'graphql-tag' import gql from 'graphql-tag'
export const unDeleteUser = gql` export const unDeleteUser = gql`
mutation ($userId: Float!) { mutation ($userId: Int!) {
unDeleteUser(userId: $userId) unDeleteUser(userId: $userId)
} }
` `

View File

@ -99,7 +99,7 @@ export default {
}, },
updateDeletedAt(userId, deletedAt) { updateDeletedAt(userId, deletedAt) {
this.searchResult.find((obj) => obj.userId === userId).deletedAt = deletedAt this.searchResult.find((obj) => obj.userId === userId).deletedAt = deletedAt
this.toastSuccess(this.$t('user_deleted')) this.toastSuccess(deletedAt ? this.$t('user_deleted') : this.$t('user_recovered'))
}, },
}, },
watch: { watch: {

View File

@ -42,7 +42,7 @@ EMAIL_SMTP_URL=gmail.com
EMAIL_SMTP_PORT=587 EMAIL_SMTP_PORT=587
EMAIL_LINK_VERIFICATION=http://localhost/checkEmail/{code} EMAIL_LINK_VERIFICATION=http://localhost/checkEmail/{code}
EMAIL_LINK_SETPASSWORD=http://localhost/reset/{code} EMAIL_LINK_SETPASSWORD=http://localhost/reset/{code}
RESEND_TIME=10 EMAIL_CODE_VALID_TIME=10
# Webhook # Webhook
WEBHOOK_ELOPAGE_SECRET=secret WEBHOOK_ELOPAGE_SECRET=secret

View File

@ -3,8 +3,9 @@ module.exports = {
verbose: true, verbose: true,
preset: 'ts-jest', preset: 'ts-jest',
collectCoverage: true, collectCoverage: true,
collectCoverageFrom: ['src/**/*.ts', '!**/node_modules/**', '!src/seeds/**'], collectCoverageFrom: ['src/**/*.ts', '!**/node_modules/**', '!src/seeds/**', '!build/**'],
setupFiles: ['<rootDir>/test/testSetup.ts'], setupFiles: ['<rootDir>/test/testSetup.ts'],
modulePathIgnorePatterns: ['<rootDir>/build/'],
moduleNameMapper: { moduleNameMapper: {
'@/(.*)': '<rootDir>/src/$1', '@/(.*)': '<rootDir>/src/$1',
'@model/(.*)': '<rootDir>/src/graphql/model/$1', '@model/(.*)': '<rootDir>/src/graphql/model/$1',

View File

@ -10,11 +10,11 @@
"scripts": { "scripts": {
"build": "tsc --build", "build": "tsc --build",
"clean": "tsc --build --clean", "clean": "tsc --build --clean",
"start": "node build/src/index.js", "start": "TZ=UTC TS_NODE_BASEURL=./build node -r tsconfig-paths/register build/src/index.js",
"dev": "nodemon -w src --ext ts --exec ts-node src/index.ts", "dev": "TZ=UTC nodemon -w src --ext ts --exec ts-node -r tsconfig-paths/register src/index.ts",
"lint": "eslint --max-warnings=0 --ext .js,.ts .", "lint": "eslint --max-warnings=0 --ext .js,.ts .",
"test": "TZ=UTC NODE_ENV=development jest --runInBand --coverage --forceExit --detectOpenHandles", "test": "TZ=UTC NODE_ENV=development jest --runInBand --coverage --forceExit --detectOpenHandles",
"seed": "TZ=UTC ts-node src/seeds/index.ts" "seed": "TZ=UTC ts-node -r tsconfig-paths/register src/seeds/index.ts"
}, },
"dependencies": { "dependencies": {
"@types/jest": "^27.0.2", "@types/jest": "^27.0.2",
@ -32,7 +32,6 @@
"jest": "^27.2.4", "jest": "^27.2.4",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
"lodash.clonedeep": "^4.5.0", "lodash.clonedeep": "^4.5.0",
"module-alias": "^2.2.2",
"mysql2": "^2.3.0", "mysql2": "^2.3.0",
"nodemailer": "^6.6.5", "nodemailer": "^6.6.5",
"random-bigint": "^0.0.1", "random-bigint": "^0.0.1",
@ -60,15 +59,7 @@
"nodemon": "^2.0.7", "nodemon": "^2.0.7",
"prettier": "^2.3.1", "prettier": "^2.3.1",
"ts-node": "^10.0.0", "ts-node": "^10.0.0",
"tsconfig-paths": "^3.14.0",
"typescript": "^4.3.4" "typescript": "^4.3.4"
},
"_moduleAliases": {
"@": "./build/src",
"@arg": "./build/src/graphql/arg",
"@dbTools": "../database/build/src",
"@entity": "../database/build/entity",
"@enum": "./build/src/graphql/enum",
"@model": "./build/src/graphql/model",
"@repository": "./build/src/typeorm/repository"
} }
} }

View File

@ -8,4 +8,5 @@ export const INALIENABLE_RIGHTS = [
RIGHTS.SEND_RESET_PASSWORD_EMAIL, RIGHTS.SEND_RESET_PASSWORD_EMAIL,
RIGHTS.SET_PASSWORD, RIGHTS.SET_PASSWORD,
RIGHTS.QUERY_TRANSACTION_LINK, RIGHTS.QUERY_TRANSACTION_LINK,
RIGHTS.QUERY_OPT_IN,
] ]

View File

@ -16,6 +16,7 @@ export enum RIGHTS {
CREATE_USER = 'CREATE_USER', CREATE_USER = 'CREATE_USER',
SEND_RESET_PASSWORD_EMAIL = 'SEND_RESET_PASSWORD_EMAIL', SEND_RESET_PASSWORD_EMAIL = 'SEND_RESET_PASSWORD_EMAIL',
SET_PASSWORD = 'SET_PASSWORD', SET_PASSWORD = 'SET_PASSWORD',
QUERY_OPT_IN = 'QUERY_OPT_IN',
UPDATE_USER_INFOS = 'UPDATE_USER_INFOS', UPDATE_USER_INFOS = 'UPDATE_USER_INFOS',
HAS_ELOPAGE = 'HAS_ELOPAGE', HAS_ELOPAGE = 'HAS_ELOPAGE',
CREATE_TRANSACTION_LINK = 'CREATE_TRANSACTION_LINK', CREATE_TRANSACTION_LINK = 'CREATE_TRANSACTION_LINK',
@ -33,4 +34,5 @@ export enum RIGHTS {
SEND_ACTIVATION_EMAIL = 'SEND_ACTIVATION_EMAIL', SEND_ACTIVATION_EMAIL = 'SEND_ACTIVATION_EMAIL',
DELETE_USER = 'DELETE_USER', DELETE_USER = 'DELETE_USER',
UNDELETE_USER = 'UNDELETE_USER', UNDELETE_USER = 'UNDELETE_USER',
CREATION_TRANSACTION_LIST = 'CREATION_TRANSACTION_LIST',
} }

View File

@ -10,7 +10,7 @@ Decimal.set({
}) })
const constants = { const constants = {
DB_VERSION: '0032-add-transaction-link-to-transaction', DB_VERSION: '0033-add_referrer_id',
DECAY_START_TIME: new Date('2021-05-13 17:46:31'), // GMT+0 DECAY_START_TIME: new Date('2021-05-13 17:46:31'), // GMT+0
CONFIG_VERSION: { CONFIG_VERSION: {
DEFAULT: 'DEFAULT', DEFAULT: 'DEFAULT',
@ -59,8 +59,6 @@ const loginServer = {
LOGIN_SERVER_KEY: process.env.LOGIN_SERVER_KEY || 'a51ef8ac7ef1abf162fb7a65261acd7a', LOGIN_SERVER_KEY: process.env.LOGIN_SERVER_KEY || 'a51ef8ac7ef1abf162fb7a65261acd7a',
} }
// TODO: Hannes if I find you... this looks like blasphemy
const resendTime = parseInt(process.env.RESEND_TIME ? process.env.RESEND_TIME : 'null')
const email = { const email = {
EMAIL: process.env.EMAIL === 'true' || false, EMAIL: process.env.EMAIL === 'true' || false,
EMAIL_USERNAME: process.env.EMAIL_USERNAME || 'gradido_email', EMAIL_USERNAME: process.env.EMAIL_USERNAME || 'gradido_email',
@ -72,7 +70,9 @@ const email = {
process.env.EMAIL_LINK_VERIFICATION || 'http://localhost/checkEmail/{code}', process.env.EMAIL_LINK_VERIFICATION || 'http://localhost/checkEmail/{code}',
EMAIL_LINK_SETPASSWORD: EMAIL_LINK_SETPASSWORD:
process.env.EMAIL_LINK_SETPASSWORD || 'http://localhost/reset-password/{code}', process.env.EMAIL_LINK_SETPASSWORD || 'http://localhost/reset-password/{code}',
RESEND_TIME: isNaN(resendTime) ? 10 : resendTime, EMAIL_CODE_VALID_TIME: process.env.EMAIL_CODE_VALID_TIME
? parseInt(process.env.EMAIL_CODE_VALID_TIME) || 10
: 10,
} }
const webhook = { const webhook = {

View File

@ -11,10 +11,4 @@ export default class Paginated {
@Field(() => Order, { nullable: true }) @Field(() => Order, { nullable: true })
order?: Order order?: Order
@Field(() => Boolean, { nullable: true })
onlyCreations?: boolean
@Field(() => Int, { nullable: true })
userId?: number
} }

View File

@ -35,6 +35,7 @@ const isAuthorized: AuthChecker<any> = async ({ context }, rights) => {
const userRepository = await getCustomRepository(UserRepository) const userRepository = await getCustomRepository(UserRepository)
try { try {
const user = await userRepository.findByPubkeyHex(context.pubKey) const user = await userRepository.findByPubkeyHex(context.pubKey)
context.user = user
const countServerUsers = await ServerUser.count({ email: user.email }) const countServerUsers = await ServerUser.count({ email: user.email })
context.role = countServerUsers > 0 ? ROLE_ADMIN : ROLE_USER context.role = countServerUsers > 0 ? ROLE_ADMIN : ROLE_USER
} catch { } catch {

View File

@ -6,7 +6,7 @@ export enum TransactionTypeId {
RECEIVE = 3, RECEIVE = 3,
// This is a virtual property, never occurring on the database // This is a virtual property, never occurring on the database
DECAY = 4, DECAY = 4,
TRANSACTION_LINK = 5, LINK_SUMMARY = 5,
} }
registerEnumType(TransactionTypeId, { registerEnumType(TransactionTypeId, {

View File

@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Resolver, Query, Arg, Args, Authorized, Mutation, Ctx } from 'type-graphql' import { Resolver, Query, Arg, Args, Authorized, Mutation, Ctx, Int } from 'type-graphql'
import { import {
getCustomRepository, getCustomRepository,
IsNull, IsNull,
@ -19,16 +19,21 @@ import { UserRepository } from '@repository/User'
import CreatePendingCreationArgs from '@arg/CreatePendingCreationArgs' import CreatePendingCreationArgs from '@arg/CreatePendingCreationArgs'
import UpdatePendingCreationArgs from '@arg/UpdatePendingCreationArgs' import UpdatePendingCreationArgs from '@arg/UpdatePendingCreationArgs'
import SearchUsersArgs from '@arg/SearchUsersArgs' import SearchUsersArgs from '@arg/SearchUsersArgs'
import { Transaction } from '@entity/Transaction' import { Transaction as DbTransaction } from '@entity/Transaction'
import { Transaction } from '@model/Transaction'
import { TransactionRepository } from '@repository/Transaction' import { TransactionRepository } from '@repository/Transaction'
import { calculateDecay } from '@/util/decay' import { calculateDecay } from '@/util/decay'
import { AdminPendingCreation } from '@entity/AdminPendingCreation' import { AdminPendingCreation } from '@entity/AdminPendingCreation'
import { hasElopageBuys } from '@/util/hasElopageBuys' import { hasElopageBuys } from '@/util/hasElopageBuys'
import { LoginEmailOptIn } from '@entity/LoginEmailOptIn' import { LoginEmailOptIn } from '@entity/LoginEmailOptIn'
import { User } from '@entity/User' import { User as dbUser } from '@entity/User'
import { User } from '@model/User'
import { TransactionTypeId } from '@enum/TransactionTypeId' import { TransactionTypeId } from '@enum/TransactionTypeId'
import Decimal from 'decimal.js-light' import Decimal from 'decimal.js-light'
import { Decay } from '@model/Decay' import { Decay } from '@model/Decay'
import Paginated from '@arg/Paginated'
import { Order } from '@enum/Order'
import { communityUser } from '@/util/communityUser'
// const EMAIL_OPT_IN_REGISTER = 1 // const EMAIL_OPT_IN_REGISTER = 1
// const EMAIL_OPT_UNKNOWN = 3 // elopage? // const EMAIL_OPT_UNKNOWN = 3 // elopage?
@ -122,28 +127,30 @@ export class AdminResolver {
@Authorized([RIGHTS.DELETE_USER]) @Authorized([RIGHTS.DELETE_USER])
@Mutation(() => Date, { nullable: true }) @Mutation(() => Date, { nullable: true })
async deleteUser(@Arg('userId') userId: number, @Ctx() context: any): Promise<Date | null> { async deleteUser(
const user = await User.findOne({ id: userId }) @Arg('userId', () => Int) userId: number,
@Ctx() context: any,
): Promise<Date | null> {
const user = await dbUser.findOne({ id: userId })
// user exists ? // user exists ?
if (!user) { if (!user) {
throw new Error(`Could not find user with userId: ${userId}`) throw new Error(`Could not find user with userId: ${userId}`)
} }
// moderator user disabled own account? // moderator user disabled own account?
const userRepository = getCustomRepository(UserRepository) const moderatorUser = context.user
const moderatorUser = await userRepository.findByPubkeyHex(context.pubKey)
if (moderatorUser.id === userId) { if (moderatorUser.id === userId) {
throw new Error('Moderator can not delete his own account!') throw new Error('Moderator can not delete his own account!')
} }
// soft-delete user // soft-delete user
await user.softRemove() await user.softRemove()
const newUser = await User.findOne({ id: userId }, { withDeleted: true }) const newUser = await dbUser.findOne({ id: userId }, { withDeleted: true })
return newUser ? newUser.deletedAt : null return newUser ? newUser.deletedAt : null
} }
@Authorized([RIGHTS.UNDELETE_USER]) @Authorized([RIGHTS.UNDELETE_USER])
@Mutation(() => Date, { nullable: true }) @Mutation(() => Date, { nullable: true })
async unDeleteUser(@Arg('userId') userId: number): Promise<Date | null> { async unDeleteUser(@Arg('userId', () => Int) userId: number): Promise<Date | null> {
const user = await User.findOne({ id: userId }, { withDeleted: true }) const user = await dbUser.findOne({ id: userId }, { withDeleted: true })
// user exists ? // user exists ?
if (!user) { if (!user) {
throw new Error(`Could not find user with userId: ${userId}`) throw new Error(`Could not find user with userId: ${userId}`)
@ -158,7 +165,7 @@ export class AdminResolver {
async createPendingCreation( async createPendingCreation(
@Args() { email, amount, memo, creationDate, moderator }: CreatePendingCreationArgs, @Args() { email, amount, memo, creationDate, moderator }: CreatePendingCreationArgs,
): Promise<number[]> { ): Promise<number[]> {
const user = await User.findOne({ email }, { withDeleted: true }) const user = await dbUser.findOne({ email }, { withDeleted: true })
if (!user) { if (!user) {
throw new Error(`Could not find user with email: ${email}`) throw new Error(`Could not find user with email: ${email}`)
} }
@ -215,7 +222,7 @@ export class AdminResolver {
async updatePendingCreation( async updatePendingCreation(
@Args() { id, email, amount, memo, creationDate, moderator }: UpdatePendingCreationArgs, @Args() { id, email, amount, memo, creationDate, moderator }: UpdatePendingCreationArgs,
): Promise<UpdatePendingCreation> { ): Promise<UpdatePendingCreation> {
const user = await User.findOne({ email }, { withDeleted: true }) const user = await dbUser.findOne({ email }, { withDeleted: true })
if (!user) { if (!user) {
throw new Error(`Could not find user with email: ${email}`) throw new Error(`Could not find user with email: ${email}`)
} }
@ -265,7 +272,7 @@ export class AdminResolver {
const userIds = pendingCreations.map((p) => p.userId) const userIds = pendingCreations.map((p) => p.userId)
const userCreations = await getUserCreations(userIds) const userCreations = await getUserCreations(userIds)
const users = await User.find({ where: { id: In(userIds) }, withDeleted: true }) const users = await dbUser.find({ where: { id: In(userIds) }, withDeleted: true })
return pendingCreations.map((pendingCreation) => { return pendingCreations.map((pendingCreation) => {
const user = users.find((u) => u.id === pendingCreation.userId) const user = users.find((u) => u.id === pendingCreation.userId)
@ -284,7 +291,7 @@ export class AdminResolver {
@Authorized([RIGHTS.DELETE_PENDING_CREATION]) @Authorized([RIGHTS.DELETE_PENDING_CREATION])
@Mutation(() => Boolean) @Mutation(() => Boolean)
async deletePendingCreation(@Arg('id') id: number): Promise<boolean> { async deletePendingCreation(@Arg('id', () => Int) id: number): Promise<boolean> {
const entity = await AdminPendingCreation.findOneOrFail(id) const entity = await AdminPendingCreation.findOneOrFail(id)
const res = await AdminPendingCreation.delete(entity) const res = await AdminPendingCreation.delete(entity)
return !!res return !!res
@ -292,14 +299,16 @@ export class AdminResolver {
@Authorized([RIGHTS.CONFIRM_PENDING_CREATION]) @Authorized([RIGHTS.CONFIRM_PENDING_CREATION])
@Mutation(() => Boolean) @Mutation(() => Boolean)
async confirmPendingCreation(@Arg('id') id: number, @Ctx() context: any): Promise<boolean> { async confirmPendingCreation(
@Arg('id', () => Int) id: number,
@Ctx() context: any,
): Promise<boolean> {
const pendingCreation = await AdminPendingCreation.findOneOrFail(id) const pendingCreation = await AdminPendingCreation.findOneOrFail(id)
const userRepository = getCustomRepository(UserRepository) const moderatorUser = context.user
const moderatorUser = await userRepository.findByPubkeyHex(context.pubKey)
if (moderatorUser.id === pendingCreation.userId) if (moderatorUser.id === pendingCreation.userId)
throw new Error('Moderator can not confirm own pending creation') throw new Error('Moderator can not confirm own pending creation')
const user = await User.findOneOrFail({ id: pendingCreation.userId }, { withDeleted: true }) const user = await dbUser.findOneOrFail({ id: pendingCreation.userId }, { withDeleted: true })
if (user.deletedAt) throw new Error('This user was deleted. Cannot confirm a creation.') if (user.deletedAt) throw new Error('This user was deleted. Cannot confirm a creation.')
const creations = await getUserCreation(pendingCreation.userId, false) const creations = await getUserCreation(pendingCreation.userId, false)
@ -321,7 +330,7 @@ export class AdminResolver {
// TODO pending creations decimal // TODO pending creations decimal
newBalance = newBalance.add(new Decimal(Number(pendingCreation.amount)).toString()) newBalance = newBalance.add(new Decimal(Number(pendingCreation.amount)).toString())
const transaction = new Transaction() const transaction = new DbTransaction()
transaction.typeId = TransactionTypeId.CREATION transaction.typeId = TransactionTypeId.CREATION
transaction.memo = pendingCreation.memo transaction.memo = pendingCreation.memo
transaction.userId = pendingCreation.userId transaction.userId = pendingCreation.userId
@ -339,6 +348,27 @@ export class AdminResolver {
return true return true
} }
@Authorized([RIGHTS.CREATION_TRANSACTION_LIST])
@Query(() => [Transaction])
async creationTransactionList(
@Args()
{ currentPage = 1, pageSize = 25, order = Order.DESC }: Paginated,
@Arg('userId', () => Int) userId: number,
): Promise<Transaction[]> {
const offset = (currentPage - 1) * pageSize
const transactionRepository = getCustomRepository(TransactionRepository)
const [userTransactions] = await transactionRepository.findByUserPaged(
userId,
pageSize,
offset,
order,
true,
)
const user = await dbUser.findOneOrFail({ id: userId })
return userTransactions.map((t) => new Transaction(t, new User(user), communityUser))
}
} }
interface CreationMap { interface CreationMap {

View File

@ -2,9 +2,7 @@
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Resolver, Query, Ctx, Authorized } from 'type-graphql' import { Resolver, Query, Ctx, Authorized } from 'type-graphql'
import { getCustomRepository } from '@dbTools/typeorm'
import { Balance } from '@model/Balance' import { Balance } from '@model/Balance'
import { UserRepository } from '@repository/User'
import { calculateDecay } from '@/util/decay' import { calculateDecay } from '@/util/decay'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
import { Transaction } from '@entity/Transaction' import { Transaction } from '@entity/Transaction'
@ -16,9 +14,7 @@ export class BalanceResolver {
@Query(() => Balance) @Query(() => Balance)
async balance(@Ctx() context: any): Promise<Balance> { async balance(@Ctx() context: any): Promise<Balance> {
// load user and balance // load user and balance
const userRepository = getCustomRepository(UserRepository) const { user } = context
const user = await userRepository.findByPubkeyHex(context.pubKey)
const now = new Date() const now = new Date()
const lastTransaction = await Transaction.findOne( const lastTransaction = await Transaction.findOne(

View File

@ -2,12 +2,10 @@
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Resolver, Query, Args, Ctx, Authorized, Arg } from 'type-graphql' import { Resolver, Query, Args, Ctx, Authorized, Arg } from 'type-graphql'
import { getCustomRepository } from '@dbTools/typeorm'
import CONFIG from '@/config' import CONFIG from '@/config'
import { GdtEntryList } from '@model/GdtEntryList' import { GdtEntryList } from '@model/GdtEntryList'
import Paginated from '@arg/Paginated' import Paginated from '@arg/Paginated'
import { apiGet } from '@/apis/HttpRequest' import { apiGet } from '@/apis/HttpRequest'
import { UserRepository } from '@repository/User'
import { Order } from '@enum/Order' import { Order } from '@enum/Order'
import { RIGHTS } from '@/auth/RIGHTS' import { RIGHTS } from '@/auth/RIGHTS'
@ -22,8 +20,7 @@ export class GdtResolver {
@Ctx() context: any, @Ctx() context: any,
): Promise<GdtEntryList> { ): Promise<GdtEntryList> {
// load user // load user
const userRepository = getCustomRepository(UserRepository) const userEntity = context.user
const userEntity = await userRepository.findByPubkeyHex(context.pubKey)
try { try {
const resultGDT = await apiGet( const resultGDT = await apiGet(

View File

@ -1,12 +1,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Resolver, Args, Arg, Authorized, Ctx, Mutation, Query } from 'type-graphql' import { Resolver, Args, Arg, Authorized, Ctx, Mutation, Query, Int } from 'type-graphql'
import { getCustomRepository } from '@dbTools/typeorm'
import { TransactionLink } from '@model/TransactionLink' import { TransactionLink } from '@model/TransactionLink'
import { TransactionLink as dbTransactionLink } from '@entity/TransactionLink' import { TransactionLink as dbTransactionLink } from '@entity/TransactionLink'
import { User as dbUser } from '@entity/User' import { User as dbUser } from '@entity/User'
import { UserRepository } from '@repository/User'
import TransactionLinkArgs from '@arg/TransactionLinkArgs' import TransactionLinkArgs from '@arg/TransactionLinkArgs'
import Paginated from '@arg/Paginated' import Paginated from '@arg/Paginated'
import { calculateBalance } from '@/util/validate' import { calculateBalance } from '@/util/validate'
@ -29,7 +27,7 @@ export const transactionLinkCode = (date: Date): string => {
const CODE_VALID_DAYS_DURATION = 14 const CODE_VALID_DAYS_DURATION = 14
const transactionLinkExpireDate = (date: Date): Date => { export const transactionLinkExpireDate = (date: Date): Date => {
const validUntil = new Date(date) const validUntil = new Date(date)
return new Date(validUntil.setDate(date.getDate() + CODE_VALID_DAYS_DURATION)) return new Date(validUntil.setDate(date.getDate() + CODE_VALID_DAYS_DURATION))
} }
@ -42,8 +40,7 @@ export class TransactionLinkResolver {
@Args() { amount, memo }: TransactionLinkArgs, @Args() { amount, memo }: TransactionLinkArgs,
@Ctx() context: any, @Ctx() context: any,
): Promise<TransactionLink> { ): Promise<TransactionLink> {
const userRepository = getCustomRepository(UserRepository) const { user } = context
const user = await userRepository.findByPubkeyHex(context.pubKey)
const createdDate = new Date() const createdDate = new Date()
const validUntil = transactionLinkExpireDate(createdDate) const validUntil = transactionLinkExpireDate(createdDate)
@ -73,9 +70,11 @@ export class TransactionLinkResolver {
@Authorized([RIGHTS.DELETE_TRANSACTION_LINK]) @Authorized([RIGHTS.DELETE_TRANSACTION_LINK])
@Mutation(() => Boolean) @Mutation(() => Boolean)
async deleteTransactionLink(@Arg('id') id: number, @Ctx() context: any): Promise<boolean> { async deleteTransactionLink(
const userRepository = getCustomRepository(UserRepository) @Arg('id', () => Int) id: number,
const user = await userRepository.findByPubkeyHex(context.pubKey) @Ctx() context: any,
): Promise<boolean> {
const { user } = context
const transactionLink = await dbTransactionLink.findOne({ id }) const transactionLink = await dbTransactionLink.findOne({ id })
if (!transactionLink) { if (!transactionLink) {
@ -100,7 +99,7 @@ export class TransactionLinkResolver {
@Authorized([RIGHTS.QUERY_TRANSACTION_LINK]) @Authorized([RIGHTS.QUERY_TRANSACTION_LINK])
@Query(() => TransactionLink) @Query(() => TransactionLink)
async queryTransactionLink(@Arg('code') code: string): Promise<TransactionLink> { async queryTransactionLink(@Arg('code') code: string): Promise<TransactionLink> {
const transactionLink = await dbTransactionLink.findOneOrFail({ code }) const transactionLink = await dbTransactionLink.findOneOrFail({ code }, { withDeleted: true })
const user = await dbUser.findOneOrFail({ id: transactionLink.userId }) const user = await dbUser.findOneOrFail({ id: transactionLink.userId })
let redeemedBy: User | null = null let redeemedBy: User | null = null
if (transactionLink && transactionLink.redeemedBy) { if (transactionLink && transactionLink.redeemedBy) {
@ -116,8 +115,7 @@ export class TransactionLinkResolver {
{ currentPage = 1, pageSize = 5, order = Order.DESC }: Paginated, { currentPage = 1, pageSize = 5, order = Order.DESC }: Paginated,
@Ctx() context: any, @Ctx() context: any,
): Promise<TransactionLink[]> { ): Promise<TransactionLink[]> {
const userRepository = getCustomRepository(UserRepository) const { user } = context
const user = await userRepository.findByPubkeyHex(context.pubKey)
// const now = new Date() // const now = new Date()
const transactionLinks = await dbTransactionLink.find({ const transactionLinks = await dbTransactionLink.find({
where: { where: {
@ -136,10 +134,12 @@ export class TransactionLinkResolver {
@Authorized([RIGHTS.REDEEM_TRANSACTION_LINK]) @Authorized([RIGHTS.REDEEM_TRANSACTION_LINK])
@Mutation(() => Boolean) @Mutation(() => Boolean)
async redeemTransactionLink(@Arg('id') id: number, @Ctx() context: any): Promise<boolean> { async redeemTransactionLink(
const userRepository = getCustomRepository(UserRepository) @Arg('code', () => String) code: string,
const user = await userRepository.findByPubkeyHex(context.pubKey) @Ctx() context: any,
const transactionLink = await dbTransactionLink.findOneOrFail({ id }) ): Promise<boolean> {
const { user } = context
const transactionLink = await dbTransactionLink.findOneOrFail({ code })
const linkedUser = await dbUser.findOneOrFail({ id: transactionLink.userId }) const linkedUser = await dbUser.findOneOrFail({ id: transactionLink.userId })
const now = new Date() const now = new Date()

View File

@ -17,7 +17,6 @@ import Paginated from '@arg/Paginated'
import { Order } from '@enum/Order' import { Order } from '@enum/Order'
import { UserRepository } from '@repository/User'
import { TransactionRepository } from '@repository/Transaction' import { TransactionRepository } from '@repository/Transaction'
import { TransactionLinkRepository } from '@repository/TransactionLink' import { TransactionLinkRepository } from '@repository/TransactionLink'
@ -131,22 +130,11 @@ export class TransactionResolver {
@Query(() => TransactionList) @Query(() => TransactionList)
async transactionList( async transactionList(
@Args() @Args()
{ { currentPage = 1, pageSize = 25, order = Order.DESC }: Paginated,
currentPage = 1,
pageSize = 25,
order = Order.DESC,
onlyCreations = false,
userId,
}: Paginated,
@Ctx() context: any, @Ctx() context: any,
): Promise<TransactionList> { ): Promise<TransactionList> {
const now = new Date() const now = new Date()
// find user const user = context.user
const userRepository = getCustomRepository(UserRepository)
// TODO: separate those usecases - this is a security issue
const user = userId
? await userRepository.findOneOrFail({ id: userId }, { withDeleted: true })
: await userRepository.findByPubkeyHex(context.pubKey)
// find current balance // find current balance
const lastTransaction = await dbTransaction.findOne( const lastTransaction = await dbTransaction.findOne(
@ -182,7 +170,6 @@ export class TransactionResolver {
pageSize, pageSize,
offset, offset,
order, order,
onlyCreations,
) )
// find involved users; I am involved // find involved users; I am involved
@ -208,7 +195,7 @@ export class TransactionResolver {
await transactionLinkRepository.summary(user.id, now) await transactionLinkRepository.summary(user.id, now)
// decay & link transactions // decay & link transactions
if (!onlyCreations && currentPage === 1 && order === Order.DESC) { if (currentPage === 1 && order === Order.DESC) {
transactions.push( transactions.push(
virtualDecayTransaction(lastTransaction.balance, lastTransaction.balanceDate, now, self), virtualDecayTransaction(lastTransaction.balance, lastTransaction.balanceDate, now, self),
) )
@ -256,8 +243,7 @@ export class TransactionResolver {
@Ctx() context: any, @Ctx() context: any,
): Promise<boolean> { ): Promise<boolean> {
// TODO this is subject to replay attacks // TODO this is subject to replay attacks
const userRepository = getCustomRepository(UserRepository) const senderUser = context.user
const senderUser = await userRepository.findByPubkeyHex(context.pubKey)
if (senderUser.pubKey.length !== 32) { if (senderUser.pubKey.length !== 32) {
throw new Error('invalid sender public key') throw new Error('invalid sender public key')
} }

View File

@ -69,7 +69,9 @@ describe('UserResolver', () => {
}) })
it('returns success', () => { it('returns success', () => {
expect(result).toEqual(expect.objectContaining({ data: { createUser: 'success' } })) expect(result).toEqual(
expect.objectContaining({ data: { createUser: { id: expect.any(Number) } } }),
)
}) })
describe('valid input data', () => { describe('valid input data', () => {
@ -99,6 +101,7 @@ describe('UserResolver', () => {
language: 'de', language: 'de',
deletedAt: null, deletedAt: null,
publisherId: 1234, publisherId: 1234,
referrerId: null,
}, },
]) ])
}) })
@ -331,6 +334,7 @@ describe('UserResolver', () => {
email: 'bibi@bloxberg.de', email: 'bibi@bloxberg.de',
firstName: 'Bibi', firstName: 'Bibi',
hasElopage: false, hasElopage: false,
id: expect.any(Number),
isAdmin: false, isAdmin: false,
klickTipp: { klickTipp: {
newsletterState: false, newsletterState: false,

View File

@ -14,7 +14,6 @@ import UpdateUserInfosArgs from '@arg/UpdateUserInfosArgs'
import { klicktippNewsletterStateMiddleware } from '@/middleware/klicktippMiddleware' import { klicktippNewsletterStateMiddleware } from '@/middleware/klicktippMiddleware'
import { UserSettingRepository } from '@repository/UserSettingRepository' import { UserSettingRepository } from '@repository/UserSettingRepository'
import { Setting } from '@enum/Setting' import { Setting } from '@enum/Setting'
import { UserRepository } from '@repository/User'
import { LoginEmailOptIn } from '@entity/LoginEmailOptIn' import { LoginEmailOptIn } from '@entity/LoginEmailOptIn'
import { sendResetPasswordEmail } from '@/mailer/sendResetPasswordEmail' import { sendResetPasswordEmail } from '@/mailer/sendResetPasswordEmail'
import { sendAccountActivationEmail } from '@/mailer/sendAccountActivationEmail' import { sendAccountActivationEmail } from '@/mailer/sendAccountActivationEmail'
@ -157,15 +156,11 @@ const createEmailOptIn = async (
emailOptInTypeId: EMAIL_OPT_IN_REGISTER, emailOptInTypeId: EMAIL_OPT_IN_REGISTER,
}) })
if (emailOptIn) { if (emailOptIn) {
const timeElapsed = Date.now() - new Date(emailOptIn.updatedAt).getTime() if (isOptInCodeValid(emailOptIn)) {
if (timeElapsed <= parseInt(CONFIG.RESEND_TIME.toString()) * 60 * 1000) { throw new Error(`email already sent less than $(CONFIG.EMAIL_CODE_VALID_TIME} minutes ago`)
throw new Error(
'email already sent less than ' + parseInt(CONFIG.RESEND_TIME.toString()) + ' minutes ago',
)
} else {
emailOptIn.updatedAt = new Date()
emailOptIn.resendCount++
} }
emailOptIn.updatedAt = new Date()
emailOptIn.resendCount++
} else { } else {
emailOptIn = new LoginEmailOptIn() emailOptIn = new LoginEmailOptIn()
emailOptIn.verificationCode = random(64) emailOptIn.verificationCode = random(64)
@ -186,17 +181,13 @@ const getOptInCode = async (loginUserId: number): Promise<LoginEmailOptIn> => {
emailOptInTypeId: EMAIL_OPT_IN_RESET_PASSWORD, emailOptInTypeId: EMAIL_OPT_IN_RESET_PASSWORD,
}) })
// Check for 10 minute delay // Check for `CONFIG.EMAIL_CODE_VALID_TIME` minute delay
if (optInCode) { if (optInCode) {
const timeElapsed = Date.now() - new Date(optInCode.updatedAt).getTime() if (isOptInCodeValid(optInCode)) {
if (timeElapsed <= parseInt(CONFIG.RESEND_TIME.toString()) * 60 * 1000) { throw new Error(`email already sent less than $(CONFIG.EMAIL_CODE_VALID_TIME} minutes ago`)
throw new Error(
'email already sent less than ' + parseInt(CONFIG.RESEND_TIME.toString()) + ' minutes ago',
)
} else {
optInCode.updatedAt = new Date()
optInCode.resendCount++
} }
optInCode.updatedAt = new Date()
optInCode.resendCount++
} else { } else {
optInCode = new LoginEmailOptIn() optInCode = new LoginEmailOptIn()
optInCode.verificationCode = random(64) optInCode.verificationCode = random(64)
@ -214,8 +205,7 @@ export class UserResolver {
@UseMiddleware(klicktippNewsletterStateMiddleware) @UseMiddleware(klicktippNewsletterStateMiddleware)
async verifyLogin(@Ctx() context: any): Promise<User> { async verifyLogin(@Ctx() context: any): Promise<User> {
// TODO refactor and do not have duplicate code with login(see below) // TODO refactor and do not have duplicate code with login(see below)
const userRepository = getCustomRepository(UserRepository) const userEntity = context.user
const userEntity = await userRepository.findByPubkeyHex(context.pubKey)
const user = new User(userEntity) const user = new User(userEntity)
// user.pubkey = userEntity.pubKey.toString('hex') // user.pubkey = userEntity.pubKey.toString('hex')
// Elopage Status & Stored PublisherId // Elopage Status & Stored PublisherId
@ -313,10 +303,10 @@ export class UserResolver {
} }
@Authorized([RIGHTS.CREATE_USER]) @Authorized([RIGHTS.CREATE_USER])
@Mutation(() => String) @Mutation(() => User)
async createUser( async createUser(
@Args() { email, firstName, lastName, language, publisherId }: CreateUserArgs, @Args() { email, firstName, lastName, language, publisherId }: CreateUserArgs,
): Promise<string> { ): Promise<User> {
// TODO: wrong default value (should be null), how does graphql work here? Is it an required field? // TODO: wrong default value (should be null), how does graphql work here? Is it an required field?
// default int publisher_id = 0; // default int publisher_id = 0;
@ -396,7 +386,7 @@ export class UserResolver {
} finally { } finally {
await queryRunner.release() await queryRunner.release()
} }
return 'success' return new User(dbUser)
} }
// THis is used by the admin only - should we move it to the admin resolver? // THis is used by the admin only - should we move it to the admin resolver?
@ -494,10 +484,9 @@ export class UserResolver {
throw new Error('Could not login with emailVerificationCode') throw new Error('Could not login with emailVerificationCode')
}) })
// Code is only valid for 10minutes // Code is only valid for `CONFIG.EMAIL_CODE_VALID_TIME` minutes
const timeElapsed = Date.now() - new Date(optInCode.updatedAt).getTime() if (!isOptInCodeValid(optInCode)) {
if (timeElapsed > 10 * 60 * 1000) { throw new Error(`email already more than $(CONFIG.EMAIL_CODE_VALID_TIME} minutes ago`)
throw new Error('Code is older than 10 minutes')
} }
// load user // load user
@ -570,6 +559,17 @@ export class UserResolver {
return true return true
} }
@Authorized([RIGHTS.QUERY_OPT_IN])
@Query(() => Boolean)
async queryOptIn(@Arg('optIn') optIn: string): Promise<boolean> {
const optInCode = await LoginEmailOptIn.findOneOrFail({ verificationCode: optIn })
// Code is only valid for `CONFIG.EMAIL_CODE_VALID_TIME` minutes
if (!isOptInCodeValid(optInCode)) {
throw new Error(`email was sent more than $(CONFIG.EMAIL_CODE_VALID_TIME} minutes ago`)
}
return true
}
@Authorized([RIGHTS.UPDATE_USER_INFOS]) @Authorized([RIGHTS.UPDATE_USER_INFOS])
@Mutation(() => Boolean) @Mutation(() => Boolean)
async updateUserInfos( async updateUserInfos(
@ -585,8 +585,7 @@ export class UserResolver {
}: UpdateUserInfosArgs, }: UpdateUserInfosArgs,
@Ctx() context: any, @Ctx() context: any,
): Promise<boolean> { ): Promise<boolean> {
const userRepository = getCustomRepository(UserRepository) const userEntity = context.user
const userEntity = await userRepository.findByPubkeyHex(context.pubKey)
if (firstName) { if (firstName) {
userEntity.firstName = firstName userEntity.firstName = firstName
@ -664,8 +663,7 @@ export class UserResolver {
@Authorized([RIGHTS.HAS_ELOPAGE]) @Authorized([RIGHTS.HAS_ELOPAGE])
@Query(() => Boolean) @Query(() => Boolean)
async hasElopage(@Ctx() context: any): Promise<boolean> { async hasElopage(@Ctx() context: any): Promise<boolean> {
const userRepository = getCustomRepository(UserRepository) const userEntity = context.user
const userEntity = await userRepository.findByPubkeyHex(context.pubKey).catch()
if (!userEntity) { if (!userEntity) {
return false return false
} }
@ -673,3 +671,7 @@ export class UserResolver {
return hasElopageBuys(userEntity.email) return hasElopageBuys(userEntity.email)
} }
} }
function isOptInCodeValid(optInCode: LoginEmailOptIn) {
const timeElapsed = Date.now() - new Date(optInCode.updatedAt).getTime()
return timeElapsed <= CONFIG.EMAIL_CODE_VALID_TIME * 60 * 1000
}

View File

@ -15,14 +15,14 @@ export const creationFactory = async (
): Promise<void> => { ): Promise<void> => {
const { mutate, query } = client const { mutate, query } = client
// login as Peter Lustig (admin) // login as Peter Lustig (admin) and get his user ID
await query({ query: login, variables: { email: 'peter@lustig.de', password: 'Aa12345_' } }) const {
data: {
login: { id },
},
} = await query({ query: login, variables: { email: 'peter@lustig.de', password: 'Aa12345_' } })
// get Peter Lustig's user id await mutate({ mutation: createPendingCreation, variables: { ...creation, moderator: id } })
const peterLustig = await User.findOneOrFail({ where: { email: 'peter@lustig.de' } })
const variables = { ...creation, moderator: peterLustig.id }
await mutate({ mutation: createPendingCreation, variables })
// get User // get User
const user = await User.findOneOrFail({ where: { email: creation.email } }) const user = await User.findOneOrFail({ where: { email: creation.email } })

View File

@ -0,0 +1,43 @@
import { ApolloServerTestClient } from 'apollo-server-testing'
import { createTransactionLink } from '@/seeds/graphql/mutations'
import { login } from '@/seeds/graphql/queries'
import { TransactionLinkInterface } from '@/seeds/transactionLink/TransactionLinkInterface'
import { transactionLinkExpireDate } from '@/graphql/resolver/TransactionLinkResolver'
import { TransactionLink } from '@entity/TransactionLink'
export const transactionLinkFactory = async (
client: ApolloServerTestClient,
transactionLink: TransactionLinkInterface,
): Promise<void> => {
const { mutate, query } = client
// login
await query({ query: login, variables: { email: transactionLink.email, password: 'Aa12345_' } })
const variables = {
amount: transactionLink.amount,
memo: transactionLink.memo,
}
// get the transaction links's id
const {
data: {
createTransactionLink: { id },
},
} = await mutate({ mutation: createTransactionLink, variables })
if (transactionLink.createdAt || transactionLink.deletedAt) {
const dbTransactionLink = await TransactionLink.findOneOrFail({ id })
if (transactionLink.createdAt) {
dbTransactionLink.createdAt = transactionLink.createdAt
dbTransactionLink.validUntil = transactionLinkExpireDate(transactionLink.createdAt)
await dbTransactionLink.save()
}
if (transactionLink.deletedAt) {
dbTransactionLink.deletedAt = new Date()
await dbTransactionLink.save()
}
}
}

View File

@ -11,36 +11,41 @@ export const userFactory = async (
): Promise<void> => { ): Promise<void> => {
const { mutate } = client const { mutate } = client
await mutate({ mutation: createUser, variables: user }) const {
let dbUser = await User.findOneOrFail({ where: { email: user.email } }) data: {
createUser: { id },
},
} = await mutate({ mutation: createUser, variables: user })
if (user.emailChecked) { if (user.emailChecked) {
const optin = await LoginEmailOptIn.findOneOrFail({ where: { userId: dbUser.id } }) const optin = await LoginEmailOptIn.findOneOrFail({ userId: id })
await mutate({ await mutate({
mutation: setPassword, mutation: setPassword,
variables: { password: 'Aa12345_', code: optin.verificationCode }, variables: { password: 'Aa12345_', code: optin.verificationCode },
}) })
} }
// refetch data if (user.createdAt || user.deletedAt || user.isAdmin) {
dbUser = await User.findOneOrFail({ where: { email: user.email } }) // get user from database
const dbUser = await User.findOneOrFail({ id })
if (user.createdAt || user.deletedAt) { if (user.createdAt || user.deletedAt) {
if (user.createdAt) dbUser.createdAt = user.createdAt if (user.createdAt) dbUser.createdAt = user.createdAt
if (user.deletedAt) dbUser.deletedAt = user.deletedAt if (user.deletedAt) dbUser.deletedAt = user.deletedAt
await dbUser.save() await dbUser.save()
} }
if (user.isAdmin) { if (user.isAdmin) {
const admin = new ServerUser() const admin = new ServerUser()
admin.username = dbUser.firstName admin.username = dbUser.firstName
admin.password = 'please_refactor' admin.password = 'please_refactor'
admin.email = dbUser.email admin.email = dbUser.email
admin.role = 'admin' admin.role = 'admin'
admin.activated = 1 admin.activated = 1
admin.lastLogin = new Date() admin.lastLogin = new Date()
admin.created = dbUser.createdAt admin.created = dbUser.createdAt
admin.modified = dbUser.createdAt admin.modified = dbUser.createdAt
await admin.save() await admin.save()
}
} }
} }

View File

@ -52,7 +52,9 @@ export const createUser = gql`
lastName: $lastName lastName: $lastName
language: $language language: $language
publisherId: $publisherId publisherId: $publisherId
) ) {
id
}
} }
` `
@ -65,6 +67,7 @@ export const sendCoins = gql`
export const createTransactionLink = gql` export const createTransactionLink = gql`
mutation ($amount: Decimal!, $memo: String!) { mutation ($amount: Decimal!, $memo: String!) {
createTransactionLink(amount: $amount, memo: $memo) { createTransactionLink(amount: $amount, memo: $memo) {
id
code code
} }
} }
@ -91,7 +94,7 @@ export const createPendingCreation = gql`
` `
export const confirmPendingCreation = gql` export const confirmPendingCreation = gql`
mutation ($id: Float!) { mutation ($id: Int!) {
confirmPendingCreation(id: $id) confirmPendingCreation(id: $id)
} }
` `

View File

@ -3,6 +3,7 @@ import gql from 'graphql-tag'
export const login = gql` export const login = gql`
query ($email: String!, $password: String!, $publisherId: Int) { query ($email: String!, $password: String!, $publisherId: Int) {
login(email: $email, password: $password, publisherId: $publisherId) { login(email: $email, password: $password, publisherId: $publisherId) {
id
email email
firstName firstName
lastName lastName

View File

@ -8,8 +8,10 @@ import { name, internet, random } from 'faker'
import { users } from './users/index' import { users } from './users/index'
import { creations } from './creation/index' import { creations } from './creation/index'
import { transactionLinks } from './transactionLink/index'
import { userFactory } from './factory/user' import { userFactory } from './factory/user'
import { creationFactory } from './factory/creation' import { creationFactory } from './factory/creation'
import { transactionLinkFactory } from './factory/transactionLink'
import { entities } from '@entity/index' import { entities } from '@entity/index'
const context = { const context = {
@ -64,6 +66,11 @@ const run = async () => {
await creationFactory(seedClient, creations[i]) await creationFactory(seedClient, creations[i])
} }
// create Transaction Links
for (let i = 0; i < transactionLinks.length; i++) {
await transactionLinkFactory(seedClient, transactionLinks[i])
}
await con.close() await con.close()
} }

View File

@ -0,0 +1,7 @@
export interface TransactionLinkInterface {
email: string
amount: number
memo: string
createdAt?: Date
deletedAt?: boolean
}

View File

@ -0,0 +1,52 @@
import { TransactionLinkInterface } from './TransactionLinkInterface'
export const transactionLinks: TransactionLinkInterface[] = [
{
email: 'bibi@bloxberg.de',
amount: 19.99,
memo: 'Leider wollte niemand meine Gradidos zum Neujahr haben :(',
createdAt: new Date(2022, 0, 1),
},
{
email: 'bibi@bloxberg.de',
amount: 19.99,
memo: `Kein Trick, keine Zauberrei,
bei Gradidio sei dabei!`,
},
{
email: 'bibi@bloxberg.de',
amount: 19.99,
memo: `Kein Trick, keine Zauberrei,
bei Gradidio sei dabei!`,
},
{
email: 'bibi@bloxberg.de',
amount: 19.99,
memo: `Kein Trick, keine Zauberrei,
bei Gradidio sei dabei!`,
},
{
email: 'bibi@bloxberg.de',
amount: 19.99,
memo: `Kein Trick, keine Zauberrei,
bei Gradidio sei dabei!`,
},
{
email: 'bibi@bloxberg.de',
amount: 19.99,
memo: `Kein Trick, keine Zauberrei,
bei Gradidio sei dabei!`,
},
{
email: 'bibi@bloxberg.de',
amount: 19.99,
memo: `Kein Trick, keine Zauberrei,
bei Gradidio sei dabei!`,
},
{
email: 'bibi@bloxberg.de',
amount: 19.99,
memo: 'Da habe ich mich wohl etwas übernommen.',
deletedAt: true,
},
]

View File

@ -1,5 +1,4 @@
import 'reflect-metadata' import 'reflect-metadata'
import 'module-alias/register'
import { ApolloServer } from 'apollo-server-express' import { ApolloServer } from 'apollo-server-express'
import express, { Express } from 'express' import express, { Express } from 'express'

View File

@ -41,7 +41,7 @@ const virtualLinkTransaction = (
id: -2, id: -2,
userId: -1, userId: -1,
previous: -1, previous: -1,
typeId: TransactionTypeId.TRANSACTION_LINK, typeId: TransactionTypeId.LINK_SUMMARY,
amount: amount, amount: amount,
balance: balance, balance: balance,
balanceDate: validUntil, balanceDate: validUntil,

View File

@ -45,16 +45,17 @@
/* Module Resolution Options */ /* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ "baseUrl": ".", /* Base directory to resolve non-absolute module names. */
"paths": { /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ "paths": { /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
"@/*": ["./src/*"], "@/*": ["src/*"],
"@arg/*": ["./src/graphql/arg/*"], "@arg/*": ["src/graphql/arg/*"],
"@dbTools/*": ["../database/src/*"], "@enum/*": ["src/graphql/enum/*"],
"@entity/*": ["../database/entity/*"], "@model/*": ["src/graphql/model/*"],
"@enum/*": ["./src/graphql/enum/*"], "@repository/*": ["src/typeorm/repository/*"],
"@model/*": ["./src/graphql/model/*"], "@test/*": ["test/*"],
"@repository/*": ["./src/typeorm/repository/*"], /* external */
"@test/*": ["./test/*"] "@dbTools/*": ["../database/src/*", "../../database/build/src/*"],
"@entity/*": ["../database/entity/*", "../../database/build/entity/*"]
}, },
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */ // "typeRoots": [], /* List of folders to include type definitions from. */
@ -82,7 +83,7 @@
{ {
"path": "../database/tsconfig.json", "path": "../database/tsconfig.json",
// add 'prepend' if you want to include the referenced project in your output file // add 'prepend' if you want to include the referenced project in your output file
// "prepend": true, // "prepend": true
} }
] ]
} }

View File

@ -4102,11 +4102,6 @@ minimist@^1.2.0, minimist@^1.2.5:
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602"
integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw== integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==
module-alias@^2.2.2:
version "2.2.2"
resolved "https://registry.yarnpkg.com/module-alias/-/module-alias-2.2.2.tgz#151cdcecc24e25739ff0aa6e51e1c5716974c0e0"
integrity sha512-A/78XjoX2EmNvppVWEhM2oGk3x4lLxnkEA4jTbaK97QKSDjkIoOsKQlfylt/d3kKKi596Qy3NP5XrXJ6fZIC9Q==
ms@2.0.0: ms@2.0.0:
version "2.0.0" version "2.0.0"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
@ -5242,6 +5237,16 @@ tsconfig-paths@^3.11.0:
minimist "^1.2.0" minimist "^1.2.0"
strip-bom "^3.0.0" strip-bom "^3.0.0"
tsconfig-paths@^3.14.0:
version "3.14.0"
resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.14.0.tgz#4fcc48f9ccea8826c41b9ca093479de7f5018976"
integrity sha512-cg/1jAZoL57R39+wiw4u/SCC6Ic9Q5NqjBOb+9xISedOYurfog9ZNmKJSxAnb2m/5Bq4lE9lhUcau33Ml8DM0g==
dependencies:
"@types/json5" "^0.0.29"
json5 "^1.0.1"
minimist "^1.2.0"
strip-bom "^3.0.0"
tslib@^1.10.0, tslib@^1.8.1, tslib@^1.9.3: tslib@^1.10.0, tslib@^1.8.1, tslib@^1.9.3:
version "1.14.1" version "1.14.1"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00"

View File

@ -0,0 +1,78 @@
import {
BaseEntity,
Entity,
PrimaryGeneratedColumn,
Column,
OneToMany,
DeleteDateColumn,
} from 'typeorm'
import { UserSetting } from '../UserSetting'
@Entity('users', { engine: 'InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci' })
export class User extends BaseEntity {
@PrimaryGeneratedColumn('increment', { unsigned: true })
id: number
@Column({ name: 'public_key', type: 'binary', length: 32, default: null, nullable: true })
pubKey: Buffer
@Column({ name: 'privkey', type: 'binary', length: 80, default: null, nullable: true })
privKey: Buffer
@Column({ length: 255, unique: true, nullable: false, collation: 'utf8mb4_unicode_ci' })
email: string
@Column({
name: 'first_name',
length: 255,
nullable: true,
default: null,
collation: 'utf8mb4_unicode_ci',
})
firstName: string
@Column({
name: 'last_name',
length: 255,
nullable: true,
default: null,
collation: 'utf8mb4_unicode_ci',
})
lastName: string
@DeleteDateColumn()
deletedAt: Date | null
@Column({ type: 'bigint', default: 0, unsigned: true })
password: BigInt
@Column({ name: 'email_hash', type: 'binary', length: 32, default: null, nullable: true })
emailHash: Buffer
@Column({ name: 'created', default: () => 'CURRENT_TIMESTAMP', nullable: false })
createdAt: Date
@Column({ name: 'email_checked', type: 'bool', nullable: false, default: false })
emailChecked: boolean
@Column({ length: 4, default: 'de', collation: 'utf8mb4_unicode_ci', nullable: false })
language: string
@Column({ name: 'referrer_id', type: 'int', unsigned: true, nullable: true, default: null })
referrerId?: number | null
@Column({ name: 'publisher_id', default: 0 })
publisherId: number
@Column({
type: 'text',
name: 'passphrase',
collation: 'utf8mb4_unicode_ci',
nullable: true,
default: null,
})
passphrase: string
@OneToMany(() => UserSetting, (userSetting) => userSetting.user)
settings: UserSetting[]
}

View File

@ -1 +1 @@
export { User } from './0023-users_disabled_soft_delete/User' export { User } from './0033-add_referrer_id/User'

View File

@ -0,0 +1,14 @@
/* MIGRATION TO ADD referrer_id FIELD TO users */
/* 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<Array<any>>) {
await queryFn(
'ALTER TABLE `users` ADD COLUMN `referrer_id` int UNSIGNED DEFAULT NULL AFTER `language`;',
)
}
export async function downgrade(queryFn: (query: string, values?: any[]) => Promise<Array<any>>) {
await queryFn('ALTER TABLE `users` DROP COLUMN `referrer_id`;')
}

View File

@ -19,7 +19,7 @@
<div class="mt-4" v-show="selected === sendTypes.link"> <div class="mt-4" v-show="selected === sendTypes.link">
<h2 class="alert-heading">{{ $t('gdd_per_link.header') }}</h2> <h2 class="alert-heading">{{ $t('gdd_per_link.header') }}</h2>
<div> <div>
{{ $t('gdd_per_link.sentence_1') }} {{ $t('gdd_per_link.choose-amount') }}
</div> </div>
</div> </div>
@ -160,15 +160,18 @@ export default {
}, },
props: { props: {
balance: { type: Number, default: 0 }, balance: { type: Number, default: 0 },
email: { type: String, default: '' },
amount: { type: Number, default: 0 },
memo: { type: String, default: '' },
}, },
data() { data() {
return { return {
amountFocused: false, amountFocused: false,
emailFocused: false, emailFocused: false,
form: { form: {
email: '', email: this.email,
amount: '', amount: this.amount ? String(this.amount) : '',
memo: '', memo: this.memo,
amountValue: 0.0, amountValue: 0.0,
}, },
selected: SEND_TYPES.send, selected: SEND_TYPES.send,

View File

@ -31,7 +31,7 @@
</template> </template>
<script> <script>
export default { export default {
name: 'TransactionResultSend', name: 'TransactionResultSendError',
props: { props: {
error: { type: Boolean, default: false }, error: { type: Boolean, default: false },
errorResult: { type: String, default: '' }, errorResult: { type: String, default: '' },

View File

@ -42,8 +42,8 @@
/> />
</template> </template>
<template #TRANSACTION_LINK> <template #LINK_SUMMARY>
<transaction-links-summary <transaction-link-summary
class="list-group-item" class="list-group-item"
v-bind="transactions[index]" v-bind="transactions[index]"
:transactionLinkCount="transactionLinkCount" :transactionLinkCount="transactionLinkCount"
@ -72,7 +72,7 @@ import TransactionDecay from '@/components/Transactions/TransactionDecay'
import TransactionSend from '@/components/Transactions/TransactionSend' import TransactionSend from '@/components/Transactions/TransactionSend'
import TransactionReceive from '@/components/Transactions/TransactionReceive' import TransactionReceive from '@/components/Transactions/TransactionReceive'
import TransactionCreation from '@/components/Transactions/TransactionCreation' import TransactionCreation from '@/components/Transactions/TransactionCreation'
import TransactionLinksSummary from '@/components/Transactions/TransactionLinksSummary' import TransactionLinkSummary from '@/components/Transactions/TransactionLinkSummary'
export default { export default {
name: 'gdd-transaction-list', name: 'gdd-transaction-list',
@ -83,7 +83,7 @@ export default {
TransactionSend, TransactionSend,
TransactionReceive, TransactionReceive,
TransactionCreation, TransactionCreation,
TransactionLinksSummary, TransactionLinkSummary,
}, },
data() { data() {
return { return {

View File

@ -0,0 +1,21 @@
<template>
<div class="redeem-information">
<b-jumbotron bg-variant="muted" text-variant="dark" border-variant="info">
<h1>
{{ firstName }}
{{ $t('transaction-link.send_you') }} {{ amount | GDD }}
</h1>
<b>{{ memo }}</b>
</b-jumbotron>
</div>
</template>
<script>
export default {
name: 'RedeemInformation',
props: {
firstName: { type: String, required: true },
amount: { type: String, required: true },
memo: { type: String, required: true, default: '' },
},
}
</script>

View File

@ -0,0 +1,47 @@
<template>
<div class="redeem-logged-out">
<redeem-information :firstName="user.firstName" :amount="amount" :memo="memo" />
<b-jumbotron>
<div class="mb-6">
<h2>{{ $t('gdd_per_link.redeem') }}</h2>
</div>
<b-row>
<b-col col sm="12" md="6">
<p>{{ $t('gdd_per_link.no-account') }}</p>
<b-button variant="primary" :to="register">
{{ $t('gdd_per_link.to-register') }}
</b-button>
</b-col>
<b-col sm="12" md="6" class="mt-xs-6 mt-sm-6 mt-md-0">
<p>{{ $t('gdd_per_link.has-account') }}</p>
<b-button variant="info" :to="login">{{ $t('gdd_per_link.to-login') }}</b-button>
</b-col>
</b-row>
</b-jumbotron>
</div>
</template>
<script>
import RedeemInformation from '@/components/LinkInformations/RedeemInformation.vue'
export default {
name: 'RedeemLoggedOut',
components: {
RedeemInformation,
},
props: {
user: { type: Object, required: true },
amount: { type: String, required: true },
memo: { type: String, required: true, default: '' },
},
computed: {
login() {
return '/login/' + this.$route.params.code
},
register() {
return '/register/' + this.$route.params.code
},
},
}
</script>

View File

@ -0,0 +1,31 @@
<template>
<div class="redeem-self-creator">
<redeem-information :firstName="user.firstName" :amount="amount" :memo="memo" />
<b-jumbotron>
<div class="mb-3 text-center">
<div class="mt-3">
{{ $t('gdd_per_link.no-redeem') }}
<a to="/transactions" href="#!">
<b>{{ $t('gdd_per_link.link-overview') }}</b>
</a>
</div>
</div>
</b-jumbotron>
</div>
</template>
<script>
import RedeemInformation from '@/components/LinkInformations/RedeemInformation.vue'
export default {
name: 'RedeemSelfCreator',
components: {
RedeemInformation,
},
props: {
user: { type: Object, required: true },
amount: { type: String, required: true },
memo: { type: String, required: true, default: '' },
},
}
</script>

View File

@ -0,0 +1,27 @@
<template>
<div class="redeem-valid">
<redeem-information :firstName="user.firstName" :amount="amount" :memo="memo" />
<b-jumbotron>
<div class="mb-3 text-center">
<b-button variant="primary" @click="$emit('redeem-link', amount)" size="lg">
{{ $t('gdd_per_link.redeem') }}
</b-button>
</div>
</b-jumbotron>
</div>
</template>
<script>
import RedeemInformation from '@/components/LinkInformations/RedeemInformation.vue'
export default {
name: 'RedeemValid',
components: {
RedeemInformation,
},
props: {
user: { type: Object, required: false },
amount: { type: String, required: false },
memo: { type: String, required: false, default: '' },
},
}
</script>

View File

@ -0,0 +1,21 @@
<template>
<div class="redeemed-text-box">
<b-jumbotron bg-variant="muted" text-variant="dark" border-variant="info">
<h1>
{{ text }}
</h1>
</b-jumbotron>
<div class="text-center">
<b-button to="/overview">{{ $t('back') }}</b-button>
</div>
</div>
</template>
<script>
export default {
name: 'RedeemedTextBox',
props: {
text: { type: String, required: true },
},
}
</script>

View File

@ -0,0 +1,16 @@
<template>
<div>
<slot :name="type"></slot>
</div>
</template>
<script>
export default {
name: 'TransactionLinkItem',
props: {
type: {
type: String,
required: true,
},
},
}
</script>

View File

@ -5,7 +5,7 @@
</template> </template>
<script> <script>
export default { export default {
name: 'TransactionList', name: 'TransactionListItem',
props: { props: {
typeId: { typeId: {
type: String, type: String,

View File

@ -1,5 +1,5 @@
import { mount } from '@vue/test-utils' import { mount } from '@vue/test-utils'
import TransactionLinksSummary from './TransactionLinksSummary' import TransactionLinksSummary from './TransactionLinkSummary'
import { listTransactionLinks } from '@/graphql/queries' import { listTransactionLinks } from '@/graphql/queries'
import { toastErrorSpy } from '@test/testSetup' import { toastErrorSpy } from '@test/testSetup'
@ -29,7 +29,7 @@ const propsData = {
transactionLinkCount: 4, transactionLinkCount: 4,
} }
describe('TransactionLinksSummary', () => { describe('TransactionLinkSummary', () => {
let wrapper let wrapper
const Wrapper = () => { const Wrapper = () => {

View File

@ -52,7 +52,9 @@ export const createUser = gql`
lastName: $lastName lastName: $lastName
language: $language language: $language
publisherId: $publisherId publisherId: $publisherId
) ) {
id
}
} }
` `
@ -71,7 +73,13 @@ export const createTransactionLink = gql`
` `
export const deleteTransactionLink = gql` export const deleteTransactionLink = gql`
mutation($id: Float!) { mutation($id: Int!) {
deleteTransactionLink(id: $id) deleteTransactionLink(id: $id)
} }
` `
export const redeemTransactionLink = gql`
mutation($code: String!) {
redeemTransactionLink(code: $code)
}
`

View File

@ -43,18 +43,8 @@ export const logout = gql`
` `
export const transactionsQuery = gql` export const transactionsQuery = gql`
query( query($currentPage: Int = 1, $pageSize: Int = 25, $order: Order = DESC) {
$currentPage: Int = 1 transactionList(currentPage: $currentPage, pageSize: $pageSize, order: $order) {
$pageSize: Int = 25
$order: Order = DESC
$onlyCreations: Boolean = false
) {
transactionList(
currentPage: $currentPage
pageSize: $pageSize
order: $order
onlyCreations: $onlyCreations
) {
balanceGDT balanceGDT
count count
linkCount linkCount
@ -129,16 +119,26 @@ export const communities = gql`
} }
` `
export const queryOptIn = gql`
query($optIn: String!) {
queryOptIn(optIn: $optIn)
}
`
export const queryTransactionLink = gql` export const queryTransactionLink = gql`
query($code: String!) { query($code: String!) {
queryTransactionLink(code: $code) { queryTransactionLink(code: $code) {
id
amount amount
memo memo
createdAt createdAt
validUntil validUntil
redeemedAt
deletedAt
user { user {
firstName firstName
publisherId publisherId
email
} }
} }
} }

View File

@ -140,14 +140,6 @@ describe('DashboardLayoutGdd', () => {
}) })
}) })
describe('update balance', () => {
it('updates the amount correctelly', async () => {
await wrapper.findComponent({ ref: 'router-view' }).vm.$emit('update-balance', 5)
await flushPromises()
expect(wrapper.vm.balance).toBe(-5)
})
})
describe('update transactions', () => { describe('update transactions', () => {
beforeEach(async () => { beforeEach(async () => {
apolloMock.mockResolvedValue({ apolloMock.mockResolvedValue({

View File

@ -27,7 +27,6 @@
:transactionLinkCount="transactionLinkCount" :transactionLinkCount="transactionLinkCount"
:pending="pending" :pending="pending"
:decayStartBlock="decayStartBlock" :decayStartBlock="decayStartBlock"
@update-balance="updateBalance"
@update-transactions="updateTransactions" @update-transactions="updateTransactions"
></router-view> ></router-view>
</fade-transition> </fade-transition>
@ -112,9 +111,6 @@ export default {
// what to do when loading balance fails? // what to do when loading balance fails?
}) })
}, },
updateBalance(ammount) {
this.balance -= ammount
},
admin() { admin() {
window.location.assign(CONFIG.ADMIN_AUTH_URL.replace('{token}', this.$store.state.token)) window.location.assign(CONFIG.ADMIN_AUTH_URL.replace('{token}', this.$store.state.token))
this.$store.dispatch('logout') // logout without redirect this.$store.dispatch('logout') // logout without redirect

View File

@ -94,18 +94,30 @@
}, },
"GDD": "GDD", "GDD": "GDD",
"gdd_per_link": { "gdd_per_link": {
"choose-amount": "Wähle einen Betrag aus, welchen du per Link versenden möchtest. Du kannst auch noch eine Nachricht eintragen. Beim Klick „jetzt generieren“ wird ein Link erstellt, den du versenden kannst.",
"copy": "kopieren", "copy": "kopieren",
"created": "Der Link wurde erstellt!", "created": "Der Link wurde erstellt!",
"decay-14-day": "Vergänglichkeit für 14 Tage", "decay-14-day": "Vergänglichkeit für 14 Tage",
"delete-the-link": "Den Link löschen?", "delete-the-link": "Den Link löschen?",
"deleted": "Der Link wurde gelöscht!", "deleted": "Der Link wurde gelöscht!",
"expired": "Abgelaufen", "expired": "Abgelaufen",
"has-account": "Du besitzt bereits ein Gradido Konto",
"header": "Gradidos versenden per Link", "header": "Gradidos versenden per Link",
"link-copied": "Link wurde in die Zwischenablage kopiert", "link-copied": "Link wurde in die Zwischenablage kopiert",
"link-deleted": "Der Link wurde am {date} gelöscht.",
"link-expired": "Der Link ist nicht mehr gültig. Die Gültigkeit ist am {date} abgelaufen.",
"link-overview": "Linkübersicht",
"links_count": "Aktive Links", "links_count": "Aktive Links",
"links_sum": "Summe deiner versendeten Gradidos", "links_sum": "Summe deiner versendeten Gradidos",
"no-account": "Du besitzt noch kein Gradido Konto",
"no-redeem": "Du darfst deinen eigenen Link nicht einlösen!",
"not-copied": "Konnte den Link nicht kopieren: {err}", "not-copied": "Konnte den Link nicht kopieren: {err}",
"sentence_1": "Wähle einen Betrag aus, welchen du per Link versenden möchtest. Du kannst auch noch eine Nachricht eintragen. Beim Klick „jetzt generieren“ wird ein Link erstellt, den du versenden kannst." "redeem": "Einlösen",
"redeem-text": "Willst du den Betrag jetzt einlösen?",
"redeemed": "Erfolgreich eingelöst! Deinem Konto wurden {n} GDD gutgeschrieben.",
"redeemed-at": "Der Link wurde bereits am {date} eingelöst.",
"to-login": "Log dich ein",
"to-register": "Registriere ein neues Konto"
}, },
"gdt": { "gdt": {
"calculation": "Berechnung der GradidoTransform", "calculation": "Berechnung der GradidoTransform",
@ -207,13 +219,14 @@
"uppercase": "Großbuchstabe erforderlich." "uppercase": "Großbuchstabe erforderlich."
}, },
"thx": { "thx": {
"activateEmail": "Dein Konto wurde noch nicht aktiviert. Bitte überprüfe deine E-Mail und klicke den Aktivierungslink!", "activateEmail": "Dein Konto wurde noch nicht aktiviert. Bitte überprüfe deine E-Mail und klicke den Aktivierungslink oder fordere einen neuen Aktivierungslink über die Password Reset Seite.",
"checkEmail": "Deine E-Mail wurde erfolgreich verifiziert. Du kannst dich jetzt anmelden.", "checkEmail": "Deine E-Mail wurde erfolgreich verifiziert. Du kannst dich jetzt anmelden.",
"email": "Wir haben dir eine E-Mail gesendet.", "email": "Wir haben dir eine E-Mail gesendet.",
"emailActivated": "Danke dass Du deine E-Mail bestätigt hast.", "emailActivated": "Danke dass Du deine E-Mail bestätigt hast.",
"errorTitle": "Achtung!", "errorTitle": "Achtung!",
"register": "Du bist jetzt registriert, bitte überprüfe deine Emails und klicke auf den Aktivierungslink.", "register": "Du bist jetzt registriert, bitte überprüfe deine Emails und klicke auf den Aktivierungslink.",
"reset": "Dein Passwort wurde geändert.", "reset": "Dein Passwort wurde geändert.",
"resetPassword": "Den Code den Du genutzt hast ist zu alt bitte fordere ein neuen über die Passwort Reset Seite an.",
"title": "Danke!" "title": "Danke!"
} }
}, },
@ -235,7 +248,6 @@
"show_all": "Alle <strong>{count}</strong> Transaktionen ansehen" "show_all": "Alle <strong>{count}</strong> Transaktionen ansehen"
}, },
"transaction-link": { "transaction-link": {
"button": "einlösen",
"send_you": "sendet dir" "send_you": "sendet dir"
} }
} }

View File

@ -94,18 +94,30 @@
}, },
"GDD": "GDD", "GDD": "GDD",
"gdd_per_link": { "gdd_per_link": {
"choose-amount": "Select an amount that you would like to send via link. You can also enter a message. Click 'Generate now' to create a link that you can share.",
"copy": "copy", "copy": "copy",
"created": "Link was created!", "created": "Link was created!",
"decay-14-day": "Decay for 14 days", "decay-14-day": "Decay for 14 days",
"delete-the-link": "Delete the link?", "delete-the-link": "Delete the link?",
"deleted": "The link was deleted!", "deleted": "The link was deleted!",
"expired": "Expired", "expired": "Expired",
"has-account": "You already have a Gradido account",
"header": "Send Gradidos via link", "header": "Send Gradidos via link",
"link-copied": "Link copied to clipboard", "link-copied": "Link copied to clipboard",
"link-deleted": "The link was deleted on {date}.",
"link-expired": "The link is no longer valid. The validity expired on {date}.",
"link-overview": "Link overview",
"links_count": "Active links", "links_count": "Active links",
"links_sum": "Total of your sent Gradidos", "links_sum": "Total of your sent Gradidos",
"no-account": "You don't have a Gradido account yet",
"no-redeem": "You not allowed to redeem your own link!",
"not-copied": "Could not copy link: {err}", "not-copied": "Could not copy link: {err}",
"sentence_1": "Select an amount that you would like to send via link. You can also enter a message. Click 'Generate now' to create a link that you can share." "redeem": "Redeem",
"redeem-text": "Do you want to redeem the amount now?",
"redeemed": "Successfully redeemed! Your account has been credited with {n} GDD.",
"redeemed-at": "The link was already redeemed on {date}.",
"to-login": "Log in",
"to-register": "Register a new account"
}, },
"gdt": { "gdt": {
"calculation": "Calculation of GradidoTransform", "calculation": "Calculation of GradidoTransform",
@ -207,13 +219,14 @@
"uppercase": "One uppercase letter required." "uppercase": "One uppercase letter required."
}, },
"thx": { "thx": {
"activateEmail": "Your account has not been activated yet, please check your emails and click the activation link!", "activateEmail": "Your account has not been activated yet, please check your emails and click the activation link or order a new activation link over the password reset page.",
"checkEmail": "Your email has been successfully verified. You can sign in now.", "checkEmail": "Your email has been successfully verified. You can sign in now.",
"email": "We have sent you an email.", "email": "We have sent you an email.",
"emailActivated": "Thank you your email has been activated.", "emailActivated": "Thank you your email has been activated.",
"errorTitle": "Attention!", "errorTitle": "Attention!",
"register": "You are registered now, please check your emails and click the activation link.", "register": "You are registered now, please check your emails and click the activation link.",
"reset": "Your password has been changed.", "reset": "Your password has been changed.",
"resetPassword": "The code you used was to old please order a new on over the password reset page.",
"title": "Thank you!" "title": "Thank you!"
} }
}, },
@ -235,7 +248,6 @@
"show_all": "View all <strong>{count}</strong> transactions." "show_all": "View all <strong>{count}</strong> transactions."
}, },
"transaction-link": { "transaction-link": {
"button": "redeem",
"send_you": "wants to send you" "send_you": "wants to send you"
} }
} }

View File

@ -52,6 +52,9 @@ describe('Login', () => {
$router: { $router: {
push: mockRouterPush, push: mockRouterPush,
}, },
$route: {
params: {},
},
$apollo: { $apollo: {
query: apolloQueryMock, query: apolloQueryMock,
}, },
@ -224,13 +227,33 @@ describe('Login', () => {
expect(mockStoreDispach).toBeCalledWith('login', 'token') expect(mockStoreDispach).toBeCalledWith('login', 'token')
}) })
it('redirects to overview page', () => {
expect(mockRouterPush).toBeCalledWith('/overview')
})
it('hides the spinner', () => { it('hides the spinner', () => {
expect(spinnerHideMock).toBeCalled() expect(spinnerHideMock).toBeCalled()
}) })
describe('without code parameter', () => {
it('redirects to overview page', () => {
expect(mockRouterPush).toBeCalledWith('/overview')
})
})
describe('with code parameter', () => {
beforeEach(async () => {
mocks.$route.params = {
code: 'some-code',
}
wrapper = Wrapper()
await wrapper.find('input[placeholder="Email"]').setValue('user@example.org')
await wrapper.find('input[placeholder="form.password"]').setValue('1234')
await flushPromises()
await wrapper.find('form').trigger('submit')
await flushPromises()
})
it('redirects to overview page', () => {
expect(mockRouterPush).toBeCalledWith('/redeem/some-code')
})
})
}) })
describe('login fails', () => { describe('login fails', () => {

View File

@ -96,13 +96,17 @@ export default {
}, },
fetchPolicy: 'network-only', fetchPolicy: 'network-only',
}) })
.then((result) => { .then(async (result) => {
const { const {
data: { login }, data: { login },
} = result } = result
this.$store.dispatch('login', login) this.$store.dispatch('login', login)
this.$router.push('/overview') await loader.hide()
loader.hide() if (this.$route.params.code) {
this.$router.push(`/redeem/${this.$route.params.code}`)
} else {
this.$router.push('/overview')
}
}) })
.catch((error) => { .catch((error) => {
this.toastError(this.$t('error.no-account')) this.toastError(this.$t('error.no-account'))

View File

@ -4,7 +4,7 @@
<div class="header py-1 py-lg-1 pt-lg-3"> <div class="header py-1 py-lg-1 pt-lg-3">
<b-container> <b-container>
<div class="header-body text-center mb-3"> <div class="header-body text-center mb-3">
<a href="#!" @click="goback"> <a href="#!" v-on:click="$router.go(-1)">
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<div class="col-sm-12 col-md-12 mt-5 mb-5"> <div class="col-sm-12 col-md-12 mt-5 mb-5">
@ -1186,7 +1186,7 @@
</b-container> </b-container>
</div> </div>
<div class="text-center"> <div class="text-center">
<b-button class="test-back" variant="light" @click="goback"> <b-button class="test-back" variant="light" v-on:click="$router.go(-1)">
{{ $t('back') }} {{ $t('back') }}
</b-button> </b-button>
</div> </div>
@ -1218,11 +1218,6 @@ export default {
}, },
} }
}, },
methods: {
goback() {
this.$router.go(-1)
},
},
} }
</script> </script>
<style> <style>

View File

@ -32,6 +32,9 @@ describe('Register', () => {
$router: { $router: {
push: routerPushMock, push: routerPushMock,
}, },
$route: {
params: {},
},
$apollo: { $apollo: {
mutate: registerUserMutationMock, mutate: registerUserMutationMock,
query: apolloQueryMock, query: apolloQueryMock,
@ -312,6 +315,45 @@ describe('Register', () => {
}) })
}) })
}) })
// TODO: line 157
describe('redeem code', () => {
describe('no redeem code', () => {
it('has no redeem code', () => {
expect(wrapper.vm.redeemCode).toBe(undefined)
})
})
})
describe('with redeem code', () => {
beforeEach(async () => {
jest.clearAllMocks()
mocks.$route.params = {
code: 'some-code',
}
wrapper = Wrapper()
wrapper.find('#registerFirstname').setValue('Max')
wrapper.find('#registerLastname').setValue('Mustermann')
wrapper.find('#Email-input-field').setValue('max.mustermann@gradido.net')
wrapper.find('.language-switch-select').findAll('option').at(1).setSelected()
wrapper.find('#registerCheckbox').setChecked()
await wrapper.find('form').trigger('submit')
await flushPromises()
})
it('sends the redeem code to the server', () => {
expect(registerUserMutationMock).toBeCalledWith(
expect.objectContaining({
variables: {
email: 'max.mustermann@gradido.net',
firstName: 'Max',
lastName: 'Mustermann',
language: 'en',
publisherId: 12345,
redeemCode: 'some-code',
},
}),
)
})
})
}) })
}) })

View File

@ -118,12 +118,14 @@
{{ messageError }} {{ messageError }}
</span> </span>
</b-alert> </b-alert>
<b-row v-b-toggle:my-collapse class="text-muted shadow-sm p-3 publisherCollaps"> <b-row v-b-toggle:my-collapse class="text-muted shadow-sm p-3 publisherCollaps">
<b-col>{{ $t('publisher.publisherId') }} {{ $store.state.publisherId }}</b-col> <b-col>{{ $t('publisher.publisherId') }} {{ $store.state.publisherId }}</b-col>
<b-col class="text-right"> <b-col class="text-right">
<b-icon icon="chevron-down" aria-hidden="true"></b-icon> <b-icon icon="chevron-down" aria-hidden="true"></b-icon>
</b-col> </b-col>
</b-row> </b-row>
<b-row> <b-row>
<b-col> <b-col>
<b-collapse id="my-collapse" class=""> <b-collapse id="my-collapse" class="">
@ -136,7 +138,7 @@
type="text" type="text"
placeholder="Publisher ID" placeholder="Publisher ID"
v-model="publisherId" v-model="publisherId"
@input="commitStore(publisherId)" @input="commitStorePublisherId(publisherId)"
></b-form-input> ></b-form-input>
</b-input-group> </b-input-group>
<div <div
@ -210,6 +212,7 @@ export default {
messageError: '', messageError: '',
register: true, register: true,
publisherId: this.$store.state.publisherId, publisherId: this.$store.state.publisherId,
redeemCode: this.$route.params.code,
} }
}, },
methods: { methods: {
@ -220,7 +223,7 @@ export default {
getValidationState({ dirty, validated, valid = null }) { getValidationState({ dirty, validated, valid = null }) {
return dirty || validated ? valid : null return dirty || validated ? valid : null
}, },
commitStore(val) { commitStorePublisherId(val) {
this.$store.commit('publisherId', val) this.$store.commit('publisherId', val)
}, },
async onSubmit() { async onSubmit() {
@ -233,6 +236,7 @@ export default {
lastName: this.form.lastname, lastName: this.form.lastname,
language: this.language, language: this.language,
publisherId: this.$store.state.publisherId, publisherId: this.$store.state.publisherId,
redeemCode: this.redeemCode,
}, },
}) })
.then(() => { .then(() => {

View File

@ -9,6 +9,7 @@ import { toastErrorSpy } from '@test/testSetup'
const localVue = global.localVue const localVue = global.localVue
const apolloMutationMock = jest.fn() const apolloMutationMock = jest.fn()
const apolloQueryMock = jest.fn().mockResolvedValue()
const routerPushMock = jest.fn() const routerPushMock = jest.fn()
@ -40,6 +41,7 @@ const mocks = {
}, },
$apollo: { $apollo: {
mutate: apolloMutationMock, mutate: apolloMutationMock,
query: apolloQueryMock,
}, },
} }

View File

@ -49,6 +49,7 @@
<script> <script>
import InputPasswordConfirmation from '@/components/Inputs/InputPasswordConfirmation' import InputPasswordConfirmation from '@/components/Inputs/InputPasswordConfirmation'
import { setPassword } from '@/graphql/mutations' import { setPassword } from '@/graphql/mutations'
import { queryOptIn } from '@/graphql/queries'
const textFields = { const textFields = {
reset: { reset: {
@ -107,7 +108,22 @@ export default {
this.$router.push('/forgot-password/resetPassword') this.$router.push('/forgot-password/resetPassword')
}) })
}, },
checkOptInCode() {
this.$apollo
.query({
query: queryOptIn,
variables: {
optIn: this.$route.params.optin,
},
})
.then()
.catch((error) => {
this.toastError(error.message)
this.$router.push('/forgot-password/resetPassword')
})
},
setDisplaySetup() { setDisplaySetup() {
this.checkOptInCode()
if (this.$route.path.includes('checkEmail')) { if (this.$route.path.includes('checkEmail')) {
this.displaySetup = textFields.checkEmail this.displaySetup = textFields.checkEmail
} }

View File

@ -17,9 +17,7 @@ describe('Send', () => {
const propsData = { const propsData = {
balance: 123.45, balance: 123.45,
GdtBalance: 1234.56, GdtBalance: 1234.56,
transactions: [{ balance: 0.1 }],
pending: true, pending: true,
currentTransactionStep: TRANSACTION_STEPS.transactionConfirmationSend,
} }
const mocks = { const mocks = {
@ -45,11 +43,10 @@ describe('Send', () => {
}) })
it('has a send field', () => { it('has a send field', () => {
expect(wrapper.find('div.gdd-send').exists()).toBeTruthy() expect(wrapper.find('div.gdd-send').exists()).toBe(true)
}) })
/* SEND */ describe('fill transaction form for send coins', () => {
describe('transaction form send', () => {
beforeEach(async () => { beforeEach(async () => {
wrapper.findComponent({ name: 'TransactionForm' }).vm.$emit('set-transaction', { wrapper.findComponent({ name: 'TransactionForm' }).vm.$emit('set-transaction', {
email: 'user@example.org', email: 'user@example.org',
@ -58,86 +55,92 @@ describe('Send', () => {
selected: SEND_TYPES.send, selected: SEND_TYPES.send,
}) })
}) })
it('steps forward in the dialog', () => { it('steps forward in the dialog', () => {
expect(wrapper.findComponent({ name: 'TransactionConfirmationSend' }).exists()).toBe(true) expect(wrapper.findComponent({ name: 'TransactionConfirmationSend' }).exists()).toBe(true)
}) })
})
describe('confirm transaction if selected: SEND_TYPES.send', () => { describe('confirm transaction view', () => {
beforeEach(() => { describe('cancel confirmation', () => {
wrapper.setData({ beforeEach(async () => {
currentTransactionStep: TRANSACTION_STEPS.transactionConfirmationSend, await wrapper
transactionData: { .findComponent({ name: 'TransactionConfirmationSend' })
email: 'user@example.org', .vm.$emit('on-reset')
amount: 23.45, })
memo: 'Make the best of it!',
selected: SEND_TYPES.send,
},
})
})
it('resets the transaction process when on-reset is emitted', async () => { it('shows the transaction formular again', () => {
await wrapper.findComponent({ name: 'TransactionConfirmationSend' }).vm.$emit('on-reset') expect(wrapper.findComponent({ name: 'TransactionForm' }).exists()).toBe(true)
expect(wrapper.findComponent({ name: 'TransactionForm' }).exists()).toBeTruthy() })
expect(wrapper.vm.transactionData).toEqual({
email: 'user@example.org',
amount: 23.45,
memo: 'Make the best of it!',
selected: SEND_TYPES.send,
})
})
describe('transaction is confirmed and server response is success', () => { it('restores the previous data in the formular', () => {
beforeEach(async () => { expect(wrapper.find('#input-group-1').find('input').vm.$el.value).toBe(
jest.clearAllMocks() 'user@example.org',
await wrapper )
.findComponent({ name: 'TransactionConfirmationSend' }) expect(wrapper.find('#input-group-2').find('input').vm.$el.value).toBe('23.45')
.vm.$emit('send-transaction') expect(wrapper.find('#input-group-3').find('textarea').vm.$el.value).toBe(
'Make the best of it!',
)
})
}) })
it('calls the API when send-transaction is emitted', async () => { describe('confirm transaction with server succees', () => {
expect(apolloMutationMock).toBeCalledWith( beforeEach(async () => {
expect.objectContaining({ jest.clearAllMocks()
mutation: sendCoins, await wrapper
variables: { .findComponent({ name: 'TransactionConfirmationSend' })
email: 'user@example.org', .vm.$emit('send-transaction')
amount: 23.45, })
memo: 'Make the best of it!',
selected: SEND_TYPES.send, it('calls the API when send-transaction is emitted', async () => {
}, expect(apolloMutationMock).toBeCalledWith(
}), expect.objectContaining({
) mutation: sendCoins,
variables: {
email: 'user@example.org',
amount: 23.45,
memo: 'Make the best of it!',
selected: SEND_TYPES.send,
},
}),
)
})
it('emits update transactions', () => {
expect(wrapper.emitted('update-transactions')).toBeTruthy()
expect(wrapper.emitted('update-transactions')).toEqual(expect.arrayContaining([[{}]]))
})
it('shows the success page', () => {
expect(wrapper.find('div.card-body').text()).toContain('form.send_transaction_success')
})
}) })
it('emits update-balance', () => { describe('confirm transaction with server error', () => {
expect(wrapper.emitted('update-balance')).toBeTruthy() beforeEach(async () => {
expect(wrapper.emitted('update-balance')).toEqual([[23.45]]) jest.clearAllMocks()
}) apolloMutationMock.mockRejectedValue({ message: 'recipient not known' })
await wrapper
.findComponent({ name: 'TransactionConfirmationSend' })
.vm.$emit('send-transaction')
})
it('shows the success page', () => { it('has a component TransactionResultSendError', () => {
expect(wrapper.find('div.card-body').text()).toContain('form.send_transaction_success') expect(wrapper.findComponent({ name: 'TransactionResultSendError' }).exists()).toBe(
}) true,
}) )
})
describe('transaction is confirmed and server response is error', () => { it('has an standard error text', () => {
beforeEach(async () => { expect(wrapper.find('.test-send_transaction_error').text()).toContain(
jest.clearAllMocks() 'form.send_transaction_error',
apolloMutationMock.mockRejectedValue({ message: 'recipient not known' }) )
await wrapper })
.findComponent({ name: 'TransactionConfirmationSend' })
.vm.$emit('send-transaction')
})
it('shows the error page', () => { it('shows recipient not found', () => {
expect(wrapper.find('.test-send_transaction_error').text()).toContain( expect(wrapper.find('.test-receiver-not-found').text()).toContain(
'form.send_transaction_error', 'transaction.receiverNotFound',
) )
}) })
it('shows recipient not found', () => {
expect(wrapper.find('.test-receiver-not-found').text()).toContain(
'transaction.receiverNotFound',
)
}) })
}) })
}) })
@ -151,10 +154,11 @@ describe('Send', () => {
}) })
await wrapper.findComponent({ name: 'TransactionForm' }).vm.$emit('set-transaction', { await wrapper.findComponent({ name: 'TransactionForm' }).vm.$emit('set-transaction', {
amount: 56.78, amount: 56.78,
memo: 'Make the best of it link!', memo: 'Make the best of the link!',
selected: SEND_TYPES.link, selected: SEND_TYPES.link,
}) })
}) })
it('steps forward in the dialog', () => { it('steps forward in the dialog', () => {
expect(wrapper.findComponent({ name: 'TransactionConfirmationLink' }).exists()).toBe(true) expect(wrapper.findComponent({ name: 'TransactionConfirmationLink' }).exists()).toBe(true)
}) })
@ -173,18 +177,18 @@ describe('Send', () => {
mutation: createTransactionLink, mutation: createTransactionLink,
variables: { variables: {
amount: 56.78, amount: 56.78,
memo: 'Make the best of it link!', memo: 'Make the best of the link!',
}, },
}), }),
) )
}) })
it.skip('emits update-balance', () => { it('emits update-transactions', () => {
expect(wrapper.emitted('update-balance')).toBeTruthy() expect(wrapper.emitted('update-transactions')).toBeTruthy()
expect(wrapper.emitted('update-balance')).toEqual([[56.78]]) expect(wrapper.emitted('update-transactions')).toEqual(expect.arrayContaining([[{}]]))
}) })
it('find components ClipBoard', () => { it('finds the clip board component', () => {
expect(wrapper.findComponent({ name: 'ClipboardCopy' }).exists()).toBe(true) expect(wrapper.findComponent({ name: 'ClipboardCopy' }).exists()).toBe(true)
}) })
@ -196,7 +200,7 @@ describe('Send', () => {
expect(wrapper.find('div.card-body').text()).toContain('form.close') expect(wrapper.find('div.card-body').text()).toContain('form.close')
}) })
describe('Copy link to Clipboard', () => { describe('copy link to clipboard', () => {
const navigatorClipboard = navigator.clipboard const navigatorClipboard = navigator.clipboard
beforeAll(() => { beforeAll(() => {
delete navigator.clipboard delete navigator.clipboard
@ -251,5 +255,39 @@ describe('Send', () => {
}) })
}) })
}) })
describe('no field selected on send transaction', () => {
const errorHandler = localVue.config.errorHandler
beforeAll(() => {
localVue.config.errorHandler = jest.fn()
})
afterAll(() => {
localVue.config.errorHandler = errorHandler
})
beforeEach(async () => {
await wrapper.setData({
currentTransactionStep: TRANSACTION_STEPS.transactionConfirmationSend,
transactionData: {
email: 'user@example.org',
amount: 23.45,
memo: 'Make the best of it!',
selected: 'not-valid',
},
})
})
it('throws an error', async () => {
try {
await wrapper
.findComponent({ name: 'TransactionConfirmationSend' })
.vm.$emit('send-transaction')
} catch (error) {
expect(error).toBe('undefined transactionData.selected : not-valid')
}
})
})
}) })
}) })

View File

@ -3,7 +3,11 @@
<b-container> <b-container>
<gdd-send :currentTransactionStep="currentTransactionStep" class="pt-3 ml-2 mr-2"> <gdd-send :currentTransactionStep="currentTransactionStep" class="pt-3 ml-2 mr-2">
<template #transactionForm> <template #transactionForm>
<transaction-form :balance="balance" @set-transaction="setTransaction"></transaction-form> <transaction-form
v-bind="transactionData"
:balance="balance"
@set-transaction="setTransaction"
></transaction-form>
</template> </template>
<template #transactionConfirmationSend> <template #transactionConfirmationSend>
<transaction-confirmation-send <transaction-confirmation-send
@ -95,7 +99,6 @@ export default {
transactions: { transactions: {
default: () => [], default: () => [],
}, },
pending: { pending: {
type: Boolean, type: Boolean,
default: true, default: true,
@ -125,7 +128,8 @@ export default {
}) })
.then(() => { .then(() => {
this.error = false this.error = false
this.$emit('update-balance', this.transactionData.amount) this.updateTransactions({})
this.transactionData = { ...EMPTY_TRANSACTION_DATA }
this.currentTransactionStep = TRANSACTION_STEPS.transactionResultSendSuccess this.currentTransactionStep = TRANSACTION_STEPS.transactionResultSendSuccess
}) })
.catch((err) => { .catch((err) => {
@ -143,6 +147,7 @@ export default {
.then((result) => { .then((result) => {
this.code = result.data.createTransactionLink.code this.code = result.data.createTransactionLink.code
this.currentTransactionStep = TRANSACTION_STEPS.transactionResultLink this.currentTransactionStep = TRANSACTION_STEPS.transactionResultLink
this.updateTransactions({})
}) })
.catch((error) => { .catch((error) => {
this.toastError(error) this.toastError(error)
@ -161,7 +166,7 @@ export default {
}, },
}, },
created() { created() {
this.updateTransactions(0) this.updateTransactions({})
}, },
} }
</script> </script>

View File

@ -1,49 +0,0 @@
import { mount } from '@vue/test-utils'
import ShowTransactionLinkInformations from './ShowTransactionLinkInformations'
const localVue = global.localVue
const errorHandler = jest.fn()
localVue.config.errorHandler = errorHandler
const queryTransactionLink = jest.fn()
queryTransactionLink.mockResolvedValue('success')
const createMockObject = (code) => {
return {
localVue,
mocks: {
$t: jest.fn((t) => t),
$i18n: {
locale: () => 'en',
},
$apollo: {
query: queryTransactionLink,
},
$route: {
params: {
code,
},
},
},
}
}
describe('ShowTransactionLinkInformations', () => {
let wrapper
const Wrapper = (functionN) => {
return mount(ShowTransactionLinkInformations, functionN)
}
describe('mount', () => {
beforeEach(() => {
wrapper = Wrapper(createMockObject())
})
it('renders the component', () => {
expect(wrapper.find('div.show-transaction-link-informations').exists()).toBeTruthy()
})
})
})

View File

@ -1,57 +0,0 @@
<template>
<div class="show-transaction-link-informations">
<!-- Header -->
<div class="header py-7 py-lg-8 pt-lg-9">
<b-container>
<div class="header-body text-center mb-7">
<p class="h1">
{{ displaySetup.user.firstName }}
{{ $t('transaction-link.send_you') }} {{ displaySetup.amount | GDD }}
</p>
<p class="h4">{{ displaySetup.memo }}</p>
<hr />
<b-button v-if="displaySetup.linkTo" :to="displaySetup.linkTo">
{{ $t('transaction-link.button') }}
</b-button>
</div>
</b-container>
</div>
</div>
</template>
<script>
import { queryTransactionLink } from '@/graphql/queries'
export default {
name: 'ShowTransactionLinkInformations',
data() {
return {
displaySetup: {
user: {
firstName: '',
},
},
}
},
methods: {
setTransactionLinkInformation() {
this.$apollo
.query({
query: queryTransactionLink,
variables: {
code: this.$route.params.code,
},
})
.then((result) => {
this.displaySetup = result.data.queryTransactionLink
this.$store.commit('publisherId', result.data.queryTransactionLink.user.publisherId)
})
.catch((error) => {
this.toastError(error)
})
},
},
created() {
this.setTransactionLinkInformation()
},
}
</script>

View File

@ -0,0 +1,360 @@
import { mount } from '@vue/test-utils'
import TransactionLink from './TransactionLink'
import { queryTransactionLink } from '@/graphql/queries'
import { redeemTransactionLink } from '@/graphql/mutations'
import { toastSuccessSpy, toastErrorSpy } from '@test/testSetup'
const localVue = global.localVue
const apolloQueryMock = jest.fn()
const apolloMutateMock = jest.fn()
const routerPushMock = jest.fn()
const now = new Date().toISOString()
const transactionLinkValidExpireDate = () => {
const validUntil = new Date()
return new Date(validUntil.setDate(new Date().getDate() + 14)).toISOString()
}
apolloQueryMock.mockResolvedValue({
data: {
queryTransactionLink: {
id: 92,
amount: '22',
memo: 'Abrakadabra drei, vier, fünf, sechs, hier steht jetzt ein Memotext! Hex hex ',
createdAt: '2022-03-17T16:10:28.000Z',
validUntil: transactionLinkValidExpireDate(),
redeemedAt: '2022-03-18T10:08:43.000Z',
deletedAt: null,
user: { firstName: 'Bibi', publisherId: 0, email: 'bibi@bloxberg.de' },
},
},
})
const mocks = {
$t: jest.fn((t, obj = null) => (obj ? [t, obj.date].join('; ') : t)),
$store: {
state: {
token: null,
email: 'bibi@bloxberg.de',
},
},
$apollo: {
query: apolloQueryMock,
mutate: apolloMutateMock,
},
$route: {
params: {
code: 'some-code',
},
},
$router: {
push: routerPushMock,
},
}
describe('TransactionLink', () => {
let wrapper
const Wrapper = () => {
return mount(TransactionLink, { localVue, mocks })
}
describe('mount', () => {
beforeEach(() => {
jest.clearAllMocks()
wrapper = Wrapper()
})
it('renders the component', () => {
expect(wrapper.find('div.show-transaction-link-informations').exists()).toBe(true)
})
it('calls the queryTransactionLink query', () => {
expect(apolloQueryMock).toBeCalledWith({
query: queryTransactionLink,
variables: {
code: 'some-code',
},
})
})
describe('deleted link', () => {
beforeEach(() => {
apolloQueryMock.mockResolvedValue({
data: {
queryTransactionLink: {
id: 92,
amount: '22',
memo: 'Abrakadabra drei, vier, fünf, sechs, hier steht jetzt ein Memotext! Hex hex ',
createdAt: '2022-03-17T16:10:28.000Z',
validUntil: transactionLinkValidExpireDate(),
redeemedAt: '2022-03-18T10:08:43.000Z',
deletedAt: now,
user: { firstName: 'Bibi', publisherId: 0, email: 'bibi@bloxberg.de' },
},
},
})
wrapper = Wrapper()
})
it('has a component RedeemedTextBox', () => {
expect(wrapper.findComponent({ name: 'RedeemedTextBox' }).exists()).toBe(true)
})
it('has a link deleted text in text box', () => {
expect(wrapper.findComponent({ name: 'RedeemedTextBox' }).text()).toContain(
'gdd_per_link.link-deleted; ' + now,
)
})
})
describe('expired link', () => {
beforeEach(() => {
apolloQueryMock.mockResolvedValue({
data: {
queryTransactionLink: {
id: 92,
amount: '22',
memo: 'Abrakadabra drei, vier, fünf, sechs, hier steht jetzt ein Memotext! Hex hex ',
createdAt: '2022-03-17T16:10:28.000Z',
validUntil: '2020-03-18T10:08:43.000Z',
redeemedAt: '2022-03-18T10:08:43.000Z',
deletedAt: null,
user: { firstName: 'Bibi', publisherId: 0, email: 'bibi@bloxberg.de' },
},
},
})
wrapper = Wrapper()
})
it('has a component RedeemedTextBox', () => {
expect(wrapper.findComponent({ name: 'RedeemedTextBox' }).exists()).toBe(true)
})
it('has a link deleted text in text box', () => {
expect(wrapper.findComponent({ name: 'RedeemedTextBox' }).text()).toContain(
'gdd_per_link.link-expired; 2020-03-18T10:08:43.000Z',
)
})
})
describe('redeemed link', () => {
beforeEach(() => {
apolloQueryMock.mockResolvedValue({
data: {
queryTransactionLink: {
id: 92,
amount: '22',
memo: 'Abrakadabra drei, vier, fünf, sechs, hier steht jetzt ein Memotext! Hex hex ',
createdAt: '2022-03-17T16:10:28.000Z',
validUntil: transactionLinkValidExpireDate(),
redeemedAt: '2022-03-18T10:08:43.000Z',
deletedAt: null,
user: { firstName: 'Bibi', publisherId: 0, email: 'bibi@bloxberg.de' },
},
},
})
wrapper = Wrapper()
})
it('has a component RedeemedTextBox', () => {
expect(wrapper.findComponent({ name: 'RedeemedTextBox' }).exists()).toBe(true)
})
it('has a link deleted text in text box', () => {
expect(wrapper.findComponent({ name: 'RedeemedTextBox' }).text()).toContain(
'gdd_per_link.redeemed-at; 2022-03-18T10:08:43.000Z',
)
})
})
describe('no token in store', () => {
beforeEach(() => {
apolloQueryMock.mockResolvedValue({
data: {
queryTransactionLink: {
id: 92,
amount: '22',
memo: 'Abrakadabra drei, vier, fünf, sechs, hier steht jetzt ein Memotext! Hex hex ',
createdAt: '2022-03-17T16:10:28.000Z',
validUntil: transactionLinkValidExpireDate(),
redeemedAt: null,
deletedAt: null,
user: { firstName: 'Bibi', publisherId: 0, email: 'bibi@bloxberg.de' },
},
},
})
wrapper = Wrapper()
})
it('has a RedeemLoggedOut component', () => {
expect(wrapper.findComponent({ name: 'RedeemLoggedOut' }).exists()).toBe(true)
})
it('has a link to register with code', () => {
expect(wrapper.find('a[href="/register/some-code"]').exists()).toBe(true)
})
it('has a link to login with code', () => {
expect(wrapper.find('a[href="/login/some-code"]').exists()).toBe(true)
})
})
describe('token in store and own link', () => {
beforeEach(() => {
mocks.$store.state.token = 'token'
apolloQueryMock.mockResolvedValue({
data: {
queryTransactionLink: {
id: 92,
amount: '22',
memo: 'Abrakadabra drei, vier, fünf, sechs, hier steht jetzt ein Memotext! Hex hex ',
createdAt: '2022-03-17T16:10:28.000Z',
validUntil: transactionLinkValidExpireDate(),
redeemedAt: null,
deletedAt: null,
user: { firstName: 'Bibi', publisherId: 0, email: 'bibi@bloxberg.de' },
},
},
})
wrapper = Wrapper()
})
it('has a RedeemSelfCreator component', () => {
expect(wrapper.findComponent({ name: 'RedeemSelfCreator' }).exists()).toBe(true)
})
it('has a no redeem text', () => {
expect(wrapper.findComponent({ name: 'RedeemSelfCreator' }).text()).toContain(
'gdd_per_link.no-redeem',
)
})
it('has a link to transaction page', () => {
expect(wrapper.find('a[to="/transactions"]').exists()).toBe(true)
})
})
describe('valid link', () => {
beforeEach(() => {
mocks.$store.state.token = 'token'
apolloQueryMock.mockResolvedValue({
data: {
queryTransactionLink: {
id: 92,
amount: '22',
memo: 'Abrakadabra drei, vier, fünf, sechs, hier steht jetzt ein Memotext! Hex hex ',
createdAt: '2022-03-17T16:10:28.000Z',
validUntil: transactionLinkValidExpireDate(),
redeemedAt: null,
deletedAt: null,
user: { firstName: 'Peter', publisherId: 0, email: 'peter@listig.de' },
},
},
})
wrapper = Wrapper()
})
it('has a RedeemValid component', () => {
expect(wrapper.findComponent({ name: 'RedeemValid' }).exists()).toBe(true)
})
it('has a button with redeem text', () => {
expect(wrapper.findComponent({ name: 'RedeemValid' }).find('button').text()).toBe(
'gdd_per_link.redeem',
)
})
describe('redeem link with success', () => {
let spy
beforeEach(async () => {
spy = jest.spyOn(wrapper.vm.$bvModal, 'msgBoxConfirm')
apolloMutateMock.mockResolvedValue()
spy.mockImplementation(() => Promise.resolve(true))
await wrapper.findComponent({ name: 'RedeemValid' }).find('button').trigger('click')
})
it('opens the modal', () => {
expect(spy).toBeCalledWith('gdd_per_link.redeem-text')
})
it('calls the API', () => {
expect(apolloMutateMock).toBeCalledWith(
expect.objectContaining({
mutation: redeemTransactionLink,
variables: {
code: 'some-code',
},
}),
)
})
it('toasts a success message', () => {
expect(mocks.$t).toBeCalledWith('gdd_per_link.redeemed', { n: '22' })
expect(toastSuccessSpy).toBeCalledWith('gdd_per_link.redeemed; ')
})
it('pushes the route to overview', () => {
expect(routerPushMock).toBeCalledWith('/overview')
})
})
describe('cancel redeem link', () => {
let spy
beforeEach(async () => {
spy = jest.spyOn(wrapper.vm.$bvModal, 'msgBoxConfirm')
apolloMutateMock.mockResolvedValue()
spy.mockImplementation(() => Promise.resolve(false))
await wrapper.findComponent({ name: 'RedeemValid' }).find('button').trigger('click')
})
it('does not call the API', () => {
expect(apolloMutateMock).not.toBeCalled()
})
it('does not toasts a success message', () => {
expect(mocks.$t).not.toBeCalledWith('gdd_per_link.redeemed', { n: '22' })
expect(toastSuccessSpy).not.toBeCalled()
})
it('does not push the route', () => {
expect(routerPushMock).not.toBeCalled()
})
})
describe('redeem link with error', () => {
let spy
beforeEach(async () => {
spy = jest.spyOn(wrapper.vm.$bvModal, 'msgBoxConfirm')
apolloMutateMock.mockRejectedValue({ message: 'Oh Noo!' })
spy.mockImplementation(() => Promise.resolve(true))
await wrapper.findComponent({ name: 'RedeemValid' }).find('button').trigger('click')
})
it('toasts an error message', () => {
expect(toastErrorSpy).toBeCalledWith('Oh Noo!')
})
it('pushes the route to overview', () => {
expect(routerPushMock).toBeCalledWith('/overview')
})
})
})
describe('error on transaction link query', () => {
beforeEach(() => {
apolloQueryMock.mockRejectedValue({ message: 'Ouchh!' })
wrapper = Wrapper()
})
it('toasts an error message', () => {
expect(toastErrorSpy).toBeCalledWith('Ouchh!')
})
})
})
})

View File

@ -0,0 +1,148 @@
<template>
<div class="show-transaction-link-informations">
<div class="text-center"><b-img :src="img" fluid alt="logo"></b-img></div>
<b-container class="mt-4">
<transaction-link-item :type="itemType">
<template #LOGGED_OUT>
<redeem-logged-out v-bind="linkData" />
</template>
<template #SELF_CREATOR>
<redeem-self-creator v-bind="linkData" />
</template>
<template #VALID>
<redeem-valid v-bind="linkData" @redeem-link="redeemLink" />
</template>
<template #TEXT>
<redeemed-text-box :text="redeemedBoxText" />
</template>
</transaction-link-item>
</b-container>
</div>
</template>
<script>
import TransactionLinkItem from '@/components/TransactionLinkItem'
import RedeemLoggedOut from '@/components/LinkInformations/RedeemLoggedOut'
import RedeemSelfCreator from '@/components/LinkInformations/RedeemSelfCreator'
import RedeemValid from '@/components/LinkInformations/RedeemValid'
import RedeemedTextBox from '@/components/LinkInformations/RedeemedTextBox'
import { queryTransactionLink } from '@/graphql/queries'
import { redeemTransactionLink } from '@/graphql/mutations'
export default {
name: 'TransactionLink',
components: {
TransactionLinkItem,
RedeemLoggedOut,
RedeemSelfCreator,
RedeemValid,
RedeemedTextBox,
},
data() {
return {
img: '/img/brand/green.png',
linkData: {
amount: '123.45',
memo: 'memo',
user: {
firstName: 'Bibi',
},
deletedAt: null,
},
}
},
methods: {
setTransactionLinkInformation() {
this.$apollo
.query({
query: queryTransactionLink,
variables: {
code: this.$route.params.code,
},
})
.then((result) => {
this.linkData = result.data.queryTransactionLink
})
.catch((err) => {
this.toastError(err.message)
})
},
redeemLink(amount) {
this.$bvModal.msgBoxConfirm(this.$t('gdd_per_link.redeem-text')).then(async (value) => {
if (value)
await this.$apollo
.mutate({
mutation: redeemTransactionLink,
variables: {
code: this.$route.params.code,
},
})
.then(() => {
this.toastSuccess(
this.$t('gdd_per_link.redeemed', {
n: amount,
}),
)
this.$router.push('/overview')
})
.catch((err) => {
this.toastError(err.message)
this.$router.push('/overview')
})
})
},
},
computed: {
itemType() {
// link wurde gelöscht: am, von
if (this.linkData.deletedAt) {
// eslint-disable-next-line vue/no-side-effects-in-computed-properties
this.redeemedBoxText = this.$t('gdd_per_link.link-deleted', {
date: this.linkData.deletedAt,
})
return `TEXT`
}
// link ist abgelaufen, nicht gelöscht
if (new Date(this.linkData.validUntil) < new Date()) {
// eslint-disable-next-line vue/no-side-effects-in-computed-properties
this.redeemedBoxText = this.$t('gdd_per_link.link-expired', {
date: this.linkData.validUntil,
})
return `TEXT`
}
// der link wurde eingelöst, nicht gelöscht
if (this.linkData.redeemedAt) {
// eslint-disable-next-line vue/no-side-effects-in-computed-properties
this.redeemedBoxText = this.$t('gdd_per_link.redeemed-at', {
date: this.linkData.redeemedAt,
})
return `TEXT`
}
if (this.$store.state.token) {
// logged in, nicht berechtigt einzulösen, eigener link
if (this.$store.state.email === this.linkData.user.email) {
return `SELF_CREATOR`
}
// logged in und berechtigt einzulösen
if (
this.$store.state.email !== this.linkData.user.email &&
!this.linkData.redeemedAt &&
!this.linkData.deletedAt
) {
return `VALID`
}
}
return `LOGGED_OUT`
},
},
created() {
this.setTransactionLinkInformation()
},
}
</script>

View File

@ -99,11 +99,11 @@ describe('Thx', () => {
}) })
it('renders the thanks redirect button', () => { it('renders the thanks redirect button', () => {
expect(wrapper.find('a.btn').text()).toBe('login') expect(wrapper.find('a.btn').text()).toBe('settings.password.reset')
}) })
it('links the redirect button to /login', () => { it('links the redirect button to /forgot-password', () => {
expect(wrapper.find('a.btn').attributes('href')).toBe('/login') expect(wrapper.find('a.btn').attributes('href')).toBe('/forgot-password')
}) })
}) })
}) })

View File

@ -48,8 +48,8 @@ const textFields = {
login: { login: {
headline: 'site.thx.errorTitle', headline: 'site.thx.errorTitle',
subtitle: 'site.thx.activateEmail', subtitle: 'site.thx.activateEmail',
button: 'login', button: 'settings.password.reset',
linkTo: '/login', linkTo: '/forgot-password',
}, },
} }

View File

@ -99,14 +99,14 @@ describe('router', () => {
describe('login', () => { describe('login', () => {
it('loads the "Login" page', async () => { it('loads the "Login" page', async () => {
const component = await routes.find((r) => r.path === '/login').component() const component = await routes.find((r) => r.path === '/login/:code?').component()
expect(component.default.name).toBe('Login') expect(component.default.name).toBe('Login')
}) })
}) })
describe('register', () => { describe('register', () => {
it('loads the "register" page', async () => { it('loads the "register" page', async () => {
const component = await routes.find((r) => r.path === '/register').component() const component = await routes.find((r) => r.path === '/register/:code?').component()
expect(component.default.name).toBe('Register') expect(component.default.name).toBe('Register')
}) })
}) })
@ -182,6 +182,13 @@ describe('router', () => {
}) })
}) })
describe('redeem', () => {
it('loads the "TransactionLink" page', async () => {
const component = await routes.find((r) => r.path === '/redeem/:code').component()
expect(component.default.name).toBe('TransactionLink')
})
})
describe('not found page', () => { describe('not found page', () => {
it('renders the "NotFound" page', async () => { it('renders the "NotFound" page', async () => {
expect(routes.find((r) => r.path === '*').component).toEqual(NotFound) expect(routes.find((r) => r.path === '*').component).toEqual(NotFound)

View File

@ -39,11 +39,11 @@ const routes = [
}, },
}, },
{ {
path: '/login', path: '/login/:code?',
component: () => import('@/pages/Login.vue'), component: () => import('@/pages/Login.vue'),
}, },
{ {
path: '/register', path: '/register/:code?',
component: () => import('@/pages/Register.vue'), component: () => import('@/pages/Register.vue'),
}, },
{ {
@ -84,7 +84,7 @@ const routes = [
}, },
{ {
path: '/redeem/:code', path: '/redeem/:code',
component: () => import('@/pages/ShowTransactionLinkInformations.vue'), component: () => import('@/pages/TransactionLink.vue'),
}, },
{ path: '*', component: NotFound }, { path: '*', component: NotFound },
] ]