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.cursor = self.conn.cursor(dictionary=True)
# GET ALL AO RECORDS using stored procedure "GetAllItr"
def get_all_ao(self):
self.cursor.callproc("GetAllAO")
records = []
@@ -25,7 +23,6 @@ class AOHandler:
def get_ao_by_id(self, id):
# Call stored procedure
self.cursor.callproc('GetAOById', [id])
# Fetch result
records = []
for result in self.cursor.stored_results():
@@ -64,26 +61,23 @@ class AOHandler:
# UPDATE ITR RECORD by AO id
# def update(self, id, data):
def update_ao(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'
# ]
fields = [
"year","gross_total_income", "disallowance_14a", "disallowance_37",
"deduction_80ia_business", "deduction_sec37_disallowance", "deduction_80g",
"net_taxable_income", "tax_30_percent", "tax_book_profit_18_5",
"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(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]
# values.append(id)
# self.cursor.execute(query, tuple(values))
# self.conn.commit()
self.cursor.callproc("UpdateAOById", values)
self.conn.commit()
# DELETE RECORD by AO id

View File

@@ -45,23 +45,26 @@ class CITHandler:
self.cursor.callproc("InsertCIT", values)
self.conn.commit()
# UPDATE CIT RECORD
# def update_cit(self, id, data):
# columns = [
# "year", "gross_total_income", "deduction_80ia_business", "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"
# ]
def update_cit(self, id, data):
columns = [
"year", "gross_total_income", "deduction_80ia_business",
"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"
]
# set_clause = ", ".join([f"{col}=%s" for col in columns])
# query = f"UPDATE cit SET {set_clause} WHERE id=%s"
values = [id] + [data.get(col, 0) for col in columns]
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
def delete_cit(self, id):

View File

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

View File

@@ -1,5 +1,17 @@
from AppCode.Config import DBConfig
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
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 = [
'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37',
'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'
]
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]
values.append(id)
self.cursor.execute(query, tuple(values))
self.cursor.callproc("UpdateITR", values)
self.conn.commit()
@@ -90,6 +115,51 @@ class ITRHandler:
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
def close(self):
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.

425
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
import os
import pandas as pd
import pymysql
import io
import mysql.connector
from werkzeug.utils import secure_filename
from AppCode.FileHandler import FileHandler
from AppCode.DocumentHandler import DocumentHandler
from config import db_config
from AppCode.Config import DBConfig
from AppCode.ITRHandler import ITRHandler
from AppCode.AOHandler import AOHandler
from AppCode.CITHandler import CITHandler
from AppCode.ITATHandler import ITATHandler
from config import db_config
from AppCode.Config import DBConfig
from AppCode.YearGet import YearGet
app = Flask(__name__)
@@ -76,42 +83,6 @@ def uploaded_file(filename):
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
## ===============================================
## 1. READ/DISPLAY all ITR records
@app.route('/itr_records')
def display_itr():
@@ -186,6 +156,61 @@ def delete_itr(id):
itr.close()
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 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
@app.route('/ao/delete/<int:id>', methods=['POST'])
@@ -224,41 +268,43 @@ def delete_ao(id):
return redirect(url_for('display_ao'))
# 3. UPDATE AO record
@app.route('/ao/update/<int:id>', methods=['GET', 'POST'])
def update_ao(id):
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM ao WHERE id = %s", (id,))
ao_record = cursor.fetchone()
# @app.route('/ao/update/<int:id>', methods=['GET', 'POST'])
# def update_ao(id):
# conn = get_db_connection()
# cursor = conn.cursor(dictionary=True)
# cursor.execute("SELECT * FROM ao WHERE id = %s", (id,))
# ao_record = cursor.fetchone()
if not ao_record:
cursor.close()
conn.close()
return "AO record not found", 404
# if not ao_record:
# cursor.close()
# conn.close()
# return "AO record not found", 404
if request.method == 'POST':
columns = [
'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37',
'deduction_80ia_business', 'deduction_sec37_disallowance', 'deduction_80g',
'net_taxable_income', 'tax_30_percent', 'tax_book_profit_18_5',
'surcharge_12', 'edu_cess_3', 'total_tax_payable', 'mat_credit',
'interest_234c', 'total_tax', 'advance_tax', 'tds', 'tcs',
'tax_on_assessment', 'refund'
]
values = [request.form.get(col, 0) for col in columns]
set_clause = ", ".join([f"{col}=%s" for col in columns])
query = f"UPDATE ao SET {set_clause} WHERE id=%s"
cursor.execute(query, tuple(values) + (id,))
conn.commit()
cursor.close()
conn.close()
flash("AO record updated successfully!", "success")
return redirect(url_for('display_ao'))
# if request.method == 'POST':
# columns = [
# 'year', 'gross_total_income', 'disallowance_14a', 'disallowance_37',
# 'deduction_80ia_business', 'deduction_sec37_disallowance', 'deduction_80g',
# 'net_taxable_income', 'tax_30_percent', 'tax_book_profit_18_5',
# 'surcharge_12', 'edu_cess_3', 'total_tax_payable', 'mat_credit',
# 'interest_234c', 'total_tax', 'advance_tax', 'tds', 'tcs',
# 'tax_on_assessment', 'refund'
# ]
# values = [request.form.get(col, 0) for col in columns]
# set_clause = ", ".join([f"{col}=%s" for col in columns])
# query = f"UPDATE ao SET {set_clause} WHERE id=%s"
# cursor.execute(query, tuple(values) + (id,))
# conn.commit()
# cursor.close()
# conn.close()
# flash("AO record updated successfully!", "success")
# return redirect(url_for('display_ao'))
cursor.close()
conn.close()
return render_template('update_ao.html', record=ao_record)
# cursor.close()
# conn.close()
# return render_template('update_ao.html', record=ao_record)
@@ -297,27 +343,28 @@ def delete_cit(id):
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'])
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()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM cit WHERE id=%s", (id,))
@@ -495,35 +542,52 @@ def update_itat(id):
# 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'])
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()
itat = ITATHandler()
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()
data = {k: request.form.get(k, 0) for k in request.form}
itat.add_itat(data)
itat.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)
itat.close()
return render_template('add_itat.html')
# @app.route('/itat/update/<int:id>', methods=['GET', 'POST'])
@@ -651,64 +715,60 @@ def get_db_connection():
connection = mysql.connector.connect(**db_config)
return connection
import pandas as pd
import pymysql
import io
@app.route('/reports')
def reports():
return render_template("reports.html")
# new new
@app.route('/itr_report', methods=['GET'])
def itr_report():
connection = pymysql.connect(**db_config)
try:
selected_year = request.args.get('year')
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 selected_year:
itr = ITRHandler()
output = itr.itr_report_download(selected_year)
itr.close()
if df.empty:
return "No records found for the selected year."
if output is None:
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)
return send_file(
output,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
as_attachment=True,
download_name=f"ITR_Report_{selected_year}.xlsx"
)
# 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)
else:
years = yearGetter.get_year_by_model("GetITRYears")
yearGetter.close()
return render_template("itr_reports.html", years=years)
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
# @app.route('/itr/reports', methods=['GET', 'POST'])
# def itr_reports():
# yearGetter = YearGet()
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"
)
# 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)
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('/ao_report', methods=['GET'])
@@ -832,35 +892,35 @@ def itat_report():
@app.route('/itr_report_download', methods=['GET'])
def itr_report_download():
connection = pymysql.connect(**db_config)
try:
selected_year = request.args.get('year')
# @app.route('/itr_report_download', methods=['GET'])
# def itr_report_download():
# connection = pymysql.connect(**db_config)
# try:
# selected_year = request.args.get('year')
if selected_year:
query = "SELECT * FROM itr WHERE year = %s"
df = pd.read_sql(query, connection, params=[selected_year])
# if selected_year:
# query = "SELECT * FROM itr WHERE year = %s"
# df = pd.read_sql(query, connection, params=[selected_year])
output = io.BytesIO()
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
df.to_excel(writer, index=False, sheet_name=f"ITR {selected_year}")
output.seek(0)
# output = io.BytesIO()
# with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
# df.to_excel(writer, index=False, sheet_name=f"ITR {selected_year}")
# output.seek(0)
return send_file(
output,
download_name=f"ITR_Report_{selected_year}.xlsx",
as_attachment=True,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
else:
# If no year is selected, show dropdown
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()
# return send_file(
# output,
# download_name=f"ITR_Report_{selected_year}.xlsx",
# as_attachment=True,
# mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
# )
# else:
# # If no year is selected, show dropdown
# 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('/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
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'])
def summary_report():
year = request.args.get('year')

120
test.py
View File

@@ -101,3 +101,123 @@ class DocumentHandler:
# return redirect(url_for('view_documents'))
#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)