taxes_az/float-change.js

152 lines
6.2 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const fs = require('fs');
const path = require('path');
// Счетчики
let totalFilesProcessed = 0;
let totalChanges = 0;
let filesModified = 0;
function processJsonFile(filePath) {
try {
// Читаем файл как текст
let content = fs.readFileSync(filePath, 'utf8');
const originalContent = content;
const fileName = path.basename(path.dirname(filePath));
console.log(`📁 Обработка: ${fileName}/`);
let changesCount = 0;
// Разбиваем на строки
const lines = content.split('\n');
const newLines = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
newLines.push(line);
// Если строка содержит "fieldtype": "Float"
if (line.includes('"fieldtype": "Float"') || line.includes('"fieldtype":"Float"')) {
// Проверяем, что следующая строка НЕ содержит precision
let hasPrecision = false;
if (i + 1 < lines.length) {
hasPrecision = lines[i + 1].includes('"precision"');
}
if (!hasPrecision) {
// Находим отступ текущей строки
const indent = line.match(/^(\s*)/)[1];
// Проверяем, есть ли запятая в конце строки
if (!line.trim().endsWith(',')) {
// Заменяем последнюю добавленную строку, добавив запятую
newLines[newLines.length - 1] = line.replace(/"Float"/, '"Float",');
}
// Добавляем строку с precision
const precisionLine = `${indent}"precision": "2",`;
newLines.push(precisionLine);
changesCount++;
console.log(` ✓ Добавлен precision (строка ${i + 1})`);
}
}
}
// Собираем обратно
if (changesCount > 0) {
content = newLines.join('\n');
// Убираем лишнюю запятую перед закрывающей скобкой, если есть
content = content.replace(/,(\s*\n\s*\})/g, '$1');
fs.writeFileSync(filePath, content, 'utf8');
console.log(` ✅ Обновлено. Добавлено precision: ${changesCount}\n`);
filesModified++;
totalChanges += changesCount;
} else {
console.log(` Изменений не требуется\n`);
}
totalFilesProcessed++;
} catch (error) {
console.error(`❌ Ошибка в файле ${filePath}:`, error.message);
}
}
function processAllDoctypes(rootPath) {
try {
const entries = fs.readdirSync(rootPath, { withFileTypes: true });
entries.forEach(entry => {
if (entry.isDirectory()) {
const doctypePath = path.join(rootPath, entry.name);
const files = fs.readdirSync(doctypePath);
const jsonFiles = files.filter(f => f.endsWith('.json'));
jsonFiles.forEach(jsonFile => {
processJsonFile(path.join(doctypePath, jsonFile));
});
}
});
} catch (error) {
console.error(`❌ Ошибка при чтении папки:`, error.message);
}
}
// ГЛАВНАЯ ФУНКЦИЯ
const doctypePath = 'D:\\taxes_az\\taxes_az\\taxes_az\\doctype';
console.log('========================================');
console.log(' Добавление precision: "2" к Float');
console.log('========================================\n');
if (!fs.existsSync(doctypePath)) {
console.error('❌ Папка не найдена:', doctypePath);
process.exit(1);
}
// Давайте сначала проверим один файл для отладки
const testMode = false; // Измените на false для обработки всех файлов
if (testMode) {
// Тестовый режим - проверяем первый найденный файл
const entries = fs.readdirSync(doctypePath, { withFileTypes: true });
for (let entry of entries) {
if (entry.isDirectory()) {
const testPath = path.join(doctypePath, entry.name);
const files = fs.readdirSync(testPath);
const jsonFile = files.find(f => f.endsWith('.json'));
if (jsonFile) {
console.log(`🧪 ТЕСТОВЫЙ РЕЖИМ - обработка одного файла\n`);
processJsonFile(path.join(testPath, jsonFile));
// Показываем фрагмент результата
const result = fs.readFileSync(path.join(testPath, jsonFile), 'utf8');
const floatIndex = result.indexOf('"fieldtype": "Float"');
if (floatIndex > -1) {
console.log('\n📝 Фрагмент результата:');
console.log(result.substring(Math.max(0, floatIndex - 100), floatIndex + 200));
}
break;
}
}
}
} else {
// Обработка всех файлов
processAllDoctypes(doctypePath);
}
console.log('========================================');
console.log('📊 РЕЗУЛЬТАТ:');
console.log(` Файлов проверено: ${totalFilesProcessed}`);
console.log(` Файлов изменено: ${filesModified}`);
console.log(` Полей с precision: ${totalChanges}`);
console.log('========================================');
if (filesModified > 0) {
console.log('\n✅ Готово!');
}