kak-napisat-spravku-o-zadolz/script.js

228 lines
9.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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.

// Инициализация даты при загрузке
document.addEventListener('DOMContentLoaded', function() {
const today = new Date().toISOString().split('T')[0];
// Заполняем форму примерными данными
document.getElementById('companyName').value = 'ТОО «АлматыСтройСервис»';
document.getElementById('companyBin').value = '123456789012';
document.getElementById('companyAddress').value = 'г. Алматы, ул. Абая 10';
document.getElementById('fio').value = 'Иванова Мария Петровна';
document.getElementById('debtAmount').value = '250000';
document.getElementById('currency').value = 'KZT';
document.getElementById('debtType').value = 'debtor';
document.getElementById('debtPeriod').value = 'Июль 2025 — Август 2025';
document.getElementById('reason').value = 'Подотчётные суммы по авансовому отчёту № 45 от 15.08.2025';
document.getElementById('document').value = 'Авансовый отчёт № 45 от 15.08.2025';
document.getElementById('legalBasis').value = 'ст. 114 ТК РК, п. 1 ст. 296 ГК РК';
document.getElementById('issueDate').value = today;
document.getElementById('issueNumber').value = '123-С';
document.getElementById('recipient').value = 'Юридический отдел';
document.getElementById('director').value = 'Генеральный директор Петров П.П.';
document.getElementById('accountant').value = 'Главный бухгалтер Сидорова А.А.';
updateCertificate();
});
// Обработка формы
document.getElementById('debtForm').addEventListener('submit', function(e) {
e.preventDefault();
updateCertificate();
// Плавный скролл к предпросмотру на мобильных
if (window.innerWidth <= 1024) {
document.querySelector('.preview-section').scrollIntoView({ behavior: 'smooth' });
}
});
// Обновление предпросмотра в реальном времени
const formInputs = document.querySelectorAll('#debtForm input, #debtForm select, #debtForm textarea');
formInputs.forEach(input => {
input.addEventListener('input', updateCertificate);
});
function updateCertificate() {
// Получаем данные из формы
const data = {
companyName: document.getElementById('companyName').value || 'ТОО «Ваша Компания»',
companyBin: document.getElementById('companyBin').value,
companyAddress: document.getElementById('companyAddress').value,
fio: document.getElementById('fio').value || '___________________________',
debtAmount: document.getElementById('debtAmount').value,
currency: document.getElementById('currency').value,
debtType: document.getElementById('debtType').value,
debtPeriod: document.getElementById('debtPeriod').value || '___________________________',
reason: document.getElementById('reason').value || '___________________________',
document: document.getElementById('document').value,
legalBasis: document.getElementById('legalBasis').value,
issueDate: document.getElementById('issueDate').value,
issueNumber: document.getElementById('issueNumber').value,
recipient: document.getElementById('recipient').value,
director: document.getElementById('director').value,
accountant: document.getElementById('accountant').value
};
// Форматируем дату
const formattedDate = formatDate(data.issueDate);
// Реквизиты компании
document.getElementById('certCompanyFullName').textContent = data.companyName;
document.getElementById('certCompanyNameInline').textContent = data.companyName;
document.getElementById('certCompanyNameInline2').textContent = data.companyName;
const binEl = document.getElementById('certCompanyBin');
if (data.companyBin) {
binEl.textContent = `БИН ${data.companyBin}`;
binEl.style.display = 'inline';
} else {
binEl.style.display = 'none';
}
const addressEl = document.getElementById('certCompanyAddress');
if (data.companyAddress) {
addressEl.textContent = `Адрес: ${data.companyAddress}`;
addressEl.style.display = 'inline';
} else {
addressEl.style.display = 'none';
}
// Дата и номер справки
document.getElementById('certIssueDateDisplay').textContent = formattedDate;
document.getElementById('certIssueNumberDisplay').textContent = data.issueNumber ? `№ ${data.issueNumber}` : '';
// Кому предоставляется
const recipientBlock = document.getElementById('certRecipientBlock');
if (data.recipient) {
recipientBlock.style.display = 'block';
document.getElementById('certRecipient').textContent = data.recipient;
} else {
recipientBlock.style.display = 'none';
}
document.getElementById('certFio').textContent = data.fio;
// Тип задолженности
const debtLabel = document.getElementById('certDebtLabel');
if (data.debtType === 'creditor') {
debtLabel.textContent = 'Имеет кредиторская задолженность:';
} else {
debtLabel.textContent = 'Имеет дебиторская задолженность:';
}
// Сумма задолженности
const amount = parseFloat(data.debtAmount) || 0;
const currencySymbol = getCurrencySymbol(data.currency);
const formattedAmount = formatNumber(amount);
document.getElementById('certDebtAmount').textContent = `${formattedAmount} ${currencySymbol}`;
document.getElementById('certDebtAmountWords').textContent = sumToWords(amount, data.currency);
document.getElementById('certDebtPeriod').textContent = data.debtPeriod;
document.getElementById('certReason').textContent = data.reason;
const docBlock = document.getElementById('certDocumentBlock');
if (data.document) {
docBlock.style.display = 'block';
document.getElementById('certDocument').textContent = data.document;
} else {
docBlock.style.display = 'none';
}
const legalBlock = document.getElementById('certLegalBasisBlock');
if (data.legalBasis) {
legalBlock.style.display = 'block';
document.getElementById('certLegalBasis').textContent = data.legalBasis;
} else {
legalBlock.style.display = 'none';
}
// Подписи
const directorText = data.director || '___________________ / _______________';
document.getElementById('certDirector').textContent = directorText;
document.getElementById('certDirectorSignDate').textContent = formattedDate;
const accountantBlock = document.querySelector('.cert-signature-line:nth-child(2)');
if (data.accountant) {
accountantBlock.style.display = 'block';
document.getElementById('certAccountant').textContent = data.accountant;
document.getElementById('certAccountantSignDate').textContent = formattedDate;
} else {
accountantBlock.style.display = 'none';
}
}
function formatDate(dateString) {
if (!dateString) return '«___» ________ 20__ г.';
const date = new Date(dateString);
const day = date.getDate();
const month = date.toLocaleDateString('ru-RU', { month: 'long' });
const year = date.getFullYear();
return `«${day}» ${month} ${year} г.`;
}
function formatNumber(num) {
return num.toLocaleString('ru-RU');
}
function getCurrencySymbol(currency) {
const symbols = {
'KZT': '₸',
'RUB': '₽',
'USD': '$'
};
return symbols[currency] || currency;
}
// Преобразование суммы в пропись (упрощённая версия)
function sumToWords(sum, currency) {
if (!sum || sum === 0) return '______________________';
const currencies = {
'KZT': {
units: ['тенге', 'тенге', 'тенге'],
kopeks: ['тиын', 'тиына', 'тиынов']
},
'RUB': {
units: ['рубль', 'рубля', 'рублей'],
kopeks: ['копейка', 'копейки', 'копеек']
},
'USD': {
units: ['доллар', 'доллара', 'долларов'],
kopeks: ['цент', 'цента', 'центов']
}
};
const curr = currencies[currency] || currencies['KZT'];
const wholePart = Math.floor(sum);
// Очень упрощённо - для точной реализации нужен полный словарь
return `${formatNumber(wholePart)} (${currency})`;
}
function printCertificate() {
window.print();
}
function copyToClipboard() {
const cert = document.getElementById('certificatePreview');
const text = cert.innerText;
navigator.clipboard.writeText(text).then(() => {
const btn = document.querySelector('.btn-copy');
const originalText = btn.textContent;
btn.textContent = '✅ Скопировано!';
setTimeout(() => {
btn.textContent = originalText;
}, 2000);
}).catch(err => {
alert('Не удалось скопировать текст');
});
}
function clearForm() {
document.getElementById('debtForm').reset();
const today = new Date().toISOString().split('T')[0];
document.getElementById('issueDate').value = today;
updateCertificate();
}