Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/testes.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
26 changes: 22 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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.

Expand Down
24 changes: 21 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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)
Expand Down
24 changes: 21 additions & 3 deletions README.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -152,21 +163,28 @@ 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.
- **Homônimos protegidos.** Quando um nome aparece mais de uma vez no RH,
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.
Expand Down Expand Up @@ -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)
Expand Down
55 changes: 36 additions & 19 deletions nucleo.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,16 +181,17 @@ 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:
return float(re.sub(r'[R$\s]', '', s).replace('.', '').replace(',', '.'))
except (ValueError, AttributeError):
return 0.0

records, avisos, periodos = [], [], []
records, avisos, periodos, declarados = [], [], [], {}
for file in linx_files:
try:
content = decodificar(file.getvalue())
Expand All @@ -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]
Expand All @@ -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()}


# ──────────────────────────────────────────────
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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]
Expand All @@ -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')
Expand All @@ -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):
Expand Down
13 changes: 8 additions & 5 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading