152 lines
6.2 KiB
JavaScript
152 lines
6.2 KiB
JavaScript
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✅ Готово!');
|
||
} |