Skip to content

Commit

Permalink
added export to file feature
Browse files Browse the repository at this point in the history
  • Loading branch information
aabduvak committed Apr 19, 2024
1 parent aea3ab8 commit f0989ba
Show file tree
Hide file tree
Showing 6 changed files with 133 additions and 18 deletions.
55 changes: 41 additions & 14 deletions api/bot/commands/callback_query.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from telegram import Update
from telegram.ext import CallbackContext

Expand All @@ -7,10 +8,13 @@

from api.utils import toggle_workplace, toggle_service, send_telegram_message
from api.utils.debt import get_debt_list
from api.utils.excel import create_debt_list_file
from .workplaces import get_workplaces_keyboard
from .service_config import get_service_keyboard
from .debt import get_export_keyboard

BRANCHES_ID = settings.BRANCHES_ID
CHAT_ID = settings.CHAT_ID


def get_current_time() -> str:
Expand Down Expand Up @@ -61,22 +65,45 @@ def callback_handler(update: Update, context: CallbackContext) -> None:

elif data[0] == "currency":
time = get_current_time()

new_markup = get_export_keyboard(data[1])
query.edit_message_text(
text="Выберите один из вариантов ниже\n",
reply_markup=new_markup,
)

return

elif data[0] == "export":
for branch in BRANCHES_ID:
debt_list = get_debt_list(branch, time, data[1])
message = "Список клиентов, у которых есть задолженность\n\n"
if data[1] == "false":
debt_list = get_debt_list(branch, data[3])
message = "Список клиентов, у которых есть задолженность\n\n"

for i in range(0, len(debt_list["customers"])):
amount = "{:,.2f}".format(
debt_list["customers"][i]["amount"]
).replace(",", " ")
message += f'{i + 1}. {debt_list["customers"][i]["name"]} --> {amount} {data[3]}\n\n'

message += (
f"Общий долг (50 чел.): "
+ "{:,.2f}".format(debt_list["total_debt"]).replace(",", " ")
+ f" {data[3]}"
)
send_telegram_message(message)
else:
filename = "DebtList.xlsx"
file_path = create_debt_list_file(
currency=data[3], filename=filename, branch=branch
)

for i in range(0, len(debt_list["customers"])):
amount = "{:,.2f}".format(debt_list["customers"][i]["amount"]).replace(
",", " "
context.bot.send_document(
chat_id=CHAT_ID,
document=open(file_path, "rb"),
caption="Список должников (топ-1000)",
)
message += f'{i + 1}. {debt_list["customers"][i]["name"]} --> {amount} {data[1]}\n\n'

message += (
f"Общий долг (50 чел.): "
+ "{:,.2f}".format(debt_list["total_debt"]).replace(",", " ")
+ f" {data[1]}"
)
send_telegram_message(message)
os.remove(file_path)

query.answer("✅ Список клиентов успешно отправлен в чат")
query.message.delete()
return
21 changes: 20 additions & 1 deletion api/bot/commands/debt.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,32 @@ def get_currency_keyboard():
return InlineKeyboardMarkup(keyboard)


def get_export_keyboard(currency):
keyboard = [
[
InlineKeyboardButton(
text="Получить полный список (xlsx)",
callback_data=f"export:true:currency:{currency}",
)
],
[
InlineKeyboardButton(
text="Получить список топ-50 должников",
callback_data=f"export:false:currency:{currency}",
)
],
]

return InlineKeyboardMarkup(keyboard)


def debt_list(update: Update, context: CallbackContext) -> None:
if not is_valid_chat(update):
return

reply_markup = get_currency_keyboard()

update.message.reply_text(
text="Выберите валюту для отображения списка долгов (50 чел.)",
text="Выберите валюту для отображения списка долгов",
reply_markup=reply_markup,
)
1 change: 1 addition & 0 deletions api/management/commands/fetch_partial.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def fetch_partial_data():
error_handler("❌ Ошибка при создании типа платежа", date)
return


class Command(BaseCommand):
help = "Fetch partial data from Smartup API"

Expand Down
10 changes: 7 additions & 3 deletions api/utils/debt.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from .get_data import get_data


def get_debt_list(branch_id: str, date: str, currency="USD", limit=50) -> dict:
def get_debt_list(branch_id: str, currency="USD", limit=50) -> dict:
columns = [
"legal_person_id",
"legal_person_name",
"currency_name",
"debit_amount",
]

Expand All @@ -30,8 +32,10 @@ def get_debt_list(branch_id: str, date: str, currency="USD", limit=50) -> dict:

for debt_info in response["data"]:
item = {
"name": debt_info[0],
"amount": float(debt_info[1]),
"id": debt_info[0],
"name": debt_info[1],
"currency": debt_info[2],
"amount": float(debt_info[3]),
}

data["total_debt"] += item["amount"]
Expand Down
60 changes: 60 additions & 0 deletions api/utils/excel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import os
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
from api.utils.debt import get_debt_list


def create_debt_list_file(
currency: str, branch: str, limit=1000, filename="DebtList.xlsx"
):
wb = Workbook()
ws = wb.active

COLUMN_LIST = ["ИД контрагента", "Контрагент", "Валюта", "Долг"]

# Set column widths (optional)
ws.column_dimensions["A"].width = 20
ws.column_dimensions["B"].width = 40
ws.column_dimensions["C"].width = 15
ws.column_dimensions["D"].width = 20

ws.column_dimensions["A"].height = 20
ws.column_dimensions["B"].height = 20
ws.column_dimensions["C"].height = 20
ws.column_dimensions["D"].height = 20

# Define custom styles
header_font = Font(bold=True, color="000000")
header_fill = PatternFill(
start_color="C4C4C4", end_color="C4C4C4", fill_type="solid"
)
alignment_center = Alignment(horizontal="center")

for col_num, header in enumerate(COLUMN_LIST, start=1):
cell = ws.cell(row=1, column=col_num, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = alignment_center

debt_list = get_debt_list(branch, currency, limit)["customers"]
for row_num, debt_item in enumerate(debt_list, start=2):
if debt_item["amount"] == 0:
continue

debt_item["amount"] = "{:,.2f}".format(debt_item["amount"]).replace(",", " ")
row = [
debt_item["id"],
debt_item["name"],
debt_item["currency"],
debt_item["amount"],
]
ws.append(row)

for col_num in range(1, 5):
if col_num != 2:
cell = ws.cell(row=row_num, column=col_num)
cell.alignment = alignment_center

wb.save(filename)
file_path = os.path.abspath(filename)
return file_path
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,19 @@ Django==4.2.11
django-environ==0.10.0
djangorestframework==3.14.0
drf-yasg==1.21.7
et-xmlfile==1.1.0
idna==3.7
inflection==0.5.1
lxml==4.9.3
mypy-extensions==1.0.0
mysqlclient==2.2.0
numpy==1.26.4
openpyxl==3.1.2
packaging==23.1
pathspec==0.12.1
platformdirs==4.2.0
psycopg2-binary==2.9.7
python-dateutil==2.9.0.post0
python-telegram-bot==13.13
pytz==2023.3
PyYAML==6.0.1
Expand Down

0 comments on commit f0989ba

Please sign in to comment.