Compare commits

...

91 Commits

Author SHA1 Message Date
Alex Ant 4925ea4af0 chore(release): publish
- cooparser-ts@1.0.19-alpha.1
 - coopback@1.7.35-alpha.2
 - coopdoc-generator-ts@1.0.79-alpha.2
 - cooptypes@1.0.22-alpha.2
 - coop-notificator@0.0.26-alpha.2
 - terminal@0.1.39-alpha.2
2024-09-11 10:04:46 +05:00
Alex Ant 57b05ce348 registration agreements 2024-09-11 10:01:09 +05:00
Alex Ant 427b53fcbd chore(release): publish
- coopback@1.7.35-alpha.1
 - coopdoc-generator-ts@1.0.79-alpha.1
 - cooptypes@1.0.22-alpha.1
 - coop-notificator@0.0.26-alpha.1
 - terminal@0.1.39-alpha.1
2024-09-10 10:06:12 +05:00
Alex Ant 2ac7a31be6 промежуточный результат добавления кооперативных соглашений 2024-09-10 10:05:17 +05:00
Alex Ant 4baed6409f chore(release): publish
- cooparser-ts@1.0.19-alpha.0
 - coopback@1.7.35-alpha.0
 - coopdoc-generator-ts@1.0.79-alpha.0
 - cooptypes@1.0.22-alpha.0
 - coop-notificator@0.0.26-alpha.0
 - terminal@0.1.39-alpha.0
2024-09-06 16:39:34 +05:00
Alex Ant 2ea0ff0965 big update 2024-09-06 16:29:18 +05:00
Alex Ant 88b9a7edce small letters 2024-09-05 19:27:23 +05:00
Alex Ant 538066b960 ufff template or Template ??? always should be small letters 2024-09-05 19:25:37 +05:00
Alex Ant b10dd1d75a update generator with new type of document 2024-09-04 20:57:59 +05:00
Alex Ant f743580b55 fix signature collection name 2024-09-03 20:33:30 +05:00
Alex Ant 0688467302 update 2024-09-03 20:11:17 +05:00
Alex Ant 29e972dbf2 fix is_paid 2024-08-27 18:47:39 +05:00
Alex Ant bd99697c5b chore(release): publish
- coopback@1.7.34
 - coopdoc-generator-ts@1.0.78
 - cooptypes@1.0.21
 - coop-notificator@0.0.25
 - terminal@0.1.38
2024-08-25 11:39:35 +05:00
Alex Ant 1d5c431ff6 update types 2024-08-25 11:38:40 +05:00
Alex Ant 3736c510ff chore(release): publish
- cooparser-ts@1.0.18
 - coopback@1.7.33
 - coopdoc-generator-ts@1.0.77
 - terminal@0.1.37
2024-08-25 11:27:44 +05:00
Alex Ant 26c12c3a85 update 2024-08-25 11:25:28 +05:00
Alex Ant 10bb08e5e6 chore(release): publish
- coopback@1.7.32
 - coopdoc-generator-ts@1.0.76
 - terminal@0.1.36
2024-08-25 11:19:13 +05:00
Alex Ant b50d5b6121 publish 2024-08-25 11:07:57 +05:00
Alex Ant 38b28752e1 chore(release): publish
- coopback@1.7.31
 - coopdoc-generator-ts@1.0.75
 - cooptypes@1.0.20
 - coop-notificator@0.0.24
 - terminal@0.1.35
2024-08-25 11:02:44 +05:00
Alex Ant 87c51009de ProgramProvision | ЦПП Цифровой Кошелёк 2024-08-25 10:59:57 +05:00
Alex Ant a950a47b28 chore(release): publish
- coopback@1.7.31-alpha.1
 - coopdoc-generator-ts@1.0.75-alpha.1
 - cooptypes@1.0.20-alpha.1
 - coop-notificator@0.0.24-alpha.1
 - terminal@0.1.35-alpha.1
2024-08-23 10:38:04 +05:00
Alex Ant 2609d10c0b update 2024-08-23 10:35:48 +05:00
Alex Ant 7b4cb0f66c publish 2024-08-23 10:34:38 +05:00
Alex Ant 26db0e1e69 push 2024-08-21 15:57:02 +05:00
Alex Ant 62e64cbd22 upgrade 2024-08-21 14:43:43 +05:00
Alex Ant 844a47830f fix types 2024-08-21 13:11:37 +05:00
Alex Ant 2cc1e32f45 chore(release): publish
- coopback@1.7.31-alpha.0
 - coopdoc-generator-ts@1.0.75-alpha.0
 - cooptypes@1.0.20-alpha.0
 - coop-notificator@0.0.24-alpha.0
 - terminal@0.1.35-alpha.0
2024-08-21 12:53:38 +05:00
Alex Ant 9890958b1e update contracts interface 2024-08-21 12:50:44 +05:00
Alex Ant 6dbd6d6edc fix 2024-08-19 14:31:01 +05:00
Alex Ant bf7a4dfd28 путь установки 2024-08-19 14:20:38 +05:00
Alex Ant f52626bda0 Полное разделение форм ввода данных пользователя пригодное для использования в процессе инсталляции 2024-08-16 16:17:24 +05:00
Alex Ant 88cec4bf2b рефакторинг | вынос форм для ввода пользовательской информации в shared для дальнейшего использования в модуле установки 2024-08-15 20:30:01 +05:00
Alex Ant b880def108 fix 2024-08-15 12:39:19 +05:00
Alex Ant bfd5dc039a addUser в панели управления 2024-08-15 12:28:18 +05:00
Alex Ant c0d236dff3 chore(release): publish
- coopback@1.7.30
 - coopdoc-generator-ts@1.0.74
 - cooptypes@1.0.19
 - coop-notificator@0.0.23
 - terminal@0.1.34
2024-08-13 23:03:13 +05:00
Alex Ant 743d5fc306 разделение формы для ввода персональных данных с регистратором; зародыш формы добавления пайщика в реестр. 2024-08-13 23:00:09 +05:00
Alex Ant 2f51516163 step to install | works on add user by api 2024-08-13 15:21:23 +05:00
Alex Ant b606b46aa4 страница настроек с кнопками выхода для пайщика 2024-08-05 14:31:27 +05:00
Alex Ant 5b65ff99a0 chore(release): publish
- coopback@1.7.29
 - coopdoc-generator-ts@1.0.73
 - cooptypes@1.0.18
 - coop-notificator@0.0.22
 - terminal@0.1.33
2024-08-05 12:36:01 +05:00
Alex Ant 74a3f52324 update 2024-08-05 12:32:23 +05:00
Alex Ant 7c2a4fdfa8 удаление потерявшейся папки 2024-08-05 12:05:05 +05:00
Alex Ant fecee3a098 fix naming 2024-08-05 11:56:29 +05:00
Alex Ant 45f7111fb9 chore(release): publish
- coopback@1.7.29-alpha.0
 - coopdoc-generator-ts@1.0.73-alpha.0
 - cooptypes@1.0.18-alpha.0
 - coop-notificator@0.0.22-alpha.0
 - terminal@0.1.33-alpha.0
2024-08-05 11:51:37 +05:00
Alex Ant f2e23a8062 перевыпуск ключа доступа 2024-08-05 11:38:10 +05:00
Alex Ant 36a3631f5e login with signature 2024-08-02 17:11:01 +05:00
Alex Ant a758d19a9f обновление mongoose, интеграция eslint и активация typescript проверок 2024-08-01 14:06:01 +05:00
Alex Ant aac3e53a30 eslint repair 2024-08-01 13:06:28 +05:00
Alex Ant 85d87ee210 FIX !!! 2024-07-31 20:48:38 +05:00
Alex Ant 2f3ee80ed4 Merge branch 'main' into dev 2024-07-31 17:26:20 +05:00
Alex Ant 3632bea54e chore(release): publish
- terminal@0.1.32
2024-07-31 17:26:08 +05:00
Alex Ant 4a0521751a update 2024-07-31 17:24:44 +05:00
Alex Ant 7d6266c241 chore(release): publish
- terminal@0.1.32-alpha.0
2024-07-31 16:28:53 +05:00
Alex Ant 1d69b9ffea Рабочие столы v1 2024-07-31 16:24:50 +05:00
Alex Ant 72674cba10 chore(release): publish
- coopback@1.7.28
 - terminal@0.1.31
2024-07-26 18:42:47 +05:00
Alex Ant 495a8e2d1e chore(release): publish
- coopback@1.7.28-alpha.0
 - terminal@0.1.31-alpha.0
2024-07-26 18:41:33 +05:00
Alex Ant 95ae221d60 Добавление платежных реквизитов | удаление | просмотр | свайп в рамках страницы 2024-07-26 18:38:14 +05:00
Alex Ant 857f746da1 bug fix 2024-07-26 11:03:52 +05:00
Alex Ant 0e2e3052b1 works 2024-07-25 21:00:04 +05:00
Alex Ant 167c04cc3f commit 2024-07-25 20:47:42 +05:00
Alex Ant 043f51479a looking for bug #2 2024-07-25 20:30:56 +05:00
Alex Ant 921282df81 looking for bug 2024-07-25 20:20:44 +05:00
Alex Ant b3c641501c migration 2024-07-25 20:07:44 +05:00
Alex Ant 3608e7601f chore(release): publish
- cooparser-ts@1.0.17
 - coopback@1.7.27
 - coopdoc-generator-ts@1.0.72
 - cooptypes@1.0.17
 - coop-notificator@0.0.21
 - terminal@0.1.30
2024-07-25 19:41:18 +05:00
Alex Ant a75cfa1056 chore(release): publish
- coopback@1.7.27-alpha.5
 - terminal@0.1.30-alpha.4
2024-07-25 19:39:41 +05:00
Alex Ant f08c4102fd login with email 2024-07-25 19:37:13 +05:00
Alex Ant 9bfd7c7d9a chore(release): publish
- coopback@1.7.27-alpha.4
2024-07-25 18:24:15 +05:00
Alex Ant a359b4fbdb fix 2024-07-25 18:22:17 +05:00
Alex Ant effb6df495 chore(release): publish
- cooparser-ts@1.0.17-alpha.2
 - coopback@1.7.27-alpha.3
 - coopdoc-generator-ts@1.0.72-alpha.3
 - cooptypes@1.0.17-alpha.3
 - coop-notificator@0.0.21-alpha.3
 - terminal@0.1.30-alpha.3
2024-07-25 17:56:22 +05:00
Alex Ant 6e6c963663 update 2024-07-25 17:55:36 +05:00
Alex Ant 23f5c7b578 update 2024-07-25 17:55:14 +05:00
Alex Ant 02b223266d pre 2024-07-25 17:05:44 +05:00
Alex Ant 745a8c99e1 publish cooptypes 2024-07-25 17:03:17 +05:00
Alex Ant 5532038fd8 coopback payment methods (list | add | del) & tests 2024-07-25 16:06:06 +05:00
Alex Ant 3be31c5240 coopback tests work 2024-07-24 23:30:01 +05:00
Alex Ant 11ab59e109 coopback tests restore #1 2024-07-23 22:34:42 +05:00
Alex Ant d5bbf10041 before generator refactoring 2024-07-23 10:10:22 +05:00
Alex Ant ba4f9581a4 before generator refactoring 2024-07-23 09:46:19 +05:00
Alex Ant 52eabab633 chore(release): publish
- coopback@1.7.27-alpha.0
 - coopdoc-generator-ts@1.0.72-alpha.0
 - cooptypes@1.0.17-alpha.0
 - coop-notificator@0.0.21-alpha.0
 - terminal@0.1.30-alpha.0
2024-07-18 20:15:52 +05:00
Alex Ant 600949b784 изменяемые публичные контакты кооператива 2024-07-18 20:09:46 +05:00
Alex Ant dcca48097d chore(members): убран лишний код 2024-07-16 21:21:06 +05:00
Alex Ant 6e20c32a14 update 2024-07-16 21:13:51 +05:00
Alex Ant 0cd1af0cf1 chore(release): publish
- cooparser-ts@1.0.16
 - coopback@1.7.26
 - coopdoc-generator-ts@1.0.71
 - cooptypes@1.0.16
 - coop-notificator@0.0.20
 - terminal@0.1.29
2024-07-15 18:51:34 +05:00
Alex Ant d786dbc095 chore(release): publish
- coop-notificator@0.0.20-alpha.1
2024-07-15 18:36:08 +05:00
Alex Ant 5b0581158a fix тип socketio 2024-07-15 18:30:36 +05:00
Alex Ant dced33c8e6 chore(release): publish
- cooparser-ts@1.0.16-alpha.0
 - coopback@1.7.26-alpha.0
 - coopdoc-generator-ts@1.0.71-alpha.0
 - cooptypes@1.0.16-alpha.0
 - coop-notificator@0.0.20-alpha.0
 - terminal@0.1.29-alpha.1
2024-07-15 17:44:30 +05:00
Alex Ant 1a9ab8d997 1. Введен WS-нотификатор, отправляющий анонимизированные оповещения всем подписанантам
2. Контроллер подключен к нотификатору для циркулярного обновления прав доступа членов совета
3. Введены настройки кооператива: управление советом и просмотр реквизитов.
2024-07-15 17:41:03 +05:00
Alex Ant 0f4da3ad18 chore(release): publish
- terminal@0.1.29-alpha.0
2024-07-14 14:31:43 +05:00
Alex Ant bba8a72eef update 2024-07-14 14:30:22 +05:00
Alex Ant 7f0a81a1bc chore(release): publish
- terminal@0.1.28
2024-07-14 14:18:54 +05:00
Alex Ant 38db03b4fc chore(release): publish
- terminal@0.1.28-alpha.0
2024-07-14 14:17:57 +05:00
Alex Ant 409ba6c104 update 2024-07-14 14:17:29 +05:00
560 changed files with 17114 additions and 14844 deletions
Vendored
BIN
View File
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
node_modules
dist
+14
View File
@@ -0,0 +1,14 @@
{
"editor.bracketPairColorization.enabled": true,
"editor.guides.bracketPairs": true,
"editor.formatOnSave": true,
"editor.tabCompletion": "onlySnippets",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": ["source.fixAll.eslint"],
"eslint.validate": ["javascript", "typescript", "vue"],
"typescript.tsdk": "node_modules/typescript/lib",
"i18n-ally.localesPaths": ["src/i18n"],
"typescript.format.enable": true,
"typescript.format.indentSwitchCase": false,
"typescript.validate.enable": true,
}
+10
View File
@@ -0,0 +1,10 @@
FROM node:18-alpine
WORKDIR /app
COPY . .
RUN npm install -g pnpm lerna
RUN pnpm install
RUN lerna run build
+24
View File
@@ -3,6 +3,30 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.0.18](https://github.com/copenomics/cooparser/compare/cooparser-ts@1.0.17...cooparser-ts@1.0.18) (2024-08-25)
**Note:** Version bump only for package cooparser-ts
## [1.0.17](https://github.com/copenomics/cooparser/compare/cooparser-ts@1.0.17-alpha.2...cooparser-ts@1.0.17) (2024-07-25)
**Note:** Version bump only for package cooparser-ts
## [1.0.16](https://github.com/copenomics/cooparser/compare/cooparser-ts@1.0.16-alpha.0...cooparser-ts@1.0.16) (2024-07-15)
**Note:** Version bump only for package cooparser-ts
## [1.0.15](https://github.com/copenomics/cooparser/compare/cooparser-ts@1.0.15-alpha.0...cooparser-ts@1.0.15) (2024-07-14)
**Note:** Version bump only for package cooparser-ts
+2 -3
View File
@@ -1,12 +1,12 @@
{
"name": "pkg-placeholder",
"version": "1.0.15",
"version": "1.0.19-alpha.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "pkg-placeholder",
"version": "1.0.15",
"version": "1.0.19-alpha.1",
"license": "MIT",
"devDependencies": {
"@antfu/eslint-config": "^2.16.0",
@@ -16,7 +16,6 @@
"bumpp": "^9.4.0",
"eslint": "^8.57.0",
"esno": "^4.7.0",
"lint-staged": "^15.2.2",
"pnpm": "^8.15.7",
"rimraf": "^5.0.5",
"simple-git-hooks": "^2.11.1",
+3 -9
View File
@@ -1,8 +1,8 @@
{
"name": "cooparser-ts",
"type": "module",
"version": "1.0.15",
"private": true,
"version": "1.0.19-alpha.1",
"private": false,
"packageManager": "pnpm@9.0.6",
"description": "",
"author": "Alex Ant <dacom.dark.sun@gmail.com>",
@@ -41,6 +41,7 @@
"deploy-production": "git checkout production && git merge testnet && git push origin production && git checkout main",
"build": "unbuild",
"dev": "concurrently -n 'PARSER' -c 'bgBlue.white' \"nodemon --watch src --ext ts,js,env --exec 'esno' src/index.ts\"",
"dev:test": "NODE_ENV=test concurrently -n 'PARSER' -c 'bgBlue.white' \"nodemon --watch src --ext ts,js,env --exec 'esno' src/index.ts\"",
"lint": "eslint .",
"prepublishOnly": "nr build",
"release": "bumpp && npm publish",
@@ -72,7 +73,6 @@
"concurrently": "^8.2.2",
"eslint": "^8.57.0",
"esno": "^4.7.0",
"lint-staged": "^15.2.2",
"nodemon": "^3.1.4",
"pnpm": "^8.15.7",
"rimraf": "^5.0.5",
@@ -82,11 +82,5 @@
"unbuild": "^2.0.0",
"vite": "^5.2.10",
"vitest": "^1.5.2"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
},
"lint-staged": {
"*": "eslint --fix"
}
}
@@ -14,6 +14,7 @@ export async function BlockParser(db: Database, reader: EosioShipReaderResolved)
setTimeout(() => process.exit(1), 10000)
})
blocks$.subscribe(async (block: IBlock) => {
// console.log('new block: ', block)
// process.stdout.write('\r') // Возврат каретки в начало строки
+1 -1
View File
@@ -16,7 +16,7 @@ export class Database {
async connect() {
await this.client.connect()
this.db = this.client.db('cooperative')
this.db = this.client.db()
this.actions = this.db.collection('actions')
this.deltas = this.db.collection('deltas')
this.sync = this.db.collection('sync')
+9 -3
View File
@@ -7,8 +7,14 @@ import { loadReader } from '../Reader'
export class Parser {
async start() {
const reader = await loadReader(db)
BlockParser(db, reader)
ActionsParser(db, reader)
DeltasParser(db, reader)
try {
BlockParser(db, reader)
ActionsParser(db, reader)
DeltasParser(db, reader)
}
catch (e) {
console.error('Ошибка: ', e)
this.start()
}
}
}
+3 -3
View File
@@ -10,10 +10,10 @@ function getEnvVar(key: string): string {
return envVar
}
export const node_env = getEnvVar('NODE_ENV')
export const eosioApi = getEnvVar('API')
export const shipApi = getEnvVar('SHIP')
export const mongoUri = getEnvVar('MONGO_EXPLORER_URI')
export const mongoUri = `${getEnvVar('MONGO_EXPLORER_URI')}${node_env === 'test' ? '-test' : ''}`
export const startBlock = getEnvVar('START_BLOCK')
export const finishBlock = getEnvVar('FINISH_BLOCK')
export const redisPort = getEnvVar('REDIS_PORT')
@@ -49,11 +49,11 @@ export const subsribedActions: IActionConfig[] = [
{ code: 'soviet', action: 'newresolved' },
{ code: 'soviet', action: 'newdecision' },
// // registrator.joincoop
{ code: 'soviet', action: 'joincoop' },
{ code: 'soviet', action: 'joincoopdec' },
{ code: 'soviet', action: 'updateboard', notify: true },
]
// --------------------------
+1 -1
View File
@@ -45,6 +45,6 @@ app.get('/get-current-block', async (req: any, res: any) => {
// Глобальный обработчик ошибок
app.use((err: any, req: any, res: any, _next: any) => {
console.error(err)
console.error('глобальная ошибка: ', err)
res.status(500).send(err.message)
})
-31
View File
@@ -1,31 +0,0 @@
{
"env": {
"node": true,
"jest": true
},
"extends": ["airbnb-base", "plugin:jest/recommended", "plugin:security/recommended", "plugin:prettier/recommended"],
"plugins": ["jest", "security", "prettier", "import"],
"parserOptions": {
"ecmaVersion": 2018
},
"rules": {
"@typescript-eslint/no-explicit-any":"off",
"no-console": "error",
"func-names": "off",
"no-underscore-dangle": "off",
"consistent-return": "off",
"jest/expect-expect": "off",
"security/detect-object-injection": "off",
"import/extensions": [
"error",
"ignorePackages",
{
"js": "never",
"jsx": "never",
"ts": "never",
"tsx": "never"
}
]
}
}
+29
View File
@@ -0,0 +1,29 @@
{
"env": {
"node": true,
"jest": true,
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"plugins": ["@typescript-eslint", "prettier"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module",
"project": "./tsconfig.json"
},
"rules": {
"no-console": "warn",
"func-names": "off",
"no-underscore-dangle": "off",
"consistent-return": "off",
"jest/expect-expect": "off",
"security/detect-object-injection": "off",
"@typescript-eslint/no-unused-vars": "warn"
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# . "$(dirname "$0")/_/husky.sh"
yarn install
# yarn install
+2 -2
View File
@@ -1,4 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# . "$(dirname "$0")/_/husky.sh"
git status
# git status
+2 -2
View File
@@ -1,4 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# . "$(dirname "$0")/_/husky.sh"
yarn lint-staged
# yarn lint-staged
+4 -2
View File
@@ -1,6 +1,8 @@
{
"CodeGPT.apiKey": "OpenAI",
"cSpell.words": [
"subcode"
]
],
"editor.formatOnSave": true,
"typescript.tsdk": "node_modules/typescript/lib",
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
+72
View File
@@ -3,6 +3,78 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.7.34](https://github.com/hagopj13/node-express-boilerplate/compare/coopback@1.7.33...coopback@1.7.34) (2024-08-25)
**Note:** Version bump only for package coopback
## [1.7.33](https://github.com/hagopj13/node-express-boilerplate/compare/coopback@1.7.32...coopback@1.7.33) (2024-08-25)
**Note:** Version bump only for package coopback
## [1.7.32](https://github.com/hagopj13/node-express-boilerplate/compare/coopback@1.7.31...coopback@1.7.32) (2024-08-25)
**Note:** Version bump only for package coopback
## [1.7.31](https://github.com/hagopj13/node-express-boilerplate/compare/coopback@1.7.31-alpha.1...coopback@1.7.31) (2024-08-25)
**Note:** Version bump only for package coopback
## [1.7.30](https://github.com/hagopj13/node-express-boilerplate/compare/coopback@1.7.29...coopback@1.7.30) (2024-08-13)
**Note:** Version bump only for package coopback
## [1.7.29](https://github.com/hagopj13/node-express-boilerplate/compare/coopback@1.7.29-alpha.0...coopback@1.7.29) (2024-08-05)
**Note:** Version bump only for package coopback
## [1.7.28](https://github.com/hagopj13/node-express-boilerplate/compare/coopback@1.7.28-alpha.0...coopback@1.7.28) (2024-07-26)
**Note:** Version bump only for package coopback
## [1.7.27](https://github.com/hagopj13/node-express-boilerplate/compare/coopback@1.7.27-alpha.5...coopback@1.7.27) (2024-07-25)
**Note:** Version bump only for package coopback
## [1.7.26](https://github.com/hagopj13/node-express-boilerplate/compare/coopback@1.7.26-alpha.0...coopback@1.7.26) (2024-07-15)
**Note:** Version bump only for package coopback
## [1.7.25](https://github.com/hagopj13/node-express-boilerplate/compare/coopback@1.7.25-alpha.0...coopback@1.7.25) (2024-07-14)
**Note:** Version bump only for package coopback
+4 -5
View File
@@ -1,12 +1,12 @@
{
"name": "create-nodejs-express-app",
"version": "1.7.25",
"version": "1.7.35-alpha.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "create-nodejs-express-app",
"version": "1.7.25",
"version": "1.7.35-alpha.2",
"license": "MIT",
"dependencies": {
"@a2seven/yoo-checkout": "^1.1.4",
@@ -32,7 +32,7 @@
"jsonwebtoken": "^8.5.1",
"jspdf": "^2.5.1",
"moment": "^2.24.0",
"mongoose": "^5.7.7",
"mongoose": "^8.5.2",
"morgan": "^1.9.1",
"nodemailer": "^6.3.1",
"nunjucks": "^3.2.4",
@@ -54,14 +54,13 @@
"@types/express": "^4.17.21",
"@types/node": "^20.11.26",
"coveralls": "^3.0.7",
"eslint": "^7.0.0",
"eslint": "^7.32.0",
"eslint-config-airbnb-base": "^14.0.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-jest": "^24.0.1",
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-security": "^1.4.0",
"lint-staged": "^11.0.0",
"node-mocks-http": "^1.8.0",
"nodemon": "^2.0.0",
"prettier": "^2.0.5",
+14 -6
View File
@@ -1,6 +1,6 @@
{
"name": "coopback",
"version": "1.7.25",
"version": "1.7.35-alpha.2",
"description": "",
"private": true,
"bin": "bin/createNodejsApp.js",
@@ -8,6 +8,7 @@
"repository": "https://github.com/hagopj13/node-express-boilerplate.git",
"author": "Alex Ant <dacom.dark.sun@gmail.com>",
"license": "MIT",
"types": "src/types/index.ts",
"engines": {
"node": ">=12.0.0"
},
@@ -16,7 +17,7 @@
"deploy-production": "git checkout production && git merge testnet && git push origin production && git checkout main",
"start": "ts-node src/index.ts",
"dev": "concurrently -n 'CONTROLLER' -c 'bgCyan.black' \"nodemon --watch src --ext ts,js,env --exec 'ts-node' src/index.ts\"",
"test": "jest -i --colors --verbose --detectOpenHandles",
"test": "jest -i --colors --testTimeout=120000",
"test:watch": "jest -i --watchAll",
"coverage": "jest -i --coverage",
"coverage:coveralls": "jest -i --coverage --coverageReporters=text-lcov | coveralls",
@@ -28,9 +29,11 @@
"docker:dev": "docker-compose -f docker-compose.yml -f docker-compose.dev.yml up",
"docker:test": "docker-compose -f docker-compose.yml -f docker-compose.test.yml up",
"types": "ts-node scripts/types.ts",
"init": "ts-node scripts/init.ts",
"swagger": "ts-node scripts/swagger.ts",
"typecheck": "tsc --noEmit",
"swagger-generate": "swagger-ui-watcher ./src/docs/swagger.json"
"docs-watch": "swagger-ui-watcher ./src/docs/swagger.json",
"docs": "ts-node scripts/swagger.ts && redoc-cli bundle ./src/docs/swagger.json -o ./docs/index.html"
},
"keywords": [
"node",
@@ -86,7 +89,7 @@
"jsonwebtoken": "^8.5.1",
"jspdf": "^2.5.1",
"moment": "^2.24.0",
"mongoose": "^5.7.7",
"mongoose": "^8.5.2",
"morgan": "^1.9.1",
"nodemailer": "^6.3.1",
"nunjucks": "^3.2.4",
@@ -94,6 +97,7 @@
"passport-jwt": "^4.0.0",
"pdf-lib": "^1.17.1",
"pm2": "^5.1.0",
"socket.io-client": "^4.7.5",
"swagger-jsdoc": "^6.0.8",
"swagger-ui-express": "^4.1.6",
"ts-jest": "^29.1.3",
@@ -104,18 +108,22 @@
"xss-clean": "^0.1.1"
},
"devDependencies": {
"@antfu/eslint-config": "^2.24.1",
"@redocly/cli": "^1.18.0",
"@types/express": "^4.17.21",
"@types/faker": "^6.6.9",
"@types/node": "^20.11.26",
"@typescript-eslint/eslint-plugin": "^5.10.0",
"@typescript-eslint/parser": "^8.0.0",
"concurrently": "^8.2.2",
"coveralls": "^3.0.7",
"eslint": "^7.0.0",
"eslint": "^7.32.0",
"eslint-config-airbnb-base": "^14.0.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-jest": "^24.0.1",
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-security": "^1.4.0",
"lint-staged": "^11.0.0",
"node-mocks-http": "^1.8.0",
"nodemon": "^2.0.0",
"prettier": "^2.0.5",
@@ -1,13 +1,14 @@
import config from '../src/config/config';
import logger from '../src/config/logger';
import { User } from '../src/models';
import { tokenService } from '../src/services';
import userService from '../src/services/user.service';
import { userService } from '../src/services';
import mongoose from 'mongoose';
const args = process.argv.slice(2);
if (args.length < 1) {
console.error('Ошибка: Необходимо указать имя пользователя');
logger.error('Ошибка: Необходимо указать имя пользователя');
process.exit(1);
}
@@ -16,12 +17,11 @@ const [username] = args;
async function createServiceUser(username: string) {
try {
await mongoose.connect(config.mongoose.url, config.mongoose.options);
const user = await userService.createServiceUser(username);
const token = await tokenService.generateServiceAccessToken(user);
console.log('token:', token.access.token);
} catch (e: any) {
console.log('Ошибка: ', e.message);
logger.error('Ошибка: ', e.message);
}
process.exit(0);
+1 -1
View File
@@ -17,7 +17,7 @@ async function deleteUser(username: string) {
try {
await mongoose.connect(config.mongoose.url, config.mongoose.options);
await userService.deleteUserById(username);
await userService.deleteUserByUsername(username);
console.log('Пользователь удалён: ', username);
} catch (e: any) {
+95
View File
@@ -0,0 +1,95 @@
import config from '../src/config/config';
import { User } from '../src/models';
import { tokenService } from '../src/services';
import { userService } from '../src/services';
import mongoose from 'mongoose';
import { connectGenerator } from '../src/services/document.service';
import crypto from 'crypto';
import bcryptjs from 'bcryptjs';
const { compare, hash } = bcryptjs;
async function init() {
try {
await connectGenerator();
await mongoose.connect(config.mongoose.url, config.mongoose.options);
const wif = '5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3';
await userService.createUser({
username: 'ant',
email: 'dacom.dark.sun@gmail.com',
public_key: 'EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV',
role: 'user',
type: 'individual',
individual_data: {
first_name: 'Иван',
last_name: 'Иванов',
middle_name: 'Иванович',
birthdate: '2000-01-01',
phone: '+1234567890',
email: 'ivanov.ivan@example.com',
full_address: 'Переулок Иванов д. 1',
},
});
const user = await userService.getUserByUsername('ant');
user.status = 'active';
user.is_registered = true;
await user.save();
const voskhod = await userService.createUser({
username: 'voskhod',
email: 'chairman.voskhod@gmail.com',
public_key: 'EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV',
role: 'user',
type: 'organization',
organization_data: {
is_cooperative: true,
type: 'coop',
short_name: '"ПК ТЕСТ-Восход"',
full_name: 'Потребительский Кооператив "ТЕСТ-ВОСХОД"',
represented_by: {
first_name: 'Иван',
last_name: 'Иванов',
middle_name: 'Иванович',
position: 'Председатель',
based_on: 'Решения общего собрания №1',
},
country: 'Russia',
city: 'Москва',
full_address: 'Переулок Правды, дом 1',
email: 'chairman.voskhod@gmail.com',
phone: '+77077770707',
details: {
inn: '1234567890',
ogrn: '1234567890123',
},
bank_account: {
account_number: '40817810099910004312',
currency: 'RUB',
card_number: '1234567890123456',
bank_name: 'Sberbank',
details: {
bik: '123456789',
corr: '30101810400000000225',
kpp: '123456789',
},
},
},
});
const coop = await userService.getUserByUsername('voskhod');
coop.status = 'active';
coop.is_registered = true;
await coop.save();
console.log('ok');
} catch (e: any) {
console.log('Ошибка: ', e);
}
process.exit(0);
}
init();
@@ -0,0 +1,43 @@
import config from '../../src/config/config';
import { User } from '../../src/models';
import { tokenService } from '../../src/services';
import { userService } from '../../src/services';
import mongoose from 'mongoose';
import { connectGenerator } from '../../src/services/document.service';
import crypto from 'crypto';
import bcryptjs from 'bcryptjs';
const { compare, hash } = bcryptjs;
async function init() {
try {
await connectGenerator();
await mongoose.connect(config.mongoose.url, config.mongoose.options);
const orgs_collection = mongoose.connection.collection('OrgData');
const bankData_collection = mongoose.connection.collection('PaymentData');
const orgs = await orgs_collection.find().toArray();
for (const org of orgs) {
await bankData_collection.insertOne({
_created_at: org._created_at,
username: org.username,
method_id: 1,
user_type: 'organization',
method_type: 'bank_transfer',
is_default: true,
data: org.bank_account,
deleted: false,
block_num: org.block_num,
});
}
} catch (e: any) {
console.log('Ошибка: ', e);
}
process.exit(0);
}
init();
+4 -4
View File
@@ -3,12 +3,12 @@ import crypto from 'crypto';
const { compare, hash } = bcryptjs;
async function generate() {
const wif = '';
const wif = '5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3';
const hash_from_wif = await crypto.createHash('sha256').update(wif).digest('hex');
const password = await hash(hash_from_wif, 8)
console.log(password)
console.log('hash_from_wif: ', hash_from_wif);
const password = await hash(hash_from_wif, 8);
console.log(password);
}
generate();
+1 -1
View File
@@ -7,7 +7,7 @@ async function types(): Promise<void> {
// Configure your settings here
const result = await convertFromDirectory({
schemaDirectory: './src/validations',
typeOutputDirectory: './src/types',
typeOutputDirectory: './src/types/auto-generated',
debug: true,
});
+6 -8
View File
@@ -14,15 +14,13 @@ import routes from './routes/v1/index';
import { errorConverter, errorHandler } from './middlewares/error';
import ApiError from './utils/ApiError';
import { connectGenerator } from './services/data.service';
// import { connectGenerator } from './services/data.service';
// Подключите генератор
connectGenerator()
.then(() => {
console.log('Generator connected');
})
.catch((error) => {
console.error('Failed to connect generator:', error);
});
// connectGenerator()
// .then(() => {})
// .catch((error) => {
// console.error('Failed to connect generator:', error);
// });
const app = express();
+16 -8
View File
@@ -1,17 +1,15 @@
import dotenv from 'dotenv';
import Joi from 'joi';
import path from 'path';
// import { fileURLToPath } from 'url';
// import { dirname, join } from 'path';
// const __filename = fileURLToPath(import.meta.url);
// const __dirname = dirname(__filename);
dotenv.config({ path: path.join(__dirname, '../../.env') });
const envVarsSchema = Joi.object()
.keys({
NODE_ENV: Joi.string().valid('production', 'development', 'test').required(),
BASE_URL: Joi.string().required(),
SERVICE_USERNAME: Joi.string().required(),
SERVICE_WIF: Joi.string().required(),
PORT: Joi.number().default(3000),
MONGODB_URL: Joi.string().required().description('Mongo DB url'),
JWT_SECRET: Joi.string().required().description('JWT secret key'),
@@ -23,11 +21,16 @@ const envVarsSchema = Joi.object()
JWT_VERIFY_EMAIL_EXPIRATION_MINUTES: Joi.number()
.default(10)
.description('minutes after which verify email token expires'),
JWT_INVITE_EXPIRATION_MINUTES: Joi.number().default(3600).description('minutes after invite token expires'),
SMTP_HOST: Joi.string().description('server that will send the emails'),
SMTP_PORT: Joi.number().description('port to connect to the email server'),
SMTP_USERNAME: Joi.string().description('username for email server'),
SMTP_PASSWORD: Joi.string().description('password for email server'),
EMAIL_FROM: Joi.string().description('the from field in the emails sent by the app'),
COOPNAME: Joi.string().description('имя аккаунта кооператива'),
})
.unknown();
@@ -39,13 +42,16 @@ if (error) {
export default {
env: envVars.NODE_ENV,
base_url: envVars.BASE_URL,
port: envVars.PORT,
service_wif: envVars.SERVICE_WIF,
service_username: envVars.SERVICE_USERNAME,
mongoose: {
url: envVars.MONGODB_URL + (envVars.NODE_ENV === 'test' ? '-test' : ''),
options: {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
// useCreateIndex: true,
// useNewUrlParser: true,
// useUnifiedTopology: true,
},
},
jwt: {
@@ -54,6 +60,7 @@ export default {
refreshExpirationDays: envVars.JWT_REFRESH_EXPIRATION_DAYS,
resetPasswordExpirationMinutes: envVars.JWT_RESET_PASSWORD_EXPIRATION_MINUTES,
verifyEmailExpirationMinutes: envVars.JWT_VERIFY_EMAIL_EXPIRATION_MINUTES,
inviteExpirationMinutes: envVars.JWT_INVITE_EXPIRATION_MINUTES,
},
email: {
smtp: {
@@ -66,4 +73,5 @@ export default {
},
from: envVars.EMAIL_FROM,
},
coopname: envVars.COOPNAME,
};
+2 -2
View File
@@ -1,5 +1,5 @@
import winston from 'winston'
import config from './config'
import winston from 'winston';
import config from './config';
const enumerateErrorFormat = winston.format((info) => {
if (info instanceof Error) {
+3 -4
View File
@@ -1,9 +1,8 @@
import {Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt'
import config from './config'
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
import config from './config';
import { tokenTypes } from './tokens';
import { User } from '../models';
const jwtOptions = {
secretOrKey: config.jwt.secret,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
@@ -14,7 +13,7 @@ const jwtVerify = async (payload, done) => {
if (payload.type !== tokenTypes.ACCESS) {
throw new Error('Invalid token type');
}
const user = await User.findOne({_id: payload.sub});
const user = await User.findOne({ _id: payload.sub });
if (!user) {
return done(null, false);
}
+3 -3
View File
@@ -1,8 +1,8 @@
const allRoles = {
user: [''],
service: ['sendNotification'],
admin: ['getUsers', 'manageUsers', 'loadAgenda', 'loadStaff', 'loadMembers', 'getDocuments'],
chairman: ['getUsers', 'manageUsers', 'loadAgenda', 'loadStaff', 'loadMembers', 'getDocuments'],
service: ['addUser', 'sendNotification', 'install'],
chairman: ['addUser', 'getUsers', 'manageUsers', 'loadAgenda', 'loadStaff', 'getDocuments', 'loadInfo'],
member: ['getUsers', 'manageUsers', 'loadAgenda', 'loadStaff', 'getDocuments', 'loadInfo'],
};
export const roles = Object.keys(allRoles);
+1
View File
@@ -3,4 +3,5 @@ export const tokenTypes = {
REFRESH: 'refresh',
RESET_PASSWORD: 'resetPassword',
VERIFY_EMAIL: 'verifyEmail',
INVITE: 'invite',
};
@@ -1,16 +1,15 @@
import httpStatus from 'http-status';
import catchAsync from '../utils/catchAsync';
import { authService, userService, tokenService, emailService, blockchainService } from '../services';
import { authService, tokenService, emailService } from '../services';
import { RForgotKey, RRefreshTokens, RResetKey, RVerifyEmail } from '../types';
const { CREATED, NO_CONTENT } = httpStatus;
const { NO_CONTENT } = httpStatus;
export const login = catchAsync(async (req, res) => {
const { username, password } = req.body;
const user = await authService.loginUserWithUsernameAndPassword(username, password);
const { now, signature, email } = req.body;
if (user.is_registered === false)
throw new Error('Регистрация не была завершена. Пожалуйста, подождите решения совета или начните с начала. ')
const user = await authService.loginUserWithSignature(email, now, signature);
const tokens = await tokenService.generateAuthTokens(user);
res.send({ user, tokens });
@@ -21,19 +20,19 @@ export const logout = catchAsync(async (req, res) => {
res.status(NO_CONTENT).send();
});
export const refreshTokens = catchAsync(async (req, res) => {
const tokens = await authService.refreshAuth(req.body.refreshToken);
res.send({ ...tokens });
export const refreshTokens = catchAsync(async (req: RRefreshTokens, res: any) => {
const tokens = await authService.refreshAuth(req.body);
res.send(tokens);
});
export const forgotPassword = catchAsync(async (req, res) => {
const resetPasswordToken = await tokenService.generateResetPasswordToken(req.body.email);
await emailService.sendResetPasswordEmail(req.body.email, resetPasswordToken);
export const lostKey = catchAsync(async (req: RForgotKey, res) => {
const resetKeyToken = await tokenService.generateResetKeyToken(req.body.email);
await emailService.sendResetKeyEmail(req.body.email, resetKeyToken);
res.status(NO_CONTENT).send();
});
export const resetPassword = catchAsync(async (req, res) => {
await authService.resetPassword(req.query.token, req.body.password);
export const resetKey = catchAsync(async (req: RResetKey, res) => {
await authService.resetKey(req.body.token, req.body.public_key);
res.status(NO_CONTENT).send();
});
@@ -43,7 +42,7 @@ export const sendVerificationEmail = catchAsync(async (req, res) => {
res.status(NO_CONTENT).send();
});
export const verifyEmail = catchAsync(async (req, res) => {
export const verifyEmail = catchAsync(async (req: RVerifyEmail, res) => {
await authService.verifyEmail(req.query.token);
res.status(NO_CONTENT).send();
});
@@ -1,60 +1,35 @@
import catchAsync from '../utils/catchAsync';
import { coopService, dataService } from '../services';
import { coopService, documentService } from '../services';
import { Cooperative } from 'cooptypes';
import { generator } from '../services/data.service';
import { Request, Response } from 'express';
export const loadInfo = catchAsync(async (req, res) => {
const cooperative: Cooperative.Model.ICooperativeData | null = await generator.constructCooperative(
String(process.env.COOPNAME)
);
if (!cooperative) throw new Error('Кооператив не найден');
const announce = cooperative?.announce
? JSON.parse(cooperative.announce)
: { phone: cooperative?.phone, email: cooperative?.email };
const result = {
full_name: cooperative?.full_name,
full_address: cooperative?.full_address,
details: cooperative?.details,
phone: announce.phone,
email: announce.email,
description: cooperative?.description,
chairman: {
first_name: cooperative?.chairman.first_name,
last_name: cooperative?.chairman.last_name,
middle_name: cooperative?.chairman.middle_name,
},
};
res.send(result);
export const loadInfo = catchAsync(async (req: Request, res: Response) => {
const cooperative = await coopService.loadInfo(String(process.env.COOPNAME));
res.send(cooperative);
});
export const loadAgenda = catchAsync(async (req, res) => {
const { coopname } = req.query;
const agenda = await coopService.loadAgenda(coopname);
export const loadContacts = catchAsync(async (req: Request, res: Response) => {
const contacts = await coopService.loadContacts(String(process.env.COOPNAME));
const complexAgenda: Cooperative.Documents.IComplexAgenda[] = [];
res.send(contacts);
});
export const loadAgenda = catchAsync(async (req: Request, res: Response) => {
const { coopname } = req.query;
const agenda = await coopService.loadAgenda(coopname as string);
const complexAgenda: Cooperative.Document.IComplexAgenda[] = [];
for (const { action, table } of agenda) {
const documents = await dataService.buildComplexDocument(action);
const documents = await documentService.buildComplexDocument(action);
if (documents.statement.document) complexAgenda.push({ documents, action, table });
}
res.send(complexAgenda);
});
export const loadStaff = catchAsync(async (req, res) => {
export const loadStaff = catchAsync(async (req, res: Response) => {
const { coopname } = req.query;
const staff = await coopService.loadStaff(coopname);
res.send(staff);
});
export const loadMembers = catchAsync(async (req, res) => {
const { coopname } = req.query;
const members = await coopService.loadMembers(coopname);
res.send(members);
});
@@ -1,22 +0,0 @@
import catchAsync from '../utils/catchAsync';
import { dataService } from '../services/index';
import type { IGetDocuments, RGenerate, RGetDocuments } from '../types';
import httpStatus from 'http-status';
import pick from '../utils/pick';
import { IGetResponse } from '../types/common';
export const generateDocument = catchAsync(async (req: RGenerate, res) => {
const document = await dataService.generateDocument(req.body);
res.status(httpStatus.CREATED).send(document);
});
export const getDocuments = catchAsync(async (req: RGetDocuments, res) => {
let filter = req.query?.filter
let limit = req.query?.limit as number
let page = req.query?.page as number
const documents: IGetResponse = await dataService.queryDocuments(filter, page, limit);
res.status(httpStatus.OK).send(documents);
});
@@ -0,0 +1,21 @@
import catchAsync from '../utils/catchAsync';
import { documentService } from '../services/index';
import type { RGenerate, RGetDocuments } from '../types';
import httpStatus from 'http-status';
export const generateDocument = catchAsync(async (req: RGenerate, res) => {
const document = await documentService.generateDocument(req.body);
res.status(httpStatus.CREATED).send(document);
});
export const getDocuments = catchAsync(async (req: RGetDocuments, res) => {
const filter = req.query?.filter;
const limit = req.query?.limit as number;
const page = req.query?.page as number;
const documents = await documentService.queryDocuments(filter, page, limit);
res.status(httpStatus.OK).send(documents);
});
+4 -2
View File
@@ -1,6 +1,8 @@
export * as authController from './auth.controller';
export * as userController from './user.controller';
export * as dataController from './data.controller';
export * as orderController from './order.controller';
export * as documentController from './document.controller';
export * as paymentController from './payment.controller';
export * as coopController from './coop.controller';
export * as notifyController from './notify.controller';
export * as monoController from './mono.controller';
export * as participantController from './participant.controller';
@@ -0,0 +1,25 @@
import httpStatus from 'http-status';
import { getMonoStatus } from '../services/mono.service';
import { getBlockchainInfo } from '../services/blockchain.service';
import { IHealthResponse, IInstall, RInstall } from '../types';
import { Request, Response } from 'express';
import catchAsync from '../utils/catchAsync';
import { monoService } from '../services';
export const install = catchAsync(async (req: RInstall, res: Response) => {
const { body } = req;
await monoService.install(body as IInstall);
res.status(httpStatus.OK).send();
});
export const getHealth = catchAsync(async (req: Request, res: Response) => {
const status = await getMonoStatus();
const blockchain = await getBlockchainInfo();
const result: IHealthResponse = {
status,
blockchain,
};
res.status(httpStatus.OK).send(result);
});
@@ -1,58 +0,0 @@
import http from 'http-status';
import catchAsync from '../utils/catchAsync';
import { orderService } from '../services';
import { ICreateDeposit, ICreateInitialPayment } from '../types';
import { Request, Response } from 'express';
import * as ip from 'ip';
// Список разрешенных IP-адресов
// const allowedIPs = [
// '185.71.76.0/27',
// '185.71.77.0/27',
// '77.75.153.0/25',
// '77.75.156.11',
// '77.75.156.35',
// '77.75.154.128/25',
// '2a02:5180::/32'
// ];
// if (process.env.NODE_ENV === 'development')
// allowedIPs.push('127.0.0.1')
export const catchIPN = catchAsync(async (req: Request, res: Response) => {
// const ipAddr = ((req.headers['x-real-ip'] as string) || req.ip || '').replace(/^::ffff:/, '');
// console.log("ip: ", ipAddr);
// const isAllowed = allowedIPs.some(allowedIP => {
// if (allowedIP.includes('/')) { // Если это диапазон
// return ip.cidrSubnet(allowedIP).contains(ipAddr);
// }
// return allowedIP === ipAddr; // Если это конкретный IP
// });
// if (!isAllowed) {
// console.log("попытка доступа с запрещенного IP: ", ipAddr)
// return res.status(http.FORBIDDEN).send('Доступ запрещен');
// }
// console.log("on catch ipn", req.body);
res.status(http.OK).send();
orderService.catchIPN(req.body);
});
export const createDeposit = catchAsync(async (req: any, res: Response) => {
const username = req.user.username
const result = await orderService.createDeposit(username, req.body as ICreateDeposit)
res.status(http.CREATED).send(result);
})
export const createInitialPayment = catchAsync(async (req: any, res: Response) => {
const username = req.user.username
const result = await orderService.createInitialOrder(username, req.body as ICreateInitialPayment)
res.status(http.CREATED).send(result);
})
@@ -0,0 +1,10 @@
import httpStatus from 'http-status';
import { participantService } from '../services';
import type { RJoinCooperative } from '../types';
import catchAsync from '../utils/catchAsync';
export const joinCooperative = catchAsync(async (req: RJoinCooperative, res) => {
await participantService.joinCooperative(req.body);
res.status(httpStatus.OK).send();
});
@@ -0,0 +1,113 @@
import http from 'http-status';
import catchAsync from '../utils/catchAsync';
import { paymentService } from '../services';
import {
ICreateDeposit,
ICreateInitialPayment,
RDeletePaymentMethod,
RGetListPaymentMethods,
RSavePaymentMethod,
} from '../types';
import { Request, Response } from 'express';
import * as ip from 'ip';
import { IGetResponse } from '../types/common';
import ApiError from '../utils/ApiError';
import httpStatus from 'http-status';
import { Cooperative } from 'cooptypes';
import { getUserByUsername } from '../services/user.service';
import { User } from '../models';
// Список разрешенных IP-адресов
// const allowedIPs = [
// '185.71.76.0/27',
// '185.71.77.0/27',
// '77.75.153.0/25',
// '77.75.156.11',
// '77.75.156.35',
// '77.75.154.128/25',
// '2a02:5180::/32'
// ];
// if (process.env.NODE_ENV === 'development')
// allowedIPs.push('127.0.0.1')
export const catchIPN = catchAsync(async (req: Request, res: Response) => {
// const ipAddr = ((req.headers['x-real-ip'] as string) || req.ip || '').replace(/^::ffff:/, '');
// console.log("ip: ", ipAddr);
// const isAllowed = allowedIPs.some(allowedIP => {
// if (allowedIP.includes('/')) { // Если это диапазон
// return ip.cidrSubnet(allowedIP).contains(ipAddr);
// }
// return allowedIP === ipAddr; // Если это конкретный IP
// });
// if (!isAllowed) {
// console.log("попытка доступа с запрещенного IP: ", ipAddr)
// return res.status(http.FORBIDDEN).send('Доступ запрещен');
// }
// console.log("on catch ipn", req.body);
res.status(http.OK).send();
paymentService.catchIPN(req.body);
});
export const createDeposit = catchAsync(async (req: any, res: Response) => {
const username = req.user.username;
const result = await paymentService.createDeposit(username, req.body as ICreateDeposit);
res.status(http.CREATED).send(result);
});
export const createInitialPayment = catchAsync(async (req: any, res: Response) => {
const username = req.user.username;
const result = await paymentService.createInitialOrder(username, req.body as ICreateInitialPayment);
res.status(http.CREATED).send(result);
});
export const listPaymentMethods = catchAsync(async (req: RGetListPaymentMethods, res) => {
const filter = req.params?.username ? { username: req.params.username } : {};
const methods: IGetResponse<any> = await paymentService.listPaymentMethods({ ...filter });
res.status(httpStatus.OK).send(methods);
});
export const addPaymentMethod = catchAsync(async (req: RSavePaymentMethod, res) => {
if (req.params?.username != req.body.username)
throw new ApiError(httpStatus.BAD_REQUEST, 'username в params и body должны совпадать');
const user = await getUserByUsername(req.body.username);
const method = req.body as any;
if (method.method_type === 'sbp' && !method.data.phone)
throw new ApiError(httpStatus.BAD_REQUEST, 'Не указан телефон для метода СБП');
if (method.method_type === 'bank_transfer' && !method.data.account_number)
throw new ApiError(httpStatus.BAD_REQUEST, 'Не верно указаны реквизиты для банковского платежа');
const paymentData: Cooperative.Payments.IPaymentData = {
username: req.body.username,
method_id: req.body.method_id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
user_type: user.type as any,
method_type: req.body.method_type,
is_default: false,
data: req.body.data,
};
await paymentService.savePaymentMethod(paymentData);
res.status(httpStatus.OK).send();
});
export const deletePaymentMethod = catchAsync(async (req: RDeletePaymentMethod, res) => {
await paymentService.deletePaymentMethod({
username: req.params?.username,
method_id: req.body.method_id,
});
res.status(httpStatus.OK).send();
});
@@ -1,11 +1,16 @@
import http, { CREATED } from 'http-status';
import http from 'http-status';
import ApiError from '../utils/ApiError';
import catchAsync from '../utils/catchAsync';
import { userService, blockchainService, tokenService, orderService } from '../services';
import { IJoinCooperative, RCreateUser, RJoinCooperative } from '../types';
import { userService, tokenService, emailService, blockchainService } from '../services';
import { IAddUser, ICreateUser, RCreateUser } from '../types';
import httpStatus from 'http-status';
import pick from '../utils/pick';
import { IGetResponse } from '../types/common';
import { IUser, userStatus } from '../models/user.model';
import { Request, Response } from 'express';
import { generateUsername } from '../../tests/utils/generateUsername';
import config from '../config/config';
import logger from '../config/logger';
/**
* Порядок регистрации:
@@ -18,9 +23,9 @@ import { IGetResponse } from '../types/common';
* 7. (joinCooperative) Пользователь подписывает заявление на вступление и вызывает метод joinCooperative, прикладывая подписанное заявление.
* 8. Система сохраняет подписанное заявление
* 9. (createInitialPayment) Пользователь получает ордер на оплату.
* 9. Пользователь оплачивает ордер.
* 10. Система принимает оплату и регистрирует аккаунт в блокчейне.
* 11. (trx confirmpay) Пользователь подписывает велком-письмо с подтверждением собственноручности оплаты (транзакция в блокчейне для активации)
* 12. Регистрация продолжается ожиданием решения совета
*/
export const createUser = catchAsync(async (req: RCreateUser, res) => {
const user = await userService.createUser(req.body);
@@ -29,33 +34,63 @@ export const createUser = catchAsync(async (req: RCreateUser, res) => {
res.status(http.CREATED).send({ user, tokens });
});
export const joinCooperative = catchAsync(async (req: RJoinCooperative, res) => {
await userService.joinCooperative(req.body);
export const addUser = catchAsync(async (req: Request, res: Response) => {
const body: IAddUser = req.body;
res.status(httpStatus.OK).send();
const newUser: ICreateUser = {
...body,
public_key: '',
role: 'user',
username: generateUsername(),
};
const user = await userService.createUser(newUser);
user.status = userStatus['4_Registered'];
user.is_registered = true;
await user.save();
try {
await blockchainService.addUser({
...body,
...newUser,
registrator: config.service_username,
referer: body.referer ? body.referer : '',
coopname: config.coopname,
meta: '',
});
const token = await tokenService.generateInviteToken(user.email);
await emailService.sendInviteEmail(req.body.email, token);
} catch (e: any) {
logger.warn('error on add user: ', e);
await userService.deleteUserByUsername(newUser.username);
throw new ApiError(httpStatus.BAD_GATEWAY, e.message);
}
res.status(httpStatus.CREATED).send({ user });
});
export const getUsers = catchAsync(async (req, res) => {
const filter = pick(req.query, ['username', 'role']);
const options = pick(req.query, ['sortBy', 'limit', 'page']);
filter.role = 'user';
const users = await userService.queryUsers(filter, options);
const result = {} as IGetResponse<IUser>;
const result = {} as IGetResponse; //
//TODO wrong format answer
const data = [] as any;
for await (let user of users.results) {
for await (const user of users.results) {
const json = user.toJSON();
json.private_data = (await user.getPrivateData()) || {};
data.push(json);
if (user.type != 'service') {
json.private_data = await user.getPrivateData();
data.push(json);
}
}
result.results = data;
result.limit = users.limit;
result.page = users.page;
result.totalPages = users.totalPages;
result.totalResults = users.totalResults;
res.send(result);
});
@@ -67,17 +102,22 @@ export const getUser = catchAsync(async (req, res) => {
}
const json = user.toJSON();
json.private_data = await user.getPrivateData();
if (user.type != 'service') {
json.private_data = await user.getPrivateData();
}
res.send(json);
});
export const updateUser = catchAsync(async (req, res) => {
const user = await userService.updateUserById(req.params.username, req.body);
if (req.user.role !== 'member' && req.user.role !== 'chairman')
throw new ApiError(httpStatus.FORBIDDEN, 'Только председатель или член совета может обновить данные пользователя');
const user = await userService.updateUserByUsername(req.params.username, req.body);
res.send(user);
});
export const deleteUser = catchAsync(async (req, res) => {
await userService.deleteUserById(req.params.username);
await userService.deleteUserByUsername(req.params.username);
res.status(http.NO_CONTENT).send();
});
@@ -0,0 +1,38 @@
import { io, Socket } from 'socket.io-client';
import { IAction } from '../types/common';
import { SovietContract } from 'cooptypes';
import { wsService } from '../services';
let clientSocket: Socket | undefined;
// Инициация подключения
export const initSocketConnection = (serverUrl: string): void => {
clientSocket = io(serverUrl);
clientSocket.on('connect', () => {
console.log('Успешное подключение к серверу оповещений.');
});
clientSocket.on('event', (event: IAction) => {
processEvent(event);
});
clientSocket.on('connect_error', (error: Error) => {
console.error('Ошибка подключения к серверу оповещений:');
});
};
// Закрытие подключения
export const closeSocketConnection = (): void => {
if (clientSocket) {
clientSocket.disconnect();
console.log('Client disconnected from server');
clientSocket = undefined;
}
};
async function processEvent(event: IAction) {
if (event.receiver === SovietContract.contractName.production && event.name === 'updateboard') {
wsService.updateBoard(event.data);
}
}
+13 -6
View File
@@ -1,21 +1,28 @@
export * from './types';
import mongoose from 'mongoose';
import app from './app';
import config from './config/config';
import logger from './config/logger';
import { updateAuth } from './services/auth.service';
import { connectGenerator } from './services/data.service';
import { connectGenerator } from './services/document.service';
import { initSocketConnection } from './controllers/ws.controller';
import { monoService } from './services';
const SERVER_URL: string = process.env.SOCKET_SERVER || 'http://localhost:2222';
let server: any;
mongoose.connect(config.mongoose.url, config.mongoose.options).then(async () => {
mongoose.connect(config.mongoose.url).then(async () => {
logger.info('Connected to MongoDB');
// logger.info('Update soviet auth');
// updateAuth();
// setInterval(() => updateAuth(), 60 * 1000);
await monoService.init();
// подключаемся к хранилищу приватных данных
await connectGenerator();
// подключаемся к ws-серверу
await initSocketConnection(SERVER_URL);
server = app.listen(config.port, () => {
logger.info(`Listening to port ${config.port}`);
});
+4 -5
View File
@@ -15,11 +15,10 @@ const verifyCallback = (req, resolve, reject, requiredRights) => async (err, use
const userRights = roleRights.get(user.role);
const hasRequiredRights = requiredRights.every((requiredRight) => userRights?.includes(requiredRight));
// if (process.env.IS_PRODUCTION) {
if (!hasRequiredRights && req.params.username !== user.username) {
return reject(new ApiError(FORBIDDEN, 'Недостаточно прав доступа'));
}
// }
if (!hasRequiredRights && req.params.username !== user.username) {
//
return reject(new ApiError(FORBIDDEN, 'Недостаточно прав доступа'));
}
}
resolve();
+5 -6
View File
@@ -10,12 +10,12 @@ export const errorConverter = (err, req, res, next) => {
if (!(error instanceof ApiError)) {
if (error instanceof RpcError) {
const message = error.json.error.details[0].message.replace('assertion failure with message: ', ''); // Получаем первую строку ошибки
const statusCode = error.json.code
const subCode = error.json.error.code
const statusCode = error.json.code;
const subCode = error.json.error.code;
error = new ApiError(statusCode, message, true, undefined, subCode);
} else {
const statusCode = error.statusCode || (error instanceof mongoose.Error ? httpStatus.BAD_REQUEST : httpStatus.INTERNAL_SERVER_ERROR);
const statusCode =
error.statusCode || (error instanceof mongoose.Error ? httpStatus.BAD_REQUEST : httpStatus.INTERNAL_SERVER_ERROR);
const message = error.message || httpStatus[statusCode];
error = new ApiError(statusCode, message, false, err.stack);
}
@@ -24,8 +24,7 @@ export const errorConverter = (err, req, res, next) => {
};
// eslint-disable-next-line no-unused-vars
export const errorHandler = (err, req, res, next) => {
export const errorHandler = (err, req, res, next?) => {
let { statusCode, message } = err;
if (config.env === 'production' && !err.isOperational) {
statusCode = httpStatus.INTERNAL_SERVER_ERROR;
+1
View File
@@ -1,3 +1,4 @@
export { default as Token } from './token.model';
export { default as User } from './user.model';
export { default as Order } from './order.model';
export { default as Mono } from './mono.model';
@@ -0,0 +1,26 @@
import mongoose, { Schema } from 'mongoose';
import { paginate, toJSON } from './plugins';
import { IHealthStatus } from '../types';
export interface IMono {
coopname: string;
status: IHealthStatus;
}
const Status = {
Install: 'install',
Active: 'active',
Maintenance: 'maintenance',
};
const MonoSchema = new Schema<IMono>({
coopname: { type: String, required: true },
status: { type: String, required: true, enum: Object.values(Status) },
});
MonoSchema.plugin(toJSON);
MonoSchema.plugin(paginate);
const MonoModel = mongoose.model<IMono>('Mono', MonoSchema);
export default MonoModel;
+52 -50
View File
@@ -5,9 +5,9 @@ interface IOrder extends Document {
creator: string;
type: string;
data: {
username: string
provider: string
quantity: string
username: string;
provider: string;
quantity: string;
};
order_id?: number;
payed?: boolean;
@@ -16,59 +16,61 @@ interface IOrder extends Document {
expired_at?: Date;
}
const orderSchema = new Schema<IOrder>({
creator: {
type: String,
required: true,
},
type: {
type: String,
required: true,
},
data: {
provider: {
type: String,
required: true
},
username: {
const orderSchema = new Schema<IOrder>(
{
creator: {
type: String,
required: true,
},
quantity: {
type: {
type: String,
required: true
}
},
order_id: {
type: Number,
required: false,
},
payed: {
type: Boolean,
required: false,
default: false,
},
delivered: {
type: Boolean,
required: false,
default: false,
},
error: {
type: Object,
required: false,
},
expired_at: {
type: Date,
default: () => {
const now = new Date();
now.setDate(now.getDate() + 1); // Увеличиваем на одни сутки
return now;
required: true,
},
data: {
provider: {
type: String,
required: true,
},
username: {
type: String,
required: true,
},
quantity: {
type: String,
required: true,
},
},
order_id: {
type: Number,
required: false,
},
payed: {
type: Boolean,
required: false,
default: false,
},
delivered: {
type: Boolean,
required: false,
default: false,
},
error: {
type: Object,
required: false,
},
expired_at: {
type: Date,
default: () => {
const now = new Date();
now.setDate(now.getDate() + 1); // Увеличиваем на одни сутки
return now;
},
},
},
},
{
timestamps: true,
});
{
timestamps: true,
}
);
// add plugin that converts mongoose to json
orderSchema.plugin(toJSON);
@@ -28,7 +28,7 @@ const toJSON = (schema) => {
}
});
// ret.id = ret._id.toString();
ret.id = ret._id.toString();
delete ret._id;
delete ret.__v;
delete ret.createdAt;
@@ -0,0 +1,51 @@
import mongoose, { Schema } from 'mongoose';
import { paginate, toJSON } from './plugins';
export enum tempdocType {
JoinStatement = 'joinStatement',
WalletAgreement = 'walletAgreement',
SignatureAgreement = 'signatureAgreement',
PrivacyAgreement = 'privacyAgreement',
UserAgreement = 'userAgreement',
}
export interface ITempDocument {
username: string;
type: tempdocType;
document: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
}
const MonoSchema = new Schema<ITempDocument>({
username: { type: String, required: true },
type: { type: String, required: true, enum: ['joinStatement', 'walletAgreement'] },
document: {
public_key: {
type: String,
default: '',
},
signature: {
type: String,
default: '',
},
meta: {
type: Object,
default: {},
},
hash: {
type: String,
default: '',
},
},
});
MonoSchema.plugin(toJSON);
MonoSchema.plugin(paginate);
const TempDocument = mongoose.model<ITempDocument>('TempDocument', MonoSchema);
export default TempDocument;
@@ -25,7 +25,7 @@ const tokenSchema = new Schema<IToken>(
},
type: {
type: String,
enum: [tokenTypes.REFRESH, tokenTypes.RESET_PASSWORD, tokenTypes.VERIFY_EMAIL],
enum: [tokenTypes.REFRESH, tokenTypes.RESET_PASSWORD, tokenTypes.VERIFY_EMAIL, tokenTypes.INVITE],
required: true,
},
expires: {
@@ -39,6 +39,7 @@ const tokenSchema = new Schema<IToken>(
},
{
timestamps: true,
toJSON: { virtuals: true },
}
);
+51 -62
View File
@@ -1,32 +1,40 @@
import mongoose, { Document, Schema, model, Model } from 'mongoose';
import mongoose, { Schema, model, Model } from 'mongoose';
import validator from 'validator/index';
import bcryptjs from 'bcryptjs';
import { toJSON, paginate } from './plugins/index';
import { roles } from '../config/roles';
import { generator } from '../services/data.service';
import { generator } from '../services/document.service';
import { Cooperative } from 'cooptypes';
const { isEmail } = validator;
const { compare, hash } = bcryptjs;
export interface IUser extends Document {
export enum userStatus {
'1_Created' = 'created',
'2_Joined' = 'joined',
'3_Payed' = 'payed',
'4_Registered' = 'registered',
'5_Active' = 'active',
'10_Failed' = 'failed',
'200_Blocked' = 'blocked',
}
export interface IUser {
username: string;
status: 'created' | 'joined' | 'payed' | 'registered' | 'active' | 'failed' | 'blocked';
status: userStatus;
message: string;
is_registered: boolean;
type: 'individual' | 'entrepreneur' | 'organization';
has_account: boolean;
type: 'individual' | 'entrepreneur' | 'organization' | 'service';
public_key: string;
referer: string;
email: string;
password: string;
role: string;
is_email_verified: boolean;
statement: {
hash: string;
meta: any;
public_key: string;
signature: string;
};
// statement: {
// hash: string;
// meta: object;
// public_key: string;
// signature: string;
// };
private_data:
| Cooperative.Users.IIndividualData
| Cooperative.Users.IEntrepreneurData
@@ -35,7 +43,6 @@ export interface IUser extends Document {
getPrivateData(): Promise<
Cooperative.Users.IIndividualData | Cooperative.Users.IEntrepreneurData | Cooperative.Users.IOrganizationData | null
>;
isPasswordMatch(password: string): Promise<boolean>;
}
interface IUserModel extends Model<IUser> {
@@ -53,8 +60,8 @@ const userSchema = new Schema<IUser, IUserModel>(
},
status: {
type: String,
enum: ['created', 'joined', 'payed', 'registered', 'active', 'failed', 'blocked'],
default: 'created',
enum: Object.values(userStatus),
default: userStatus['1_Created'],
},
message: {
type: String,
@@ -71,7 +78,7 @@ const userSchema = new Schema<IUser, IUserModel>(
},
public_key: {
type: String,
required: true,
default: '',
},
referer: {
type: String,
@@ -79,7 +86,7 @@ const userSchema = new Schema<IUser, IUserModel>(
},
email: {
type: String,
required: true,
required: false,
unique: true,
trim: true,
lowercase: true,
@@ -89,18 +96,6 @@ const userSchema = new Schema<IUser, IUserModel>(
}
},
},
password: {
type: String,
required: true,
trim: true,
minlength: 8,
validate(value) {
if (!value.match(/\d/) || !value.match(/[a-zA-Z]/)) {
throw new Error('Password must contain at least one letter and one number');
}
},
private: true, // used by the toJSON plugin
},
role: {
type: String,
enum: roles,
@@ -114,26 +109,27 @@ const userSchema = new Schema<IUser, IUserModel>(
type: Boolean,
default: false,
},
statement: {
public_key: {
type: String,
default: '',
},
signature: {
type: String,
default: '',
},
meta: {
type: Object,
default: {},
},
hash: {
type: String,
default: '',
},
},
// statement: {
// public_key: {
// type: String,
// default: '',
// },
// signature: {
// type: String,
// default: '',
// },
// meta: {
// type: Object,
// default: {},
// },
// hash: {
// type: String,
// default: '',
// },
// },
},
{
minimize: false,
timestamps: true,
toJSON: { virtuals: true },
}
@@ -152,22 +148,15 @@ userSchema.statics.isEmailTaken = async function (email) {
userSchema.methods.getPrivateData = async function (): Promise<
Cooperative.Users.IIndividualData | Cooperative.Users.IEntrepreneurData | Cooperative.Users.IOrganizationData | null
> {
return await generator.get(this.type, { username: this.username });
};
const result = (await generator.get(this.type, { username: this.username })) as
| Cooperative.Users.IIndividualData
| Cooperative.Users.IEntrepreneurData
| Cooperative.Users.IOrganizationData
| null;
userSchema.methods.isPasswordMatch = async function (password) {
const user = this;
return compare(password, user.password);
return result;
};
userSchema.pre('save', async function (next) {
const user = this;
if (user.isModified('password')) {
user.password = await hash(user.password, 8);
}
next();
});
const User = model<IUser, IUserModel>('User', userSchema);
export default User;
@@ -7,13 +7,13 @@ import auth from '../../middlewares/auth';
const router = Router();
router.post('/login', validate(authValidation.login), authController.login);
router.post('/logout', validate(authValidation.logout), authController.logout);
router.post('/refresh-tokens', validate(authValidation.refreshTokens), authController.refreshTokens);
router.post('/forgot-password', validate(authValidation.forgotPassword), authController.forgotPassword);
router.post('/reset-password', validate(authValidation.resetPassword), authController.resetPassword);
router.post('/login', validate(authValidation.RLogin), authController.login);
router.post('/logout', validate(authValidation.RLogout), authController.logout);
router.post('/refresh-tokens', validate(authValidation.RRefreshTokens), authController.refreshTokens);
router.post('/lost-key', validate(authValidation.RForgotKey), authController.lostKey);
router.post('/reset-key', validate(authValidation.RResetKey), authController.resetKey);
router.post('/send-verification-email', auth(), authController.sendVerificationEmail);
router.post('/verify-email', validate(authValidation.verifyEmail), authController.verifyEmail);
router.post('/verify-email', validate(authValidation.RVerifyEmail), authController.verifyEmail);
export default router;
@@ -2,15 +2,14 @@ import { Router } from 'express';
import auth from '../../middlewares/auth';
import validate from '../../middlewares/validate';
import * as coopValidation from '../../validations/coop.validation';
// import { loadAgenda, loadStaff, loadMembers } from '../../validations/coop.validation';
import * as coopController from '../../controllers/coop.controller';
const router = Router();
router.route('/agenda').get(auth('loadAgenda'), validate(coopValidation.loadAgenda), coopController.loadAgenda);
router.route('/staff').get(auth('loadStaff'), validate(coopValidation.loadStaff), coopController.loadStaff);
router.route('/members').get(auth('loadMembers'), validate(coopValidation.loadMembers), coopController.loadMembers);
router.route('/info').get(auth('loadInfo'), coopController.loadInfo);
router.route('/info').get(coopController.loadInfo);
router.route('/contacts').get(coopController.loadContacts);
export default router;
@@ -1,32 +0,0 @@
import express from "express"
import auth from "../../middlewares/auth"
import validate from "../../middlewares/validate"
import * as dataValidation from "../../validations/data.validation"
import { dataController } from "../../controllers"
const router = express.Router()
router
.route("/generate")
.post(
auth(),
validate(dataValidation.RGenerate),
dataController.generateDocument
)
router
.route("/get-documents")
.get(
auth("getDocuments"),
validate(dataValidation.RGetDocuments),
dataController.getDocuments
)
router
.route("/get-my-documents")
.get(
auth(),
validate(dataValidation.RGetDocuments),
dataController.getDocuments
)
export default router
@@ -0,0 +1,17 @@
import express from 'express';
import auth from '../../middlewares/auth';
import validate from '../../middlewares/validate';
import * as documentValidation from '../../validations/document.validation';
import { documentController } from '../../controllers';
const router = express.Router();
router.route('/generate').post(auth(), validate(documentValidation.RGenerate), documentController.generateDocument);
router
.route('/get-documents')
.get(auth('getDocuments'), validate(documentValidation.RGetDocuments), documentController.getDocuments);
router.route('/get-my-documents').get(auth(), validate(documentValidation.RGetDocuments), documentController.getDocuments);
export default router;
+15 -5
View File
@@ -2,16 +2,22 @@ import { Router } from 'express';
import authRoute from './auth.route';
import userRoute from './user.route';
import docsRoute from './docs.route';
import orderRoute from './order.route';
import paymentRoute from './payment.route';
import coopRoute from './coop.route';
import dataRoute from './data.route';
import monoRoute from './mono.route';
import dataRoute from './document.route';
import notifyRoute from './notify.route';
import participantsRoute from './participant.route';
import config from '../../config/config';
const router = Router();
const defaultRoutes = [
{
path: '/system',
route: monoRoute,
},
{
path: '/auth',
route: authRoute,
@@ -21,12 +27,16 @@ const defaultRoutes = [
route: userRoute,
},
{
path: '/data',
path: '/participants',
route: participantsRoute,
},
{
path: '/documents',
route: dataRoute,
},
{
path: '/orders',
route: orderRoute,
path: '/payments',
route: paymentRoute,
},
{
path: '/coop',
@@ -0,0 +1,12 @@
import { Router } from 'express';
import { monoController } from '../../controllers';
import auth from '../../middlewares/auth';
import validate from '../../middlewares/validate';
import { monoValidation } from '../../validations';
const router = Router();
router.route('/install').post(auth('install'), validate(monoValidation.RInstall), monoController.install);
router.route('/health').get(monoController.getHealth);
export default router;
@@ -0,0 +1,13 @@
import { Router } from 'express';
import auth from '../../middlewares/auth';
import validate from '../../middlewares/validate';
import { participantValidation } from '../../validations';
import { participantController } from '../../controllers';
const router = Router();
router
.route('/join-cooperative')
.post(auth(), validate(participantValidation.RJoinCooperative), participantController.joinCooperative);
export default router;
@@ -1,7 +1,7 @@
import { Router } from 'express';
import { orderController } from '../../controllers';
import { paymentController } from '../../controllers';
import validate from '../../middlewares/validate';
import * as orderValidation from '../../validations/order.validation';
import * as paymentValidation from '../../validations/payment.validation';
import auth from '../../middlewares/auth';
import { Request, Response } from 'express';
@@ -41,7 +41,7 @@ const router = Router();
* 200:
* description: Успешное выполнение запроса.
*/
router.route('/ipn').post(validate(orderValidation.RRecieveIPN), orderController.catchIPN);
router.route('/ipn').post(validate(paymentValidation.RRecieveIPN), paymentController.catchIPN);
/**
* @swagger
@@ -66,7 +66,9 @@ router.route('/ipn').post(validate(orderValidation.RRecieveIPN), orderController
* schema:
* $ref: '#/components/schemas/ICreatedPayment'
*/
router.route('/initial').post(auth(), validate(orderValidation.RCreateInitialPayment), orderController.createInitialPayment);
router
.route('/initial')
.post(auth(), validate(paymentValidation.RCreateInitialPayment), paymentController.createInitialPayment);
/**
* @swagger
@@ -91,6 +93,18 @@ router.route('/initial').post(auth(), validate(orderValidation.RCreateInitialPay
* schema:
* $ref: '#/components/schemas/ICreatedPayment'
*/
router.route('/deposit').post(auth(), validate(orderValidation.RCreateDeposit), orderController.createDeposit);
router.route('/deposit').post(auth(), validate(paymentValidation.RCreateDeposit), paymentController.createDeposit);
router
.route('/methods/:username?')
.get(auth('getUsers'), validate(paymentValidation.RGetListPaymentMethods), paymentController.listPaymentMethods);
router
.route('/methods/:username/add')
.post(auth('manageUsers'), validate(paymentValidation.RSavePaymentMethod), paymentController.addPaymentMethod);
router
.route('/methods/:username/delete')
.post(auth('manageUsers'), validate(paymentValidation.RDeletePaymentMethod), paymentController.deletePaymentMethod);
export default router;
@@ -11,9 +11,7 @@ router
.post(validate(userValidation.RCreateUser), userController.createUser)
.get(auth('getUsers'), validate(userValidation.RGetUsers), userController.getUsers);
router
.route('/join-cooperative')
.post(validate(userValidation.RJoinCooperative), userController.joinCooperative)
router.route('/add').post(auth('addUser'), validate(userValidation.RAddUser), userController.addUser);
router
.route('/:username')
@@ -1,67 +1,50 @@
import httpStatus from 'http-status';
import * as tokenService from './token.service';
import userService from './user.service';
import { getSoviet } from './blockchain.service';
import * as userService from './user.service';
import Token from '../models/token.model';
import ApiError from '../utils/ApiError';
import { tokenTypes } from '../config/tokens';
import { IRefreshTokens } from '../types';
import { getUserByEmail } from './user.service';
import { Bytes, Checksum256, Signature } from '@wharfkit/antelope';
import { getBlockchainAccount, getBlockchainInfo, hasActiveKey } from '../services/blockchain.service';
import config from '../config/config';
import { blockchainService } from '.';
export const updateAuth = async () => {
try {
const board = await getSoviet(process.env.COOPNAME);
// TODO снимать права с тех, кто уже не в совете
// eslint-disable-next-line no-restricted-syntax
for (const member of board.members) {
// eslint-disable-next-line no-await-in-loop
const user = await userService.getUserByUsername(member.username);
if (member.position === 'chairman' && !user) {
// eslint-disable-next-line no-await-in-loop
// await userService.createUser({
// username: member.username,
// public_key: '-',
// email: process.env.CHAIRMAN_EMAIL ,
// password: process.env.CHAIRMAN_PASSWORD as string,
// is_registered: true,
// is_organization: false,
// user_profile: {
// first_name: 'Имя',
// last_name: 'Фамилия',
// middle_name: 'Отчество',
// birthday: '23-42-3423',
// phone: '+7902294404',
// },
// signature: '-',
// signature_hash: '-',
// role: 'chairman',
// });
} else if (member.position === 'chairman' && user) {
user.role = 'chairman';
user.password = process.env.CHAIRMAN_PASSWORD || 'password';
// eslint-disable-next-line no-await-in-loop
await user.save();
} else if (user) {
user.role = 'admin';
// eslint-disable-next-line no-await-in-loop
await user.save();
}
export const loginUserWithSignature = async (email, now, signature) => {
const user = await getUserByEmail(email);
if (!user) {
throw new ApiError(httpStatus.UNAUTHORIZED, 'Пользователь не найден');
}
const bytes = Bytes.fromString(now, 'utf8');
const checksum = Checksum256.hash(bytes);
const wharf_signature = Signature.from(signature);
const publicKey = wharf_signature.recoverDigest(checksum).toLegacyString();
const info = await getBlockchainInfo();
const blockchainDate = new Date(info.head_block_time).getTime();
const userData = new Date(now).getTime();
const differenceInSeconds = (blockchainDate - userData) / 1000;
if (differenceInSeconds > 30) {
throw new ApiError(httpStatus.BAD_REQUEST, 'Время подписи и время блокчейна превышает допустимое расхождение');
}
if (config.env !== 'test') {
try {
const blockchainAccount = await getBlockchainAccount(user.username);
const hasKey = hasActiveKey(blockchainAccount, publicKey);
if (!hasKey) throw new ApiError(httpStatus.UNAUTHORIZED, 'Неверный приватный ключ');
} catch (e) {
throw new ApiError(httpStatus.UNAUTHORIZED, 'Неверный приватный ключ');
}
} catch (e: any) {
// eslint-disable-next-line no-console
console.log('Ошибка при автоматической проверке целевой авторизации: ', e.message);
}
};
/**
* Login with username and password
* @param {string} username
* @param {string} password
* @returns {Promise<User>}
*/
export const loginUserWithUsernameAndPassword = async (username, password) => {
const user = await userService.getUserByUsername(username);
if (!user || !(await user.isPasswordMatch(password))) {
throw new ApiError(httpStatus.UNAUTHORIZED, 'Incorrect username or password');
}
return user;
};
@@ -75,7 +58,7 @@ export const logout = async (refreshToken) => {
if (!refreshTokenDoc) {
throw new ApiError(httpStatus.NOT_FOUND, 'Not found');
}
await refreshTokenDoc.remove();
await refreshTokenDoc.deleteOne();
};
/**
@@ -83,16 +66,14 @@ export const logout = async (refreshToken) => {
* @param {string} refreshToken
* @returns {Promise<Object>}
*/
export const refreshAuth = async (refreshToken) => {
export const refreshAuth = async (data: IRefreshTokens) => {
try {
const refreshTokenDoc = await tokenService.verifyToken(refreshToken, tokenTypes.REFRESH);
const user = await userService.getUserByUsername(refreshTokenDoc.user);
const refreshTokenDoc = await tokenService.verifyToken(data.refreshToken, tokenTypes.REFRESH);
const user = await userService.getUserById(refreshTokenDoc.user);
if (!user) {
throw new Error();
}
await refreshTokenDoc.remove();
await refreshTokenDoc.deleteOne();
return tokenService.generateAuthTokens(user);
} catch (error) {
throw new ApiError(httpStatus.UNAUTHORIZED, 'Please authenticate');
@@ -100,22 +81,34 @@ export const refreshAuth = async (refreshToken) => {
};
/**
* Reset password
* @param {string} resetPasswordToken
* @param {string} newPassword
* Reset key
* @param {string} resetKeyToken
* @param {string} publicKey
* @returns {Promise}
*/
export const resetPassword = async (resetPasswordToken, newPassword) => {
export const resetKey = async (resetKeyToken, publicKey) => {
try {
const resetPasswordTokenDoc = await tokenService.verifyToken(resetPasswordToken, tokenTypes.RESET_PASSWORD);
const user = await userService.getUserByUsername(resetPasswordTokenDoc.user);
const resetKeyTokenDoc = await tokenService.verifyToken(resetKeyToken, [tokenTypes.RESET_PASSWORD, tokenTypes.INVITE]);
const user = await userService.getUserById(resetKeyTokenDoc.user);
if (!user) {
throw new Error();
}
await userService.updateUserById(user.username, { password: newPassword });
await Token.deleteMany({ user: user.username, type: tokenTypes.RESET_PASSWORD });
if (config.env !== 'test')
await blockchainService.changeKey({
coopname: config.coopname,
changer: config.service_username,
username: user.username,
public_key: publicKey,
});
await userService.updateUserById(user._id, { public_key: publicKey });
await Token.deleteMany({ user: user._id, type: tokenTypes.RESET_PASSWORD });
} catch (error) {
throw new ApiError(httpStatus.UNAUTHORIZED, 'Password reset failed');
console.log(error);
throw new ApiError(httpStatus.UNAUTHORIZED, 'Token reset failed');
}
};
@@ -127,12 +120,12 @@ export const resetPassword = async (resetPasswordToken, newPassword) => {
export const verifyEmail = async (verifyEmailToken) => {
try {
const verifyEmailTokenDoc = await tokenService.verifyToken(verifyEmailToken, tokenTypes.VERIFY_EMAIL);
const user = await userService.getUserByUsername(verifyEmailTokenDoc.user);
const user = await userService.getUserById(verifyEmailTokenDoc.user);
if (!user) {
throw new Error();
}
await Token.deleteMany({ user: user.username, type: tokenTypes.VERIFY_EMAIL });
await userService.updateUserById(user.username, { is_email_verified: true });
await Token.deleteMany({ user: user._id, type: tokenTypes.VERIFY_EMAIL });
await userService.updateUserById(user._id, { is_email_verified: true });
} catch (error) {
throw new ApiError(httpStatus.UNAUTHORIZED, 'Email verification failed');
}
@@ -6,9 +6,33 @@ import EosApi from 'eosjs-api';
import getInternalAction from '../utils/getInternalAction';
import { GatewayContract, RegistratorContract, SovietContract } from 'cooptypes';
import { IUser } from '../models/user.model';
import { GetAccountResult, GetInfoResult } from 'eosjs/dist/eosjs-rpc-interfaces';
import config from '../config/config';
import TempDocument, { tempdocType } from '../models/tempDocument.model';
import ApiError from '../utils/ApiError';
import httpStatus from 'http-status';
const rpc = new JsonRpc(process.env.BLOCKCHAIN_RPC as string, { fetch });
function hasActiveKey(account, publicKey) {
const activePermissions = account.permissions.find((p: any) => p.perm_name === 'active');
if (!activePermissions) return false;
return activePermissions.required_auth.keys.some((key: any) => key.key === publicKey);
}
async function getBlockchainInfo(): Promise<GetInfoResult> {
const api = getApi();
return await api.getInfo({});
}
async function getBlockchainAccount(username): Promise<GetAccountResult> {
const api = getApi();
return await api.getAccount(username);
}
/**
* Получить инстанс для осуществления транзакции в блокчейн.
* @param {username} - авторизация от аккаунта
@@ -22,7 +46,7 @@ async function getInstance(wif) {
return api;
}
async function getApi() {
function getApi() {
const options = {
httpEndpoint: process.env.BLOCKCHAIN_RPC, // default, null for cold-storage
verbose: false, // API logging
@@ -63,9 +87,9 @@ async function getCooperative(coopname) {
const [cooperative] = await lazyFetch(
api,
process.env.REGISTRATOR_CONTRACT,
process.env.REGISTRATOR_CONTRACT,
'orgs',
RegistratorContract.contractName.production,
RegistratorContract.contractName.production,
RegistratorContract.Tables.Cooperatives.tableName,
coopname,
coopname,
1
@@ -74,7 +98,7 @@ async function getCooperative(coopname) {
}
async function registerBlockchainAccount(user: IUser, orderData: GatewayContract.Actions.CompleteDeposit.ICompleteDeposit) {
const eos = await getInstance(process.env.REGISTRATOR_WIF);
const eos = await getInstance(process.env.SERVICE_WIF);
const newaccount: RegistratorContract.Actions.CreateAccount.ICreateAccount = {
registrator: process.env.COOPNAME as string,
@@ -83,23 +107,36 @@ async function registerBlockchainAccount(user: IUser, orderData: GatewayContract
username: user.username,
public_key: user.public_key,
meta: '',
signature_hash: '' // LEGACY - delete it later
}
};
const registerUserData: RegistratorContract.Actions.RegisterUser.IRegistrerUser = {
coopname: process.env.COOPNAME as string,
registrator: process.env.COOPNAME as string,
username: user.username,
}
type: user.type,
};
const statement = await TempDocument.findOne({ username: user.username, type: tempdocType.JoinStatement });
if (!statement) throw new ApiError(httpStatus.BAD_REQUEST, 'Не найдено заявление на вступление');
const joinCooperativeData: RegistratorContract.Actions.JoinCooperative.IJoinCooperative = {
coopname: process.env.COOPNAME as string,
registrator: process.env.COOPNAME as string,
username: user.username,
document: {...user.statement, meta: JSON.stringify(user.statement.meta)},
}
document: { ...statement.document, meta: JSON.stringify(statement.document.meta) },
};
console.log("joinCooperativeData: ", joinCooperativeData)
//TODO добавить здесь соглашений
const walletAgreement = await TempDocument.findOne({ username: user.username, type: tempdocType.WalletAgreement });
if (!walletAgreement) throw new ApiError(httpStatus.BAD_REQUEST, 'Не найдено заявление на вступление');
const walletAgreementData: SovietContract.Actions.Agreements.SendAgreement.ISendAgreement = {
coopname: process.env.COOPNAME as string,
administrator: process.env.COOPNAME as string,
username: user.username,
agreement_type: 'wallet',
document: { ...walletAgreement.document, meta: JSON.stringify(walletAgreement.document.meta) },
};
const actions = [
{
@@ -115,7 +152,7 @@ async function registerBlockchainAccount(user: IUser, orderData: GatewayContract
},
{
account: RegistratorContract.contractName.production,
name: RegistratorContract.Actions.RegisterUser.actionName,//reguser
name: RegistratorContract.Actions.RegisterUser.actionName, //reguser
authorization: [
{
actor: process.env.COOPNAME as string,
@@ -146,7 +183,17 @@ async function registerBlockchainAccount(user: IUser, orderData: GatewayContract
],
data: orderData,
},
{
account: SovietContract.contractName.production,
name: SovietContract.Actions.Agreements.SendAgreement.actionName,
authorization: [
{
actor: process.env.COOPNAME as string,
permission: 'active',
},
],
data: walletAgreementData,
},
];
const result = await eos.transact(
@@ -160,12 +207,42 @@ async function registerBlockchainAccount(user: IUser, orderData: GatewayContract
);
}
async function createOrder(data) {
const eos = await getInstance(process.env.REGISTRATOR_WIF);
async function createBoard(data: SovietContract.Actions.Boards.CreateBoard.ICreateboard) {
const eos = await getInstance(config.service_wif);
console.log('data: ', data);
const actions = [
{
account: process.env.GATEWAY_CONTRACT as string,
account: SovietContract.contractName.production,
name: SovietContract.Actions.Boards.CreateBoard.actionName,
authorization: [
{
actor: config.service_username,
permission: 'active',
},
],
data,
},
];
await eos.transact(
{
actions,
},
{
blocksBehind: 3,
expireSeconds: 30,
}
);
}
async function createOrder(data) {
const eos = await getInstance(process.env.SERVICE_WIF);
const actions = [
{
account: GatewayContract.contractName.production,
name: 'deposit',
authorization: [
{
@@ -193,7 +270,7 @@ async function createOrder(data) {
}
async function completeOrder(data: GatewayContract.Actions.CompleteDeposit.ICompleteDeposit) {
const eos = await getInstance(process.env.REGISTRATOR_WIF);
const eos = await getInstance(process.env.SERVICE_WIF);
const actions = [
{
@@ -221,11 +298,11 @@ async function completeOrder(data: GatewayContract.Actions.CompleteDeposit.IComp
}
async function failOrder(data) {
const eos = await getInstance(process.env.REGISTRATOR_WIF);
const eos = await getInstance(process.env.SERVICE_WIF);
const actions = [
{
account: process.env.GATEWAY_CONTRACT as string,
account: GatewayContract.contractName.production,
name: 'dpfail',
authorization: [
{
@@ -248,10 +325,66 @@ async function failOrder(data) {
);
}
export async function addUser(data: RegistratorContract.Actions.AddUser.IAddUser) {
const eos = await getInstance(config.service_wif);
const actions = [
{
account: RegistratorContract.contractName.production,
name: RegistratorContract.Actions.AddUser.actionName,
authorization: [
{
actor: config.service_username,
permission: 'active',
},
],
data,
},
];
await eos.transact(
{
actions,
},
{
blocksBehind: 3,
expireSeconds: 30,
}
);
}
export async function changeKey(data: RegistratorContract.Actions.ChangeKey.IChangeKey) {
const eos = await getInstance(config.service_wif);
const actions = [
{
account: RegistratorContract.contractName.production,
name: RegistratorContract.Actions.ChangeKey.actionName,
authorization: [
{
actor: config.service_username,
permission: 'active',
},
],
data,
},
];
await eos.transact(
{
actions,
},
{
blocksBehind: 3,
expireSeconds: 30,
}
);
}
async function getSoviet(coopname) {
const api = await getApi();
const soviet = (await lazyFetch(api, process.env.SOVIET_CONTRACT, coopname, 'boards'))[0];
const soviet = (await lazyFetch(api, SovietContract.contractName.production, coopname, 'boards'))[0];
return soviet;
}
@@ -259,7 +392,7 @@ async function getSoviet(coopname) {
async function fetchAllParticipants() {
const api = await getApi();
const participants = await lazyFetch(api, process.env.SOVIET_CONTRACT, process.env.COOPNAME, 'participants');
const participants = await lazyFetch(api, SovietContract.contractName.production, process.env.COOPNAME, 'participants');
return participants;
}
@@ -274,4 +407,8 @@ export {
failOrder,
completeOrder,
getSoviet,
getBlockchainInfo,
getBlockchainAccount,
hasActiveKey,
createBoard,
};
@@ -1,25 +1,28 @@
import { getActions } from '../utils/getFetch';
import { generator } from './data.service';
import { generator } from './document.service';
import { userService, blockchainService } from './index';
import { Cooperative, SovietContract } from 'cooptypes';
import { Cooperative, RegistratorContract, SovietContract } from 'cooptypes';
import ApiError from '../utils/ApiError';
import httpStatus from 'http-status';
import logger from '../config/logger';
const loadAgenda = async (coopname: string): Promise<Cooperative.Documents.IAgenda[]> => {
export const loadAgenda = async (coopname: string): Promise<Cooperative.Document.IAgenda[]> => {
const api = await blockchainService.getApi();
const decisions = (await blockchainService.lazyFetch(
api,
process.env.SOVIET_CONTRACT as string,
SovietContract.contractName.production as string,
coopname,
'decisions'
)) as SovietContract.Tables.Decisions.IDecision[];
const agenda = [] as Cooperative.Documents.IAgenda[];
const agenda = [] as Cooperative.Document.IAgenda[];
for (const table of decisions) {
const action = (
await getActions(`${process.env.SIMPLE_EXPLORER_API}/get-actions`, {
filter: JSON.stringify({
account: process.env.SOVIET_CONTRACT,
account: SovietContract.contractName.production,
name: SovietContract.Actions.Registry.NewSubmitted.actionName,
receiver: process.env.COOPNAME,
'data.decision_id': String(table.id),
@@ -34,10 +37,10 @@ const loadAgenda = async (coopname: string): Promise<Cooperative.Documents.IAgen
return agenda;
};
const loadStaff = async (coopname) => {
export const loadStaff = async (coopname) => {
const api = await blockchainService.getApi();
const staff = await blockchainService.lazyFetch(api, process.env.SOVIET_CONTRACT, coopname, 'staff');
const staff = await blockchainService.lazyFetch(api, SovietContract.contractName.production, coopname, 'staff');
for (const staf of staff) {
const user = await userService.getUserByUsername(staf.username);
@@ -51,60 +54,54 @@ const loadStaff = async (coopname) => {
return staff;
};
const loadMembers = async (coopname) => {
// const api = await blockchainService.getApi()
// const soviet = (await blockchainService.lazyFetch(
// api,
// process.env.SOVIET_CONTRACT,
// coopname,
// 'boards',
// "soviet",
// "soviet",
// 1,
// 'i64',
// 2
// ))[0]
// for (const member of soviet.members) {
// const user = await userService.getUserByUsername(member.username)
// if (user) {
// member.is_organization = user.is_organization
// member.user_profile = user.user_profile
// member.org_profile = user.organization_profile
// }
// }
// return soviet.members
export const loadInfo = async (coopname: string) => {
const cooperative: Cooperative.Model.ICooperativeData | null = await generator.constructCooperative(coopname);
if (!cooperative) throw new ApiError(httpStatus.NO_CONTENT, 'Кооператив не найден');
else return cooperative;
};
const loadSoviet = async (api, coopname) => {
const [soviet] = await blockchainService.lazyFetch(
api,
process.env.SOVIET_CONTRACT,
coopname,
'boards',
'soviet',
'soviet',
1,
'i64',
2
);
export const loadContacts = async (coopname: string) => {
const cooperative: Cooperative.Model.ICooperativeData | null = await generator.constructCooperative(coopname);
soviet.chairman = soviet.members.find((el) => el.position == 'chairman').username;
if (!cooperative) throw new ApiError(httpStatus.NOT_FOUND, 'Кооператив не найден');
return soviet;
const api = await blockchainService.getApi();
const coopAccount = (
await blockchainService.lazyFetch(
api,
RegistratorContract.contractName.production,
RegistratorContract.contractName.production,
RegistratorContract.Tables.Accounts.tableName,
coopname,
coopname,
1
)
)[0];
if (!coopAccount) throw new ApiError(httpStatus.NOT_FOUND, 'Аккаунт не найден');
let announce: Cooperative.Users.IAccountMeta = { phone: cooperative?.phone, email: cooperative?.email };
if (coopAccount.meta) {
try {
announce = JSON.parse(coopAccount.meta);
} catch (e: any) {
logger.warn(`Ошибка при получении контактов: ${e.message}`);
}
}
return {
full_name: cooperative?.full_name,
full_address: cooperative?.full_address,
details: cooperative?.details,
phone: announce.phone,
email: announce.email,
description: cooperative?.description,
chairman: {
first_name: cooperative?.chairman.first_name,
last_name: cooperative?.chairman.last_name,
middle_name: cooperative?.chairman.middle_name,
},
};
};
const getDecision = async (api, coopname, decision_id) => {
const [decision] = await blockchainService.lazyFetch(
api,
process.env.SOVIET_CONTRACT,
coopname,
'decisions',
decision_id,
decision_id,
1
);
return decision;
};
export { loadAgenda, loadStaff, loadMembers, getDecision };
@@ -1,15 +1,9 @@
import eosjsecc from 'eosjs-ecc';
import ApiError from '../utils/ApiError';
import { getActions, getTables } from '../utils/getFetch';
import * as coopService from './coop.service';
const { verify, sha256 } = eosjsecc;
import { getActions } from '../utils/getFetch';
import config from '../config/config';
import { Generator } from 'coopdoc-generator-ts';
import type { IGenerate, IGetDocuments } from '../types';
import type { IGenerate } from '../types';
import { Cooperative, SovietContract } from 'cooptypes';
import { User } from '../models';
import { IUser } from '../models/user.model';
export const generator = new Generator();
@@ -18,25 +12,36 @@ export const connectGenerator = async () => {
};
export const generateDocument = async (options: IGenerate) => {
console.log('controller generate: ', options);
return await generator.generate(options);
};
// Шаг 1: Создание новой функции для сборки complexDocument
export async function buildComplexDocument(
raw_action_document: Cooperative.Blockchain.IAction
): Promise<Cooperative.Documents.IComplexDocument> {
let statement = {} as Cooperative.Documents.IComplexStatement;
let decision = {} as Cooperative.Documents.IComplexDecision;
let act = {} as Cooperative.Documents.IComplexAct;
): Promise<Cooperative.Document.IComplexDocument> {
let statement = {} as Cooperative.Document.IComplexStatement;
let decision = {} as Cooperative.Document.IComplexDecision;
const act = {} as Cooperative.Document.IComplexAct;
const links: Cooperative.Document.IGeneratedDocument[] = [];
const raw_document = raw_action_document.data as SovietContract.Actions.Registry.NewSubmitted.INewSubmitted;
// Готовим заявления
{
const document = await generator.getDocument({ hash: raw_document.document.hash });
console.log('document: ', document);
if (document)
for (const link of document.meta.links) {
console.log('look for link: ', link);
const linked_document = await generator.getDocument({ hash: link });
links.push(linked_document);
}
const user = await User.findOne({ username: raw_document.username });
if (user) {
if (user && user.type != 'service') {
const user_data = await user?.getPrivateData();
const action: Cooperative.Blockchain.IExtendedAction = {
@@ -45,8 +50,6 @@ export async function buildComplexDocument(
};
statement = { action, document };
} else {
// throw new ApiError(400, 'Ошибка, один из пользователей не найден. Обратитесь в поддержку.');
}
}
@@ -57,7 +60,7 @@ export async function buildComplexDocument(
const decision_action = (
await getActions(`${process.env.SIMPLE_EXPLORER_API}/get-actions`, {
filter: JSON.stringify({
account: process.env.SOVIET_CONTRACT,
account: SovietContract.contractName.production,
name: SovietContract.Actions.Registry.NewDecision.actionName,
receiver: process.env.COOPNAME,
'data.decision_id': String(raw_document.decision_id),
@@ -71,8 +74,6 @@ export async function buildComplexDocument(
const user = await User.findOne({ username: decision_action?.data?.username });
if (user) {
const user_data = user.getPrivateData();
decision_extended_action = {
...decision_action,
user: (await user?.getPrivateData()) || null,
@@ -80,6 +81,12 @@ export async function buildComplexDocument(
const document = await generator.getDocument({ hash: decision_action?.data?.document?.hash });
if (document)
for (const link of document.meta.links) {
const linked_document = await generator.getDocument({ hash: link });
links.push(linked_document);
}
decision = {
document,
action: decision_extended_action,
@@ -93,21 +100,21 @@ export async function buildComplexDocument(
}
// Готовим акты
const acts: Cooperative.Documents.IComplexAct[] = [];
const acts: Cooperative.Document.IComplexAct[] = [];
return { statement, decision, acts };
return { statement, decision, acts, links };
}
export const queryDocuments = async (
filter: any,
page: number = 1,
limit: number = 100
): Promise<Cooperative.Documents.IGetComplexDocuments> => {
page = 1,
limit = 100
): Promise<Cooperative.Document.IGetComplexDocuments> => {
const actions = await getActions<SovietContract.Actions.Registry.NewResolved.INewResolved>(
`${process.env.SIMPLE_EXPLORER_API}/get-actions`,
{
filter: JSON.stringify({
account: process.env.SOVIET_CONTRACT,
account: SovietContract.contractName.production,
name: SovietContract.Actions.Registry.NewResolved.actionName,
receiver: process.env.COOPNAME,
...filter,
@@ -117,7 +124,7 @@ export const queryDocuments = async (
}
);
let response: Cooperative.Documents.IGetComplexDocuments = {
const response: Cooperative.Document.IGetComplexDocuments = {
results: [],
page,
limit,
@@ -128,30 +135,6 @@ export const queryDocuments = async (
if (complexDocument.decision.action) response.results.push(complexDocument);
}
console.log(response);
return response;
};
export const getDocuments = async (account) => {
// let data = await getActions('/v2/history/get_actions', {
// "filter": "soviettest1:statement",
// "account": account,
// })
// for (const action of data.actions) {
// action.decision = (await getActions('/v2/history/get_actions', {
// "account": account,
// "filter": "soviettest1:decision",
// "@decision.decision_id": action.act.data.decision_id,
// }))?.actions?.[0]
// if (action.act.data.action == 'joincoop') {
// try {
// action.verified = await verify(action.act.data.statement.sign, action.act.data.statement.hash, action.act.data.statement.pkey)
// } catch(e: any){
// console.error(e)
// action.verified = false
// action.verify_message = e.message
// }
// }
// }
// return data.actions
};
@@ -2,9 +2,9 @@ import { createTransport } from 'nodemailer';
import config from '../config/config';
import logger from '../config/logger';
const { email, env } = config
const { email, env } = config;
const transport = createTransport(email.smtp);
export const transport = createTransport(email.smtp);
/* istanbul ignore next */
if (env !== 'test') {
@@ -21,7 +21,7 @@ if (env !== 'test') {
* @param {string} text
* @returns {Promise}
*/
const sendEmail = async (to, subject, text) => {
export const sendEmail = async (to, subject, text) => {
const msg = { from: email.from, to, subject, text };
await transport.sendMail(msg);
};
@@ -32,13 +32,33 @@ const sendEmail = async (to, subject, text) => {
* @param {string} token
* @returns {Promise}
*/
const sendResetPasswordEmail = async (to, token) => {
const subject = 'Reset password';
// replace this url with the link to the reset password page of your front-end app
const resetPasswordUrl = `http://link-to-app/reset-password?token=${token}`;
const text = `Dear user,
To reset your password, click on this link: ${resetPasswordUrl}
If you did not request any password resets, then ignore this email.`;
export const sendResetKeyEmail = async (to, token) => {
const subject = 'Восстановление доступа';
const resetPasswordUrl = `${config.base_url}/#/${config.coopname}/auth/reset-key?token=${token}`;
const text = `Мы получили запрос на перевыпуск приватного ключа,
Для перевыпуска нажмите на ссылку: ${resetPasswordUrl}. Время действия ссылки - 10 минут.
Если вы не запрашивали перевыпуск ключа - проигнорируйте это сообщение.`;
await sendEmail(to, subject, text);
};
/**
* Send reset password email
* @param {string} to
* @param {string} token
* @returns {Promise}
*/
export const sendInviteEmail = async (to, token) => {
const subject = 'Приглашение в Цифровой Кооператив';
const inviteUrl = `${config.base_url}/#/${config.coopname}/auth/reset-key?token=${token}`;
const text = `Вам отправлено приглашение на подключение к Цифровому Кооперативу в качестве действующего пайщика.
Для того, чтобы воспользоваться приглашением и получить ключ доступа, пожалуйста, нажмите на ссылку: ${inviteUrl}
Время действия ссылки - 24 часа.`;
await sendEmail(to, subject, text);
};
@@ -48,7 +68,7 @@ If you did not request any password resets, then ignore this email.`;
* @param {string} token
* @returns {Promise}
*/
const sendVerificationEmail = async (to, token) => {
export const sendVerificationEmail = async (to, token) => {
const subject = 'Email Verification';
// replace this url with the link to the email verification page of your front-end app
const verificationEmailUrl = `http://link-to-app/verify-email?token=${token}`;
@@ -57,10 +77,3 @@ To verify your email, click on this link: ${verificationEmailUrl}
If you did not create an account, then ignore this email.`;
await sendEmail(to, subject, text);
};
export {
transport,
sendEmail,
sendResetPasswordEmail,
sendVerificationEmail,
};
+5 -2
View File
@@ -3,6 +3,9 @@ export * as emailService from './email.service';
export * as tokenService from './token.service';
export * as userService from './user.service';
export * as blockchainService from './blockchain.service';
export * as orderService from './order.service';
export * as dataService from './data.service';
export * as paymentService from './payment.service';
export * as documentService from './document.service';
export * as coopService from './coop.service';
export * as wsService from './ws.service';
export * as monoService from './mono.service';
export * as participantService from './participant.service';
@@ -0,0 +1,131 @@
import httpStatus from 'http-status';
import { Mono } from '../models';
import ApiError from '../utils/ApiError';
import config from '../config/config';
import logger from '../config/logger';
import { IAddUser, ICreateUser, IHealthStatus, IInstall } from '../types';
import { generateUsername } from '../../tests/utils/generateUsername';
import { generator } from './document.service';
import { blockchainService, emailService, tokenService, userService } from '.';
import { IUser, userStatus } from '../models/user.model';
import axios from 'axios';
import { getBlockchainInfo } from './blockchain.service';
import { RegistratorContract } from 'cooptypes';
export const install = async (soviet: IInstall): Promise<void> => {
console.log('IInstall: ', soviet);
const mono = await Mono.findOne({ coopname: config.coopname });
const info = await getBlockchainInfo();
const coop = await blockchainService.getCooperative(config.coopname);
if (!coop) throw new ApiError(httpStatus.BAD_REQUEST, 'Информация о кооперативе не обнаружена');
if (mono && mono.status != 'install') {
throw new ApiError(httpStatus.BAD_REQUEST, 'Установка уже выполнена');
}
const users = [] as IUser[];
const members = [] as any;
const sovietExt = [] as any;
try {
for (const member of soviet) {
console.log(member);
const username = generateUsername();
sovietExt.push({ ...member, username });
const addUser: RegistratorContract.Actions.AddUser.IAddUser = {
registrator: config.service_username,
coopname: config.coopname,
referer: '',
username,
type: 'individual',
created_at: info.head_block_time,
initial: coop.initial,
minimum: coop.minimum,
spread_initial: false,
meta: '',
};
await blockchainService.addUser(addUser);
const createUser: ICreateUser = {
email: member.individual_data.email,
individual_data: member.individual_data,
referer: '',
role: 'user',
type: 'individual',
username,
};
const user = await userService.createUser(createUser);
user.status = userStatus['4_Registered'];
user.is_registered = true;
await user.save();
//Генерируем токен и отправляем приглашение
const token = await tokenService.generateInviteToken(member.individual_data.email);
await emailService.sendInviteEmail(member.individual_data.email, token);
//Добавляем в массив членов для отправки в бч
members.push({
username: username,
is_voting: true,
position_title: member.role === 'chairman' ? 'Председатель совета' : 'Член совета',
position: member.role,
});
users.push(user);
}
const chairman = sovietExt.find((el) => el.role == 'chairman');
//TODO создаёт доску совета
await blockchainService.createBoard({
coopname: config.coopname,
username: config.service_username,
type: 'soviet',
members: members,
name: 'Совет',
description: '',
});
} catch (e: any) {
console.log('on error', e);
for (const user of users) {
await userService.deleteUserByUsername(user.username);
await generator.del('individual', { username: user.username });
}
throw new ApiError(httpStatus.BAD_REQUEST, e.message);
}
await Mono.updateOne(
{ coopname: config.coopname },
{
status: 'active',
}
);
logger.info('MONO активирован');
};
export const init = async (): Promise<void> => {
const mono = await Mono.findOne({ coopname: config.coopname });
if (!mono)
await Mono.create({
coopname: config.coopname,
status: 'install',
});
logger.info('MONO инициализирован');
};
export const getMonoStatus = async (): Promise<IHealthStatus> => {
const mono = await Mono.findOne({ coopname: config.coopname });
if (!mono) throw new ApiError(httpStatus.BAD_REQUEST, 'Установщик не найден');
return mono.status;
};
@@ -1 +1 @@
export default {};
@@ -0,0 +1,82 @@
import { PublicKey, Signature } from '@wharfkit/antelope';
import type { IDocument, IJoinCooperative } from '../types';
import ApiError from '../utils/ApiError';
import { getUserByUsername } from './user.service';
import http from 'http-status';
import TempDocument, { tempdocType } from '../models/tempDocument.model';
import mongoose from 'mongoose';
import { userStatus, type IUser } from '../models/user.model';
const verifyDocumentSignature = (user: IUser, document: IDocument): void => {
const { hash, public_key, signature } = document;
const publicKeyObj = PublicKey.from(public_key);
const signatureObj = Signature.from(signature);
const verified: boolean = signatureObj.verifyDigest(hash, publicKeyObj);
if (!verified) {
throw new ApiError(http.INTERNAL_SERVER_ERROR, 'Invalid signature');
}
if (user.public_key !== document.public_key) throw new ApiError(http.BAD_REQUEST, 'Public keys are mismatched');
};
/**
* Join a Cooperative
*
*/
export const joinCooperative = async (data: IJoinCooperative): Promise<void> => {
const user = await getUserByUsername(data.username);
if (!user) {
throw new ApiError(http.NOT_FOUND, 'Пользователь не найден');
}
if (user.status !== userStatus['1_Created'] && user.status !== userStatus['2_Joined']) {
throw new ApiError(http.NOT_FOUND, 'Пользователь уже вступил в кооператив');
}
verifyDocumentSignature(user, data.statement);
verifyDocumentSignature(user, data.wallet_agreement);
verifyDocumentSignature(user, data.user_agreement);
verifyDocumentSignature(user, data.privacy_agreement);
verifyDocumentSignature(user, data.signature_agreement);
const session = await mongoose.startSession();
await session.withTransaction(async () => {
await TempDocument.findOneAndUpdate(
{ username: user.username, type: tempdocType.JoinStatement },
{ $set: { document: data.statement } },
{ upsert: true, new: true, session }
);
await TempDocument.findOneAndUpdate(
{ username: user.username, type: tempdocType.WalletAgreement },
{ $set: { document: data.wallet_agreement } },
{ upsert: true, new: true, session }
);
await TempDocument.findOneAndUpdate(
{ username: user.username, type: tempdocType.PrivacyAgreement },
{ $set: { document: data.privacy_agreement } },
{ upsert: true, new: true, session }
);
await TempDocument.findOneAndUpdate(
{ username: user.username, type: tempdocType.SignatureAgreement },
{ $set: { document: data.signature_agreement } },
{ upsert: true, new: true, session }
);
await TempDocument.findOneAndUpdate(
{ username: user.username, type: tempdocType.UserAgreement },
{ $set: { document: data.user_agreement } },
{ upsert: true, new: true, session }
);
user.status = userStatus['2_Joined'];
await user.save({ session });
});
session.endSession();
};
@@ -6,13 +6,28 @@ import { getUserByUsername } from './user.service';
import * as blockchainService from './blockchain.service';
import logger from '../config/logger';
import { ICreateDeposit, ICreateInitialPayment } from '../types';
import { generator } from './data.service';
import { generator } from './document.service';
import ApiError from '../utils/ApiError';
import httpStatus from 'http-status';
import { ICreatedPayment, IYandexIPN, PaymentDetails } from '../types/common';
import { Cooperative } from 'cooptypes';
import { FilterQuery } from 'mongoose';
import { userStatus } from '../models/user.model';
const { connection } = mongoose;
export const savePaymentMethod = async (data: Cooperative.Payments.IPaymentData) => {
return await generator.save('paymentMethod', data);
};
export const deletePaymentMethod = async (filter: FilterQuery<Cooperative.Payments.IPaymentData>) => {
return await generator.del('paymentMethod', filter as any);
};
export const listPaymentMethods = async (filter: FilterQuery<Cooperative.Payments.IPaymentData>) => {
return await generator.list('paymentMethod', filter as any);
};
function getAmountPlusFee(amount: number, provider: string): number {
const matrix = {
yookassa: 3.5,
@@ -26,7 +41,7 @@ function getAmountPlusFee(amount: number, provider: string): number {
}
export async function createDeposit(username: string, data: ICreateDeposit): Promise<ICreatedPayment> {
let cooperative = await generator.constructCooperative(process.env.COOPNAME as string);
const cooperative = await generator.constructCooperative(process.env.COOPNAME as string);
if (!cooperative) throw new Error('Кооператив не найден');
@@ -36,7 +51,7 @@ export async function createDeposit(username: string, data: ICreateDeposit): Pro
type: 'deposit',
data: { username, provider: data.provider, quantity: data.quantity },
});
const internal_id = db_order._id;
const internal_id = db_order.id;
let order_id = 0;
@@ -104,9 +119,9 @@ export async function createDeposit(username: string, data: ICreateDeposit): Pro
}
export async function createInitialOrder(username: string, data: ICreateInitialPayment): Promise<ICreatedPayment> {
let cooperative = await generator.constructCooperative(process.env.COOPNAME as string);
const cooperative = await generator.constructCooperative(process.env.COOPNAME as string);
if (!cooperative) throw new Error('Кооператив не найден');
if (!cooperative) throw new ApiError(httpStatus.BAD_REQUEST, 'Кооператив не найден');
const user = await getUserByUsername(username);
let amount = '';
@@ -114,8 +129,6 @@ export async function createInitialOrder(username: string, data: ICreateInitialP
if (user.type === 'individual' || user.type === 'entrepreneur') amount = cooperative.registration;
else amount = cooperative.org_registration;
console.log('amount: ', cooperative);
const [, symbol] = cooperative.initial.split(' ');
let order_id = 0;
@@ -127,7 +140,7 @@ export async function createInitialOrder(username: string, data: ICreateInitialP
type: 'registration',
data: { provider: data.provider, username, quantity: amount },
});
const internal_id = db_order._id;
const internal_id = db_order.id;
if (data.provider === 'yookassa') {
// 2. Используешь внутренний айди для получения ордера в системе платежей
@@ -175,7 +188,7 @@ export async function createInitialOrder(username: string, data: ICreateInitialP
type: 'registration',
quantity: amount,
};
console.log('amount: ', amount);
order_id = await blockchainService.createOrder(order);
// 4. Обновляешь ордер идентификатором ордера в блокчейне (order_id)
@@ -186,7 +199,10 @@ export async function createInitialOrder(username: string, data: ICreateInitialP
}
export async function catchIPN(ipnBody: IYandexIPN) {
if (!connection.db) throw new Error('Нет подключения');
const payments = await connection.db.collection('payments');
const exist = await payments.findOne({ 'object.id': ipnBody.object.id });
if (!exist) {
@@ -225,8 +241,8 @@ export async function catchIPN(ipnBody: IYandexIPN) {
memo: '',
});
console.log('Зарегистрирован новый пользователь: ', user.username);
user.status = 'registered';
logger.info('Зарегистрирован новый пользователь: ', user.username);
user.status = userStatus['4_Registered'];
user.is_registered = true;
} else if (order.type === 'deposit') {
await blockchainService.completeOrder({
@@ -236,7 +252,7 @@ export async function catchIPN(ipnBody: IYandexIPN) {
memo: '',
});
const quantity = parseFloat(order.data.quantity);
console.log(`Принят паевый взнос пользователя: ${user.username} на сумму ${order.data.quantity}`);
logger.info(`Принят паевый взнос пользователя: ${user.username} на сумму ${order.data.quantity}`);
}
await user.save();
@@ -244,7 +260,7 @@ export async function catchIPN(ipnBody: IYandexIPN) {
order.delivered = true;
await order.save();
} catch (e: any) {
console.error(e);
logger.warn(e);
order.error = e;
order.delivered = false;
await order.save();
@@ -256,7 +272,7 @@ export async function catchIPN(ipnBody: IYandexIPN) {
memo: '',
});
user.status = 'failed';
user.status = userStatus['10_Failed'];
user.message = e.message;
await user.save();
}
@@ -269,12 +285,8 @@ export async function catchIPN(ipnBody: IYandexIPN) {
});
}
} else {
logger.warn(`Ордер не найден: `, ipnBody);
throw new Error(`Ордер не найден`);
}
}
}
export default {
createInitialOrder,
catchIPN,
};
@@ -2,7 +2,7 @@ import jwt from 'jsonwebtoken';
import moment from 'moment';
import httpStatus from 'http-status';
import config from '../config/config';
import userService from './user.service';
import * as userService from './user.service';
import { Token } from '../models';
import ApiError from '../utils/ApiError';
import { tokenTypes } from '../config/tokens';
@@ -48,12 +48,17 @@ export const saveToken = async (token, userId, expires, type, blacklisted = fals
/**
* Verify token and return token doc (or throw an error if it is not valid)
* @param {string} token
* @param {string} type
* @param {string[]} types
* @returns {Promise<Token>}
*/
export const verifyToken = async (token, type) => {
export const verifyToken = async (token, types) => {
const payload = jwt.verify(token, config.jwt.secret);
const tokenDoc = await Token.findOne({ token, type, user: payload.sub, blacklisted: false });
const tokenDoc = await Token.findOne({
token,
$or: types.map((type) => ({ type })),
user: payload.sub,
blacklisted: false,
});
if (!tokenDoc) {
throw new Error('Token not found');
}
@@ -68,7 +73,7 @@ export const verifyToken = async (token, type) => {
export const generateServiceAccessToken = async (user) => {
const accessTokenExpires = moment().add(100, 'years'); // Пример с очень долгим сроком действия
const accessToken = generateToken(user.id, accessTokenExpires, tokenTypes.ACCESS);
console.log('on generate', accessToken);
return {
access: {
token: accessToken,
@@ -107,15 +112,31 @@ export const generateAuthTokens = async (user) => {
* @param {string} email
* @returns {Promise<string>}
*/
export const generateResetPasswordToken = async (email) => {
export const generateResetKeyToken = async (email) => {
const user = await userService.getUserByEmail(email);
if (!user) {
throw new ApiError(httpStatus.NOT_FOUND, 'No users found with this email');
}
const expires = moment().add(config.jwt.resetPasswordExpirationMinutes, 'minutes');
const resetPasswordToken = generateToken(user.id, expires, tokenTypes.RESET_PASSWORD);
await saveToken(resetPasswordToken, user.id, expires, tokenTypes.RESET_PASSWORD);
return resetPasswordToken;
const resetKeyToken = generateToken(user.id, expires, tokenTypes.RESET_PASSWORD);
await saveToken(resetKeyToken, user.id, expires, tokenTypes.RESET_PASSWORD);
return resetKeyToken;
};
/**
* Generate invite token
* @param {string} email
* @returns {Promise<string>}
*/
export const generateInviteToken = async (email) => {
const user = await userService.getUserByEmail(email);
if (!user) {
throw new ApiError(httpStatus.NOT_FOUND, 'No users found with this email');
}
const expires = moment().add(config.jwt.inviteExpirationMinutes, 'minutes');
const inviteToken = generateToken(user.id, expires, tokenTypes.INVITE);
await saveToken(inviteToken, user.id, expires, tokenTypes.INVITE);
return inviteToken;
};
/**
@@ -1,22 +1,16 @@
import http from 'http-status';
import { User } from '../models';
import ApiError from '../utils/ApiError';
import { generator } from './data.service';
import { ICreateUser, IJoinCooperative } from '../types/user.validation';
import ecc from 'eosjs-ecc';
import { generator } from './document.service';
import { ICreateUser } from '../types/auto-generated/user.validation';
import { PublicKey, Signature } from '@wharfkit/antelope';
import faker from 'faker';
import { randomBytes } from 'crypto';
export const createServiceUser = async (username: string) => {
const password = randomBytes(16).toString('hex');
return User.create({
username,
type: 'service',
role: 'service',
public_key: 'thanks-no-need',
password,
email: faker.internet.email().toLowerCase(),
});
};
@@ -28,6 +22,7 @@ export const createServiceUser = async (username: string) => {
export const createUser = async (userBody: ICreateUser) => {
//TODO проверяем на существование пользователя
//допускаем обновление личных данных, если пользователь находится в статусе 'created'
const exist = await User.findOne({ email: userBody.email });
if (userBody.type === 'individual' && !userBody.individual_data)
@@ -62,35 +57,6 @@ export const createUser = async (userBody: ICreateUser) => {
}
};
/**
* Join a Cooperative
*
*/
export const joinCooperative = async (data: IJoinCooperative): Promise<void> => {
const user = await getUserByUsername(data.username);
if (!user) {
throw new ApiError(http.NOT_FOUND, 'Пользователь не найден');
}
user.statement = data.statement;
user.status = 'joined';
const hash = data.statement.hash;
const public_key = PublicKey.from(data.statement.public_key);
const signature = Signature.from(data.statement.signature);
const verified: boolean = signature.verifyDigest(hash, public_key);
if (!verified) {
throw new ApiError(http.INTERNAL_SERVER_ERROR, 'Invalid signature');
}
if (user.public_key !== data.statement.public_key) throw new ApiError(http.BAD_REQUEST, 'Public keys are mismatched');
await user.save();
};
/**
* Query for users
* @param {Object} filter - Mongo filter
@@ -119,6 +85,19 @@ export const getUserByUsername = async (username: string) => {
return user;
};
/**
* Get user by username
* @param {string} id
* @returns {Promise<User>}
*/
export const getUserById = async (_id: string) => {
const user = await User.findById(_id);
if (!user) throw new ApiError(http.NOT_FOUND, 'Пользователь не найден');
return user;
};
/**
* Get user by email
* @param {string} email
@@ -134,8 +113,8 @@ export const getUserByEmail = async (email: string) => {
* @param {Object} updateBody
* @returns {Promise<User>}
*/
export const updateUserById = async (username, updateBody) => {
const user = await getUserByUsername(username);
export const updateUserById = async (id, updateBody) => {
const user = await getUserById(id);
if (!user) {
throw new ApiError(http.NOT_FOUND, 'Пользователь не найден');
}
@@ -147,26 +126,37 @@ export const updateUserById = async (username, updateBody) => {
return user;
};
/**
* Update user by username
* @param {string} username
* @param {Object} updateBody
* @returns {Promise<User>}
*/
export const updateUserByUsername = async (username, updateBody) => {
const user = await getUserByUsername(username);
if (!user) {
throw new ApiError(http.NOT_FOUND, 'Пользователь не найден');
}
if (updateBody.email && (await User.isEmailTaken(updateBody.email))) {
throw new ApiError(http.BAD_REQUEST, 'Email already taken');
}
Object.assign(user, updateBody);
await user.save();
return user;
};
/**
* Delete user by id
* @param {string} username
* @returns {Promise<User>}
*/
export const deleteUserById = async (username) => {
export const deleteUserByUsername = async (username) => {
const user = await getUserByUsername(username);
if (!user) {
throw new ApiError(http.NOT_FOUND, 'Пользователь не найден');
}
await user.remove();
await user.deleteOne();
return user;
};
export default {
createUser,
queryUsers,
getUserByUsername,
getUserByEmail,
updateUserById,
deleteUserById,
createServiceUser,
};
@@ -0,0 +1,24 @@
import { SovietContract } from 'cooptypes';
import { userService } from '.';
import { User } from '../models';
export const updateBoard = async (action: SovietContract.Actions.Boards.UpdateBoard.IUpdateBoard): Promise<void> => {
//сброс всех прав
const users = await User.find({ role: { $in: ['member', 'chairman'] } }).exec();
for (const user of users) {
user.role = 'user';
await user.save();
}
for (const member of action.members) {
const user = await userService.getUserByUsername(member.username);
user.role = 'member';
await user.save();
}
const chairman_username = action.members.find((el) => el.position == 'chairman')?.username;
const chairman = await userService.getUserByUsername(chairman_username as string);
chairman.role = 'chairman';
await chairman.save();
};
@@ -1,44 +0,0 @@
/**
* This file was automatically generated by joi-to-typescript
* Do not modify this file manually
*/
export interface forgotPassword {
body?: {
email: string;
};
}
export interface login {
body?: {
password: string;
username: string;
};
}
export interface logout {
body?: {
refreshToken: string;
};
}
export interface refreshTokens {
body?: {
refreshToken: string;
};
}
export interface resetPassword {
body?: {
password: string;
};
query?: {
token: string;
};
}
export interface verifyEmail {
query?: {
token: string;
};
}
@@ -0,0 +1,70 @@
/**
* This file was automatically generated by joi-to-typescript
* Do not modify this file manually
*/
export interface IForgotPassword {
email: string;
}
export interface ILogin {
email: string;
now: string;
signature: string;
}
export interface ILogout {
refreshToken: string;
}
export interface IRefreshTokens {
refreshToken: string;
}
export interface IResetKeyBody {
public_key: string;
token: string;
}
export interface IVerifyEmail {
token: string;
}
export interface RForgotKey {
body: {
email: string;
};
}
export interface RLogin {
body: {
email: string;
now: string;
signature: string;
};
}
export interface RLogout {
body: {
refreshToken: string;
};
}
export interface RRefreshTokens {
body: {
refreshToken: string;
};
}
export interface RResetKey {
body: {
public_key: string;
token: string;
};
}
export interface RVerifyEmail {
query: {
token: string;
};
}
@@ -9,12 +9,6 @@ export interface loadAgenda {
};
}
export interface loadMembers {
query?: {
coopname: string;
};
}
export interface loadStaff {
query?: {
coopname: string;
@@ -8,19 +8,23 @@ export interface IGenerate {
* Unknown Property
*/
[x: string]: unknown;
action: string;
block_num?: number;
code: string;
coopname: string;
created_at?: string;
generator?: string;
lang?: 'ru';
links?: string[];
registry_id: number;
timezone?: string;
username: string;
version?: string;
}
export interface IGetDocuments {
/**
* Unknown Property
*/
[x: string]: unknown;
filter?: {
receiver?: string;
};
@@ -35,13 +39,13 @@ export interface RGenerate {
* Unknown Property
*/
[x: string]: unknown;
action: string;
block_num?: number;
code: string;
coopname: string;
created_at?: string;
generator?: string;
lang?: 'ru';
links?: string[];
registry_id: number;
timezone?: string;
username: string;
version?: string;
@@ -50,6 +54,10 @@ export interface RGenerate {
export interface RGetDocuments {
query?: {
/**
* Unknown Property
*/
[x: string]: unknown;
filter?: {
receiver?: string;
};
@@ -0,0 +1,13 @@
/**
* This file was automatically generated by joi-to-typescript
* Do not modify this file manually
*/
export * from './auth.validation';
export * from './coop.validation';
export * from './document.validation';
export * from './mono.validation';
export * from './notify.validation';
export * from './participant.validation';
export * from './payment.validation';
export * from './user.validation';
@@ -0,0 +1,32 @@
/**
* This file was automatically generated by joi-to-typescript
* Do not modify this file manually
*/
export type IInstall = ({
individual_data: {
birthdate: string;
email: string;
first_name: string;
full_address: string;
last_name: string;
middle_name: string;
phone: string;
};
role: 'chairman' | 'member';
})[];
export interface RInstall {
body: ({
individual_data: {
birthdate: string;
email: string;
first_name: string;
full_address: string;
last_name: string;
middle_name: string;
phone: string;
};
role: 'chairman' | 'member';
})[];
}
@@ -0,0 +1,81 @@
/**
* This file was automatically generated by joi-to-typescript
* Do not modify this file manually
*/
export interface IDocument {
hash: string;
meta: object;
public_key: string;
signature: string;
}
export interface IJoinCooperative {
privacy_agreement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
signature_agreement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
statement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
user_agreement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
username: string;
wallet_agreement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
}
export interface RJoinCooperative {
body: {
privacy_agreement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
signature_agreement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
statement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
user_agreement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
username: string;
wallet_agreement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
};
}
@@ -3,6 +3,18 @@
* Do not modify this file manually
*/
export interface IBankAccount {
account_number: string;
bank_name: string;
card_number?: string;
currency: 'RUB' | 'Other';
details: {
bik: string;
corr: string;
kpp: string;
};
}
export interface ICreateDeposit {
provider: 'yookassa';
quantity: string;
@@ -12,6 +24,10 @@ export interface ICreateInitialPayment {
provider: 'yookassa';
}
export interface IDeletePaymentMethod {
method_id: number;
}
export interface IRecieveIPN {
event: string;
object: {
@@ -98,3 +114,65 @@ export interface IRecieveIPN {
};
type: string;
}
export interface ISavePaymentMethod {
data: {
phone: string;
} | ({
account_number: string;
bank_name: string;
card_number?: string;
currency: 'RUB' | 'Other';
details: {
bik: string;
corr: string;
kpp: string;
};
});
method_id: number;
method_type: 'sbp' | 'bank_transfer';
username: string;
}
export interface ISbpDetails {
phone: string;
}
export interface RDeletePaymentMethod {
body: {
method_id: number;
};
params?: {
username: string;
};
}
export interface RGetListPaymentMethods {
params?: {
username?: string;
};
}
export interface RSavePaymentMethod {
body: {
data: {
phone: string;
} | ({
account_number: string;
bank_name: string;
card_number?: string;
currency: 'RUB' | 'Other';
details: {
bik: string;
corr: string;
kpp: string;
};
});
method_id: number;
method_type: 'sbp' | 'bank_transfer';
username: string;
};
params?: {
username: string;
};
}
@@ -3,6 +3,84 @@
* Do not modify this file manually
*/
export interface IAddUser {
created_at: string;
email: string;
entrepreneur_data?: {
bank_account: {
account_number: string;
bank_name: string;
card_number?: string;
currency: 'RUB' | 'Other';
details: {
bik: string;
corr: string;
kpp: string;
};
};
birthdate: string;
city: string;
country: 'Russia' | 'Other';
details: {
inn: string;
ogrn: string;
};
email: string;
first_name: string;
full_address: string;
last_name: string;
middle_name: string;
phone: string;
};
individual_data?: {
birthdate: string;
email: string;
first_name: string;
full_address: string;
last_name: string;
middle_name: string;
phone: string;
};
initial: string;
minimum: string;
organization_data?: {
bank_account: {
account_number: string;
bank_name: string;
card_number?: string;
currency: 'RUB' | 'Other';
details: {
bik: string;
corr: string;
kpp: string;
};
};
city: string;
country: 'Russia' | 'Other';
details: {
inn: string;
ogrn: string;
};
email: string;
full_address: string;
full_name: string;
is_cooperative: boolean;
phone: string;
represented_by: {
based_on: string;
first_name: string;
last_name: string;
middle_name: string;
position: string;
};
short_name: string;
type: 'coop' | 'ooo' | 'oao' | 'zao' | 'pao' | 'ao';
};
referer?: string;
spread_initial: boolean;
type: 'individual' | 'entrepreneur' | 'organization';
}
export interface ICreateUser {
email: string;
entrepreneur_data?: {
@@ -73,21 +151,13 @@ export interface ICreateUser {
short_name: string;
type: 'coop' | 'ooo' | 'oao' | 'zao' | 'pao' | 'ao';
};
password: string;
public_key: string;
public_key?: string;
referer?: string;
role: 'user' | 'admin';
role: 'user';
type: 'individual' | 'entrepreneur' | 'organization';
username: string;
}
export interface IDocument {
hash: string;
meta: object;
public_key: string;
signature: string;
}
export interface IEntrepreneurData {
bank_account: {
account_number: string;
@@ -125,16 +195,6 @@ export interface IIndividualData {
phone: string;
}
export interface IJoinCooperative {
statement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
username: string;
}
export interface IOrganizationData {
bank_account: {
account_number: string;
@@ -169,6 +229,86 @@ export interface IOrganizationData {
type: 'coop' | 'ooo' | 'oao' | 'zao' | 'pao' | 'ao';
}
export interface RAddUser {
body: {
created_at: string;
email: string;
entrepreneur_data?: {
bank_account: {
account_number: string;
bank_name: string;
card_number?: string;
currency: 'RUB' | 'Other';
details: {
bik: string;
corr: string;
kpp: string;
};
};
birthdate: string;
city: string;
country: 'Russia' | 'Other';
details: {
inn: string;
ogrn: string;
};
email: string;
first_name: string;
full_address: string;
last_name: string;
middle_name: string;
phone: string;
};
individual_data?: {
birthdate: string;
email: string;
first_name: string;
full_address: string;
last_name: string;
middle_name: string;
phone: string;
};
initial: string;
minimum: string;
organization_data?: {
bank_account: {
account_number: string;
bank_name: string;
card_number?: string;
currency: 'RUB' | 'Other';
details: {
bik: string;
corr: string;
kpp: string;
};
};
city: string;
country: 'Russia' | 'Other';
details: {
inn: string;
ogrn: string;
};
email: string;
full_address: string;
full_name: string;
is_cooperative: boolean;
phone: string;
represented_by: {
based_on: string;
first_name: string;
last_name: string;
middle_name: string;
position: string;
};
short_name: string;
type: 'coop' | 'ooo' | 'oao' | 'zao' | 'pao' | 'ao';
};
referer?: string;
spread_initial: boolean;
type: 'individual' | 'entrepreneur' | 'organization';
};
}
export interface RCreateUser {
body: {
email: string;
@@ -240,10 +380,9 @@ export interface RCreateUser {
short_name: string;
type: 'coop' | 'ooo' | 'oao' | 'zao' | 'pao' | 'ao';
};
password: string;
public_key: string;
public_key?: string;
referer?: string;
role: 'user' | 'admin';
role: 'user';
type: 'individual' | 'entrepreneur' | 'organization';
username: string;
};
@@ -265,24 +404,11 @@ export interface RGetUsers {
};
}
export interface RJoinCooperative {
body: {
statement: {
hash: string;
meta: object;
public_key: string;
signature: string;
};
username: string;
};
}
export interface RUpdateUser {
body?: {
email?: string;
password?: string;
};
params?: {
username: any;
username: string;
};
}
+81 -91
View File
@@ -1,5 +1,5 @@
import { IEntrepreneurData, IGeneratedDocument, IIndividualData, IOrganizationData } from "coopdoc-generator-ts"
import { SovietContract } from "cooptypes";
import { IEntrepreneurData, IGeneratedDocument, IIndividualData, IOrganizationData } from 'coopdoc-generator-ts';
import { Cooperative, SovietContract } from 'cooptypes';
// Определение унифицированного типа для деталей платежа
export interface PaymentDetails {
@@ -8,73 +8,69 @@ export interface PaymentDetails {
}
export interface IYandexIPN {
type: string;
event: string;
object: {
id: string;
status: string;
paid: boolean;
amount: {
value: string;
currency: string;
};
income_amount: {
value: string;
currency: string;
};
authorization_details: {
rrn: string;
auth_code: string;
three_d_secure: {
applied: boolean;
};
};
created_at: string;
description: string;
expires_at: string;
metadata: Record<string, unknown>;
payment_method: {
type: string;
id: string;
saved: boolean;
card: {
first6: string;
last4: string;
expiry_month: string;
expiry_year: string;
card_type: string;
issuer_country: string;
issuer_name: string;
};
title: string;
};
refundable: boolean;
test: boolean;
type: string;
event: string;
object: {
id: string;
status: string;
paid: boolean;
amount: {
value: string;
currency: string;
};
income_amount: {
value: string;
currency: string;
};
authorization_details: {
rrn: string;
auth_code: string;
three_d_secure: {
applied: boolean;
};
};
created_at: string;
description: string;
expires_at: string;
metadata: Record<string, unknown>;
payment_method: {
type: string;
id: string;
saved: boolean;
card: {
first6: string;
last4: string;
expiry_month: string;
expiry_year: string;
card_type: string;
issuer_country: string;
issuer_name: string;
};
title: string;
};
refundable: boolean;
test: boolean;
};
}
export interface ICreatedPayment {
provider: string
provider: string;
order_id: string | number;
details: PaymentDetails
};
export interface IGetResponse {
results: any[]
page: number
limit: number
details: PaymentDetails;
}
export type IGetResponse<T> = Cooperative.Document.IGetResponse<T>;
export interface IGetActions<T> {
results: IAction[]
page: number
limit: number
results: IAction[];
page: number;
limit: number;
}
export interface IGetTables<T> {
results: ITable[]
page: number
limit: number
results: ITable[];
page: number;
limit: number;
}
export interface ITable {
@@ -89,25 +85,24 @@ export interface ITable {
value?: any;
}
export interface IAction {
transaction_id: string;
account: string;
block_num: number,
block_id: string,
chain_id: string,
block_num: number;
block_id: string;
chain_id: string;
name: string;
receiver: string;
authorization: Array<{
actor: string;
permission: string;
actor: string;
permission: string;
}>;
data: any;
action_ordinal: number;
global_sequence: string;
account_ram_deltas: Array<{
account: string;
delta: number;
account: string;
delta: number;
}>;
console: string;
receipt: {
@@ -116,8 +111,8 @@ export interface IAction {
global_sequence: string;
recv_sequence: string;
auth_sequence: Array<{
account: string;
sequence: string;
account: string;
sequence: string;
}>;
code_sequence: number;
abi_sequence: number;
@@ -127,51 +122,46 @@ export interface IAction {
elapsed: number;
}
export interface IExtendedTable extends ITable {
}
export type IExtendedTable = ITable;
export interface IExtendedAction extends IAction {
user: IIndividualData | IEntrepreneurData | IOrganizationData | null;
}
export interface IComplexStatement {
action: IExtendedAction
document: IGeneratedDocument
action: IExtendedAction;
document: IGeneratedDocument;
}
export interface IComplexDecision {
action: IExtendedAction
document: IGeneratedDocument
votes_for: IExtendedAction[],
votes_against: IExtendedAction[],
action: IExtendedAction;
document: IGeneratedDocument;
votes_for: IExtendedAction[];
votes_against: IExtendedAction[];
}
export interface IComplexAct {
action?: IExtendedAction
document?: IGeneratedDocument
action?: IExtendedAction;
document?: IGeneratedDocument;
}
export interface IComplexDocument {
statement: IComplexStatement
decision: IComplexDecision
acts: IComplexAct[]
statement: IComplexStatement;
decision: IComplexDecision;
acts: IComplexAct[];
}
export interface IGetComplexDocuments {
results: IComplexDocument[]
page: number
limit: number
results: IComplexDocument[];
page: number;
limit: number;
}
export interface IAgenda {
row: SovietContract.Tables.Decisions.IDecision
action: IAction
row: SovietContract.Tables.Decisions.IDecision;
action: IAction;
}
export interface IComplexAgenda extends IAgenda {
document: IComplexDocument
document: IComplexDocument;
}
+3 -11
View File
@@ -1,11 +1,3 @@
/**
* This file was automatically generated by joi-to-typescript
* Do not modify this file manually
*/
export * from './auth.validation';
export * from './coop.validation';
export * from './data.validation';
export * from './notify.validation';
export * from './order.validation';
export * from './user.validation';
export * from './auto-generated';
export * from './mono.types';
export * from './common';
@@ -0,0 +1,8 @@
import { GetInfoResult } from 'eosjs/dist/eosjs-rpc-interfaces';
export type IHealthStatus = 'install' | 'active' | 'maintenance';
export interface IHealthResponse {
status: IHealthStatus;
blockchain: GetInfoResult;
}
+28
View File
@@ -0,0 +1,28 @@
import 'mongoose';
declare module 'mongoose' {
interface PaginateOptions {
sortBy?: string;
populate?: string;
limit?: number;
page?: number;
}
interface QueryResult<T> {
results: T[];
page: number;
limit: number;
totalPages: number;
totalResults: number;
}
interface PaginateModel<T extends Document> extends Model<T> {
paginate(filter: FilterQuery<T>, options: PaginateOptions): Promise<QueryResult<T>>;
}
}
declare global {
interface Error {
statusCode?: number;
subcode?: number;
}
}
@@ -1,43 +1,56 @@
import * as Joi from 'joi';
import { password } from './custom.validation'
import { password } from './custom.validation';
export const login = Joi.object({
body: Joi.object().keys({
username: Joi.string().required(),
password: Joi.string().required(),
}),
})
export const IRefreshTokens = Joi.object({
refreshToken: Joi.string().required(),
});
export const logout = Joi.object({
body: Joi.object().keys({
refreshToken: Joi.string().required(),
}),
})
export const RRefreshTokens = Joi.object({
body: IRefreshTokens.required(),
});
export const refreshTokens = Joi.object({
body: Joi.object().keys({
refreshToken: Joi.string().required(),
}),
})
export const IForgotPassword = Joi.object({
email: Joi.string().email().required(),
});
export const forgotPassword = Joi.object({
body: Joi.object().keys({
email: Joi.string().email().required(),
}),
})
export const RForgotKey = Joi.object({
body: IForgotPassword.required(),
});
export const resetPassword = Joi.object({
query: Joi.object().keys({
token: Joi.string().required(),
}),
body: Joi.object().keys({
password: Joi.string().required().custom(password),
}),
})
// Внутренние параметры
export const ILogin = Joi.object({
signature: Joi.string().required(),
email: Joi.string().email().required(),
now: Joi.string().required(),
});
export const verifyEmail = Joi.object({
query: Joi.object().keys({
token: Joi.string().required(),
}),
})
export const ILogout = Joi.object({
refreshToken: Joi.string().required(),
});
export const IResetKeyBody = Joi.object({
public_key: Joi.string().required(),
token: Joi.string().required(),
});
export const IVerifyEmail = Joi.object({
token: Joi.string().required(),
});
// Внешние запросы
export const RLogin = Joi.object({
body: ILogin.required(),
});
export const RLogout = Joi.object({
body: ILogout.required(),
});
export const RResetKey = Joi.object({
body: IResetKeyBody.required(),
});
export const RVerifyEmail = Joi.object({
query: IVerifyEmail.required(),
});
@@ -4,16 +4,10 @@ export const loadAgenda = Joi.object({
query: Joi.object().keys({
coopname: Joi.string().required(),
}),
})
});
export const loadStaff = Joi.object({
query: Joi.object().keys({
coopname: Joi.string().required(),
}),
})
export const loadMembers = Joi.object({
query: Joi.object().keys({
coopname: Joi.string().required(),
}),
})
});
@@ -1,8 +1,7 @@
import * as Joi from 'joi';
export const IGenerate = Joi.object({
code: Joi.string().required(),
action: Joi.string().required(),
registry_id: Joi.number().required(),
coopname: Joi.string().required(),
username: Joi.string().required(),
generator: Joi.string().optional(),
@@ -11,10 +10,11 @@ export const IGenerate = Joi.object({
created_at: Joi.string().optional(),
block_num: Joi.number().optional(),
timezone: Joi.string().optional(),
links: Joi.array().items(Joi.string()).default([]),
}).unknown(true);
export const RGenerate = Joi.object({
body: IGenerate.required()
body: IGenerate.required(),
}).required();
export const IGetDocuments = Joi.object({
@@ -24,14 +24,14 @@ export const IGetDocuments = Joi.object({
sortBy: Joi.string(),
limit: Joi.number().integer(),
page: Joi.number().integer(),
})
}).unknown(true);
export const RGetDocuments = Joi.object({
query: IGetDocuments
})
query: IGetDocuments,
});
export const RGetMyDocuments = Joi.object({
query: Joi.object().keys({
username: Joi.string()
username: Joi.string(),
}),
})
});
+4 -2
View File
@@ -1,7 +1,9 @@
export * as authValidation from './auth.validation';
export * as userValidation from './user.validation';
export * as documentValidation from './data.validation';
export * as orderValidation from './order.validation';
export * as documentValidation from './document.validation';
export * as orderValidation from './payment.validation';
export * as coopValidation from './coop.validation';
export * as customValidation from './custom.validation';
export * as notifyValidation from './notify.validation';
export * as monoValidation from './mono.validation';
export * as participantValidation from './participant.validation';
@@ -0,0 +1,13 @@
import * as Joi from 'joi';
import { IIndividualData } from './user.validation';
export const IInstall = Joi.array().items(
Joi.object({
role: Joi.string().required().valid('chairman', 'member'),
individual_data: IIndividualData.required(),
})
);
export const RInstall = Joi.object({
body: IInstall.required(),
});
@@ -0,0 +1,21 @@
import * as Joi from 'joi';
export const IDocument = Joi.object().keys({
hash: Joi.string().required(),
signature: Joi.string().required(),
public_key: Joi.string().required(),
meta: Joi.object().required(),
});
export const IJoinCooperative = Joi.object({
username: Joi.string().required(),
statement: IDocument.required(),
wallet_agreement: IDocument.required(),
signature_agreement: IDocument.required(),
privacy_agreement: IDocument.required(),
user_agreement: IDocument.required(),
});
export const RJoinCooperative = Joi.object({
body: IJoinCooperative.required(),
});
@@ -2,21 +2,20 @@ import * as Joi from 'joi';
export const ICreateDeposit = Joi.object().keys({
quantity: Joi.string().required(),
provider: Joi.string().valid('yookassa').required()
})
provider: Joi.string().valid('yookassa').required(),
});
export const ICreateInitialPayment = Joi.object().keys({
provider: Joi.string().valid('yookassa').required()
})
provider: Joi.string().valid('yookassa').required(),
});
export const RCreateDeposit = {
body: ICreateDeposit.required(),
}
};
export const RCreateInitialPayment = {
body: ICreateInitialPayment.required(),
}
};
export const IRecieveIPN = Joi.object({
type: Joi.string().required(),
@@ -28,15 +27,21 @@ export const IRecieveIPN = Joi.object({
amount: Joi.object({
value: Joi.string().required(),
currency: Joi.string().required(),
}).required().unknown(true),
})
.required()
.unknown(true),
income_amount: Joi.object({
value: Joi.string().required(),
currency: Joi.string().required(),
}).required().unknown(true),
})
.required()
.unknown(true),
refunded_amount: Joi.object({
value: Joi.string().required(),
currency: Joi.string().required(),
}).required().unknown(true),
})
.required()
.unknown(true),
authorization_details: Joi.object({
rrn: Joi.string(),
auth_code: Joi.string(),
@@ -62,15 +67,70 @@ export const IRecieveIPN = Joi.object({
issuer_name: Joi.string(),
}).unknown(true),
title: Joi.string(),
}).required().unknown(true),
})
.required()
.unknown(true),
refundable: Joi.boolean(),
test: Joi.boolean(),
}).required().unknown(true),
})
.required()
.unknown(true),
});
export const RRecieveIPN = {
body: IRecieveIPN.required()
}
body: IRecieveIPN.required(),
};
const RussianBankDetailsSchema = Joi.object({
bik: Joi.string().required(),
corr: Joi.string().required(),
kpp: Joi.string().required(),
});
export const IBankAccount = Joi.object({
currency: Joi.string().required().valid('RUB', 'Other'),
card_number: Joi.string().default(''),
bank_name: Joi.string().required(),
account_number: Joi.string().required(),
details: RussianBankDetailsSchema.required(),
});
export const ISbpDetails = Joi.object({
phone: Joi.string().required(),
});
export const RGetListPaymentMethods = Joi.object({
params: {
username: Joi.string().optional(),
},
});
const MethodTypes = Joi.string().valid('sbp', 'bank_transfer');
export const ISavePaymentMethod = Joi.object({
username: Joi.string().required(),
method_id: Joi.number().required(),
method_type: MethodTypes.required(),
data: Joi.alternatives().try(ISbpDetails, IBankAccount).required(),
});
export const RSavePaymentMethod = Joi.object({
params: {
username: Joi.string().required(),
},
body: ISavePaymentMethod.required(),
});
export const IDeletePaymentMethod = Joi.object({
method_id: Joi.number().required(),
});
export const RDeletePaymentMethod = Joi.object({
params: {
username: Joi.string().required(),
},
body: IDeletePaymentMethod.required(),
});
/**
* @swagger
@@ -1,5 +1,6 @@
import * as Joi from 'joi';
import { password, objectId } from './custom.validation';
import { password } from './custom.validation';
import { IBankAccount } from './payment.validation';
export const IIndividualData = Joi.object({
first_name: Joi.string().required(),
@@ -24,20 +25,6 @@ const RussiaDetailsSchema = Joi.object({
ogrn: Joi.string().required(),
});
const RussianBankDetailsSchema = Joi.object({
bik: Joi.string().required(),
corr: Joi.string().required(),
kpp: Joi.string().required(),
});
const IBankAccount = Joi.object({
currency: Joi.string().required().valid('RUB', 'Other'),
card_number: Joi.string().default(''),
bank_name: Joi.string().required(),
account_number: Joi.string().required(),
details: RussianBankDetailsSchema.required(),
});
export const IOrganizationData = Joi.object({
type: Joi.string().valid('coop', 'ooo', 'oao', 'zao', 'pao', 'ao').required(),
is_cooperative: Joi.boolean().required().default(false),
@@ -70,9 +57,8 @@ export const IEntrepreneurData = Joi.object({
export const ICreateUser = Joi.object({
email: Joi.string().required().email(),
password: Joi.string().required().custom(password),
role: Joi.string().required().valid('user', 'admin'),
public_key: Joi.string().required(),
role: Joi.string().required().valid('user'),
public_key: Joi.string().optional(),
username: Joi.string().required().length(12),
referer: Joi.string().length(12).allow('').optional(),
type: Joi.string().required().valid('individual', 'entrepreneur', 'organization'),
@@ -81,11 +67,23 @@ export const ICreateUser = Joi.object({
entrepreneur_data: IEntrepreneurData.optional(),
});
export const IDocument = Joi.object().keys({
hash: Joi.string().required(),
signature: Joi.string().required(),
public_key: Joi.string().required(),
meta: Joi.object().required(),
export const IAddUser = Joi.object({
email: Joi.string().required().email(),
referer: Joi.string().length(12).allow('').optional(),
type: Joi.string().required().valid('individual', 'entrepreneur', 'organization'),
individual_data: IIndividualData.optional(),
organization_data: IOrganizationData.optional(),
entrepreneur_data: IEntrepreneurData.optional(),
spread_initial: Joi.boolean().required(),
created_at: Joi.string().required(),
initial: Joi.string().required(),
minimum: Joi.string().required(),
});
export const RAddUser = Joi.object({
body: IAddUser.required(),
});
// API
@@ -112,25 +110,15 @@ export const RGetUser = Joi.object({
export const RUpdateUser = Joi.object({
params: Joi.object().keys({
username: Joi.required().custom(objectId),
username: Joi.string().required(),
}),
body: Joi.object()
.keys({
email: Joi.string().email(),
password: Joi.string().custom(password),
})
.min(1),
});
export const IJoinCooperative = Joi.object({
username: Joi.string().required(),
statement: IDocument.required(),
});
export const RJoinCooperative = Joi.object({
body: IJoinCooperative.required(),
});
/**
* @swagger
* components:
+37 -43
View File
@@ -1,7 +1,7 @@
import { SovietContract, RegistratorContract } from 'cooptypes';
import { SovietContract, RegistratorContract, DraftContract } from 'cooptypes';
import { IAction, ITable } from '../../src/types/common';
import mongoose from 'mongoose';
import { Cooperative } from 'cooptypes';
import { DocumentsRegistry } from 'coopdoc-generator-ts';
export const insertAction = async (action: IAction) => {
const collection = mongoose.connection.db.collection('actions'); // Замените на имя вашей коллекции
@@ -18,43 +18,6 @@ export const insertDelta = async (delta: ITable) => {
await collection.insertOne(delta);
};
export const fixtureVoskhod = (): Cooperative.Users.IOrganizationData => {
return {
username: 'voskhod',
type: 'coop',
is_cooperative: true,
short_name: 'Voskhod',
full_name: 'ПК ВОСХОД',
represented_by: {
first_name: 'Алексей',
last_name: 'Муравьев',
middle_name: 'Николаевич',
position: 'Председатель',
based_on: 'Решения общего собрания №1',
},
country: 'Russia',
city: 'Moscow',
full_address: '123 Main St, Moscow, Russia',
email: 'contact@orgco.com',
phone: '+71234567890',
details: {
inn: '1234567890',
ogrn: '1234567890123',
},
bank_account: {
account_number: '40817810099910004312',
currency: 'RUB',
card_number: '1234567890123456',
bank_name: 'Sberbank',
details: {
bik: '123456789',
corr: '30101810400000000225',
kpp: '123456789',
},
},
};
};
export const installInitialCooperativeData = async () => {
const delta1 = fixtureDelta(0, 'registrator', 'registrator', 'orgs', '1', {
username: 'voskhod',
@@ -64,10 +27,13 @@ export const installInitialCooperativeData = async () => {
is_cooperative: true,
is_branched: false,
coop_type: 'conscoop',
registration: '2.0000 RUB',
initial: '1.0000 RUB',
minimum: '1.0000 RUB',
} as RegistratorContract.Tables.Organizations.IOrganization);
registration: '200.0000 TRUB',
initial: '100.0000 TRUB',
minimum: '100.0000 TRUB',
org_registration: '2000.0000 TRUB',
org_initial: '1000.0000 TRUB',
org_minimum: '1000.0000 TRUB',
} as RegistratorContract.Tables.Cooperatives.ICooperative);
await insertDelta(delta1);
@@ -89,6 +55,34 @@ export const installInitialCooperativeData = async () => {
} as SovietContract.Tables.Boards.IBoards);
await insertDelta(delta2);
const k = 1;
for (const id in DocumentsRegistry) {
const template = DocumentsRegistry[id as unknown as keyof typeof DocumentsRegistry];
await insertDelta(
fixtureDelta(0, 'draft', 'draft', 'drafts', String(k), {
id: String(k),
creator: 'eosio',
version: String(1),
default_translation_id: String(k),
registry_id: String(id),
title: template.title,
description: template.description,
context: template.context,
model: JSON.stringify(template.model),
} as DraftContract.Tables.Drafts.IDraft)
);
await insertDelta(
fixtureDelta(0, 'draft', 'draft', 'translations', String(k), {
id: String(k),
draft_id: String(k),
lang: 'ru',
data: JSON.stringify(template.translations.ru),
} as DraftContract.Tables.Translations.ITranslation)
);
}
};
export const fixtureDelta = (
@@ -0,0 +1,23 @@
import faker from 'faker';
import { generateUsername } from '../utils/generateUsername';
import { ICreateUser } from '../../src/types';
const email1 = faker.internet.email().toLowerCase();
export const participantOne: ICreateUser = {
email: email1,
username: generateUsername(),
public_key: 'EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV',
role: 'user',
referer: '',
type: 'individual',
individual_data: {
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
middle_name: '',
birthdate: '2023-04-01',
phone: '+1234567890',
email: email1,
full_address: 'Russia, Moscow, Tverskaya street, 1',
},
};

Some files were not shown because too many files have changed in this diff Show More