-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
307 lines (273 loc) · 13.4 KB
/
Copy pathindex.html
File metadata and controls
307 lines (273 loc) · 13.4 KB
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
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Проценты по 395 ГК РФ</title>
<link rel="stylesheet" href="styles.css">
<script src="https://cdn.jsdelivr.net/npm/docx@7.6.0/build/index.min.js"></script>
</head>
<body>
<div class="container">
<h1>Проценты по 395 ГК РФ</h1>
<h3>Добавьте объект для осуществления расчета</h3>
<div class="add-remove-buttons">
<button id="addObject">+ Добавить объект</button>
</div>
<div id="objects">
<!-- Объекты добавляются здесь -->
</div>
<button id="calculate" style="display: block; margin: 0 auto;">Рассчитать</button>
<h2>Результат:</h2>
<div class="result" id="result">Здесь отобразится результат расчета.</div>
<button id="copyResult" style="display: block; margin: 20px auto;">Скопировать результат</button>
<button id="exportToDocx" style="display: block; margin: 20px auto;">Экспортировать в DOCX</button>
</div>
<script>
const objectsContainer = document.getElementById('objects');
const resultContainer = document.getElementById('result');
const copyResultButton = document.getElementById('copyResult');
// Массив ставок (изменения ставок)
const rates = [
{ start: new Date('2024-10-28'), rate: 21 },
{ start: new Date('2024-09-16'), rate: 19 },
{ start: new Date('2024-07-29'), rate: 18 },
{ start: new Date('2023-12-18'), rate: 16 },
{ start: new Date('2023-10-30'), rate: 15 },
{ start: new Date('2023-09-18'), rate: 13 },
{ start: new Date('2023-08-15'), rate: 12 },
{ start: new Date('2023-07-24'), rate: 8.5 },
{ start: new Date('2022-09-19'), rate: 7.5 },
{ start: new Date('2022-07-25'), rate: 8 },
{ start: new Date('2022-06-14'), rate: 9.5 },
{ start: new Date('2022-05-27'), rate: 11 },
{ start: new Date('2022-05-04'), rate: 14 },
{ start: new Date('2022-04-11'), rate: 17 },
{ start: new Date('2022-02-28'), rate: 20 },
{ start: new Date('2022-02-14'), rate: 9.5 },
{ start: new Date('2021-12-20'), rate: 8.5 },
{ start: new Date('2021-10-25'), rate: 7.5 },
{ start: new Date('2021-09-13'), rate: 6.75 },
{ start: new Date('2021-07-26'), rate: 6.5 },
{ start: new Date('2021-06-15'), rate: 5.5 },
{ start: new Date('2021-04-26'), rate: 5 },
{ start: new Date('2021-03-22'), rate: 4.5 },
{ start: new Date('2020-07-27'), rate: 4.25 },
{ start: new Date('2020-06-22'), rate: 4.5 },
{ start: new Date('2020-04-27'), rate: 5.5 },
{ start: new Date('2020-02-10'), rate: 6 },
{ start: new Date('2019-12-16'), rate: 6.25 }
];
// Добавление нового объекта расчета
document.getElementById('addObject').addEventListener('click', () => {
const objectDiv = document.createElement('div');
objectDiv.className = 'object';
objectDiv.innerHTML = `
<div class="object-header">
<strong>Объект</strong>
<button class="removeObject">-</button>
</div>
<label>
Наименование объекта:
<input type="text" class="object-name" placeholder="Введите название">
</label>
<label>
Ежемесячный платеж:
<input type="number" class="monthly-payment" placeholder="Введите сумму">
</label>
<label>
Период задолженности:
<div class="period-inputs">
<!-- Поля изменены на type="date" для выбора конкретной даты -->
<input type="date" class="start-period">
<span>по</span>
<input type="date" class="end-period">
</div>
</label>
`;
objectDiv.querySelector('.removeObject').addEventListener('click', () => {
objectDiv.remove();
});
objectsContainer.appendChild(objectDiv);
});
// Функция расчёта с периодом, выбранным с конкретной даты
document.getElementById('calculate').addEventListener('click', () => {
const objects = document.querySelectorAll('.object');
let resultText = '';
let grandTotalDebt = 0; // Общий долг по всем объектам
let grandTotalInterest = 0; // Общие проценты
objects.forEach((object, index) => {
const name = object.querySelector('.object-name').value || `Объект ${index + 1}`;
const payment = parseFloat(object.querySelector('.monthly-payment').value);
const startPeriod = object.querySelector('.start-period').value;
const endPeriod = object.querySelector('.end-period').value;
if (!payment || !startPeriod || !endPeriod) {
resultText += `Ошибка: Заполните все данные для <strong>${name}</strong>\n`;
return;
}
// Парсинг выбранных дат (формат YYYY-MM-DD)
const startDate = new Date(startPeriod);
const endDate = new Date(endPeriod);
// Для расчёта будем проходить по месяцам (учитывая неполные периоды в начале и конце)
let currentPeriodStart = new Date(startDate);
let cumulativeDebt = 0;
let totalInterest = 0;
resultText += `\n<strong>${name}</strong>:\n`;
// Добавляем платеж в день начала периода
cumulativeDebt += payment;
while (currentPeriodStart <= endDate) {
let currentPeriodEnd;
// Если период начинается и заканчивается в одном месяце – берем конечную дату из выбора
if (currentPeriodStart.getFullYear() === endDate.getFullYear() &&
currentPeriodStart.getMonth() === endDate.getMonth()) {
currentPeriodEnd = new Date(endDate);
} else {
// Иначе берем последний день текущего месяца
currentPeriodEnd = new Date(currentPeriodStart.getFullYear(), currentPeriodStart.getMonth() + 1, 0);
}
// Получаем периоды с фиксированной ставкой в рамках текущего интервала
const rateChanges = getRateChangesForPeriod(currentPeriodStart, currentPeriodEnd, rates);
rateChanges.forEach(period => {
const periodYear = period.start.getFullYear();
const daysInYear = (periodYear % 4 === 0 && (periodYear % 100 !== 0 || periodYear % 400 === 0)) ? 366 : 365;
const interest = (cumulativeDebt * period.days / daysInYear) * (period.rate / 100);
totalInterest += interest;
resultText += `Период: ${period.start.toLocaleDateString('ru')} - ${period.end.toLocaleDateString('ru')}, ` +
`Ставка: ${period.rate}%, ` +
`Дней: ${period.days}, ` +
`Накопленный долг: ${cumulativeDebt.toFixed(2)}, ` +
`Формула: (${cumulativeDebt.toFixed(2)} * ${period.days} / ${daysInYear}) * (${period.rate}%)\n` +
`Проценты за период: ${interest.toFixed(2)}\n`;
});
// Переходим к следующему месячному интервалу:
currentPeriodStart = new Date(currentPeriodEnd.getFullYear(), currentPeriodEnd.getMonth() + 1, 1);
if (currentPeriodStart <= endDate) {
cumulativeDebt += payment;
}
}
resultText += `Итоговый долг: ${cumulativeDebt.toFixed(2)}\n`;
resultText += `Итоговые проценты: ${totalInterest.toFixed(2)}\n`;
grandTotalDebt += cumulativeDebt;
grandTotalInterest += totalInterest;
});
if (resultText === '') {
resultText = 'Добавьте хотя бы один объект.';
} else {
resultText += `\n<strong>Общий итог:</strong>\n`;
resultText += `Долг: ${grandTotalDebt.toFixed(2)}\n`;
resultText += `Проценты: ${grandTotalInterest.toFixed(2)}\n`;
}
resultContainer.innerHTML = resultText;
});
copyResultButton.addEventListener('click', () => {
navigator.clipboard.writeText(resultContainer.textContent).then(() => {
alert('Результат скопирован в буфер обмена!');
});
});
// Возвращает ставку, действующую на указанную дату
function getRateForDate(date) {
for (let i = 0; i < rates.length; i++) {
if (date >= rates[i].start) {
return rates[i].rate;
}
}
return rates[rates.length - 1].rate;
}
// Функция для разделения произвольного периода (от startDate до endDate) на интервалы, в которых ставка не меняется
function getRateChangesForPeriod(startDate, endDate, rates) {
const changes = rates
.filter(rate => rate.start > startDate && rate.start <= endDate)
.sort((a, b) => a.start - b.start);
const periods = [];
let periodStart = startDate;
let currentRate = getRateForDate(startDate);
if (changes.length === 0) {
const days = Math.round((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
periods.push({ start: periodStart, end: endDate, rate: currentRate, days: days });
} else {
changes.forEach(change => {
let periodEnd = new Date(change.start);
periodEnd.setDate(periodEnd.getDate() - 1);
const days = Math.round((periodEnd - periodStart) / (1000 * 60 * 60 * 24)) + 1;
periods.push({ start: periodStart, end: periodEnd, rate: currentRate, days: days });
periodStart = change.start;
currentRate = getRateForDate(change.start);
});
if (periodStart <= endDate) {
const days = Math.round((endDate - periodStart) / (1000 * 60 * 60 * 24)) + 1;
periods.push({ start: periodStart, end: endDate, rate: currentRate, days: days });
}
}
return periods;
}
document.getElementById('exportToDocx').addEventListener('click', () => {
const resultContent = document.getElementById('result').innerText;
// Собираем наименования объектов из полей ввода
const objectNames = Array.from(document.querySelectorAll('.object-name'))
.map(input => input.value.trim())
.filter(name => name !== "");
// Разделяем текст на строки
const lines = resultContent.split('\n');
// Преобразуем каждую строку в отдельный абзац
const paragraphs = lines.map(line => {
// Проверяем, содержит ли строка одно из наименований объектов
const isObjectName = objectNames.some(name => line.includes(name));
const isBoldLine = line.startsWith('Общий итог:') ||
line.startsWith('Долг:') ||
line.startsWith('Проценты:');
return new docx.Paragraph({
alignment: docx.AlignmentType.JUSTIFIED,
spacing: {
line: 360,
before: 200,
after: 200,
},
children: [
new docx.TextRun({
text: line.trim(),
font: "Times New Roman",
size: 24,
bold: isBoldLine || isObjectName,
}),
],
});
});
// Создание верхнего колонтитула
const header = new docx.Header({
children: [
new docx.Paragraph({
alignment: docx.AlignmentType.CENTER,
children: [
new docx.TextRun({
text: "Проценты по ст. 395 ГК РФ",
font: "Times New Roman",
size: 24,
bold: true,
}),
],
}),
],
});
// Создание документа с верхним колонтитулом
const doc = new docx.Document({
sections: [
{
properties: {},
headers: {
default: header,
},
children: paragraphs,
},
],
});
// Генерация и скачивание DOCX-файла
docx.Packer.toBlob(doc).then((blob) => {
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "Расчет 395 ГК.docx";
link.click();
});
});
</script>
</body>
</html>