1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
| //index.js
const { app, BrowserWindow, ipcMain, dialog } = require("electron");
const path = require("path");
const { useWrite, useRead } = require("./utils.js");
const goodEXCEL = require("./goodEXCEL.js");
const goodTXT = require("./goodTXT.js");
const sortComb = require("./sortComb.js");
const compareFiles = require("./findDifferences.js");
const getDPE = require("./changeDescriptionToDPE.js");
const swertka = require("./classAndChangeCombos.js");
const getAllZDV = require("./getAllZDV.js");
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: false,
contextIsolation: true,
enableRemoteModule: false,
},
});
win.loadFile("index.html");
}
app.whenReady().then(() => {
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
function getName(inputFilePath, postfix) {
// Извлекаем имя файла без расширения
const fileName = path.basename(inputFilePath, path.extname(inputFilePath));
// Формируем новое имя файла с суффиксом "_output"
const outputFileName = `${fileName}` + `${postfix}.txt`;
return outputFileName;
}
ipcMain.handle("dialog:openFile", async () => {
const { canceled, filePaths } = await dialog.showOpenDialog({
properties: ["openFile"],
});
if (canceled) {
return null;
} else {
return filePaths[0];
}
});
ipcMain.handle("process-file", async (event, inputFilePath) => {
try {
const data = await useRead(inputFilePath);
const processedData = goodEXCEL.processFile(data);
const outputFilePath = "goodEXC.txt";
// goodEXCEL.processFile(inputFilePath, outputFilePath);
useWrite(outputFilePath, processedData);
return outputFilePath;
} catch (error) {
console.error("Failed to process the file:", error);
}
});
ipcMain.handle("processInputTXTData", async (event, inputFilePath) => {
try {
const data = await useRead(inputFilePath);
const processedData = goodTXT.processInputData(data);
const outputFilePath = "goodTXT.txt";
// goodEXCEL.processFile(inputFilePath, outputFilePath);
useWrite(outputFilePath, processedData);
return outputFilePath;
} catch (error) {
console.error("Failed to process the file:", error);
}
});
ipcMain.handle("sort", async (event, inputFilePath) => {
try {
const data = await useRead(inputFilePath);
const processedData = sortComb.processInputData(data);
const outputFilePath = getName(inputFilePath, "_sorted");
// goodEXCEL.processFile(inputFilePath, outputFilePath);
useWrite(outputFilePath, processedData);
return outputFilePath;
} catch (error) {
console.error("Failed to process the file:", error);
}
});
ipcMain.handle(
"processCompareFiles",
async (event, inputFilePath_first, inputFilePath_second) => {
try {
const outputFilePath_first = getName(inputFilePath_first, "_output1");
const outputFilePath_second = getName(inputFilePath_second, "_output2");
// Маппинг задвижек
let tempData = await useRead("ALL_ZDV.txt");
const ZDVmap = compareFiles.processInputMappingZDV(tempData);
//Получаем маппинги файлов
tempData = await useRead(inputFilePath_first);
const mapFileFirst = compareFiles.processInputMappingComb(
tempData,
ZDVmap
);
tempData = await useRead(inputFilePath_second);
const mapFileSecond = compareFiles.processInputMappingComb(
tempData,
ZDVmap
);
//Ищем и записываем отличия
const dif1 = compareFiles.findDifferences(
mapFileFirst,
mapFileSecond,
ZDVmap
);
useWrite(outputFilePath_first, dif1);
const dif2 = compareFiles.findDifferences(
mapFileSecond,
mapFileFirst,
ZDVmap
);
useWrite(outputFilePath_second, dif2);
return [outputFilePath_first, outputFilePath_second];
} catch (error) {
console.error("Failed to process the file:", error);
}
}
);
ipcMain.handle("getDPE", async (event, inputFilePath) => {
try {
const outputFilePath = getName(inputFilePath, "_dpe");
//EXCEL читается только 1-ый лист, работа происходит с форматом json
const workbook = await useRead("Value&Keys.xlsx");
const ZDVmap = new Map();
workbook.forEach((row) => {
if (row.length >= 2) {
// Убедимся, что есть хотя бы 2 колонки
const key = row[1]; // Второй столбец
const value = row[0]; // Первый столбец
ZDVmap.set(key, value);
}
});
const data = await useRead(inputFilePath);
const processedData = getDPE.processInputMappingComb(data, ZDVmap);
useWrite(outputFilePath, processedData);
return outputFilePath;
} catch (error) {
console.error("Failed to process the file:", error);
}
});
ipcMain.handle("processSwertka", async (event, inputFilePath) => {
try {
const outputFilePath = getName(inputFilePath, "_swertka");
//EXCEL читается только 1-ый лист, работа происходит с форматом json
const workbook = await useRead("ArraysCombos.xlsx");
const data = await useRead(inputFilePath);
const processedData = swertka.processGetModifiedCombinations(
data,
workbook
);
useWrite(outputFilePath, swertka.removeDuplicateTextBlocks(processedData));
return outputFilePath;
} catch (error) {
console.error("Failed to process the file:", error);
}
});
ipcMain.handle(
"getAllZDV",
async (event, inputFilePath_first, inputFilePath_second) => {
try {
const outputFilePath = "ALL_ZDV.txt";
// Маппинг задвижек
// let tempData = await useRead("ALL_ZDV.txt");
// const ZDVmap = compareFiles.processInputMappingZDV(tempData);
//Получаем маппинги файлов
const tempData1 = await useRead(inputFilePath_first);
const tempData2 = await useRead(inputFilePath_second);
const mapFile = getAllZDV.processFile(tempData1, tempData2);
useWrite(outputFilePath, mapFile);
return [outputFilePath];
} catch (error) {
console.error("Failed to process the file:", error);
}
}
);
//classAndChangeCombos.js
class DynamicMatrix {
constructor(name) {
// Изначально двумерный массив пустой
this.name = name;
this.groupCombs = [];
print(name);
}
// Метод для добавления строки (можно добавлять пустую строку или с элементами)
addRow(row = []) {
this.groupCombs.push(row);
}
// Метод для добавления элемента в конец конкретной строки
addElementToRow(rowIdx, value) {
if (this.groupCombs[rowIdx]) {
this.groupCombs[rowIdx].push(value);
} else {
console.error(`Строка с индексом ${rowIdx} не существует`);
}
}
// Метод для получения значения из конкретной ячейки
getValue(row, col) {
if (this.isValidIndex(row, col)) {
return this.groupCombs[row][col];
} else {
console.error("Индекс выходит за пределы массива");
return null;
}
}
// Метод для проверки допустимости индексов
isValidIndex(row, col) {
return (
row >= 0 &&
row < this.groupCombs.length &&
col >= 0 &&
col < this.groupCombs[row].length
);
}
// Метод для вывода всего массива
printMatrix() {
console.log(this.groupCombs);
}
}
function fillGroups(data) {
// Пример использования класса
const LU11 = new DynamicMatrix("ЛЧ 1.1");
const LU12 = new DynamicMatrix("ЛЧ 1.2");
const NPS = new DynamicMatrix("НПС Кузьмичи-2");
const LU21 = new DynamicMatrix("ЛЧ 2.1");
const LU22 = new DynamicMatrix("ЛЧ 2.2");
const VNPZ = new DynamicMatrix("ВНПЗ");
data.forEach((row) => {
if (row[0] == LU11.name) {
const tempGroup = [];
for (let i = 0; i < row.length - 1; i++) {
tempGroup.push(row[i + 1]);
}
LU11.addRow(tempGroup);
}
const tempGroup = [];
switch (row[0]) {
case "ЛЧ 1.1":
for (let i = 0; i < row.length - 1; i++) {
tempGroup.push(row[i + 1]);
}
LU11.addRow(tempGroup);
break;
case "ЛЧ 1.2":
for (let i = 0; i < row.length - 1; i++) {
tempGroup.push(row[i + 1]);
}
LU12.addRow(tempGroup);
break;
case "НПС Кузьмичи-2":
for (let i = 0; i < row.length - 1; i++) {
tempGroup.push(row[i + 1]);
}
NPS.addRow(tempGroup);
break;
case "ЛЧ 2.1":
for (let i = 0; i < row.length - 1; i++) {
tempGroup.push(row[i + 1]);
}
LU21.addRow(tempGroup);
break;
case "ЛЧ 2.2":
for (let i = 0; i < row.length - 1; i++) {
tempGroup.push(row[i + 1]);
}
LU22.addRow(tempGroup);
break;
case "ВНПЗ":
for (let i = 0; i < row.length - 1; i++) {
tempGroup.push(row[i + 1]);
}
VNPZ.addRow(tempGroup);
break;
default:
console.log("ERROR!!! Element not recognized.");
break;
}
});
return [LU11, LU12, NPS, LU21, LU22, VNPZ];
}
function replaceCombinations(stringArray, groups) {
// Создаем копию массива stringArray, чтобы работать с ней
const comboHeader = stringArray.shift();
let resultArray = [...stringArray];
// Проходим по каждому объекту из groups
groups.forEach((group) => {
group.groupCombs.forEach((combination) => {
// Проверяем, если все элементы комбинации есть в resultArray
const match = combination.every((item) => resultArray.includes(item));
if (match) {
// Если найдена полная комбинация, заменяем все её элементы на name
resultArray = resultArray.filter((item) => !combination.includes(item));
resultArray.push(group.name);
}
});
});
return [comboHeader, ...resultArray];
}
function processGetModifiedCombinations(inputData, inputCombos) {
const lines = inputData.split("\n");
//Заполнение матрицы
const groups = fillGroups(inputCombos);
const outputLines = [];
// let map = new Map();
let currentCombo = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.startsWith("Комбинация №:")) {
if (currentCombo.length > 0) {
//добавляем предыдущую комбинацию в итоговый список
outputLines.push(...replaceCombinations(currentCombo, groups));
}
// Начинаем новую комбинацию
currentCombo = [line];
} else if (line !== "") {
currentCombo.push(line);
}
}
//Костыль для последней комбинации
outputLines.push(...replaceCombinations(currentCombo, groups));
return outputLines.join("\n");
}
function removeDuplicateTextBlocks(inputText) {
const blocks = inputText.trim().split(/(?=Комбинация №:)/); // Разбиваем текст на блоки по строке "Комбинация №:"
const uniqueCombinations = new Set();
const result = [];
blocks.forEach((block) => {
// Убираем строку с номером комбинации и сортируем оставшиеся строки в блоке
const sortedBlock = block.split("\n").slice(1).sort().join(",");
// Если блок уникален, добавляем его в результат
if (!uniqueCombinations.has(sortedBlock)) {
uniqueCombinations.add(sortedBlock);
result.push(block.trim());
}
});
return result.join("\n\n"); // Объединяем уникальные блоки с двумя переносами строки
}
// processFile(inputExcelfile, groups);
module.exports = {
processGetModifiedCombinations,
removeDuplicateTextBlocks,
};
// // Сохранение Map в файл, если нужно (например, в формате JSON)
// const mapObject = Object.fromEntries(ZDVmap); // Преобразуем Map в объект
// fs.writeFileSync("output.json", JSON.stringify(mapObject, null, 2));
//utils.js
const fs = require("fs");
const xlsx = require("xlsx");
function useWrite(outputFilePath, resultData) {
if (outputFilePath.endsWith(".xlsx")) {
const workbook = xlsx.utils.book_new();
const worksheet = xlsx.utils.aoa_to_sheet(resultData);
xlsx.utils.book_append_sheet(workbook, worksheet, "Sheet1");
xlsx.writeFile(workbook, outputFilePath);
console.log(
"Excel file successfully processed and written:",
outputFilePath
);
} else {
fs.writeFile(outputFilePath, resultData, "utf8", (err) => {
if (err) {
console.error("Error writing file:", err);
} else {
console.log("File successfully processed and written:", outputFilePath);
}
});
}
}
function useRead(inputFilePath) {
return new Promise((resolve, reject) => {
if (inputFilePath.endsWith(".xlsx")) {
try {
const workbook = xlsx.readFile(inputFilePath);
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const jsonData = xlsx.utils.sheet_to_json(worksheet, { header: 1 });
resolve(jsonData);
} catch (error) {
console.error("Error reading Excel file:", error);
reject(error);
}
} else {
fs.readFile(inputFilePath, "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
reject(err);
} else {
resolve(data);
}
});
}
});
}
module.exports = {
useWrite,
useRead,
}; |