Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 427b53fcbd | |||
| 2ac7a31be6 | |||
| 4baed6409f | |||
| 2ea0ff0965 | |||
| 88b9a7edce | |||
| 538066b960 | |||
| b10dd1d75a | |||
| f743580b55 | |||
| 0688467302 |
@@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
dist
|
||||
|
||||
Vendored
+14
@@ -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
@@ -0,0 +1,10 @@
|
||||
FROM node:18-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN npm install -g pnpm lerna
|
||||
RUN pnpm install
|
||||
RUN lerna run build
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "pkg-placeholder",
|
||||
"version": "1.0.18",
|
||||
"version": "1.0.19-alpha.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "pkg-placeholder",
|
||||
"version": "1.0.18",
|
||||
"version": "1.0.19-alpha.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^2.16.0",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "cooparser-ts",
|
||||
"type": "module",
|
||||
"version": "1.0.18",
|
||||
"version": "1.0.19-alpha.0",
|
||||
"private": false,
|
||||
"packageManager": "pnpm@9.0.6",
|
||||
"description": "",
|
||||
|
||||
@@ -11,7 +11,6 @@ export class Database {
|
||||
private sync: Collection | undefined
|
||||
|
||||
constructor() {
|
||||
console.log('mongo2: ', mongoUri)
|
||||
this.client = new MongoClient(mongoUri)
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ function getEnvVar(key: string): string {
|
||||
return envVar
|
||||
}
|
||||
export const node_env = getEnvVar('NODE_ENV')
|
||||
console.log('ENV: ', node_env)
|
||||
export const eosioApi = getEnvVar('API')
|
||||
export const shipApi = getEnvVar('SHIP')
|
||||
export const mongoUri = `${getEnvVar('MONGO_EXPLORER_URI')}${node_env === 'test' ? '-test' : ''}`
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "create-nodejs-express-app",
|
||||
"version": "1.7.34",
|
||||
"version": "1.7.35-alpha.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "create-nodejs-express-app",
|
||||
"version": "1.7.34",
|
||||
"version": "1.7.35-alpha.1",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@a2seven/yoo-checkout": "^1.1.4",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "coopback",
|
||||
"version": "1.7.34",
|
||||
"version": "1.7.35-alpha.1",
|
||||
"description": "",
|
||||
"private": true,
|
||||
"bin": "bin/createNodejsApp.js",
|
||||
|
||||
@@ -18,7 +18,7 @@ export const loadAgenda = catchAsync(async (req: Request, res: Response) => {
|
||||
const { coopname } = req.query;
|
||||
const agenda = await coopService.loadAgenda(coopname as string);
|
||||
|
||||
const complexAgenda: Cooperative.Documents.IComplexAgenda[] = [];
|
||||
const complexAgenda: Cooperative.Document.IComplexAgenda[] = [];
|
||||
|
||||
for (const { action, table } of agenda) {
|
||||
const documents = await documentService.buildComplexDocument(action);
|
||||
|
||||
@@ -5,3 +5,4 @@ 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,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();
|
||||
});
|
||||
@@ -2,11 +2,11 @@ import http from 'http-status';
|
||||
import ApiError from '../utils/ApiError';
|
||||
import catchAsync from '../utils/catchAsync';
|
||||
import { userService, tokenService, emailService, blockchainService } from '../services';
|
||||
import { IAddUser, ICreateUser, RCreateUser, RJoinCooperative } from '../types';
|
||||
import { IAddUser, ICreateUser, RCreateUser } from '../types';
|
||||
import httpStatus from 'http-status';
|
||||
import pick from '../utils/pick';
|
||||
import { IGetResponse } from '../types/common';
|
||||
import { IUser } from '../models/user.model';
|
||||
import { IUser, userStatus } from '../models/user.model';
|
||||
import { Request, Response } from 'express';
|
||||
import { generateUsername } from '../../tests/utils/generateUsername';
|
||||
import config from '../config/config';
|
||||
@@ -45,7 +45,7 @@ export const addUser = catchAsync(async (req: Request, res: Response) => {
|
||||
};
|
||||
|
||||
const user = await userService.createUser(newUser);
|
||||
user.status = 'registered';
|
||||
user.status = userStatus['4_Registered'];
|
||||
user.is_registered = true;
|
||||
await user.save();
|
||||
|
||||
@@ -58,11 +58,10 @@ export const addUser = catchAsync(async (req: Request, res: Response) => {
|
||||
coopname: config.coopname,
|
||||
meta: '',
|
||||
});
|
||||
console.log('user: ', user);
|
||||
|
||||
const token = await tokenService.generateInviteToken(user.email);
|
||||
await emailService.sendInviteEmail(req.body.email, token);
|
||||
} catch (e: any) {
|
||||
console.log('on e: ', e);
|
||||
logger.warn('error on add user: ', e);
|
||||
await userService.deleteUserByUsername(newUser.username);
|
||||
throw new ApiError(httpStatus.BAD_GATEWAY, e.message);
|
||||
@@ -71,12 +70,6 @@ export const addUser = catchAsync(async (req: Request, res: Response) => {
|
||||
res.status(httpStatus.CREATED).send({ user });
|
||||
});
|
||||
|
||||
export const joinCooperative = catchAsync(async (req: RJoinCooperative, res) => {
|
||||
await userService.joinCooperative(req.body);
|
||||
|
||||
res.status(httpStatus.OK).send();
|
||||
});
|
||||
|
||||
export const getUsers = catchAsync(async (req, res) => {
|
||||
const filter = pick(req.query, ['username', 'role']);
|
||||
const options = pick(req.query, ['sortBy', 'limit', 'page']);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import mongoose, { Schema } from 'mongoose';
|
||||
import { paginate, toJSON } from './plugins';
|
||||
|
||||
export enum tempdocType {
|
||||
JoinStatement = 'joinStatement',
|
||||
WalletAgreement = 'walletAgreement',
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -1,17 +1,25 @@
|
||||
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/document.service';
|
||||
import { Cooperative } from 'cooptypes';
|
||||
|
||||
const { isEmail } = validator;
|
||||
const { compare, hash } = bcryptjs;
|
||||
|
||||
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;
|
||||
has_account: boolean;
|
||||
@@ -21,12 +29,12 @@ export interface IUser {
|
||||
email: string;
|
||||
role: string;
|
||||
is_email_verified: boolean;
|
||||
statement: {
|
||||
hash: string;
|
||||
meta: object;
|
||||
public_key: string;
|
||||
signature: string;
|
||||
};
|
||||
// statement: {
|
||||
// hash: string;
|
||||
// meta: object;
|
||||
// public_key: string;
|
||||
// signature: string;
|
||||
// };
|
||||
private_data:
|
||||
| Cooperative.Users.IIndividualData
|
||||
| Cooperative.Users.IEntrepreneurData
|
||||
@@ -52,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,
|
||||
@@ -101,24 +109,24 @@ 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,
|
||||
|
||||
@@ -7,6 +7,7 @@ import coopRoute from './coop.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';
|
||||
|
||||
@@ -14,7 +15,7 @@ const router = Router();
|
||||
|
||||
const defaultRoutes = [
|
||||
{
|
||||
path: '/mono',
|
||||
path: '/system',
|
||||
route: monoRoute,
|
||||
},
|
||||
{
|
||||
@@ -25,6 +26,10 @@ const defaultRoutes = [
|
||||
path: '/users',
|
||||
route: userRoute,
|
||||
},
|
||||
{
|
||||
path: '/participants',
|
||||
route: participantsRoute,
|
||||
},
|
||||
{
|
||||
path: '/documents',
|
||||
route: dataRoute,
|
||||
|
||||
@@ -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;
|
||||
@@ -11,8 +11,6 @@ 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
|
||||
|
||||
@@ -8,6 +8,9 @@ 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 });
|
||||
|
||||
@@ -95,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,
|
||||
@@ -113,11 +116,28 @@ async function registerBlockchainAccount(user: IUser, orderData: GatewayContract
|
||||
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) },
|
||||
};
|
||||
|
||||
//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',
|
||||
program_id: 1,
|
||||
draft_registry_id: 1,
|
||||
document: { ...walletAgreement.document, meta: JSON.stringify(walletAgreement.document.meta) },
|
||||
};
|
||||
|
||||
const actions = [
|
||||
@@ -165,6 +185,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(
|
||||
@@ -209,11 +240,11 @@ async function createBoard(data: SovietContract.Actions.Boards.CreateBoard.ICrea
|
||||
}
|
||||
|
||||
async function createOrder(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: 'deposit',
|
||||
authorization: [
|
||||
{
|
||||
@@ -241,7 +272,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 = [
|
||||
{
|
||||
@@ -269,11 +300,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: [
|
||||
{
|
||||
@@ -355,7 +386,7 @@ export async function changeKey(data: RegistratorContract.Actions.ChangeKey.ICha
|
||||
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;
|
||||
}
|
||||
@@ -363,7 +394,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,23 +6,23 @@ import ApiError from '../utils/ApiError';
|
||||
import httpStatus from 'http-status';
|
||||
import logger from '../config/logger';
|
||||
|
||||
export 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),
|
||||
@@ -40,7 +40,7 @@ export const loadAgenda = async (coopname: string): Promise<Cooperative.Document
|
||||
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);
|
||||
|
||||
@@ -12,22 +12,33 @@ 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 && user.type != 'service') {
|
||||
@@ -39,8 +50,6 @@ export async function buildComplexDocument(
|
||||
};
|
||||
|
||||
statement = { action, document };
|
||||
} else {
|
||||
// throw new ApiError(400, 'Ошибка, один из пользователей не найден. Обратитесь в поддержку.');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,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),
|
||||
@@ -65,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,
|
||||
@@ -74,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,
|
||||
@@ -87,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 = 1,
|
||||
limit = 100
|
||||
): Promise<Cooperative.Documents.IGetComplexDocuments> => {
|
||||
): 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,
|
||||
@@ -111,7 +124,7 @@ export const queryDocuments = async (
|
||||
}
|
||||
);
|
||||
|
||||
const response: Cooperative.Documents.IGetComplexDocuments = {
|
||||
const response: Cooperative.Document.IGetComplexDocuments = {
|
||||
results: [],
|
||||
page,
|
||||
limit,
|
||||
@@ -122,6 +135,6 @@ export const queryDocuments = async (
|
||||
|
||||
if (complexDocument.decision.action) response.results.push(complexDocument);
|
||||
}
|
||||
|
||||
console.log(response);
|
||||
return response;
|
||||
};
|
||||
|
||||
@@ -8,3 +8,4 @@ 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';
|
||||
|
||||
@@ -7,7 +7,7 @@ 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 } from '../models/user.model';
|
||||
import { IUser, userStatus } from '../models/user.model';
|
||||
import axios from 'axios';
|
||||
import { getBlockchainInfo } from './blockchain.service';
|
||||
import { RegistratorContract } from 'cooptypes';
|
||||
@@ -61,7 +61,7 @@ export const install = async (soviet: IInstall): Promise<void> => {
|
||||
};
|
||||
|
||||
const user = await userService.createUser(createUser);
|
||||
user.status = 'registered';
|
||||
user.status = userStatus['4_Registered'];
|
||||
user.is_registered = true;
|
||||
await user.save();
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
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);
|
||||
console.log(data);
|
||||
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);
|
||||
|
||||
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 }
|
||||
);
|
||||
|
||||
user.status = userStatus['2_Joined'];
|
||||
await user.save({ session });
|
||||
});
|
||||
|
||||
session.endSession();
|
||||
};
|
||||
@@ -12,6 +12,7 @@ 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;
|
||||
|
||||
@@ -241,7 +242,7 @@ export async function catchIPN(ipnBody: IYandexIPN) {
|
||||
});
|
||||
|
||||
logger.info('Зарегистрирован новый пользователь: ', user.username);
|
||||
user.status = 'registered';
|
||||
user.status = userStatus['4_Registered'];
|
||||
user.is_registered = true;
|
||||
} else if (order.type === 'deposit') {
|
||||
await blockchainService.completeOrder({
|
||||
@@ -271,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();
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import http from 'http-status';
|
||||
import { User } from '../models';
|
||||
import ApiError from '../utils/ApiError';
|
||||
import { generator } from './document.service';
|
||||
import { ICreateUser, IJoinCooperative } from '../types/auto-generated/user.validation';
|
||||
import { ICreateUser } from '../types/auto-generated/user.validation';
|
||||
import { PublicKey, Signature } from '@wharfkit/antelope';
|
||||
import faker from 'faker';
|
||||
|
||||
@@ -57,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
|
||||
|
||||
@@ -8,13 +8,13 @@ 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;
|
||||
@@ -39,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;
|
||||
|
||||
@@ -8,5 +8,6 @@ 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';
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Do not modify this file manually
|
||||
*/
|
||||
|
||||
export type IInstall = {
|
||||
export type IInstall = ({
|
||||
individual_data: {
|
||||
birthdate: string;
|
||||
email: string;
|
||||
@@ -14,10 +14,10 @@ export type IInstall = {
|
||||
phone: string;
|
||||
};
|
||||
role: 'chairman' | 'member';
|
||||
}[];
|
||||
})[];
|
||||
|
||||
export interface RInstall {
|
||||
body: {
|
||||
body: ({
|
||||
individual_data: {
|
||||
birthdate: string;
|
||||
email: string;
|
||||
@@ -28,5 +28,5 @@ export interface RInstall {
|
||||
phone: string;
|
||||
};
|
||||
role: 'chairman' | 'member';
|
||||
}[];
|
||||
})[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 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 {
|
||||
statement: {
|
||||
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: {
|
||||
statement: {
|
||||
hash: string;
|
||||
meta: object;
|
||||
public_key: string;
|
||||
signature: string;
|
||||
};
|
||||
username: string;
|
||||
wallet_agreement: {
|
||||
hash: string;
|
||||
meta: object;
|
||||
public_key: string;
|
||||
signature: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -158,13 +158,6 @@ export interface ICreateUser {
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface IDocument {
|
||||
hash: string;
|
||||
meta: object;
|
||||
public_key: string;
|
||||
signature: string;
|
||||
}
|
||||
|
||||
export interface IEntrepreneurData {
|
||||
bank_account: {
|
||||
account_number: string;
|
||||
@@ -202,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;
|
||||
@@ -421,18 +404,6 @@ 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;
|
||||
|
||||
@@ -59,7 +59,7 @@ export interface ICreatedPayment {
|
||||
details: PaymentDetails;
|
||||
}
|
||||
|
||||
export type IGetResponse<T> = Cooperative.Documents.IGetResponse<T>;
|
||||
export type IGetResponse<T> = Cooperative.Document.IGetResponse<T>;
|
||||
|
||||
export interface IGetActions<T> {
|
||||
results: IAction[];
|
||||
|
||||
@@ -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,6 +10,7 @@ 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({
|
||||
|
||||
@@ -6,3 +6,4 @@ 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,18 @@
|
||||
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(),
|
||||
});
|
||||
|
||||
export const RJoinCooperative = Joi.object({
|
||||
body: IJoinCooperative.required(),
|
||||
});
|
||||
@@ -86,13 +86,6 @@ export const RAddUser = Joi.object({
|
||||
body: IAddUser.required(),
|
||||
});
|
||||
|
||||
export const IDocument = Joi.object().keys({
|
||||
hash: Joi.string().required(),
|
||||
signature: Joi.string().required(),
|
||||
public_key: Joi.string().required(),
|
||||
meta: Joi.object().required(),
|
||||
});
|
||||
|
||||
// API
|
||||
|
||||
export const RCreateUser = Joi.object({
|
||||
@@ -126,15 +119,6 @@ export const RUpdateUser = Joi.object({
|
||||
.min(1),
|
||||
});
|
||||
|
||||
export const IJoinCooperative = Joi.object({
|
||||
username: Joi.string().required(),
|
||||
statement: IDocument.required(),
|
||||
});
|
||||
|
||||
export const RJoinCooperative = Joi.object({
|
||||
body: IJoinCooperative.required(),
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* components:
|
||||
|
||||
@@ -3,6 +3,11 @@ import { defineBuildConfig } from 'unbuild'
|
||||
export default defineBuildConfig({
|
||||
entries: [
|
||||
'src/index',
|
||||
// {
|
||||
// input: 'src/Templates/index',
|
||||
// outDir: 'dist',
|
||||
// name: 'Templates',
|
||||
// },
|
||||
],
|
||||
declaration: true,
|
||||
clean: false,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "coopdoc-generator-ts",
|
||||
"type": "module",
|
||||
"version": "1.0.78",
|
||||
"version": "1.0.79-alpha.1",
|
||||
"private": false,
|
||||
"packageManager": "pnpm@9.0.6",
|
||||
"description": "",
|
||||
@@ -17,6 +17,7 @@
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.cjs"
|
||||
}
|
||||
|
||||
-7455
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,39 @@
|
||||
import { WalletAgreement } from '../templates'
|
||||
import { DocFactory } from '../Factory'
|
||||
import type { IGeneratedDocument, IMetaDocument, ITemplate } from '../Interfaces'
|
||||
import type { MongoDBConnector } from '../Services/Databazor'
|
||||
|
||||
export { WalletAgreement as Template } from '../templates'
|
||||
|
||||
export class Factory extends DocFactory<WalletAgreement.Action> {
|
||||
constructor(storage: MongoDBConnector) {
|
||||
super(storage)
|
||||
}
|
||||
|
||||
async generateDocument(options: WalletAgreement.Action): Promise<IGeneratedDocument> {
|
||||
let template: ITemplate<WalletAgreement.Model>
|
||||
|
||||
if (process.env.SOURCE === 'local') {
|
||||
template = WalletAgreement.Template
|
||||
}
|
||||
else {
|
||||
template = await this.getTemplate(options.coopname, WalletAgreement.registry_id, options.block_num)
|
||||
}
|
||||
|
||||
const meta: IMetaDocument = await super.getMeta({ title: template.title, ...options })
|
||||
|
||||
const combinedData: WalletAgreement.Model = {
|
||||
meta,
|
||||
}
|
||||
|
||||
await super.validate(combinedData, template.model)
|
||||
|
||||
const translation = template.translations[meta.lang]
|
||||
|
||||
const document: IGeneratedDocument = await super.generatePDF(null, template.context, combinedData, translation, meta)
|
||||
|
||||
await super.saveDraft(document)
|
||||
|
||||
return document
|
||||
}
|
||||
}
|
||||
+14
-13
@@ -1,27 +1,25 @@
|
||||
import { DraftContract } from 'cooptypes'
|
||||
import type { IJoinCoopAction } from '../Templates/100.ParticipantApplication'
|
||||
import { DocFactory } from '../Factory'
|
||||
import type { IGeneratedDocument, IMetaDocument, ITemplate } from '../Interfaces'
|
||||
import type { MongoDBConnector } from '../Services/Databazor'
|
||||
import { ParticipantApplicationTemplate } from '../Templates/100.ParticipantApplication'
|
||||
import DataService from '../Services/Databazor/DataService'
|
||||
import type { IGenerateJoinCoop } from '../Interfaces/Actions'
|
||||
import { ParticipantApplication } from '../templates'
|
||||
|
||||
export const registry_id = 100
|
||||
export { ParticipantApplication as Template } from '../templates'
|
||||
|
||||
export class JoinCoopTemplateFactory extends DocFactory {
|
||||
export class Factory extends DocFactory<ParticipantApplication.Action> {
|
||||
constructor(storage: MongoDBConnector) {
|
||||
super(storage)
|
||||
}
|
||||
|
||||
async generateDocument(options: IGenerateJoinCoop): Promise<IGeneratedDocument> {
|
||||
let template: ITemplate<IJoinCoopAction>
|
||||
async generateDocument(options: ParticipantApplication.Action): Promise<IGeneratedDocument> {
|
||||
let template: ITemplate<ParticipantApplication.Model>
|
||||
|
||||
if (process.env.SOURCE === 'local') {
|
||||
template = ParticipantApplicationTemplate
|
||||
template = ParticipantApplication.Template
|
||||
}
|
||||
else {
|
||||
template = await this.getTemplate(DraftContract.contractName.production, registry_id, options.block_num)
|
||||
template = await this.getTemplate(DraftContract.contractName.production, ParticipantApplication.registry_id, options.block_num)
|
||||
}
|
||||
|
||||
const user = await super.getUser(options.username, options.block_num)
|
||||
@@ -33,8 +31,11 @@ export class JoinCoopTemplateFactory extends DocFactory {
|
||||
const coop = await super.getCooperative(options.coopname, options.block_num)
|
||||
|
||||
let { signature, ...modifiedOptions } = options
|
||||
const meta: IMetaDocument = await super.getMeta({ title: template.title, ...modifiedOptions }) // Генерируем мета-данные
|
||||
|
||||
const meta: IMetaDocument = await super.getMeta({ registry_id, title: template.title, ...modifiedOptions }) // Генерируем мета-данные
|
||||
console.log('generator options: ', options)
|
||||
|
||||
console.log('generator meta: ', meta)
|
||||
|
||||
interface SignatureData {
|
||||
username: string
|
||||
@@ -42,7 +43,7 @@ export class JoinCoopTemplateFactory extends DocFactory {
|
||||
signature: string
|
||||
}
|
||||
|
||||
const data_service = new DataService<SignatureData>(this.storage, 'SignatureData')
|
||||
const data_service = new DataService<SignatureData>(this.storage, 'signatures')
|
||||
|
||||
// пропуск сохранения необходим при вступлении для того, чтобы подготовить документ только для отображения без сохранения
|
||||
if (!options.skip_save) {
|
||||
@@ -60,12 +61,12 @@ export class JoinCoopTemplateFactory extends DocFactory {
|
||||
}
|
||||
else {
|
||||
// если подпись указана - сохраняем в хранилище
|
||||
const data_service = new DataService<SignatureData>(this.storage, 'SignatureData')
|
||||
const data_service = new DataService<SignatureData>(this.storage, 'signatures')
|
||||
await data_service.save({ username: options.username, block_num: meta.block_num, signature })
|
||||
}
|
||||
}
|
||||
|
||||
const combinedData: IJoinCoopAction = { ...userData, meta, coop, type: user.type, signature }
|
||||
const combinedData: ParticipantApplication.Model = { ...userData, meta, coop, type: user.type, signature }
|
||||
|
||||
// валидируем скомбинированные данные
|
||||
await super.validate(combinedData, template.model)
|
||||
+11
-14
@@ -1,33 +1,31 @@
|
||||
import { DraftContract } from 'cooptypes'
|
||||
import type { IJoinCoopDecisionAction } from '../Templates/501.DecisionOfParticipantApplication'
|
||||
import { type Cooperative, DraftContract } from 'cooptypes'
|
||||
import { DocFactory } from '../Factory'
|
||||
import type {
|
||||
IDecisionData,
|
||||
IGeneratedDocument,
|
||||
IMetaDocument,
|
||||
ITemplate,
|
||||
} from '../Interfaces'
|
||||
import type { MongoDBConnector } from '../Services/Databazor'
|
||||
import { DecisionOfParticipantApplicationTemplate } from '../Templates/501.DecisionOfParticipantApplication'
|
||||
import type { IGenerateJoinCoopDecision } from '../Interfaces/Actions'
|
||||
|
||||
export const registry_id = 501
|
||||
import { DecisionOfParticipantApplication } from '../templates'
|
||||
|
||||
export class DecisionOfJoinCoopTemplateFactory extends DocFactory {
|
||||
export { DecisionOfParticipantApplication as Template } from '../templates'
|
||||
|
||||
export class Factory extends DocFactory<DecisionOfParticipantApplication.Action> {
|
||||
constructor(storage: MongoDBConnector) {
|
||||
super(storage)
|
||||
}
|
||||
|
||||
async generateDocument(
|
||||
options: IGenerateJoinCoopDecision,
|
||||
options: DecisionOfParticipantApplication.Action,
|
||||
): Promise<IGeneratedDocument> {
|
||||
let template: ITemplate<IJoinCoopDecisionAction>
|
||||
let template: ITemplate<DecisionOfParticipantApplication.Model>
|
||||
|
||||
if (process.env.SOURCE === 'local') {
|
||||
template = DecisionOfParticipantApplicationTemplate
|
||||
template = DecisionOfParticipantApplication.Template
|
||||
}
|
||||
else {
|
||||
template = await this.getTemplate(DraftContract.contractName.production, registry_id, options.block_num)
|
||||
template = await this.getTemplate(DraftContract.contractName.production, DecisionOfParticipantApplication.registry_id, options.block_num)
|
||||
}
|
||||
|
||||
const user = await super.getUser(options.username, options.block_num)
|
||||
@@ -40,19 +38,18 @@ export class DecisionOfJoinCoopTemplateFactory extends DocFactory {
|
||||
|
||||
// TODO необходимо строго типизировать мета-данные документов друг под друга!
|
||||
const meta: IMetaDocument = await super.getMeta({
|
||||
registry_id,
|
||||
title: template.title,
|
||||
...options,
|
||||
}) // Генерируем мета-данные
|
||||
|
||||
const decision: IDecisionData = await super.getDecision(
|
||||
const decision: Cooperative.Document.IDecisionData = await super.getDecision(
|
||||
coop,
|
||||
options.coopname,
|
||||
options.decision_id,
|
||||
meta.created_at,
|
||||
)
|
||||
|
||||
const combinedData: IJoinCoopDecisionAction = {
|
||||
const combinedData: DecisionOfParticipantApplication.Model = {
|
||||
...userData,
|
||||
meta,
|
||||
coop,
|
||||
@@ -1,3 +1,3 @@
|
||||
export * as JoinCoop from './registrator.joincoop'
|
||||
export * as JoinCoopDecision from './registrator.joincoopdec'
|
||||
export * as JoinProgram from './soviet.joinprog'
|
||||
export * as ParticipantApplication from './100.ParticipantApplication'
|
||||
export * as DecisionOfParticipantApplication from './501.DecisionOfParticipantApplication'
|
||||
export * as WalletAgreement from './1.WalletAgreement'
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import { DocFactory } from '../Factory'
|
||||
import type { IGeneratedDocument, IMetaDocument } from '../Interfaces'
|
||||
import type { MongoDBConnector } from '../Services/Databazor'
|
||||
import { DocumentsRegistry } from '../Templates'
|
||||
import type { IGenerateJoinProgram } from '../Interfaces/Actions'
|
||||
import type { IJoinProgram } from '../Templates/1000.ProgramProvision'
|
||||
|
||||
export class JoinProgramTemplateFactory extends DocFactory {
|
||||
constructor(storage: MongoDBConnector) {
|
||||
super(storage)
|
||||
}
|
||||
|
||||
async generateDocument(options: IGenerateJoinProgram): Promise<IGeneratedDocument> {
|
||||
// TODO
|
||||
/**
|
||||
* Получаем шаблон программы по registry_id из options (registry_id)
|
||||
* Получаем из бд парсера
|
||||
*/
|
||||
|
||||
let template
|
||||
|
||||
if (process.env.SOURCE === 'local') {
|
||||
template = DocumentsRegistry[options.registry_id as keyof typeof DocumentsRegistry]
|
||||
}
|
||||
else {
|
||||
template = await this.getTemplate(options.coopname, options.registry_id, options.block_num)
|
||||
}
|
||||
|
||||
const coop = await super.getCooperative(options.coopname, options.block_num)
|
||||
|
||||
const meta: IMetaDocument = await super.getMeta({
|
||||
title: template.title,
|
||||
...options,
|
||||
}) // Генерируем мета-данные
|
||||
|
||||
const combinedData: IJoinProgram = {
|
||||
meta,
|
||||
coop,
|
||||
protocol_number: options.protocol_number,
|
||||
protocol_day_month_year: options.protocol_day_month_year,
|
||||
}
|
||||
|
||||
// валидируем скомбинированные данные
|
||||
await super.validate(combinedData, template.model)
|
||||
|
||||
// получаем комплекс перевода
|
||||
const translation = template.translations[meta.lang]
|
||||
|
||||
// генерируем документ
|
||||
const document: IGeneratedDocument = await super.generatePDF(null, template.context, combinedData, translation, meta)
|
||||
|
||||
// сохраняем его в бд
|
||||
await super.saveDraft(document)
|
||||
|
||||
return document
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { JSONSchemaType } from 'ajv'
|
||||
import moment from 'moment-timezone'
|
||||
import type { Cooperative as TCooperative } from 'cooptypes'
|
||||
import { DraftContract, SovietContract } from 'cooptypes'
|
||||
import type { ICombinedData, IGeneratedDocument, IMetaDocument, IMetaDocumentPartial, ITemplate, ITranslations, externalDataTypes } from '../Interfaces'
|
||||
import type { MongoDBConnector } from '../Services/Databazor'
|
||||
import { Individual, Organization } from '../Models'
|
||||
import type { IDecisionData, IGenerate } from '../Interfaces/Documents'
|
||||
import type { IGenerate } from '../Interfaces/Documents'
|
||||
import { PDFService } from '../Services/Generator'
|
||||
import packageJson from '../../package.json'
|
||||
import { Validator } from '../Services/Validator'
|
||||
@@ -17,8 +18,8 @@ import { getCurrentBlock } from '../Utils/getCurrentBlock'
|
||||
|
||||
const packageVersion = packageJson.version
|
||||
|
||||
export abstract class DocFactory {
|
||||
abstract generateDocument(options: IGenerate): Promise<IGeneratedDocument>
|
||||
export abstract class DocFactory<T extends IGenerate> {
|
||||
abstract generateDocument(options: T): Promise<IGeneratedDocument>
|
||||
|
||||
public storage: MongoDBConnector
|
||||
|
||||
@@ -77,12 +78,12 @@ export abstract class DocFactory {
|
||||
return coop
|
||||
}
|
||||
|
||||
async getDecision(coop: CooperativeData, coopname: string, decision_id: number, created_at: string): Promise<IDecisionData> {
|
||||
async getDecision(coop: CooperativeData, coopname: string, decision_id: number, created_at: string): Promise<TCooperative.Document.IDecisionData> {
|
||||
const votes_for_actions = (await getFetch(`${getEnvVar('SIMPLE_EXPLORER_API')}/get-actions`, new URLSearchParams({
|
||||
filter: JSON.stringify({
|
||||
'account': process.env.SOVIET_CONTRACT,
|
||||
'account': SovietContract.contractName.production,
|
||||
'name': SovietContract.Actions.Decisions.VoteFor.actionName,
|
||||
'receiver': process.env.SOVIET_CONTRACT,
|
||||
'receiver': SovietContract.contractName.production,
|
||||
'data.decision_id': String(decision_id),
|
||||
'data.coopname': coopname,
|
||||
}),
|
||||
@@ -93,9 +94,9 @@ export abstract class DocFactory {
|
||||
|
||||
const votes_against_actions = (await getFetch(`${getEnvVar('SIMPLE_EXPLORER_API')}/get-actions`, new URLSearchParams({
|
||||
filter: JSON.stringify({
|
||||
'account': process.env.SOVIET_CONTRACT,
|
||||
'account': SovietContract.contractName.production,
|
||||
'name': SovietContract.Actions.Decisions.VoteAgainst.actionName,
|
||||
'receiver': process.env.SOVIET_CONTRACT,
|
||||
'receiver': SovietContract.contractName.production,
|
||||
'data.decision_id': String(decision_id),
|
||||
'data.coopname': coopname,
|
||||
}),
|
||||
@@ -146,7 +147,7 @@ export abstract class DocFactory {
|
||||
'code': DraftContract.contractName.production,
|
||||
'scope': scope,
|
||||
'table': 'translations',
|
||||
'value.draft_id': String(draft.id),
|
||||
'value.draft_id': String(draft.registry_id),
|
||||
...block_filter,
|
||||
}),
|
||||
}))
|
||||
@@ -201,12 +202,11 @@ export abstract class DocFactory {
|
||||
}
|
||||
|
||||
async getMeta<T extends IMetaDocumentPartial>({
|
||||
code,
|
||||
action,
|
||||
title,
|
||||
username,
|
||||
coopname,
|
||||
registry_id,
|
||||
links = [],
|
||||
lang = 'ru',
|
||||
generator = 'coopjs',
|
||||
version = packageVersion, // TODO перенести в .env
|
||||
@@ -220,8 +220,8 @@ export abstract class DocFactory {
|
||||
if (!title)
|
||||
throw new Error('Заголовок документа должен быть установлен')
|
||||
|
||||
if (!code || !action)
|
||||
throw new Error('Параметры действия должны быть переданы')
|
||||
if (!registry_id)
|
||||
throw new Error('Параметр номера документа в реестре должен быть передан')
|
||||
|
||||
if (created_at)
|
||||
dateWithTimezone = moment.tz(created_at, 'DD.MM.YYYY HH:mm', timezone).format('DD.MM.YYYY HH:mm').toString()
|
||||
@@ -232,12 +232,11 @@ export abstract class DocFactory {
|
||||
block_num = await getCurrentBlock()
|
||||
|
||||
return {
|
||||
code,
|
||||
action,
|
||||
title,
|
||||
lang,
|
||||
registry_id,
|
||||
generator,
|
||||
links,
|
||||
version,
|
||||
coopname,
|
||||
username,
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import type { Cooperative } from 'cooptypes'
|
||||
|
||||
export type IGenerateJoinCoopDecision = Cooperative.Documents.IGenerateJoinCoopDecision
|
||||
export type IGenerateJoinCoop = Cooperative.Documents.IGenerateJoinCoop
|
||||
export type IGenerateJoinProgram = Cooperative.Documents.IGenerateJoinProgram
|
||||
export type IGenerateJoinCoopDecision = Cooperative.Document.IGenerateJoinCoopDecision
|
||||
|
||||
/**
|
||||
* Интерфейс генерации заявления на вступление в кооператив
|
||||
*/
|
||||
export interface IGenerateJoinCoop extends IGenerate {
|
||||
signature: string
|
||||
skip_save: boolean
|
||||
}
|
||||
|
||||
export type IGenerateAgreement = Cooperative.Document.IGenerateAgreement
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
import type { JSONSchemaType } from 'ajv'
|
||||
import type { Cooperative } from 'cooptypes'
|
||||
import type { DocumentsMappingByActionAndCode } from '../Templates/registry'
|
||||
import type { Registry } from '../templates/registry'
|
||||
import type { CooperativeData } from '../Models/Cooperative'
|
||||
import type { ExternalEntrepreneurData, ExternalIndividualData, ExternalOrganizationData } from '../Models'
|
||||
|
||||
// Определение базового интерфейса для мета-информации
|
||||
export type IMetaDocument = Cooperative.Documents.IMetaDocument
|
||||
|
||||
export interface IDecisionData {
|
||||
id: number
|
||||
date: string
|
||||
time: string
|
||||
votes_for: number
|
||||
votes_against: number
|
||||
votes_abstained: number
|
||||
voters_percent: number
|
||||
}
|
||||
export type IMetaDocument = Cooperative.Document.IMetaDocument
|
||||
|
||||
export interface IGeneratedDocument {
|
||||
full_title?: string
|
||||
@@ -43,11 +33,11 @@ export interface ICombinedData {
|
||||
individual?: ExternalIndividualData
|
||||
organization?: ExternalOrganizationData
|
||||
entrepreneur?: ExternalEntrepreneurData
|
||||
coop: CooperativeData
|
||||
coop?: CooperativeData
|
||||
meta: IMetaDocument
|
||||
}
|
||||
|
||||
export type Actions = keyof DocumentsMappingByActionAndCode
|
||||
export type Numbers = keyof typeof Registry
|
||||
export type LangType = 'ru'
|
||||
|
||||
export interface IMetaDocumentPartial extends Partial<IMetaDocument> {
|
||||
@@ -57,10 +47,4 @@ export interface IMetaDocumentPartial extends Partial<IMetaDocument> {
|
||||
title: string
|
||||
}
|
||||
|
||||
export interface IGenerate extends Omit<Partial<IMetaDocument>, 'registry_id' | 'title'> {
|
||||
code: string
|
||||
action: string
|
||||
coopname: string
|
||||
username: string
|
||||
[key: string]: any
|
||||
}
|
||||
export type IGenerate = Cooperative.Document.IGenerate
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
export * from './Documents'
|
||||
export * from './BankAccounts'
|
||||
export * from './Storage'
|
||||
export * from './Actions'
|
||||
|
||||
@@ -46,7 +46,7 @@ export class Cooperative {
|
||||
constructor(storage: MongoDBConnector) {
|
||||
this.db = storage
|
||||
this.cooperative = null
|
||||
this.data_service = new DataService<CooperativeData>(storage, 'CooperativeData')
|
||||
this.data_service = new DataService<CooperativeData>(storage, 'cooperatives')
|
||||
}
|
||||
|
||||
async getOne(username: string, block_num?: number): Promise<CooperativeData> {
|
||||
|
||||
@@ -24,7 +24,7 @@ export class Entrepreneur {
|
||||
constructor(storage: MongoDBConnector, data?: ExternalEntrepreneurData) {
|
||||
this.db = storage
|
||||
this.entrepreneur = data
|
||||
this.data_service = new DataService<InternalEntrepreneurData>(storage, 'EntrepreneurData')
|
||||
this.data_service = new DataService<InternalEntrepreneurData>(storage, 'entrepreneurs')
|
||||
}
|
||||
|
||||
validate(): ValidateResult {
|
||||
@@ -74,7 +74,7 @@ export class Entrepreneur {
|
||||
return entr as ExternalEntrepreneurData
|
||||
}
|
||||
|
||||
async getMany(filter: Filter<InternalEntrepreneurData>): Promise<Cooperative.Documents.IGetResponse<ExternalEntrepreneurData>> {
|
||||
async getMany(filter: Filter<InternalEntrepreneurData>): Promise<Cooperative.Document.IGetResponse<ExternalEntrepreneurData>> {
|
||||
const response = await this.data_service.getMany({ deleted: false, ...filter }, 'username')
|
||||
const entrepreneurs = response.results
|
||||
const blockFilter = filter.block_num ? { block_num: filter.block_num } : {}
|
||||
@@ -83,7 +83,7 @@ export class Entrepreneur {
|
||||
entr.bank_account = (await (new PaymentMethod(this.db).getOne({ ...blockFilter, username: entr.username, method_type: 'bank_transfer', is_default: true })))?.data as IBankAccount
|
||||
}
|
||||
|
||||
const result: Cooperative.Documents.IGetResponse<ExternalEntrepreneurData> = {
|
||||
const result: Cooperative.Document.IGetResponse<ExternalEntrepreneurData> = {
|
||||
results: entrepreneurs as ExternalEntrepreneurData[],
|
||||
page: response.page,
|
||||
limit: response.limit,
|
||||
|
||||
@@ -16,7 +16,7 @@ export class Individual {
|
||||
|
||||
constructor(storage: MongoDBConnector, data?: ExternalIndividualData) {
|
||||
this.individual = data
|
||||
this.data_service = new DataService<InternalIndividualData>(storage, 'IndividualData')
|
||||
this.data_service = new DataService<InternalIndividualData>(storage, 'individuals')
|
||||
}
|
||||
|
||||
validate(): ValidateResult {
|
||||
@@ -44,7 +44,7 @@ export class Individual {
|
||||
return this.data_service.getOne(filter)
|
||||
}
|
||||
|
||||
async getMany(filter: Filter<InternalIndividualData>): Promise<Cooperative.Documents.IGetResponse<ExternalIndividualData>> {
|
||||
async getMany(filter: Filter<InternalIndividualData>): Promise<Cooperative.Document.IGetResponse<ExternalIndividualData>> {
|
||||
return this.data_service.getMany(filter, 'username')
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ export class Organization {
|
||||
constructor(storage: MongoDBConnector, data?: ExternalOrganizationData) {
|
||||
this.db = storage
|
||||
this.organization = data
|
||||
this.data_service = new DataService<InternalOrganizationData>(storage, 'OrgData')
|
||||
this.data_service = new DataService<InternalOrganizationData>(storage, 'organizations')
|
||||
}
|
||||
|
||||
validate(): ValidateResult {
|
||||
@@ -75,7 +75,7 @@ export class Organization {
|
||||
return org as ExternalOrganizationData
|
||||
}
|
||||
|
||||
async getMany(filter: Filter<InternalOrganizationData>): Promise<Cooperative.Documents.IGetResponse<ExternalOrganizationData>> {
|
||||
async getMany(filter: Filter<InternalOrganizationData>): Promise<Cooperative.Document.IGetResponse<ExternalOrganizationData>> {
|
||||
const response = (await this.data_service.getMany({ deleted: false, ...filter }, 'username'))
|
||||
const orgs = response.results
|
||||
const blockFilter = filter.block_num ? { block_num: filter.block_num } : {}
|
||||
@@ -84,7 +84,7 @@ export class Organization {
|
||||
org.bank_account = (await (new PaymentMethod(this.db).getOne({ ...blockFilter, username: org.username, method_type: 'bank_transfer', is_default: true })))?.data as IBankAccount
|
||||
}
|
||||
|
||||
const result: Cooperative.Documents.IGetResponse<ExternalOrganizationData> = {
|
||||
const result: Cooperative.Document.IGetResponse<ExternalOrganizationData> = {
|
||||
results: orgs as ExternalOrganizationData[],
|
||||
page: response.page,
|
||||
limit: response.limit,
|
||||
|
||||
@@ -18,7 +18,7 @@ export class PaymentMethod {
|
||||
constructor(storage: MongoDBConnector, data?: PaymentData) {
|
||||
this.db = storage
|
||||
this.paymentMethod = data
|
||||
this.data_service = new DataService(storage, 'PaymentData')
|
||||
this.data_service = new DataService(storage, 'paymentMethods')
|
||||
}
|
||||
|
||||
validate(): ValidateResult {
|
||||
@@ -41,7 +41,7 @@ export class PaymentMethod {
|
||||
return this.data_service.getOne(filter)
|
||||
}
|
||||
|
||||
async getMany(filter: Filter<PaymentData>): Promise<Cooperative.Documents.IGetResponse<PaymentData>> {
|
||||
async getMany(filter: Filter<PaymentData>): Promise<Cooperative.Document.IGetResponse<PaymentData>> {
|
||||
return this.data_service.getMany({ deleted: false, ...filter }, ['username', 'method_id'])
|
||||
}
|
||||
|
||||
|
||||
@@ -2,3 +2,5 @@ export * from './Individual'
|
||||
export * from './Organization'
|
||||
export * from './Entrepreneur'
|
||||
export * from './Cooperative'
|
||||
export * from './Document'
|
||||
export * from './PaymentMethod'
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { JSONSchemaType } from 'ajv'
|
||||
import type { IDecisionData } from '../Interfaces'
|
||||
import type { Cooperative } from 'cooptypes'
|
||||
|
||||
export const decisionSchema: JSONSchemaType<IDecisionData> = {
|
||||
export const decisionSchema: JSONSchemaType<Cooperative.Document.IDecisionData> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'number' },
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { JSONSchemaType } from 'ajv'
|
||||
import type { IMetaDocument } from '../Interfaces'
|
||||
|
||||
export const IMetaJSONSchema: JSONSchemaType<IMetaDocument> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string' },
|
||||
registry_id: { type: 'number' },
|
||||
lang: { type: 'string', enum: ['ru'] },
|
||||
generator: { type: 'string' },
|
||||
version: { type: 'string' },
|
||||
coopname: { type: 'string' },
|
||||
username: { type: 'string' },
|
||||
created_at: { type: 'string' },
|
||||
block_num: { type: 'number' },
|
||||
timezone: { type: 'string' },
|
||||
links: { type: 'array', items: { type: 'string' } },
|
||||
},
|
||||
required: [
|
||||
'title',
|
||||
'registry_id',
|
||||
'lang',
|
||||
'generator',
|
||||
'version',
|
||||
'coopname',
|
||||
'username',
|
||||
'created_at',
|
||||
'block_num',
|
||||
'timezone',
|
||||
],
|
||||
additionalProperties: true,
|
||||
}
|
||||
@@ -25,7 +25,7 @@ class DataService<T extends IDocument> {
|
||||
groupByFields: string | string[],
|
||||
page: number = 1,
|
||||
limit: number = 100,
|
||||
): Promise<Cooperative.Documents.IGetResponse<T>> {
|
||||
): Promise<Cooperative.Document.IGetResponse<T>> {
|
||||
const groupFields = Array.isArray(groupByFields) ? groupByFields : [groupByFields]
|
||||
const groupId = groupFields.reduce((acc, field) => ({ ...acc, [field]: `$${field}` }), {})
|
||||
|
||||
@@ -55,7 +55,7 @@ class DataService<T extends IDocument> {
|
||||
{ $limit: limit },
|
||||
]).toArray()
|
||||
|
||||
const result: Cooperative.Documents.IGetResponse<T> = {
|
||||
const result: Cooperative.Document.IGetResponse<T> = {
|
||||
results: results as T[],
|
||||
page,
|
||||
limit,
|
||||
|
||||
@@ -77,7 +77,7 @@ export class PDFService implements IPDFService {
|
||||
pdfDoc.setTitle(meta.title)
|
||||
pdfDoc.setLanguage(meta.lang)
|
||||
pdfDoc.setProducer(meta.version)
|
||||
pdfDoc.setSubject(`документ для действия: ${meta.code}::${meta.action}`)
|
||||
pdfDoc.setSubject(`Шаблона документа по реестру №${meta.registry_id}`)
|
||||
pdfDoc.setCreator(meta.generator)
|
||||
pdfDoc.setCreationDate(dateWithTimezone)
|
||||
pdfDoc.setModificationDate(dateWithTimezone)
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import type { JSONSchemaType } from 'ajv'
|
||||
import Ajv from 'ajv'
|
||||
import addFormats from 'ajv-formats'
|
||||
import localize_ru from 'ajv-i18n/localize/ru'
|
||||
import type { IMetaDocument } from '../../Interfaces'
|
||||
|
||||
const ajv = new Ajv()
|
||||
addFormats(ajv)
|
||||
@@ -11,44 +9,12 @@ ajv.addFormat('phone', {
|
||||
type: 'string',
|
||||
validate: () => true,
|
||||
})
|
||||
|
||||
// ajv.addFormat('phone', {
|
||||
// type: 'string',
|
||||
// validate: str => /^[+]?[(]?[0-9]{1,4}[)]?[-\\s\\.0-9]*$/.test(str),
|
||||
// })
|
||||
|
||||
export const IMetaJSONSchema: JSONSchemaType<IMetaDocument> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
code: { type: 'string' },
|
||||
action: { type: 'string' },
|
||||
title: { type: 'string' },
|
||||
registry_id: { type: 'number' },
|
||||
lang: { type: 'string', enum: ['ru'] },
|
||||
generator: { type: 'string' },
|
||||
version: { type: 'string' },
|
||||
coopname: { type: 'string' },
|
||||
username: { type: 'string' },
|
||||
created_at: { type: 'string' },
|
||||
block_num: { type: 'number' },
|
||||
timezone: { type: 'string' },
|
||||
},
|
||||
required: [
|
||||
'code',
|
||||
'action',
|
||||
'title',
|
||||
'registry_id',
|
||||
'lang',
|
||||
'generator',
|
||||
'version',
|
||||
'coopname',
|
||||
'username',
|
||||
'created_at',
|
||||
'block_num',
|
||||
'timezone',
|
||||
],
|
||||
additionalProperties: true,
|
||||
}
|
||||
|
||||
export interface ValidateResult {
|
||||
valid: boolean
|
||||
error: string
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
import type { JSONSchemaType } from 'ajv'
|
||||
|
||||
import type { IMetaDocument, ITemplate } from '../Interfaces'
|
||||
import { IMetaJSONSchema } from '../Services/Validator'
|
||||
import { individualSchema } from '../Schema/IndividualSchema'
|
||||
import type { ExternalIndividualData, ExternalOrganizationData } from '../Models'
|
||||
import { organizationSchema } from '../Schema'
|
||||
import { type CooperativeData, CooperativeSchema } from '../Models/Cooperative'
|
||||
import type { ExternalEntrepreneurData } from '../Models/Entrepreneur'
|
||||
import { entrepreneurSchema } from '../Schema/EntrepreneurSchema'
|
||||
|
||||
// Модель данных
|
||||
export interface IJoinCoopAction {
|
||||
type: string
|
||||
individual?: ExternalIndividualData
|
||||
organization?: ExternalOrganizationData
|
||||
entrepreneur?: ExternalEntrepreneurData
|
||||
coop: CooperativeData
|
||||
meta: IMetaDocument
|
||||
signature: string
|
||||
}
|
||||
|
||||
// Схема для сверки
|
||||
export const joinCoopJSONSchema: JSONSchemaType<IJoinCoopAction> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: ['individual', 'entrepreneur', 'organization'],
|
||||
},
|
||||
individual: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...individualSchema.properties,
|
||||
},
|
||||
required: [...individualSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
organization: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...organizationSchema.properties,
|
||||
},
|
||||
required: [...organizationSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
entrepreneur: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...entrepreneurSchema.properties,
|
||||
},
|
||||
required: [...entrepreneurSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
coop: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...CooperativeSchema.properties,
|
||||
},
|
||||
required: [...CooperativeSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
signature: {
|
||||
type: 'string',
|
||||
},
|
||||
meta: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...IMetaJSONSchema.properties,
|
||||
},
|
||||
required: [...IMetaJSONSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
},
|
||||
required: ['meta', 'coop', 'type', 'signature'],
|
||||
additionalProperties: true,
|
||||
}
|
||||
|
||||
export const ParticipantApplicationTemplate: ITemplate<IJoinCoopAction> = {
|
||||
title: 'Заявление на вступление в кооператив',
|
||||
description: 'Форма заявления на вступление в потребительский кооператив',
|
||||
model: joinCoopJSONSchema,
|
||||
context: `<style>\nh1 {\nmargin: 0px;\ntext-align:center;\n}\n</style>\n{% if type == 'individual' %}\n<h1 class=\"header\">{% trans 'application_individual' %}</h1>\n<p style=\"text-align: center\">{% trans 'in' %} {{ coop.full_name }}<p>\n<p style=\"text-align: right\">{{ meta.created_at }}, {{coop.city}}</p>\n<p>{% trans 'to_council_of' %} {{ coop.short_name }} {% trans 'from' %} {{ individual.last_name }} {{ individual.first_name }} {{ individual.middle_name }}, {% trans 'birthdate' %} {{ individual.birthdate }}, {% trans 'registration_address' %} {{ individual.full_address }}, {% trans 'phone_and_email_notice', individual.phone, individual.email %}</p>\n<p>{% trans 'request_to_join' %} {{ coop.full_name }}. {% trans 'acknowledge_documents_individual' %} {% if coop.is_branched %}</p> \n<p>{% trans 'authorize_chairman_branch', individual.branch_name %} {% endif %} </p>\n<p>{% trans 'obligation_to_pay_individual', coop.initial, coop.minimum %}</p>\n<p>{% trans 'agreement_on_sms_email_notice_individual' %}</p>\n<div class=\"signature\">\n<img style=\"max-width: 150px;\" src=\"{{ signature }}\"/>\n<p>{% trans 'signature' %} </p>\n<p style=\"text-align: right;\">{{ individual.last_name }} {{ individual.first_name }} {{ individual.middle_name }}</p>\n</div>\n\n{% elif type == 'entrepreneur' %}\n<h1 class=\"header\">{% trans 'application_entrepreneur' %}</h1>\n<p style=\"text-align: center\">{% trans 'in' %} {{ coop.full_name }}<p>\n<p style=\"text-align: right\">{{ meta.created_at }}, {{coop.city}}</p> <p>{% trans 'to_council_of' %} {{ coop.short_name }} {% trans 'from_entrepreneur' %} {{ entrepreneur.last_name }} {{ entrepreneur.first_name }} {{ entrepreneur.middle_name }}, {% trans 'birthdate' %} {{ entrepreneur.birthdate }}, {% trans 'registration_address' %} {{ entrepreneur.full_address }}, {% trans 'entrepreneur_details', entrepreneur.details.inn, entrepreneur.details.ogrn, entrepreneur.bank_account.account_number, entrepreneur.bank_account.details.kpp, entrepreneur.bank_account.details.corr, entrepreneur.bank_account.details.bik, entrepreneur.bank_account.bank_name %}, {% trans 'phone_and_email_notice', entrepreneur.phone, entrepreneur.email %}</p>\n<p>{% trans 'request_to_join' %} {{ coop.full_name }}. {% trans 'acknowledge_documents_entrepreneur' %}</p> \n<p>{% if coop.is_branched %}{% trans 'authorize_chairman_branch', entrepreneur.branch_name %} {% endif %} </p>\n<p>{% trans 'obligation_to_pay_entrepreneur', coop.initial, coop.minimum %} </p>\n<p>{% trans 'agreement_on_sms_email_notice_entrepreneur' %}</p>\n<div class=\"signature\">\n<img style=\"max-width: 150px;\" src=\"{{ signature }}\"/>\n<p>{% trans 'signature' %} </p>\n<p style=\"text-align: right;\">{{ entrepreneur.last_name }} {{ entrepreneur.first_name }} {{ entrepreneur.middle_name }}</p>\n</div>\n\n{% elif type == 'organization' %}\n<h1 class=\"header\">{% trans 'application_legal_entity' %}</h1>\n<p style=\"text-align: center\">{% trans 'in' %} {{ coop.full_name }}<p>\n<p style=\"text-align: right\">{{ meta.created_at }}, {{coop.city}}</p>\n<p>{% trans 'to_council_of' %} «{{ coop.full_name }}» {% trans 'from_legal_entity' %} {{ organization.full_name }}, {% trans 'legal_address' %} {{ organization.full_address }}, {% trans 'legal_entity_details', organization.details.inn, organization.details.ogrn, organization.bank_account.account_number, organization.bank_account.details.kpp, organization.bank_account.details.corr, organization.bank_account.details.bik, organization.bank_account.bank_name %}, {% trans 'phone_and_email_notice', organization.phone, organization.email %}</p>\n<p>{% trans 'request_to_join_legal_entity', organization.represented_by.position, organization.represented_by.last_name, organization.represented_by.first_name, organization.represented_by.middle_name, organization.represented_by.based_on %} {{ coop.full_name }}.</p>\n<p>{% trans 'acknowledge_documents_legal_entity' %}</p> \n<p>{% if coop.is_branched %}{% trans 'authorize_chairman_branch_organization', organization.branch_name %} {% endif %}</p>\n<p>{% trans 'obligation_to_pay_legal_entity', coop.initial, coop.minimum %}</p>\n<p>{% trans 'agreement_on_sms_email_notice_legal_entity' %}</p>\n<div class=\"signature\">\n<img style=\"max-width: 150px;\" src=\"{{ signature }}\"/>\n<p>{% trans 'signature' %} </p>\n<p style=\"text-align: right;\">{{ organization.represented_by.last_name }} {{ organization.represented_by.first_name }} {{ organization.represented_by.middle_name }}</p>\n</div>\n\n{% endif %}\n\n`,
|
||||
translations: {
|
||||
ru: {
|
||||
from: 'от',
|
||||
application_individual: 'Заявление физического лица о приеме в пайщики',
|
||||
to_council_of: 'В Совет',
|
||||
birthdate: 'дата рождения',
|
||||
registration_address: 'адрес регистрации (как в паспорте): ',
|
||||
phone_and_email_notice: 'номер телефона с активированной функцией получения sms: {0}, адрес электронной почты: {1}.',
|
||||
acknowledge_documents_individual: 'Подтверждаю, что с Уставом и иными нормативными документами Общества ознакомлен(а).',
|
||||
agreement_on_sms_email_notice_individual: 'Выражаю свое согласие с тем, что информация, отправляемая Обществом в sms-сообщениях на указанный мной номер телефона, в сообщениях на указанный мной адрес электронной почты, или в PUSH уведомлениях с сайта, приравнивается к уведомлению меня Обществом в письменной форме.',
|
||||
application_entrepreneur: 'Заявление индивидуального предпринимателя о приеме в пайщики',
|
||||
from_entrepreneur: 'от индивидуального предпринимателя',
|
||||
acknowledge_documents_entrepreneur: 'Подтверждаю, что с Уставом и иными нормативными документами Общества ознакомлен(а).',
|
||||
agreement_on_sms_email_notice_entrepreneur: 'Выражаю свое согласие с тем, что информация, отправляемая Обществом в sms-сообщениях на указанный мной номер телефона, в сообщениях на указанный мной адрес электронной почты, или в PUSH уведомлениях с сайта, приравнивается к уведомлению меня Обществом в письменной форме.',
|
||||
application_legal_entity: 'Заявление юридического лица о приеме в пайщики',
|
||||
from_legal_entity: 'от юридического лица',
|
||||
legal_address: 'юридический адрес организации',
|
||||
legal_entity_details: 'ИНН {0}, ОГРН {1}, Р/с {2}, КПП {3}, К/с {4}, БИК {5}, банк получателя {6}',
|
||||
acknowledge_documents_legal_entity: 'Подтверждает, что с Уставом и иными нормативными документами Общества ознакомлен.',
|
||||
agreement_on_sms_email_notice_legal_entity: 'Выражает свое согласие с тем, что информация, отправляемая Обществом в sms-сообщениях на указанный номер телефона, в сообщениях на указанный адрес электронной почты, или в PUSH уведомлениях с сайта, приравнивается к уведомлению Заявителя Обществом в письменной форме.',
|
||||
obligation_to_pay_individual: 'Обязуюсь своевременно внести в Общество вступительный {0} и минимальный паевой {1} взносы в порядке, предусмотренном Уставом Общества.',
|
||||
obligation_to_pay_entrepreneur: 'Обязуюсь своевременно внести в Общество вступительный {0} и минимальный паевой {1} взносы в порядке, предусмотренном Уставом Общества.',
|
||||
obligation_to_pay_legal_entity: 'Обязуется своевременно внести в Общество вступительный {0} и минимальный паевой {1} взносы в порядке, предусмотренном Уставом Общества.',
|
||||
entrepreneur_details: 'ИНН {0}, ОГРНИП {1}, Р/с {2}, КПП {3}, К/с {4}, БИК {5}, банк получателя {6}',
|
||||
authorize_chairman_branch: 'Уполномочиваю Председателя кооперативного участка {0} принимать участие с правом голоса в Общих собраниях уполномоченных Общества, на период моего членства в Обществе при указанном кооперативном участке.',
|
||||
request_to_join_legal_entity: 'Заявитель, в лице представителя юридического лица - {0} {1} {2} {3}, действующий на основании {4}, просит принять в пайщики ',
|
||||
authorize_chairman_branch_organization: 'Уполномочивает Председателя кооперативного участка {0} принимать участие с правом голоса в Общих собраниях уполномоченных Общества, на период моего членства в Обществе при указанном кооперативном участке.',
|
||||
signature: 'подпись',
|
||||
in: 'в',
|
||||
request_to_join: 'Прошу принять меня в пайщики',
|
||||
},
|
||||
// ... другие переводы
|
||||
},
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
-123
@@ -1,123 +0,0 @@
|
||||
import type { JSONSchemaType } from 'ajv'
|
||||
|
||||
import type { IDecisionData, IMetaDocument, ITemplate } from '../Interfaces'
|
||||
import { IMetaJSONSchema } from '../Services/Validator'
|
||||
import { individualSchema } from '../Schema/IndividualSchema'
|
||||
import { organizationSchema } from '../Schema'
|
||||
import { type CooperativeData, CooperativeSchema } from '../Models/Cooperative'
|
||||
import { entrepreneurSchema } from '../Schema/EntrepreneurSchema'
|
||||
import { decisionSchema } from '../Schema/DecisionSchema'
|
||||
import type { ExternalEntrepreneurData, ExternalIndividualData, ExternalOrganizationData } from '../Models'
|
||||
|
||||
// Модель данных
|
||||
export interface IJoinCoopDecisionAction {
|
||||
type: string
|
||||
individual?: ExternalIndividualData
|
||||
organization?: ExternalOrganizationData
|
||||
entrepreneur?: ExternalEntrepreneurData
|
||||
coop: CooperativeData
|
||||
decision: IDecisionData
|
||||
meta: IMetaDocument
|
||||
}
|
||||
|
||||
// Схема для сверки
|
||||
export const joinCoopJSONSchema: JSONSchemaType<IJoinCoopDecisionAction> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: ['individual', 'entrepreneur', 'organization'],
|
||||
},
|
||||
individual: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...individualSchema.properties,
|
||||
},
|
||||
required: [...individualSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
organization: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...organizationSchema.properties,
|
||||
},
|
||||
required: [...organizationSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
entrepreneur: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...entrepreneurSchema.properties,
|
||||
},
|
||||
required: [...entrepreneurSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
coop: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...CooperativeSchema.properties,
|
||||
},
|
||||
required: [...CooperativeSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
decision: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...decisionSchema.properties,
|
||||
},
|
||||
required: [...decisionSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
meta: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...IMetaJSONSchema.properties,
|
||||
},
|
||||
required: [...IMetaJSONSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
},
|
||||
required: ['meta', 'coop', 'type', 'decision'],
|
||||
additionalProperties: true,
|
||||
}
|
||||
|
||||
export const DecisionOfParticipantApplicationTemplate: ITemplate<IJoinCoopDecisionAction> = {
|
||||
title: 'Решение совета о приёме пайщика в кооператив',
|
||||
description: 'Форма решения совета о приёме пайщика в потребительский кооператив',
|
||||
model: joinCoopJSONSchema,
|
||||
context: `<style> \nh1 {\nmargin: 0px; \ntext-align:center;\n}\nh3{\nmargin: 0px;\npadding-top: 15px;\n}\n.about {\npadding: 20px;\n}\n.about p{\nmargin: 0px;\n}\n.signature {\npadding-top: 20px;\n}\n</style>\n\n<h1 class=\"header\">{% trans 'protocol_number', decision.id %}</h1>\n<p style=\"text-align:center\">{% trans 'council_meeting_name' %}\n{{ coop.full_name }}</p>\n<p style=\"text-align: right\"> {{ meta.created_at }}, {{ coop.city }}</p>\n\n<div class=\"about\">\n<p>{% trans 'meeting_format' %}</p>\n<p>{% trans 'meeting_place', coop.full_address %}</p>\n<p>{% trans 'meeting_date', decision.date %}</p>\n<p>{% trans 'opening_time', decision.time %}</p>\n</div>\n\n<h3>{% trans 'council_members' %}</h3>\n<ol>{% for member in coop.members %}\n<li>{{ member.last_name }} {{ member.first_name }} {{ member.middle_name }}{% if member.is_chairman %} {% trans 'chairman_of_the_council' %}{% endif %}</li>\n{% endfor %}\n</ol>\n\n<h3>{% trans 'meeting_legality' %} </h3>\n<p>{% trans 'voting_results', decision.voters_percent %} {% trans 'quorum' %} {% trans 'chairman_of_the_meeting', coop.chairman.last_name, coop.chairman.first_name, coop.chairman.middle_name %}.</p>\n\n<h3>{% trans 'agenda' %}</h3>\n<ol><li> {% trans 'decision_joincoop1' %}{% if type == 'individual' %} {{individual.last_name}} {{individual.first_name}} {{individual.middle.name}} ({{individual.birthdate}} {% trans 'birthdate' %}) {% endif %}{% if type == 'entrepreneur' %} {% trans 'entrepreneur' %} {{entrepreneur.last_name}} {{entrepreneur.first_name}} {{entrepreneur.middle.name}} ({% trans 'ogrnip' %} {{entrepreneur.details.ogrn}}) {% endif %}{% if type == 'organization' %} {{organization.short_name}} ({% trans 'ogrn' %} {{organization.details.ogrn}}) {% endif %}{% trans 'in_participants' %} {{ coop.short_name }}.\n</li></ol>\n\n<h3>{% trans 'voting' %}</h3>\n<p>{% trans 'vote_results', decision.votes_for, decision.votes_against, decision.votes_abstained %} </p>\n\n<h3>{% trans 'decision_made' %}</h3>\n<p>{% trans 'decision_joincoop2' %}{% if type == 'individual' %} {{individual.last_name}} {{individual.first_name}} {{individual.middle.name}} {{individual.birthdate}} {% trans 'birthdate' %}{% endif %} {% if type == 'entrepreneur' %}{% trans 'entrepreneur' %} {{entrepreneur.last_name}} {{entrepreneur.first_name}} {{entrepreneur.middle.name}}, {% trans 'ogrnip' %} {{entrepreneur.details.ogrn}}{% endif %} {% if type == 'organization' %} {{organization.short_name}}, {% trans 'ogrn' %} {{organization.details.ogrn}} {% endif %}</p>\n<hr>\n<p>{% trans 'closing_time', decision.time %}</p>\n\n<div class=\"signature\"> \n<p>{% trans 'signature' %}<p>\n<p style=\"text-align: right;\">{% trans 'chairman' %} {{ coop.chairman.last_name }} {{ coop.chairman.first_name }} {{ coop.chairman.middle_name }}</p></div>`,
|
||||
translations: {
|
||||
ru: {
|
||||
meeting_format: 'Форма проведения собрания совета: заочная',
|
||||
meeting_date: 'Дата проведения собрания совета: {0}',
|
||||
meeting_place: 'Место проведения собрания совета: {0}',
|
||||
opening_time: 'Время открытия собрания совета: {0}',
|
||||
council_members: 'Члены Совета',
|
||||
voting_results: 'Количество голосов составляет {0}% от общего числа членов Совета.',
|
||||
meeting_legality: 'Собрание правомочно',
|
||||
chairman_of_the_meeting: 'Председатель собрания совета: {0} {1} {2}',
|
||||
agenda: 'Повестка дня',
|
||||
vote_results: 'По первому вопросу повестки дня проголосовали: «За» – {0}; «Против» - {1}; «Воздержался» - {2}.',
|
||||
decision_made: 'Решили',
|
||||
closing_time: 'Время закрытия собрания совета: {0}.',
|
||||
protocol_number: 'Протокол № {0}',
|
||||
council_meeting_name: 'Собрания Совета',
|
||||
chairman_of_the_council: '(председатель совета)',
|
||||
signature: 'Документ подписан электронной подписью.',
|
||||
chairman: 'Председатель',
|
||||
birthdate: 'г.р.',
|
||||
ogrnip: 'ОГРНИП',
|
||||
entrepreneur: 'ИП',
|
||||
ogrn: 'ОГРН',
|
||||
quorum: 'Кворум для решения поставленных на повестку дня вопросов имеется.',
|
||||
voting: 'Голосование',
|
||||
in_participants: 'о приёме в пайщики',
|
||||
decision_joincoop1: 'Рассмотреть заявление',
|
||||
decision_joincoop2: 'Принять нового пайщика',
|
||||
},
|
||||
// ... другие переводы
|
||||
},
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export * from './registry'
|
||||
@@ -1,15 +0,0 @@
|
||||
import * as ParticipantApplication from './100.ParticipantApplication'
|
||||
import * as DecisionOfParticipantApplication from './501.DecisionOfParticipantApplication'
|
||||
import * as ProgramProvision from './1000.ProgramProvision'
|
||||
|
||||
export const DocumentsRegistry = {
|
||||
100: ParticipantApplication.ParticipantApplicationTemplate,
|
||||
501: DecisionOfParticipantApplication.DecisionOfParticipantApplicationTemplate,
|
||||
1000: ProgramProvision.JoinProgramTemplate,
|
||||
}
|
||||
|
||||
export interface DocumentsMappingByActionAndCode {
|
||||
'registrator::joincoop': ParticipantApplication.IJoinCoopAction // Тип данных для документа 'registrator::joincoop'
|
||||
'registrator::joincoopdec': DecisionOfParticipantApplication.IJoinCoopDecisionAction // Тип данных для документа 'registrator::joincoopdec'
|
||||
'soviet::joinprog': ProgramProvision.IJoinProgram
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DraftContract } from 'cooptypes/index'
|
||||
import { DraftContract } from 'cooptypes'
|
||||
import { getEnvVar } from '../config'
|
||||
import { getFetch } from './getFetch'
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DraftContract } from 'cooptypes/index'
|
||||
import { DraftContract } from 'cooptypes'
|
||||
import { getEnvVar } from '../config'
|
||||
import { getFetch } from './getFetch'
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
export * from './Interfaces'
|
||||
export * from './Templates'
|
||||
|
||||
export * from './templates'
|
||||
import type { Filter, InsertOneResult, UpdateResult } from 'mongodb'
|
||||
import type { Cooperative as CooperativeModel } from 'cooptypes'
|
||||
import type { Actions, IFilterDocuments, IGeneratedDocument, externalDataTypes, externalDataTypesArrays, internalFilterTypes } from './Interfaces'
|
||||
import type { IFilterDocuments, IGeneratedDocument, Numbers, externalDataTypes, externalDataTypesArrays, internalFilterTypes } from './Interfaces'
|
||||
import type { IGenerate } from './Interfaces/Documents'
|
||||
import { JoinCoop, JoinCoopDecision, JoinProgram } from './Actions'
|
||||
import * as Actions from './Actions'
|
||||
|
||||
import { MongoDBConnector } from './Services/Databazor'
|
||||
import type { ExternalIndividualData } from './Models/Individual'
|
||||
import { Individual } from './Models/Individual'
|
||||
@@ -35,7 +35,7 @@ export interface IGenerator {
|
||||
get: (type: dataTypes, filter: Filter<internalFilterTypes>) => Promise<externalDataTypes | null>
|
||||
del: (type: dataTypes, filter: Filter<internalFilterTypes>) => Promise<UpdateResult>
|
||||
|
||||
list: (type: dataTypes, filter: Filter<internalFilterTypes>) => Promise<CooperativeModel.Documents.IGetResponse<internalFilterTypes>>
|
||||
list: (type: dataTypes, filter: Filter<internalFilterTypes>) => Promise<CooperativeModel.Document.IGetResponse<internalFilterTypes>>
|
||||
|
||||
getHistory: (type: dataTypes, filter: Filter<internalFilterTypes>) => Promise<externalDataTypesArrays>
|
||||
}
|
||||
@@ -43,7 +43,7 @@ export interface IGenerator {
|
||||
export class Generator implements IGenerator {
|
||||
// Определение фабрик
|
||||
factories!: {
|
||||
[K in Actions]: DocFactory
|
||||
[K in Numbers]: DocFactory<IGenerate>
|
||||
}
|
||||
|
||||
// Определение хранилища
|
||||
@@ -53,11 +53,11 @@ export class Generator implements IGenerator {
|
||||
async connect(mongoUri: string): Promise<void> {
|
||||
this.storage = new MongoDBConnector(mongoUri)
|
||||
|
||||
// Инициализация фабрик для разных типов документов
|
||||
// Инициализация фабрик документов
|
||||
this.factories = {
|
||||
'registrator::joincoop': new JoinCoop.JoinCoopTemplateFactory(this.storage),
|
||||
'registrator::joincoopdec': new JoinCoopDecision.DecisionOfJoinCoopTemplateFactory(this.storage),
|
||||
'soviet::joinprog': new JoinProgram.JoinProgramTemplateFactory(this.storage),
|
||||
[Actions.WalletAgreement.Template.registry_id]: new Actions.WalletAgreement.Factory(this.storage),
|
||||
[Actions.ParticipantApplication.Template.registry_id]: new Actions.ParticipantApplication.Factory(this.storage),
|
||||
[Actions.DecisionOfParticipantApplication.Template.registry_id]: new Actions.DecisionOfParticipantApplication.Factory(this.storage),
|
||||
}
|
||||
await this.storage.connect()
|
||||
}
|
||||
@@ -69,10 +69,10 @@ export class Generator implements IGenerator {
|
||||
|
||||
// Метод генерации документа
|
||||
async generate(options: IGenerate): Promise<IGeneratedDocument> {
|
||||
const factory = this.factories[`${options.code}::${options.action}` as Actions] // Get the factory
|
||||
const factory = this.factories[options.registry_id as Numbers] // Get the factory
|
||||
|
||||
if (!factory)
|
||||
throw new Error(`Фабрика для документа типа ${options.code}::${options.action} не найдена.`)
|
||||
throw new Error(`Фабрика для документа #${options.registry_id} не найдена.`)
|
||||
|
||||
// синтезируем документ
|
||||
return await factory.generateDocument(options)
|
||||
@@ -104,7 +104,7 @@ export class Generator implements IGenerator {
|
||||
}
|
||||
|
||||
// Универсальные методы получения списка объектов
|
||||
async list(type: dataTypes, filter: Filter<internalFilterTypes>): Promise<CooperativeModel.Documents.IGetResponse<externalDataTypes>> {
|
||||
async list(type: dataTypes, filter: Filter<internalFilterTypes>): Promise<CooperativeModel.Document.IGetResponse<externalDataTypes>> {
|
||||
const model = this.getModel(type)
|
||||
return model.getMany(filter)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { JSONSchemaType } from 'ajv'
|
||||
import { Cooperative } from 'cooptypes'
|
||||
import type { IGenerate, IMetaDocument, ITemplate } from '../Interfaces'
|
||||
import { IMetaJSONSchema } from '../Schema/MetaSchema'
|
||||
|
||||
export const registry_id = Cooperative.Registry.WalletAgreement.registry_id
|
||||
|
||||
// Модель действия для генерации
|
||||
export type Action = Cooperative.Registry.WalletAgreement.Action
|
||||
|
||||
// Модель данных
|
||||
export type Model = Cooperative.Registry.WalletAgreement.Model
|
||||
|
||||
// Схема для сверки
|
||||
export const Schema: JSONSchemaType<Model> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
meta: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...IMetaJSONSchema.properties,
|
||||
},
|
||||
required: [...IMetaJSONSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
},
|
||||
required: ['meta'],
|
||||
additionalProperties: true,
|
||||
}
|
||||
|
||||
export const Template: ITemplate<Model> = {
|
||||
title: Cooperative.Registry.WalletAgreement.title,
|
||||
description: Cooperative.Registry.WalletAgreement.description,
|
||||
model: Schema,
|
||||
context: Cooperative.Registry.WalletAgreement.context,
|
||||
translations: Cooperative.Registry.WalletAgreement.translations,
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { JSONSchemaType } from 'ajv'
|
||||
|
||||
import { Cooperative } from 'cooptypes'
|
||||
import type { IGenerate, IMetaDocument, ITemplate } from '../Interfaces'
|
||||
import { IMetaJSONSchema } from '../Schema/MetaSchema'
|
||||
import { individualSchema } from '../Schema/IndividualSchema'
|
||||
import type { ExternalIndividualData, ExternalOrganizationData } from '../Models'
|
||||
import { organizationSchema } from '../Schema'
|
||||
import { type CooperativeData, CooperativeSchema } from '../Models/Cooperative'
|
||||
import type { ExternalEntrepreneurData } from '../Models/Entrepreneur'
|
||||
import { entrepreneurSchema } from '../Schema/EntrepreneurSchema'
|
||||
|
||||
export const registry_id = Cooperative.Registry.ParticipantApplication.registry_id
|
||||
|
||||
/**
|
||||
* Интерфейс генерации заявления на вступление в кооператив
|
||||
*/
|
||||
export type Action = Cooperative.Registry.ParticipantApplication.Action
|
||||
|
||||
// Модель данных
|
||||
export type Model = Cooperative.Registry.ParticipantApplication.Model
|
||||
|
||||
// Схема для сверки
|
||||
export const Schema: JSONSchemaType<Model> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: ['individual', 'entrepreneur', 'organization'],
|
||||
},
|
||||
individual: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...individualSchema.properties,
|
||||
},
|
||||
required: [...individualSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
organization: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...organizationSchema.properties,
|
||||
},
|
||||
required: [...organizationSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
entrepreneur: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...entrepreneurSchema.properties,
|
||||
},
|
||||
required: [...entrepreneurSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
coop: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...CooperativeSchema.properties,
|
||||
},
|
||||
required: [...CooperativeSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
signature: {
|
||||
type: 'string',
|
||||
},
|
||||
meta: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...IMetaJSONSchema.properties,
|
||||
},
|
||||
required: [...IMetaJSONSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
},
|
||||
required: ['meta', 'coop', 'type', 'signature'],
|
||||
additionalProperties: true,
|
||||
}
|
||||
|
||||
export const Template: ITemplate<Model> = {
|
||||
title: Cooperative.Registry.ParticipantApplication.title,
|
||||
description: Cooperative.Registry.ParticipantApplication.description,
|
||||
model: Schema,
|
||||
context: Cooperative.Registry.ParticipantApplication.context,
|
||||
translations: Cooperative.Registry.ParticipantApplication.translations,
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { JSONSchemaType } from 'ajv'
|
||||
|
||||
import { Cooperative } from 'cooptypes'
|
||||
import type { IGenerate, IMetaDocument, ITemplate } from '../Interfaces'
|
||||
import { IMetaJSONSchema } from '../Schema/MetaSchema'
|
||||
import { individualSchema } from '../Schema/IndividualSchema'
|
||||
import { organizationSchema } from '../Schema'
|
||||
import { type CooperativeData, CooperativeSchema } from '../Models/Cooperative'
|
||||
import { entrepreneurSchema } from '../Schema/EntrepreneurSchema'
|
||||
import { decisionSchema } from '../Schema/DecisionSchema'
|
||||
import type { ExternalEntrepreneurData, ExternalIndividualData, ExternalOrganizationData } from '../Models'
|
||||
|
||||
export const registry_id = Cooperative.Registry.DecisionOfParticipantApplication.registry_id
|
||||
|
||||
/**
|
||||
* Интерфейс генерации решения совета
|
||||
*/
|
||||
export type Action = Cooperative.Registry.DecisionOfParticipantApplication.Action
|
||||
|
||||
export type Model = Cooperative.Registry.DecisionOfParticipantApplication.Model
|
||||
|
||||
// Схема для сверки
|
||||
export const Schema: JSONSchemaType<Model> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: ['individual', 'entrepreneur', 'organization'],
|
||||
},
|
||||
individual: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...individualSchema.properties,
|
||||
},
|
||||
required: [...individualSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
organization: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...organizationSchema.properties,
|
||||
},
|
||||
required: [...organizationSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
entrepreneur: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...entrepreneurSchema.properties,
|
||||
},
|
||||
required: [...entrepreneurSchema.required],
|
||||
additionalProperties: true,
|
||||
nullable: true,
|
||||
},
|
||||
coop: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...CooperativeSchema.properties,
|
||||
},
|
||||
required: [...CooperativeSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
decision: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...decisionSchema.properties,
|
||||
},
|
||||
required: [...decisionSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
meta: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...IMetaJSONSchema.properties,
|
||||
},
|
||||
required: [...IMetaJSONSchema.required],
|
||||
additionalProperties: true,
|
||||
},
|
||||
},
|
||||
required: ['meta', 'coop', 'type', 'decision'],
|
||||
additionalProperties: true,
|
||||
}
|
||||
|
||||
export const Template: ITemplate<Model> = {
|
||||
title: Cooperative.Registry.DecisionOfParticipantApplication.title,
|
||||
description: Cooperative.Registry.DecisionOfParticipantApplication.description,
|
||||
model: Schema,
|
||||
context: Cooperative.Registry.DecisionOfParticipantApplication.context,
|
||||
translations: Cooperative.Registry.DecisionOfParticipantApplication.translations,
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export * as WalletAgreement from './1.WalletAgreement'
|
||||
export * as ParticipantApplication from './100.ParticipantApplication'
|
||||
export * as DecisionOfParticipantApplication from './501.DecisionOfParticipantApplication'
|
||||
|
||||
export * from './registry'
|
||||
@@ -0,0 +1,21 @@
|
||||
import * as ParticipantApplication from './100.ParticipantApplication'
|
||||
import * as DecisionOfParticipantApplication from './501.DecisionOfParticipantApplication'
|
||||
import * as WalletAgreement from './1.WalletAgreement'
|
||||
|
||||
export const Registry = {
|
||||
1: WalletAgreement,
|
||||
100: ParticipantApplication,
|
||||
501: DecisionOfParticipantApplication,
|
||||
}
|
||||
|
||||
export interface IRegistry {
|
||||
1: WalletAgreement.Action // Тип данных для документа
|
||||
100: ParticipantApplication.Action // Тип данных для документа
|
||||
501: DecisionOfParticipantApplication.Action // Тип данных для документа
|
||||
}
|
||||
|
||||
export interface MRegistry {
|
||||
1: WalletAgreement.Model // Тип данных для документа
|
||||
100: ParticipantApplication.Model // Тип данных для документа
|
||||
501: DecisionOfParticipantApplication.Model // Тип данных для документа
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
import { beforeAll, beforeEach, describe, expect, it } from 'vitest'
|
||||
import type { RegistratorContract, SovietContract } from 'cooptypes'
|
||||
import { Generator, type IGenerateJoinProgram } from '../src'
|
||||
import { Generator, type IGenerateWalletAgreement } from '../src'
|
||||
import type { IGeneratedDocument } from '../src/Interfaces/Documents'
|
||||
import { saveBufferToDisk } from '../src/Utils/saveBufferToDisk'
|
||||
import { loadBufferFromDisk } from '../src/Utils/loadBufferFromDisk'
|
||||
import { calculateSha256 } from '../src/Utils/calculateSHA'
|
||||
import { DocumentsRegistry } from '../src/Templates'
|
||||
import { MongoDBConnector } from '../src/Services/Databazor'
|
||||
|
||||
const mongoUri = 'mongodb://127.0.0.1:27017/cooperative'
|
||||
const mongoUri = 'mongodb://127.0.0.1:27017/cooperative-test'
|
||||
const coopname = 'voskhod'
|
||||
|
||||
import type { ExternalEntrepreneurData, ExternalIndividualData, ExternalOrganizationData } from '../src/Models'
|
||||
import type { PaymentData } from '../src/Models/PaymentMethod'
|
||||
import { Registry } from '../src/templates'
|
||||
import { signatureExample } from './signatureExample'
|
||||
|
||||
const generator = new Generator()
|
||||
@@ -41,7 +41,7 @@ describe('тест генератора документов', async () => {
|
||||
return
|
||||
|
||||
let i = 0
|
||||
for (const [key, value] of Object.entries(DocumentsRegistry)) {
|
||||
for (const [key, value] of Object.entries(Registry)) {
|
||||
i++
|
||||
await deltas.insertOne({
|
||||
block_num: 0,
|
||||
@@ -55,10 +55,10 @@ describe('тест генератора документов', async () => {
|
||||
registry_id: String(key),
|
||||
version: 1,
|
||||
default_translation_id: String(i),
|
||||
title: value.title,
|
||||
description: value.description,
|
||||
context: value.context,
|
||||
model: JSON.stringify(value.model),
|
||||
title: value.Template.title,
|
||||
description: value.Template.description,
|
||||
context: value.Template.context,
|
||||
model: JSON.stringify(value.Template.model),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -73,7 +73,7 @@ describe('тест генератора документов', async () => {
|
||||
id: String(i),
|
||||
draft_id: String(i),
|
||||
lang: 'ru',
|
||||
data: JSON.stringify(value.translations.ru),
|
||||
data: JSON.stringify(value.Template.translations.ru),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -299,13 +299,11 @@ describe('тест генератора документов', async () => {
|
||||
})
|
||||
|
||||
it('генерируем заявление на присоединение к ЦПП', async () => {
|
||||
const params: IGenerateJoinProgram = {
|
||||
code: 'soviet',
|
||||
action: 'joinprog',
|
||||
const params: IGenerateWalletAgreement = {
|
||||
coopname: 'voskhod',
|
||||
username: 'ant',
|
||||
lang: 'ru',
|
||||
registry_id: 1000,
|
||||
registry_id: 1,
|
||||
protocol_number: '01-01-2024',
|
||||
protocol_day_month_year: '1 января 2024 г.',
|
||||
}
|
||||
@@ -343,238 +341,232 @@ describe('тест генератора документов', async () => {
|
||||
expect(hash1).toEqual(hash2)
|
||||
})
|
||||
|
||||
// it('генерируем заявление на вступление физического лица', async () => {
|
||||
// const document: IGeneratedDocument = await generator.generate({
|
||||
// code: 'registrator',
|
||||
// action: 'joincoop',
|
||||
// coopname: 'voskhod',
|
||||
// username: 'ant',
|
||||
// lang: 'ru',
|
||||
// signature: signatureExample,
|
||||
// })
|
||||
it('генерируем заявление на вступление физического лица', async () => {
|
||||
const document: IGeneratedDocument = await generator.generate({
|
||||
registry_id: 100,
|
||||
coopname: 'voskhod',
|
||||
username: 'ant',
|
||||
lang: 'ru',
|
||||
signature: signatureExample,
|
||||
})
|
||||
|
||||
// const filename1 = `${document.meta.title}-${document.meta.username}.pdf`
|
||||
// await saveBufferToDisk(document.binary, filename1)
|
||||
const filename1 = `${document.meta.title}-${document.meta.username}.pdf`
|
||||
await saveBufferToDisk(document.binary, filename1)
|
||||
|
||||
// const regenerated_document: IGeneratedDocument = await generator.generate({
|
||||
// ...document.meta,
|
||||
// })
|
||||
// const filename2 = `regenerated-${document.meta.title}-${document.meta.username}.pdf`
|
||||
// await saveBufferToDisk(regenerated_document.binary, filename2)
|
||||
const regenerated_document: IGeneratedDocument = await generator.generate({
|
||||
...document.meta,
|
||||
})
|
||||
const filename2 = `regenerated-${document.meta.title}-${document.meta.username}.pdf`
|
||||
await saveBufferToDisk(regenerated_document.binary, filename2)
|
||||
|
||||
// expect(document.meta).toEqual(regenerated_document.meta)
|
||||
// expect(document.hash).toEqual(regenerated_document.hash)
|
||||
expect(document.meta).toEqual(regenerated_document.meta)
|
||||
expect(document.hash).toEqual(regenerated_document.hash)
|
||||
|
||||
// const document_from_disk1 = await loadBufferFromDisk(filename1)
|
||||
// const document_from_disk2 = await loadBufferFromDisk(filename2)
|
||||
const document_from_disk1 = await loadBufferFromDisk(filename1)
|
||||
const document_from_disk2 = await loadBufferFromDisk(filename2)
|
||||
|
||||
// const hash1 = calculateSha256(document_from_disk1)
|
||||
// const hash2 = calculateSha256(document_from_disk2)
|
||||
const hash1 = calculateSha256(document_from_disk1)
|
||||
const hash2 = calculateSha256(document_from_disk2)
|
||||
|
||||
// const getted_document = await generator.getDocument({ hash: regenerated_document.hash })
|
||||
const getted_document = await generator.getDocument({ hash: regenerated_document.hash })
|
||||
|
||||
// expect(getted_document).toBeDefined()
|
||||
// expect(getted_document.hash).toEqual(document.hash)
|
||||
expect(getted_document).toBeDefined()
|
||||
expect(getted_document.hash).toEqual(document.hash)
|
||||
|
||||
// // console.log('hash1: ', hash1)
|
||||
// // console.log('hash2: ', hash2)
|
||||
// // console.log(document)
|
||||
// console.log('hash1: ', hash1)
|
||||
// console.log('hash2: ', hash2)
|
||||
// console.log(document)
|
||||
|
||||
// expect(hash1).toEqual(hash2)
|
||||
expect(hash1).toEqual(hash2)
|
||||
|
||||
// const decision_document: IGeneratedDocument = await generator.generate({
|
||||
// code: 'registrator',
|
||||
// action: 'joincoopdec',
|
||||
// coopname: 'voskhod',
|
||||
// username: 'ant',
|
||||
// lang: 'ru',
|
||||
// decision_id: 1,
|
||||
// })
|
||||
const decision_document: IGeneratedDocument = await generator.generate({
|
||||
registry_id: 501,
|
||||
coopname: 'voskhod',
|
||||
username: 'ant',
|
||||
lang: 'ru',
|
||||
decision_id: 1,
|
||||
})
|
||||
|
||||
// const filename3 = `${decision_document.meta.title}-${decision_document.meta.username}.pdf`
|
||||
// await saveBufferToDisk(decision_document.binary, filename3)
|
||||
// })
|
||||
const filename3 = `${decision_document.meta.title}-${decision_document.meta.username}.pdf`
|
||||
await saveBufferToDisk(decision_document.binary, filename3)
|
||||
})
|
||||
|
||||
// it('сохранение данных организации', async () => {
|
||||
// const organizationData: ExternalOrganizationData = {
|
||||
// username: 'exampleorg',
|
||||
// type: 'ooo',
|
||||
// is_cooperative: false,
|
||||
// short_name: 'ExampleOrg',
|
||||
// full_name: 'Примерная организация',
|
||||
// represented_by: {
|
||||
// first_name: 'Иван',
|
||||
// last_name: 'Иванов',
|
||||
// middle_name: 'Иванович',
|
||||
// position: 'Директор',
|
||||
// based_on: 'Устава организации',
|
||||
// },
|
||||
// country: 'Russia',
|
||||
// city: 'Moscow',
|
||||
// full_address: '456 Main St, Moscow, Russia',
|
||||
// email: 'contact@exampleorg.com',
|
||||
// phone: '+71234567890',
|
||||
// details: {
|
||||
// inn: '0987654321',
|
||||
// ogrn: '0987654321098',
|
||||
// },
|
||||
// bank_account: {
|
||||
// account_number: '40817810099910004312',
|
||||
// currency: 'RUB',
|
||||
// card_number: '0987654321098765',
|
||||
// bank_name: 'Example Bank',
|
||||
// details: {
|
||||
// bik: '098765432',
|
||||
// corr: '30101810400000000225',
|
||||
// kpp: '098765432',
|
||||
// },
|
||||
// },
|
||||
// }
|
||||
it('сохранение данных организации', async () => {
|
||||
const organizationData: ExternalOrganizationData = {
|
||||
username: 'exampleorg',
|
||||
type: 'ooo',
|
||||
is_cooperative: false,
|
||||
short_name: 'ExampleOrg',
|
||||
full_name: 'Примерная организация',
|
||||
represented_by: {
|
||||
first_name: 'Иван',
|
||||
last_name: 'Иванов',
|
||||
middle_name: 'Иванович',
|
||||
position: 'Директор',
|
||||
based_on: 'Устава организации',
|
||||
},
|
||||
country: 'Russia',
|
||||
city: 'Moscow',
|
||||
full_address: '456 Main St, Moscow, Russia',
|
||||
email: 'contact@exampleorg.com',
|
||||
phone: '+71234567890',
|
||||
details: {
|
||||
inn: '0987654321',
|
||||
ogrn: '0987654321098',
|
||||
},
|
||||
bank_account: {
|
||||
account_number: '40817810099910004312',
|
||||
currency: 'RUB',
|
||||
card_number: '0987654321098765',
|
||||
bank_name: 'Example Bank',
|
||||
details: {
|
||||
bik: '098765432',
|
||||
corr: '30101810400000000225',
|
||||
kpp: '098765432',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// const saved = await generator.save('organization', organizationData)
|
||||
const saved = await generator.save('organization', organizationData)
|
||||
|
||||
// const organization = await generator.get('organization', { username: organizationData.username }) as any
|
||||
const organization = await generator.get('organization', { username: organizationData.username }) as any
|
||||
|
||||
// expect(organization._id).toEqual(saved.insertedId)
|
||||
expect(organization._id).toEqual(saved.insertedId)
|
||||
|
||||
// Object.keys(organizationData).forEach((field) => {
|
||||
// expect(organization[field]).toBeDefined()
|
||||
// })
|
||||
// })
|
||||
Object.keys(organizationData).forEach((field) => {
|
||||
expect(organization[field]).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
// it('генерируем заявление на вступление юридического лица', async () => {
|
||||
// const document: IGeneratedDocument = await generator.generate({
|
||||
// code: 'registrator',
|
||||
// action: 'joincoop',
|
||||
// coopname: 'voskhod',
|
||||
// username: 'exampleorg',
|
||||
// lang: 'ru',
|
||||
// signature: signatureExample,
|
||||
// })
|
||||
it('генерируем заявление на вступление юридического лица', async () => {
|
||||
const document: IGeneratedDocument = await generator.generate({
|
||||
registry_id: 100,
|
||||
coopname: 'voskhod',
|
||||
username: 'exampleorg',
|
||||
lang: 'ru',
|
||||
signature: signatureExample,
|
||||
})
|
||||
|
||||
// const filename1 = `${document.meta.title}-${document.meta.username}.pdf`
|
||||
// await saveBufferToDisk(document.binary, filename1)
|
||||
const filename1 = `${document.meta.title}-${document.meta.username}.pdf`
|
||||
await saveBufferToDisk(document.binary, filename1)
|
||||
|
||||
// const regenerated_document: IGeneratedDocument = await generator.generate({
|
||||
// ...document.meta,
|
||||
// })
|
||||
const regenerated_document: IGeneratedDocument = await generator.generate({
|
||||
...document.meta,
|
||||
})
|
||||
|
||||
// const filename2 = `regenerated-${document.meta.title}-${document.meta.username}.pdf`
|
||||
// await saveBufferToDisk(regenerated_document.binary, filename2)
|
||||
const filename2 = `regenerated-${document.meta.title}-${document.meta.username}.pdf`
|
||||
await saveBufferToDisk(regenerated_document.binary, filename2)
|
||||
|
||||
// expect(document.meta).toEqual(regenerated_document.meta)
|
||||
// expect(document.hash).toEqual(regenerated_document.hash)
|
||||
expect(document.meta).toEqual(regenerated_document.meta)
|
||||
expect(document.hash).toEqual(regenerated_document.hash)
|
||||
|
||||
// const document_from_disk1 = await loadBufferFromDisk(filename1)
|
||||
// const document_from_disk2 = await loadBufferFromDisk(filename2)
|
||||
const document_from_disk1 = await loadBufferFromDisk(filename1)
|
||||
const document_from_disk2 = await loadBufferFromDisk(filename2)
|
||||
|
||||
// const hash1 = calculateSha256(document_from_disk1)
|
||||
// const hash2 = calculateSha256(document_from_disk2)
|
||||
const hash1 = calculateSha256(document_from_disk1)
|
||||
const hash2 = calculateSha256(document_from_disk2)
|
||||
|
||||
// // console.log('hash1: ', hash1)
|
||||
// // console.log('hash2: ', hash2)
|
||||
// // console.log(document)
|
||||
// console.log('hash1: ', hash1)
|
||||
// console.log('hash2: ', hash2)
|
||||
// console.log(document)
|
||||
|
||||
// expect(hash1).toEqual(hash2)
|
||||
expect(hash1).toEqual(hash2)
|
||||
|
||||
// const decision_document: IGeneratedDocument = await generator.generate({
|
||||
// code: 'registrator',
|
||||
// action: 'joincoopdec',
|
||||
// coopname: 'voskhod',
|
||||
// username: 'exampleorg',
|
||||
// lang: 'ru',
|
||||
// decision_id: 2,
|
||||
// })
|
||||
const decision_document: IGeneratedDocument = await generator.generate({
|
||||
registry_id: 501,
|
||||
coopname: 'voskhod',
|
||||
username: 'exampleorg',
|
||||
lang: 'ru',
|
||||
decision_id: 2,
|
||||
})
|
||||
|
||||
// const filename3 = `${decision_document.meta.title}-${decision_document.meta.username}.pdf`
|
||||
// await saveBufferToDisk(decision_document.binary, filename3)
|
||||
// })
|
||||
const filename3 = `${decision_document.meta.title}-${decision_document.meta.username}.pdf`
|
||||
await saveBufferToDisk(decision_document.binary, filename3)
|
||||
})
|
||||
|
||||
// it('сохранение данных индивидуального предпринимателя', async () => {
|
||||
// const entrepreneurData: ExternalEntrepreneurData = {
|
||||
// username: 'entrepreneur',
|
||||
// first_name: 'John',
|
||||
// last_name: 'Doe',
|
||||
// middle_name: 'Middle',
|
||||
// birthdate: '2023-04-01',
|
||||
// phone: '+1234567890',
|
||||
// email: 'john.doe@example.com',
|
||||
// full_address: 'переулок правды д. 1',
|
||||
// country: 'Russia',
|
||||
// city: 'Moscow',
|
||||
// details: {
|
||||
// inn: '0987654321',
|
||||
// ogrn: '0987654321098',
|
||||
// },
|
||||
// bank_account: {
|
||||
// account_number: '40817810099910004312',
|
||||
// currency: 'RUB',
|
||||
// card_number: '0987654321098765',
|
||||
// bank_name: 'Example Bank',
|
||||
// details: {
|
||||
// bik: '098765432',
|
||||
// corr: '30101810400000000225',
|
||||
// kpp: '098765432',
|
||||
// },
|
||||
// },
|
||||
// }
|
||||
it('сохранение данных индивидуального предпринимателя', async () => {
|
||||
const entrepreneurData: ExternalEntrepreneurData = {
|
||||
username: 'entrepreneur',
|
||||
first_name: 'John',
|
||||
last_name: 'Doe',
|
||||
middle_name: 'Middle',
|
||||
birthdate: '2023-04-01',
|
||||
phone: '+1234567890',
|
||||
email: 'john.doe@example.com',
|
||||
full_address: 'переулок правды д. 1',
|
||||
country: 'Russia',
|
||||
city: 'Moscow',
|
||||
details: {
|
||||
inn: '0987654321',
|
||||
ogrn: '0987654321098',
|
||||
},
|
||||
bank_account: {
|
||||
account_number: '40817810099910004312',
|
||||
currency: 'RUB',
|
||||
card_number: '0987654321098765',
|
||||
bank_name: 'Example Bank',
|
||||
details: {
|
||||
bik: '098765432',
|
||||
corr: '30101810400000000225',
|
||||
kpp: '098765432',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// const saved = await generator.save('entrepreneur', entrepreneurData)
|
||||
// console.log(saved)
|
||||
// const entrepreneur = await generator.get('entrepreneur', { username: entrepreneurData.username }) as any
|
||||
// console.log(entrepreneur)
|
||||
// expect(entrepreneur._id).toEqual(saved.insertedId)
|
||||
const saved = await generator.save('entrepreneur', entrepreneurData)
|
||||
console.log(saved)
|
||||
const entrepreneur = await generator.get('entrepreneur', { username: entrepreneurData.username }) as any
|
||||
console.log(entrepreneur)
|
||||
expect(entrepreneur._id).toEqual(saved.insertedId)
|
||||
|
||||
// Object.keys(entrepreneurData).forEach((field) => {
|
||||
// expect(entrepreneur[field]).toBeDefined()
|
||||
// })
|
||||
// })
|
||||
Object.keys(entrepreneurData).forEach((field) => {
|
||||
expect(entrepreneur[field]).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
// it('генерируем заявление на вступление индивидуального предпринимателя', async () => {
|
||||
// const document: IGeneratedDocument = await generator.generate({
|
||||
// code: 'registrator',
|
||||
// action: 'joincoop',
|
||||
// coopname: 'voskhod',
|
||||
// username: 'entrepreneur',
|
||||
// lang: 'ru',
|
||||
// signature: signatureExample,
|
||||
// })
|
||||
it('генерируем заявление на вступление индивидуального предпринимателя', async () => {
|
||||
const document: IGeneratedDocument = await generator.generate({
|
||||
registry_id: 100,
|
||||
coopname: 'voskhod',
|
||||
username: 'entrepreneur',
|
||||
lang: 'ru',
|
||||
signature: signatureExample,
|
||||
})
|
||||
|
||||
// const filename1 = `${document.meta.title}-${document.meta.username}.pdf`
|
||||
// await saveBufferToDisk(document.binary, filename1)
|
||||
const filename1 = `${document.meta.title}-${document.meta.username}.pdf`
|
||||
await saveBufferToDisk(document.binary, filename1)
|
||||
|
||||
// const regenerated_document: IGeneratedDocument = await generator.generate({
|
||||
// ...document.meta,
|
||||
// })
|
||||
const regenerated_document: IGeneratedDocument = await generator.generate({
|
||||
...document.meta,
|
||||
})
|
||||
|
||||
// const filename2 = `regenerated-${document.meta.title}-${document.meta.username}.pdf`
|
||||
// await saveBufferToDisk(regenerated_document.binary, filename2)
|
||||
const filename2 = `regenerated-${document.meta.title}-${document.meta.username}.pdf`
|
||||
await saveBufferToDisk(regenerated_document.binary, filename2)
|
||||
|
||||
// expect(document.meta).toEqual(regenerated_document.meta)
|
||||
// expect(document.hash).toEqual(regenerated_document.hash)
|
||||
expect(document.meta).toEqual(regenerated_document.meta)
|
||||
expect(document.hash).toEqual(regenerated_document.hash)
|
||||
|
||||
// const document_from_disk1 = await loadBufferFromDisk(filename1)
|
||||
// const document_from_disk2 = await loadBufferFromDisk(filename2)
|
||||
const document_from_disk1 = await loadBufferFromDisk(filename1)
|
||||
const document_from_disk2 = await loadBufferFromDisk(filename2)
|
||||
|
||||
// const hash1 = calculateSha256(document_from_disk1)
|
||||
// const hash2 = calculateSha256(document_from_disk2)
|
||||
const hash1 = calculateSha256(document_from_disk1)
|
||||
const hash2 = calculateSha256(document_from_disk2)
|
||||
|
||||
// // console.log('hash1: ', hash1)
|
||||
// // console.log('hash2: ', hash2)
|
||||
// // console.log(document)
|
||||
// console.log('hash1: ', hash1)
|
||||
// console.log('hash2: ', hash2)
|
||||
// console.log(document)
|
||||
|
||||
// expect(hash1).toEqual(hash2)
|
||||
expect(hash1).toEqual(hash2)
|
||||
|
||||
// const decision_document: IGeneratedDocument = await generator.generate({
|
||||
// code: 'registrator',
|
||||
// action: 'joincoopdec',
|
||||
// coopname: 'voskhod',
|
||||
// username: 'entrepreneur',
|
||||
// lang: 'ru',
|
||||
// decision_id: 3,
|
||||
// })
|
||||
const decision_document: IGeneratedDocument = await generator.generate({
|
||||
registry_id: 501,
|
||||
coopname: 'voskhod',
|
||||
username: 'entrepreneur',
|
||||
lang: 'ru',
|
||||
decision_id: 3,
|
||||
})
|
||||
|
||||
// const filename3 = `${decision_document.meta.title}-${decision_document.meta.username}.pdf`
|
||||
// await saveBufferToDisk(decision_document.binary, filename3)
|
||||
// })
|
||||
const filename3 = `${decision_document.meta.title}-${decision_document.meta.username}.pdf`
|
||||
await saveBufferToDisk(decision_document.binary, filename3)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"target": "ESNext",
|
||||
"lib": ["ESNext"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"moduleResolution": "Bundler",
|
||||
"resolveJsonModule": true,
|
||||
"strict": true,
|
||||
"strictNullChecks": true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "cooptypes",
|
||||
"type": "module",
|
||||
"version": "1.0.21",
|
||||
"version": "1.0.22-alpha.1",
|
||||
"description": "_description_",
|
||||
"author": "Alex Ant <dacom.dark.sun@gmail.com>",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import * as Permissions from '../../../common/permissions'
|
||||
import * as ContractNames from '../../../common/names'
|
||||
import type * as Draft from '../../../interfaces/draft'
|
||||
|
||||
export const authorizations = [{ permissions: [Permissions.active], actor: ContractNames._system }] as const
|
||||
|
||||
/**
|
||||
* Имя действия
|
||||
*/
|
||||
export const actionName = 'editdraft'
|
||||
|
||||
/**
|
||||
* @interface
|
||||
*/
|
||||
export type IEditDraft = Draft.IEditdraft
|
||||
@@ -1,6 +1,7 @@
|
||||
export * as CreateTranslation from './createTranslation'
|
||||
export * as CreateDraft from './createDraft'
|
||||
export * as EditDraft from './editDraft'
|
||||
export * as DeleteDraft from './deleteDraft'
|
||||
export * as CreateTranslation from './createTranslation'
|
||||
export * as EditTranslation from './editTranslation'
|
||||
|
||||
/**
|
||||
|
||||
@@ -23,13 +23,3 @@ export * as SetRights from './setRights'
|
||||
* @private
|
||||
*/
|
||||
export * as Init from './init'
|
||||
|
||||
/**
|
||||
* Действие подтверждения приёма заявления пайщика
|
||||
*/
|
||||
export * as ConfirmIncomeDocument from './confirmIncomeDocument'
|
||||
|
||||
/**
|
||||
* Действие отклонения приёма заявления пайщика
|
||||
*/
|
||||
export * as DeclineIncomeDocument from './declineIncomeDocument'
|
||||
|
||||
+2
-2
@@ -12,10 +12,10 @@ export const authorizations = [
|
||||
/**
|
||||
* Имя действия
|
||||
*/
|
||||
export const actionName = 'cnfrmindoc'
|
||||
export const actionName = 'confirmagree'
|
||||
|
||||
/**
|
||||
* @interface
|
||||
* Действие подтверждает приём заявления администратором
|
||||
*/
|
||||
export type IConfirmIncomeDocument = Soviet.ICnfrmindoc
|
||||
export type IConfirmAgreement = Soviet.IConfirmagree
|
||||
+2
-2
@@ -12,10 +12,10 @@ export const authorizations = [
|
||||
/**
|
||||
* Имя действия
|
||||
*/
|
||||
export const actionName = 'declnindoc'
|
||||
export const actionName = 'declineagree'
|
||||
|
||||
/**
|
||||
* @interface
|
||||
* Действие отклоняет заявление пайщика администратором
|
||||
*/
|
||||
export type IDeclineIncomeDocument = Soviet.IDeclnindoc
|
||||
export type IDeclineAgreement = Soviet.IDeclineagree
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Действие подтверждения приёма заявления пайщика
|
||||
*/
|
||||
export * as ConfirmAgreement from './confirmAgreement'
|
||||
|
||||
/**
|
||||
* Действие отклонения приёма заявления пайщика
|
||||
*/
|
||||
export * as DeclineAgreement from './declineAgreement'
|
||||
|
||||
/**
|
||||
* Действие отправки заявления на присоединение к ЦПП Кооператива
|
||||
*/
|
||||
export * as SendAgreement from './sendAgreement'
|
||||
|
||||
/**
|
||||
* Действие создания внутри-кооперативного соглашения.
|
||||
*/
|
||||
export * as MakeCoagreement from './makeCoagreement'
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as Permissions from '../../../../common/permissions'
|
||||
import type * as Soviet from '../../../../interfaces/soviet'
|
||||
import { Actors } from '../../../../common'
|
||||
|
||||
/**
|
||||
* Действие выполняется за подписью {@link Actors._admin | администратора}.
|
||||
*/
|
||||
export const authorizations = [
|
||||
{ permissions: [Permissions.active, Permissions.special], actor: Actors._admin },
|
||||
] as const
|
||||
|
||||
/**
|
||||
* Имя действия
|
||||
*/
|
||||
export const actionName = 'makecoagreem'
|
||||
|
||||
/**
|
||||
* Действие отправки заявления на присоединение к ЦПП кооператива
|
||||
*/
|
||||
export type IMakeCoagreement = Soviet.IMakecoagreem
|
||||
+2
-2
@@ -12,9 +12,9 @@ export const authorizations = [
|
||||
/**
|
||||
* Имя действия
|
||||
*/
|
||||
export const actionName = 'joinprog'
|
||||
export const actionName = 'sndagreement'
|
||||
|
||||
/**
|
||||
* Действие отправки заявления на присоединение к ЦПП кооператива
|
||||
*/
|
||||
export type IJoinProgram = Soviet.IJoinprog
|
||||
export type ISendAgreement = Soviet.ISndagreement
|
||||
@@ -35,3 +35,8 @@ export * as Boards from './boards'
|
||||
* Пространство управления администраторами.
|
||||
*/
|
||||
export * as Admins from './admins'
|
||||
|
||||
/**
|
||||
* Пространство управления соглашениями.
|
||||
*/
|
||||
export * as Agreements from './agreements'
|
||||
|
||||
@@ -12,8 +12,3 @@ export * as EditProgram from './editProgram'
|
||||
* Действие отключает целевую потребительскую программу маркетплейса.
|
||||
*/
|
||||
export * as DisableProgram from './disableProgram'
|
||||
|
||||
/**
|
||||
* Действие отправки заявления на присоединение к ЦПП Кооператива
|
||||
*/
|
||||
export * as JoinProgram from './joinProgram'
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ import { Actors } from '../../../common'
|
||||
/**
|
||||
* Имя таблицы
|
||||
*/
|
||||
export const tableName = 'indocuments'
|
||||
export const tableName = 'agreements'
|
||||
|
||||
/**
|
||||
* Таблица хранится в {@link Actors._coopname | области памяти кооператива}.
|
||||
@@ -14,4 +14,4 @@ export const scope = Actors._coopname
|
||||
/**
|
||||
* @interface
|
||||
*/
|
||||
export type IIncomeDocument = Soviet.IIndocument
|
||||
export type IAgreement = Soviet.IAgreement
|
||||
@@ -59,6 +59,6 @@ export * as ProgramWallets from './programWallets'
|
||||
export * as Wallets from './wallets'
|
||||
|
||||
/**
|
||||
* Таблица содержит заявления пайщиков кооператива, которые ожидают приёма, но не требуют решения совета.
|
||||
* Таблица содержит подписанные пайщиками документы соглашений с кооперативом
|
||||
*/
|
||||
export * as IncomeDocuments from './incomeDocuments'
|
||||
export * as Agreements from './agreements'
|
||||
|
||||
+24
-9
@@ -12,8 +12,6 @@ export interface IChainDocument {
|
||||
|
||||
// Определение базового интерфейса для мета-информации
|
||||
export interface IMetaDocument {
|
||||
code: string
|
||||
action: string
|
||||
title: string
|
||||
registry_id: number
|
||||
lang: LangType
|
||||
@@ -24,6 +22,7 @@ export interface IMetaDocument {
|
||||
created_at: string
|
||||
block_num: number
|
||||
timezone: string
|
||||
links: string[]
|
||||
}
|
||||
|
||||
export interface IGeneratedDocument {
|
||||
@@ -55,6 +54,7 @@ export interface IComplexDocument {
|
||||
statement: IComplexStatement
|
||||
decision: IComplexDecision
|
||||
acts: IComplexAct[]
|
||||
links: IGeneratedDocument[]
|
||||
}
|
||||
|
||||
export interface IGetComplexDocuments {
|
||||
@@ -83,26 +83,41 @@ export interface IGetResponse<T> {
|
||||
/**
|
||||
* Общий интерфейс для генерации/регенерации документа
|
||||
*/
|
||||
export interface IGenerate extends Omit<Partial<IMetaDocument>, 'registry_id' | 'title'> {
|
||||
code: string
|
||||
action: string
|
||||
export interface IGenerate extends Omit<Partial<IMetaDocument>, 'title'> {
|
||||
registry_id: number
|
||||
coopname: string
|
||||
username: string
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
/**
|
||||
* Интерфейс генерации заявления на вступление в кооператив
|
||||
*/
|
||||
export interface IGenerateJoinCoop extends IGenerate {
|
||||
signature: string
|
||||
skip_save: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Интерфейс генерации решения совета
|
||||
*/
|
||||
export interface IGenerateJoinCoopDecision extends IGenerate {
|
||||
decision_id: number
|
||||
}
|
||||
|
||||
/** Интерфейс генерации документа для присоединения к программе ЦПП */
|
||||
export interface IGenerateJoinProgram extends IGenerate {
|
||||
/**
|
||||
* Интерфейс генерации соглашения
|
||||
*/
|
||||
export interface IGenerateWalletAgreement extends IGenerate {
|
||||
registry_id: number
|
||||
protocol_number: string
|
||||
protocol_day_month_year: string
|
||||
}
|
||||
|
||||
export interface IDecisionData {
|
||||
id: number
|
||||
date: string
|
||||
time: string
|
||||
votes_for: number
|
||||
votes_against: number
|
||||
votes_abstained: number
|
||||
voters_percent: number
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export * as Documents from './documents'
|
||||
export * as Document from './document'
|
||||
export * as Users from './users'
|
||||
export * as Blockchain from './blockchain'
|
||||
export * as Model from './model'
|
||||
export * as Payments from './payments'
|
||||
export * as Registry from './registry'
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,62 @@
|
||||
import type { IGenerate, IMetaDocument } from '../../document'
|
||||
import type { ICooperativeData } from '../../model'
|
||||
import type { IEntrepreneurData, IIndividualData, IOrganizationData } from '../../users'
|
||||
|
||||
export const registry_id = 100
|
||||
|
||||
/**
|
||||
* Интерфейс генерации заявления на вступление в кооператив
|
||||
*/
|
||||
export interface Action extends IGenerate {
|
||||
signature: string
|
||||
skip_save: boolean
|
||||
}
|
||||
|
||||
// Модель данных
|
||||
export interface Model {
|
||||
type: string
|
||||
individual?: IIndividualData
|
||||
organization?: IOrganizationData
|
||||
entrepreneur?: IEntrepreneurData
|
||||
coop: ICooperativeData
|
||||
meta: IMetaDocument
|
||||
signature: string
|
||||
}
|
||||
|
||||
export const title = 'Заявление на вступление в кооператив'
|
||||
export const description = 'Форма заявления на вступление в потребительский кооператив'
|
||||
export const context = `<style>\nh1 {\nmargin: 0px;\ntext-align:center;\n}\n</style>\n{% if type == 'individual' %}\n<h1 class=\"header\">{% trans 'application_individual' %}</h1>\n<p style=\"text-align: center\">{% trans 'in' %} {{ coop.full_name }}<p>\n<p style=\"text-align: right\">{{ meta.created_at }}, {{coop.city}}</p>\n<p>{% trans 'to_council_of' %} {{ coop.short_name }} {% trans 'from' %} {{ individual.last_name }} {{ individual.first_name }} {{ individual.middle_name }}, {% trans 'birthdate' %} {{ individual.birthdate }}, {% trans 'registration_address' %} {{ individual.full_address }}, {% trans 'phone_and_email_notice', individual.phone, individual.email %}</p>\n<p>{% trans 'request_to_join' %} {{ coop.full_name }}. {% trans 'acknowledge_documents_individual' %} {% if coop.is_branched %}</p> \n<p>{% trans 'authorize_chairman_branch', individual.branch_name %} {% endif %} </p>\n<p>{% trans 'obligation_to_pay_individual', coop.initial, coop.minimum %}</p>\n<p>{% trans 'agreement_on_sms_email_notice_individual' %}</p>\n<div class=\"signature\">\n<img style=\"max-width: 150px;\" src=\"{{ signature }}\"/>\n<p>{% trans 'signature' %} </p>\n<p style=\"text-align: right;\">{{ individual.last_name }} {{ individual.first_name }} {{ individual.middle_name }}</p>\n</div>\n\n{% elif type == 'entrepreneur' %}\n<h1 class=\"header\">{% trans 'application_entrepreneur' %}</h1>\n<p style=\"text-align: center\">{% trans 'in' %} {{ coop.full_name }}<p>\n<p style=\"text-align: right\">{{ meta.created_at }}, {{coop.city}}</p> <p>{% trans 'to_council_of' %} {{ coop.short_name }} {% trans 'from_entrepreneur' %} {{ entrepreneur.last_name }} {{ entrepreneur.first_name }} {{ entrepreneur.middle_name }}, {% trans 'birthdate' %} {{ entrepreneur.birthdate }}, {% trans 'registration_address' %} {{ entrepreneur.full_address }}, {% trans 'entrepreneur_details', entrepreneur.details.inn, entrepreneur.details.ogrn, entrepreneur.bank_account.account_number, entrepreneur.bank_account.details.kpp, entrepreneur.bank_account.details.corr, entrepreneur.bank_account.details.bik, entrepreneur.bank_account.bank_name %}, {% trans 'phone_and_email_notice', entrepreneur.phone, entrepreneur.email %}</p>\n<p>{% trans 'request_to_join' %} {{ coop.full_name }}. {% trans 'acknowledge_documents_entrepreneur' %}</p> \n<p>{% if coop.is_branched %}{% trans 'authorize_chairman_branch', entrepreneur.branch_name %} {% endif %} </p>\n<p>{% trans 'obligation_to_pay_entrepreneur', coop.initial, coop.minimum %} </p>\n<p>{% trans 'agreement_on_sms_email_notice_entrepreneur' %}</p>\n<div class=\"signature\">\n<img style=\"max-width: 150px;\" src=\"{{ signature }}\"/>\n<p>{% trans 'signature' %} </p>\n<p style=\"text-align: right;\">{{ entrepreneur.last_name }} {{ entrepreneur.first_name }} {{ entrepreneur.middle_name }}</p>\n</div>\n\n{% elif type == 'organization' %}\n<h1 class=\"header\">{% trans 'application_legal_entity' %}</h1>\n<p style=\"text-align: center\">{% trans 'in' %} {{ coop.full_name }}<p>\n<p style=\"text-align: right\">{{ meta.created_at }}, {{coop.city}}</p>\n<p>{% trans 'to_council_of' %} «{{ coop.full_name }}» {% trans 'from_legal_entity' %} {{ organization.full_name }}, {% trans 'legal_address' %} {{ organization.full_address }}, {% trans 'legal_entity_details', organization.details.inn, organization.details.ogrn, organization.bank_account.account_number, organization.bank_account.details.kpp, organization.bank_account.details.corr, organization.bank_account.details.bik, organization.bank_account.bank_name %}, {% trans 'phone_and_email_notice', organization.phone, organization.email %}</p>\n<p>{% trans 'request_to_join_legal_entity', organization.represented_by.position, organization.represented_by.last_name, organization.represented_by.first_name, organization.represented_by.middle_name, organization.represented_by.based_on %} {{ coop.full_name }}.</p>\n<p>{% trans 'acknowledge_documents_legal_entity' %}</p> \n<p>{% if coop.is_branched %}{% trans 'authorize_chairman_branch_organization', organization.branch_name %} {% endif %}</p>\n<p>{% trans 'obligation_to_pay_legal_entity', coop.initial, coop.minimum %}</p>\n<p>{% trans 'agreement_on_sms_email_notice_legal_entity' %}</p>\n<div class=\"signature\">\n<img style=\"max-width: 150px;\" src=\"{{ signature }}\"/>\n<p>{% trans 'signature' %} </p>\n<p style=\"text-align: right;\">{{ organization.represented_by.last_name }} {{ organization.represented_by.first_name }} {{ organization.represented_by.middle_name }}</p>\n</div>\n\n{% endif %}\n\n`
|
||||
|
||||
export const translations = {
|
||||
ru: {
|
||||
from: 'от',
|
||||
application_individual: 'Заявление физического лица о приеме в пайщики',
|
||||
to_council_of: 'В Совет',
|
||||
birthdate: 'дата рождения',
|
||||
registration_address: 'адрес регистрации (как в паспорте): ',
|
||||
phone_and_email_notice: 'номер телефона с активированной функцией получения sms: {0}, адрес электронной почты: {1}.',
|
||||
acknowledge_documents_individual: 'Подтверждаю, что с Уставом и иными нормативными документами Общества ознакомлен(а).',
|
||||
agreement_on_sms_email_notice_individual: 'Выражаю свое согласие с тем, что информация, отправляемая Обществом в sms-сообщениях на указанный мной номер телефона, в сообщениях на указанный мной адрес электронной почты, или в PUSH уведомлениях с сайта, приравнивается к уведомлению меня Обществом в письменной форме.',
|
||||
application_entrepreneur: 'Заявление индивидуального предпринимателя о приеме в пайщики',
|
||||
from_entrepreneur: 'от индивидуального предпринимателя',
|
||||
acknowledge_documents_entrepreneur: 'Подтверждаю, что с Уставом и иными нормативными документами Общества ознакомлен(а).',
|
||||
agreement_on_sms_email_notice_entrepreneur: 'Выражаю свое согласие с тем, что информация, отправляемая Обществом в sms-сообщениях на указанный мной номер телефона, в сообщениях на указанный мной адрес электронной почты, или в PUSH уведомлениях с сайта, приравнивается к уведомлению меня Обществом в письменной форме.',
|
||||
application_legal_entity: 'Заявление юридического лица о приеме в пайщики',
|
||||
from_legal_entity: 'от юридического лица',
|
||||
legal_address: 'юридический адрес организации',
|
||||
legal_entity_details: 'ИНН {0}, ОГРН {1}, Р/с {2}, КПП {3}, К/с {4}, БИК {5}, банк получателя {6}',
|
||||
acknowledge_documents_legal_entity: 'Подтверждает, что с Уставом и иными нормативными документами Общества ознакомлен.',
|
||||
agreement_on_sms_email_notice_legal_entity: 'Выражает свое согласие с тем, что информация, отправляемая Обществом в sms-сообщениях на указанный номер телефона, в сообщениях на указанный адрес электронной почты, или в PUSH уведомлениях с сайта, приравнивается к уведомлению Заявителя Обществом в письменной форме.',
|
||||
obligation_to_pay_individual: 'Обязуюсь своевременно внести в Общество вступительный {0} и минимальный паевой {1} взносы в порядке, предусмотренном Уставом Общества.',
|
||||
obligation_to_pay_entrepreneur: 'Обязуюсь своевременно внести в Общество вступительный {0} и минимальный паевой {1} взносы в порядке, предусмотренном Уставом Общества.',
|
||||
obligation_to_pay_legal_entity: 'Обязуется своевременно внести в Общество вступительный {0} и минимальный паевой {1} взносы в порядке, предусмотренном Уставом Общества.',
|
||||
entrepreneur_details: 'ИНН {0}, ОГРНИП {1}, Р/с {2}, КПП {3}, К/с {4}, БИК {5}, банк получателя {6}',
|
||||
authorize_chairman_branch: 'Уполномочиваю Председателя кооперативного участка {0} принимать участие с правом голоса в Общих собраниях уполномоченных Общества, на период моего членства в Обществе при указанном кооперативном участке.',
|
||||
request_to_join_legal_entity: 'Заявитель, в лице представителя юридического лица - {0} {1} {2} {3}, действующий на основании {4}, просит принять в пайщики ',
|
||||
authorize_chairman_branch_organization: 'Уполномочивает Председателя кооперативного участка {0} принимать участие с правом голоса в Общих собраниях уполномоченных Общества, на период моего членства в Обществе при указанном кооперативном участке.',
|
||||
signature: 'подпись',
|
||||
in: 'в',
|
||||
request_to_join: 'Прошу принять меня в пайщики',
|
||||
},
|
||||
// ... другие переводы
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import type { IDecisionData, IGenerate, IMetaDocument } from '../../document'
|
||||
import type { ICooperativeData } from '../../model'
|
||||
import type { IEntrepreneurData, IIndividualData, IOrganizationData } from '../../users'
|
||||
|
||||
export const registry_id = 501
|
||||
|
||||
/**
|
||||
* Интерфейс генерации решения совета
|
||||
*/
|
||||
export interface Action extends IGenerate {
|
||||
decision_id: number
|
||||
}
|
||||
|
||||
// Модель данных
|
||||
export interface Model {
|
||||
type: string
|
||||
|
||||
individual?: IIndividualData
|
||||
organization?: IOrganizationData
|
||||
entrepreneur?: IEntrepreneurData
|
||||
coop: ICooperativeData
|
||||
meta: IMetaDocument
|
||||
decision: IDecisionData
|
||||
}
|
||||
|
||||
export const title = 'Решение совета о приёме пайщика в кооператив'
|
||||
export const description = 'Форма решения совета о приёме пайщика в потребительский кооператив'
|
||||
export const context = `<style> \nh1 {\nmargin: 0px; \ntext-align:center;\n}\nh3{\nmargin: 0px;\npadding-top: 15px;\n}\n.about {\npadding: 20px;\n}\n.about p{\nmargin: 0px;\n}\n.signature {\npadding-top: 20px;\n}\n</style>\n\n<h1 class=\"header\">{% trans 'protocol_number', decision.id %}</h1>\n<p style=\"text-align:center\">{% trans 'council_meeting_name' %}\n{{ coop.full_name }}</p>\n<p style=\"text-align: right\"> {{ meta.created_at }}, {{ coop.city }}</p>\n\n<div class=\"about\">\n<p>{% trans 'meeting_format' %}</p>\n<p>{% trans 'meeting_place', coop.full_address %}</p>\n<p>{% trans 'meeting_date', decision.date %}</p>\n<p>{% trans 'opening_time', decision.time %}</p>\n</div>\n\n<h3>{% trans 'council_members' %}</h3>\n<ol>{% for member in coop.members %}\n<li>{{ member.last_name }} {{ member.first_name }} {{ member.middle_name }}{% if member.is_chairman %} {% trans 'chairman_of_the_council' %}{% endif %}</li>\n{% endfor %}\n</ol>\n\n<h3>{% trans 'meeting_legality' %} </h3>\n<p>{% trans 'voting_results', decision.voters_percent %} {% trans 'quorum' %} {% trans 'chairman_of_the_meeting', coop.chairman.last_name, coop.chairman.first_name, coop.chairman.middle_name %}.</p>\n\n<h3>{% trans 'agenda' %}</h3>\n<ol><li> {% trans 'decision_joincoop1' %}{% if type == 'individual' %} {{individual.last_name}} {{individual.first_name}} {{individual.middle.name}} ({{individual.birthdate}} {% trans 'birthdate' %}) {% endif %}{% if type == 'entrepreneur' %} {% trans 'entrepreneur' %} {{entrepreneur.last_name}} {{entrepreneur.first_name}} {{entrepreneur.middle.name}} ({% trans 'ogrnip' %} {{entrepreneur.details.ogrn}}) {% endif %}{% if type == 'organization' %} {{organization.short_name}} ({% trans 'ogrn' %} {{organization.details.ogrn}}) {% endif %}{% trans 'in_participants' %} {{ coop.short_name }}.\n</li></ol>\n\n<h3>{% trans 'voting' %}</h3>\n<p>{% trans 'vote_results', decision.votes_for, decision.votes_against, decision.votes_abstained %} </p>\n\n<h3>{% trans 'decision_made' %}</h3>\n<p>{% trans 'decision_joincoop2' %}{% if type == 'individual' %} {{individual.last_name}} {{individual.first_name}} {{individual.middle.name}} {{individual.birthdate}} {% trans 'birthdate' %}{% endif %} {% if type == 'entrepreneur' %}{% trans 'entrepreneur' %} {{entrepreneur.last_name}} {{entrepreneur.first_name}} {{entrepreneur.middle.name}}, {% trans 'ogrnip' %} {{entrepreneur.details.ogrn}}{% endif %} {% if type == 'organization' %} {{organization.short_name}}, {% trans 'ogrn' %} {{organization.details.ogrn}} {% endif %}</p>\n<hr>\n<p>{% trans 'closing_time', decision.time %}</p>\n\n<div class=\"signature\"> \n<p>{% trans 'signature' %}<p>\n<p style=\"text-align: right;\">{% trans 'chairman' %} {{ coop.chairman.last_name }} {{ coop.chairman.first_name }} {{ coop.chairman.middle_name }}</p></div>`
|
||||
export const translations = {
|
||||
ru: {
|
||||
meeting_format: 'Форма проведения собрания совета: заочная',
|
||||
meeting_date: 'Дата проведения собрания совета: {0}',
|
||||
meeting_place: 'Место проведения собрания совета: {0}',
|
||||
opening_time: 'Время открытия собрания совета: {0}',
|
||||
council_members: 'Члены Совета',
|
||||
voting_results: 'Количество голосов составляет {0}% от общего числа членов Совета.',
|
||||
meeting_legality: 'Собрание правомочно',
|
||||
chairman_of_the_meeting: 'Председатель собрания совета: {0} {1} {2}',
|
||||
agenda: 'Повестка дня',
|
||||
vote_results: 'По первому вопросу повестки дня проголосовали: «За» – {0}; «Против» - {1}; «Воздержался» - {2}.',
|
||||
decision_made: 'Решили',
|
||||
closing_time: 'Время закрытия собрания совета: {0}.',
|
||||
protocol_number: 'Протокол № {0}',
|
||||
council_meeting_name: 'Собрания Совета',
|
||||
chairman_of_the_council: '(председатель совета)',
|
||||
signature: 'Документ подписан электронной подписью.',
|
||||
chairman: 'Председатель',
|
||||
birthdate: 'г.р.',
|
||||
ogrnip: 'ОГРНИП',
|
||||
entrepreneur: 'ИП',
|
||||
ogrn: 'ОГРН',
|
||||
quorum: 'Кворум для решения поставленных на повестку дня вопросов имеется.',
|
||||
voting: 'Голосование',
|
||||
in_participants: 'о приёме в пайщики',
|
||||
decision_joincoop1: 'Рассмотреть заявление',
|
||||
decision_joincoop2: 'Принять нового пайщика',
|
||||
},
|
||||
// ... другие переводы
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * as WalletAgreement from './1.WalletAgreement'
|
||||
export * as ParticipantApplication from './100.ParticipantApplication'
|
||||
export * as DecisionOfParticipantApplication from './501.DecisionOfParticipantApplication'
|
||||
@@ -27,7 +27,7 @@ export interface ICreatedraft {
|
||||
export interface ICreatetrans {
|
||||
scope: IName
|
||||
username: IName
|
||||
draft_id: IUint64
|
||||
registry_id: IUint64
|
||||
lang: IName
|
||||
data: string
|
||||
}
|
||||
@@ -35,7 +35,7 @@ export interface ICreatetrans {
|
||||
export interface IDeldraft {
|
||||
scope: IName
|
||||
username: IName
|
||||
draft_id: IUint64
|
||||
registry_id: IUint64
|
||||
}
|
||||
|
||||
export interface IDeltrans {
|
||||
@@ -44,6 +44,16 @@ export interface IDeltrans {
|
||||
translate_id: IUint64
|
||||
}
|
||||
|
||||
export interface IEditdraft {
|
||||
scope: IName
|
||||
username: IName
|
||||
registry_id: IUint64
|
||||
title: string
|
||||
description: string
|
||||
context: string
|
||||
model: string
|
||||
}
|
||||
|
||||
export interface IEdittrans {
|
||||
scope: IName
|
||||
username: IName
|
||||
@@ -60,7 +70,6 @@ export interface INewid {
|
||||
}
|
||||
|
||||
export interface IOnedraft {
|
||||
id: IUint64
|
||||
registry_id: IUint64
|
||||
version: IUint64
|
||||
default_translation_id: IUint64
|
||||
|
||||
@@ -65,6 +65,19 @@ export interface IAdduser {
|
||||
spread_initial: boolean
|
||||
}
|
||||
|
||||
export interface IAgreement {
|
||||
id: IUint64
|
||||
coopname: IName
|
||||
username: IName
|
||||
type: IName
|
||||
program_id: IUint64
|
||||
draft_id: IUint64
|
||||
version: IUint64
|
||||
document: IDocument
|
||||
status: IName
|
||||
updated_at: ITimePointSec
|
||||
}
|
||||
|
||||
export interface IAuthorize {
|
||||
coopname: IName
|
||||
chairman: IName
|
||||
@@ -140,11 +153,18 @@ export interface IChanges {
|
||||
return_product_decision_id: IUint64
|
||||
}
|
||||
|
||||
export interface ICnfrmindoc {
|
||||
export interface ICoagreement {
|
||||
type: IName
|
||||
coopname: IName
|
||||
registrator: IName
|
||||
program_id: IUint64
|
||||
draft_id: IUint64
|
||||
}
|
||||
|
||||
export interface IConfirmagree {
|
||||
coopname: IName
|
||||
administrator: IName
|
||||
username: IName
|
||||
indoc_id: IUint64
|
||||
agreement_id: IUint64
|
||||
}
|
||||
|
||||
export interface ICounts extends ICountsBase {
|
||||
@@ -185,8 +205,7 @@ export interface ICreatebranch {
|
||||
export interface ICreateprog {
|
||||
coopname: IName
|
||||
username: IName
|
||||
program_type: IName
|
||||
draft_registry_id: IUint64
|
||||
draft_id: IUint64
|
||||
title: string
|
||||
announce: string
|
||||
description: string
|
||||
@@ -215,11 +234,11 @@ export interface IDecision {
|
||||
created_at: ITimePointSec
|
||||
}
|
||||
|
||||
export interface IDeclnindoc {
|
||||
export interface IDeclineagree {
|
||||
coopname: IName
|
||||
registrator: IName
|
||||
administrator: IName
|
||||
username: IName
|
||||
indoc_id: IUint64
|
||||
agreement_id: IUint64
|
||||
comment: string
|
||||
}
|
||||
|
||||
@@ -276,7 +295,7 @@ export interface IEditprog {
|
||||
coopname: IName
|
||||
username: IName
|
||||
program_id: IUint64
|
||||
draft_registry_id: IUint64
|
||||
draft_id: IUint64
|
||||
title: string
|
||||
announce: string
|
||||
description: string
|
||||
@@ -299,17 +318,6 @@ export interface IFundwithdraw {
|
||||
document: IDocument
|
||||
}
|
||||
|
||||
export interface IIndocument {
|
||||
id: IUint64
|
||||
coopname: IName
|
||||
username: IName
|
||||
type: IName
|
||||
secondary_id: IUint64
|
||||
draft_registry_id: IUint64
|
||||
version: IUint64
|
||||
document: IDocument
|
||||
}
|
||||
|
||||
export interface IInit {
|
||||
}
|
||||
|
||||
@@ -326,12 +334,12 @@ export interface IJoincoops {
|
||||
notice: string
|
||||
}
|
||||
|
||||
export interface IJoinprog {
|
||||
export interface IMakecoagreem {
|
||||
coopname: IName
|
||||
username: IName
|
||||
document: IDocument
|
||||
administrator: IName
|
||||
type: IName
|
||||
draft_id: IUint64
|
||||
program_id: IUint64
|
||||
version: IUint64
|
||||
}
|
||||
|
||||
export interface IMigrate {
|
||||
@@ -402,9 +410,9 @@ export interface IParticipant {
|
||||
|
||||
export interface IProgram {
|
||||
id: IUint64
|
||||
draft_registry_id: IUint64
|
||||
coopname: IName
|
||||
draft_id: IUint64
|
||||
program_type: IName
|
||||
coopname: IName
|
||||
is_active: boolean
|
||||
title: string
|
||||
announce: string
|
||||
@@ -423,10 +431,9 @@ export interface IProgwallet {
|
||||
id: IUint64
|
||||
coopname: IName
|
||||
program_id: IUint64
|
||||
version: IUint64
|
||||
agreement_id: IUint64
|
||||
username: IName
|
||||
available: IAsset
|
||||
document: IDocument
|
||||
}
|
||||
|
||||
export interface IRecieved {
|
||||
@@ -457,6 +464,14 @@ export interface ISetrights {
|
||||
rights: IRight[]
|
||||
}
|
||||
|
||||
export interface ISndagreement {
|
||||
coopname: IName
|
||||
administrator: IName
|
||||
username: IName
|
||||
agreement_type: IName
|
||||
document: IDocument
|
||||
}
|
||||
|
||||
export interface IStaff {
|
||||
username: IName
|
||||
position_title: string
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"target": "ESNext",
|
||||
"lib": ["ESNext"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"moduleResolution": "Node",
|
||||
"resolveJsonModule": true,
|
||||
"strict": true,
|
||||
"strictNullChecks": true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "coop-notificator",
|
||||
"type": "module",
|
||||
"version": "0.0.25",
|
||||
"version": "0.0.26-alpha.1",
|
||||
"private": true,
|
||||
"packageManager": "pnpm@9.1.1",
|
||||
"description": "_description_",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable node/prefer-global/process */
|
||||
import type { BaseHandler } from '../handlers/baseHandler'
|
||||
import { EmailNotificationHandler } from '../handlers/emailNotificationHandler'
|
||||
import { PushNotificationHandler } from '../handlers/pushNotificationHandler'
|
||||
@@ -7,11 +8,11 @@ export class NotificationHandlerFactory {
|
||||
static createHandler(group: string, type: string): BaseHandler | null {
|
||||
if (type === 'action') {
|
||||
switch (group) {
|
||||
case 'emailGroup':
|
||||
case `${process.env.COOPNAME}-email`:
|
||||
return new EmailNotificationHandler()
|
||||
case 'websocketGroup':
|
||||
case `${process.env.COOPNAME}-websocket`:
|
||||
return new WebsocketNotificationHandler()
|
||||
case 'pushGroup':
|
||||
case `${process.env.COOPNAME}-push`:
|
||||
return new PushNotificationHandler()
|
||||
default:
|
||||
return null
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable node/prefer-global/process */
|
||||
import dotenv from 'dotenv'
|
||||
import Redis from 'ioredis'
|
||||
|
||||
@@ -10,11 +11,8 @@ startSocketServer()
|
||||
|
||||
const consumer = `consumer-${Math.random()}`
|
||||
|
||||
// eslint-disable-next-line node/prefer-global/process
|
||||
const redisPort = Number(process.env.REDIS_PORT) || 6379
|
||||
// eslint-disable-next-line node/prefer-global/process
|
||||
const redisHost = process.env.REDIS_HOST
|
||||
// eslint-disable-next-line node/prefer-global/process
|
||||
const redisPassword = process.env.REDIS_PASSWORD
|
||||
|
||||
const redis = new Redis({
|
||||
@@ -68,7 +66,7 @@ async function consumeMessages(group: string) {
|
||||
|
||||
// Главная функция выполнения
|
||||
(async () => {
|
||||
const groups = ['emailGroup', 'websocketGroup'] // , 'pushGroup'
|
||||
const groups = [`${process.env.COOPNAME}-email`, `${process.env.COOPNAME}-websocket`] // push
|
||||
for (const group of groups)
|
||||
await createConsumerGroup('notifications', group)
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ export async function postRequest(url: string, data: any): Promise<any> {
|
||||
return response.data
|
||||
}
|
||||
catch (error: any) {
|
||||
console.error('Ошибка при выполнении POST запроса:', error.message)
|
||||
console.error('Ошибка при выполнении POST запроса:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user