add itai model and irt report download code commit.

This commit is contained in:
2025-12-01 17:45:16 +05:30
parent aa063b7a80
commit 7cf8287b34
13 changed files with 503 additions and 235 deletions

View File

@@ -9,10 +9,8 @@ class AOHandler:
self.conn = DBConfig.get_db_connection() self.conn = DBConfig.get_db_connection()
self.cursor = self.conn.cursor(dictionary=True) self.cursor = self.conn.cursor(dictionary=True)
# GET ALL AO RECORDS using stored procedure "GetAllItr" # GET ALL AO RECORDS using stored procedure "GetAllItr"
def get_all_ao(self): def get_all_ao(self):
self.cursor.callproc("GetAllAO") self.cursor.callproc("GetAllAO")
records = [] records = []
@@ -25,7 +23,6 @@ class AOHandler:
def get_ao_by_id(self, id): def get_ao_by_id(self, id):
# Call stored procedure # Call stored procedure
self.cursor.callproc('GetAOById', [id]) self.cursor.callproc('GetAOById', [id])
# Fetch result # Fetch result
records = [] records = []
for result in self.cursor.stored_results(): for result in self.cursor.stored_results():
@@ -64,26 +61,23 @@ class AOHandler:
# UPDATE ITR RECORD by AO id # UPDATE ITR RECORD by AO id
# def update(self, id, data): def update_ao(self, id, data):
# columns = [ fields = [
# 'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37', "year","gross_total_income", "disallowance_14a", "disallowance_37",
# 'deduction_80ia_business', 'deduction_80ia_misc', 'deduction_80ia_other', "deduction_80ia_business", "deduction_sec37_disallowance", "deduction_80g",
# 'deduction_sec37_disallowance', 'deduction_80g', 'net_taxable_income', "net_taxable_income", "tax_30_percent", "tax_book_profit_18_5",
# 'tax_30_percent', 'tax_book_profit_18_5', 'tax_payable', 'surcharge_12', "surcharge_12", "edu_cess_3", "total_tax_payable", "mat_credit",
# 'edu_cess_3', 'total_tax_payable', 'mat_credit', 'interest_234c', "interest_234c", "total_tax", "advance_tax", "tds", "tcs",
# 'total_tax', 'advance_tax', 'tds', 'tcs', 'tax_on_assessment', 'refund' "tax_on_assessment", "refund"
# ] ]
# set_clause = ", ".join([f"{col}=%s" for col in columns]) values = [id] + [data.get(f, 0) for f in fields]
# query = f"UPDATE itr SET {set_clause} WHERE id = %s" print("AO update values:", values)
# values = [data.get(col, 0) for col in columns] self.cursor.callproc("UpdateAOById", values)
# values.append(id) self.conn.commit()
# self.cursor.execute(query, tuple(values))
# self.conn.commit()
# DELETE RECORD by AO id # DELETE RECORD by AO id

View File

@@ -45,23 +45,26 @@ class CITHandler:
self.cursor.callproc("InsertCIT", values) self.cursor.callproc("InsertCIT", values)
self.conn.commit() self.conn.commit()
# UPDATE CIT RECORD # UPDATE CIT RECORD
# def update_cit(self, id, data): def update_cit(self, id, data):
# columns = [ columns = [
# "year", "gross_total_income", "deduction_80ia_business", "deduction_sec37_disallowance", "year", "gross_total_income", "deduction_80ia_business",
# "deduction_80g", "net_taxable_income", "tax_30_percent", "tax_book_profit_18_5", "deduction_sec37_disallowance", "deduction_80g",
# "tax_payable", "surcharge_12", "edu_cess_3", "total_tax_payable", "mat_credit", "net_taxable_income", "tax_30_percent", "tax_book_profit_18_5",
# "interest_234c", "total_tax", "advance_tax", "tds", "tcs", "tax_on_assessment", "refund" "tax_payable", "surcharge_12", "edu_cess_3",
# ] "total_tax_payable", "mat_credit", "interest_234c",
"total_tax", "advance_tax", "tds", "tcs",
"tax_on_assessment", "refund"
]
# set_clause = ", ".join([f"{col}=%s" for col in columns]) values = [id] + [data.get(col, 0) for col in columns]
# query = f"UPDATE cit SET {set_clause} WHERE id=%s"
self.cursor.callproc("UpdateCITById", values)
self.conn.commit()
# values = [data.get(col, 0) for col in columns]
# values.append(id)
# self.cursor.execute(query, tuple(values))
# self.conn.commit()
# DELETE CIT RECORD # DELETE CIT RECORD
def delete_cit(self, id): def delete_cit(self, id):

View File

@@ -31,17 +31,15 @@ class ITATHandler:
# INSERT ITAT (PROC) # INSERT ITAT (PROC)
def add_itat(self, data): def add_itat(self, data):
values = [ values = [
data.get("cit_id"), data.get("mat_tax_credit", 0),
data.get("year"), data.get("surcharge", 0),
data.get("mat_tax_credit"), data.get("cess", 0),
data.get("surcharge"), data.get("total_credit", 0),
data.get("cess"), data.get("year", 0)
data.get("total_credit")
] ]
self.cursor.callproc("InsertITAT", values) self.cursor.callproc("InsertITAT", values)
self.conn.commit() self.conn.commit()
# UPDATE ITAT (PROC) # UPDATE ITAT (PROC)
def update_itat(self, id, data): def update_itat(self, id, data):
values = [ values = [

View File

@@ -1,5 +1,17 @@
from AppCode.Config import DBConfig from AppCode.Config import DBConfig
import mysql.connector import mysql.connector
from AppCode.YearGet import YearGet
import pandas as pd
import pymysql
import io
# new
from AppCode.Config import DBConfig
import mysql.connector
import pandas as pd
import io
from flask import send_file, render_template, request
@@ -61,8 +73,24 @@ class ITRHandler:
# UPDATE ITR RECORD by ITR id # UPDATE ITR RECORD by ITR id
def update(self, id, data): # def update(self, id, data):
# columns = [
# 'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37',
# 'deduction_80ia_business', 'deduction_80ia_misc', 'deduction_80ia_other',
# 'deduction_sec37_disallowance', 'deduction_80g', 'net_taxable_income',
# 'tax_30_percent', 'tax_book_profit_18_5', 'tax_payable', 'surcharge_12',
# 'edu_cess_3', 'total_tax_payable', 'mat_credit', 'interest_234c',
# 'total_tax', 'advance_tax', 'tds', 'tcs', 'tax_on_assessment', 'refund'
# ]
# values = [data.get(col, 0) for col in columns]
# values.insert(0, id) # first argument is ID
# print("values.insert(0, id)-->",values.insert(0, id))
# self.cursor.callproc("UpdateITR", values)
# self.conn.commit()
def update(self, id, data):
columns = [ columns = [
'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37', 'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37',
'deduction_80ia_business', 'deduction_80ia_misc', 'deduction_80ia_other', 'deduction_80ia_business', 'deduction_80ia_misc', 'deduction_80ia_other',
@@ -72,14 +100,11 @@ class ITRHandler:
'total_tax', 'advance_tax', 'tds', 'tcs', 'tax_on_assessment', 'refund' 'total_tax', 'advance_tax', 'tds', 'tcs', 'tax_on_assessment', 'refund'
] ]
set_clause = ", ".join([f"{col}=%s" for col in columns]) values = [id] + [data.get(col, 0) for col in columns]
query = f"UPDATE itr SET {set_clause} WHERE id = %s" print("Final values:", values)
values = [data.get(col, 0) for col in columns] self.cursor.callproc("UpdateITR", values)
values.append(id)
self.cursor.execute(query, tuple(values))
self.conn.commit() self.conn.commit()
@@ -90,6 +115,51 @@ class ITRHandler:
self.conn.commit() self.conn.commit()
def itr_report_download(self, selected_year):
try:
# Call stored procedure
self.cursor.callproc("GetITRByYear", [selected_year])
rows = []
for result in self.cursor.stored_results():
rows = result.fetchall()
if not rows:
return None
# Convert SQL rows to DataFrame
df = pd.DataFrame(rows)
# Transpose
df_transposed = df.transpose()
df_transposed.insert(0, 'Field', df_transposed.index)
record_cols = {
i: f"Record {i}"
for i in df_transposed.columns if isinstance(i, int)
}
df_transposed.rename(columns=record_cols, inplace=True)
df_transposed.reset_index(drop=True, inplace=True)
# Save to Excel in memory
output = io.BytesIO()
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
df_transposed.to_excel(writer, index=False, sheet_name='ITR_Vertical')
worksheet = writer.sheets['ITR_Vertical']
worksheet.set_column(0, 0, 30)
output.seek(0)
return output
except mysql.connector.Error as e:
print("MySQL Error →", e)
return None
# CLOSE CONNECTION # CLOSE CONNECTION
def close(self): def close(self):
self.cursor.close() self.cursor.close()

28
AppCode/YearGet.py Normal file
View File

@@ -0,0 +1,28 @@
from AppCode.Config import DBConfig
import mysql.connector
class YearGet:
def __init__(self):
self.conn = DBConfig.get_db_connection()
self.cursor = self.conn.cursor(dictionary=True)
def get_year_by_model(self, proc_name):
try:
self.cursor.callproc(proc_name)
years = []
for result in self.cursor.stored_results():
rows = result.fetchall()
years = [row["year"] for row in rows]
return years
except mysql.connector.Error as e:
print("MySQL Error:", e)
return []
def close(self):
self.cursor.close()
self.conn.close()

Binary file not shown.

411
main.py
View File

@@ -1,17 +1,24 @@
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, abort, flash,send_file from flask import Flask, render_template, request, redirect, url_for, send_from_directory, abort, flash,send_file
import os import os
import pandas as pd
import pymysql
import io
import mysql.connector import mysql.connector
from werkzeug.utils import secure_filename from werkzeug.utils import secure_filename
from AppCode.FileHandler import FileHandler from AppCode.FileHandler import FileHandler
from AppCode.DocumentHandler import DocumentHandler from AppCode.DocumentHandler import DocumentHandler
from config import db_config
from AppCode.Config import DBConfig
from AppCode.ITRHandler import ITRHandler from AppCode.ITRHandler import ITRHandler
from AppCode.AOHandler import AOHandler from AppCode.AOHandler import AOHandler
from AppCode.CITHandler import CITHandler from AppCode.CITHandler import CITHandler
from AppCode.ITATHandler import ITATHandler from AppCode.ITATHandler import ITATHandler
from config import db_config from AppCode.YearGet import YearGet
from AppCode.Config import DBConfig
app = Flask(__name__) app = Flask(__name__)
@@ -76,42 +83,6 @@ def uploaded_file(filename):
return send_file(filepath, as_attachment=True) return send_file(filepath, as_attachment=True)
## 3. UPDATE an existing ITR record
@app.route('/itr/update/<int:id>', methods=['GET', 'POST'])
def update_itr(id):
conn = get_db_connection()
if request.method == 'POST':
cursor = conn.cursor()
columns = [
'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37',
'deduction_80ia_business', 'deduction_80ia_misc', 'deduction_80ia_other',
'deduction_sec37_disallowance', 'deduction_80g', 'net_taxable_income',
'tax_30_percent', 'tax_book_profit_18_5', 'tax_payable', 'surcharge_12',
'edu_cess_3', 'total_tax_payable', 'mat_credit', 'interest_234c',
'total_tax', 'advance_tax', 'tds', 'tcs', 'tax_on_assessment', 'refund'
]
# Create the "SET column = %s" part of the query
set_clause = ', '.join([f"{col} = %s" for col in columns])
query = f"UPDATE itr SET {set_clause} WHERE id = %s"
values = [request.form.get(col, 0) for col in columns]
values.append(id) # Add the ID for the WHERE clause at the end
cursor.execute(query, tuple(values))
conn.commit()
cursor.close()
conn.close()
return redirect(url_for('display_itr'))
# For a GET request, fetch the existing data and show it in the form
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM itr WHERE id = %s", (id,))
record = cursor.fetchone()
cursor.close()
conn.close()
return render_template('update_itr.html', record=record)
@@ -155,7 +126,6 @@ def update_itr(id):
## ITR (Income Tax Return) Routes ## ITR (Income Tax Return) Routes
## =============================================== ## ===============================================
## 1. READ/DISPLAY all ITR records ## 1. READ/DISPLAY all ITR records
@app.route('/itr_records') @app.route('/itr_records')
def display_itr(): def display_itr():
@@ -186,6 +156,61 @@ def delete_itr(id):
itr.close() itr.close()
return redirect(url_for('display_itr')) return redirect(url_for('display_itr'))
## 3. UPDATE an existing ITR record
@app.route('/itr/update/<int:id>', methods=['GET', 'POST'])
def update_itr(id):
itr = ITRHandler()
if request.method == 'POST':
data = {k: request.form.get(k, 0) for k in request.form}
print("itr data-->",data)
itr.update(id, data=data)
itr.close()
return redirect(url_for('display_itr'))
record = itr.get_itr_by_id(id)
itr.close()
return render_template('update_itr.html', record=record)
## 3. UPDATE an existing ITR record
# @app.route('/itr/update/<int:id>', methods=['GET', 'POST'])
# def update_itr(id):
# conn = get_db_connection()
# if request.method == 'POST':
# cursor = conn.cursor()
# columns = [
# 'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37',
# 'deduction_80ia_business', 'deduction_80ia_misc', 'deduction_80ia_other',
# 'deduction_sec37_disallowance', 'deduction_80g', 'net_taxable_income',
# 'tax_30_percent', 'tax_book_profit_18_5', 'tax_payable', 'surcharge_12',
# 'edu_cess_3', 'total_tax_payable', 'mat_credit', 'interest_234c',
# 'total_tax', 'advance_tax', 'tds', 'tcs', 'tax_on_assessment', 'refund'
# ]
# # Create the "SET column = %s" part of the query
# set_clause = ', '.join([f"{col} = %s" for col in columns])
# query = f"UPDATE itr SET {set_clause} WHERE id = %s"
# values = [request.form.get(col, 0) for col in columns]
# values.append(id) # Add the ID for the WHERE clause at the end
# cursor.execute(query, tuple(values))
# conn.commit()
# cursor.close()
# conn.close()
# return redirect(url_for('display_itr'))
# # For a GET request, fetch the existing data and show it in the form
# cursor = conn.cursor(dictionary=True)
# cursor.execute("SELECT * FROM itr WHERE id = %s", (id,))
# record = cursor.fetchone()
# cursor.close()
# conn.close()
# return render_template('update_itr.html', record=record)
@@ -213,6 +238,25 @@ def add_ao():
return redirect(url_for('display_ao')) return redirect(url_for('display_ao'))
return render_template('add_ao.html') return render_template('add_ao.html')
# 3. UPDATE AO record
@app.route('/ao/update/<int:id>', methods=['GET', 'POST'])
def update_ao(id):
ao = AOHandler()
record = ao.get_ao_by_id(id)
if not record:
return "AO record not found", 404
if request.method == 'POST':
data = request.form.to_dict()
ao.update_ao(id, data)
ao.close()
flash("AO record updated successfully!", "success")
return redirect(url_for('display_ao'))
ao.close()
return render_template("update_ao.html", record=record)
# 4. DELETE AO record safely # 4. DELETE AO record safely
@app.route('/ao/delete/<int:id>', methods=['POST']) @app.route('/ao/delete/<int:id>', methods=['POST'])
@@ -224,41 +268,43 @@ def delete_ao(id):
return redirect(url_for('display_ao')) return redirect(url_for('display_ao'))
# 3. UPDATE AO record # 3. UPDATE AO record
@app.route('/ao/update/<int:id>', methods=['GET', 'POST']) # @app.route('/ao/update/<int:id>', methods=['GET', 'POST'])
def update_ao(id): # def update_ao(id):
conn = get_db_connection() # conn = get_db_connection()
cursor = conn.cursor(dictionary=True) # cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM ao WHERE id = %s", (id,)) # cursor.execute("SELECT * FROM ao WHERE id = %s", (id,))
ao_record = cursor.fetchone() # ao_record = cursor.fetchone()
if not ao_record: # if not ao_record:
cursor.close() # cursor.close()
conn.close() # conn.close()
return "AO record not found", 404 # return "AO record not found", 404
if request.method == 'POST': # if request.method == 'POST':
columns = [ # columns = [
'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37', # 'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37',
'deduction_80ia_business', 'deduction_sec37_disallowance', 'deduction_80g', # 'deduction_80ia_business', 'deduction_sec37_disallowance', 'deduction_80g',
'net_taxable_income', 'tax_30_percent', 'tax_book_profit_18_5', # 'net_taxable_income', 'tax_30_percent', 'tax_book_profit_18_5',
'surcharge_12', 'edu_cess_3', 'total_tax_payable', 'mat_credit', # 'surcharge_12', 'edu_cess_3', 'total_tax_payable', 'mat_credit',
'interest_234c', 'total_tax', 'advance_tax', 'tds', 'tcs', # 'interest_234c', 'total_tax', 'advance_tax', 'tds', 'tcs',
'tax_on_assessment', 'refund' # 'tax_on_assessment', 'refund'
] # ]
values = [request.form.get(col, 0) for col in columns] # values = [request.form.get(col, 0) for col in columns]
set_clause = ", ".join([f"{col}=%s" for col in columns]) # set_clause = ", ".join([f"{col}=%s" for col in columns])
query = f"UPDATE ao SET {set_clause} WHERE id=%s" # query = f"UPDATE ao SET {set_clause} WHERE id=%s"
cursor.execute(query, tuple(values) + (id,)) # cursor.execute(query, tuple(values) + (id,))
conn.commit() # conn.commit()
cursor.close() # cursor.close()
conn.close() # conn.close()
flash("AO record updated successfully!", "success") # flash("AO record updated successfully!", "success")
return redirect(url_for('display_ao')) # return redirect(url_for('display_ao'))
cursor.close() # cursor.close()
conn.close() # conn.close()
return render_template('update_ao.html', record=ao_record) # return render_template('update_ao.html', record=ao_record)
@@ -297,27 +343,28 @@ def delete_cit(id):
return redirect(url_for('display_cit')) return redirect(url_for('display_cit'))
# @app.route('/cit/update/<int:id>', methods=['GET', 'POST'])
# def update_cit(id):
# handler = CITHandler()
# record = handler.get_cit_by_id(id)
# if not record:
# handler.close()
# return "CIT record not found", 404
# if request.method == 'POST':
# handler.update_cit(id, request.form)
# handler.close()
# return redirect(url_for('display_cit'))
# handler.close()
# return render_template('add_cit.html', record=record)
@app.route('/cit/update/<int:id>', methods=['GET', 'POST']) @app.route('/cit/update/<int:id>', methods=['GET', 'POST'])
def update_cit(id): def update_cit(id):
cit = CITHandler()
record = cit.get_cit_by_id(id)
if not record:
cit.close()
return "CIT record not found", 404
if request.method == 'POST':
data = {k: request.form.get(k, 0) for k in request.form}
cit.update_cit(id, data)
cit.close()
return redirect(url_for('display_cit'))
cit.close()
return render_template('update_cit.html', record=record)
# @app.route('/cit/update/<int:id>', methods=['GET', 'POST'])
# def update_cit(id):
conn = get_db_connection() conn = get_db_connection()
cursor = conn.cursor(dictionary=True) cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM cit WHERE id=%s", (id,)) cursor.execute("SELECT * FROM cit WHERE id=%s", (id,))
@@ -495,35 +542,52 @@ def update_itat(id):
# ADD a new ITAT record # ADD a new ITAT record
# @app.route('/itat/add', methods=['GET', 'POST'])
# def add_itat():
# conn = get_db_connection()
# cursor = conn.cursor(dictionary=True)
# # Fetch all CIT records to choose from
# cursor.execute("SELECT id, year FROM cit ORDER BY year DESC")
# cit_records = cursor.fetchall()
# if request.method == 'POST':
# cit_id = request.form.get('cit_id') # selected parent CIT id
# columns = ['id', 'year','mat_tax_credit', 'surcharge', 'cess', 'total_credit']
# values = [cit_id,
# request.form.get('year', 0),
# request.form.get('mat_tax_credit', 0),
# request.form.get('surcharge', 0),
# request.form.get('cess', 0),
# request.form.get('total_credit', 0)]
# query = f"INSERT INTO itat ({', '.join(columns)}) VALUES ({', '.join(['%s'] * len(columns))})"
# cursor.execute(query, tuple(values))
# conn.commit()
# cursor.close()
# conn.close()
# flash("ITAT record added successfully!", "success")
# return redirect(url_for('display_itat'))
# cursor.close()
# conn.close()
# return render_template('add_itat.html', cit_records=cit_records)
@app.route('/itat/add', methods=['GET', 'POST']) @app.route('/itat/add', methods=['GET', 'POST'])
def add_itat(): def add_itat():
conn = get_db_connection() itat = ITATHandler()
cursor = conn.cursor(dictionary=True)
# Fetch all CIT records to choose from
cursor.execute("SELECT id, year FROM cit ORDER BY year DESC")
cit_records = cursor.fetchall()
if request.method == 'POST': if request.method == 'POST':
cit_id = request.form.get('cit_id') # selected parent CIT id data = {k: request.form.get(k, 0) for k in request.form}
columns = ['id', 'year','mat_tax_credit', 'surcharge', 'cess', 'total_credit'] itat.add_itat(data)
values = [cit_id, itat.close()
request.form.get('year', 0),
request.form.get('mat_tax_credit', 0),
request.form.get('surcharge', 0),
request.form.get('cess', 0),
request.form.get('total_credit', 0)]
query = f"INSERT INTO itat ({', '.join(columns)}) VALUES ({', '.join(['%s'] * len(columns))})"
cursor.execute(query, tuple(values))
conn.commit()
cursor.close()
conn.close()
flash("ITAT record added successfully!", "success") flash("ITAT record added successfully!", "success")
return redirect(url_for('display_itat')) return redirect(url_for('display_itat'))
cursor.close() itat.close()
conn.close() return render_template('add_itat.html')
return render_template('add_itat.html', cit_records=cit_records)
# @app.route('/itat/update/<int:id>', methods=['GET', 'POST']) # @app.route('/itat/update/<int:id>', methods=['GET', 'POST'])
@@ -651,48 +715,25 @@ def get_db_connection():
connection = mysql.connector.connect(**db_config) connection = mysql.connector.connect(**db_config)
return connection return connection
import pandas as pd
import pymysql
import io
@app.route('/reports') @app.route('/reports')
def reports(): def reports():
return render_template("reports.html") return render_template("reports.html")
# new new
@app.route('/itr_report', methods=['GET']) @app.route('/itr_report', methods=['GET'])
def itr_report(): def itr_report():
connection = pymysql.connect(**db_config) yearGetter = YearGet()
try:
selected_year = request.args.get('year') selected_year = request.args.get('year')
if selected_year: if selected_year:
# Fetch ITR data for the selected year itr = ITRHandler()
query = "SELECT * FROM itr WHERE year = %s" output = itr.itr_report_download(selected_year)
df = pd.read_sql(query, connection, params=[selected_year]) itr.close()
if df.empty: if output is None:
return "No records found for the selected year." return "No records found for the selected year."
# Transpose DataFrame: vertical fields, horizontal records
df_transposed = df.transpose()
df_transposed.insert(0, 'Field', df_transposed.index)
# Rename columns as Record 1, Record 2, etc.
record_cols = {i: f'Record {i}' for i in df_transposed.columns if isinstance(i, int)}
df_transposed.rename(columns=record_cols, inplace=True)
df_transposed.reset_index(drop=True, inplace=True)
output = io.BytesIO()
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
df_transposed.to_excel(writer, index=False, sheet_name='ITR_Vertical')
# Format for better readability (optional)
workbook = writer.book
worksheet = writer.sheets['ITR_Vertical']
worksheet.set_column(0, 0, 30) # Field column wider
output.seek(0)
return send_file( return send_file(
output, output,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
@@ -701,14 +742,33 @@ def itr_report():
) )
else: else:
# Render dropdown form with available years years = yearGetter.get_year_by_model("GetITRYears")
with connection.cursor() as cursor: yearGetter.close()
cursor.execute("SELECT DISTINCT year FROM itr ORDER BY year DESC")
years = [row[0] for row in cursor.fetchall()]
return render_template("itr_reports.html", years=years) return render_template("itr_reports.html", years=years)
finally:
connection.close()
# @app.route('/itr/reports', methods=['GET', 'POST'])
# def itr_reports():
# yearGetter = YearGet()
# if request.method == "POST":
# selected_year = request.form.get("year")
# itr=ITRHandler()
# yearGetter.close()
# return redirect(url_for("itr_report_result", year=selected_year))
# # GET method → fetch all distinct years through procedure
# years = yearGetter.get_year_by_model("GetITRYears")
# yearGetter.close()
# print("---- year --",years)
# return render_template("itr_reports.html", years=years)
@app.route('/ao_report', methods=['GET']) @app.route('/ao_report', methods=['GET'])
@@ -832,35 +892,35 @@ def itat_report():
@app.route('/itr_report_download', methods=['GET']) # @app.route('/itr_report_download', methods=['GET'])
def itr_report_download(): # def itr_report_download():
connection = pymysql.connect(**db_config) # connection = pymysql.connect(**db_config)
try: # try:
selected_year = request.args.get('year') # selected_year = request.args.get('year')
if selected_year: # if selected_year:
query = "SELECT * FROM itr WHERE year = %s" # query = "SELECT * FROM itr WHERE year = %s"
df = pd.read_sql(query, connection, params=[selected_year]) # df = pd.read_sql(query, connection, params=[selected_year])
output = io.BytesIO() # output = io.BytesIO()
with pd.ExcelWriter(output, engine='xlsxwriter') as writer: # with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
df.to_excel(writer, index=False, sheet_name=f"ITR {selected_year}") # df.to_excel(writer, index=False, sheet_name=f"ITR {selected_year}")
output.seek(0) # output.seek(0)
return send_file( # return send_file(
output, # output,
download_name=f"ITR_Report_{selected_year}.xlsx", # download_name=f"ITR_Report_{selected_year}.xlsx",
as_attachment=True, # as_attachment=True,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
) # )
else: # else:
# If no year is selected, show dropdown # # If no year is selected, show dropdown
with connection.cursor() as cursor: # with connection.cursor() as cursor:
cursor.execute("SELECT DISTINCT year FROM itr ORDER BY year DESC") # cursor.execute("SELECT DISTINCT year FROM itr ORDER BY year DESC")
years = [row[0] for row in cursor.fetchall()] # years = [row[0] for row in cursor.fetchall()]
return render_template('itr_reports.html', years=years) # return render_template('itr_reports.html', years=years)
finally: # finally:
connection.close() # connection.close()
@app.route('/download/<int:doc_id>') @app.route('/download/<int:doc_id>')
@@ -878,12 +938,7 @@ def download_report(doc_id):
file_path = os.path.join('static', 'uploads', document['filename']) # adjust as per your storage file_path = os.path.join('static', 'uploads', document['filename']) # adjust as per your storage
return send_from_directory(directory='static/uploads', path=document['filename'], as_attachment=True) return send_from_directory(directory='static/uploads', path=document['filename'], as_attachment=True)
# main.py
from flask import Flask, send_file
import pandas as pd
import io
import pymysql # or use mysql.connector if preferred
from config import db_config
@app.route('/summary_report', methods=['GET']) @app.route('/summary_report', methods=['GET'])
def summary_report(): def summary_report():
year = request.args.get('year') year = request.args.get('year')

120
test.py
View File

@@ -101,3 +101,123 @@ class DocumentHandler:
# return redirect(url_for('view_documents')) # return redirect(url_for('view_documents'))
#return render_template('upload.html') #return render_template('upload.html')
# old itr report code
@app.route('/itr_report', methods=['GET'])
def itr_report():
yearGetter = YearGet()
connection = pymysql.connect(**db_config)
try:
selected_year = request.args.get('year')
if selected_year:
# Fetch ITR data for the selected year
query = "SELECT * FROM itr WHERE year = %s"
df = pd.read_sql(query, connection, params=[selected_year])
if df.empty:
return "No records found for the selected year."
# Transpose DataFrame: vertical fields, horizontal records
df_transposed = df.transpose()
df_transposed.insert(0, 'Field', df_transposed.index)
# Rename columns as Record 1, Record 2, etc.
record_cols = {i: f'Record {i}' for i in df_transposed.columns if isinstance(i, int)}
df_transposed.rename(columns=record_cols, inplace=True)
df_transposed.reset_index(drop=True, inplace=True)
output = io.BytesIO()
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
df_transposed.to_excel(writer, index=False, sheet_name='ITR_Vertical')
# Format for better readability (optional)
workbook = writer.book
worksheet = writer.sheets['ITR_Vertical']
worksheet.set_column(0, 0, 30) # Field column wider
output.seek(0)
return send_file(
output,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
as_attachment=True,
download_name=f"ITR_Report_{selected_year}.xlsx"
)
else:
# Render dropdown form with available years
with connection.cursor() as cursor:
cursor.execute("SELECT DISTINCT year FROM itr ORDER BY year DESC")
years = [row[0] for row in cursor.fetchall()]
return render_template("itr_reports.html", years=years)
finally:
connection.close()
# --------------\
@app.route('/itr_report', methods=['GET'])
def itr_report():
yearGetter = YearGet()
selected_year = request.args.get('year')
if selected_year:
# Fetch ITR data for the selected year
query = "SELECT * FROM itr WHERE year = %s"
df = pd.read_sql(query, connection, params=[selected_year])
if df.empty:
return "No records found for the selected year."
# Transpose DataFrame: vertical fields, horizontal records
df_transposed = df.transpose()
df_transposed.insert(0, 'Field', df_transposed.index)
# Rename columns as Record 1, Record 2, etc.
record_cols = {i: f'Record {i}' for i in df_transposed.columns if isinstance(i, int)}
df_transposed.rename(columns=record_cols, inplace=True)
df_transposed.reset_index(drop=True, inplace=True)
output = io.BytesIO()
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
df_transposed.to_excel(writer, index=False, sheet_name='ITR_Vertical')
# Format for better readability (optional)
workbook = writer.book
worksheet = writer.sheets['ITR_Vertical']
worksheet.set_column(0, 0, 30) # Field column wider
output.seek(0)
return send_file(
output,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
as_attachment=True,
download_name=f"ITR_Report_{selected_year}.xlsx"
)
else:
# Render dropdown form with available years
with connection.cursor() as cursor:
# cursor.execute("SELECT DISTINCT year FROM itr ORDER BY year DESC")
# years = [row[0] for row in cursor.fetchall()]
years = yearGetter.get_year_by_model("GetITRYears")
yearGetter.close()
print("---- year --",years)
return render_template("itr_reports.html", years=years)