From 8ebd735e7e55bdd303e3b5a2095e3acd0ff2483f Mon Sep 17 00:00:00 2001 From: Alex Ant Date: Sun, 13 Oct 2024 13:08:59 +0500 Subject: [PATCH] update --- README.md | 2 +- components/migrator/migration_state.json | 3 +- .../migrations/010_edit_all_drafts.ts | 96 +++++++++++++++++++ ...all_drafts.ts => 001_create_all_drafts.ts} | 4 +- .../{ => archive}/009_edit_draft_1.ts | 0 components/migrator/src/migrator.ts | 37 ++++--- 6 files changed, 123 insertions(+), 19 deletions(-) create mode 100644 components/migrator/migrations/010_edit_all_drafts.ts rename components/migrator/migrations/archive/{001_update_all_drafts.ts => 001_create_all_drafts.ts} (94%) rename components/migrator/migrations/{ => archive}/009_edit_draft_1.ts (100%) diff --git a/README.md b/README.md index 6f5b1fd7587..98f5e118027 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # MONOCOOP -Моно-репозиторий компонент Цифрового Кооператива. +Моно-репозиторий компонент клиента системы электронного документооборота для потребительских и производственных кооперативов. ## Инициализация ``` diff --git a/components/migrator/migration_state.json b/components/migrator/migration_state.json index 49b0e055685..473b55adea3 100644 --- a/components/migrator/migration_state.json +++ b/components/migrator/migration_state.json @@ -1,3 +1,4 @@ { - "lastMigration": "009_edit_draft_1.ts" + "local": "010_edit_all_drafts.ts", + "test": "010_edit_all_drafts.ts" } \ No newline at end of file diff --git a/components/migrator/migrations/010_edit_all_drafts.ts b/components/migrator/migrations/010_edit_all_drafts.ts new file mode 100644 index 00000000000..312da77dc02 --- /dev/null +++ b/components/migrator/migrations/010_edit_all_drafts.ts @@ -0,0 +1,96 @@ +import {Migration} from '../src/migration_interface' +import { api } from '../src/eos' +import { Cooperative, DraftContract, SovietContract } from 'cooptypes'; +import { Registry } from 'coopdoc-generator-ts'; + +export class InitialMigration implements Migration { + async run(): Promise { + + const editTranslation = async(params: DraftContract.Actions.EditTranslation.IEditTranslation) => { + await api.transact({ + actions: [ + { + account: DraftContract.contractName.production, + name: DraftContract.Actions.EditTranslation.actionName, + authorization: [ + { + actor: 'eosio', + permission: "active", + }, + ], + data: { + ...params, + }, + }, + ], + }, + { + blocksBehind: 3, + expireSeconds: 30, + } + ) + + console.log("Перевод установлен для:", params.translate_id) + } + + const editDraft = async(params: DraftContract.Actions.EditDraft.IEditDraft) => { + + await api.transact( + { + actions: [ + { + account: DraftContract.contractName.production, + name: DraftContract.Actions.EditDraft.actionName, + authorization: [ + { + actor: 'eosio', + permission: "active", + }, + ], + data: { + ...params, + }, + }, + ], + }, + { + blocksBehind: 3, + expireSeconds: 30, + } + ) + + console.log("Шаблон отредактирован: ", params.title, params.registry_id) + } + + try { + const drafts = await api.rpc.get_table_rows({json: true, code: 'draft', scope: 'draft', table: 'drafts'}) + // console.log(drafts) + + for (const draft of drafts.rows) { + const template = Registry[(draft.registry_id as unknown) as keyof typeof Registry] + + await editDraft({ + scope: DraftContract.contractName.production, + username: 'eosio', + registry_id: draft.registry_id, + title: template.Template.title, + description: template.Template.description, + context: template.Template.context, + model: JSON.stringify(template.Template.model), + }) + + await editTranslation({ + scope: DraftContract.contractName.production, + username: 'eosio', + translate_id: draft.default_translation_id, + data: JSON.stringify(template.Template.translations.ru) + }) + + } + + console.log('update drafts successful'); + } catch (error) { + console.error('Error during migration:', error); + } + } +} diff --git a/components/migrator/migrations/archive/001_update_all_drafts.ts b/components/migrator/migrations/archive/001_create_all_drafts.ts similarity index 94% rename from components/migrator/migrations/archive/001_update_all_drafts.ts rename to components/migrator/migrations/archive/001_create_all_drafts.ts index a9b6f1d0fe6..b54b27345d7 100644 --- a/components/migrator/migrations/archive/001_update_all_drafts.ts +++ b/components/migrator/migrations/archive/001_create_all_drafts.ts @@ -1,5 +1,5 @@ -import {Migration} from '../src/migration_interface' -import { api } from '../src/eos' +import {Migration} from '../../src/migration_interface' +import { api } from '../../src/eos' import { Cooperative, DraftContract, SovietContract } from 'cooptypes'; import { Registry } from 'coopdoc-generator-ts'; diff --git a/components/migrator/migrations/009_edit_draft_1.ts b/components/migrator/migrations/archive/009_edit_draft_1.ts similarity index 100% rename from components/migrator/migrations/009_edit_draft_1.ts rename to components/migrator/migrations/archive/009_edit_draft_1.ts diff --git a/components/migrator/src/migrator.ts b/components/migrator/src/migrator.ts index 8a4e872becd..4a8b4cd2e31 100644 --- a/components/migrator/src/migrator.ts +++ b/components/migrator/src/migrator.ts @@ -4,27 +4,35 @@ import { getDirname } from './utils/dirname'; import { MigrationFactory } from './factory'; interface MigrationState { - lastMigration: string | null; + [env: string]: string | null; } export class Migrator { private stateFilePath: string; private state: MigrationState; + private env: string; constructor() { const __dirname = getDirname(import.meta.url); this.stateFilePath = path.join(__dirname, '../migration_state.json'); - this.state = { lastMigration: null }; + this.env = process.env.NODE_ENV || 'local'; // Получаем текущее окружение + this.state = { [this.env]: null }; // Инициализируем состояние для текущего окружения } // Загружаем состояние из файла private async loadState(): Promise { try { if (await fs.pathExists(this.stateFilePath)) { - const stateData = await fs.readFile(this.stateFilePath, 'utf-8'); // Используем fs напрямую + const stateData = await fs.readFile(this.stateFilePath, 'utf-8'); this.state = JSON.parse(stateData); } else { - // Если файл не существует, создаем его с начальным значением + // Если файл не существует, создаем его с начальными значениями для всех окружений + await this.saveState(); + } + + // Если состояние для текущего окружения отсутствует, инициализируем его + if (!this.state[this.env]) { + this.state[this.env] = null; await this.saveState(); } } catch (error) { @@ -35,29 +43,28 @@ export class Migrator { // Сохраняем состояние в файл private async saveState(): Promise { try { - await fs.writeFile(this.stateFilePath, JSON.stringify(this.state, null, 2)); // Используем fs напрямую + await fs.writeFile(this.stateFilePath, JSON.stringify(this.state, null, 2)); } catch (error) { console.error('Failed to save migration state:', error); } } - // Получаем список миграций, начиная с последней выполненной, и исключаем ненужные файлы + // Получаем список миграций, начиная с последней выполненной для текущего окружения private async getPendingMigrations(): Promise { const __dirname = getDirname(import.meta.url); const migrationsDir = path.join(__dirname, '../migrations'); - const allMigrationFiles = await fs.readdir(migrationsDir); // Используем fs напрямую + const allMigrationFiles = await fs.readdir(migrationsDir); - // Фильтруем файлы, чтобы использовать только те, что соответствуют шаблону миграций (например, '001_some_migration.ts') const migrationFiles = allMigrationFiles.filter(file => file.match(/^\d+.*\.ts$/)); - if (this.state.lastMigration) { - const lastMigrationIndex = migrationFiles.indexOf(this.state.lastMigration); + if (this.state[this.env]) { + const lastMigrationIndex = migrationFiles.indexOf(this.state[this.env] as string); return lastMigrationIndex >= 0 - ? migrationFiles.slice(lastMigrationIndex + 1) // Возвращаем миграции после последней выполненной - : migrationFiles; // Если последняя миграция не найдена (возможно, была удалена), выполняем все + ? migrationFiles.slice(lastMigrationIndex + 1) + : migrationFiles; // Если последняя миграция не найдена, выполняем все миграции } - return migrationFiles; // Если миграции еще не запускались, выполняем все + return migrationFiles; // Если миграции еще не запускались для текущего окружения, выполняем все } // Основной метод для выполнения миграций @@ -78,8 +85,8 @@ export class Migrator { console.log(`Running migration: ${file}`); await migration.run(); - // Обновляем состояние и сохраняем его - this.state.lastMigration = file; + // Обновляем состояние для текущего окружения и сохраняем его + this.state[this.env] = file; await this.saveState(); } }