diff --git a/.github/workflows/testes.yml b/.github/workflows/testes.yml index 3d395fd..0c58ee2 100644 --- a/.github/workflows/testes.yml +++ b/.github/workflows/testes.yml @@ -19,8 +19,8 @@ jobs: - uses: actions/setup-python@v6 with: python-version: ${{ matrix.python }} - # Só o que o núcleo usa: a interface (Streamlit) não entra nos testes - - run: pip install pandas openpyxl xlrd thefuzz + # As mesmas versões do requirements.txt: o teste da tela usa o Streamlit + - run: pip install -r requirements.txt - run: python -m unittest discover -s tests -v - # A tela não roda no CI, mas precisa ao menos compilar em todas as versões + # A tela também precisa compilar em todas as versões - run: python -m py_compile unifydata.py nucleo.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 09c406c..71cdec2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,29 @@ # Changelog +## Unreleased + +### Closing +- The app now reads the *Total geral* line of each Linx report and + compares it with the sum of the people it read. The tape gets a + *Total geral no relatório* line, and a warning appears (also in the + printed report) when they differ. A report without that line is not + checked, and the app says so. + +### Code and tests +- Removed the unused `escolhas` parameter from `consolidar` and + `divergencia_repetido`; the namesake test now uses `fixar_linha`, the + path the app really takes. +- `parse_linx_files` also returns the *Total geral* of each report. +- New test that runs the screen in sample mode (Streamlit's `AppTest`) + and checks the final total. +- `requirements.txt` pins the tested versions; CI installs from it. + ## 1.1.0 (2026-10-13) ### Closing - The result opens with a reconciliation tape, like an adding-machine roll: each store's total in Linx (kept before any card is ignored), - their sum, what was ignored and what goes to payroll. The sum matches - the grand total of the Linx reports. + their sum, what was ignored and what goes to payroll. - Each step's number is part of its title. - On wide screens (1200 px or more) the column is wider and the company table sits beside the tape. @@ -18,8 +35,9 @@ ### Outputs - Files are named after the month of the due dates (`Fechamento_UnifyData_2026-09.xlsx`). -- In the sample mode, the Excel, the CSV and the report say the data is - made up, and the file names end in `_DEMO`. +- In the sample mode, the Excel and the report say the data is made up, + and the file names (Excel, CSV) end in `_DEMO`. The CSV itself carries + no notice. - The report and the Excel header use the brand teal instead of burgundy, and the report summary shows the same reconciliation as the tape. diff --git a/README.md b/README.md index dcd8887..8b23657 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,17 @@ arquivos de exemplo** (Try with sample files): made-up files, nothing is saved. Or try the [web version](https://alyssom-fernandes.github.io/UnifyData-Web/?demo=1) right now, in the browser, with nothing to install. +## Why two repositories + +One problem, two strategies for matching Linx to HR. They are not a +duplicate: each fits a different data situation. + +- **By code, in the [web version](https://github.com/alyssom-fernandes/UnifyData-Web):** + when Linx and HR share the employee code, the match is exact and + needs no review. +- **By name, here:** when there is no common code, the name is the only + link, so similar names are shown to a person to confirm. + [![Tests](https://github.com/alyssom-fernandes/UnifyData-Python/actions/workflows/testes.yml/badge.svg)](https://github.com/alyssom-fernandes/UnifyData-Python/actions/workflows/testes.yml) ![Python](https://img.shields.io/badge/Python-3.10+-3776ab?style=flat-square&logo=python&logoColor=white) ![Streamlit](https://img.shields.io/badge/Streamlit-1.57+-ff4b4b?style=flat-square&logo=streamlit&logoColor=white) @@ -153,14 +164,16 @@ the result and in the report. | Names | thefuzz (`token_sort_ratio`) for similarity | | Writing | openpyxl for the .xlsx; the CSV and the report are made by the app | | Fonts | Instrument Sans for the interface; JetBrains Mono for labels and the signature, hosted in the project (SIL OFL 1.1) | -| Tests | `unittest`, on every push (GitHub Actions) | +| Tests | `unittest` and Streamlit's `AppTest`, on every push (GitHub Actions) | Some decisions behind it: - **The rules live apart from the screen.** `nucleo.py` has pure functions for reading, matching, consolidating and writing the Excel and the CSV; `unifydata.py` only draws the screen and calls them. The - tests run the rules against the same sample files, without Streamlit. + tests run the rules against the same sample files, without Streamlit, + and one more test drives the screen in sample mode with Streamlit's + `AppTest` and checks the final total. - **Automatic only when the match is unambiguous.** A link is made alone only when the name is the same once accents, case and spaces are removed, and HR has a single spelling of it; everything else waits for @@ -169,6 +182,11 @@ Some decisions behind it: the consumption goes to the chosen row only, and the other rows stay at zero. Consumption that a CPF has already tied to one person stays with that person, whatever is chosen later for the name. +- **The tape checks itself against the report.** Each Linx report ends + with a *Total geral* line. The app reads it, compares it with the sum + of the people it read and shows a warning, with a *Total geral no + relatório* line on the tape, when they differ (a block the reader did + not recognize would otherwise drop out silently). - **Clicks are safe.** Every action is a callback that runs before the next redraw, so a double click on a button that already did its job does nothing. @@ -221,7 +239,7 @@ Iniciar_UnifyData.bat Windows launcher .streamlit/config.toml light and dark themes, fonts, toolbar, telemetry off assets/favicon.png the UnifyData mark static/fonts/ Instrument Sans and JetBrains Mono (woff2), with their licenses -tests/ tests for the rules, with the sample files +tests/ tests for the rules and for the screen in sample mode, with the sample files exemplos/ made-up files in the Linx and HR formats .github/workflows/ runs the tests on every push docs/telas/ images for this README (revisao.gif included) and the social preview (og.png) diff --git a/README.pt-BR.md b/README.pt-BR.md index 219043b..3ed46d3 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -24,6 +24,17 @@ arquivos de exemplo**: arquivos fictícios, nada é salvo. Ou experimente agora a [versão Web](https://alyssom-fernandes.github.io/UnifyData-Web/?demo=1), no navegador, sem instalar nada. +## Por que dois repositórios + +Um problema, duas estratégias para ligar o Linx ao RH. Não é duplicação: +cada uma serve a uma situação diferente dos dados. + +- **Por código, na [versão Web](https://github.com/alyssom-fernandes/UnifyData-Web):** + quando o Linx e o RH têm a matrícula em comum, o cruzamento é exato e + dispensa revisão. +- **Por nome, aqui:** quando não há código em comum, o nome é a única + ligação, então nomes parecidos vão para uma pessoa confirmar. + [![Testes](https://github.com/alyssom-fernandes/UnifyData-Python/actions/workflows/testes.yml/badge.svg)](https://github.com/alyssom-fernandes/UnifyData-Python/actions/workflows/testes.yml) ![Python](https://img.shields.io/badge/Python-3.10+-3776ab?style=flat-square&logo=python&logoColor=white) ![Streamlit](https://img.shields.io/badge/Streamlit-1.57+-ff4b4b?style=flat-square&logo=streamlit&logoColor=white) @@ -152,14 +163,16 @@ resultado e no relatório. | Nomes | thefuzz (`token_sort_ratio`) para a semelhança | | Escrita | openpyxl para o .xlsx; o CSV e o relatório são feitos pelo app | | Fontes | Instrument Sans na interface; JetBrains Mono em rótulos e na assinatura, hospedadas no projeto (SIL OFL 1.1) | -| Testes | `unittest`, a cada push (GitHub Actions) | +| Testes | `unittest` e o `AppTest` do Streamlit, a cada push (GitHub Actions) | Algumas decisões por trás: - **As regras ficam separadas da tela.** O `nucleo.py` tem funções puras para ler, cruzar, consolidar e escrever o Excel e o CSV; o `unifydata.py` só desenha a tela e chama essas funções. Os testes rodam - as regras com os mesmos arquivos de exemplo, sem o Streamlit. + as regras com os mesmos arquivos de exemplo, sem o Streamlit, e mais um + teste percorre a tela no modo de exemplo com o `AppTest` do Streamlit e + confere o total final. - **Automático só quando não há ambiguidade.** O vínculo sozinho só acontece quando o nome é o mesmo depois de tirar acentos, maiúsculas e espaços, e o RH tem uma única grafia dele; o resto espera um clique. @@ -167,6 +180,11 @@ Algumas decisões por trás: o consumo vai só para a linha escolhida, e as outras ficam zeradas. O consumo que um CPF já ligou a uma pessoa fica com ela, seja qual for a escolha feita depois para o nome. +- **A fita se confere com o relatório.** Cada relatório do Linx termina + com uma linha *Total geral*. O app a lê, compara com a soma das pessoas + que leu e mostra um aviso, com uma linha *Total geral no relatório* na + fita, quando diferem (um bloco que o leitor não reconhecesse sumiria + sem ninguém ver). - **Cliques seguros.** Cada ação é um callback que roda antes do próximo desenho da tela, então um clique duplo num botão que já fez o trabalho não faz nada. @@ -218,7 +236,7 @@ Iniciar_UnifyData.bat atalho para Windows .streamlit/config.toml temas claro e escuro, fontes, barra de ferramentas, telemetria desligada assets/favicon.png a marca do UnifyData static/fonts/ Instrument Sans e JetBrains Mono (woff2), com as licenças -tests/ testes das regras, com os arquivos de exemplo +tests/ testes das regras e da tela no modo de exemplo, com os arquivos de exemplo exemplos/ arquivos fictícios nos formatos do Linx e do RH .github/workflows/ roda os testes a cada push docs/telas/ imagens deste README (com o revisao.gif) e da prévia para redes (og.png) diff --git a/nucleo.py b/nucleo.py index 3ecd289..d8ee4f7 100644 --- a/nucleo.py +++ b/nucleo.py @@ -181,8 +181,9 @@ def parse_hr_files(hr_files): def parse_linx_files(linx_files): """ Lê relatórios CSV do Linx (Pendências por Responsável). - Retorna (DataFrame com Nome, Vencido, Total e Origem, avisos, períodos de vencimento) — - capturando os DOIS valores da linha Total separadamente. + Retorna (DataFrame com Nome, Vencido, Total e Origem, avisos, períodos de vencimento, "Total geral" de cada + relatório) — capturando os DOIS valores da linha Total separadamente. O "Total geral" é o valor que o próprio + Linx imprime no fim do relatório, guardado por origem para a conferência comparar com a soma dos responsáveis. """ def to_float(s): try: @@ -190,7 +191,7 @@ def to_float(s): except (ValueError, AttributeError): return 0.0 - records, avisos, periodos = [], [], [] + records, avisos, periodos, declarados = [], [], [], {} for file in linx_files: try: content = decodificar(file.getvalue()) @@ -209,10 +210,15 @@ def to_float(s): if m: current_nome = ' '.join(m.group(1).strip().upper().split()) + if re.match(r'total\s+geral', line.strip(), re.IGNORECASE): + # O Total geral vem depois do último responsável: é o valor do Linx para conferir a soma lida + campos = [p.strip() for p in line.split(';') if p.strip()] + if len(campos) >= 2: + declarados[origem] = declarados.get(origem, 0.0) + to_float(campos[2] if len(campos) >= 3 else campos[1]) + current_nome = None + continue + if current_nome and line.strip().lower().startswith('total'): - if re.match(r'total\s+geral', line.strip(), re.IGNORECASE): - current_nome = None - continue campos = [p.strip() for p in line.split(';')] # "Total;;18,50": sem vencido. Nos demais casos, campos vazios são ignorados. parts = ['Total', '0', campos[2]] if len(campos) > 2 and not campos[1] and campos[2] else [p for p in campos if p] @@ -231,7 +237,7 @@ def to_float(s): df = pd.DataFrame(records) if records else pd.DataFrame(columns=['Nome', 'Vencido', 'Total', 'Origem']) # Linha do RH dona do consumo: SEM_LINHA enquanto o cruzamento é pelo nome; o índice da linha quando o CPF já decidiu df['Linha'] = SEM_LINHA - return df, avisos, periodos + return df, avisos, periodos, {o: round(v, 2) for o, v in declarados.items()} # ────────────────────────────────────────────── @@ -259,10 +265,10 @@ def fixar_linha(linx_df, nome, linha): linx_df.loc[alvo, 'Linha'] = int(linha) -def divergencia_repetido(hr_df, linx_df, nome, escolhas): +def divergencia_repetido(hr_df, linx_df, nome): """Nome do Linx que aparece em mais de uma linha do RH (homônimos ou a mesma pessoa em duas empresas).""" linhas = hr_df[hr_df['Nome'] == nome] - if len(linhas) < 2 or nome in escolhas: + if len(linhas) < 2: return None consumo = linx_df[pelo_nome(linx_df, nome)] if consumo.empty: @@ -294,7 +300,7 @@ def encontrar_divergencias(hr_df, linx_df): divergencias = [] for nome in linx_df['Nome'].unique(): if nome in hr_names: - repetido = divergencia_repetido(hr_df, linx_df, nome, {}) + repetido = divergencia_repetido(hr_df, linx_df, nome) if repetido: divergencias.append(repetido) continue @@ -310,7 +316,7 @@ def encontrar_divergencias(hr_df, linx_df): return divergencias, ligados -def consolidar(hr_df, linx_df, origens, escolhas): +def consolidar(hr_df, linx_df, origens): """Uma linha por funcionário do RH, com vencido e total por origem e o Total Desconto.""" vazio = linx_df is None or linx_df.empty por_nome = pd.DataFrame() if vazio else linx_df[linhas_fixas(linx_df) == SEM_LINHA] @@ -332,10 +338,7 @@ def make_pivot(df, chave, col): if col not in merged: merged[col] = 0.0 merged[valores] = merged[valores].fillna(0.0) - # Nome repetido no RH: o consumo pelo nome fica só na linha escolhida na revisão (sem descontar duas vezes) - for nome, linha in escolhas.items(): - merged.loc[(merged['Nome'] == nome) & (merged['_linha'] != linha), valores] = 0.0 - # Consumo cuja pessoa o CPF já definiu: soma direto na linha certa, sem passar pelo nome + # Consumo cuja pessoa já foi definida (pelo CPF ou pela escolha na revisão): soma direto na linha certa, sem passar pelo nome if not por_linha.empty: for prefixo in ('Vencido', 'Total'): extra = make_pivot(por_linha, 'Linha', prefixo).set_index('Linha') @@ -346,21 +349,35 @@ def make_pivot(df, chave, col): def totais_por_loja(linx_df): - """Total de cada relatório do Linx (o "Total geral" dele), guardado antes de qualquer divergência ser ignorada.""" + """Soma dos responsáveis lidos em cada relatório do Linx, guardada antes de qualquer divergência ser ignorada.""" if linx_df is None or linx_df.empty: return {} return {o: round(float(v), 2) for o, v in linx_df.groupby('Origem', sort=False)['Total'].sum().items()} -def conferencia(totais_linx, ignorados): +def divergencias_do_total_geral(totais_linx, declarados): + """ + Relatórios cuja soma dos responsáveis lidos difere do "Total geral" impresso pelo Linx: [(origem, lido, no relatório)]. + Relatório sem a linha "Total geral" não entra: não há com o que comparar. + """ + return [(o, lido, declarados[o]) for o, lido in totais_linx.items() + if o in declarados and abs(round(lido - declarados[o], 2)) >= 0.01] + + +def conferencia(totais_linx, ignorados, declarados=None): """ A conta do fechamento como numa fita de calculadora: o total de cada loja no Linx, a soma, o que foi - ignorado e o que vai para a folha (que precisa bater com o total da planilha). + ignorado e o que vai para a folha (que precisa bater com o total da planilha). Com os "Total geral" lidos dos + relatórios, confere também a soma lida contra o que o Linx imprimiu e lista as divergências. """ + declarados = declarados or {} consumo = round(sum(totais_linx.values()), 2) ignorado = round(sum(x['valor'] for x in ignorados), 2) + completo = bool(totais_linx) and all(o in declarados for o in totais_linx) return {'por_origem': list(totais_linx.items()), 'consumo': consumo, 'ignorado': ignorado, - 'a_descontar': round(consumo - ignorado, 2)} + 'a_descontar': round(consumo - ignorado, 2), + 'no_relatorio': round(sum(declarados[o] for o in totais_linx), 2) if completo else None, + 'divergentes': divergencias_do_total_geral(totais_linx, declarados)} def mes_do_periodo(periodos): diff --git a/requirements.txt b/requirements.txt index a70f153..23a85f2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,8 @@ -streamlit>=1.57 -pandas>=2.0 -openpyxl>=3.1 -xlrd>=2.0 -thefuzz>=0.20 +# Versões testadas (as instaladas na máquina onde os testes rodam). +# O pandas 3 exige Python 3.11 ou mais novo; no 3.10 vale a linha 2.x. +streamlit==1.57.0 +pandas==3.0.3; python_version >= "3.11" +pandas>=2.0,<3; python_version < "3.11" +openpyxl==3.1.5 +xlrd==2.0.2 +thefuzz==0.22.1 diff --git a/tests/test_nucleo.py b/tests/test_nucleo.py index 9df42cd..be4a8f2 100644 --- a/tests/test_nucleo.py +++ b/tests/test_nucleo.py @@ -44,7 +44,7 @@ def test_planilhas_do_rh_de_exemplo(self): self.assertTrue((hr['CPF'].str.len() == 11).all()) def test_relatorios_do_linx_de_exemplo(self): - linx, avisos, periodos = N.parse_linx_files(linx_exemplo()) + linx, avisos, periodos, _ = N.parse_linx_files(linx_exemplo()) self.assertEqual(avisos, []) self.assertEqual(len(linx), 34) self.assertEqual(periodos, ['01/09/2026 a 30/09/2026']) @@ -55,9 +55,41 @@ def test_linha_de_total_sem_vencido_e_com_milhar(self): texto = ('Conta: 1 Responsável: 1 - ANA;;\r\nTotal;;18,50;;\r\n' 'Conta: 1 Responsável: 2 - BRUNO;;\r\nTotal;1.234,56;2.000,10;;\r\n' 'Total geral;1.234,56;2.018,60;;\r\n').encode('cp1252') - linx, _, _ = N.parse_linx_files([Arquivo('LOJA.csv', texto)]) + linx, _, _, _ = N.parse_linx_files([Arquivo('LOJA.csv', texto)]) self.assertEqual(linx[['Nome', 'Vencido', 'Total']].values.tolist(), [['ANA', 0.0, 18.5], ['BRUNO', 1234.56, 2000.1]]) + def test_total_geral_do_relatorio_e_lido_por_origem(self): + _, _, _, declarados = N.parse_linx_files(linx_exemplo()) + self.assertEqual(declarados, {'LOJA': 1385.6, 'RESTAURANTE': 1296.2}) + + def test_total_geral_que_bate_com_a_soma_dos_responsaveis(self): + texto = ('Conta: 1 Responsável: 1 - ANA;;\r\nTotal;;18,50;;\r\n' + 'Conta: 1 Responsável: 2 - BRUNO;;\r\nTotal;1.234,56;2.000,10;;\r\n' + 'Total geral;1.234,56;2.018,60;;\r\n').encode('cp1252') + linx, _, _, declarados = N.parse_linx_files([Arquivo('LOJA.csv', texto)]) + c = N.conferencia(N.totais_por_loja(linx), [], declarados) + self.assertEqual(declarados, {'LOJA': 2018.6}) + self.assertEqual((c['consumo'], c['no_relatorio'], c['divergentes']), (2018.6, 2018.6, [])) + + def test_total_geral_que_nao_bate_vira_divergencia(self): + # O bloco do BRUNO não traz a linha "Total": o parser não o reconhece e o valor some da soma + texto = ('Conta: 1 Responsável: 1 - ANA;;\r\nTotal;;18,50;;\r\n' + 'Conta: 1 Responsável: 2 - BRUNO;;\r\nSubtotal;1.234,56;2.000,10;;\r\n' + 'Total geral;1.234,56;2.018,60;;\r\n').encode('cp1252') + linx, _, _, declarados = N.parse_linx_files([Arquivo('LOJA.csv', texto)]) + c = N.conferencia(N.totais_por_loja(linx), [], declarados) + self.assertEqual(c['consumo'], 18.5) + self.assertEqual(c['no_relatorio'], 2018.6) + self.assertEqual(c['divergentes'], [('LOJA', 18.5, 2018.6)]) + + def test_relatorio_sem_total_geral_nao_e_conferido(self): + texto = 'Conta: 1 Responsável: 1 - ANA;;\r\nTotal;;18,50;;\r\n'.encode('cp1252') + linx, _, _, declarados = N.parse_linx_files([Arquivo('LOJA.csv', texto)]) + c = N.conferencia(N.totais_por_loja(linx), [], declarados) + self.assertEqual(declarados, {}) + self.assertIsNone(c['no_relatorio']) + self.assertEqual(c['divergentes'], []) + def test_csv_do_rh_com_titulo_aspas_e_rodape(self): texto = ('RELAÇÃO DE FUNCIONÁRIOS\nNome;CPF;Endereço\n"SILVA, JOÃO";123.456.789-01;"Rua A, 1"\n' 'TOTAL: 1;;\n').encode('utf-8') @@ -76,7 +108,7 @@ def test_planilha_ilegivel_fica_de_fora_com_aviso_claro(self): class Cruzamento(unittest.TestCase): def test_exemplos_um_ligado_por_acento_e_cinco_divergencias(self): hr, _ = N.parse_hr_files(rh_exemplo()) - linx, _, _ = N.parse_linx_files(linx_exemplo()) + linx, _, _, _ = N.parse_linx_files(linx_exemplo()) divergencias, ligados = N.encontrar_divergencias(hr, linx) self.assertEqual(ligados, 1) self.assertIn('DÉBORA LIMA FONSECA', set(linx['Nome']), 'DEBORA (Linx) vira DÉBORA (RH)') @@ -87,7 +119,7 @@ def test_exemplos_um_ligado_por_acento_e_cinco_divergencias(self): def test_conferencia_total_do_linx_menos_ignorado_e_o_total_da_planilha(self): # O fluxo da demonstração: aprova o nome parecido e ignora as quatro pessoas fora do RH hr, _ = N.parse_hr_files(rh_exemplo()) - linx, _, periodos = N.parse_linx_files(linx_exemplo()) + linx, _, periodos, declarados = N.parse_linx_files(linx_exemplo()) totais = N.totais_por_loja(linx) divergencias, _ = N.encontrar_divergencias(hr, linx) ignorados = [] @@ -97,9 +129,11 @@ def test_conferencia_total_do_linx_menos_ignorado_e_o_total_da_planilha(self): else: ignorados.append({'nome': d['Linx_Nome'], 'valor': d['Valor']}) linx = linx[~N.pelo_nome(linx, d['Linx_Nome'])] - total = float(N.consolidar(hr, linx, list(totais), {})['Total Desconto'].sum()) - c = N.conferencia(totais, ignorados) + total = float(N.consolidar(hr, linx, list(totais))['Total Desconto'].sum()) + c = N.conferencia(totais, ignorados, declarados) self.assertEqual([o for o, _ in c['por_origem']], ['LOJA', 'RESTAURANTE']) + self.assertEqual(c['no_relatorio'], c['consumo'], 'a soma lida fecha com o Total geral impresso pelo Linx') + self.assertEqual(c['divergentes'], []) self.assertEqual(c['a_descontar'], round(total, 2), 'total do Linx − ignorado = total da planilha') self.assertEqual(N.mes_do_periodo(periodos), 'setembro de 2026') self.assertEqual(N.mes_do_periodo(['16/09/2026 a 15/10/2026']), '16/09/2026 a 15/10/2026') @@ -119,9 +153,12 @@ def test_homonimo_vira_revisao_e_o_desconto_nao_dobra(self): self.assertEqual(divergencias[0]['Tipo'], 'Repetido') self.assertEqual([r for _, r in divergencias[0]['Opcoes']], ['Posto · CPF 111.111.111-11', 'Hotel · CPF 222.222.222-22']) - sem_escolha = N.consolidar(hr, linx, ['LOJA'], {}) + sem_escolha = N.consolidar(hr, linx, ['LOJA']) self.assertEqual(sem_escolha['Total Desconto'].sum(), 20.0, 'sem a revisão, o homônimo pagaria duas vezes') - com_escolha = N.consolidar(hr, linx, ['LOJA'], {'ANA': 0}) + # Caminho real do app: a escolha na revisão prende o consumo à linha escolhida (fixar_linha) + N.fixar_linha(linx, 'ANA', 0) + self.assertIsNone(N.divergencia_repetido(hr, linx, 'ANA'), 'escolhido, o cartão some') + com_escolha = N.consolidar(hr, linx, ['LOJA']) self.assertEqual(com_escolha['Total Desconto'].tolist(), [10.0, 0.0]) def test_cpf_fixa_a_linha_e_a_escolha_do_homonimo_nao_leva_junto(self): @@ -131,17 +168,17 @@ def test_cpf_fixa_a_linha_e_a_escolha_do_homonimo_nao_leva_junto(self): linx = pd.DataFrame([{'Nome': 'JOAO PEDRO SANTOS', 'Vencido': 0.0, 'Total': 80.0, 'Origem': 'LOJA'}, {'Nome': 'MARIA', 'Vencido': 0.0, 'Total': 20.0, 'Origem': 'LOJA'}]) N.fixar_linha(linx, 'MARIA', 0) - repetido = N.divergencia_repetido(hr, linx, 'JOAO PEDRO SANTOS', {}) + repetido = N.divergencia_repetido(hr, linx, 'JOAO PEDRO SANTOS') self.assertEqual(repetido['Valor'], 80.0, 'o consumo já fixado pelo CPF não entra no cartão do homônimo') N.fixar_linha(linx, 'JOAO PEDRO SANTOS', 1) - self.assertIsNone(N.divergencia_repetido(hr, linx, 'JOAO PEDRO SANTOS', {})) - merged = N.consolidar(hr, linx, ['LOJA'], {}) + self.assertIsNone(N.divergencia_repetido(hr, linx, 'JOAO PEDRO SANTOS')) + merged = N.consolidar(hr, linx, ['LOJA']) self.assertEqual(merged[['Empresa', 'Total Desconto']].values.tolist(), [['Alfa', 20.0], ['Beta', 80.0]]) def test_consolidar_inclui_quem_nao_consumiu(self): hr = pd.DataFrame([{'Nome': 'ANA', 'CPF': '', 'Empresa': 'Posto'}, {'Nome': 'BRUNO', 'CPF': '', 'Empresa': 'Posto'}]) linx = pd.DataFrame([{'Nome': 'ANA', 'Vencido': 2.0, 'Total': 3.0, 'Origem': 'LOJA'}]) - merged = N.consolidar(hr, linx, ['LOJA', 'RESTAURANTE'], {}) + merged = N.consolidar(hr, linx, ['LOJA', 'RESTAURANTE']) self.assertEqual(merged[['Nome', 'Vencido__LOJA', 'Total__RESTAURANTE', 'Total Desconto']].values.tolist(), [['ANA', 2.0, 0.0, 3.0], ['BRUNO', 0.0, 0.0, 0.0]]) @@ -152,7 +189,7 @@ def setUp(self): {'Nome': 'ÂNGELA', 'CPF': '', 'Empresa': 'Obras: Sede'}, {'Nome': 'ZÉLIA', 'CPF': '', 'Empresa': 'History'}]) linx = pd.DataFrame([{'Nome': '=HYPERLINK("x")', 'Vencido': 1.5, 'Total': 2.0, 'Origem': 'LOJA'}]) - self.merged = N.consolidar(hr, linx, ['LOJA'], {}) + self.merged = N.consolidar(hr, linx, ['LOJA']) def test_excel_abas_validas_rodape_e_nome_como_texto(self): wb = load_workbook(N.gerar_excel(self.merged, ['LOJA'])) @@ -183,7 +220,7 @@ def test_nome_do_arquivo_pelo_mes_dos_vencimentos(self): self.assertEqual(N.nome_do_arquivo(['16/09/2026 a 15/10/2026'], hoje=hoje), 'Fechamento_UnifyData_2026-09_a_2026-10') self.assertEqual(N.nome_do_arquivo([], hoje=hoje), 'Fechamento_UnifyData_2026-10-13', 'sem período, vale a data de hoje') self.assertEqual(N.nome_do_arquivo(['01/09/2026 a 30/09/2026'], demo=True, hoje=hoje), 'Fechamento_UnifyData_2026-09_DEMO') - _, _, periodos = N.parse_linx_files(linx_exemplo()) + _, _, periodos, _ = N.parse_linx_files(linx_exemplo()) self.assertEqual(N.nome_do_arquivo(periodos, hoje=hoje), 'Fechamento_UnifyData_2026-09') def test_csv_para_o_excel_brasileiro(self): diff --git a/tests/test_tela.py b/tests/test_tela.py new file mode 100644 index 0000000..7fba62e --- /dev/null +++ b/tests/test_tela.py @@ -0,0 +1,51 @@ +"""Teste da tela (unifydata.py) em modo exemplo, com o AppTest do Streamlit: sem navegador e sem enviar arquivo.""" +import re +import unittest +from pathlib import Path + +from streamlit.testing.v1 import AppTest + +TELA = Path(__file__).resolve().parents[1] / 'unifydata.py' + + +def abrir_demo(): + at = AppTest.from_file(str(TELA), default_timeout=60) + at.query_params['demo'] = '1' + return at.run() + + +class Demonstracao(unittest.TestCase): + def test_fluxo_completo_fecha_com_o_total_do_linx_menos_o_ignorado(self): + at = abrir_demo() + self.assertFalse(at.exception) + rotulos = [b.label for b in at.button] + self.assertEqual(rotulos.count('Aprovar vínculo'), 1, 'uma pessoa com nome parecido') + self.assertEqual(rotulos.count('Ignorar'), 5, 'o nome parecido e as quatro fora do RH, cada um com o seu Ignorar') + + # Aprova o nome parecido e ignora as quatro pessoas que não estão no RH, como no roteiro da demonstração + at.button[[b.label for b in at.button].index('Aprovar vínculo')].click().run() + while any(b.label == 'Ignorar' for b in at.button): + next(b for b in at.button if b.label == 'Ignorar').click().run() + self.assertFalse(at.exception) + + texto = ' '.join(m.value for m in at.markdown) + self.assertIn('Conferência com o Linx', texto) + self.assertIn('Total geral no relatório', texto, 'a fita mostra o Total geral lido do relatório') + self.assertEqual(re.findall(r'
A descontar
([^<]+)
', texto), ['R$ 2.159,00']) + self.assertEqual(len(at.warning), 0, 'o exemplo fecha com o Total geral: nenhum aviso de divergência') + + def test_total_geral_diferente_mostra_aviso_e_marca_a_fita(self): + at = abrir_demo() + at.button[[b.label for b in at.button].index('Aprovar vínculo')].click().run() + while any(b.label == 'Ignorar' for b in at.button): + next(b for b in at.button if b.label == 'Ignorar').click().run() + # Como se o relatório do Linx trouxesse mais 100,00 do que a leitura somou + at.session_state['totais_relatorio'] = {**at.session_state['totais_relatorio'], 'LOJA': 1485.60} + at.run() + self.assertEqual(len(at.warning), 1) + self.assertIn('não fecha com o Total geral', at.warning[0].value) + self.assertIn('ud-fita-diverge', ' '.join(m.value for m in at.markdown)) + + +if __name__ == '__main__': + unittest.main() diff --git a/unifydata.py b/unifydata.py index 9c5b263..2423973 100644 --- a/unifydata.py +++ b/unifydata.py @@ -121,6 +121,8 @@ .ud-fita .ud-fita-soma { margin-top: 6px; padding-top: 8px; border-top: 1px solid var(--ud-borda-2); } .ud-fita .ud-fita-soma dt span, .ud-fita .ud-fita-soma dd { font-weight: 700; } .ud-fita .ud-fita-menos dd { color: var(--ud-atencao); } + .ud-fita .ud-fita-confere dt span, .ud-fita .ud-fita-confere dd { color: var(--ud-texto-3); font-size: 12.5px; } + .ud-fita .ud-fita-diverge dd { color: var(--ud-atencao); font-weight: 700; } .ud-fita .ud-fita-total { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 2px 12px; margin-top: 10px; padding-top: 10px; border-top: 3px double var(--ud-texto-3); color: var(--ud-acento); } .ud-fita .ud-fita-total dt { margin: 0; font: 600 14px/1.3 'Instrument Sans', sans-serif; } @@ -217,11 +219,11 @@ 'origens': [], 'periodos': [], 'totais_linx': {}, + 'totais_relatorio': {}, 'avisos': [], 'ignorados': [], 'ligados_auto': 0, 'erros_div': {}, - 'escolhas': {}, 'demo': False, 'erro_envio': None, 'rodada': 0, @@ -240,7 +242,7 @@ def __init__(self, caminho): def processar(hr_files, linx_files): hr_df, avisos_rh = parse_hr_files(hr_files) - linx_df, avisos_linx, periodos = parse_linx_files(linx_files) + linx_df, avisos_linx, periodos, totais_relatorio = parse_linx_files(linx_files) if hr_df.empty: st.session_state.erro_envio = ('Não consegui tirar funcionários das planilhas do RH. Confira se elas têm as colunas **Nome** e **CPF**.', avisos_rh) return @@ -251,6 +253,7 @@ def processar(hr_files, linx_files): st.session_state.update( hr_df=hr_df, linx_df=linx_df, origens=list(dict.fromkeys(linx_df['Origem'])), periodos=periodos, totais_linx=totais_por_loja(linx_df), # antes de qualquer divergência ser ignorada: é o que a fita confere + totais_relatorio=totais_relatorio, # o "Total geral" que o próprio Linx imprimiu, para conferir a soma lida divergences=divergencias, avisos=avisos_rh + avisos_linx, ligados_auto=ligados, erro_envio=None, processing_done=True, ) @@ -315,7 +318,7 @@ def _limpar_erro(div_id): def _atualizar_repetido(nome_rh): """Nome que se repete no RH vira cartão para escolher a linha; se o cartão já existe, o valor dele é refeito.""" - nova = divergencia_repetido(st.session_state.hr_df, st.session_state.linx_df, nome_rh, st.session_state.escolhas) + nova = divergencia_repetido(st.session_state.hr_df, st.session_state.linx_df, nome_rh) if not nova: return existente = next((d for d in st.session_state.divergences if d['id'] == nova['id']), None) @@ -552,7 +555,7 @@ def campos_cpf_empresa(i, empresas, rotulo_cpf): # Interface: Download # ────────────────────────────────────────────── else: - merged = consolidar(st.session_state.hr_df, st.session_state.linx_df, st.session_state.origens, st.session_state.escolhas) + merged = consolidar(st.session_state.hr_df, st.session_state.linx_df, st.session_state.origens) origens = st.session_state.origens periodo = '; '.join(st.session_state.periodos) com_consumo = merged[merged['Total Desconto'] > 0] @@ -579,8 +582,17 @@ def campos_cpf_empresa(i, empresas, rotulo_cpf): f'Consumos de {escape(lista_por_extenso(origens))}{f", vencimentos de {escape(periodo)}" if periodo else ""}, ' 'cruzados com as planilhas do RH.') + # A soma dos responsáveis lidos tem de fechar com o "Total geral" do relatório; se não fecha, falta consumo na leitura + conf = conferencia(st.session_state.totais_linx, ign, st.session_state.totais_relatorio) + if conf['divergentes']: + detalhe = '; '.join(f'{escape(o)}: lido {brl(lido)}, relatório {brl(rel)}' for o, lido, rel in conf['divergentes']) + st.warning(f'**A soma lida não fecha com o Total geral do relatório do Linx** ({detalhe}). ' + 'Algum responsável pode não ter sido reconhecido: confira o arquivo antes de usar a planilha.', + icon=':material/warning:') + elif conf['no_relatorio'] is None: + st.caption('Algum relatório não traz a linha "Total geral", então a soma lida não pôde ser conferida com ele.') + # Fita de conferência: o total de cada loja no Linx (+), a soma (=), o ignorado (−) e o que vai para a folha - conf = conferencia(st.session_state.totais_linx, ign) numero = lambda v: brl(v)[3:] # na fita, só o número; o R$ fica no total linha_fita = lambda rotulo, valor, op, classe='': ( f'
{escape(rotulo)}
' @@ -592,6 +604,9 @@ def campos_cpf_empresa(i, empresas, rotulo_cpf): + (f'

Vencimentos de {escape(mes)}

' if mes else '') + '
' + ''.join(linha_fita(o, numero(v), '+') for o, v in conf['por_origem']) + linha_fita('Total no Linx', numero(conf['consumo']), '=', ' ud-fita-soma') + + (linha_fita('Total geral no relatório', numero(conf['no_relatorio']), '', + ' ud-fita-diverge' if conf['divergentes'] else ' ud-fita-confere') + if conf['no_relatorio'] is not None else '') + linha_fita(f'Ignorado ({n_ign} {"pessoa" if n_ign == 1 else "pessoas"})' if n_ign else 'Ignorado', f'−{numero(conf["ignorado"])}', '', ' ud-fita-menos') + f'
A descontar
{brl(total)}
' @@ -648,6 +663,8 @@ def tabela_relatorio(emp_df): # Demonstração: aviso no topo e marca-d'água em todas as páginas + (f'

{AVISO_DEMO}

' if st.session_state.demo else '') + + (f'

Atenção: a soma lida não fecha com o Total geral do relatório do Linx ({detalhe}).

' + if conf['divergentes'] else '') + f'
Com consumo{len(com_consumo)}
' f'
Empresas{len(grupos)}
Total no Linx{brl(conf["consumo"])}
' f'
Ignorado{brl(conf["ignorado"])}
' @@ -769,7 +786,7 @@ def passo(numero, titulo, resumo, estado, atual): if n_div: resumo_planilha = 'Depois das divergências' else: - total_lateral = float(consolidar(ss.hr_df, ss.linx_df, ss.origens, ss.escolhas)['Total Desconto'].sum()) + total_lateral = float(consolidar(ss.hr_df, ss.linx_df, ss.origens)['Total Desconto'].sum()) resumo_planilha = brl(total_lateral) if total_lateral else 'Nada para descontar' else: resumo_rh = f"{n_rh} {'planilha' if n_rh == 1 else 'planilhas'}" if n_rh else 'Nenhuma planilha'