added test logs to land tax
This commit is contained in:
parent
a9126beb29
commit
f665c21017
|
|
@ -1,5 +1,8 @@
|
||||||
frappe.ui.form.on('Land tax declaration', {
|
frappe.ui.form.on('Land tax declaration', {
|
||||||
il: function(frm) {
|
il: function(frm) {
|
||||||
|
console.log('=== НАЧАЛО: Изменение года ===');
|
||||||
|
console.log('Выбранный год:', frm.doc.il);
|
||||||
|
|
||||||
if (frm.doc.il) {
|
if (frm.doc.il) {
|
||||||
reload_assets_for_year(frm, frm.doc.il);
|
reload_assets_for_year(frm, frm.doc.il);
|
||||||
}
|
}
|
||||||
|
|
@ -7,19 +10,25 @@ frappe.ui.form.on('Land tax declaration', {
|
||||||
});
|
});
|
||||||
|
|
||||||
function reload_assets_for_year(frm, year) {
|
function reload_assets_for_year(frm, year) {
|
||||||
|
console.log('=== reload_assets_for_year ===');
|
||||||
|
console.log('Год для загрузки:', year);
|
||||||
|
|
||||||
// Clear existing tables
|
// Clear existing tables
|
||||||
|
console.log('Очистка таблиц əlavə_1 и əlavə_2');
|
||||||
frm.clear_table('əlavə_1');
|
frm.clear_table('əlavə_1');
|
||||||
frm.clear_table('əlavə_2');
|
frm.clear_table('əlavə_2');
|
||||||
frm.refresh_fields();
|
frm.refresh_fields();
|
||||||
|
|
||||||
// Load assets for the specified year
|
// Load assets for the specified year
|
||||||
|
console.log('Запуск параллельной загрузки активов...');
|
||||||
Promise.all([
|
Promise.all([
|
||||||
load_agricultural_assets_for_year(frm, 'əlavə_1', year),
|
load_agricultural_assets_for_year(frm, 'əlavə_1', year),
|
||||||
load_industrial_assets_for_year(frm, 'əlavə_2', year)
|
load_industrial_assets_for_year(frm, 'əlavə_2', year)
|
||||||
]).then(() => {
|
]).then(() => {
|
||||||
|
console.log('✅ Все активы успешно загружены и обработаны');
|
||||||
frm.refresh_fields();
|
frm.refresh_fields();
|
||||||
}).catch(() => {
|
}).catch((error) => {
|
||||||
// Silently handle any errors
|
console.error('❌ Ошибка при загрузке активов:', error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -28,6 +37,9 @@ function reload_assets_for_year(frm, year) {
|
||||||
// ===============================
|
// ===============================
|
||||||
|
|
||||||
function load_agricultural_assets_for_year(frm, table_fieldname, year) {
|
function load_agricultural_assets_for_year(frm, table_fieldname, year) {
|
||||||
|
console.log('=== load_agricultural_assets_for_year ===');
|
||||||
|
console.log('Таблица:', table_fieldname, 'Год:', year);
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
frappe.call({
|
frappe.call({
|
||||||
method: 'taxes_az.taxes_az.doctype.land_tax_declaration.land_tax_declaration.get_assets_for_year',
|
method: 'taxes_az.taxes_az.doctype.land_tax_declaration.land_tax_declaration.get_assets_for_year',
|
||||||
|
|
@ -36,13 +48,19 @@ function load_agricultural_assets_for_year(frm, table_fieldname, year) {
|
||||||
year: year
|
year: year
|
||||||
},
|
},
|
||||||
callback: function(response) {
|
callback: function(response) {
|
||||||
|
console.log('Ответ от сервера (сельхоз активы):', response);
|
||||||
|
|
||||||
if (response.message && response.message.length > 0) {
|
if (response.message && response.message.length > 0) {
|
||||||
|
console.log(`Найдено ${response.message.length} сельхоз активов`);
|
||||||
|
console.log('Список активов:', response.message);
|
||||||
process_agricultural_assets_silent(frm, table_fieldname, response.message, resolve);
|
process_agricultural_assets_silent(frm, table_fieldname, response.message, resolve);
|
||||||
} else {
|
} else {
|
||||||
|
console.log('⚠️ Сельхоз активы не найдены для года', year);
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: function() {
|
error: function(error) {
|
||||||
|
console.error('❌ Ошибка загрузки сельхоз активов:', error);
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
@ -50,34 +68,50 @@ function load_agricultural_assets_for_year(frm, table_fieldname, year) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function process_agricultural_assets_silent(frm, table_fieldname, assets, resolve) {
|
function process_agricultural_assets_silent(frm, table_fieldname, assets, resolve) {
|
||||||
|
console.log('=== process_agricultural_assets_silent ===');
|
||||||
|
console.log('Количество активов для обработки:', assets.length);
|
||||||
|
|
||||||
let agricultural_purposes = {};
|
let agricultural_purposes = {};
|
||||||
let processed_count = 0;
|
let processed_count = 0;
|
||||||
let unique_purposes = get_unique_purposes(assets);
|
let unique_purposes = get_unique_purposes(assets);
|
||||||
|
|
||||||
|
console.log('Уникальных назначений найдено:', unique_purposes.size);
|
||||||
|
console.log('Список уникальных назначений:', Array.from(unique_purposes));
|
||||||
|
|
||||||
if (unique_purposes.size > 0) {
|
if (unique_purposes.size > 0) {
|
||||||
unique_purposes.forEach(purpose_id => {
|
unique_purposes.forEach(purpose_id => {
|
||||||
|
console.log(`Загрузка данных для назначения: "${purpose_id}"`);
|
||||||
|
|
||||||
frappe.call({
|
frappe.call({
|
||||||
method: 'frappe.client.get_value', // Изменено с 'frappe.client.get'
|
method: 'frappe.client.get_value',
|
||||||
args: {
|
args: {
|
||||||
doctype: 'Agricultural Purpose Type',
|
doctype: 'Agricultural Purpose Type',
|
||||||
filters: {'purpose_name': purpose_id}, // Поиск по полю purpose_name
|
filters: {'purpose_name': purpose_id},
|
||||||
fieldname: ['name', 'purpose_name']
|
fieldname: ['name', 'purpose_name']
|
||||||
},
|
},
|
||||||
callback: function(agri_response) {
|
callback: function(agri_response) {
|
||||||
|
console.log(`Ответ для назначения "${purpose_id}":`, agri_response);
|
||||||
|
|
||||||
if (agri_response.message) {
|
if (agri_response.message) {
|
||||||
// Сохраняем данные в нужном формате
|
|
||||||
agricultural_purposes[purpose_id] = {
|
agricultural_purposes[purpose_id] = {
|
||||||
name: agri_response.message.name,
|
name: agri_response.message.name,
|
||||||
purpose_name: agri_response.message.purpose_name
|
purpose_name: agri_response.message.purpose_name
|
||||||
};
|
};
|
||||||
|
console.log(`✅ Назначение загружено:`, agricultural_purposes[purpose_id]);
|
||||||
|
} else {
|
||||||
|
console.warn(`⚠️ Назначение "${purpose_id}" не найдено в базе`);
|
||||||
}
|
}
|
||||||
|
|
||||||
processed_count++;
|
processed_count++;
|
||||||
|
console.log(`Прогресс загрузки назначений: ${processed_count}/${unique_purposes.size}`);
|
||||||
|
|
||||||
if (processed_count === unique_purposes.size) {
|
if (processed_count === unique_purposes.size) {
|
||||||
|
console.log('Все назначения загружены, начинаем группировку');
|
||||||
group_and_create_agricultural_rows_silent(frm, table_fieldname, assets, agricultural_purposes, resolve);
|
group_and_create_agricultural_rows_silent(frm, table_fieldname, assets, agricultural_purposes, resolve);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: function() {
|
error: function(error) {
|
||||||
|
console.error(`❌ Ошибка загрузки назначения "${purpose_id}":`, error);
|
||||||
processed_count++;
|
processed_count++;
|
||||||
if (processed_count === unique_purposes.size) {
|
if (processed_count === unique_purposes.size) {
|
||||||
group_and_create_agricultural_rows_silent(frm, table_fieldname, assets, agricultural_purposes, resolve);
|
group_and_create_agricultural_rows_silent(frm, table_fieldname, assets, agricultural_purposes, resolve);
|
||||||
|
|
@ -86,25 +120,35 @@ function process_agricultural_assets_silent(frm, table_fieldname, assets, resolv
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
|
console.log('⚠️ Нет уникальных назначений, пропускаем группировку');
|
||||||
group_and_create_agricultural_rows_silent(frm, table_fieldname, assets, agricultural_purposes, resolve);
|
group_and_create_agricultural_rows_silent(frm, table_fieldname, assets, agricultural_purposes, resolve);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_unique_purposes(assets) {
|
function get_unique_purposes(assets) {
|
||||||
|
console.log('=== get_unique_purposes ===');
|
||||||
let unique_purposes = new Set();
|
let unique_purposes = new Set();
|
||||||
|
|
||||||
assets.forEach(asset => {
|
assets.forEach(asset => {
|
||||||
if (asset.agricultural_purpose) {
|
if (asset.agricultural_purpose) {
|
||||||
unique_purposes.add(asset.agricultural_purpose);
|
unique_purposes.add(asset.agricultural_purpose);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log('Найдено уникальных назначений:', unique_purposes.size);
|
||||||
return unique_purposes;
|
return unique_purposes;
|
||||||
}
|
}
|
||||||
|
|
||||||
function group_and_create_agricultural_rows_silent(frm, table_fieldname, assets, agricultural_purposes, resolve) {
|
function group_and_create_agricultural_rows_silent(frm, table_fieldname, assets, agricultural_purposes, resolve) {
|
||||||
|
console.log('=== group_and_create_agricultural_rows_silent ===');
|
||||||
|
console.log('Активов для группировки:', assets.length);
|
||||||
|
console.log('Загруженных назначений:', Object.keys(agricultural_purposes).length);
|
||||||
|
|
||||||
let grouped_assets = {};
|
let grouped_assets = {};
|
||||||
|
|
||||||
assets.forEach(function(asset) {
|
assets.forEach(function(asset) {
|
||||||
let group_key = create_agricultural_group_key(asset, agricultural_purposes);
|
let group_key = create_agricultural_group_key(asset, agricultural_purposes);
|
||||||
|
console.log(`Актив "${asset.name}" → Ключ группы: "${group_key}"`);
|
||||||
|
|
||||||
if (!grouped_assets[group_key]) {
|
if (!grouped_assets[group_key]) {
|
||||||
grouped_assets[group_key] = {
|
grouped_assets[group_key] = {
|
||||||
|
|
@ -113,6 +157,7 @@ function group_and_create_agricultural_rows_silent(frm, table_fieldname, assets,
|
||||||
count: 0,
|
count: 0,
|
||||||
asset_names: []
|
asset_names: []
|
||||||
};
|
};
|
||||||
|
console.log(`Создана новая группа: "${group_key}"`);
|
||||||
}
|
}
|
||||||
|
|
||||||
grouped_assets[group_key].total_hectare += (asset.hectare || 0);
|
grouped_assets[group_key].total_hectare += (asset.hectare || 0);
|
||||||
|
|
@ -121,18 +166,34 @@ function group_and_create_agricultural_rows_silent(frm, table_fieldname, assets,
|
||||||
});
|
});
|
||||||
|
|
||||||
let total_groups = Object.keys(grouped_assets).length;
|
let total_groups = Object.keys(grouped_assets).length;
|
||||||
|
console.log(`Создано групп: ${total_groups}`);
|
||||||
|
|
||||||
|
// Детальная информация по группам
|
||||||
|
Object.entries(grouped_assets).forEach(([key, group]) => {
|
||||||
|
console.log(`Группа "${key}":`, {
|
||||||
|
количество_активов: group.count,
|
||||||
|
общая_площадь: group.total_hectare,
|
||||||
|
активы: group.asset_names
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
let completed_calculations = 0;
|
let completed_calculations = 0;
|
||||||
|
|
||||||
if (total_groups === 0) {
|
if (total_groups === 0) {
|
||||||
|
console.log('⚠️ Нет групп для создания строк');
|
||||||
resolve();
|
resolve();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.entries(grouped_assets).forEach(function([group_key, group]) {
|
Object.entries(grouped_assets).forEach(function([group_key, group]) {
|
||||||
|
console.log(`Создание строки для группы: "${group_key}"`);
|
||||||
|
|
||||||
create_agricultural_row_with_calculation_silent(frm, table_fieldname, group.asset, agricultural_purposes, group.total_hectare, group, function() {
|
create_agricultural_row_with_calculation_silent(frm, table_fieldname, group.asset, agricultural_purposes, group.total_hectare, group, function() {
|
||||||
completed_calculations++;
|
completed_calculations++;
|
||||||
|
console.log(`Прогресс создания строк: ${completed_calculations}/${total_groups}`);
|
||||||
|
|
||||||
if (completed_calculations === total_groups) {
|
if (completed_calculations === total_groups) {
|
||||||
|
console.log('✅ Все сельхоз строки созданы');
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
@ -145,61 +206,88 @@ function create_agricultural_group_key(asset, agricultural_purposes) {
|
||||||
purpose_name = agricultural_purposes[asset.agricultural_purpose].purpose_name || '';
|
purpose_name = agricultural_purposes[asset.agricultural_purpose].purpose_name || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
let key_parts = [
|
||||||
get_select_option_value(purpose_name),
|
get_select_option_value(purpose_name),
|
||||||
asset.cadastral_district_code || '',
|
asset.cadastral_district_code || '',
|
||||||
asset.cadastral_district_name || '',
|
asset.cadastral_district_name || '',
|
||||||
asset.quality_groups || '',
|
asset.quality_groups || '',
|
||||||
asset.agricultural_land_purpose || ''
|
asset.agricultural_land_purpose || ''
|
||||||
].join('|');
|
];
|
||||||
|
|
||||||
|
console.log('Создание ключа из частей:', key_parts);
|
||||||
|
return key_parts.join('|');
|
||||||
}
|
}
|
||||||
|
|
||||||
function create_agricultural_row_with_calculation_silent(frm, table_fieldname, asset, agricultural_purposes, total_hectare, group_info, callback) {
|
function create_agricultural_row_with_calculation_silent(frm, table_fieldname, asset, agricultural_purposes, total_hectare, group_info, callback) {
|
||||||
|
console.log('=== create_agricultural_row_with_calculation_silent ===');
|
||||||
|
console.log('Актив:', asset.name, 'Общая площадь:', total_hectare);
|
||||||
|
|
||||||
let row = frm.add_child(table_fieldname);
|
let row = frm.add_child(table_fieldname);
|
||||||
|
console.log('Строка добавлена в таблицу');
|
||||||
|
|
||||||
fill_agricultural_row_fields(row, asset, agricultural_purposes, total_hectare, group_info);
|
fill_agricultural_row_fields(row, asset, agricultural_purposes, total_hectare, group_info);
|
||||||
|
console.log('Поля строки заполнены:', row);
|
||||||
|
|
||||||
calculate_agricultural_tax_for_row_silent(row, asset, total_hectare, group_info, callback);
|
calculate_agricultural_tax_for_row_silent(row, asset, total_hectare, group_info, callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
function fill_agricultural_row_fields(row, asset, agricultural_purposes, total_hectare, group_info) {
|
function fill_agricultural_row_fields(row, asset, agricultural_purposes, total_hectare, group_info) {
|
||||||
|
console.log('=== fill_agricultural_row_fields ===');
|
||||||
|
|
||||||
if (asset.agricultural_purpose && agricultural_purposes[asset.agricultural_purpose]) {
|
if (asset.agricultural_purpose && agricultural_purposes[asset.agricultural_purpose]) {
|
||||||
let purpose_doc = agricultural_purposes[asset.agricultural_purpose];
|
let purpose_doc = agricultural_purposes[asset.agricultural_purpose];
|
||||||
if (purpose_doc.purpose_name) {
|
if (purpose_doc.purpose_name) {
|
||||||
let mapped_value = get_select_option_value(purpose_doc.purpose_name);
|
let mapped_value = get_select_option_value(purpose_doc.purpose_name);
|
||||||
row.bəyannaməsətrininkoduvəadı = mapped_value;
|
row.bəyannaməsətrininkoduvəadı = mapped_value;
|
||||||
|
console.log('Назначение:', mapped_value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (asset.cadastral_district_code) {
|
if (asset.cadastral_district_code) {
|
||||||
row.torpaqsahəsininyerləşdiyikadastrqiymətrayonununkodu = asset.cadastral_district_code;
|
row.torpaqsahəsininyerləşdiyikadastrqiymətrayonununkodu = asset.cadastral_district_code;
|
||||||
|
console.log('Код кадастрового района:', asset.cadastral_district_code);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (asset.cadastral_district_name) {
|
if (asset.cadastral_district_name) {
|
||||||
row.torpaqsahəsininyerləşdiyikadastrqiymətrayonununadı = asset.cadastral_district_name;
|
row.torpaqsahəsininyerləşdiyikadastrqiymətrayonununadı = asset.cadastral_district_name;
|
||||||
|
console.log('Название кадастрового района:', asset.cadastral_district_name);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (asset.quality_groups) {
|
if (asset.quality_groups) {
|
||||||
row.keyfiyyətqrupu = asset.quality_groups;
|
row.keyfiyyətqrupu = asset.quality_groups;
|
||||||
|
console.log('Группа качества:', asset.quality_groups);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (asset.agricultural_land_purpose) {
|
if (asset.agricultural_land_purpose) {
|
||||||
|
console.log('Тип использования земли:', asset.agricultural_land_purpose);
|
||||||
if (asset.agricultural_land_purpose === 'Əkin, dinc və çoxillik əkmələr') {
|
if (asset.agricultural_land_purpose === 'Əkin, dinc və çoxillik əkmələr') {
|
||||||
row.torpaqsahəsinintəyinatıəkindincçoxillikəkmələr = 1;
|
row.torpaqsahəsinintəyinatıəkindincçoxillikəkmələr = 1;
|
||||||
row.torpaqsahəsinintəyinatıbiçənəkörüşotlaqlar = 0;
|
row.torpaqsahəsinintəyinatıbiçənəkörüşotlaqlar = 0;
|
||||||
|
console.log('→ Пахотная земля');
|
||||||
} else if (asset.agricultural_land_purpose === 'Biçənək, örüş və otlaqlar') {
|
} else if (asset.agricultural_land_purpose === 'Biçənək, örüş və otlaqlar') {
|
||||||
row.torpaqsahəsinintəyinatıəkindincçoxillikəkmələr = 0;
|
row.torpaqsahəsinintəyinatıəkindincçoxillikəkmələr = 0;
|
||||||
row.torpaqsahəsinintəyinatıbiçənəkörüşotlaqlar = 1;
|
row.torpaqsahəsinintəyinatıbiçənəkörüşotlaqlar = 1;
|
||||||
|
console.log('→ Пастбище');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (total_hectare > 0) {
|
if (total_hectare > 0) {
|
||||||
row.torpaqsahəsi6001kodlarüzrəkvmetrlə6002kodlarüzrəhektarlaümumi = total_hectare;
|
row.torpaqsahəsi6001kodlarüzrəkvmetrlə6002kodlarüzrəhektarlaümumi = total_hectare;
|
||||||
|
console.log('Общая площадь:', total_hectare, 'га');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function calculate_agricultural_tax_for_row_silent(row, asset, total_hectare, group_info, callback) {
|
function calculate_agricultural_tax_for_row_silent(row, asset, total_hectare, group_info, callback) {
|
||||||
|
console.log('=== calculate_agricultural_tax_for_row_silent ===');
|
||||||
|
console.log('Параметры расчета:', {
|
||||||
|
hectare: total_hectare,
|
||||||
|
cadastral_district_name: asset.cadastral_district_name,
|
||||||
|
quality_groups: asset.quality_groups,
|
||||||
|
agricultural_land_purpose: asset.agricultural_land_purpose
|
||||||
|
});
|
||||||
|
|
||||||
if (!asset.cadastral_district_name || !asset.quality_groups || !asset.agricultural_land_purpose) {
|
if (!asset.cadastral_district_name || !asset.quality_groups || !asset.agricultural_land_purpose) {
|
||||||
|
console.warn('⚠️ Не все поля заполнены, пропускаем расчет налога');
|
||||||
callback();
|
callback();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -213,26 +301,44 @@ function calculate_agricultural_tax_for_row_silent(row, asset, total_hectare, gr
|
||||||
agricultural_land_purpose: asset.agricultural_land_purpose
|
agricultural_land_purpose: asset.agricultural_land_purpose
|
||||||
},
|
},
|
||||||
callback: function(response) {
|
callback: function(response) {
|
||||||
|
console.log('Результат расчета налога:', response);
|
||||||
|
|
||||||
if (response.message && response.message.tax_amount) {
|
if (response.message && response.message.tax_amount) {
|
||||||
row.vergiməbləğimanatla = response.message.tax_amount;
|
row.vergiməbləğimanatla = response.message.tax_amount;
|
||||||
|
console.log(`✅ Налог рассчитан: ${response.message.tax_amount} манат`);
|
||||||
|
|
||||||
|
if (response.message.calculation_details) {
|
||||||
|
console.log('Детали расчета:', response.message.calculation_details);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn('⚠️ Налог не рассчитан');
|
||||||
}
|
}
|
||||||
callback();
|
callback();
|
||||||
},
|
},
|
||||||
error: function() {
|
error: function(error) {
|
||||||
|
console.error('❌ Ошибка расчета налога:', error);
|
||||||
callback();
|
callback();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_select_option_value(purpose_name) {
|
function get_select_option_value(purpose_name) {
|
||||||
|
console.log('=== get_select_option_value ===');
|
||||||
|
console.log('Входное назначение:', purpose_name);
|
||||||
|
|
||||||
if (purpose_name === 'Təyinatı üzrə istifadə edilməyən kənd təsərrüfatı torpaqları üzrə hesablanmış vergi məbləği') {
|
if (purpose_name === 'Təyinatı üzrə istifadə edilməyən kənd təsərrüfatı torpaqları üzrə hesablanmış vergi məbləği') {
|
||||||
return '600.1 Təyinatı üzrə istifadə edilməyən kənd təsərrüfatı torpaqları üzrə hesablanmış vergi məbləği';
|
let result = '600.1 Təyinatı üzrə istifadə edilməyən kənd təsərrüfatı torpaqları üzrə hesablanmış vergi məbləği';
|
||||||
|
console.log('→ Маппинг на:', result);
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (purpose_name === 'Təyinatı üzrə istifadə edilən və ya irriqasiya, meliorasiya və digər aqrotexniki səbəblərdən təyinatı üzrə istifadə edilməsi mümkün olmayan kənd təsərrüfatı torpaqları üzrə verginin məbləği') {
|
if (purpose_name === 'Təyinatı üzrə istifadə edilən və ya irriqasiya, meliorasiya və digər aqrotexniki səbəblərdən təyinatı üzrə istifadə edilməsi mümkün olmayan kənd təsərrüfatı torpaqları üzrə verginin məbləği') {
|
||||||
return '600.2 Təyinatı üzrə istifadə edilən və ya irriqasiya, meliorasiya və digər aqrotexniki səbəblərdən təyinatı üzrə istifadə edilməsi mümkün olmayan kənd təsərrüfatı torpaqları üzrə verginin məbləği';
|
let result = '600.2 Təyinatı üzrə istifadə edilən və ya irriqasiya, meliorasiya və digər aqrotexniki səbəblərdən təyinatı üzrə istifadə edilməsi mümkün olmayan kənd təsərrüfatı torpaqları üzrə verginin məbləği';
|
||||||
|
console.log('→ Маппинг на:', result);
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('→ Маппинг не найден, возвращаем как есть');
|
||||||
return purpose_name;
|
return purpose_name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -241,6 +347,9 @@ function get_select_option_value(purpose_name) {
|
||||||
// ===============================
|
// ===============================
|
||||||
|
|
||||||
function load_industrial_assets_for_year(frm, table_fieldname, year) {
|
function load_industrial_assets_for_year(frm, table_fieldname, year) {
|
||||||
|
console.log('=== load_industrial_assets_for_year ===');
|
||||||
|
console.log('Таблица:', table_fieldname, 'Год:', year);
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
frappe.call({
|
frappe.call({
|
||||||
method: 'taxes_az.taxes_az.doctype.land_tax_declaration.land_tax_declaration.get_assets_for_year',
|
method: 'taxes_az.taxes_az.doctype.land_tax_declaration.land_tax_declaration.get_assets_for_year',
|
||||||
|
|
@ -249,13 +358,19 @@ function load_industrial_assets_for_year(frm, table_fieldname, year) {
|
||||||
year: year
|
year: year
|
||||||
},
|
},
|
||||||
callback: function(response) {
|
callback: function(response) {
|
||||||
|
console.log('Ответ от сервера (промышленные активы):', response);
|
||||||
|
|
||||||
if (response.message && response.message.length > 0) {
|
if (response.message && response.message.length > 0) {
|
||||||
|
console.log(`Найдено ${response.message.length} промышленных активов`);
|
||||||
|
console.log('Список активов:', response.message);
|
||||||
group_and_create_industrial_rows_silent(frm, table_fieldname, response.message, resolve);
|
group_and_create_industrial_rows_silent(frm, table_fieldname, response.message, resolve);
|
||||||
} else {
|
} else {
|
||||||
|
console.log('⚠️ Промышленные активы не найдены для года', year);
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: function() {
|
error: function(error) {
|
||||||
|
console.error('❌ Ошибка загрузки промышленных активов:', error);
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
@ -263,10 +378,14 @@ function load_industrial_assets_for_year(frm, table_fieldname, year) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function group_and_create_industrial_rows_silent(frm, table_fieldname, assets, resolve) {
|
function group_and_create_industrial_rows_silent(frm, table_fieldname, assets, resolve) {
|
||||||
|
console.log('=== group_and_create_industrial_rows_silent ===');
|
||||||
|
console.log('Активов для группировки:', assets.length);
|
||||||
|
|
||||||
let grouped_assets = {};
|
let grouped_assets = {};
|
||||||
|
|
||||||
assets.forEach(function(asset) {
|
assets.forEach(function(asset) {
|
||||||
let group_key = create_industrial_group_key(asset);
|
let group_key = create_industrial_group_key(asset);
|
||||||
|
console.log(`Актив "${asset.name}" → Ключ группы: "${group_key}"`);
|
||||||
|
|
||||||
if (!grouped_assets[group_key]) {
|
if (!grouped_assets[group_key]) {
|
||||||
grouped_assets[group_key] = {
|
grouped_assets[group_key] = {
|
||||||
|
|
@ -275,6 +394,7 @@ function group_and_create_industrial_rows_silent(frm, table_fieldname, assets, r
|
||||||
count: 0,
|
count: 0,
|
||||||
asset_names: []
|
asset_names: []
|
||||||
};
|
};
|
||||||
|
console.log(`Создана новая группа: "${group_key}"`);
|
||||||
}
|
}
|
||||||
|
|
||||||
grouped_assets[group_key].total_hectare += (asset.hectare || 0);
|
grouped_assets[group_key].total_hectare += (asset.hectare || 0);
|
||||||
|
|
@ -283,18 +403,34 @@ function group_and_create_industrial_rows_silent(frm, table_fieldname, assets, r
|
||||||
});
|
});
|
||||||
|
|
||||||
let total_groups = Object.keys(grouped_assets).length;
|
let total_groups = Object.keys(grouped_assets).length;
|
||||||
|
console.log(`Создано групп: ${total_groups}`);
|
||||||
|
|
||||||
|
// Детальная информация по группам
|
||||||
|
Object.entries(grouped_assets).forEach(([key, group]) => {
|
||||||
|
console.log(`Группа "${key}":`, {
|
||||||
|
количество_активов: group.count,
|
||||||
|
общая_площадь: group.total_hectare,
|
||||||
|
активы: group.asset_names
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
let completed_calculations = 0;
|
let completed_calculations = 0;
|
||||||
|
|
||||||
if (total_groups === 0) {
|
if (total_groups === 0) {
|
||||||
|
console.log('⚠️ Нет групп для создания строк');
|
||||||
resolve();
|
resolve();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.entries(grouped_assets).forEach(function([group_key, group]) {
|
Object.entries(grouped_assets).forEach(function([group_key, group]) {
|
||||||
|
console.log(`Создание строки для группы: "${group_key}"`);
|
||||||
|
|
||||||
create_industrial_row_with_calculation_silent(frm, table_fieldname, group.asset, group.total_hectare, group, function() {
|
create_industrial_row_with_calculation_silent(frm, table_fieldname, group.asset, group.total_hectare, group, function() {
|
||||||
completed_calculations++;
|
completed_calculations++;
|
||||||
|
console.log(`Прогресс создания строк: ${completed_calculations}/${total_groups}`);
|
||||||
|
|
||||||
if (completed_calculations === total_groups) {
|
if (completed_calculations === total_groups) {
|
||||||
|
console.log('✅ Все промышленные строки созданы');
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
@ -302,52 +438,77 @@ function group_and_create_industrial_rows_silent(frm, table_fieldname, assets, r
|
||||||
}
|
}
|
||||||
|
|
||||||
function create_industrial_group_key(asset) {
|
function create_industrial_group_key(asset) {
|
||||||
return [
|
let key_parts = [
|
||||||
asset.territorial_unit_name || '',
|
asset.territorial_unit_name || '',
|
||||||
asset.territorial_unit_code || '',
|
asset.territorial_unit_code || '',
|
||||||
asset.industrial_land_purpose || '',
|
asset.industrial_land_purpose || '',
|
||||||
asset.mining_note ? 'mining' : 'no_mining'
|
asset.mining_note ? 'mining' : 'no_mining'
|
||||||
].join('|');
|
];
|
||||||
|
|
||||||
|
console.log('Создание ключа из частей:', key_parts);
|
||||||
|
return key_parts.join('|');
|
||||||
}
|
}
|
||||||
|
|
||||||
function create_industrial_row_with_calculation_silent(frm, table_fieldname, asset, total_hectare, group_info, callback) {
|
function create_industrial_row_with_calculation_silent(frm, table_fieldname, asset, total_hectare, group_info, callback) {
|
||||||
|
console.log('=== create_industrial_row_with_calculation_silent ===');
|
||||||
|
console.log('Актив:', asset.name, 'Общая площадь:', total_hectare);
|
||||||
|
|
||||||
let row = frm.add_child(table_fieldname);
|
let row = frm.add_child(table_fieldname);
|
||||||
|
console.log('Строка добавлена в таблицу');
|
||||||
|
|
||||||
fill_industrial_row_fields(row, asset, total_hectare, group_info);
|
fill_industrial_row_fields(row, asset, total_hectare, group_info);
|
||||||
|
console.log('Поля строки заполнены:', row);
|
||||||
|
|
||||||
calculate_industrial_tax_for_row_silent(row, asset, total_hectare, group_info, callback);
|
calculate_industrial_tax_for_row_silent(row, asset, total_hectare, group_info, callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
function fill_industrial_row_fields(row, asset, total_hectare, group_info) {
|
function fill_industrial_row_fields(row, asset, total_hectare, group_info) {
|
||||||
|
console.log('=== fill_industrial_row_fields ===');
|
||||||
|
|
||||||
if (asset.territorial_unit_code) {
|
if (asset.territorial_unit_code) {
|
||||||
row.torpaqsahəsininyerləşdiyiəraziməntəqəsininkodu = parseFloat(asset.territorial_unit_code) || 0;
|
row.torpaqsahəsininyerləşdiyiəraziməntəqəsininkodu = parseFloat(asset.territorial_unit_code) || 0;
|
||||||
|
console.log('Код территориальной единицы:', asset.territorial_unit_code);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (asset.territorial_unit_name) {
|
if (asset.territorial_unit_name) {
|
||||||
row.torpaqsahəsininyerləşdiyiəraziməntəqəsininadı = asset.territorial_unit_name;
|
row.torpaqsahəsininyerləşdiyiəraziməntəqəsininadı = asset.territorial_unit_name;
|
||||||
|
console.log('Название территориальной единицы:', asset.territorial_unit_name);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (asset.industrial_land_purpose) {
|
if (asset.industrial_land_purpose) {
|
||||||
|
console.log('Назначение земли:', asset.industrial_land_purpose);
|
||||||
if (asset.industrial_land_purpose === 'Sənaye, tikinti, nəqliyyat, rabitə, ticarət-məişət xid-ti və dig. xüs. təy-tlı sahələr') {
|
if (asset.industrial_land_purpose === 'Sənaye, tikinti, nəqliyyat, rabitə, ticarət-məişət xid-ti və dig. xüs. təy-tlı sahələr') {
|
||||||
row.torpaqsahəsinintəyinatısənayətikinti = 1;
|
row.torpaqsahəsinintəyinatısənayətikinti = 1;
|
||||||
row.torpaqsahəsinintəyinatıyaşayışfondları = 0;
|
row.torpaqsahəsinintəyinatıyaşayışfondları = 0;
|
||||||
|
console.log('→ Промышленное назначение');
|
||||||
} else if (asset.industrial_land_purpose === 'Yaşayış fondları, həyətyanı və bağsahələri üzrə sahələr') {
|
} else if (asset.industrial_land_purpose === 'Yaşayış fondları, həyətyanı və bağsahələri üzrə sahələr') {
|
||||||
row.torpaqsahəsinintəyinatısənayətikinti = 0;
|
row.torpaqsahəsinintəyinatısənayətikinti = 0;
|
||||||
row.torpaqsahəsinintəyinatıyaşayışfondları = 1;
|
row.torpaqsahəsinintəyinatıyaşayışfondları = 1;
|
||||||
|
console.log('→ Жилое назначение');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (asset.mining_note !== undefined) {
|
if (asset.mining_note !== undefined) {
|
||||||
row.faydalıqazıntıçıxarılmasıbarədəqeyd = asset.mining_note ? 1 : 0;
|
row.faydalıqazıntıçıxarılmasıbarədəqeyd = asset.mining_note ? 1 : 0;
|
||||||
|
console.log('Полезные ископаемые:', asset.mining_note ? 'Да' : 'Нет');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (total_hectare > 0) {
|
if (total_hectare > 0) {
|
||||||
row.torpaqsahəsikvmetrləümumisahə = total_hectare;
|
row.torpaqsahəsikvmetrləümumisahə = total_hectare;
|
||||||
|
console.log('Общая площадь:', total_hectare, 'м²');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function calculate_industrial_tax_for_row_silent(row, asset, total_hectare, group_info, callback) {
|
function calculate_industrial_tax_for_row_silent(row, asset, total_hectare, group_info, callback) {
|
||||||
|
console.log('=== calculate_industrial_tax_for_row_silent ===');
|
||||||
|
console.log('Параметры расчета:', {
|
||||||
|
hectare: total_hectare,
|
||||||
|
territorial_unit_name: asset.territorial_unit_name,
|
||||||
|
industrial_land_purpose: asset.industrial_land_purpose
|
||||||
|
});
|
||||||
|
|
||||||
if (!asset.territorial_unit_name || !asset.industrial_land_purpose) {
|
if (!asset.territorial_unit_name || !asset.industrial_land_purpose) {
|
||||||
|
console.warn('⚠️ Не все поля заполнены, пропускаем расчет налога');
|
||||||
callback();
|
callback();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -360,12 +521,22 @@ function calculate_industrial_tax_for_row_silent(row, asset, total_hectare, grou
|
||||||
industrial_land_purpose: asset.industrial_land_purpose
|
industrial_land_purpose: asset.industrial_land_purpose
|
||||||
},
|
},
|
||||||
callback: function(response) {
|
callback: function(response) {
|
||||||
|
console.log('Результат расчета налога:', response);
|
||||||
|
|
||||||
if (response.message && response.message.tax_amount) {
|
if (response.message && response.message.tax_amount) {
|
||||||
row.vergiməbləğimanatla = response.message.tax_amount;
|
row.vergiməbləğimanatla = response.message.tax_amount;
|
||||||
|
console.log(`✅ Налог рассчитан: ${response.message.tax_amount} манат`);
|
||||||
|
|
||||||
|
if (response.message.calculation_details) {
|
||||||
|
console.log('Детали расчета:', response.message.calculation_details);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn('⚠️ Налог не рассчитан');
|
||||||
}
|
}
|
||||||
callback();
|
callback();
|
||||||
},
|
},
|
||||||
error: function() {
|
error: function(error) {
|
||||||
|
console.error('❌ Ошибка расчета налога:', error);
|
||||||
callback();
|
callback();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -10,10 +10,13 @@ class Landtaxdeclaration(Document):
|
||||||
def get_doctype_fields_info():
|
def get_doctype_fields_info():
|
||||||
"""Gets information about fields of əlavə_1 table and Asset"""
|
"""Gets information about fields of əlavə_1 table and Asset"""
|
||||||
|
|
||||||
|
frappe.log_error("=== get_doctype_fields_info: Начало ===", "Land Tax Debug")
|
||||||
|
|
||||||
result = {}
|
result = {}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Get metadata for əlavə_1 table
|
# Get metadata for əlavə_1 table
|
||||||
|
frappe.log_error("Получение метаданных для Land tax declaration Elave 1", "Land Tax Debug")
|
||||||
elave1_meta = frappe.get_meta('Land tax declaration Elave 1')
|
elave1_meta = frappe.get_meta('Land tax declaration Elave 1')
|
||||||
result['elave1_fields'] = []
|
result['elave1_fields'] = []
|
||||||
|
|
||||||
|
|
@ -28,7 +31,10 @@ def get_doctype_fields_info():
|
||||||
}
|
}
|
||||||
result['elave1_fields'].append(field_info)
|
result['elave1_fields'].append(field_info)
|
||||||
|
|
||||||
|
frappe.log_error(f"Elave 1 - найдено полей: {len(result['elave1_fields'])}", "Land Tax Debug")
|
||||||
|
|
||||||
# Get metadata for əlavə_2 table
|
# Get metadata for əlavə_2 table
|
||||||
|
frappe.log_error("Получение метаданных для Land tax declaration Elave 2", "Land Tax Debug")
|
||||||
elave2_meta = frappe.get_meta('Land tax declaration Elave 2')
|
elave2_meta = frappe.get_meta('Land tax declaration Elave 2')
|
||||||
result['elave2_fields'] = []
|
result['elave2_fields'] = []
|
||||||
|
|
||||||
|
|
@ -43,7 +49,10 @@ def get_doctype_fields_info():
|
||||||
}
|
}
|
||||||
result['elave2_fields'].append(field_info)
|
result['elave2_fields'].append(field_info)
|
||||||
|
|
||||||
|
frappe.log_error(f"Elave 2 - найдено полей: {len(result['elave2_fields'])}", "Land Tax Debug")
|
||||||
|
|
||||||
# Get metadata for Asset
|
# Get metadata for Asset
|
||||||
|
frappe.log_error("Получение метаданных для Asset", "Land Tax Debug")
|
||||||
asset_meta = frappe.get_meta('Asset')
|
asset_meta = frappe.get_meta('Asset')
|
||||||
result['asset_fields'] = []
|
result['asset_fields'] = []
|
||||||
|
|
||||||
|
|
@ -57,11 +66,14 @@ def get_doctype_fields_info():
|
||||||
'depends_on': field.depends_on or ''
|
'depends_on': field.depends_on or ''
|
||||||
}
|
}
|
||||||
result['asset_fields'].append(field_info)
|
result['asset_fields'].append(field_info)
|
||||||
|
|
||||||
|
frappe.log_error(f"Asset - найдено полей: {len(result['asset_fields'])}", "Land Tax Debug")
|
||||||
|
frappe.log_error("=== get_doctype_fields_info: Успешно завершено ===", "Land Tax Debug")
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
frappe.log_error(f"Error in get_doctype_fields_info: {str(e)}")
|
frappe.log_error(f"❌ Ошибка в get_doctype_fields_info: {str(e)}\n{frappe.get_traceback()}", "Land Tax Error")
|
||||||
return {'error': str(e)}
|
return {'error': str(e)}
|
||||||
|
|
||||||
# ===============================
|
# ===============================
|
||||||
|
|
@ -74,20 +86,43 @@ def calculate_agricultural_tax(hectare, cadastral_district_name, quality_groups,
|
||||||
Calculates tax for agricultural land
|
Calculates tax for agricultural land
|
||||||
Formula: hectare × score × markup
|
Formula: hectare × score × markup
|
||||||
"""
|
"""
|
||||||
|
frappe.log_error(
|
||||||
|
f"=== calculate_agricultural_tax: Начало ===\n"
|
||||||
|
f"Параметры:\n"
|
||||||
|
f" - hectare: {hectare}\n"
|
||||||
|
f" - cadastral_district_name: {cadastral_district_name}\n"
|
||||||
|
f" - quality_groups: {quality_groups}\n"
|
||||||
|
f" - agricultural_land_purpose: {agricultural_land_purpose}",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Input validation
|
# Input validation
|
||||||
if not hectare or not cadastral_district_name or not quality_groups or not agricultural_land_purpose:
|
if not hectare or not cadastral_district_name or not quality_groups or not agricultural_land_purpose:
|
||||||
frappe.throw("Not all fields are filled for calculation")
|
error_msg = "Не все поля заполнены для расчета"
|
||||||
|
frappe.log_error(f"❌ Валидация: {error_msg}", "Land Tax Error")
|
||||||
|
frappe.throw(error_msg)
|
||||||
|
|
||||||
# Get score from JSON file
|
# Get score from JSON file
|
||||||
|
frappe.log_error(f"Получение балла для района '{cadastral_district_name}', группа '{quality_groups}'", "Land Tax Debug")
|
||||||
score = get_cadastral_score(cadastral_district_name, quality_groups)
|
score = get_cadastral_score(cadastral_district_name, quality_groups)
|
||||||
|
frappe.log_error(f"✅ Получен балл: {score}", "Land Tax Debug")
|
||||||
|
|
||||||
# Determine markup
|
# Determine markup
|
||||||
|
frappe.log_error(f"Получение коэффициента для назначения '{agricultural_land_purpose}'", "Land Tax Debug")
|
||||||
markup = get_markup_coefficient(agricultural_land_purpose)
|
markup = get_markup_coefficient(agricultural_land_purpose)
|
||||||
|
frappe.log_error(f"✅ Получен коэффициент: {markup}", "Land Tax Debug")
|
||||||
|
|
||||||
# Calculate using formula
|
# Calculate using formula
|
||||||
result = float(hectare) * score * markup
|
result = float(hectare) * score * markup
|
||||||
|
|
||||||
|
frappe.log_error(
|
||||||
|
f"=== Расчет завершен ===\n"
|
||||||
|
f"Формула: {hectare} × {score} × {markup} = {result}\n"
|
||||||
|
f"Результат: {result} манат",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'tax_amount': result,
|
'tax_amount': result,
|
||||||
'calculation_details': {
|
'calculation_details': {
|
||||||
|
|
@ -99,44 +134,78 @@ def calculate_agricultural_tax(hectare, cadastral_district_name, quality_groups,
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
frappe.throw(f"Error during calculation: {str(e)}")
|
frappe.log_error(
|
||||||
|
f"❌ Ошибка в calculate_agricultural_tax: {str(e)}\n{frappe.get_traceback()}",
|
||||||
|
"Land Tax Error"
|
||||||
|
)
|
||||||
|
frappe.throw(f"Ошибка при расчете: {str(e)}")
|
||||||
|
|
||||||
def get_cadastral_score(cadastral_district_name, quality_group):
|
def get_cadastral_score(cadastral_district_name, quality_group):
|
||||||
"""
|
"""
|
||||||
Extracts score from JSON file based on cadastral district name and quality group
|
Extracts score from JSON file based on cadastral district name and quality group
|
||||||
"""
|
"""
|
||||||
|
frappe.log_error(
|
||||||
|
f"=== get_cadastral_score ===\n"
|
||||||
|
f"Район: {cadastral_district_name}\n"
|
||||||
|
f"Группа качества: {quality_group}",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Path to JSON file
|
# Path to JSON file
|
||||||
json_file_path = frappe.get_app_path('taxes_az', 'data', 'cadastral_points_data.json')
|
json_file_path = frappe.get_app_path('taxes_az', 'data', 'cadastral_points_data.json')
|
||||||
|
frappe.log_error(f"Путь к JSON: {json_file_path}", "Land Tax Debug")
|
||||||
|
|
||||||
# Read JSON file
|
# Read JSON file
|
||||||
with open(json_file_path, 'r', encoding='utf-8') as file:
|
with open(json_file_path, 'r', encoding='utf-8') as file:
|
||||||
data = json.load(file)
|
data = json.load(file)
|
||||||
|
|
||||||
|
frappe.log_error(f"JSON файл успешно загружен, всего регионов: {len(data.get('cadastral_regions', []))}", "Land Tax Debug")
|
||||||
|
|
||||||
# Find corresponding region
|
# Find corresponding region
|
||||||
for region in data.get('cadastral_regions', []):
|
for region in data.get('cadastral_regions', []):
|
||||||
if region.get('region_name') == cadastral_district_name:
|
if region.get('region_name') == cadastral_district_name:
|
||||||
|
frappe.log_error(f"✅ Найден регион: {cadastral_district_name}", "Land Tax Debug")
|
||||||
|
|
||||||
# Get score for specified quality group
|
# Get score for specified quality group
|
||||||
quality_groups = region.get('quality_groups', {})
|
quality_groups = region.get('quality_groups', {})
|
||||||
score = quality_groups.get(quality_group)
|
score = quality_groups.get(quality_group)
|
||||||
|
|
||||||
|
frappe.log_error(
|
||||||
|
f"Группы качества в регионе: {list(quality_groups.keys())}\n"
|
||||||
|
f"Балл для группы '{quality_group}': {score}",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
# If score is null or not found, return 0
|
# If score is null or not found, return 0
|
||||||
return score if score is not None else 0
|
return score if score is not None else 0
|
||||||
|
|
||||||
# If region not found
|
# If region not found
|
||||||
frappe.throw(f"Cadastral district '{cadastral_district_name}' not found in database")
|
error_msg = f"Кадастровый район '{cadastral_district_name}' не найден в базе данных"
|
||||||
|
frappe.log_error(f"❌ {error_msg}", "Land Tax Error")
|
||||||
|
frappe.throw(error_msg)
|
||||||
|
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
frappe.throw("Cadastral data file not found. Contact system administrator")
|
error_msg = "Файл кадастровых данных не найден. Обратитесь к администратору"
|
||||||
except json.JSONDecodeError:
|
frappe.log_error(f"❌ {error_msg}\nПуть: {json_file_path}", "Land Tax Error")
|
||||||
frappe.throw("Error reading cadastral data file")
|
frappe.throw(error_msg)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
error_msg = f"Ошибка чтения файла кадастровых данных: {str(e)}"
|
||||||
|
frappe.log_error(f"❌ {error_msg}", "Land Tax Error")
|
||||||
|
frappe.throw("Ошибка чтения файла кадастровых данных")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
frappe.throw(f"Error getting cadastral score: {str(e)}")
|
frappe.log_error(
|
||||||
|
f"❌ Ошибка получения кадастрового балла: {str(e)}\n{frappe.get_traceback()}",
|
||||||
|
"Land Tax Error"
|
||||||
|
)
|
||||||
|
frappe.throw(f"Ошибка получения кадастрового балла: {str(e)}")
|
||||||
|
|
||||||
def get_markup_coefficient(agricultural_land_purpose):
|
def get_markup_coefficient(agricultural_land_purpose):
|
||||||
"""
|
"""
|
||||||
Determines markup coefficient based on land use purpose
|
Determines markup coefficient based on land use purpose
|
||||||
"""
|
"""
|
||||||
|
frappe.log_error(f"=== get_markup_coefficient ===\nНазначение: {agricultural_land_purpose}", "Land Tax Debug")
|
||||||
|
|
||||||
markup_map = {
|
markup_map = {
|
||||||
"Əkin, dinc və çoxillik əkmələr": 0.06,
|
"Əkin, dinc və çoxillik əkmələr": 0.06,
|
||||||
"Biçənək, örüş və otlaqlar": 0.006 # 0.06 / 10
|
"Biçənək, örüş və otlaqlar": 0.006 # 0.06 / 10
|
||||||
|
|
@ -145,8 +214,14 @@ def get_markup_coefficient(agricultural_land_purpose):
|
||||||
coefficient = markup_map.get(agricultural_land_purpose)
|
coefficient = markup_map.get(agricultural_land_purpose)
|
||||||
|
|
||||||
if coefficient is None:
|
if coefficient is None:
|
||||||
frappe.throw(f"Unknown land purpose type: {agricultural_land_purpose}")
|
error_msg = f"Неизвестный тип назначения земли: {agricultural_land_purpose}"
|
||||||
|
frappe.log_error(
|
||||||
|
f"❌ {error_msg}\nДоступные типы: {list(markup_map.keys())}",
|
||||||
|
"Land Tax Error"
|
||||||
|
)
|
||||||
|
frappe.throw(error_msg)
|
||||||
|
|
||||||
|
frappe.log_error(f"✅ Коэффициент: {coefficient}", "Land Tax Debug")
|
||||||
return coefficient
|
return coefficient
|
||||||
|
|
||||||
# ===============================
|
# ===============================
|
||||||
|
|
@ -159,67 +234,126 @@ def calculate_industrial_tax(hectare, territorial_unit_name, industrial_land_pur
|
||||||
Calculates tax for industrial land
|
Calculates tax for industrial land
|
||||||
Formula: (area_in_sqm ÷ 100) × score (progressive system)
|
Formula: (area_in_sqm ÷ 100) × score (progressive system)
|
||||||
"""
|
"""
|
||||||
|
frappe.log_error(
|
||||||
|
f"=== calculate_industrial_tax: Начало ===\n"
|
||||||
|
f"Параметры:\n"
|
||||||
|
f" - hectare (площадь в м²): {hectare}\n"
|
||||||
|
f" - territorial_unit_name: {territorial_unit_name}\n"
|
||||||
|
f" - industrial_land_purpose: {industrial_land_purpose}",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Input validation
|
# Input validation
|
||||||
if not hectare or not territorial_unit_name or not industrial_land_purpose:
|
if not hectare or not territorial_unit_name or not industrial_land_purpose:
|
||||||
frappe.throw("Not all fields are filled for calculation")
|
error_msg = "Не все поля заполнены для расчета"
|
||||||
|
frappe.log_error(f"❌ Валидация: {error_msg}", "Land Tax Error")
|
||||||
|
frappe.throw(error_msg)
|
||||||
|
|
||||||
# Use value as is - this is square meters
|
# Use value as is - this is square meters
|
||||||
area_sqm = float(hectare)
|
area_sqm = float(hectare)
|
||||||
|
frappe.log_error(f"Площадь для расчета: {area_sqm} м²", "Land Tax Debug")
|
||||||
|
|
||||||
# Get scores from JSON file
|
# Get scores from JSON file
|
||||||
|
frappe.log_error(f"Получение баллов для '{territorial_unit_name}', назначение '{industrial_land_purpose}'", "Land Tax Debug")
|
||||||
score_data = get_industrial_land_scores(territorial_unit_name, industrial_land_purpose)
|
score_data = get_industrial_land_scores(territorial_unit_name, industrial_land_purpose)
|
||||||
|
frappe.log_error(f"✅ Получены баллы: {score_data}", "Land Tax Debug")
|
||||||
|
|
||||||
# Calculate using progressive formula
|
# Calculate using progressive formula
|
||||||
|
frappe.log_error("Начало расчета по прогрессивной формуле", "Land Tax Debug")
|
||||||
calculation_result = calculate_industrial_land_formula(area_sqm, score_data)
|
calculation_result = calculate_industrial_land_formula(area_sqm, score_data)
|
||||||
|
|
||||||
|
frappe.log_error(
|
||||||
|
f"=== Расчет завершен ===\n"
|
||||||
|
f"Формула: {calculation_result['formula']}\n"
|
||||||
|
f"Результат: {calculation_result['total']} манат",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'tax_amount': calculation_result['total'],
|
'tax_amount': calculation_result['total'],
|
||||||
'calculation_details': calculation_result
|
'calculation_details': calculation_result
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
frappe.throw(f"Error during calculation: {str(e)}")
|
frappe.log_error(
|
||||||
|
f"❌ Ошибка в calculate_industrial_tax: {str(e)}\n{frappe.get_traceback()}",
|
||||||
|
"Land Tax Error"
|
||||||
|
)
|
||||||
|
frappe.throw(f"Ошибка при расчете: {str(e)}")
|
||||||
|
|
||||||
def get_industrial_land_scores(territorial_unit_name, industrial_land_purpose):
|
def get_industrial_land_scores(territorial_unit_name, industrial_land_purpose):
|
||||||
"""
|
"""
|
||||||
Extracts scores from JSON file for industrial land
|
Extracts scores from JSON file for industrial land
|
||||||
"""
|
"""
|
||||||
|
frappe.log_error(
|
||||||
|
f"=== get_industrial_land_scores ===\n"
|
||||||
|
f"Территория: {territorial_unit_name}\n"
|
||||||
|
f"Назначение: {industrial_land_purpose}",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Path to JSON file
|
# Path to JSON file
|
||||||
json_file_path = frappe.get_app_path('taxes_az', 'data', 'industrial_land_data.json')
|
json_file_path = frappe.get_app_path('taxes_az', 'data', 'industrial_land_data.json')
|
||||||
|
frappe.log_error(f"Путь к JSON: {json_file_path}", "Land Tax Debug")
|
||||||
|
|
||||||
# Read JSON file
|
# Read JSON file
|
||||||
with open(json_file_path, 'r', encoding='utf-8') as file:
|
with open(json_file_path, 'r', encoding='utf-8') as file:
|
||||||
data = json.load(file)
|
data = json.load(file)
|
||||||
|
|
||||||
|
frappe.log_error(f"JSON файл успешно загружен, всего регионов: {len(data.get('industrial_land_regions', []))}", "Land Tax Debug")
|
||||||
|
|
||||||
# Find corresponding region
|
# Find corresponding region
|
||||||
for region in data.get('industrial_land_regions', []):
|
for region in data.get('industrial_land_regions', []):
|
||||||
if region.get('settlement_name') == territorial_unit_name:
|
if region.get('settlement_name') == territorial_unit_name:
|
||||||
|
frappe.log_error(f"✅ Найден регион: {territorial_unit_name}", "Land Tax Debug")
|
||||||
|
|
||||||
# Get scores for specified land purpose
|
# Get scores for specified land purpose
|
||||||
land_purpose_rates = region.get('land_purpose_rates', {})
|
land_purpose_rates = region.get('land_purpose_rates', {})
|
||||||
purpose_rates = land_purpose_rates.get(industrial_land_purpose)
|
purpose_rates = land_purpose_rates.get(industrial_land_purpose)
|
||||||
|
|
||||||
if purpose_rates:
|
if purpose_rates:
|
||||||
return {
|
result = {
|
||||||
'up_to_10000': purpose_rates.get('up_to_10000_sqm', 0),
|
'up_to_10000': purpose_rates.get('up_to_10000_sqm', 0),
|
||||||
'above_10000': purpose_rates.get('above_10000_sqm', 0)
|
'above_10000': purpose_rates.get('above_10000_sqm', 0)
|
||||||
}
|
}
|
||||||
|
frappe.log_error(f"✅ Получены ставки: {result}", "Land Tax Debug")
|
||||||
|
return result
|
||||||
|
else:
|
||||||
|
frappe.log_error(f"⚠️ Назначение '{industrial_land_purpose}' не найдено в регионе", "Land Tax Debug")
|
||||||
|
|
||||||
# If region or purpose not found
|
# If region or purpose not found
|
||||||
frappe.throw(f"Data not found for territory '{territorial_unit_name}' and purpose '{industrial_land_purpose}'")
|
error_msg = f"Данные не найдены для территории '{territorial_unit_name}' и назначения '{industrial_land_purpose}'"
|
||||||
|
frappe.log_error(f"❌ {error_msg}", "Land Tax Error")
|
||||||
|
frappe.throw(error_msg)
|
||||||
|
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
frappe.throw("Industrial land data file not found. Contact system administrator")
|
error_msg = "Файл данных промышленных земель не найден. Обратитесь к администратору"
|
||||||
except json.JSONDecodeError:
|
frappe.log_error(f"❌ {error_msg}\nПуть: {json_file_path}", "Land Tax Error")
|
||||||
frappe.throw("Error reading industrial land data file")
|
frappe.throw(error_msg)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
error_msg = f"Ошибка чтения файла промышленных земель: {str(e)}"
|
||||||
|
frappe.log_error(f"❌ {error_msg}", "Land Tax Error")
|
||||||
|
frappe.throw("Ошибка чтения файла данных промышленных земель")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
frappe.throw(f"Error getting industrial land scores: {str(e)}")
|
frappe.log_error(
|
||||||
|
f"❌ Ошибка получения баллов промышленных земель: {str(e)}\n{frappe.get_traceback()}",
|
||||||
|
"Land Tax Error"
|
||||||
|
)
|
||||||
|
frappe.throw(f"Ошибка получения баллов промышленных земель: {str(e)}")
|
||||||
|
|
||||||
def calculate_industrial_land_formula(area_sqm, score_data):
|
def calculate_industrial_land_formula(area_sqm, score_data):
|
||||||
"""
|
"""
|
||||||
Calculates cost using progressive formula for industrial land
|
Calculates cost using progressive formula for industrial land
|
||||||
"""
|
"""
|
||||||
|
frappe.log_error(
|
||||||
|
f"=== calculate_industrial_land_formula ===\n"
|
||||||
|
f"Площадь: {area_sqm} м²\n"
|
||||||
|
f"Баллы: {score_data}",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
up_to_10000_score = score_data['up_to_10000']
|
up_to_10000_score = score_data['up_to_10000']
|
||||||
above_10000_score = score_data['above_10000']
|
above_10000_score = score_data['above_10000']
|
||||||
|
|
||||||
|
|
@ -240,6 +374,12 @@ def calculate_industrial_land_formula(area_sqm, score_data):
|
||||||
|
|
||||||
formula_text = f"{area_sqm} ÷ 100 × {up_to_10000_score} = {total}"
|
formula_text = f"{area_sqm} ÷ 100 × {up_to_10000_score} = {total}"
|
||||||
|
|
||||||
|
frappe.log_error(
|
||||||
|
f"Простой расчет (площадь ≤ 10000):\n"
|
||||||
|
f" {formula_text}",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# Progressive system: up to 10000 sqm + above 10000 sqm
|
# Progressive system: up to 10000 sqm + above 10000 sqm
|
||||||
|
|
||||||
|
|
@ -264,23 +404,42 @@ def calculate_industrial_land_formula(area_sqm, score_data):
|
||||||
|
|
||||||
total = part1_result + part2_result
|
total = part1_result + part2_result
|
||||||
formula_text = f"(10000 ÷ 100 × {up_to_10000_score}) + ({remaining_area} ÷ 100 × {above_10000_score}) = {part1_result} + {part2_result} = {total}"
|
formula_text = f"(10000 ÷ 100 × {up_to_10000_score}) + ({remaining_area} ÷ 100 × {above_10000_score}) = {part1_result} + {part2_result} = {total}"
|
||||||
|
|
||||||
|
frappe.log_error(
|
||||||
|
f"Прогрессивный расчет (площадь > 10000):\n"
|
||||||
|
f" Часть 1 (до 10000): {calculation_parts[0]['formula']}\n"
|
||||||
|
f" Часть 2 (свыше 10000): {calculation_parts[1]['formula']}\n"
|
||||||
|
f" Итого: {total}",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
return {
|
result = {
|
||||||
'total': total,
|
'total': total,
|
||||||
'area_sqm': area_sqm,
|
'area_sqm': area_sqm,
|
||||||
'formula': formula_text,
|
'formula': formula_text,
|
||||||
'calculation_parts': calculation_parts,
|
'calculation_parts': calculation_parts,
|
||||||
'scores_used': score_data
|
'scores_used': score_data
|
||||||
}
|
}
|
||||||
|
|
||||||
|
frappe.log_error(f"✅ Расчет завершен, результат: {result}", "Land Tax Debug")
|
||||||
|
return result
|
||||||
|
|
||||||
@frappe.whitelist()
|
@frappe.whitelist()
|
||||||
def get_assets_for_year(asset_type, year):
|
def get_assets_for_year(asset_type, year):
|
||||||
"""
|
"""
|
||||||
Gets assets filtered by type and purchase year
|
Gets assets filtered by type and purchase year
|
||||||
"""
|
"""
|
||||||
|
frappe.log_error(
|
||||||
|
f"=== get_assets_for_year: Начало ===\n"
|
||||||
|
f"Тип актива: {asset_type}\n"
|
||||||
|
f"Год: {year}",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Convert year to int for comparison
|
# Convert year to int for comparison
|
||||||
target_year = int(year)
|
target_year = int(year)
|
||||||
|
frappe.log_error(f"Целевой год (int): {target_year}", "Land Tax Debug")
|
||||||
|
|
||||||
# Build filters
|
# Build filters
|
||||||
filters = {
|
filters = {
|
||||||
|
|
@ -288,6 +447,8 @@ def get_assets_for_year(asset_type, year):
|
||||||
'custom_asset_type': asset_type
|
'custom_asset_type': asset_type
|
||||||
}
|
}
|
||||||
|
|
||||||
|
frappe.log_error(f"Фильтры для поиска: {filters}", "Land Tax Debug")
|
||||||
|
|
||||||
# Get appropriate fields based on asset type
|
# Get appropriate fields based on asset type
|
||||||
if asset_type == 'Kənd təsərrüfatı təyinatlı torpaq sahələri':
|
if asset_type == 'Kənd təsərrüfatı təyinatlı torpaq sahələri':
|
||||||
fields = [
|
fields = [
|
||||||
|
|
@ -301,6 +462,7 @@ def get_assets_for_year(asset_type, year):
|
||||||
'hectare',
|
'hectare',
|
||||||
'purchase_date'
|
'purchase_date'
|
||||||
]
|
]
|
||||||
|
frappe.log_error("Тип: Сельскохозяйственные земли", "Land Tax Debug")
|
||||||
else: # Industrial assets
|
else: # Industrial assets
|
||||||
fields = [
|
fields = [
|
||||||
'name',
|
'name',
|
||||||
|
|
@ -312,22 +474,50 @@ def get_assets_for_year(asset_type, year):
|
||||||
'hectare',
|
'hectare',
|
||||||
'purchase_date'
|
'purchase_date'
|
||||||
]
|
]
|
||||||
|
frappe.log_error("Тип: Промышленные земли", "Land Tax Debug")
|
||||||
|
|
||||||
|
frappe.log_error(f"Поля для выборки: {fields}", "Land Tax Debug")
|
||||||
|
|
||||||
# Get all assets of the specified type
|
# Get all assets of the specified type
|
||||||
|
frappe.log_error("Выполнение запроса к базе данных...", "Land Tax Debug")
|
||||||
assets = frappe.get_list('Asset', filters=filters, fields=fields)
|
assets = frappe.get_list('Asset', filters=filters, fields=fields)
|
||||||
|
frappe.log_error(f"✅ Получено активов из БД: {len(assets)}", "Land Tax Debug")
|
||||||
|
|
||||||
# Filter by purchase_date year
|
# Filter by purchase_date year
|
||||||
filtered_assets = []
|
filtered_assets = []
|
||||||
for asset in assets:
|
for asset in assets:
|
||||||
if asset.get('purchase_date'):
|
if asset.get('purchase_date'):
|
||||||
purchase_year = asset['purchase_date'].year
|
purchase_year = asset['purchase_date'].year
|
||||||
|
|
||||||
if purchase_year == target_year:
|
if purchase_year == target_year:
|
||||||
filtered_assets.append(asset)
|
filtered_assets.append(asset)
|
||||||
# If no purchase_date, we can decide whether to include or exclude
|
frappe.log_error(
|
||||||
# For now, excluding assets without purchase_date
|
f"✅ Актив подходит: {asset['name']} (дата покупки: {asset['purchase_date']})",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
frappe.log_error(
|
||||||
|
f"⏭️ Актив пропущен: {asset['name']} (год покупки: {purchase_year}, нужен {target_year})",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
frappe.log_error(
|
||||||
|
f"⚠️ Актив без даты покупки: {asset['name']} - пропущен",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
|
frappe.log_error(
|
||||||
|
f"=== get_assets_for_year: Завершено ===\n"
|
||||||
|
f"Всего активов из БД: {len(assets)}\n"
|
||||||
|
f"Отфильтровано по году {target_year}: {len(filtered_assets)}",
|
||||||
|
"Land Tax Debug"
|
||||||
|
)
|
||||||
|
|
||||||
return filtered_assets
|
return filtered_assets
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
frappe.log_error(f"Error in get_assets_for_year: {str(e)}")
|
frappe.log_error(
|
||||||
return []
|
f"❌ Ошибка в get_assets_for_year: {str(e)}\n{frappe.get_traceback()}",
|
||||||
|
"Land Tax Error"
|
||||||
|
)
|
||||||
|
return []
|
||||||
Loading…
Reference in New Issue