expenses.confirm_expense

  1from datetime import datetime
  2from dictionary.sql import not_payed_expense_query
  3from dictionary.vars import to_remove_list, today, decimal_values
  4from functions.query_executor import QueryExecutor
  5from functions.login import Login
  6from screens.reports.receipts import Receipts
  7from time import sleep
  8import pandas as pd
  9import streamlit as st
 10
 11
 12class ConfirmExpense:
 13    """
 14    Classe que representa a confirmação de despesas ainda não pagas.
 15    """
 16
 17    def get_not_payed_expense_id(self, description: str, value: float, date: str, time: str, category: str, account: str):
 18        """
 19        Realiza a consulta do id da despesa que ainda não foi paga.
 20
 21        Parameters
 22        ----------
 23        description : str
 24            A descrição da despesa.
 25        value : float
 26            O valor da despesa.
 27        date : str
 28            A data da despesa.
 29        time : str
 30            O horário da despesa.
 31        category : str
 32            A categoria da despesa.
 33        account : str
 34            A conta na qual a despesa foi registrada.
 35
 36        Returns
 37        -------
 38        id : int
 39            O ID da despesa não paga.
 40        """
 41
 42        get_id_query = """SELECT id_despesa FROM despesas WHERE descricao = "{}" AND valor = {} AND data = "{}" AND horario = "{}" AND categoria = "{}" AND conta = "{}";""".format(description, value, date, time, category, account)
 43        id = QueryExecutor().simple_consult_brute_query(get_id_query)
 44        id = QueryExecutor().treat_simple_result(id, to_remove_list)
 45        id = int(id)
 46
 47        return id
 48
 49    def update_not_payed_expenses(self, id: int, new_date: str):
 50        """
 51        Atualiza a despesa não paga para constar como paga.
 52
 53        Parameters
 54        ----------
 55        new_date : str
 56            A nova data da despesa.
 57        """
 58
 59        update_not_payed_query = """UPDATE despesas SET data = "{}", pago = "S" WHERE id_despesa = {};""".format(new_date, id)
 60        QueryExecutor().update_table_unique_register(update_not_payed_query,"Despesa atualizada com sucesso!", "Erro ao atualizar receita:")
 61
 62    def main_menu(self):
 63        """
 64        Exibe as despesas ainda não pagas.
 65        """
 66        user_name, user_document = Login().get_user_data(return_option="user_doc_name")
 67        logged_user, logged_user_password = Login().get_user_data(return_option="user_login_password")
 68
 69        col4, col5, col6 = st.columns(3)
 70
 71        expense_values = QueryExecutor().complex_compund_query(query=not_payed_expense_query, list_quantity=7, params=(user_name, user_document))
 72
 73        if len(expense_values[0]) >= 1:
 74
 75            with col4:
 76                st.subheader(body=":computer: Valores")
 77
 78                with st.expander(label="Dados", expanded=True):
 79
 80                    expense_id, description, value, date, time, category, account = (expense_values)
 81
 82                    time_list = []
 83
 84                    for i in range(0, len(time)):
 85                        aux_time = QueryExecutor().treat_simple_result(time[i], to_remove_list)
 86                        time_list.append(aux_time)
 87
 88                    loan_data_df = pd.DataFrame({"ID": expense_id, "Descrição": description, "Valor": value, "Data": date, "Horário": time_list, "Categoria": category, "Conta": account})
 89                    loan_data_df["Valor"] = loan_data_df["Valor"].apply(lambda x: f"R$ {x:.2f}".replace(".", ","))
 90                    loan_data_df["Data"] = pd.to_datetime(loan_data_df["Data"]).dt.strftime("%d/%m/%Y")
 91
 92                    st.dataframe(loan_data_df, hide_index=True,use_container_width=True)
 93
 94                    description_list = []
 95
 96                    for i in range(0, len(description)):
 97
 98                        index_description = {}
 99                        str_value = str(value[i])
100                        str_date = str(date[i])
101                        str_date = datetime.strptime(str_date, "%Y-%m-%d")
102                        query_str_date = str_date.strftime("%Y-%m-%d")
103                        final_str_account = str(account[i])
104
105                        index_description.update({"descrição": description[i], "valor": str_value, "data": query_str_date, "horario": time[i], "categoria": category[i], "conta": final_str_account})
106
107                        formatted_data = str(index_description["data"])
108                        formatted_data = datetime.strptime(formatted_data, "%Y-%m-%d")
109                        formatted_data = formatted_data.strftime("%d/%m/%Y")
110
111                        formatted_description = str(index_description["descrição"]) + " - " + "R$ {}".format(str(index_description["valor"]).replace(".", ",")) + " - " + formatted_data + " - " + str(index_description["horario"]) + " - " + str(index_description["categoria"]) + " - " + str(index_description["conta"])
112                        description_list.append(formatted_description)
113
114                    selected_revenue = st.selectbox(label="Selecione a despesa", options=description_list)
115
116                    confirm_selection = st.checkbox(label="Confirmar seleção")
117
118                update_button = st.button(label=":floppy_disk: Confirmar pagamento")
119
120                if confirm_selection and update_button:
121                    with col5:
122                        with st.spinner(text="Aguarde..."):
123                            sleep(2.5)
124
125                        st.subheader(body=":white_check_mark: Validação de Dados")
126
127                        final_description = str(index_description["descrição"])
128                        final_value = float(index_description["valor"])
129                        final_date = str(index_description["data"])
130                        final_category = str(index_description["categoria"])
131                        final_account = str(index_description["conta"])
132
133                        str_final_value = str(final_value)
134                        str_final_value = str_final_value.replace(".", ",")
135                        last_two_digits = str_final_value[-2:]
136                        if last_two_digits in decimal_values:
137                            str_final_value = str_final_value + "0"
138
139                        with st.subheader(body=":white_check_mark: Validação de Dados"):
140                            with st.expander(label="Dados", expanded=True):
141                                st.info(body="Descrição: {}".format(final_description))
142                                st.info(body="Valor: :heavy_dollar_sign: {}".format(str_final_value))
143                                st.info(body="Categoria: {}".format(final_category))
144                                st.info(body="Conta: {}".format(final_account))
145
146                    with col6:
147                        st.subheader(body=":pencil: Comprovante")
148                        with st.spinner(text="Aguarde..."):
149                            sleep(2.5)
150
151                        final_id = self.get_not_payed_expense_id(description=index_description["descrição"], value=index_description["valor"], date=index_description["data"], time=index_description["horario"], category=index_description["categoria"], account=index_description["conta"])
152
153                        self.update_not_payed_expenses(id=final_id, new_date=today)
154
155                        Receipts().generate_receipt(table="despesas", id=final_id, description=final_description, value=final_value, date=final_date, category=final_category, account=final_account)
156
157                        str_value = str(value)
158                        str_value = str_value.replace(".", ",")
159                        last_two_digits = str_value[-2:]
160                        if last_two_digits in decimal_values:
161                            str_value = str_value + "0"
162
163                        log_query = '''INSERT INTO financas.logs_atividades (usuario_log, tipo_log, conteudo_log) VALUES ( %s, %s, %s);'''
164                        log_values = (logged_user, "Registro", "Registrou uma despesa no valor de R$ {} associada a conta {}.".format(str_value, account))
165                        QueryExecutor().insert_query(log_query, log_values, "Log gravado.", "Erro ao gravar log:")
166
167                elif update_button and confirm_selection == False:
168                    with col5:
169                        st.subheader(body="")
170                        with st.spinner(text="Aguarde..."):
171                            sleep(2.5)
172                        with st.expander(label="Aviso", expanded=True):
173                            st.warning(body="Confirme os dados antes de prosseguir.")
174
175        elif len(expense_values[0]) == 0:
176
177            with col5:
178                st.info("Você não possui valores futuros a pagar aguardando confirmação.")
class ConfirmExpense:
 13class ConfirmExpense:
 14    """
 15    Classe que representa a confirmação de despesas ainda não pagas.
 16    """
 17
 18    def get_not_payed_expense_id(self, description: str, value: float, date: str, time: str, category: str, account: str):
 19        """
 20        Realiza a consulta do id da despesa que ainda não foi paga.
 21
 22        Parameters
 23        ----------
 24        description : str
 25            A descrição da despesa.
 26        value : float
 27            O valor da despesa.
 28        date : str
 29            A data da despesa.
 30        time : str
 31            O horário da despesa.
 32        category : str
 33            A categoria da despesa.
 34        account : str
 35            A conta na qual a despesa foi registrada.
 36
 37        Returns
 38        -------
 39        id : int
 40            O ID da despesa não paga.
 41        """
 42
 43        get_id_query = """SELECT id_despesa FROM despesas WHERE descricao = "{}" AND valor = {} AND data = "{}" AND horario = "{}" AND categoria = "{}" AND conta = "{}";""".format(description, value, date, time, category, account)
 44        id = QueryExecutor().simple_consult_brute_query(get_id_query)
 45        id = QueryExecutor().treat_simple_result(id, to_remove_list)
 46        id = int(id)
 47
 48        return id
 49
 50    def update_not_payed_expenses(self, id: int, new_date: str):
 51        """
 52        Atualiza a despesa não paga para constar como paga.
 53
 54        Parameters
 55        ----------
 56        new_date : str
 57            A nova data da despesa.
 58        """
 59
 60        update_not_payed_query = """UPDATE despesas SET data = "{}", pago = "S" WHERE id_despesa = {};""".format(new_date, id)
 61        QueryExecutor().update_table_unique_register(update_not_payed_query,"Despesa atualizada com sucesso!", "Erro ao atualizar receita:")
 62
 63    def main_menu(self):
 64        """
 65        Exibe as despesas ainda não pagas.
 66        """
 67        user_name, user_document = Login().get_user_data(return_option="user_doc_name")
 68        logged_user, logged_user_password = Login().get_user_data(return_option="user_login_password")
 69
 70        col4, col5, col6 = st.columns(3)
 71
 72        expense_values = QueryExecutor().complex_compund_query(query=not_payed_expense_query, list_quantity=7, params=(user_name, user_document))
 73
 74        if len(expense_values[0]) >= 1:
 75
 76            with col4:
 77                st.subheader(body=":computer: Valores")
 78
 79                with st.expander(label="Dados", expanded=True):
 80
 81                    expense_id, description, value, date, time, category, account = (expense_values)
 82
 83                    time_list = []
 84
 85                    for i in range(0, len(time)):
 86                        aux_time = QueryExecutor().treat_simple_result(time[i], to_remove_list)
 87                        time_list.append(aux_time)
 88
 89                    loan_data_df = pd.DataFrame({"ID": expense_id, "Descrição": description, "Valor": value, "Data": date, "Horário": time_list, "Categoria": category, "Conta": account})
 90                    loan_data_df["Valor"] = loan_data_df["Valor"].apply(lambda x: f"R$ {x:.2f}".replace(".", ","))
 91                    loan_data_df["Data"] = pd.to_datetime(loan_data_df["Data"]).dt.strftime("%d/%m/%Y")
 92
 93                    st.dataframe(loan_data_df, hide_index=True,use_container_width=True)
 94
 95                    description_list = []
 96
 97                    for i in range(0, len(description)):
 98
 99                        index_description = {}
100                        str_value = str(value[i])
101                        str_date = str(date[i])
102                        str_date = datetime.strptime(str_date, "%Y-%m-%d")
103                        query_str_date = str_date.strftime("%Y-%m-%d")
104                        final_str_account = str(account[i])
105
106                        index_description.update({"descrição": description[i], "valor": str_value, "data": query_str_date, "horario": time[i], "categoria": category[i], "conta": final_str_account})
107
108                        formatted_data = str(index_description["data"])
109                        formatted_data = datetime.strptime(formatted_data, "%Y-%m-%d")
110                        formatted_data = formatted_data.strftime("%d/%m/%Y")
111
112                        formatted_description = str(index_description["descrição"]) + " - " + "R$ {}".format(str(index_description["valor"]).replace(".", ",")) + " - " + formatted_data + " - " + str(index_description["horario"]) + " - " + str(index_description["categoria"]) + " - " + str(index_description["conta"])
113                        description_list.append(formatted_description)
114
115                    selected_revenue = st.selectbox(label="Selecione a despesa", options=description_list)
116
117                    confirm_selection = st.checkbox(label="Confirmar seleção")
118
119                update_button = st.button(label=":floppy_disk: Confirmar pagamento")
120
121                if confirm_selection and update_button:
122                    with col5:
123                        with st.spinner(text="Aguarde..."):
124                            sleep(2.5)
125
126                        st.subheader(body=":white_check_mark: Validação de Dados")
127
128                        final_description = str(index_description["descrição"])
129                        final_value = float(index_description["valor"])
130                        final_date = str(index_description["data"])
131                        final_category = str(index_description["categoria"])
132                        final_account = str(index_description["conta"])
133
134                        str_final_value = str(final_value)
135                        str_final_value = str_final_value.replace(".", ",")
136                        last_two_digits = str_final_value[-2:]
137                        if last_two_digits in decimal_values:
138                            str_final_value = str_final_value + "0"
139
140                        with st.subheader(body=":white_check_mark: Validação de Dados"):
141                            with st.expander(label="Dados", expanded=True):
142                                st.info(body="Descrição: {}".format(final_description))
143                                st.info(body="Valor: :heavy_dollar_sign: {}".format(str_final_value))
144                                st.info(body="Categoria: {}".format(final_category))
145                                st.info(body="Conta: {}".format(final_account))
146
147                    with col6:
148                        st.subheader(body=":pencil: Comprovante")
149                        with st.spinner(text="Aguarde..."):
150                            sleep(2.5)
151
152                        final_id = self.get_not_payed_expense_id(description=index_description["descrição"], value=index_description["valor"], date=index_description["data"], time=index_description["horario"], category=index_description["categoria"], account=index_description["conta"])
153
154                        self.update_not_payed_expenses(id=final_id, new_date=today)
155
156                        Receipts().generate_receipt(table="despesas", id=final_id, description=final_description, value=final_value, date=final_date, category=final_category, account=final_account)
157
158                        str_value = str(value)
159                        str_value = str_value.replace(".", ",")
160                        last_two_digits = str_value[-2:]
161                        if last_two_digits in decimal_values:
162                            str_value = str_value + "0"
163
164                        log_query = '''INSERT INTO financas.logs_atividades (usuario_log, tipo_log, conteudo_log) VALUES ( %s, %s, %s);'''
165                        log_values = (logged_user, "Registro", "Registrou uma despesa no valor de R$ {} associada a conta {}.".format(str_value, account))
166                        QueryExecutor().insert_query(log_query, log_values, "Log gravado.", "Erro ao gravar log:")
167
168                elif update_button and confirm_selection == False:
169                    with col5:
170                        st.subheader(body="")
171                        with st.spinner(text="Aguarde..."):
172                            sleep(2.5)
173                        with st.expander(label="Aviso", expanded=True):
174                            st.warning(body="Confirme os dados antes de prosseguir.")
175
176        elif len(expense_values[0]) == 0:
177
178            with col5:
179                st.info("Você não possui valores futuros a pagar aguardando confirmação.")

Classe que representa a confirmação de despesas ainda não pagas.

def get_not_payed_expense_id( self, description: str, value: float, date: str, time: str, category: str, account: str):
18    def get_not_payed_expense_id(self, description: str, value: float, date: str, time: str, category: str, account: str):
19        """
20        Realiza a consulta do id da despesa que ainda não foi paga.
21
22        Parameters
23        ----------
24        description : str
25            A descrição da despesa.
26        value : float
27            O valor da despesa.
28        date : str
29            A data da despesa.
30        time : str
31            O horário da despesa.
32        category : str
33            A categoria da despesa.
34        account : str
35            A conta na qual a despesa foi registrada.
36
37        Returns
38        -------
39        id : int
40            O ID da despesa não paga.
41        """
42
43        get_id_query = """SELECT id_despesa FROM despesas WHERE descricao = "{}" AND valor = {} AND data = "{}" AND horario = "{}" AND categoria = "{}" AND conta = "{}";""".format(description, value, date, time, category, account)
44        id = QueryExecutor().simple_consult_brute_query(get_id_query)
45        id = QueryExecutor().treat_simple_result(id, to_remove_list)
46        id = int(id)
47
48        return id

Realiza a consulta do id da despesa que ainda não foi paga.

Parameters
  • description (str): A descrição da despesa.
  • value (float): O valor da despesa.
  • date (str): A data da despesa.
  • time (str): O horário da despesa.
  • category (str): A categoria da despesa.
  • account (str): A conta na qual a despesa foi registrada.
Returns
  • id (int): O ID da despesa não paga.
def update_not_payed_expenses(self, id: int, new_date: str):
50    def update_not_payed_expenses(self, id: int, new_date: str):
51        """
52        Atualiza a despesa não paga para constar como paga.
53
54        Parameters
55        ----------
56        new_date : str
57            A nova data da despesa.
58        """
59
60        update_not_payed_query = """UPDATE despesas SET data = "{}", pago = "S" WHERE id_despesa = {};""".format(new_date, id)
61        QueryExecutor().update_table_unique_register(update_not_payed_query,"Despesa atualizada com sucesso!", "Erro ao atualizar receita:")

Atualiza a despesa não paga para constar como paga.

Parameters
  • new_date (str): A nova data da despesa.
def main_menu(self):
 63    def main_menu(self):
 64        """
 65        Exibe as despesas ainda não pagas.
 66        """
 67        user_name, user_document = Login().get_user_data(return_option="user_doc_name")
 68        logged_user, logged_user_password = Login().get_user_data(return_option="user_login_password")
 69
 70        col4, col5, col6 = st.columns(3)
 71
 72        expense_values = QueryExecutor().complex_compund_query(query=not_payed_expense_query, list_quantity=7, params=(user_name, user_document))
 73
 74        if len(expense_values[0]) >= 1:
 75
 76            with col4:
 77                st.subheader(body=":computer: Valores")
 78
 79                with st.expander(label="Dados", expanded=True):
 80
 81                    expense_id, description, value, date, time, category, account = (expense_values)
 82
 83                    time_list = []
 84
 85                    for i in range(0, len(time)):
 86                        aux_time = QueryExecutor().treat_simple_result(time[i], to_remove_list)
 87                        time_list.append(aux_time)
 88
 89                    loan_data_df = pd.DataFrame({"ID": expense_id, "Descrição": description, "Valor": value, "Data": date, "Horário": time_list, "Categoria": category, "Conta": account})
 90                    loan_data_df["Valor"] = loan_data_df["Valor"].apply(lambda x: f"R$ {x:.2f}".replace(".", ","))
 91                    loan_data_df["Data"] = pd.to_datetime(loan_data_df["Data"]).dt.strftime("%d/%m/%Y")
 92
 93                    st.dataframe(loan_data_df, hide_index=True,use_container_width=True)
 94
 95                    description_list = []
 96
 97                    for i in range(0, len(description)):
 98
 99                        index_description = {}
100                        str_value = str(value[i])
101                        str_date = str(date[i])
102                        str_date = datetime.strptime(str_date, "%Y-%m-%d")
103                        query_str_date = str_date.strftime("%Y-%m-%d")
104                        final_str_account = str(account[i])
105
106                        index_description.update({"descrição": description[i], "valor": str_value, "data": query_str_date, "horario": time[i], "categoria": category[i], "conta": final_str_account})
107
108                        formatted_data = str(index_description["data"])
109                        formatted_data = datetime.strptime(formatted_data, "%Y-%m-%d")
110                        formatted_data = formatted_data.strftime("%d/%m/%Y")
111
112                        formatted_description = str(index_description["descrição"]) + " - " + "R$ {}".format(str(index_description["valor"]).replace(".", ",")) + " - " + formatted_data + " - " + str(index_description["horario"]) + " - " + str(index_description["categoria"]) + " - " + str(index_description["conta"])
113                        description_list.append(formatted_description)
114
115                    selected_revenue = st.selectbox(label="Selecione a despesa", options=description_list)
116
117                    confirm_selection = st.checkbox(label="Confirmar seleção")
118
119                update_button = st.button(label=":floppy_disk: Confirmar pagamento")
120
121                if confirm_selection and update_button:
122                    with col5:
123                        with st.spinner(text="Aguarde..."):
124                            sleep(2.5)
125
126                        st.subheader(body=":white_check_mark: Validação de Dados")
127
128                        final_description = str(index_description["descrição"])
129                        final_value = float(index_description["valor"])
130                        final_date = str(index_description["data"])
131                        final_category = str(index_description["categoria"])
132                        final_account = str(index_description["conta"])
133
134                        str_final_value = str(final_value)
135                        str_final_value = str_final_value.replace(".", ",")
136                        last_two_digits = str_final_value[-2:]
137                        if last_two_digits in decimal_values:
138                            str_final_value = str_final_value + "0"
139
140                        with st.subheader(body=":white_check_mark: Validação de Dados"):
141                            with st.expander(label="Dados", expanded=True):
142                                st.info(body="Descrição: {}".format(final_description))
143                                st.info(body="Valor: :heavy_dollar_sign: {}".format(str_final_value))
144                                st.info(body="Categoria: {}".format(final_category))
145                                st.info(body="Conta: {}".format(final_account))
146
147                    with col6:
148                        st.subheader(body=":pencil: Comprovante")
149                        with st.spinner(text="Aguarde..."):
150                            sleep(2.5)
151
152                        final_id = self.get_not_payed_expense_id(description=index_description["descrição"], value=index_description["valor"], date=index_description["data"], time=index_description["horario"], category=index_description["categoria"], account=index_description["conta"])
153
154                        self.update_not_payed_expenses(id=final_id, new_date=today)
155
156                        Receipts().generate_receipt(table="despesas", id=final_id, description=final_description, value=final_value, date=final_date, category=final_category, account=final_account)
157
158                        str_value = str(value)
159                        str_value = str_value.replace(".", ",")
160                        last_two_digits = str_value[-2:]
161                        if last_two_digits in decimal_values:
162                            str_value = str_value + "0"
163
164                        log_query = '''INSERT INTO financas.logs_atividades (usuario_log, tipo_log, conteudo_log) VALUES ( %s, %s, %s);'''
165                        log_values = (logged_user, "Registro", "Registrou uma despesa no valor de R$ {} associada a conta {}.".format(str_value, account))
166                        QueryExecutor().insert_query(log_query, log_values, "Log gravado.", "Erro ao gravar log:")
167
168                elif update_button and confirm_selection == False:
169                    with col5:
170                        st.subheader(body="")
171                        with st.spinner(text="Aguarde..."):
172                            sleep(2.5)
173                        with st.expander(label="Aviso", expanded=True):
174                            st.warning(body="Confirme os dados antes de prosseguir.")
175
176        elif len(expense_values[0]) == 0:
177
178            with col5:
179                st.info("Você não possui valores futuros a pagar aguardando confirmação.")

Exibe as despesas ainda não pagas.