Spaces:
Running
Running
Andre commited on
Commit ·
61fee22
1
Parent(s): a6f0fd5
deploy: snapshot d63a0d1 -- accruals da Revenue sobre a Contabilidade + accruals puros por regra (v1.3.76)
Browse filesFiles changed (41)
- .dockerignore-5
- Dockerfile-4
- backend/alembic/versions/a1c5e7b93d20_customer_category.pyDeleted-35
- backend/app_version.py+1-1
- backend/backup.py-81
- backend/etl_package.pyDeleted-144
- backend/models.py-6
- backend/release_notes.py-88
- backend/routers/admin.py+6-21
- backend/routers/dashboard.py+1-121
- backend/routers/etl_sync.py+3-101
- backend/routers/exports.py+6-39
- backend/routers/imports.py+27-113
- backend/routers/invoice_lines.py+7-40
- backend/routers/invoices.py+9-37
- backend/routers/management_dashboard.py+2-3
- backend/routers/procurement.py+3-4
- backend/routers/sales_insights.py+7-13
- backend/schemas.py-2
- backend/tests/test_customer_abc.pyDeleted-150
- backend/tests/test_etl_package.pyDeleted-106
- backend/tests/test_management_dashboard.py+6-8
- backend/tests/test_portable_snapshot.pyDeleted-137
- backend/tests/test_procurement.py+7-9
- backend/tests/test_sales_insights.py+18-24
- backend/tests/test_synthetic_rows.py-135
- backend/tests/test_translation.py+2-10
- docs/gateway_visma_pipeline_reference.md-1
- etl/README.md-38
- etl/force_sync_agent.py+5-214
- etl/tests/test_agent_self_update.pyDeleted-138
- etl/visma_unified_extractor.py+2-48
- frontend/src/app/admin/page.tsx+1-30
- frontend/src/app/page.tsx-7
- frontend/src/components/analytics/CustomerAnalytics.tsx+194-243
- frontend/src/components/analytics/DetailDrawer.tsx+5-4
- frontend/src/components/analytics/FreightDashboard.tsx+2-16
- frontend/src/components/analytics/InvoiceDetailDrawer.tsx+5-48
- frontend/src/components/analytics/InvoiceLinesTable.tsx+3-29
- frontend/src/components/analytics/InvoicesTable.tsx-11
- frontend/src/components/analytics/SalesInsights.tsx+2-13
7 unmodified lines891011121314157 unmodified lines.git.claude**/.npmrcetl/outputetl/logsetl/.depsetl/testsetl/tools39 unmodified lines4041424344454643444539 unmodified linesCOPY --chown=user:user backend/requirements.txt backend/RUN pip install --no-cache-dir -r backend/requirements.txtCOPY --chown=user:user backend/ backend/# The Visma-side ETL scripts ride in the image so the backend can hand them# to the on-prem agent (self-update, see backend/etl_package.py). They are# never executed here — the ADK DLL only exists on the Visma server.COPY --chown=user:user etl/ etl/
# Frontend (pre-built)COPY --chown=user:user --from=fe-builder /app/.next frontend/.next1234567891011121314151617181920212223242526272829303132333435"""customers.category_code / category_name (Visma Kundkategori)
Revision ID: a1c5e7b93d20Revises: d4e8b2f61c07Create Date: 2026-09-08
Adds the Visma customer category (ADK_CUSTOMER_CATEGORY, field 26, plus thelabel from ADK_DB_CODE_OF_CUSTOMER_CATEGORY) to the customers table. Thecategory groups the individual stores of a chain (ICA, Varner, ApoteketHjärtat, ...) into the commercial account finance actually negotiates with,which is the level the ABC customer classification is computed on.Nullable: rows imported from bundles without the columns stay NULL."""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
revision: str = 'a1c5e7b93d20'down_revision: Union[str, None] = 'd4e8b2f61c07'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.add_column('customers', sa.Column('category_code', sa.String(), nullable=True)) op.add_column('customers', sa.Column('category_name', sa.String(), nullable=True)) op.create_index('ix_customers_category_code', 'customers', ['category_code'])
def downgrade() -> None: op.drop_index('ix_customers_category_code', table_name='customers') op.drop_column('customers', 'category_name') op.drop_column('customers', 'category_code')16 unmodified lines17181920202116 unmodified linesread); the constant below is the deploy-time source that seeds the DB."""
APP_VERSION = "1.3.75"APP_VERSION = "1.3.69"APP_BUILT_AT = "2026-09-08" # bump alongside APP_VERSION at release time90 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317490 unmodified lines logger.info("Pruned old backup %s.", old.name) except OSError as e: logger.warning("Failed to prune %s: %s", old.name, e)
# ── Portable snapshot (works on Postgres too) ────────────────────────────────# run_backup() above is the nightly job and is SQLite-only by design: it uses# sqlite3's online-backup API on the live file. Production runs on Postgres,# where that path returns None — which left /api/admin/backup/download# answering 503 for the entire life of the Postgres deployment.## This builds the same thing the other way round: a fresh SQLite file with the# application's own schema, filled by streaming every table out of whatever# database is live. The result opens in any SQLite tool and can be handed to# the local dev stack as-is.
# Copied in metadata order so a table never lands before the one it references._SNAPSHOT_BATCH = 2_000
def build_portable_snapshot(dest: "Path") -> "Path": """Stream every table of the live database into a new SQLite file at `dest`.
Works regardless of the live backend. Rows are read and written in batches so a large table never has to fit in memory at once. """ import sqlalchemy as sa
import models
if dest.exists(): dest.unlink()
src_engine = database.engine dst_engine = sa.create_engine(f"sqlite:///{dest}")
# Copy the columns the LIVE database actually has, not the ones the models # declare. The two drift apart routinely — a snapshot taken while the live # DB is one migration behind (or ahead of) the running code must still # produce a usable file instead of failing on a missing column. inspector = sa.inspect(src_engine) try: live_tables = set(inspector.get_table_names()) except Exception: live_tables = set()
try: models.Base.metadata.create_all(bind=dst_engine) copied: dict[str, int] = {} skipped: list[str] = [] with src_engine.connect() as src, dst_engine.begin() as dst: for table in models.Base.metadata.sorted_tables: if live_tables and table.name not in live_tables: skipped.append(table.name) continue live_cols = {c["name"] for c in inspector.get_columns(table.name)} cols = [c for c in table.columns if c.name in live_cols] if not cols: skipped.append(table.name) continue total = 0 result = src.execution_options(stream_results=True).execute(sa.select(*cols)) while True: chunk = result.fetchmany(_SNAPSHOT_BATCH) if not chunk: break # JSON columns pass through as the decoded objects # SQLAlchemy handed back: its JSON type encodes them once # on the way in. Re-encoding here by hand is what produces # the double-encoded values the Neon cutover ran into. rows = [dict(r._mapping) for r in chunk] dst.execute(table.insert(), rows) total += len(rows) result.close() if total: copied[table.name] = total logger.warning( "Portable snapshot built: %s (%d bytes, %d tables, %d rows).%s", dest.name, dest.stat().st_size, len(copied), sum(copied.values()), f" Skipped (absent in the live DB): {', '.join(skipped)}." if skipped else "", ) return dest finally: dst_engine.dispose()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""Distributable ETL package served to the on-prem agent.
The Visma extractor and its companions live in `etl/` at the repo root andrun on the Windows server that has the ADK DLL — not in this container.Until 1.3.74 every change to those scripts meant VPN + copy/paste onto theserver. Now the image ships `etl/` alongside `backend/` (see Dockerfile), thismodule packs the runtime files into a zip with a content-hash version, and`force_sync_agent.py` compares that version with the one it last applied onevery poll (`GET /api/etl/agent/next`), downloads the zip, verifies theSHA-256, swaps the files and restarts itself.
What is distributed: only the Python runtime files and requirements.txt.Server-side one-off setup (set_token.ps1, setup_python_env.ps1, theinstall_*.cmd tasks, run_daily.ps1 with its machine-local config) is onpurpose NOT overwritten by the agent — see RUNTIME_FILES.
The version is a hash of (path + bytes) over the packaged files, so it onlychanges when something the agent runs actually changed, regardless of theapp version. The package is built once per process and cached: the containerfilesystem is immutable."""from __future__ import annotations
import datetimeimport hashlibimport ioimport loggingimport osimport zipfilefrom pathlib import Pathfrom typing import Optional
logger = logging.getLogger(__name__)
# Top-level etl/ files the agent needs at run time. Anything else in etl/# (tests/, tools/, output/, logs/, .cmd/.ps1 setup scripts) stays put.RUNTIME_FILES: tuple[str, ...] = ( "visma_unified_extractor.py", "sync_to_hf.py", "force_sync_agent.py", "adk_constants.py", "adk_mvp2_tables.py", "adk_mvp2_extract.py", "build_gateway_invoices_v5.py", "build_gateway_service_freight.py", "requirements.txt",)
# Files whose change means the running agent process must restart to pick# it up (the extractor is a subprocess, so it always runs the new file).RESTART_FILES: tuple[str, ...] = ("force_sync_agent.py", "sync_to_hf.py")
def etl_dir() -> Path: """Where the etl/ sources live: env override, else <repo>/etl next to backend/.""" override = os.environ.get("ETL_PACKAGE_DIR") if override: return Path(override) return Path(__file__).resolve().parent.parent / "etl"
class EtlPackage: def __init__(self, version: str, files: list[dict], zip_bytes: bytes, built_at: str): self.version = version self.files = files # [{path, sha256, size}] self.zip_bytes = zip_bytes self.zip_sha256 = hashlib.sha256(zip_bytes).hexdigest() self.built_at = built_at
def manifest(self) -> dict: return { "version": self.version, "built_at": self.built_at, "zip_sha256": self.zip_sha256, "zip_size": len(self.zip_bytes), "files": self.files, "restart_files": list(RESTART_FILES), }
def summary(self) -> dict: """The cheap bit that rides along with every agent poll.""" return {"version": self.version, "files": len(self.files)}
def build_package(source_dir: Optional[Path] = None) -> Optional[EtlPackage]: """Pack RUNTIME_FILES from `source_dir`. None when the directory is absent (a backend started outside the repo/image layout) — the agent then just never sees a package and keeps running what it has.""" src = source_dir or etl_dir() if not src.is_dir(): logger.warning("ETL package: source dir %s not found — self-update disabled", src) return None
entries: list[tuple[str, bytes]] = [] for name in RUNTIME_FILES: p = src / name if not p.is_file(): logger.warning("ETL package: %s missing from %s — skipped", name, src) continue entries.append((name, p.read_bytes())) if not entries: logger.warning("ETL package: no runtime files in %s — self-update disabled", src) return None
h = hashlib.sha256() files: list[dict] = [] for name, data in entries: h.update(name.encode("utf-8")) h.update(b"\0") h.update(data) h.update(b"\0") files.append({"path": name, "sha256": hashlib.sha256(data).hexdigest(), "size": len(data)}) version = h.hexdigest()[:12]
buf = io.BytesIO() # Fixed timestamps so the same content always yields byte-identical zips # (and therefore a stable zip_sha256) across container restarts. with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf: for name, data in entries: info = zipfile.ZipInfo(name, date_time=(2020, 1, 1, 0, 0, 0)) info.compress_type = zipfile.ZIP_DEFLATED zf.writestr(info, data) built_at = datetime.datetime.utcnow().isoformat(timespec="seconds") logger.info("ETL package built: version=%s files=%d bytes=%d", version, len(files), buf.tell()) return EtlPackage(version, files, buf.getvalue(), built_at)
_cache: dict[str, Optional[EtlPackage]] = {}
def get_package() -> Optional[EtlPackage]: """Process-wide cached package (built on first use).""" if "pkg" not in _cache: try: _cache["pkg"] = build_package() except Exception: logger.exception("ETL package build failed — self-update disabled") _cache["pkg"] = None return _cache["pkg"]
def reset_cache() -> None: """Tests only.""" _cache.clear()58 unmodified lines59606162636465666762636458 unmodified lines country = Column(String) currency = Column(String) is_export = Column(Boolean, default=False) # Visma "Kundkategori" (ADK_CUSTOMER_CATEGORY, field 26): the code and the # label from the code register ADK_DB_CODE_OF_CUSTOMER_CATEGORY. Used to # group chain stores (ICA, Varner, Apoteket, ...) into one commercial # account for the ABC classification. category_code = Column(String, nullable=True, index=True) category_name = Column(String, nullable=True) revenue_ytd = Column(Float, default=0.0) margin_ytd = Column(Float, default=0.0) last_invoice = Column(String, nullable=True) # YYYY-MM-DD19 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911023242519 unmodified lines"""
RELEASES: list[dict] = [ { "version": "1.3.75", "released_at": "2026-09-08", "title_en": "Download a database snapshot again", "title_pt": "Baixar um snapshot do banco de novo", "highlights_en": [ "Admin → the database snapshot download works again. It had been answering \"backup unavailable\" ever since the move to the Postgres database, because it could only snapshot the older SQLite setup.", "It now streams every table into a fresh SQLite file that opens in any database tool — useful for reconciliations, for handing a dataset to someone, or for loading production data into a local copy.", "The snapshot is taken from whatever the live database actually contains, so it still works when the database is a version behind the running code instead of failing outright.", ], "highlights_pt": [ "Admin → o download de snapshot do banco voltou a funcionar. Ele respondia \"backup indisponível\" desde a mudança para o banco Postgres, porque só sabia copiar o formato SQLite antigo.", "Agora ele grava todas as tabelas num arquivo SQLite novo, que abre em qualquer ferramenta de banco — serve para conciliações, para entregar um conjunto de dados a alguém, ou para carregar dados de produção numa cópia local.", "O snapshot é tirado do que o banco realmente tem, então continua funcionando quando o banco está uma versão atrás do código em execução, em vez de falhar.", ], }, { "version": "1.3.74", "released_at": "2026-09-08", "title_en": "ETL scripts update themselves on the Visma server", "title_pt": "Scripts do ETL se atualizam sozinhos no servidor do Visma", "highlights_en": [ "Until now every change to the Visma extractor meant opening the VPN and copying files onto the server by hand. From this release the app ships the ETL scripts itself: the agent already running on the Visma server checks, on every poll, whether the app has a newer set of scripts and, when idle, downloads it, verifies the checksum, swaps the files (keeping a backup of the previous ones) and restarts itself.", "Admin → System Health gains an 'ETL scripts' row: up to date / outdated / update failed, with the version on the server versus the one the app ships and when the agent last applied it. Nothing is replaced while a sync is running.", "One last manual copy is needed to install this self-updating agent (the old one does not know how to update). After that, publishing a new app version is enough — the customer category export from 1.3.72, for example, reaches the server on its own.", "Only the runtime scripts are distributed; the server's one-off setup (token, Python environment, scheduled tasks) is never touched. The agent can be pinned with --no-self-update if ever needed.", ], "highlights_pt": [ "Até agora toda mudança no extrator do Visma exigia abrir a VPN e copiar arquivos no servidor à mão. A partir desta versão o próprio app distribui os scripts do ETL: o agente que já roda no servidor do Visma verifica, a cada poll, se o app tem um conjunto de scripts mais novo e, quando está ocioso, baixa, confere o checksum, troca os arquivos (guardando backup dos anteriores) e reinicia sozinho.", "Admin → System Health ganha a linha 'ETL scripts': atualizado / desatualizado / falha na atualização, com a versão no servidor contra a que o app distribui e quando o agente aplicou pela última vez. Nada é trocado enquanto um sync está rodando.", "É preciso uma última cópia manual para instalar este agente auto-atualizável (o antigo não sabe se atualizar). Depois disso, publicar uma nova versão do app basta — o export de categoria de cliente da 1.3.72, por exemplo, chega ao servidor sozinho.", "Só os scripts de execução são distribuídos; a configuração única do servidor (token, ambiente Python, tarefas agendadas) nunca é tocada. O agente pode ser travado com --no-self-update se um dia for preciso.", ], }, { "version": "1.3.72", "released_at": "2026-09-08", "title_en": "Customers: Visma category (Kundkategori) and ABC classification", "title_pt": "Clientes: categoria do Visma (Kundkategori) e classificação ABC", "highlights_en": [ "The Customers page now shows each customer's Visma category (Kundkategori — ICA, Varner SV, Apoteket Hjärtat, Distributers, ...). Sort by the Category column, pick a category in the new filter, or click a row in the category table to see only those customers.", "ABC classification as requested by finance: class A = the customers that make up about 80% of revenue, B = the next 15%, C = the last 5%. It follows the selected period, uses revenue excl. VAT with credit notes deducted, and shows the cumulative % so you can see where each class ends.", "The class is computed twice, and both are on every row: per customer, and per account by category — a chain like ICA is dozens of store accounts in Visma but one negotiated account, so the category ranking is the one to use when the customer is a chain. A customer without a category, or in Visma's catch-all category 'Sverige', stands alone as its own account instead of being lumped into one bucket. The new Customer Categories — ABC panel ranks the accounts with a chart coloured by class; click a category row to see only its customers.", "The customers tables gained the house filter box, click-to-sort headers and paging; the Customers CSV export gained Category, ABC class (customer and category) and Cumulative % columns.", "Data: the Visma extractor (v6.3) exports Category_Code + Category_Name in dim_customers.csv. Categories appear after the next extractor run + customer import; until then customers show as 'No category' and the per-customer ABC still works.", ], "highlights_pt": [ "A página Customers passa a mostrar a categoria de cada cliente no Visma (Kundkategori — ICA, Varner SV, Apoteket Hjärtat, Distributers, ...). Ordene pela coluna Category, escolha uma categoria no novo filtro ou clique numa linha da tabela de categorias para ver só aqueles clientes.", "Classificação ABC como o financeiro pediu: classe A = os clientes que somam cerca de 80% da receita, B = os próximos 15%, C = os últimos 5%. Segue o período selecionado, usa receita sem IVA com credit notes deduzidas e mostra o % acumulado para se ver onde cada classe termina.", "A classe é calculada duas vezes, e as duas aparecem em cada linha: por cliente e por conta segundo a categoria — uma rede como a ICA são dezenas de contas de loja no Visma mas uma conta negociada, então o ranking por categoria é o que vale quando o cliente é uma rede. Cliente sem categoria, ou na categoria genérica 'Sverige' do Visma, fica como conta própria em vez de ser amontoado num único balde. O novo painel Customer Categories — ABC ranqueia as contas com gráfico colorido por classe; clique numa categoria para ver só os clientes dela.", "As tabelas de clientes ganharam a caixa de filtro padrão, ordenação clicando no cabeçalho e paginação; o export CSV de Customers ganhou as colunas Category, classe ABC (cliente e categoria) e Cumulative %.", "Dados: o extrator do Visma (v6.3) exporta Category_Code + Category_Name no dim_customers.csv. As categorias aparecem depois da próxima rodada do extrator + import de clientes; até lá os clientes ficam como 'No category' e o ABC por cliente já funciona.", ], }, { "version": "1.3.71", "released_at": "2026-09-08", "title_en": "Open orders: 'Ej klar' orders were missing from the backlog", "title_pt": "Pedidos abertos: pedidos 'Ej klar' sumiam do backlog", "highlights_en": [ "Orders marked 'Ej klar' (not finalised / not print-ready) in Visma were being treated as voided and left out of every open-order view — Beyond Technology's four August orders (4880–4883, 1.95 MSEK) were invisible on the home page's Open Orders by Customer card, in Sales → Backlog and in the article cards. Cancelled documents never reach the ERP in the first place, so 'Ej klar' is simply an open order that has not been finalised yet.", "Those orders now count in the backlog, the overdue and due-soon figures and the per-customer margins, and carry a small 'not finalised' marker in Sales → Backlog, on the home page order list and in the order detail panel. The same rule applies to open offers and open purchase orders.", "Reminder: an order only appears under Invoices once it has been invoiced in Visma — until then it lives in the open-order views.", ], "highlights_pt": [ "Pedidos marcados 'Ej klar' (não finalizado / não pronto para impressão) no Visma eram tratados como cancelados e ficavam fora de todas as visões de pedidos abertos — os quatro pedidos de agosto da Beyond Technology (4880–4883, 1,95 MSEK) não apareciam no card Open Orders by Customer da página inicial, em Sales → Backlog nem nos cards de artigo. Documentos cancelados nem chegam ao ERP, então 'Ej klar' é apenas um pedido aberto ainda não finalizado.", "Esses pedidos agora contam no backlog, nos valores atrasados e a vencer e nas margens por cliente, e levam um marcador 'not finalised' em Sales → Backlog, na lista de pedidos da página inicial e no painel de detalhe do pedido. A mesma regra vale para ofertas abertas e pedidos de compra abertos.", "Lembrete: um pedido só aparece em Invoices depois de faturado no Visma — até lá ele vive nas visões de pedidos abertos.", ], }, { "version": "1.3.70", "released_at": "2026-09-08", "title_en": "Cancelled invoices: their freight is a cost, not revenue", "title_pt": "Faturas canceladas: o frete delas é custo, não receita", "highlights_en": [ "When an invoice is cancelled in Visma, every line is zeroed and no ledger voucher is posted — but Visma leaves the freight sitting in the invoice net. The ERP used to read that leftover as freight charged to the customer, so a cancelled invoice (e.g. 137219, 170 USD) still counted as invoiced freight. It no longer does: that freight is booked as a cost we absorbed, with nothing invoiced.", "Where you see it: the invoice opens with a red Cancelled tag, its freight row reads 'not invoiced' with the amount shown as a cost, and the document still reconciles. The Invoices list shows the same tag; the Freight tab of Invoice Lines lists the row with a 'Cancelled · cost' chip and a separate card for the total; the Freight dashboard has a 'Cancelled-invoice Freight' card and takes it off the Net Freight Result.", "Invoiced freight and the embedded-freight figure go down by exactly the freight on cancelled invoices (10 invoices in 2026 so far). Exports follow: the freight lines CSV and the invoice Excel carry a Cancelled_Freight_Cost column, and the freight cost CSV summary includes it.", "Invoices imported before this update are corrected automatically at startup — no re-import needed. An invoice counts as cancelled when every line has nothing delivered or billed and the goods value is zero; an invoice that simply has no line detail is not affected.", ], "highlights_pt": [ "Quando uma fatura é cancelada no Visma, todas as linhas ficam zeradas e nenhum lançamento vai para o razão — mas o Visma deixa o frete dentro do líquido da fatura. O ERP lia essa sobra como frete cobrado do cliente, então uma fatura cancelada (ex.: 137219, 170 USD) continuava contando como frete faturado. Não conta mais: esse frete passa a ser custo absorvido, sem nada faturado.", "Onde aparece: a fatura abre com a etiqueta vermelha Cancelled, a linha de frete mostra 'not invoiced' com o valor como custo, e o documento continua fechando. A lista de faturas mostra a mesma etiqueta; a aba Freight de Invoice Lines lista a linha com o chip 'Cancelled · cost' e um card separado com o total; o painel Freight ganha o card 'Cancelled-invoice Freight' e desconta esse valor do Net Freight Result.", "O frete faturado e o frete embutido caem exatamente pelo frete das faturas canceladas (10 faturas em 2026 até agora). Os exports acompanham: o CSV de linhas de frete e o Excel da fatura ganham a coluna Cancelled_Freight_Cost, e o resumo do CSV de custo de frete a inclui.", "Faturas importadas antes desta atualização são corrigidas automaticamente no startup — não precisa reimportar. Uma fatura conta como cancelada quando todas as linhas estão sem entrega e sem faturamento e o valor de mercadoria é zero; fatura que apenas não tem detalhe de linhas não é afetada.", ], }, { "version": "1.3.69", "released_at": "2026-09-08",14 unmodified lines1516171819181920616 unmodified lines63763863964264364464564664764864965065164064164264365465565665765865966066166264464564664764864965014 unmodified linesimport datetimeimport loggingimport osimport pathlibimport tempfilefrom typing import Dict, Optional
from fastapi import APIRouter, Depends, HTTPException, Query616 unmodified lines# ── DB snapshot download ─────────────────────────────────────────────────────@router.get("/backup/download", tags=["Admin"])def download_backup(actor: models.User = Depends(require_admin)) -> FileResponse: """Create a fresh, consistent SQLite snapshot and return it as a file.
Two paths, same result — a SQLite file any tool can open: - SQLite live DB: sqlite3's online backup, exactly what the nightly job writes (consistent while readers and writers are active). - Anything else (Postgres in production): every table is streamed into a fresh SQLite file with the application's own schema. Before 1.3.75 this endpoint answered 503 on Postgres, so it had been unusable in production since the Neon cutover. """ """Create a fresh, consistent SQLite snapshot (same online-backup logic as the nightly job) and return it as a downloadable file.""" path = backup.run_backup() if path is None: try: dest = pathlib.Path(tempfile.gettempdir()) / f"snapshot-{datetime.date.today().isoformat()}.db" path = backup.build_portable_snapshot(dest) except Exception: logger.exception("Portable snapshot failed") raise HTTPException( status_code=503, detail="Backup unavailable: could not build a snapshot of the live database.", ) raise HTTPException( status_code=503, detail="Backup unavailable: database is not SQLite or the live DB file was not found.", ) logger.warning("BACKUP DOWNLOAD by user %s (id=%s): %s", actor.email, actor.id, path.name) stamp = datetime.date.today().isoformat() return FileResponse(26 unmodified lines2728293031323334353637303132327 unmodified lines360361362371372373374375376377378363364365356 unmodified lines722723724741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836725726727187 unmodified lines9159169171030103191891992028 unmodified lines9499509511066106710681069107095295395495567 unmodified lines1023102410251144114510261027102826 unmodified linesrouter = APIRouter(prefix="/api/dashboard", tags=["Dashboard"], dependencies=[Depends(get_current_user)])
# Visma Kundkategori labels that are a default bucket rather than a chain.# In the Visma register category 1 is "Sverige" — the catch-all every plain# Swedish customer lands in — so grouping it would turn hundreds of unrelated# customers into one class-A "account". Customers in these categories keep# the label on their row but stand alone in the account (category) ranking.GENERIC_CUSTOMER_CATEGORIES = {"sverige", "sweden", "norge", "norway", "export", "övriga", "ovriga", "other"}
# ── Revenue V2 helpers (used by /analytics + /products) ───────────────────────def _abc_class_from_share(cumulative_share_pct: float) -> str: """Pareto ABC: A = until 80% cumulative revenue, B = 80-95%, C = rest."""327 unmodified lines freight_rev_coded = sum(l.revenue_sek or 0.0 for l in freight_adk_lines) freight_header_gap_sek = sum(l.revenue_sek or 0.0 for l in freight_synth_lines) total_freight_rev = freight_rev_coded + freight_header_gap_sek # Freight Visma kept on CANCELLED invoices ('cancelled_freight' rows, see # imports.is_cancelled_invoice): nothing was invoiced, the carrier was # still paid — a cost we absorbed, never invoiced freight. Stored with # revenue_sek 0 and the amount in unit_cost_sek, so the sums above are # already clean; it is reported on its own and taken off the net result. freight_cancelled_lines = [l for l in freight_lines if (l.row_source or 'adk') == 'cancelled_freight'] freight_cancelled_cost_sek = sum(l.unit_cost_sek or 0.0 for l in freight_cancelled_lines) freight_cancelled_invoices = len({l.invoice_number for l in freight_cancelled_lines}) service_rev = sum(l.revenue_sek or 0.0 for l in service_lines) # Service margin comes from Visma's own cost field — labour lines # typically have 0 cost (margin == revenue) but subcontracted/resold356 unmodified lines
top_customers = sorted(top_customers, key=lambda x: -x["revenue"])
# ── CUSTOMER CATEGORY + ABC CLASSIFICATION ────────────────────────────── # Finance's rule (Victor, 2026-09): A = customers that make up ~80% of # revenue, B = the next 15%, C = the last 5%. Computed twice: # * per customer row (name group), and # * per commercial account — the Visma Kundkategori when the customer # has one (the chains ICA, Varner, Apoteket... are hundreds of store # accounts in Visma but one negotiated account for finance), and the # customer itself otherwise. That is the "accurate" ranking they asked # for; lumping every uncategorised customer into one bucket would # hand that bucket class A on real data (41% of revenue), so a # customer without a category simply stands alone as its own account. # Boundary rule: a customer is A while the cumulative share *before* it # is under 80% (so the one that crosses 80% still belongs to A) — that's # the reading of "accounts for approximately 80%". customer_total_rev = sum(c["revenue"] for c in top_customers)
def _abc_from_prev_cum(prev_cum_pct: float) -> str: if prev_cum_pct < 80.0: return "A" if prev_cum_pct < 95.0: return "B" return "C"
def _customer_category(nk): for cid in customer_data[nk].get("customer_ids", []): cust = customer_map.get(cid) if cust is not None and cust.category_code: return cust.category_code, (cust.category_name or cust.category_code) return None, None
running = 0.0 abc_counts_customer = {"A": 0, "B": 0, "C": 0} category_rows: dict[str, dict] = {} for idx, c in enumerate(top_customers): share = (c["revenue"] / customer_total_rev * 100) if customer_total_rev > 0 else 0.0 c["abc_class"] = _abc_from_prev_cum(running) c["share_pct"] = round(share, 2) running += share c["cumulative_share_pct"] = round(min(running, 100.0), 1) c["rank"] = idx + 1 abc_counts_customer[c["abc_class"]] += 1
# customer_id on the row is the first id of the name group; the # category lookup walks every id of the group like country does. nk = normalize_name(c["name"]) code, label = _customer_category(nk) c["category_code"] = code c["category"] = label groups = bool(code) and (label or "").strip().lower() not in GENERIC_CUSTOMER_CATEGORIES key = f"cat:{code}" if groups else f"cust:{nk}" c["account_key"] = key row = category_rows.setdefault(key, { "account_key": key, "is_category": groups, "category_code": code if groups else None, "category": label if groups else c["name"], "revenue": 0.0, "margin_visma": 0.0, "margin_fifo": 0.0, "invoices": 0, "customers": 0, }) row["revenue"] += c["revenue"] row["margin_visma"] += c["margin_visma"] row["margin_fifo"] += c["margin_fifo"] row["invoices"] += c["invoices"] row["customers"] += 1
customer_categories = sorted(category_rows.values(), key=lambda r: -r["revenue"]) running = 0.0 abc_counts_category = {"A": 0, "B": 0, "C": 0} class_by_category_key: dict[str, str] = {} for idx, r in enumerate(customer_categories): share = (r["revenue"] / customer_total_rev * 100) if customer_total_rev > 0 else 0.0 r["abc_class"] = _abc_from_prev_cum(running) r["share_pct"] = round(share, 2) running += share r["cumulative_share_pct"] = round(min(running, 100.0), 1) r["rank"] = idx + 1 r["revenue"] = round(r["revenue"], 2) r["margin_visma"] = round(r["margin_visma"], 2) r["margin_fifo"] = round(r["margin_fifo"], 2) r["margin_pct"] = round(r["margin_visma"] / r["revenue"] * 100, 1) if r["revenue"] > 0 else 0.0 abc_counts_category[r["abc_class"]] += 1 class_by_category_key[r["account_key"]] = r["abc_class"]
for c in top_customers: c["category_abc_class"] = class_by_category_key.get(c["account_key"])
customer_abc = { "thresholds": {"A": 80.0, "B": 95.0}, "basis": "Revenue excl. VAT, credit notes deducted, in the selected period", "total_revenue": round(customer_total_rev, 2), "counts_customer": abc_counts_customer, "counts_category": abc_counts_category, "categorised_customers": sum(1 for c in top_customers if c["category_code"]), "uncategorised_customers": sum(1 for c in top_customers if not c["category_code"]), "category_count": sum(1 for r in customer_categories if r["is_category"]), "account_count": len(customer_categories), }
# ── CONCENTRATION (HHI) ─────────────────────────────────────────────────── # Herfindahl-Hirschman Index across ALL customers in the window (not just # top 10). HHI ∈ [0, 10 000]; anti-trust convention: <1500 low, 1500-2500187 unmodified lines for l in freight_lines: if l.account_number not in FREIGHT_ACCT_FOR_ZONE.values(): continue if (l.row_source or 'adk') == 'cancelled_freight': continue # nothing invoiced — no geography to get wrong zone = country_vat_zone(cust_country.get(head_customer.get(l.invoice_number))) if zone is None: continue28 unmodified lines freight_cost_first_date.date().isoformat() if freight_cost_first_date else None ), "freight_cost_available": (not has_dim_filter) and freight_cost_entries > 0, # Freight absorbed on cancelled invoices — attributable per # invoice, so it is always available and always in the net. "freight_cancelled_cost_sek": round(freight_cancelled_cost_sek, 2), "freight_cancelled_invoices": freight_cancelled_invoices, "freight_net_sek": round(total_freight_rev - freight_cost_sek - freight_cancelled_cost_sek, 2), "freight_net_sek": round(total_freight_rev - freight_cost_sek, 2), "geog_mismatch_count": len(fgt_mismatches), "geog_mismatch_sek": round(sum(m["revenue_sek"] for m in fgt_mismatches), 2), },67 unmodified lines "category_mix": category_mix, "exception_queue": exception_queue, "customers": top_customers, "customer_categories": customer_categories, "customer_abc": customer_abc, "deltas": deltas, # Mirror of the top-level freshness fields so RevenueDashboard # can read `revenue.meta.last_etl_at` directly (single source).38 unmodified lines3940414242434445464747484923 unmodified lines73747577787980818276777832 unmodified lines111112113121122114115116117127128129130131132133134135136118119120254 unmodified lines3753763773973983994004013783794043803813823834 unmodified lines38838939041541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848939139239339438 unmodified linesimport osfrom typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Responsefrom fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import BaseModel, Fieldfrom sqlalchemy.orm import Session
import databaseimport etl_packageimport modelsfrom auth import get_current_user, require_adminfrom database import get_db23 unmodified lines
_META_AGENT_LAST_SEEN = "etl_agent_last_seen"_META_AGENT_HOST = "etl_agent_host"# Self-update bookkeeping (see etl_package.py): what the agent reports it# last applied, so the Admin page can say "agent up to date / outdated"._META_AGENT_PKG_VERSION = "etl_agent_package_version"_META_AGENT_PKG_APPLIED_AT = "etl_agent_package_applied_at"_META_AGENT_PKG_STATUS = "etl_agent_package_status" # 'applied' | 'error'_META_AGENT_PKG_ERROR = "etl_agent_package_error"
# ── Auto-sync (scheduled nightly through the same queue) ─────────────────────# `requested_by` marker for scheduler-created requests.32 unmodified lines online = (_utcnow() - last_seen).total_seconds() < AGENT_ONLINE_SECONDS except ValueError: last_seen_raw = None pkg = etl_package.get_package() agent_version = _meta_get(db, _META_AGENT_PKG_VERSION) return { "online": online, "last_seen": last_seen_raw, "host": _meta_get(db, _META_AGENT_HOST), "package": { "server_version": pkg.version if pkg else None, "agent_version": agent_version, "applied_at": _meta_get(db, _META_AGENT_PKG_APPLIED_AT), "status": _meta_get(db, _META_AGENT_PKG_STATUS), "error": _meta_get(db, _META_AGENT_PKG_ERROR), # None when either side is unknown (no package, or an agent # older than 1.3.74 that never reported one). "up_to_date": (pkg.version == agent_version) if (pkg and agent_version) else None, }, }
254 unmodified lines db.commit()
req = _active_request(db) # The package summary rides along on every poll: the agent compares the # version with the one it last applied and self-updates when it differs. pkg = etl_package.get_package() pkg_summary = pkg.summary() if pkg else None
if req is None or req.status != "pending": # Nothing to do — either idle, or a run is already claimed/running. return {"request": None, "etl_package": pkg_summary} return {"request": None}
req.status = "claimed" req.claimed_at = now4 unmodified lines db.refresh(req) logger.warning("Force sync request %s claimed by agent host=%s (token user %s)", req.id, host, user.email) return {"request": _serialize(req), "etl_package": pkg_summary}
# ── Agent self-update (etl/ package distribution) ────────────────────────────
@router.get("/agent/package/manifest")def agent_package_manifest( _: models.User = Depends(get_current_user),) -> dict: """Version + per-file hashes of the etl/ runtime package this build ships.""" pkg = etl_package.get_package() if pkg is None: raise HTTPException(status_code=404, detail="No ETL package in this build") return pkg.manifest()
@router.get("/agent/package")def agent_package_download( _: models.User = Depends(get_current_user),) -> Response: """The zip itself. The agent verifies X-Package-SHA256 before applying.""" pkg = etl_package.get_package() if pkg is None: raise HTTPException(status_code=404, detail="No ETL package in this build") return Response( content=pkg.zip_bytes, media_type="application/zip", headers={ "X-Package-Version": pkg.version, "X-Package-SHA256": pkg.zip_sha256, "Content-Disposition": f'attachment; filename="gateway-etl-{pkg.version}.zip"', }, )
class AgentPackageApplied(BaseModel): version: str = Field(max_length=64) status: str # 'applied' | 'error' previous_version: Optional[str] = Field(default=None, max_length=64) host: Optional[str] = Field(default=None, max_length=120) error: Optional[str] = Field(default=None, max_length=2000) requirements_changed: bool = False
@router.post("/agent/package/applied")def agent_package_applied( body: AgentPackageApplied, _: models.User = Depends(get_current_user), db: Session = Depends(get_db),) -> dict: """Agent reports the outcome of a self-update (or its current version on start-up, status 'applied'), so the Admin page can show it.""" if body.status not in ("applied", "error"): raise HTTPException(status_code=422, detail="status must be 'applied' or 'error'") now = _utcnow() _meta_set(db, _META_AGENT_LAST_SEEN, now.isoformat()) if body.host: _meta_set(db, _META_AGENT_HOST, body.host[:120]) if body.status == "applied": _meta_set(db, _META_AGENT_PKG_VERSION, body.version) _meta_set(db, _META_AGENT_PKG_APPLIED_AT, now.isoformat()) _meta_set(db, _META_AGENT_PKG_STATUS, "applied") _meta_set(db, _META_AGENT_PKG_ERROR, "") if body.previous_version != body.version: logger.warning("ETL agent on %s updated package %s -> %s%s", body.host, body.previous_version, body.version, " (requirements.txt changed — pip install may be needed)" if body.requirements_changed else "") else: _meta_set(db, _META_AGENT_PKG_STATUS, "error") _meta_set(db, _META_AGENT_PKG_ERROR, (body.error or "")[:2000]) logger.error("ETL agent on %s failed to apply package %s: %s", body.host, body.version, body.error) db.commit() return {"ok": True} return {"request": _serialize(req)}
@router.post("/agent/requests/{request_id}/progress")403 unmodified lines40440540640740740840941019 unmodified lines43043143243343343443543643743843843944044244344144244316 unmodified lines46046146246646746346446514 unmodified lines48048148248848948348448515 unmodified lines501502503511512513504505506359 unmodified lines866867868879880881882883884869870871872873874891892875876877878106 unmodified lines98598698710051006100710089889899906 unmodified lines997998999102110221023102410001001100211 unmodified lines10141015101610421017101810191020561 unmodified lines1582158315841610161115851586158730 unmodified lines161816191620164816491621162216232 unmodified lines162616271628165816591629163016319 unmodified lines164116421643167516441645164616471 unmodified line164916501651168316521653165410 unmodified lines16651666166717001668166916701671167217061673167416751676403 unmodified lines metadata block when the cap bites. """ from helpers import CAT_MAP, FGT_CAT from routers.invoice_lines import VALID_SCOPES, build_lines_query, cancelled_cost, line_values from routers.invoice_lines import VALID_SCOPES, build_lines_query, line_values
if scope not in VALID_SCOPES: scope = "products"19 unmodified lines with_category = scope in ("service", "freight")
rows: list[_Row] = [] tot_rev = tot_margin = tot_qty = tot_cancelled = 0.0 tot_rev = tot_margin = tot_qty = 0.0 for line, cust_id, cust_name in fetched: rev = line.revenue_sek or 0.0 qty = line.qty or 0.0 unit_cost, margin, pct = line_values(line) cancelled = cancelled_cost(line) # freight absorbed on a cancelled invoice tot_rev += rev if margin is not None: tot_margin += margin if cancelled is not None: tot_cancelled += cancelled tot_qty += qty row: _Row = { "Date": line.date.date().isoformat() if line.date else "",16 unmodified lines f"Margin_{suffix}": _convert(margin, rate), "Margin_Pct": pct, }) if scope == "freight": row[f"Cancelled_Freight_Cost_{suffix}"] = _convert(cancelled, rate) rows.append(row)
totals_row: _Row = {14 unmodified lines if with_category: totals_row["Account"] = "" totals_row["Category"] = "" if scope == "freight": totals_row[f"Cancelled_Freight_Cost_{suffix}"] = _convert(tot_cancelled, rate)
filter_bits = [f"period={_period_label(period, start_date, end_date)}"] if customer_id: filter_bits.append(f"customer_id={customer_id}")15 unmodified lines f"Margin_{suffix}": 2, "Margin_Pct": 1, } if scope == "freight": number_cols[f"Cancelled_Freight_Cost_{suffix}"] = 2 metadata.insert(1, "Note: rows with Cancelled_Freight_Cost are cancelled invoices — freight Visma kept on the header; a cost, not invoiced freight (Revenue is 0)")
today_str = datetime.date.today().isoformat() return _csv_response(359 unmodified lines invoiced = lines_q.with_entities( func.coalesce(func.sum(models.InvoiceLine.revenue_sek), 0.0) ).scalar() or 0.0 # Freight absorbed on cancelled invoices (revenue 0, amount in # unit_cost_sek) — part of the net result, same as on the dashboard. from routers.invoice_lines import CANCELLED_FREIGHT cancelled_freight = lines_q.filter(models.InvoiceLine.row_source == CANCELLED_FREIGHT).with_entities( func.coalesce(func.sum(models.InvoiceLine.unit_cost_sek), 0.0) ).scalar() or 0.0
metadata = [ f"Report: Freight cost — carrier ledger rows, GL {', '.join(sorted(FREIGHT_COST_ACCTS))} (rows={len(rows)})", f"Filters: period={_period_label(period, start_date, end_date)} — window only (carrier rows have no customer/project attribution)", f"Summary_{suffix}: invoiced_freight={_fmt_num(_convert(invoiced, rate), 2, locale)}" f" / freight_cost={_fmt_num(_convert(tot_cost, rate), 2, locale)}" f" / cancelled_invoice_freight={_fmt_num(_convert(cancelled_freight, rate), 2, locale)}" f" / net_result={_fmt_num(_convert(invoiced - tot_cost - cancelled_freight, rate), 2, locale)}", f" / net_result={_fmt_num(_convert(invoiced - tot_cost, rate), 2, locale)}", f"Currency: {ccy} (1 SEK = {rate:.4f} {ccy})", f"Generated: {datetime.datetime.now().isoformat(timespec='seconds')}", ]106 unmodified lines "Customer_ID": c.get("customer_id", ""), "Name": c.get("name", ""), "Country": c.get("country", ""), "Category": c.get("category") or "", "ABC_Class": c.get("abc_class", ""), "ABC_Class_Category": c.get("category_abc_class") or "", "Cumulative_Pct": c.get("cumulative_share_pct", 0), f"Revenue_{suffix}": _convert(rev, rate), f"Margin_Visma_{suffix}": _convert(m_visma, rate), f"Margin_FIFO_{suffix}": _convert(m_fifo, rate),6 unmodified lines "Customer_ID": "TOTAL", "Name": f"{len(rows)} customers", "Country": "", "Category": "", "ABC_Class": "", "ABC_Class_Category": "", "Cumulative_Pct": 100.0 if tot_rev > 0 else 0.0, f"Revenue_{suffix}": _convert(tot_rev, rate), f"Margin_Visma_{suffix}": _convert(tot_v, rate), f"Margin_FIFO_{suffix}": _convert(tot_f, rate),11 unmodified lines f"Revenue_{suffix}": 2, f"Margin_Visma_{suffix}": 2, f"Margin_FIFO_{suffix}": 2, "Margin_Pct": 1, "Pct_Of_Total": 1, "Cumulative_Pct": 1, "Margin_Pct": 1, "Pct_Of_Total": 1, } today_str = datetime.date.today().isoformat() return _csv_response(561 unmodified lines
row("Document", font=bold) row("Type", "Credit note" if h.get("is_credit_note") else "Invoice") if h.get("is_cancelled"): row("Status", "CANCELLED in Visma — nothing delivered or billed; the freight below is a cost, not revenue") row("Invoice date", h.get("date")) row("Due date", h.get("due_date")) row("Payment terms", h.get("payment_terms"))30 unmodified lines
row("Cost & margin (as posted)", font=bold) money_row("Cost (kalkylpris)", t.get("cost")) if t.get("cancelled_freight_cost"): money_row("Freight on cancelled invoice (cost)", t.get("cancelled_freight_cost")) money_row("Margin — header", t.get("margin_header")) money_row("Margin — lines", t.get("margin_lines")) row("Margin %", round(t["margin_pct"], 2) if t.get("margin_pct") is not None else None)2 unmodified lines
row("Reconciliation", font=bold) money_row(f"Sum of {t.get('line_count')} lines", t.get("line_sum")) if t.get("cancelled_freight_cost"): money_row("+ freight on cancelled invoice (cost)", t.get("cancelled_freight_cost")) money_row("Header net", t.get("net")) money_row("Difference", t.get("recon_diff")) row("Reconciled", "yes" if t.get("reconciled") else "no")9 unmodified lines headers = [ "SKU", "Description", "Account", "VAT_Code", "Stream", "In_Ledger", "Billed", "Qty", "Unit_Price_SEK", "Unit_Cost_SEK", "Revenue_SEK", "Margin_SEK", "Margin_Pct", "Cancelled_Freight_Cost_SEK", "Margin_SEK", "Margin_Pct", ] ws.append(headers) for cell in ws[ws.max_row]:1 unmodified line num_formats = { "Qty": _XLSX_QTY, "Unit_Price_SEK": _XLSX_MONEY, "Unit_Cost_SEK": _XLSX_MONEY, "Revenue_SEK": _XLSX_MONEY, "Margin_SEK": _XLSX_MONEY, "Margin_Pct": "0.00", "Cancelled_Freight_Cost_SEK": _XLSX_MONEY, } for l in lines: ws.append([10 unmodified lines l.get("revenue"), l.get("margin"), round(l["margin_pct"], 2) if l.get("margin_pct") is not None else None, l.get("cancelled_cost"), ]) for col_idx, hname in enumerate(headers, start=1): if hname in num_formats: ws.cell(row=ws.max_row, column=col_idx).number_format = num_formats[hname] ws.freeze_panes = "A3" _autosize(ws, [14, 44, 10, 10, 12, 10, 8, 10, 14, 14, 14, 14, 11, 16]) _autosize(ws, [14, 44, 10, 10, 12, 10, 8, 10, 14, 14, 14, 14, 11])
buf = BytesIO() wb.save(buf)306 unmodified lines3073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663103683693703713723733743113123133143153163173183193203803813823833213223233243253263893903273283293303313323973983333343354024034044054064074084094103363373383393403413423434154164173443454194204214223464243473483493503515 unmodified lines3573583594363603614384393623633644 unmodified lines36937037145037237337437532 unmodified lines40840941048941141241341420 unmodified lines435436437516517518519520521438439440441442443444445446447448449450530451452532453454455456404 unmodified lines861862863943944945946947948864865866462 unmodified lines132913301331141713321333141913341335142113361337133813391340142614271341134213431344306 unmodified lines return '3520'
# Synthetic row kinds for freight charged at header level. 'header_freight'# is invoiced freight (revenue on 3520/21/22). 'cancelled_freight' is the same# header gap on a CANCELLED invoice: Visma's makulering zeroes every delivered# quantity and the goods value but leaves the freight sitting in Excl.VAT, and# no ledger voucher is ever posted for the document. Nothing was invoiced, so# that freight is a cost we absorbed (the carrier was still paid), never# revenue — it is stored with revenue_sek=0 and the amount in unit_cost_sek.ROW_SOURCE_HEADER_FREIGHT = 'header_freight'ROW_SOURCE_CANCELLED_FREIGHT = 'cancelled_freight'FREIGHT_SYNTHETIC_SOURCES = (ROW_SOURCE_HEADER_FREIGHT, ROW_SOURCE_CANCELLED_FREIGHT)
def is_cancelled_invoice(total_gross: float | None, adk_lines) -> bool: """Heuristic for a cancelled (makulerad) Visma invoice, from the data the extractor delivers today (the ADK cancelled flag is only honoured by the v6.1 extractor, which skips such documents at the source).
A cancelled invoice keeps its rows but with nothing delivered or billed: every ADK line has qty 0 and revenue 0, and the header goods value is 0. A document with no ADK lines at all is NOT treated as cancelled — that is the legacy 'no line detail' case handled by 'header_unallocated'. `adk_lines` is any iterable of objects with `qty` and `revenue_sek`. """ lines = list(adk_lines) if not lines: return False if abs(float(total_gross or 0.0)) >= 0.01: return False return all( abs(float(l.qty or 0.0)) < 1e-9 and abs(float(l.revenue_sek or 0.0)) < 0.005 for l in lines )
def _freight_row_fields(kind: str, amount: float, fa: str) -> dict: """Column values that distinguish the two header-freight row kinds.""" if kind == ROW_SOURCE_CANCELLED_FREIGHT: return { 'row_source': ROW_SOURCE_CANCELLED_FREIGHT, 'account_number': fa, 'description': f'Freight on cancelled invoice (Excl.VAT − Gross) — cost, not invoiced ({fa})', 'revenue_sek': 0.0, 'unit_cost_sek': amount, 'unit_cost_fx': amount, 'margin_sek': -amount, } return { 'row_source': ROW_SOURCE_HEADER_FREIGHT, 'account_number': fa, 'description': f'Header freight gap (Excl.VAT − Gross) classified as {fa}', 'revenue_sek': amount, 'unit_cost_sek': 0.0, 'unit_cost_fx': 0.0, 'margin_sek': 0.0, }
def reclassify_header_freight(db: Session) -> int: """Re-derive every synthetic header-freight row ('header_freight' and 'cancelled_freight') with the current rules and rewrite the ones that differ: the freight account (`_freight_account_for`) and the row kind (`is_cancelled_invoice`). Idempotent and cheap (one pass over a few hundred rows), so it runs at every startup: a rule fix reaches invoices imported before the fix without waiting for a re-import. Returns the number of rows changed. """Re-derive the freight account of every synthetic 'header_freight' row with the current `_freight_account_for` rule and rewrite the ones that differ. Idempotent and cheap (one pass over a few hundred rows), so it runs at every startup: a rule fix reaches invoices imported before the fix without waiting for a re-import. Returns the number of rows changed. """ rows = db.query( models.InvoiceLine.id, models.InvoiceLine.invoice_number, models.InvoiceLine.account_number, models.InvoiceLine.row_source, models.InvoiceLine.revenue_sek, models.InvoiceLine.unit_cost_sek, ).filter(models.InvoiceLine.row_source.in_(FREIGHT_SYNTHETIC_SOURCES)).all() ).filter(models.InvoiceLine.row_source == 'header_freight').all() if not rows: return 0
inv_nums = sorted({r.invoice_number for r in rows}) accts_by_inv: dict[str, set[str]] = {} adk_by_inv: dict[str, list] = {} gross_by_inv: dict[str, float] = {} batch = 500 for i in range(0, len(inv_nums), batch): chunk = inv_nums[i:i + batch] q = db.query( models.InvoiceLine.invoice_number, models.InvoiceLine.account_number, models.InvoiceLine.qty, models.InvoiceLine.revenue_sek, ).filter( models.InvoiceLine.invoice_number.in_(chunk), models.InvoiceLine.row_source == 'adk', ) for r in q: if r.account_number: accts_by_inv.setdefault(r.invoice_number, set()).add(r.account_number) adk_by_inv.setdefault(r.invoice_number, []).append(r) for inv, gross in db.query( models.InvoiceHead.invoice_number, models.InvoiceHead.total_gross, ).filter(models.InvoiceHead.invoice_number.in_(chunk)): gross_by_inv[inv] = float(gross or 0.0) ).distinct() for inv, acct in q: if acct: accts_by_inv.setdefault(inv, set()).add(acct)
changed = 0 for r in rows: fa = _freight_account_for(accts_by_inv.get(r.invoice_number, set())) cancelled = is_cancelled_invoice(gross_by_inv.get(r.invoice_number), adk_by_inv.get(r.invoice_number, [])) kind = ROW_SOURCE_CANCELLED_FREIGHT if cancelled else ROW_SOURCE_HEADER_FREIGHT if kind == r.row_source and fa == r.account_number: if fa == r.account_number: continue # The amount lives in revenue_sek on an invoiced row and in # unit_cost_sek on a cancelled one. amount = float(r.revenue_sek or 0.0) if r.row_source == ROW_SOURCE_HEADER_FREIGHT else float(r.unit_cost_sek or 0.0) fields = _freight_row_fields(kind, amount, fa) db.query(models.InvoiceLine).filter(models.InvoiceLine.id == r.id).update({ getattr(models.InvoiceLine, k): v for k, v in fields.items() models.InvoiceLine.account_number: fa, models.InvoiceLine.description: f'Header freight gap (Excl.VAT − Gross) classified as {fa}', }, synchronize_session=False) changed += 1 if changed:5 unmodified lines """For each invoice_number, insert synthetic InvoiceLine rows so the line total matches the header's total_excl_vat exactly.
Four kinds of synthetic rows may be produced per invoice: Three kinds of synthetic rows may be produced per invoice: - 'header_freight' (Excl.VAT − Gross, classified into 3520/21/22) - 'cancelled_freight' (same gap on a cancelled invoice — a cost row, revenue_sek 0, amount in unit_cost_sek) - 'header_unallocated' (residual revenue without an ADK line) - 'rounding_adj' (final float-rounding close-out, <= 1 SEK each)
4 unmodified lines Returns a dict of counters for logging. """ if not invoice_numbers: return {"freight": 0, "cancelled": 0, "unallocated": 0, "rounding": 0} return {"freight": 0, "unallocated": 0, "rounding": 0}
# Defensive wipe — caller already deleted ADK lines for these invoices, # but an import that arrives without a lines file would leave stale32 unmodified lines .all()): lines_by_inv[l.invoice_number].append(l)
counts = {"freight": 0, "cancelled": 0, "unallocated": 0, "rounding": 0} counts = {"freight": 0, "unallocated": 0, "rounding": 0} to_add: list[models.InvoiceLine] = []
for inv_num in invoice_numbers:20 unmodified lines
if abs(freight_sek) >= 0.01: fa = _freight_account_for(accts) # A cancelled invoice (every line qty 0 / revenue 0, goods 0) # still carries its freight in Excl.VAT. Book it as a cost row, # not as invoiced freight — see ROW_SOURCE_CANCELLED_FREIGHT. adk_rows = [l for l in lines_by_inv.get(inv_num, []) if (l.row_source or 'adk') == 'adk'] cancelled = is_cancelled_invoice(head.total_gross, adk_rows) kind = ROW_SOURCE_CANCELLED_FREIGHT if cancelled else ROW_SOURCE_HEADER_FREIGHT to_add.append(models.InvoiceLine( invoice_number=inv_num, sku='[Freight/Dispatch]', description=f'Header freight gap (Excl.VAT − Gross) classified as {fa}', qty=0.0, unit_price_sek=0.0, unit_cost_sek=0.0, revenue_sek=freight_sek, margin_sek=0.0, date=inv_date, account_number=fa, invoice_type=inv_type, row_type='', **_freight_row_fields(kind, freight_sek, fa), row_source='header_freight', )) counts["cancelled" if cancelled else "freight"] += 1 counts["freight"] += 1
if abs(unallocated_sek) >= 0.01: to_add.append(models.InvoiceLine(404 unmodified lines "margin_ytd": safe_float(row.get("Margin_This_Year_SEK")), "last_invoice": (row.get("Last_Invoice_Date") or "").strip() or None, } # Kundkategori columns arrived with extractor v6.3 (1.3.70). # Older bundles don't carry them: leave the stored value # untouched instead of wiping it on every legacy re-import. if "Category_Code" in row: fields["category_code"] = (row.get("Category_Code") or "").strip() or None fields["category_name"] = (row.get("Category_Name") or "").strip() or None
existing = customer_by_id.get(cid) if existing is not None:462 unmodified lines db = _get_session() try: counts = _reconcile_synthetic_rows(db, invs_to_reconcile) total_synth = counts["freight"] + counts["cancelled"] + counts["unallocated"] + counts["rounding"] total_synth = counts["freight"] + counts["unallocated"] + counts["rounding"] logger.info( "reconcile synthetic rows: invoices=%d freight=%d cancelled=%d unallocated=%d rounding=%d", "reconcile synthetic rows: invoices=%d freight=%d unallocated=%d rounding=%d", len(invs_to_reconcile), counts["freight"], counts["cancelled"], counts["unallocated"], counts["rounding"], counts["freight"], counts["unallocated"], counts["rounding"], ) yield sse({"type": "step", "step": "reconcile", "status": "done", "label": ( f"Reconciled {len(invs_to_reconcile)} invoices — " f"{counts['freight']} freight, {counts['cancelled']} cancelled-invoice freight (cost), " f"{counts['unallocated']} unallocated, " f"{counts['freight']} freight, {counts['unallocated']} unallocated, " f"{counts['rounding']} rounding synthetic rows ✓" )}) except Exception:8 unmodified lines910111213141213141534 unmodified lines505152555657585953545550 unmodified lines1061071081161091101111129 unmodified lines12212312413213313413513613713812512612712812925 unmodified lines15515615717017117215815916016116216316410 unmodified lines1751761771921931781791801811821831842002011851861874 unmodified lines1921931942122132142151951961971981992212222002012023 unmodified lines20620720823223323423523623723820921021124221221321410 unmodified lines2252262272592602282292302632312322338 unmodified lines freight — rows on the freight accounts (3520–3590): adk lines PLUS the synthetic `header_freight` rows (freight charged only at header level, docs/gateway_visma_pipeline_reference.md §9.5) — matches the Revenue freight stream. `cancelled_freight` rows (the same header gap on a cancelled invoice) are listed too, but as a COST: revenue is null and the amount is in `cancelled_cost` — nothing was invoiced. freight stream.
Cost methodology — the values POSTED ON THE INVOICE, not a current estimate:
34 unmodified lines
# Margin exists only on real ADK rows; synthetic reconciliation rows have none._IS_ADK = models.InvoiceLine.row_source == "adk"# Header freight on a cancelled invoice (imports.ROW_SOURCE_CANCELLED_FREIGHT):# revenue_sek is 0 and the absorbed freight sits in unit_cost_sek.CANCELLED_FREIGHT = "cancelled_freight"_IS_CANCELLED_FREIGHT = models.InvoiceLine.row_source == CANCELLED_FREIGHT_CANCELLED_COST_EXPR = case((_IS_CANCELLED_FREIGHT, models.InvoiceLine.unit_cost_sek), else_=0.0)# Freight lines (3520–3590) carry no usable cost or margin either: the# "Freight cost" article 106 has a stale Visma kalkylpris (~5 000 SEK on a# 170 SEK charge) that turns every freight line into a −4.8k margin. The real50 unmodified lines q = q.filter(models.InvoiceLine.row_type.in_(_SERVICE_ROW_TYPES)) q = q.filter(models.InvoiceLine.account_number.in_(SERVICE_ACCTS)) elif scope == "freight": q = q.filter(models.InvoiceLine.row_source.in_(("adk", "header_freight", CANCELLED_FREIGHT))) q = q.filter(models.InvoiceLine.row_source.in_(("adk", "header_freight"))) q = q.filter(models.InvoiceLine.row_type.in_(_PRODUCT_ROW_TYPES)) q = q.filter(models.InvoiceLine.account_number.in_(FREIGHT_ACCTS)) else: # products9 unmodified lines # Visma exports include order-confirmation rows with nothing invoiced # (Qty_Delivered=0, Revenue=0 — only qty_ordered is set). Nothing was # billed, so they don't belong here. Discount rows (qty=0 but # revenue != 0) stay in: they move the margin. Cancelled-invoice freight # rows have neither (revenue is 0 by design) but carry a cost to show. q = q.filter(or_( models.InvoiceLine.qty != 0, models.InvoiceLine.revenue_sek != 0, _IS_CANCELLED_FREIGHT, )) # revenue != 0) stay in: they move the margin. q = q.filter(or_(models.InvoiceLine.qty != 0, models.InvoiceLine.revenue_sek != 0))
if customer_id: # Same-name expansion: one commercial customer spans several Visma ids.25 unmodified lines """ if line.date and line.date < MIN_DATE: return None src = line.row_source or "adk" if src == CANCELLED_FREIGHT: return "freight" # shown as a cost row on the Freight tab if not (line.qty or line.revenue_sek): return None # order confirmation — nothing was billed
src = line.row_source or "adk" acct = line.account_number row_type = line.row_type or ""
10 unmodified linesdef _compute_kpis(q) -> dict: """Single SQL aggregate pass over the filtered set.""" no_cost = func.coalesce(models.InvoiceLine.unit_cost_fx, 0.0) == 0.0 (line_count, revenue, margin, adk_revenue, invoice_count, no_cost_count, cancelled_cost, cancelled_count) = q.with_entities( (line_count, revenue, margin, adk_revenue, invoice_count, no_cost_count) = q.with_entities( func.count(models.InvoiceLine.id), func.coalesce(func.sum(models.InvoiceLine.revenue_sek), 0.0), func.coalesce(func.sum(case((_HAS_MARGIN, models.InvoiceLine.margin_sek), else_=0.0)), 0.0), func.coalesce(func.sum(case((_HAS_MARGIN, models.InvoiceLine.revenue_sek), else_=0.0)), 0.0), func.count(func.distinct(models.InvoiceLine.invoice_number)), func.coalesce(func.sum(case((no_cost, 1), else_=0)), 0), func.coalesce(func.sum(_CANCELLED_COST_EXPR), 0.0), func.coalesce(func.sum(case((_IS_CANCELLED_FREIGHT, 1), else_=0)), 0), ).one() return { "revenue": revenue,4 unmodified lines "line_count": line_count, "invoice_count": invoice_count, "no_cost_count": no_cost_count, # Freight absorbed on cancelled invoices (freight scope only) — a # cost, kept out of `revenue`. "cancelled_freight_cost": cancelled_cost, "cancelled_freight_count": cancelled_count, }
def line_values(line: models.InvoiceLine): """(unit_cost, margin, margin_pct) as posted — shared with the CSV export.""" if line.row_source == CANCELLED_FREIGHT: return None, None, None # cost row — see cancelled_cost() is_adk = (line.row_source or "adk") == "adk" has_margin = is_adk and line.account_number not in FREIGHT_ACCTS unit_cost = (line.unit_cost_fx or 0.0) if has_margin else 0.03 unmodified lines return (unit_cost if unit_cost != 0.0 else None), margin, pct
def cancelled_cost(line: models.InvoiceLine) -> Optional[float]: """Freight absorbed on a cancelled invoice, or None for every other row.""" if line.row_source != CANCELLED_FREIGHT: return None return float(line.unit_cost_sek or 0.0)
def _row_dict(line: models.InvoiceLine, cust_id, cust_name) -> dict: unit_cost, margin, pct = line_values(line) acct = line.account_number cancelled = cancelled_cost(line) return { "id": line.id, "date": line.date.date().isoformat() if line.date else None,10 unmodified lines "qty": line.qty, "unit_price": line.unit_price_sek, "unit_cost": unit_cost, # Nothing was invoiced on a cancelled invoice: revenue is null, not 0. "revenue": None if cancelled is not None else line.revenue_sek, "revenue": line.revenue_sek, "margin": margin, "margin_pct": pct, "cancelled_cost": cancelled, "category": CAT_MAP.get(acct) or FGT_CAT.get(acct), "account_number": acct, "row_source": line.row_source,55 unmodified lines565758595960616215 unmodified lines78798081828384858681828376 unmodified lines16016116216916316416516665 unmodified lines2322332342412352362372382392402472412422432442452532462472482496 unmodified lines25625725826625926026126226326427227327426526626726815 unmodified lines28428528629629729829928728828910 unmodified lines30030130231630330430530630732232332430830931031132831231331431531 unmodified lines34734834936635035135248 unmodified lines40140240342142242342442540440540640713 unmodified lines42142242344544644744842442542613 unmodified lines44044144246846947044344444555 unmodified lines CAT_MAP, FGT_CAT, FREIGHT_ACCTS, SERVICE_ACCTS, MIN_DATE, escape_like, related_customer_ids, resolve_date_window,)from routers.invoice_lines import CANCELLED_FREIGHT, cancelled_cost, ledger_scopefrom routers.invoice_lines import ledger_scope
router = APIRouter(prefix="/api/dashboard", tags=["Invoices"], dependencies=[Depends(get_current_user)])
15 unmodified lines_BALANCE_SEK = func.coalesce(models.InvoiceHead.balance_fx, 0.0) * _RATE
_IS_ADK = models.InvoiceLine.row_source == "adk"# Freight on a cancelled invoice is stored as a cost row (revenue_sek 0, the# amount in unit_cost_sek). It still explains the Visma header net — the# header keeps the freight after a makulering — so reconciliation counts it._IS_CANCELLED_FREIGHT = models.InvoiceLine.row_source == CANCELLED_FREIGHT_CANCELLED_COST = case((_IS_CANCELLED_FREIGHT, models.InvoiceLine.unit_cost_sek), else_=0.0)_EXPLAINED = func.coalesce(models.InvoiceLine.revenue_sek, 0.0) + func.coalesce(_CANCELLED_COST, 0.0)# Freight lines have no usable cost/margin (stale kalkylpris on article 106;# real carrier cost is GL 57xx) — see routers/invoice_lines._HAS_MARGIN._HAS_MARGIN = (_IS_ADK) & (76 unmodified lines per_invoice = ( q.with_entities( _NET.label("net"), func.coalesce(func.sum(_EXPLAINED), 0.0).label("line_sum"), func.coalesce(func.sum(models.InvoiceLine.revenue_sek), 0.0).label("line_sum"), ) .outerjoin(models.InvoiceLine, models.InvoiceLine.invoice_number == models.InvoiceHead.invoice_number)65 unmodified lines numbers = [h.invoice_number for h in heads] agg: dict = {} if numbers: for num, count, line_sum, line_margin, cancelled_sum in ( for num, count, line_sum, line_margin in ( db.query( models.InvoiceLine.invoice_number, func.count(models.InvoiceLine.id), func.coalesce(func.sum(models.InvoiceLine.revenue_sek), 0.0), func.coalesce(func.sum(case((_HAS_MARGIN, models.InvoiceLine.margin_sek), else_=0.0)), 0.0), func.coalesce(func.sum(_CANCELLED_COST), 0.0), ) .filter(models.InvoiceLine.invoice_number.in_(numbers)) .group_by(models.InvoiceLine.invoice_number) .all() ): agg[num] = (count, line_sum, line_margin, cancelled_sum) agg[num] = (count, line_sum, line_margin)
cust_ids = {h.customer_id for h in heads if h.customer_id} countries: dict = {}6 unmodified lines
rows = [] for h in heads: count, line_sum, line_margin, cancelled_sum = agg.get(h.invoice_number, (0, 0.0, 0.0, 0.0)) count, line_sum, line_margin = agg.get(h.invoice_number, (0, 0.0, 0.0)) net = h.total_excl_vat or 0.0 total = h.total_incl_vat or 0.0 margin = h.margin_sek or 0.0 rate = h.currency_rate or 1.0 balance = (h.balance_fx or 0.0) * (rate if rate > 0 else 1.0) # Cancelled-invoice freight is a cost row, not revenue — but it is # the reason the Visma header still shows a net, so it reconciles. diff = (line_sum + cancelled_sum) - net diff = line_sum - net rows.append({ "invoice_number": h.invoice_number, "date": h.date.date().isoformat() if h.date else None,15 unmodified lines "reconciled": abs(diff) <= RECONCILE_TOLERANCE, "balance": balance, "settled": abs(balance) <= SETTLED_TOLERANCE, # Cancelled in Visma (nothing delivered or billed); the freight # it still carries is booked as a cost, not as invoiced freight. "cancelled": abs(cancelled_sum) >= 0.01, "cancelled_freight_cost": cancelled_sum, })
return {10 unmodified linesdef _detail_row(line: models.InvoiceLine, supplier: Optional[str], item_id: Optional[int]) -> dict: is_adk = (line.row_source or "adk") == "adk" acct = line.account_number cancelled = cancelled_cost(line) # Freight lines: no cost, no margin (see invoice_lines._HAS_MARGIN). has_margin = is_adk and acct not in FREIGHT_ACCTS unit_cost = (line.unit_cost_fx or 0.0) if has_margin else 0.0 # kalkylpris — SEK despite the name qty = line.qty or 0.0 margin = line.margin_sek if has_margin else None # A cancelled invoice invoiced nothing: its freight row reports no # revenue at all (null, not 0) and carries the amount as `cancelled_cost`. revenue = None if cancelled is not None else line.revenue_sek revenue = line.revenue_sek scope = ledger_scope(line)
if not is_adk: stream = "freight" if line.row_source in ("header_freight", CANCELLED_FREIGHT) else "reconciliation" stream = "freight" if line.row_source == "header_freight" else "reconciliation" elif acct in SERVICE_ACCTS: stream = "service" elif acct in FREIGHT_ACCTS:31 unmodified lines "in_ledger": scope is not None, "ledger_scope": scope, "billed": bool(line.qty or line.revenue_sek), "cancelled_cost": cancelled, "supplier": supplier, "item_id": item_id, }48 unmodified lines cost_total = sum(r["cost_total"] or 0.0 for r in line_rows) margin_lines = sum(r["margin"] or 0.0 for r in line_rows) margin_header = head.margin_sek or 0.0 # Freight kept by Visma on a cancelled invoice: a cost row, but it is # what explains the header net, so the document still reconciles. cancelled_freight = sum(r["cancelled_cost"] or 0.0 for r in line_rows) is_cancelled = any(r["cancelled_cost"] is not None for r in line_rows) diff = (line_sum + cancelled_freight) - net diff = line_sum - net
return { "header": {13 unmodified lines "customer_country": customer.country if customer else None, "customer_currency": customer.currency if customer else None, "customer_is_export": bool(customer.is_export) if customer else None, # Cancelled in Visma (makulerad): nothing delivered or billed, no # ledger voucher. Derived from the lines — see # imports.is_cancelled_invoice. "is_cancelled": is_cancelled, }, "totals": { # Authoritative Visma header figures, all SEK.13 unmodified lines "dispatch_vat_code": head.dispatch_vat_code, # Cost & margin, as posted. "cost": cost_total, # Freight absorbed on a cancelled invoice (not in `cost`, which is # the kalkylpris of the lines, and never revenue). "cancelled_freight_cost": cancelled_freight, "margin_header": margin_header, "margin_lines": margin_lines, "margin_pct": (margin_header / net * 100.0) if net else None,443 unmodified lines44444544644744744844945010 unmodified lines46146246346446446546633 unmodified lines500501502504503504505506443 unmodified lines bl = sales_backlog(db=db) cm_by_order = dict( db.query(SalesOrder.order_number, SalesOrder.contribution_margin_sek) .filter(SalesOrder.delivered.isnot(True)) .filter(SalesOrder.delivered.isnot(True), SalesOrder.not_done.isnot(True)) .all() ) external = [o for o in bl["orders"] if not o["is_internal"]]10 unmodified lines "margin": _r(cm_by_order[o["order_number"]]) if cm_by_order.get(o["order_number"]) is not None else None, "seller": o["seller_code"], "not_finalised": o["not_finalised"], } for o in external ]33 unmodified lines offers_count, offers_value = ( db.query(func.count(Offer.offer_number), func.coalesce(func.sum(Offer.total_excl_vat_sek), 0.0)) .filter(func.coalesce(Offer.order_number, 0) == 0) .filter(Offer.not_done.isnot(True), func.coalesce(Offer.order_number, 0) == 0) .one() )
48 unmodified lines49505152535253545556575958596061672 unmodified lines73473573673873773873974048 unmodified linesdef _open_po_rows(db: Session) -> list[dict]: """One dict per open PO with received/remaining derived from its lines.
Open = not flagged delivered. Cancelled POs are skipped by the extractor; ``not_done`` is Visma's "Ej klar" (not finalised), still an open PO. ``remaining_sek`` Open = not flagged delivered and not voided (not_done). ``remaining_sek`` is a pro-rata of each line's SEK amount by undelivered quantity; rows without a quantity (services, fees) count in full until the PO closes. """ heads = ( db.query(PurchaseOrder) .filter(PurchaseOrder.delivered.isnot(True)) .filter(PurchaseOrder.delivered.isnot(True), PurchaseOrder.not_done.isnot(True)) .all() ) if not heads:672 unmodified lines .filter(PurchaseOrderLine.sku == sku) .all() ): if head.delivered or (ln.row_type or "") != "": if head.not_done or head.delivered or (ln.row_type or "") != "": continue ordered = ln.qty_ordered or 0.0 delivered = ln.qty_delivered or 0.04 unmodified lines56789101112891011121318191415161746 unmodified lines646566726768697039 unmodified lines11011111211811311411539 unmodified lines15515615716415815916016112 unmodified lines174175176183177178179180426 unmodified lines60760860961661061161261332 unmodified lines6466476486556496506516524 unmodified linesSQLite in tests behaves exactly like Postgres in prod).
Semantics validated against the real Visma CSVs (2026-08-21/25):- Open order = not flagged delivered. Cancelled documents never reach the bundle (the extractor skips ADK_OOI_HEAD_DOCUMENT_CANCELLED); ``not_done`` is Visma's "Ej klar" (not finalised / not print-ready) — a real, open commitment that must stay in the backlog (Beyond Technology 4880-4883, 2026-09-08: 1.95 MSEK hidden by treating it as voided). Backlog value comes- Open order = not delivered and not voided (not_done). Backlog value comes from the HEAD total (total_excl_vat_sek) — line sums differ only by cargo, and package/structure rows carry no meaningful double count.- Internal orders (customer 'P'/Produktion, is_internal at import) have no prices — they are tracked by count/quantity, not value.- Sales order lines: Q1 = delivered, Q2 = ordered (mirror of purchase rows).- Offers: open = not yet linked to an order (order_number 0); "Ej klar" offers are still open offers.- Offers: open = not voided and not yet linked to an order (order_number 0).- Agreements: head total equals the line sum; value is per billing cycle — annualised = cycle value x 12 / interval_months.- Customer payments carry no voided rows in practice; negative amounts are46 unmodified lines today = _today() heads = ( db.query(SalesOrder) .filter(SalesOrder.delivered.isnot(True)) .filter(SalesOrder.delivered.isnot(True), SalesOrder.not_done.isnot(True)) .all() ) numbers = [h.order_number for h in heads]39 unmodified lines "status": status, "days_late": days_late, "is_internal": bool(h.is_internal), "not_finalised": bool(h.not_done), "seller_code": h.seller_code or None, }) order_rank = {"late": 0, "due_soon": 1, "to_invoice": 2, "on_track": 3, "no_date": 4}39 unmodified lines
open_rows = [] for o in all_offers: if (o.order_number or 0) > 0: if o.not_done or (o.order_number or 0) > 0: continue expired = bool(o.valid_until and o.valid_until < today) open_rows.append({12 unmodified lines open_rows.sort(key=lambda r: -(r["total_sek"]))
# Conversion inside the window: offers issued in the window that became orders. issued = [o for o in all_offers if o.offer_date and o.offer_date >= floor] issued = [o for o in all_offers if o.offer_date and o.offer_date >= floor and not o.not_done] converted = [o for o in issued if (o.order_number or 0) > 0]
return {426 unmodified lines .filter(SalesOrderLine.sku == sku) .all() ): if head.delivered or ln.is_package or ln.is_structure: if head.delivered or head.not_done or ln.is_package or ln.is_structure: continue ordered = ln.qty_ordered or 0.0 # Q2 on sales rows delivered = ln.qty_delivered or 0.0 # Q1 on sales rows32 unmodified lines .filter(OfferLine.sku == sku) .all() ): if (head.order_number or 0) > 0: if head.not_done or (head.order_number or 0) > 0: continue qty = ln.qty_offered or 0.0 offers_out.append({248 unmodified lines249250251252253252253254248 unmodified lines country: Optional[str] currency: Optional[str] is_export: bool category_code: Optional[str] = None category_name: Optional[str] = None revenue_ytd: float margin_ytd: float last_invoice: Optional[str]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Customer category (Visma Kundkategori) + ABC classification (1.3.70).
Finance's rule: A = customers making up ~80% of revenue, B = next 15%,C = last 5%. Computed per customer row and per category so a chain's manystore accounts rank as one commercial account."""from datetime import datetimefrom io import BytesIO
from fastapi.testclient import TestClient
import mainimport models
def _inv(db, number, customer_id, name, revenue, inv_type="F"): db.add(models.InvoiceHead( invoice_number=number, date=datetime(2025, 3, 1), customer_id=customer_id, customer_name=name, total_excl_vat=revenue if inv_type == "F" else -revenue, invoice_type=inv_type, currency_code="SEK", currency_rate=1.0, ))
def _seed(db): # ICA chain: 3 stores, small individually, big as a category. for i in range(1, 4): db.add(models.Customer(id=f"ICA{i}", name=f"ICA Store {i}", category_code="20", category_name="ICA")) db.add(models.Customer(id="BIG", name="Big Distributor", category_code="23", category_name="Distributers")) # Category 1 "Sverige" is Visma's catch-all, not a chain: stands alone. db.add(models.Customer(id="SMALL", name="Tiny Shop", category_code="1", category_name="Sverige")) _inv(db, "I1", "ICA1", "ICA Store 1", 300.0) _inv(db, "I2", "ICA2", "ICA Store 2", 300.0) _inv(db, "I3", "ICA3", "ICA Store 3", 300.0) _inv(db, "I4", "BIG", "Big Distributor", 500.0) _inv(db, "K1", "BIG", "Big Distributor", 100.0, inv_type="K") # credit note _inv(db, "I5", "SMALL", "Tiny Shop", 100.0) db.commit()
def test_customer_rows_carry_category_and_abc(client: TestClient): db = main._get_session() try: _seed(db) finally: db.close()
resp = client.get("/api/dashboard/analytics?period=all") assert resp.status_code == 200 rev = resp.json()["revenue"] rows = {c["name"]: c for c in rev["customers"]}
# Total = 900 + 400 + 100 = 1400 (credit note deducted). assert rev["customer_abc"]["total_revenue"] == 1400.0 assert rows["Big Distributor"]["revenue"] == 400.0 assert rows["Big Distributor"]["category"] == "Distributers" assert rows["ICA Store 1"]["category_code"] == "20" assert rows["Tiny Shop"]["category"] == "Sverige"
# Per customer: 400 (28.6%) → A, 300 (50%) → A, 300 (71.4%) → A, # 300 crosses 80 → still A (cum before = 71.4), 100 → C (cum before 92.9 → B). assert rows["Big Distributor"]["abc_class"] == "A" assert rows["ICA Store 3"]["abc_class"] == "A" assert rows["Tiny Shop"]["abc_class"] == "B" assert rows["Tiny Shop"]["cumulative_share_pct"] == 100.0 assert rev["customer_abc"]["counts_customer"] == {"A": 4, "B": 1, "C": 0}
def test_category_level_abc_groups_chain_stores(client: TestClient): db = main._get_session() try: _seed(db) finally: db.close()
rev = client.get("/api/dashboard/analytics?period=all").json()["revenue"] cats = rev["customer_categories"] # A customer without a category is its own account in this ranking. assert [c["category"] for c in cats] == ["ICA", "Distributers", "Tiny Shop"] ica, dist, tiny = cats assert ica["revenue"] == 900.0 and ica["customers"] == 3 and ica["invoices"] == 3 assert ica["is_category"] is True assert ica["abc_class"] == "A" # 64.3% cumulative assert dist["abc_class"] == "A" # crosses 80 (cum before = 64.3) assert tiny["abc_class"] == "B" # cum before = 92.9 assert tiny["category_code"] is None and tiny["is_category"] is False assert tiny["customers"] == 1 assert rev["customer_abc"]["counts_category"] == {"A": 2, "B": 1, "C": 0} assert rev["customer_abc"]["category_count"] == 2 assert rev["customer_abc"]["account_count"] == 3 assert rev["customer_abc"]["uncategorised_customers"] == 0
# Each customer row also carries the class of its category. rows = {c["name"]: c for c in rev["customers"]} assert rows["ICA Store 2"]["category_abc_class"] == "A" assert rows["Tiny Shop"]["category_abc_class"] == "B"
def test_customers_export_has_category_and_abc_columns(client: TestClient): db = main._get_session() try: _seed(db) finally: db.close()
resp = client.get("/api/export/analytics/customers?period=all") assert resp.status_code == 200 body = resp.content.decode("utf-8-sig") header = next(l for l in body.splitlines() if l.startswith("Customer_ID")) for col in ("Category", "ABC_Class", "ABC_Class_Category", "Cumulative_Pct"): assert col in header, header assert "Distributers" in body
def test_import_reads_category_columns_and_keeps_them_on_legacy_bundle(job_client): from conftest import poll_import_job
csv_new = ( "Customer_ID;Name;Country;Currency_Code;Category_Code;Category_Name\n" "C1;Alpha;SE;SEK;20;ICA\n" ).encode("utf-8-sig") r = job_client.post("/api/import/visma", files={ "customers_file": ("dim_customers.csv", BytesIO(csv_new), "text/csv"), }, data={"author": "tester"}) assert r.status_code == 200, r.text poll_import_job(job_client, r.json()["job_id"])
db = main._get_session() try: c = db.query(models.Customer).get("C1") assert (c.category_code, c.category_name) == ("20", "ICA") finally: db.close()
# A bundle from the old extractor (no category columns) must not wipe it. csv_old = ("Customer_ID;Name;Country;Currency_Code\nC1;Alpha renamed;SE;SEK\n").encode("utf-8-sig") r = job_client.post("/api/import/visma", files={ "customers_file": ("dim_customers_old.csv", BytesIO(csv_old), "text/csv"), }, data={"author": "tester"}) assert r.status_code == 200, r.text poll_import_job(job_client, r.json()["job_id"]) db = main._get_session() try: c = db.query(models.Customer).get("C1") assert c.name == "Alpha renamed" assert (c.category_code, c.category_name) == ("20", "ICA") finally: db.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""ETL package distribution (1.3.74): the backend packs etl/ runtime filesfor the on-prem agent, which self-updates from /api/etl/agent/package."""import hashlibimport ioimport zipfile
import pytestfrom fastapi.testclient import TestClient
import etl_package
@pytest.fixturedef fake_etl(tmp_path, monkeypatch): src = tmp_path / "etl" src.mkdir() (src / "visma_unified_extractor.py").write_bytes(b"print('extract v1')\n") (src / "sync_to_hf.py").write_bytes(b"print('sync')\n") (src / "force_sync_agent.py").write_bytes(b"print('agent')\n") (src / "requirements.txt").write_bytes(b"requests\n") monkeypatch.setenv("ETL_PACKAGE_DIR", str(src)) etl_package.reset_cache() yield src etl_package.reset_cache()
def test_build_package_is_deterministic_and_versioned_by_content(fake_etl): a = etl_package.build_package(fake_etl) b = etl_package.build_package(fake_etl) assert a is not None and b is not None assert a.version == b.version and len(a.version) == 12 assert a.zip_sha256 == b.zip_sha256 # byte-identical zips assert {f["path"] for f in a.files} == { "visma_unified_extractor.py", "sync_to_hf.py", "force_sync_agent.py", "requirements.txt"}
(fake_etl / "visma_unified_extractor.py").write_bytes(b"print('extract v2')\n") c = etl_package.build_package(fake_etl) assert c.version != a.version
with zipfile.ZipFile(io.BytesIO(c.zip_bytes)) as zf: assert zf.read("visma_unified_extractor.py") == b"print('extract v2')\n" assert all("/" not in n for n in zf.namelist())
def test_build_package_returns_none_without_source(tmp_path): assert etl_package.build_package(tmp_path / "nope") is None
def test_agent_poll_carries_package_and_download_matches_manifest(client: TestClient, fake_etl): r = client.get("/api/etl/agent/next?host=visma-srv") assert r.status_code == 200 body = r.json() assert body["request"] is None version = body["etl_package"]["version"] assert body["etl_package"]["files"] == 4
m = client.get("/api/etl/agent/package/manifest").json() assert m["version"] == version assert "force_sync_agent.py" in m["restart_files"]
d = client.get("/api/etl/agent/package") assert d.status_code == 200 assert d.headers["X-Package-Version"] == version assert hashlib.sha256(d.content).hexdigest() == d.headers["X-Package-SHA256"] == m["zip_sha256"] assert d.headers["content-type"].startswith("application/zip")
def test_agent_reports_applied_version_and_status_shows_up_to_date(client: TestClient, fake_etl): version = client.get("/api/etl/agent/next").json()["etl_package"]["version"]
st = client.get("/api/etl/force-sync/status").json()["agent"]["package"] assert st["server_version"] == version assert st["agent_version"] is None and st["up_to_date"] is None
r = client.post("/api/etl/agent/package/applied", json={ "version": "old000000000", "status": "applied", "previous_version": None, "host": "visma-srv"}) assert r.status_code == 200 st = client.get("/api/etl/force-sync/status").json()["agent"]["package"] assert st["agent_version"] == "old000000000" and st["up_to_date"] is False
r = client.post("/api/etl/agent/package/applied", json={ "version": version, "status": "applied", "previous_version": "old000000000", "host": "visma-srv", "requirements_changed": True}) assert r.status_code == 200 st = client.get("/api/etl/force-sync/status").json()["agent"]["package"] assert st["up_to_date"] is True and st["status"] == "applied"
r = client.post("/api/etl/agent/package/applied", json={ "version": version, "status": "error", "previous_version": version, "error": "disk full"}) assert r.status_code == 200 st = client.get("/api/etl/force-sync/status").json()["agent"]["package"] assert st["status"] == "error" and st["error"] == "disk full" assert st["agent_version"] == version # an error doesn't lose the last good version
health = client.get("/api/admin/system-health").json() assert health["etl_agent"]["package"]["server_version"] == version
def test_package_endpoints_404_without_source(client: TestClient, tmp_path, monkeypatch): monkeypatch.setenv("ETL_PACKAGE_DIR", str(tmp_path / "missing")) etl_package.reset_cache() try: assert client.get("/api/etl/agent/package").status_code == 404 assert client.get("/api/etl/agent/next").json()["etl_package"] is None finally: etl_package.reset_cache()83 unmodified lines848586878788899052 unmodified lines14314414514614714614714814915060 unmodified lines21121221321421521421521621721821922022122222022122222383 unmodified lines SalesOrder(order_number=5001, customer_id="AC", customer_name="ACME", delivery_date=date(2030, 1, 15), total_excl_vat_sek=900.0, contribution_margin_sek=300.0, seller_code="JS"), SalesOrder(order_number=5002, customer_name="DRAFT", not_done=True, # Ej klar: still open SalesOrder(order_number=5002, customer_name="VOID", not_done=True, total_excl_vat_sek=999.0), SalesOrder(order_number=5003, customer_name="DONE", delivered=True, total_excl_vat_sek=999.0),52 unmodified lines assert k["revenue_prev"] == 850.0 # 800 invoiced + 50 accrual assert k["margin_prev"] == 300.0 assert k["invoices_prev"] == 1 assert k["backlog_value"] == 1999.0 # incl. the not-finalised order assert k["offers_open_value"] == 1249.0 # incl. the not-finalised offer assert k["backlog_value"] == 1000.0 assert k["offers_open_value"] == 250.0
def test_month_filter_scopes_kpis_and_splits(client: TestClient):60 unmodified lines
def test_backlog_orders_and_family_split(client: TestClient): bl = _get(_seeded(client))["backlog"] assert bl["kpis"]["count"] == 3 # delivered/internal out, Ej klar in assert bl["kpis"]["value"] == 1999.0 assert bl["kpis"]["count"] == 2 # voided/delivered/internal out assert bl["kpis"]["value"] == 1000.0 assert bl["kpis"]["overdue_value"] == 100.0 assert bl["kpis"]["internal_count"] == 1
orders = {o["order_number"]: o for o in bl["orders"]} assert set(orders) == {5001, 5002, 5005} assert orders[5002]["status"] == "no_date" and orders[5002]["not_finalised"] is True assert orders[5001]["not_finalised"] is False assert set(orders) == {5001, 5005} o = orders[5001] assert (o["customer"], o["month"], o["status"], o["value"], o["margin"]) == \ ("ACME", "2030-01", "on_track", 900.0, 300.0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Portable DB snapshot — the admin download that works on Postgres too.
run_backup() is SQLite-only by design (it uses sqlite3's online-backup API onthe live file), so /api/admin/backup/download answered 503 for the whole lifeof the Postgres deployment. build_portable_snapshot() is the other half: itstreams every table of whatever database is live into a fresh SQLite file.
Protocol coverage: - positive: rows land in the snapshot, JSON survives the round trip, and the endpoint serves a file when the SQLite fast path is unavailable. - edge: the live DB missing a column the models declare (a snapshot taken one migration behind) still produces a usable file."""import datetimeimport sqlite3
import sqlalchemy as safrom fastapi.testclient import TestClient
import backupimport main # noqaimport models
def _live_engine(): """The engine the test fixtures actually bound the app to.""" db = main._get_session() try: return db.get_bind() finally: db.close()
def _seed(db): db.add(models.Item(sku="SNAP-1", name="Snapshot item", type="RAW", stock_value_sek=10.0)) db.add(models.GLEntry( year_id="D", voucher_number="1", voucher_row=1, voucher_series="A", date=datetime.datetime(2026, 7, 31), account_number="1400", amount_sek=100.0, description="Artnr: SNAP-1", )) # The one JSON column in the schema — the type most likely to be mangled. db.add(models.EventLog(action="TEST", author="pytest", changes={"ip": "10.0.0.1"})) db.commit()
def test_snapshot_copies_rows_and_preserves_json(client: TestClient, tmp_path, monkeypatch): db = main._get_session() try: _seed(db) finally: db.close()
# The snapshot reads whatever engine is live. Take it from the app's own # session rather than re-importing conftest: pytest already imported that # module, and importing it again under a second name builds a second # in-memory engine — a different, empty database. monkeypatch.setattr(backup.database, "engine", _live_engine())
dest = tmp_path / "snap.db" out = backup.build_portable_snapshot(dest) assert out.exists() and out.stat().st_size > 0
con = sqlite3.connect(str(out)) try: assert con.execute("PRAGMA quick_check").fetchone()[0] == "ok" assert con.execute("SELECT COUNT(*) FROM items").fetchone()[0] == 1 assert con.execute("SELECT COUNT(*) FROM gl_entries").fetchone()[0] == 1 assert con.execute("SELECT sku FROM items").fetchone()[0] == "SNAP-1" # Encoded exactly once — a double-encoded value would come back as a # JSON string wrapping a JSON string. raw = con.execute("SELECT changes FROM event_logs WHERE action='TEST'").fetchone()[0] assert raw == '{"ip": "10.0.0.1"}', f"JSON not round-tripped cleanly: {raw!r}" finally: con.close()
def test_snapshot_survives_a_live_db_missing_a_column(client: TestClient, tmp_path, monkeypatch): """A live database one migration behind the models must still snapshot.
Selecting the model's columns blindly fails with "no such column" — the copy takes the intersection with what the live DB actually has instead. """ db = main._get_session() try: _seed(db) finally: db.close()
live = _live_engine() with live.begin() as conn: conn.execute(sa.text("ALTER TABLE gl_entries DROP COLUMN quantity")) monkeypatch.setattr(backup.database, "engine", live)
dest = tmp_path / "drifted.db" out = backup.build_portable_snapshot(dest)
con = sqlite3.connect(str(out)) try: assert con.execute("PRAGMA quick_check").fetchone()[0] == "ok" assert con.execute("SELECT COUNT(*) FROM gl_entries").fetchone()[0] == 1 # The column the live DB lacked is present but empty, not missing. assert con.execute("SELECT quantity FROM gl_entries").fetchone()[0] is None finally: con.close()
def test_download_falls_back_to_the_portable_snapshot(client: TestClient, monkeypatch): """On Postgres run_backup() returns None; the endpoint must serve a file rather than the 503 it used to.""" db = main._get_session() try: _seed(db) finally: db.close()
monkeypatch.setattr(backup, "run_backup", lambda *a, **k: None) monkeypatch.setattr(backup.database, "engine", _live_engine())
r = client.get("/api/admin/backup/download") assert r.status_code == 200, r.text assert r.headers["content-type"] == "application/octet-stream" assert "inventory-" in r.headers.get("content-disposition", "") assert len(r.content) > 0
def test_download_reports_a_failure_instead_of_a_broken_file(client: TestClient, monkeypatch): """If the snapshot cannot be built the endpoint says so — it must never hand back a truncated database.""" monkeypatch.setattr(backup, "run_backup", lambda *a, **k: None)
def boom(*a, **k): raise RuntimeError("disk full") monkeypatch.setattr(backup, "build_portable_snapshot", boom)
r = client.get("/api/admin/backup/download") assert r.status_code == 503 assert "snapshot" in r.json()["detail"].lower()39 unmodified lines404142434443444546128 unmodified lines17517617717918017817918018118214 unmodified lines1971981992012002012032042022032042054 unmodified lines21021121221521621321421521621739 unmodified lines Supplier(supplier_id="S3", name="Gone Oy", inactive=True), ])
# POs: 100 late/partial, 101 due soon, 102 delivered, 103 not finalised # (Ej klar — still open), 104 undated/complete-qty. # POs: 100 late/partial, 101 due soon, 102 delivered, 103 voided, 104 undated/complete-qty. db.add_all([ PurchaseOrder(po_number=100, supplier_id="S1", supplier_name="Alpha AB", order_date=_d(-30), delivery_date=_d(-10), currency_code="EUR",128 unmodified lines assert r.status_code == 200 data = r.json()
assert data["open_pos"]["count"] == 4 assert data["open_pos"]["value_sek"] == 25888.0 assert data["open_pos"]["count"] == 3 assert data["open_pos"]["value_sek"] == 17000.0 # PO100: 10000*(1-5/10) + fee 1000 = 6000; PO101: 4000; PO104: 0. assert data["open_pos"]["remaining_sek"] == 10000.0 assert data["open_pos"]["overdue_count"] == 114 unmodified lines r = client.get("/api/procurement/open-orders") assert r.status_code == 200 data = r.json() assert data["count"] == 4 assert data["count"] == 3 by_number = {o["po_number"]: o for o in data["orders"]} assert set(by_number) == {100, 101, 103, 104} assert by_number[103]["status"] == "due_soon" # Ej klar PO is still open assert set(by_number) == {100, 101, 104}
po100 = by_number[100] assert po100["status"] == "late" and po100["days_late"] == 104 unmodified lines assert by_number[104]["status"] == "received" assert by_number[104]["received_pct"] == 100.0
# Urgency order: late → due_soon (by date) → received. assert [o["po_number"] for o in data["orders"]] == [100, 101, 103, 104] # Urgency order: late → due_soon → no_date. assert [o["po_number"] for o in data["orders"]] == [100, 101, 104]
def test_ap_aging_buckets(client):43 unmodified lines4445464748474849116 unmodified lines1661671681711691701711721 unmodified line1741751761791801811821771781791803 unmodified lines1841851861921871881891901 unmodified line192193194200201202203204195196197198199200201118 unmodified lines32032132232932332432532632732832933633033133233362 unmodified lines39639739840540640739940040140240340441140540640740840941641741041141241342042141441541642341741841942043 unmodified lines SalesOrder(order_number=4, customer_id="C1", customer_name="Acme AB", delivered=True, not_done=False, is_internal=False, total_excl_vat_sek=77777.0), # "Ej klar" (not finalised) in Visma — still an open order, never voided # (cancelled documents are skipped by the extractor). SalesOrder(order_number=5, customer_id="C2", customer_name="Beta Oy", delivered=False, not_done=True, is_internal=False, total_excl_vat_sek=88888.0),116 unmodified lines data = r.json()
assert data["external"] == { "count": 5, "value_sek": 288888.0, "count": 4, "value_sek": 200000.0, "overdue_count": 1, "overdue_value_sek": 100000.0, "due_7d_value_sek": 50000.0, "to_invoice_count": 1, "to_invoice_value_sek": 20000.0,1 unmodified line assert data["internal"] == {"count": 1, "overdue_count": 1}
by_number = {o["order_number"]: o for o in data["orders"]} assert set(by_number) == {1, 2, 3, 5, 6, 7} # Not-finalised (Ej klar) order stays in the book, flagged for the UI. assert by_number[5]["status"] == "no_date" and by_number[5]["not_finalised"] is True assert by_number[1]["not_finalised"] is False assert set(by_number) == {1, 2, 3, 6, 7} assert by_number[1]["status"] == "late" and by_number[1]["days_late"] == 5 assert by_number[1]["delivered_pct"] == 40.0 # package/structure rows ignored assert by_number[2]["status"] == "due_soon"3 unmodified lines assert by_number[7]["status"] == "to_invoice" assert by_number[7]["delivered_pct"] == 100.0 # Externals first (urgency order), internals last. assert [o["order_number"] for o in data["orders"]] == [1, 2, 7, 3, 5, 6] assert [o["order_number"] for o in data["orders"]] == [1, 2, 7, 3, 6]
def test_offers_pipeline_and_conversion(client):1 unmodified line r = client.get("/api/sales/offers") assert r.status_code == 200 data = r.json() # Offer 14 is "Ej klar" (not finalised) — still an open offer. assert data["open"] == {"count": 3, "value_sek": 34999.0, "expired_count": 1} # Window (365d): offers 11, 12, 13, 14 issued; only 13 converted. assert data["conversion"] == {"issued": 4, "converted": 1, "rate_pct": 25.0} assert [o["offer_number"] for o in data["offers"]] == [11, 14, 12] # by value desc assert data["open"] == {"count": 2, "value_sek": 25000.0, "expired_count": 1} # Window (365d): offers 11, 12, 13 issued; only 13 converted. assert data["conversion"] == {"issued": 3, "converted": 1, "rate_pct": 33.3} assert [o["offer_number"] for o in data["offers"]] == [11, 12] # by value desc
def test_receivables_aging_and_payment_behaviour(client):118 unmodified lines # Internal Produktion order: quantity only, no value. SalesOrderLine(order_number=6, row_number=1, sku="A", row_type="", qty_ordered=3.0, qty_delivered=0.0, amount_sek=0.0), # Delivered order must not show as backlog; the not-finalised one must. # Delivered order and voided order must not show as backlog. SalesOrderLine(order_number=4, row_number=1, sku="A", row_type="", qty_ordered=5.0, qty_delivered=0.0, amount_sek=5000.0), SalesOrderLine(order_number=5, row_number=1, sku="A", row_type="", qty_ordered=5.0, qty_delivered=0.0, amount_sek=5000.0), ]) db.add_all([ # Offers 11 and 14 (not finalised) are open; 13 became an order. # Offer 11 is open; 13 became an order and 14 is voided. OfferLine(offer_number=11, row_number=3, sku="A", row_type="", qty_offered=5.0, unit_price_fx=1200.0, amount_sek=12000.0), OfferLine(offer_number=13, row_number=1, sku="A", row_type="",62 unmodified lines client = _item_client(client) data = client.get("/api/sales/items/A/sales").json()
# Open external orders (incl. the not-finalised one) and the internal one; # delivered out, and the package row never counts. assert [b["order_number"] for b in data["backlog"]] == [1, 5, 6] # Only the open external order and the internal one; delivered/voided out, # and the package row never counts. assert [b["order_number"] for b in data["backlog"]] == [1, 6] external = data["backlog"][0] assert external["qty_open"] == 6.0 and external["open_value_sek"] == 60000.0 assert external["status"] == "late" and external["days_late"] == 5 internal = data["backlog"][2] internal = data["backlog"][1] assert internal["is_internal"] and internal["qty_open"] == 3.0 assert internal["open_value_sek"] == 0.0 # Produktion rows carry no price
s = data["summary"] assert s["backlog_qty"] == 11.0 and s["backlog_value_sek"] == 65000.0 assert s["backlog_order_count"] == 2 and s["late_order_count"] == 1 assert s["backlog_qty"] == 6.0 and s["backlog_value_sek"] == 60000.0 assert s["backlog_order_count"] == 1 and s["late_order_count"] == 1 assert s["internal_backlog_qty"] == 3.0 and s["internal_order_count"] == 1
# Offers still open (not yet an order), newest first. assert [o["offer_number"] for o in data["offers"]] == [11, 14] # Only the offer that is still open (not voided, not yet an order). assert [o["offer_number"] for o in data["offers"]] == [11] assert data["offers"][0]["qty_offered"] == 5.0 assert s["offer_qty"] == 14.0 and s["offer_value_sek"] == 21999.0 and s["offer_count"] == 2 assert s["offer_qty"] == 5.0 and s["offer_value_sek"] == 12000.0 and s["offer_count"] == 1
def test_item_sales_history_unknown_sku(client):215 unmodified lines216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353219220221215 unmodified lines db.close()
def test_cancelled_invoice_freight_is_a_cost_row(client: TestClient): """Cancelled (makulerad) invoice: every ADK line qty 0 / revenue 0, goods 0, yet Visma keeps the freight in Excl.VAT. Expected: ONE 'cancelled_freight' row with revenue 0 and the amount in unit_cost_sek — the gap is explained, nothing is booked as invoiced freight. """ _seed_invoice( invoice_number='CAN-1', date=datetime(2026, 3, 18), total_excl_vat=1572.18, total_gross=0.0, adk_lines=[ {'sku': '420190-A', 'qty': 0.0, 'revenue_sek': 0.0, 'account_number': '3132'}, {'sku': '420030-B', 'qty': 0.0, 'revenue_sek': 0.0, 'account_number': '3132'}, ], ) db = main._get_session() try: counts = _reconcile_synthetic_rows(db, ['CAN-1']) assert counts['cancelled'] == 1 and counts['freight'] == 0 assert counts['unallocated'] == 0 and counts['rounding'] == 0 rows = db.query(models.InvoiceLine).filter_by(invoice_number='CAN-1').all() synth = [r for r in rows if r.row_source != 'adk'] assert len(synth) == 1 s = synth[0] assert s.row_source == 'cancelled_freight' assert s.sku == '[Freight/Dispatch]' assert s.revenue_sek == 0.0 assert s.unit_cost_sek == pytest.approx(1572.18, abs=0.01) assert s.margin_sek == pytest.approx(-1572.18, abs=0.01) assert s.account_number == '3522' # export mix (3132) → 3522 finally: db.close()
# Invoice detail: flagged, no revenue on the row, still reconciles. r = client.get('/api/dashboard/invoices/CAN-1') assert r.status_code == 200, r.text body = r.json() assert body['header']['is_cancelled'] is True assert body['totals']['line_sum'] == 0.0 assert body['totals']['cancelled_freight_cost'] == pytest.approx(1572.18, abs=0.01) assert body['totals']['reconciled'] is True assert body['totals']['cost'] == 0.0 # not mixed into the kalkylpris cost frt = [l for l in body['lines'] if l['sku'] == '[Freight/Dispatch]'][0] assert frt['revenue'] is None assert frt['cancelled_cost'] == pytest.approx(1572.18, abs=0.01) assert frt['stream'] == 'freight' and frt['in_ledger'] is True
# Invoice list: flagged and reconciled. r = client.get('/api/dashboard/invoices?period=all&search=CAN-1') row = [x for x in r.json()['rows'] if x['invoice_number'] == 'CAN-1'][0] assert row['cancelled'] is True assert row['reconciled'] is True assert r.json()['kpis']['unreconciled_count'] == 0
# Freight ledger tab: listed as a cost, never as invoiced freight. r = client.get('/api/dashboard/invoice-lines?period=all&scope=freight&search=CAN-1') data = r.json() assert [x['row_source'] for x in data['rows']] == ['cancelled_freight'] assert data['rows'][0]['revenue'] is None assert data['rows'][0]['cancelled_cost'] == pytest.approx(1572.18, abs=0.01) assert data['kpis']['revenue'] == 0.0 assert data['kpis']['cancelled_freight_cost'] == pytest.approx(1572.18, abs=0.01) assert data['kpis']['cancelled_freight_count'] == 1
# Revenue dashboard: out of invoiced freight, into the net result. import helpers helpers.invalidate_caches() r = client.get('/api/dashboard/analytics?period=all') fk = r.json()['freight']['kpis'] assert fk['freight_cancelled_cost_sek'] == pytest.approx(1572.18, abs=0.01) assert fk['freight_cancelled_invoices'] == 1 assert fk['freight_gap_sek'] == pytest.approx(0.0, abs=0.01) assert fk['freight_revenue_sek'] == pytest.approx(0.0, abs=0.01) assert fk['freight_net_sek'] == pytest.approx(-1572.18 - fk['freight_cost_sek'], abs=0.01)
def test_zero_lines_with_goods_is_not_cancelled(client: TestClient): """An invoice whose lines are all unbilled but whose header still has a goods value is NOT a cancellation — plain header freight as before.""" _seed_invoice( invoice_number='NC-1', date=datetime(2026, 3, 18), total_excl_vat=1170.0, total_gross=1000.0, adk_lines=[{'sku': 'P1', 'qty': 0.0, 'revenue_sek': 0.0, 'account_number': '3130'}], ) db = main._get_session() try: counts = _reconcile_synthetic_rows(db, ['NC-1']) assert counts['cancelled'] == 0 and counts['freight'] == 1 kinds = {r.row_source for r in db.query(models.InvoiceLine).filter_by(invoice_number='NC-1')} assert 'header_freight' in kinds and 'cancelled_freight' not in kinds finally: db.close()
def test_reclassify_flips_header_freight_to_cancelled_cost(client: TestClient): """Rows imported before the rule existed are converted at startup.""" from routers.imports import reclassify_header_freight _seed_invoice( invoice_number='RC-CAN', date=datetime(2026, 4, 20), total_excl_vat=3963.0, total_gross=0.0, adk_lines=[{'sku': 'P1', 'qty': 0.0, 'revenue_sek': 0.0, 'account_number': '3112'}], ) db = main._get_session() try: # Legacy row: booked as invoiced freight. db.add(models.InvoiceLine( invoice_number='RC-CAN', sku='[Freight/Dispatch]', description='Header freight gap (Excl.VAT − Gross) classified as 3522', qty=0, unit_price_sek=0, unit_cost_sek=0, revenue_sek=3963.0, margin_sek=0, date=datetime(2026, 4, 20), account_number='3522', invoice_type='F', row_type='', row_source='header_freight', )) db.commit()
assert reclassify_header_freight(db) == 1 row = db.query(models.InvoiceLine).filter_by(invoice_number='RC-CAN', sku='[Freight/Dispatch]').one() assert row.row_source == 'cancelled_freight' assert row.revenue_sek == 0.0 assert row.unit_cost_sek == pytest.approx(3963.0) assert row.account_number == '3522' assert 'cancelled' in row.description # Idempotent. assert reclassify_header_freight(db) == 0 finally: db.query(models.InvoiceLine).filter_by(invoice_number='RC-CAN').delete() db.query(models.InvoiceHead).filter_by(invoice_number='RC-CAN').delete() db.commit() db.close()
def test_header_freight_synthesis_closes_gap(client: TestClient): """Invoice where Excl.VAT exceeds Gross by 100 SEK (= freight gap). Expected: one synthetic 'header_freight' row with revenue_sek=100 and262 unmodified lines263264265266267268269270271272273266267268269277278270271272273262 unmodified lines assert "attachment" in r.headers.get("content-disposition", "")
def test_backup_download_falls_back_when_sqlite_path_unavailable(client, monkeypatch): """run_backup() returning None no longer means 503.
That is the normal state on Postgres (the nightly SQLite online-backup cannot run there), and since 1.3.75 the endpoint builds a portable snapshot instead. 503 is now reserved for a snapshot that genuinely failed — covered in tests/test_portable_snapshot.py. """def test_backup_download_503_when_unavailable(client, monkeypatch): import backup as backup_module monkeypatch.setattr(backup_module, "run_backup", lambda: None) r = client.get("/api/admin/backup/download") assert r.status_code == 200 assert r.headers["content-type"] == "application/octet-stream" assert r.status_code == 503
def test_backfill_covers_mvp2_registers(client):423 unmodified lines424425426427427428429423 unmodified lines
When `freight_gap > 0.01 SEK`:- **`[Freight/Dispatch]`** rows (green) — freight portion, account code derived from other lines on the same invoice - On a **cancelled** invoice (every ADK line qty 0 / revenue 0, `Head_Gross_FX` 0 — Visma's makulering zeroes the rows but leaves the freight in `Head_Total_Excl_VAT_FX`, and no ledger voucher is posted) the same gap is stored as a `cancelled_freight` row instead of `header_freight`: `revenue_sek = 0`, the amount in `unit_cost_sek`. It is a cost the company absorbed, never invoiced freight (`imports.is_cancelled_invoice`, since 1.3.70). Existing rows are re-kinded at startup by `reclassify_header_freight`.- **`[Unallocated]`** rows (yellow) — any remaining residual representing revenue that ADK cannot expose at line level- **`[Rounding]`** — one row per workbook closing floating-point accumulation from FX conversions
219 unmodified lines220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260223224225219 unmodified linesLogs em `etl\logs\agent-YYYY-MM-DD.log`. Remover:`schtasks /Delete /TN "GatewayERP-ForceSyncAgent" /F`.
## Atualização automática dos scripts (v1.3.74, 08/09/2026)
O app distribui os scripts desta pasta para o servidor do Visma — não émais preciso VPN + copy/paste a cada mudança no extrator.
Como funciona:
1. A imagem do app leva `etl/` junto com `backend/`. No boot, `backend/etl_package.py` empacota os arquivos de execução (`visma_unified_extractor.py`, `sync_to_hf.py`, `force_sync_agent.py`, `adk_*.py`, `build_gateway_*.py`, `requirements.txt`) num zip com versão = hash do conteúdo (12 hex). Setup único do servidor (`set_token.ps1`, `setup_python_env.ps1`, `install_*.cmd`, `run_daily.ps1`) **nunca** é distribuído.2. Toda resposta de `GET /api/etl/agent/next` traz `etl_package.version`. O agente compara com `etl/.etl_package_version`; se diferir e não houver request em andamento, baixa `GET /api/etl/agent/package`, confere o `X-Package-SHA256`, grava cada arquivo via temp + `os.replace`, guarda os anteriores em `etl/.backup/<versão-antiga>/` (3 últimos) e reporta em `POST /api/etl/agent/package/applied`.3. Se `force_sync_agent.py` ou `sync_to_hf.py` mudaram, o agente solta o lock e se relança (processo destacado); o extrator é subprocesso, então pega o arquivo novo sempre. Se o relançamento falhar, a task de 30 min revive o agente.4. Admin → System Health mostra a linha **ETL scripts** (up to date / outdated / update failed, versão no servidor × versão do app, quando foi aplicada).
Instalação (uma última vez, à mão): copiar a pasta `etl/` atual para o servidor(robocopy do passo 0 do setup) e reiniciar o agente (`schtasks /End` + `/Run` em`GatewayERP-ForceSyncAgent`, ou esperar o tick de 30 min). O agente antigo nãosabe se atualizar; o novo reporta a versão no start e se atualiza dali em diante.
Ressalvas:
- `requirements.txt` novo é copiado mas **não** instalado (Python embeddable sem pip no servidor): o log do agente avisa e o Admin mostra a versão aplicada — rodar `setup_python_env.ps1` se a próxima execução falhar num import.- `--no-self-update` no agente trava o servidor nos arquivos em disco.- Entradas do zip fora do padrão (subpastas, `..`, extensão que não seja .py/.txt) são recusadas antes de gravar qualquer byte.
## Operação
### Logs13 unmodified lines14151617181920212223241718195 unmodified lines25262736372829304131323334354736373819 unmodified lines585960737475767778798081828361626321 unmodified lines85868711111288899035 unmodified lines1261271281541551291301311321 unmodified line134135136163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194137138139140187 unmodified lines32832933038838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152233133233317 unmodified lines35135235354654754854955055155235435535655435735855755835936036156156256336236336436556856936636736836937037157657757857958037237337413 unmodified linesAuth: the SAME API token as sync_to_hf.py (--token / GATEWAY_API_TOKEN env /keyring GatewayERP/etl-sync), sent as `Authorization: Bearer`.
Self-update (since app 1.3.74): every poll response carries the version ofthe etl/ package the backend ships (backend/etl_package.py). When it differsfrom the version recorded in etl/.etl_package_version the agent downloadsthe zip, checks its SHA-256, writes the files next to itself (previous copiesgo to etl/.backup/<version>/), reports the outcome, and restarts so the newagent/sync code is what runs. Updates never start while a request is beingserved. Pass --no-self-update to pin the server to the files on disk.
Install as an at-startup scheduled task with install_force_sync_agent.cmd,or run in a console for testing:
5 unmodified lines
import argparseimport datetimeimport hashlibimport ioimport loggingimport osimport queueimport shutilimport socketimport subprocessimport sysimport threadingimport timeimport zipfilefrom pathlib import Pathfrom typing import Optional
19 unmodified linesLOCK_RETRY_DELAY_S = 90LOCK_RETRY_MAX = 10 # ~15 min of waiting before giving up
# Self-update bookkeeping, all relative to the etl/ folder.PKG_VERSION_FILE = ".etl_package_version"PKG_BACKUP_DIR = ".backup"PKG_BACKUPS_KEPT = 3# Files that only take effect after the agent process restarts (the# extractor runs as a subprocess, so it always picks up the new file).PKG_RESTART_FILES = ("force_sync_agent.py", "sync_to_hf.py")# Package names must be plain file names inside etl/ -- anything else in the# zip (paths, drive letters, ..) is refused before a byte is written.PKG_ALLOWED_SUFFIXES = (".py", ".txt")
# Mirrors $ExpectedCsvs in run_daily.ps1 -- the extractor's exit code is# unreliable, so freshness-on-disk is the real success signal.# Every CSV the uploader knows how to send (legacy bundles + MVP 2) — the21 unmodified lines p.add_argument("--keyring-service", default="GatewayERP") p.add_argument("--keyring-username", default="etl-sync") p.add_argument("--lock-file", type=Path, default=etl_dir / ".agent.lock") p.add_argument("--no-self-update", action="store_true", help="Never replace the etl/ files with the backend's package") return p.parse_args(argv)
35 unmodified lines self.headers = {"Authorization": f"Bearer {token}"} self.log = log
def poll(self) -> dict: """One poll: {"request": ... | None, "etl_package": {...} | None}.""" def poll_next(self) -> Optional[dict]: url = f"{self.base}/api/etl/agent/next" r = requests.get(url, headers=self.headers, params={"host": socket.gethostname()}, timeout=30)1 unmodified line raise SystemExit("401 Unauthorized -- token invalid/revoked. " "Re-run set_token.ps1 with a fresh token.") r.raise_for_status() return r.json()
def poll_next(self) -> Optional[dict]: return self.poll().get("request")
def download_package(self) -> tuple[str, bytes]: """Fetch the etl/ package zip; returns (version, bytes) after checking the SHA-256 the server announced for it.""" url = f"{self.base}/api/etl/agent/package" r = requests.get(url, headers=self.headers, timeout=120) r.raise_for_status() version = r.headers.get("X-Package-Version", "") expected = r.headers.get("X-Package-SHA256", "") actual = hashlib.sha256(r.content).hexdigest() if not version or not expected: raise RuntimeError("package response lacks X-Package-Version/SHA256 headers") if actual != expected: raise RuntimeError(f"package SHA-256 mismatch: expected {expected}, got {actual}") return version, r.content
def package_applied(self, version: str, status: str, previous: Optional[str], error: Optional[str] = None, requirements_changed: bool = False) -> None: url = f"{self.base}/api/etl/agent/package/applied" body = {"version": version, "status": status, "previous_version": previous, "host": socket.gethostname(), "error": error, "requirements_changed": requirements_changed} try: r = requests.post(url, headers=self.headers, json=body, timeout=30) if not r.ok: self.log.warning("package/applied POST HTTP %d: %s", r.status_code, r.text[:200]) except (requests.ConnectionError, requests.Timeout) as e: self.log.warning("package/applied POST failed: %s", e) return r.json().get("request")
def progress(self, request_id: int, **body) -> bool: """POST progress; returns False if the server considers us dead (409)."""187 unmodified lines error=f"sync_to_hf exited {code}. See log tail above.")
# ── Self-update ──────────────────────────────────────────────────────────────
def read_local_package_version(etl_dir: Path) -> Optional[str]: try: v = (etl_dir / PKG_VERSION_FILE).read_text(encoding="utf-8").strip() return v or None except OSError: return None
def _validate_zip_names(names: list[str]) -> None: for n in names: if (not n or "/" in n or "\\" in n or n.startswith(".") or ":" in n or not n.endswith(PKG_ALLOWED_SUFFIXES)): raise RuntimeError(f"refusing package entry {n!r}")
def apply_package(zip_bytes: bytes, version: str, etl_dir: Path, log: logging.Logger) -> dict: """Write the package's files into etl_dir.
Existing copies of the files being replaced go to .backup/<old-version>/ first (older backups pruned to PKG_BACKUPS_KEPT). Each file is written to a temp name and os.replace()d, so a crash mid-way leaves either the old or the new file, never a truncated one. Returns a summary dict: {changed: [...], restart_needed: bool, requirements_changed: bool}. """ with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: names = zf.namelist() _validate_zip_names(names) payload = {n: zf.read(n) for n in names} if not payload: raise RuntimeError("package is empty")
previous = read_local_package_version(etl_dir) or "unversioned" backup_dir = etl_dir / PKG_BACKUP_DIR / previous changed: list[str] = [] for name, data in payload.items(): target = etl_dir / name if target.exists() and target.read_bytes() == data: continue if target.exists(): backup_dir.mkdir(parents=True, exist_ok=True) shutil.copy2(target, backup_dir / name) tmp = etl_dir / f".{name}.{os.getpid()}.tmp" tmp.write_bytes(data) os.replace(tmp, target) changed.append(name) log.info("[update] wrote %s (%d bytes)", name, len(data))
(etl_dir / PKG_VERSION_FILE).write_text(version + "\n", encoding="utf-8")
# Prune old backups (newest kept by mtime). root = etl_dir / PKG_BACKUP_DIR if root.is_dir(): dirs = sorted((d for d in root.iterdir() if d.is_dir()), key=lambda d: d.stat().st_mtime, reverse=True) for old in dirs[PKG_BACKUPS_KEPT:]: shutil.rmtree(old, ignore_errors=True)
return { "changed": changed, "restart_needed": any(n in PKG_RESTART_FILES for n in changed), "requirements_changed": "requirements.txt" in changed, }
def maybe_self_update(server_pkg: Optional[dict], args: argparse.Namespace, backend: Backend, log: logging.Logger) -> bool: """Called between polls when idle. Returns True when the agent must restart (files it runs from were replaced); False otherwise.""" if args.no_self_update or not server_pkg: return False server_version = str(server_pkg.get("version") or "") if not server_version: return False etl_dir = Path(__file__).resolve().parent local_version = read_local_package_version(etl_dir) if local_version == server_version: return False
log.info("[update] etl package %s available (local %s) -- downloading", server_version, local_version or "unversioned") try: version, blob = backend.download_package() if version != server_version: log.info("[update] server now serves %s; applying that one", version) result = apply_package(blob, version, etl_dir, log) except Exception as e: log.error("[update] failed: %s", e) backend.package_applied(server_version, "error", local_version, error=str(e)[:2000]) return False
log.info("[update] applied %s: %d file(s) changed %s", version, len(result["changed"]), result["changed"]) if result["requirements_changed"]: log.warning("[update] requirements.txt changed -- run setup_python_env.ps1 " "on this server if the next run fails on an import") backend.package_applied(version, "applied", local_version, requirements_changed=result["requirements_changed"]) return result["restart_needed"]
def report_current_package(args: argparse.Namespace, backend: Backend, log: logging.Logger) -> None: """On start-up tell the backend which package version is on disk, so the Admin page shows it even before the first update ever happens.""" v = read_local_package_version(Path(__file__).resolve().parent) if v: backend.package_applied(v, "applied", v) else: log.info("No %s yet -- first poll will fetch the backend's package", PKG_VERSION_FILE)
def restart_self(log: logging.Logger) -> None: """Spawn a fresh agent with the same arguments and let this one exit.
The caller releases the instance lock first; the child is detached so it survives our exit. If the spawn fails the half-hourly scheduled task revives the agent anyway.""" cmd = [sys.executable, str(Path(__file__).resolve())] + sys.argv[1:] flags = 0 if os.name == "nt": flags = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP try: subprocess.Popen(cmd, cwd=str(Path(__file__).resolve().parent), creationflags=flags, close_fds=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) log.info("[update] restarted agent: %s", " ".join(cmd)) except Exception as e: log.error("[update] could not respawn agent (%s); the scheduled task " "will start it within 30 minutes", e)
# ── Entry point ──────────────────────────────────────────────────────────────
def main(argv: Optional[list[str]] = None) -> int:17 unmodified lines return 2 backend = Backend(args.api_base, token, log)
log.info("Agent started. api=%s poll=%ss host=%s self_update=%s", args.api_base, args.poll_seconds, socket.gethostname(), not args.no_self_update) try: report_current_package(args, backend, log) except Exception as e: log.warning("could not report package version: %s", e) log.info("Agent started. api=%s poll=%ss host=%s", args.api_base, args.poll_seconds, socket.gethostname())
restart = False while True: try: resp = backend.poll() req = resp.get("request") req = backend.poll_next() if req is not None: run_request(req, args, backend, log) else: # Idle -- safe moment to swap our own files. restart = maybe_self_update(resp.get("etl_package"), args, backend, log) except SystemExit: raise except Exception as e: log.warning("poll cycle error (will retry): %s", e) if restart: break if args.once: return 0 time.sleep(args.poll_seconds) finally: lock.release()
if restart: log.info("[update] agent files changed -- restarting") restart_self(log) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""force_sync_agent self-update: apply a package safely, decide when toupdate, and never touch files while a request is running."""from __future__ import annotations
import argparseimport hashlibimport ioimport loggingimport zipfilefrom pathlib import Path
import pytest
import force_sync_agent as agent
LOG = logging.getLogger("test-agent")
def _zip(files: dict[str, bytes]) -> bytes: buf = io.BytesIO() with zipfile.ZipFile(buf, "w") as zf: for n, d in files.items(): zf.writestr(n, d) return buf.getvalue()
def test_apply_package_writes_files_backs_up_and_records_version(tmp_path: Path): (tmp_path / "visma_unified_extractor.py").write_bytes(b"old extractor") (tmp_path / "sync_to_hf.py").write_bytes(b"same") (tmp_path / agent.PKG_VERSION_FILE).write_text("aaaaaaaaaaaa\n")
blob = _zip({ "visma_unified_extractor.py": b"new extractor", "sync_to_hf.py": b"same", # unchanged -> not rewritten "adk_constants.py": b"brand new file", }) result = agent.apply_package(blob, "bbbbbbbbbbbb", tmp_path, LOG)
assert (tmp_path / "visma_unified_extractor.py").read_bytes() == b"new extractor" assert (tmp_path / "adk_constants.py").read_bytes() == b"brand new file" assert sorted(result["changed"]) == ["adk_constants.py", "visma_unified_extractor.py"] assert result["restart_needed"] is False # neither agent nor sync changed assert result["requirements_changed"] is False assert agent.read_local_package_version(tmp_path) == "bbbbbbbbbbbb" # previous copy of the replaced file is kept under .backup/<old version>/ assert (tmp_path / ".backup" / "aaaaaaaaaaaa" / "visma_unified_extractor.py").read_bytes() == b"old extractor" assert not (tmp_path / ".backup" / "aaaaaaaaaaaa" / "sync_to_hf.py").exists() assert not list(tmp_path.glob("*.tmp"))
def test_apply_package_flags_restart_when_agent_or_sync_changes(tmp_path: Path): result = agent.apply_package(_zip({"force_sync_agent.py": b"v2", "requirements.txt": b"requests\nkeyring\n"}), "cccccccccccc", tmp_path, LOG) assert result["restart_needed"] is True assert result["requirements_changed"] is True
@pytest.mark.parametrize("bad", ["sub/dir.py", "..\\evil.py", ".hidden.py", "C:evil.py", "run.cmd", ""])def test_apply_package_refuses_unsafe_entries(tmp_path: Path, bad: str): with pytest.raises(RuntimeError): agent.apply_package(_zip({bad: b"x", "ok.py": b"y"}), "dddddddddddd", tmp_path, LOG) assert not (tmp_path / "ok.py").exists() # nothing written before validation passed
class _FakeBackend: def __init__(self, version: str, files: dict[str, bytes], corrupt: bool = False): self.version = version self.blob = _zip(files) self.corrupt = corrupt self.reports: list[dict] = []
def download_package(self): if self.corrupt: raise RuntimeError("package SHA-256 mismatch") return self.version, self.blob
def package_applied(self, version, status, previous, error=None, requirements_changed=False): self.reports.append({"version": version, "status": status, "previous": previous, "error": error, "requirements_changed": requirements_changed})
def _args(**kw) -> argparse.Namespace: base = {"no_self_update": False} base.update(kw) return argparse.Namespace(**base)
def test_maybe_self_update_skips_when_versions_match_or_disabled(tmp_path: Path, monkeypatch): monkeypatch.setattr(agent, "__file__", str(tmp_path / "force_sync_agent.py")) (tmp_path / agent.PKG_VERSION_FILE).write_text("eeeeeeeeeeee\n") be = _FakeBackend("eeeeeeeeeeee", {"x.py": b"1"}) assert agent.maybe_self_update({"version": "eeeeeeeeeeee"}, _args(), be, LOG) is False assert be.reports == []
be2 = _FakeBackend("ffffffffffff", {"x.py": b"1"}) assert agent.maybe_self_update({"version": "ffffffffffff"}, _args(no_self_update=True), be2, LOG) is False assert agent.maybe_self_update(None, _args(), be2, LOG) is False assert be2.reports == []
def test_maybe_self_update_applies_reports_and_requests_restart(tmp_path: Path, monkeypatch): monkeypatch.setattr(agent, "__file__", str(tmp_path / "force_sync_agent.py")) be = _FakeBackend("ffffffffffff", {"force_sync_agent.py": b"new agent", "x.py": b"1"}) restart = agent.maybe_self_update({"version": "ffffffffffff"}, _args(), be, LOG) assert restart is True assert (tmp_path / "force_sync_agent.py").read_bytes() == b"new agent" assert be.reports == [{"version": "ffffffffffff", "status": "applied", "previous": None, "error": None, "requirements_changed": False}]
def test_maybe_self_update_reports_error_and_keeps_files(tmp_path: Path, monkeypatch): monkeypatch.setattr(agent, "__file__", str(tmp_path / "force_sync_agent.py")) (tmp_path / "x.py").write_bytes(b"keep me") be = _FakeBackend("ffffffffffff", {"x.py": b"1"}, corrupt=True) assert agent.maybe_self_update({"version": "ffffffffffff"}, _args(), be, LOG) is False assert (tmp_path / "x.py").read_bytes() == b"keep me" assert be.reports[0]["status"] == "error" and "SHA-256" in be.reports[0]["error"] assert agent.read_local_package_version(tmp_path) is None
def test_download_package_verifies_sha256(monkeypatch): class _Resp: def __init__(self, content, headers): self.content, self.headers = content, headers def raise_for_status(self): pass
blob = b"zipzip" good = hashlib.sha256(blob).hexdigest() monkeypatch.setattr(agent.requests, "get", lambda *a, **k: _Resp(blob, {"X-Package-Version": "v1", "X-Package-SHA256": good})) be = agent.Backend("http://x", "tok", LOG) assert be.download_package() == ("v1", blob)
monkeypatch.setattr(agent.requests, "get", lambda *a, **k: _Resp(blob, {"X-Package-Version": "v1", "X-Package-SHA256": "0" * 64})) with pytest.raises(RuntimeError): be.download_package()123345633 unmodified lines4041424344454647434445122 unmodified lines16816917017617117217382 unmodified lines25625725826525926026114 unmodified lines276277278286287288289279280281576 unmodified lines85885986087287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190286186290586386486586686786891286987087187211 unmodified lines884885886930887888889890891892937938893894895"""================================================================================VISMA UNIFIED EXTRACTOR v6.3 — Gateway SecurityVISMA UNIFIED EXTRACTOR v6.2 — Gateway Security================================================================================Replaces (and de-duplicates): - visma_invoice_extractor_v5.py (invoices + articles + BOM + customers)33 unmodified lines(ADK ids 21/22). Voucher numbers restart per booking year and series, so theyear id is what makes the schedule → source-voucher join in gl_entries exact.
v6.3: dim_customers.csv gains Category_Code + Category_Name (Kundkategori,ADK_CUSTOMER_CATEGORY = 26, label from ADK_DB_CODE_OF_CUSTOMER_CATEGORY = 18).Feeds the ABC customer classification in the ERP, computed per category so achain (ICA, Varner, ...) counts as one account instead of many small stores.
--------------------------------------------------------------------------------CLI--------------------------------------------------------------------------------122 unmodified lines# =============================================================================ADK_DB_CUSTOMER = 0ADK_DB_ARTICLE = 1ADK_DB_CODE_OF_CUSTOMER_CATEGORY = 18 # Kundkategori (code register)ADK_DB_INVOICE_HEAD = 6ADK_DB_ACCOUNT = 11 # KontoplanADK_DB_ARTICLE_PARCEL = 35 # Paketartikelrader (BOM)82 unmodified linesADK_CUSTOMER_COUNTRY = 8ADK_CUSTOMER_TELEPHONE = 9ADK_CUSTOMER_ORGANISATION_NUMBER = 25ADK_CUSTOMER_CATEGORY = 26 # Kundkategori (v7)ADK_CUSTOMER_SELLER = 28ADK_CUSTOMER_CODE_OF_TERMS_OF_PAYMENT = 30ADK_CUSTOMER_CODE_OF_CURRENCY = 37 # FIX-P14 unmodified linesADK_CUSTOMER_CONTRIBUTION_DEGREE_LAST_YEAR = 65ADK_CUSTOMER_INACTIVE = 112
# Code register ADK_DB_CODE_OF_CUSTOMER_CATEGORY (Adk.h)ADK_CODE_OF_CUSTOMER_CATEGORY_CODE = 0 # eCharADK_CODE_OF_CUSTOMER_CATEGORY_TEXT = 1 # eChar
# =============================================================================# FIELD IDs — INVOICE HEAD (manual pp. 139–156; every v5 FIX preserved)576 unmodified lines# =============================================================================# [3] CUSTOMERS → dim_customers.csv# =============================================================================def read_customer_categories() -> dict[str, str]: """Kundkategori code → label, from the code register (DB 18).
The customer record only carries the category *code* (field 26); the label users see in Visma ("ICA", "Varner SV", "Apoteket Hjärtat AB", ...) lives in this register. Returned as a dict so extract_customers() can write both columns into dim_customers.csv without a second file in the bundle. Any failure degrades to an empty map (codes still exported). """ cats: dict[str, str] = {} ptr = None try: ptr = get_status(Api.AdkCreateData(ADK_DB_CODE_OF_CUSTOMER_CATEGORY)) res = get_status(Api.AdkFirstEx(ptr, False)) while res.lRc == 0: code = safe_str(ptr, ADK_CODE_OF_CUSTOMER_CATEGORY_CODE) if code: cats[code] = safe_str(ptr, ADK_CODE_OF_CUSTOMER_CATEGORY_TEXT) res = get_status(Api.AdkNextEx(ptr, False)) log(f"Customer categories (Kundkategori): {len(cats)} codes", "OK") except Exception as e: log(f"Customer categories unavailable, exporting codes only: {e}", "WARN") finally: if ptr is not None: try: Api.AdkDeleteStruct(ptr) except Exception: pass return cats
def extract_customers() -> None: log_section("CUSTOMERS → dim_customers.csv", 3) categories = read_customer_categories() data_ptr = get_status(Api.AdkCreateData(ADK_DB_CUSTOMER)) count = 0 t0 = time.time()
HEADER = [ "Customer_ID", "Name", "City", "Country", "Currency_Code", "Category_Code", "Category_Name", "Currency_Code", "Org_Number", "VAT_Number", "EU_Customer", "Export_Flag", "Seller_Code", "Payment_Terms", "Invoice_Discount_Pct", "Row_Discount_Pct",11 unmodified lines
res = get_status(Api.AdkFirstEx(data_ptr, False)) while res.lRc == 0: cat_code = safe_str(data_ptr, ADK_CUSTOMER_CATEGORY) writer.writerow([ safe_str(data_ptr, ADK_CUSTOMER_NUMBER), safe_str(data_ptr, ADK_CUSTOMER_NAME), safe_str(data_ptr, ADK_CUSTOMER_CITY), safe_str(data_ptr, ADK_CUSTOMER_COUNTRY), safe_str(data_ptr, ADK_CUSTOMER_CODE_OF_CURRENCY), cat_code, categories.get(cat_code, ""), safe_str(data_ptr, ADK_CUSTOMER_ORGANISATION_NUMBER), safe_str(data_ptr, ADK_CUSTOMER_VAT_NUMBER), safe_bool(data_ptr, ADK_CUSTOMER_EU_CUSTOMER),702 unmodified lines703704705706707708709710711712706707708709146 unmodified lines856857858865866867868869870871872873874875876877878879880881882883884885886887859860861702 unmodified lines }; }; etl_sync: { last_run_at: string | null; age_hours: number | null; health: "green" | "yellow" | "red" }; etl_agent: { online: boolean; last_seen: string | null; host: string | null; package?: { server_version: string | null; agent_version: string | null; applied_at: string | null; status: string | null; error: string | null; up_to_date: boolean | null; }; }; etl_agent: { online: boolean; last_seen: string | null; host: string | null }; last_import: { at: string | null; type: string | null; source: string | null }; backup: { enabled: boolean; last_backup_at: string | null }; exchange_rates: { cached: boolean; fetched_at: string | null };146 unmodified lines : "never connected"} </dd> </div> {health.etl_agent.package && health.etl_agent.package.server_version && ( <div className="admin-kv-row"> <dt>ETL scripts</dt> <dd> {health.etl_agent.package.status === "error" ? ( <HealthPill tone="bad">update failed</HealthPill> ) : health.etl_agent.package.up_to_date === true ? ( <HealthPill tone="good">up to date</HealthPill> ) : health.etl_agent.package.up_to_date === false ? ( <HealthPill tone="warn">outdated</HealthPill> ) : ( <HealthPill tone="warn">not reported</HealthPill> )}{" "} {`server ${health.etl_agent.package.server_version}`} {health.etl_agent.package.agent_version ? ` · agent ${health.etl_agent.package.agent_version}${health.etl_agent.package.applied_at ? ` (${formatRelativeTime(health.etl_agent.package.applied_at)})` : ""}` : " · agent has not reported a version yet (pre-1.3.74 agent — copy etl/ once, then it self-updates)"} {health.etl_agent.package.status === "error" && health.etl_agent.package.error ? ` — ${health.etl_agent.package.error}` : ""} </dd> </div> )} <div className="admin-kv-row"> <dt>Last ETL sync</dt> <dd>63 unmodified lines64656667676869942 unmodified lines10121013101410161017101810191020102110151016101763 unmodified lines order_number: number; customer: string; order_date: string | null; delivery_date: string | null; month: string | null; status: string; days_late: number; value: number; margin: number | null; seller: string | null; not_finalised: boolean;}interface MgmtPayload { meta: {942 unmodified lines }}> {ORDER_STATUS[o.status] ?? o.status}{o.status === "late" && o.days_late ? ` · ${o.days_late}d` : ""} </span> {o.not_finalised && ( <span title="Marked 'Ej klar' (not finalised) in Visma — still an open order" style={{ marginLeft: 6, fontSize: 10.5, fontWeight: 600, color: "var(--shell-muted)" }}> · not finalised </span> )} </td> <td style={{ ...tdNum, fontSize: 12 }}>{fmtMoney(o.value, ccy)}</td> <td style={{ ...tdNum, fontSize: 12 }}>{o.margin == null ? "—" : fmtMoney(o.value - o.margin, ccy)}</td>12342345678789104 unmodified lines151617181920212223242526272425262728293031323334353637382829404142303132334445463435363738394048495051525354555657585960616263646566676869707172737475764142434445464748495051525354555657585960616263646597 unmodified lines1631641651801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642651661671685 unmodified lines17417517627727817717817918065 unmodified lines246247248350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398249250251252253403404405406407408409410254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291412413414415416417418419420421422423424292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339426427428429430431432433434340341342343344345346347348349350351352353436437438354440441442443444445446447448449355356357358359360361362363364365366367368369370371372373454455456457458459460461374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415"use client";import React, { useState } from 'react';import { BarChart, Bar, PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer,import React, { useState, useEffect } from 'react';import { AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer, CartesianGrid, XAxis, YAxis} from "recharts";import { Panel, KpiCard, TT, ExportButton, Chip } from './shared';import { DataTable, DataCol } from './DataTable';import { Panel, KpiCard, TT, ExportButton } from './shared';import { fmtMoney, fmtMoneyCompact, fmtNumCompact, CCY_RATES, CHART_PALETTE, Currency } from '@/utils/formatters';import { API } from "@/lib/api";import { tName } from '@/utils/i18n';4 unmodified lines convertedKpis: any; ccy: Currency; selectedCustomerId?: string; onPageChange?: (page: number, pageSize: number) => void; page?: number; pageSize?: number; totalCount?: number; exportParams?: string;}
const COLORS = CHART_PALETTE;const PAGE_SIZE_OPTIONS = [10, 25, 50, 100];
/* ABC classes follow finance's rule (Sept 2026): A = customers that make up * ~80% of revenue, B = the next 15%, C = the last 5%. The backend computes * the class both per customer and per Visma customer category (Kundkategori), * because a chain such as ICA is many store accounts in Visma but one * negotiated account for finance. */const ABC_COLOR: Record<string, string> = { A: "var(--shell-good)", B: "var(--shell-warn)", C: "var(--shell-muted)",};const AbcChip = ({ cls }: { cls?: string | null }) => cls ? <Chip text={cls} color={ABC_COLOR[cls] || "var(--shell-muted)"} /> : <span style={{ color: "var(--shell-muted)" }}>—</span>;
const NO_CATEGORY = "No category";const pctColor = (pct: number) => pct > 15 ? "var(--shell-good)" : pct < 5 ? "var(--shell-bad)" : "var(--shell-muted)";
export const CustomerAnalytics = React.memo(function CustomerAnalytics({ data, convertedKpis, ccy, selectedCustomerId, exportParams = "", externalTotalCount }: CustomerAnalyticsProps & { externalTotalCount?: number }) {export const CustomerAnalytics = React.memo(function CustomerAnalytics({ data, convertedKpis, ccy, selectedCustomerId, exportParams = "", externalPage, externalPageSize, externalTotalCount, onPageChange }: CustomerAnalyticsProps & { selectedCustomerId?: string; externalPage?: number; externalPageSize?: number; externalTotalCount?: number; onPageChange?: (page: number, pageSize: number) => void }) { const { lang } = useLang(); const [categoryFilter, setCategoryFilter] = useState<string>(""); const [abcFilter, setAbcFilter] = useState<string>("");
const [internalPage, setInternalPage] = useState(0); const [internalPageSize, setInternalPageSize] = useState(10); const isFilteredByCustomer = !!selectedCustomerId;
const allCustomers: any[] = React.useMemo(() => data?.revenue?.customers || [], [data]); const totalCount = externalTotalCount ?? allCustomers.length; const page = externalPage ?? internalPage; const pageSize = externalPageSize ?? internalPageSize; const totalCount = externalTotalCount ?? (data?.revenue?.customers?.length ?? 0); const customerData = data?.revenue?.customers || []; const kpis = data?.revenue?.kpis || {}; const categoryRows: any[] = React.useMemo(() => data?.revenue?.customer_categories || [], [data]); const abcMeta = data?.revenue?.customer_abc || {};
// A new payload (period / region change) invalidates the category and // class filters — reset them during render, the React-sanctioned way. const [seenData, setSeenData] = useState(data); if (data !== seenData) { setSeenData(data); setCategoryFilter(""); setAbcFilter(""); }
// Dropdown: the real Visma categories (with their class) plus one entry // for customers that have none; standalone accounts are not listed. const categoryOptions = React.useMemo(() => { const opts = categoryRows.filter((r: any) => r.is_category) .map((r: any) => ({ key: r.category_code, label: r.category, cls: r.abc_class })); if (categoryRows.some((r: any) => !r.is_category)) opts.push({ key: "__none__", label: NO_CATEGORY, cls: "" }); return opts; }, [categoryRows]);
// Category + ABC filters narrow the customer tables and the charts alike, // so "show me the ICA stores" reads consistently across the page. const customerData: any[] = React.useMemo(() => allCustomers.filter((c: any) => { if (categoryFilter && (c.category_code ?? "__none__") !== categoryFilter) return false; if (abcFilter && c.abc_class !== abcFilter) return false; return true; }), [allCustomers, categoryFilter, abcFilter]); const isNarrowed = !!categoryFilter || !!abcFilter; const totalPages = Math.ceil(totalCount / pageSize); const paginatedCustomers = customerData.slice(page * pageSize, (page + 1) * pageSize); useEffect(() => { setInternalPage(0); }, [data, totalCount]);
const handlePageSizeChange = (newSize: number) => { setInternalPageSize(newSize); setInternalPage(0); if (onPageChange) { onPageChange(0, newSize); } };
const handlePageChange = (newPage: number) => { setInternalPage(newPage); if (onPageChange) { onPageChange(newPage, pageSize); } };
const countryData = React.useMemo(() => { const countries: Record<string, { revenue: number; margin: number; customers: number }> = {};97 unmodified lines return [...productData].sort((a, b) => b.margin_pct - a.margin_pct).slice(0, 8); }, [productData]);
const money = React.useCallback( (v: number) => <span title={fmtMoney(v || 0, ccy)}>{fmtMoneyCompact(v || 0, ccy)}</span>, [ccy]);
const customerColumns = React.useMemo<DataCol<any>[]>(() => [ { key: "rank", label: "#", numeric: true, value: c => c.rank ?? 0, render: c => <span style={{ fontWeight: 600, color: (c.rank ?? 99) <= 3 ? "var(--shell-accent)" : "var(--shell-muted)" }}>#{c.rank}</span> }, { key: "name", label: "Customer", value: c => c.name, render: c => <span style={{ fontWeight: 500 }}>{c.name}</span> }, { key: "category", label: "Category", value: c => c.category || "", render: c => c.category ? <span>{c.category}</span> : <span style={{ color: "var(--shell-muted)" }}>—</span> }, { key: "abc", label: "Class", value: c => c.abc_class || "", render: c => <AbcChip cls={c.abc_class} /> }, { key: "cat_abc", label: "Cat. class", value: c => c.category_abc_class || "", render: c => <AbcChip cls={c.category_abc_class} /> }, { key: "country", label: "Country", value: c => c.country || "", render: c => <span style={{ color: "var(--shell-muted)" }}>{c.country}</span> }, { key: "invoices", label: "Invoices", numeric: true, value: c => c.invoices || 0 }, { key: "revenue", label: "Revenue", numeric: true, value: c => c.revenue || 0, render: c => <span style={{ fontWeight: 600 }}>{money(c.revenue)}</span> }, { key: "margin_pct", label: "Margin %", numeric: true, value: c => c.margin_pct || 0, render: c => <span style={{ color: pctColor(c.margin_pct || 0) }}>{c.margin_pct}%</span> }, { key: "top_product", label: "Top Product", value: c => c.top_product && c.top_product.sku !== "-" ? tName(c.top_product, lang) : "", render: c => c.top_product && c.top_product.sku !== "-" ? ( <span> <span style={{ fontWeight: 500 }}>{tName(c.top_product, lang)}</span> <span style={{ color: "var(--shell-muted)", marginLeft: 6, fontSize: "0.7rem" }}>{c.top_product.margin_pct}%</span> </span> ) : <span style={{ color: "var(--shell-muted)" }}>-</span> }, { key: "share", label: "% of Total", numeric: true, value: c => c.share_pct ?? c.pct_of_total ?? 0, render: c => <span style={{ color: (c.share_pct ?? 0) > 10 ? "var(--shell-accent-2)" : "var(--shell-muted)" }}>{(c.share_pct ?? c.pct_of_total ?? 0).toFixed(1)}%</span> }, { key: "cum", label: "Cumulative %", numeric: true, value: c => c.cumulative_share_pct ?? 0, render: c => <span style={{ color: "var(--shell-muted)" }}>{(c.cumulative_share_pct ?? 0).toFixed(1)}%</span> }, ], [money, lang]);
const categoryColumns = React.useMemo<DataCol<any>[]>(() => [ { key: "rank", label: "#", numeric: true, value: r => r.rank ?? 0, render: r => <span style={{ fontWeight: 600, color: (r.rank ?? 99) <= 3 ? "var(--shell-accent)" : "var(--shell-muted)" }}>#{r.rank}</span> }, { key: "category", label: "Account", value: r => r.category || "", render: r => ( <span style={{ fontWeight: 500 }}> {r.category} <span style={{ color: "var(--shell-muted)", marginLeft: 6, fontSize: "0.7rem" }}>{r.is_category ? `category ${r.category_code}` : "customer"}</span> </span> ) }, { key: "abc", label: "Class", value: r => r.abc_class || "", render: r => <AbcChip cls={r.abc_class} /> }, { key: "customers", label: "Customers", numeric: true, value: r => r.customers || 0 }, { key: "invoices", label: "Invoices", numeric: true, value: r => r.invoices || 0 }, { key: "revenue", label: "Revenue", numeric: true, value: r => r.revenue || 0, render: r => <span style={{ fontWeight: 600 }}>{money(r.revenue)}</span> }, { key: "margin_pct", label: "Margin %", numeric: true, value: r => r.margin_pct || 0, render: r => <span style={{ color: pctColor(r.margin_pct || 0) }}>{r.margin_pct}%</span> }, { key: "share", label: "% of Total", numeric: true, value: r => r.share_pct || 0, render: r => <span>{(r.share_pct || 0).toFixed(1)}%</span> }, { key: "cum", label: "Cumulative %", numeric: true, value: r => r.cumulative_share_pct || 0, render: r => <span style={{ color: "var(--shell-muted)" }}>{(r.cumulative_share_pct || 0).toFixed(1)}%</span> }, ], [money]);
const productColumns = React.useMemo<DataCol<any>[]>(() => [ { key: "sku", label: "SKU", mono: true, value: p => p.sku, render: p => <span style={{ fontWeight: 500 }}>{p.sku}</span> }, { key: "name", label: "Product Name", value: p => p.name, render: p => <span style={{ color: "var(--shell-muted)" }}>{p.name}</span> }, { key: "qty", label: "Qty", numeric: true, value: p => p.qty || 0 }, { key: "revenue", label: "Revenue", numeric: true, value: p => p.revenue || 0, render: p => <span style={{ fontWeight: 600 }}>{money(p.revenue)}</span> }, { key: "margin_fifo", label: "FIFO Margin", numeric: true, value: p => p.margin_fifo || 0, render: p => <span style={{ color: p.margin_fifo > 0 ? "var(--shell-good)" : "var(--shell-bad)", fontWeight: 700 }}>{money(p.margin_fifo)}</span> }, { key: "booked", label: "Booked Margin", numeric: true, value: p => p.margin_visma || 0, render: p => <span style={{ color: "var(--shell-muted)" }}>{money(p.margin_visma)}</span> }, { key: "margin_pct", label: "FIFO %", numeric: true, value: p => p.margin_pct || 0, render: p => <span style={{ color: pctColor(p.margin_pct || 0) }}>{p.margin_pct}%</span> }, ], [money]);
const matrixColumns = React.useMemo<DataCol<any>[]>(() => { const pct = (num: number, rev: number) => rev ? (num || 0) / rev * 100 : 0; const pctStyle = (v: number, hi: string) => ({ color: v >= 30 ? hi : v >= 15 ? "var(--shell-ink-2)" : "var(--shell-bad)", fontWeight: 600 }); return [ { key: "name", label: "Customer", value: c => c.name, render: c => <span style={{ fontWeight: 500, whiteSpace: "nowrap" }}>{c.name}</span> }, { key: "category", label: "Category", value: c => c.category || "", render: c => <span style={{ color: "var(--shell-muted)" }}>{c.category || "—"}</span> }, { key: "abc", label: "Class", value: c => c.abc_class || "", render: c => <AbcChip cls={c.abc_class} /> }, { key: "country", label: "Country", value: c => c.country || "", render: c => <span style={{ color: "var(--shell-muted)" }}>{c.country}</span> }, { key: "revenue", label: "Revenue", numeric: true, value: c => c.revenue || 0, render: c => <span style={{ fontWeight: 600 }}>{money(c.revenue)}</span> }, { key: "margin_visma", label: "Booked (Visma)", numeric: true, value: c => c.margin_visma || 0, render: c => <span style={{ color: "var(--shell-muted)" }}>{money(c.margin_visma)}</span> }, { key: "margin_kalkyl", label: "Est. Price", numeric: true, value: c => c.margin_kalkyl || 0, render: c => <span style={{ color: "var(--shell-warn)" }}>{money(c.margin_kalkyl)}</span> }, { key: "margin_fifo", label: "FIFO (LPP)", numeric: true, value: c => c.margin_fifo || 0, render: c => <span style={{ color: c.margin_fifo > 0 ? "var(--shell-good)" : "var(--shell-bad)", fontWeight: 700 }}>{money(c.margin_fifo)}</span> }, { key: "booked_pct", label: "Booked %", numeric: true, value: c => pct(c.margin_visma, c.revenue), render: c => <span style={pctStyle(pct(c.margin_visma, c.revenue), "var(--shell-good)")}>{pct(c.margin_visma, c.revenue).toFixed(1)}%</span> }, { key: "fifo_pct", label: "FIFO %", numeric: true, value: c => pct(c.margin_fifo, c.revenue), render: c => <span style={pctStyle(pct(c.margin_fifo, c.revenue), "var(--shell-accent)")}>{pct(c.margin_fifo, c.revenue).toFixed(1)}%</span> }, { key: "est_pct", label: "Est. Price %", numeric: true, value: c => pct(c.margin_kalkyl, c.revenue), render: c => <span style={pctStyle(pct(c.margin_kalkyl, c.revenue), "var(--shell-warn)")}>{pct(c.margin_kalkyl, c.revenue).toFixed(1)}%</span> }, { key: "products", label: "Products", numeric: true, value: c => c.product_count || 0 }, ]; }, [money]);
const displayCountryData = isFilteredByCustomer ? productCountryData : countryData; const displayChartTitle = isFilteredByCustomer ? "Revenue by Product" : "Revenue by Country"; const displayChartSubtitle = isFilteredByCustomer ? `Top ${productData.length} products for selected customer` : "Top 10 countries by revenue";5 unmodified lines <KpiCard label="Total Customers" value={fmtNumCompact(totalCount)} fullValue={String(totalCount)} sub="Active in period" color="var(--shell-accent)" /> <KpiCard label="Total Revenue" value={convertedKpis?.revenue?.total_revenue || '$0'} sub="All customer revenue" color="var(--shell-accent)" /> <KpiCard label="Avg Revenue/Customer" value={fmtMoneyCompact(kpis.avg_order_value || 0, ccy)} fullValue={fmtMoney(kpis.avg_order_value || 0, ccy)} sub="Average per customer" color="var(--shell-accent-2)" /> <KpiCard label="Class A customers" value={fmtNumCompact(abcMeta.counts_customer?.A || 0)} fullValue={String(abcMeta.counts_customer?.A || 0)} sub={`≈80% of revenue · B ${abcMeta.counts_customer?.B || 0} · C ${abcMeta.counts_customer?.C || 0}`} /> <KpiCard label="Class A accounts" value={fmtNumCompact(abcMeta.counts_category?.A || 0)} fullValue={String(abcMeta.counts_category?.A || 0)} sub={`by category (${abcMeta.category_count || 0} chains + standalone) · B ${abcMeta.counts_category?.B || 0} · C ${abcMeta.counts_category?.C || 0}`} /> <KpiCard label="Unique Customers" value={fmtNumCompact(kpis.unique_customers || 0)} fullValue={String(kpis.unique_customers || 0)} sub="Distinct customer IDs" /> </div> </section>
65 unmodified lines </ResponsiveContainer> </Panel>
{!isFilteredByCustomer && ( <Panel title="Customer Categories — ABC" subtitle={`Accounts ranked by revenue: a Visma Kundkategori groups a chain's stores into one account, a customer without category stands alone · A ≈ first 80% · B next 15% · C last 5% · ${abcMeta.category_count || 0} categories, ${abcMeta.uncategorised_customers || 0} customers without one`} full > <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.4fr)", gap: 20, alignItems: "start" }}> <div style={{ minWidth: 0 }}> <ResponsiveContainer minWidth={0} width="100%" height={Math.max(220, Math.min(categoryRows.length, 15) * 26 + 40)}> <BarChart data={categoryRows.slice(0, 15).map((r: any) => ({ name: (r.category || "").substring(0, 22), revenue: Math.round(r.revenue), abc: r.abc_class }))} layout="vertical"> <CartesianGrid strokeDasharray="3 3" stroke="var(--shell-grid)" horizontal={false} /> <XAxis type="number" tickFormatter={(v) => `${(v/1000 * CCY_RATES[ccy]).toFixed(0)}k`} tick={{ fill: "var(--shell-muted)", fontSize: 10, fontFamily: "var(--font-inter)" }} /> <YAxis type="category" dataKey="name" tick={{ fill: "var(--shell-muted)", fontSize: 10, fontFamily: "var(--font-inter)" }} width={120} /> <Tooltip content={<TT />} /> <Bar dataKey="revenue" name="Revenue" radius={[0, 4, 4, 0]}> {categoryRows.slice(0, 15).map((r: any, i: number) => ( <Cell key={`cat-${i}`} fill={r.abc_class === "A" ? "var(--shell-good)" : r.abc_class === "B" ? "var(--shell-warn)" : "var(--shell-muted)"} /> ))} </Bar> </BarChart> </ResponsiveContainer> </div> <div style={{ minWidth: 0 }}> <DataTable<any> columns={categoryColumns} rows={categoryRows} rowKey={(r) => r.account_key} initialSort={{ key: "revenue", dir: "desc" }} searchPlaceholder="Filter accounts…" pageSize={15} emptyMessage="No customer categories yet — re-run the Visma extractor (v6.3+) and import dim_customers.csv" onRowClick={(r) => setCategoryFilter(prev => prev === r.category_code ? "" : r.category_code)} rowClickable={(r) => !!r.is_category} rowLabel={(r) => `Filter customers by ${r.category}`} exportName="customer_categories_abc" /> </div> </div> </Panel> )}
<Panel title={isFilteredByCustomer ? "Products Purchased" : "Customers by Revenue — ABC"} subtitle={isFilteredByCustomer ? `${productData.length} products` : `${customerData.length}${isNarrowed ? ` of ${allCustomers.length}` : ""} customers · click a header to sort · class per customer and per category`} full style={{ position: "relative" }} > <Panel title={isFilteredByCustomer ? "Products Purchased" : "Customers by Revenue"} subtitle={isFilteredByCustomer ? `${productData.length} products` : `Showing ${page * pageSize + 1}–${Math.min((page + 1) * pageSize, totalCount)} of ${totalCount}`} full style={{ position: "relative" }}> <div style={{ position: "absolute", top: 20, right: 24 }}> <ExportButton href={`${API}/api/export/analytics/customers${exportParams ? `?${exportParams}` : ""}`} label="Export Customers CSV" /> </div> {isFilteredByCustomer ? ( <DataTable<any> columns={productColumns} rows={productData} rowKey={(p) => p.sku} initialSort={{ key: "revenue", dir: "desc" }} searchPlaceholder="Filter products…" pageSize={25} /> <div style={{ overflowX: "auto" }}> <table style={{ width: "100%", fontSize: "0.78rem", borderCollapse: "collapse" }}> <thead> <tr style={{ textAlign: "left", borderBottom: "1px solid var(--shell-border)", color: "var(--shell-muted)" }}> <th style={{ padding: "8px 4px" }}>#</th> <th>SKU</th> <th>Product Name</th> <th style={{ textAlign: "right" }}>Qty</th> <th style={{ textAlign: "right" }}>Revenue</th> <th style={{ textAlign: "right", color: "var(--shell-warn)" }}>Est. Price Margin</th> <th style={{ textAlign: "right" }}>FIFO Margin</th> <th style={{ textAlign: "right" }}>Booked Margin</th> <th style={{ textAlign: "right" }}>FIFO %</th> </tr> </thead> <tbody> {productData.slice(0, 50).map((p: any, idx: number) => { const bookedPct = p.revenue ? ((p.margin || p.margin_visma || 0) / p.revenue * 100) : 0; return ( <tr key={p.sku} style={{ borderBottom: "1px solid var(--shell-grid)" }}> <td style={{ padding: "10px 4px", fontWeight: 600, color: idx < 3 ? "var(--shell-accent)" : "var(--shell-muted)" }}>#{idx + 1}</td> <td style={{ fontWeight: 500 }}>{p.sku}</td> <td style={{ color: "var(--shell-muted)" }}>{p.name}</td> <td style={{ textAlign: "right", whiteSpace: "nowrap" }}>{p.qty}</td> <td title={fmtMoney(p.revenue, ccy)} style={{ textAlign: "right", fontWeight: 600, whiteSpace: "nowrap" }}>{fmtMoneyCompact(p.revenue, ccy)}</td> <td title={fmtMoney(p.margin_kalkyl || 0, ccy)} style={{ textAlign: "right", color: "var(--shell-warn)", whiteSpace: "nowrap" }}>{fmtMoneyCompact(p.margin_kalkyl || 0, ccy)}</td> <td title={fmtMoney(p.margin_fifo, ccy)} style={{ textAlign: "right", color: p.margin_fifo > 0 ? "var(--shell-good)" : "var(--shell-bad)", fontWeight: 700, whiteSpace: "nowrap" }}>{fmtMoneyCompact(p.margin_fifo, ccy)}</td> <td style={{ textAlign: "right", color: bookedPct >= 30 ? "var(--shell-good)" : bookedPct >= 15 ? "var(--shell-ink-2)" : "var(--shell-bad)", fontWeight: 600, whiteSpace: "nowrap" }}>{bookedPct.toFixed(1)}%</td> <td style={{ textAlign: "right", color: p.margin_pct > 15 ? "var(--shell-good)" : p.margin_pct < 5 ? "var(--shell-bad)" : "var(--shell-muted)" }}> {p.margin_pct}% </td> </tr> ); })} </tbody> </table> </div> ) : ( <> <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center", marginBottom: 10, fontSize: "0.82rem" }}> <label htmlFor="customer-category-filter" style={{ color: "var(--shell-muted)" }}>Category</label> <select id="customer-category-filter" value={categoryFilter} onChange={e => setCategoryFilter(e.target.value)} style={{ background: 'var(--shell-surface)', border: '1px solid var(--shell-border)', borderRadius: 6, color: 'var(--shell-ink)', padding: '5px 8px', fontSize: '0.82rem', maxWidth: 260 }} > <option value="">All categories</option> {categoryOptions.map(o => <option key={o.key} value={o.key}>{o.label}{o.cls ? ` (${o.cls})` : ""}</option>)} </select> <label htmlFor="customer-abc-filter" style={{ color: "var(--shell-muted)", marginLeft: 8 }}>Class</label> <div style={{ overflowX: "auto" }}> <table style={{ width: "100%", fontSize: "0.78rem", borderCollapse: "collapse" }}> <thead> <tr style={{ textAlign: "left", borderBottom: "1px solid var(--shell-border)", color: "var(--shell-muted)" }}> <th style={{ padding: "8px 4px" }}>#</th> <th>Customer</th> <th>Country</th> <th style={{ textAlign: "right" }}>Invoices</th> <th style={{ textAlign: "right" }}>Revenue</th> <th style={{ textAlign: "right" }}>Margin %</th> <th>Top Product</th> <th style={{ textAlign: "right" }}>% of Total</th> </tr> </thead> <tbody> {paginatedCustomers.map((c: any, idx: number) => ( <tr key={`${c.customer_id}-${c.name}`} style={{ borderBottom: "1px solid var(--shell-grid)" }}> <td style={{ padding: "10px 4px", fontWeight: 600, color: (page * pageSize + idx) < 3 ? "var(--shell-accent)" : "var(--shell-muted)" }}>#{page * pageSize + idx + 1}</td> <td style={{ fontWeight: 500 }}>{c.name}</td> <td style={{ color: "var(--shell-muted)" }}>{c.country}</td> <td style={{ textAlign: "right", whiteSpace: "nowrap" }}>{c.invoices}</td> <td title={fmtMoney(c.revenue, ccy)} style={{ textAlign: "right", fontWeight: 600, whiteSpace: "nowrap" }}>{fmtMoneyCompact(c.revenue, ccy)}</td> <td style={{ textAlign: "right", color: c.margin_pct > 15 ? "var(--shell-good)" : c.margin_pct < 5 ? "var(--shell-bad)" : "var(--shell-muted)" }}> {c.margin_pct}% </td> <td> {c.top_product && c.top_product.sku !== "-" ? ( <span> <span style={{ fontWeight: 500 }}>{tName(c.top_product, lang)}</span> <span style={{ color: "var(--shell-muted)", marginLeft: 6, fontSize: "0.7rem" }}>{c.top_product.margin_pct}%</span> </span> ) : ( <span style={{ color: "var(--shell-muted)" }}>-</span> )} </td> <td style={{ textAlign: "right", color: c.pct_of_total > 10 ? "var(--shell-accent-2)" : "var(--shell-muted)" }}>{c.pct_of_total}%</td> </tr> ))} </tbody> </table> </div> )}
{!isFilteredByCustomer && totalPages > 1 && ( <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 16, padding: '0 4px' }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: '0.85rem', color: 'var(--shell-ink-2)' }}> <label htmlFor="customer-page-size-select">Rows per page:</label> <select id="customer-abc-filter" value={abcFilter} onChange={e => setAbcFilter(e.target.value)} style={{ background: 'var(--shell-surface)', border: '1px solid var(--shell-border)', borderRadius: 6, color: 'var(--shell-ink)', padding: '5px 8px', fontSize: '0.82rem' }} > <option value="">All</option> <option value="A">A — top 80%</option> <option value="B">B — next 15%</option> <option value="C">C — last 5%</option> id="customer-page-size-select" value={pageSize} onChange={e => { const newSize = Number(e.target.value); if (onPageChange) { onPageChange(0, newSize); } else { setInternalPageSize(newSize); setInternalPage(0); } }} style={{ background: 'var(--shell-surface)', border: '1px solid var(--shell-border)', borderRadius: 6, color: 'var(--shell-ink)', padding: '6px 10px', fontSize: '0.85rem', cursor: 'pointer', outline: 'none' }}> {PAGE_SIZE_OPTIONS.map(s => <option key={s} value={s}>{s}</option>)} </select> {isNarrowed && ( <button type="button" className="btn btn-secondary" onClick={() => { setCategoryFilter(""); setAbcFilter(""); }} style={{ padding: '4px 10px', fontSize: '0.78rem' }}>Clear</button> )} </div> <DataTable<any> columns={customerColumns} rows={customerData} rowKey={(c) => `${c.customer_id}-${c.name}`} initialSort={{ key: "revenue", dir: "desc" }} searchPlaceholder="Filter customers…" pageSize={25} emptyMessage="No customers match the selected category / class" /> </> <div style={{ display: 'flex', gap: 6 }}> <button className="btn btn-secondary" onClick={() => handlePageChange(0)} disabled={page === 0} style={{ padding: '6px 12px', fontSize: '0.82rem' }}>«</button> <button className="btn btn-secondary" onClick={() => handlePageChange(page - 1)} disabled={page === 0} style={{ padding: '6px 12px', fontSize: '0.82rem' }}>‹ Prev</button> <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}> {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => { const p = totalPages <= 7 ? i : page < 4 ? i : page > totalPages - 4 ? totalPages - 7 + i : page - 3 + i; return ( <button key={p} onClick={() => handlePageChange(p)} className={p === page ? 'btn btn-primary' : 'btn btn-secondary'} style={{ padding: '6px 11px', fontSize: '0.82rem', minWidth: 36 }}>{p + 1}</button> ); })} </div> <button className="btn btn-secondary" onClick={() => handlePageChange(page + 1)} disabled={page >= totalPages - 1} style={{ padding: '6px 12px', fontSize: '0.82rem' }}>Next ›</button> <button className="btn btn-secondary" onClick={() => handlePageChange(totalPages - 1)} disabled={page >= totalPages - 1} style={{ padding: '6px 12px', fontSize: '0.82rem' }}>»</button> </div> </div> )} </Panel>
<Panel title="Customer Performance Matrix" subtitle="Revenue vs Margin analysis — all cost bases" full> <DataTable<any> columns={matrixColumns} rows={customerData} rowKey={(c) => `${c.customer_id}-${c.name}-perf`} initialSort={{ key: "revenue", dir: "desc" }} searchPlaceholder="Filter customers…" pageSize={25} /> <div style={{ overflowX: "auto" }}> <table style={{ width: "100%", fontSize: "0.78rem", borderCollapse: "collapse" }}> <thead> <tr style={{ textAlign: "left", borderBottom: "1px solid var(--shell-border)", color: "var(--shell-muted)" }}> <th style={{ padding: "8px 4px" }}>Customer</th> <th>Country</th> <th style={{ textAlign: "right" }}>Revenue</th> <th style={{ textAlign: "right" }}>Booked (Visma)</th> <th style={{ textAlign: "right", color: "var(--shell-warn)" }}>Est. Price</th> <th style={{ textAlign: "right", color: "var(--shell-good)" }}>FIFO (LPP)</th> <th style={{ textAlign: "right", color: "var(--shell-good)" }}>Booked %</th> <th style={{ textAlign: "right", color: "var(--shell-accent)" }}>FIFO %</th> <th style={{ textAlign: "right", color: "var(--shell-warn)" }}>Est. Price %</th> <th style={{ textAlign: "right" }}>Products</th> </tr> </thead> <tbody> {paginatedCustomers.map((c: any, idx: number) => { const bookedPct = c.revenue ? ((c.margin_visma || 0) / c.revenue * 100) : 0; const fifoPct = c.revenue ? ((c.margin_fifo || 0) / c.revenue * 100) : 0; const estPct = c.revenue ? ((c.margin_kalkyl || 0) / c.revenue * 100) : 0; return ( <tr key={`${c.customer_id}-${c.name}-perf`} style={{ borderBottom: "1px solid var(--shell-grid)" }}> <td style={{ padding: "10px 4px", fontWeight: 500, whiteSpace: "nowrap" }}>{c.name}</td> <td style={{ color: "var(--shell-muted)", whiteSpace: "nowrap" }}>{c.country}</td> <td title={fmtMoney(c.revenue, ccy)} style={{ textAlign: "right", fontWeight: 600, whiteSpace: "nowrap" }}>{fmtMoneyCompact(c.revenue, ccy)}</td> <td title={fmtMoney(c.margin_visma || 0, ccy)} style={{ textAlign: "right", color: "var(--shell-muted)", whiteSpace: "nowrap" }}>{fmtMoneyCompact(c.margin_visma || 0, ccy)}</td> <td title={fmtMoney(c.margin_kalkyl || 0, ccy)} style={{ textAlign: "right", color: "var(--shell-warn)", whiteSpace: "nowrap" }}>{fmtMoneyCompact(c.margin_kalkyl || 0, ccy)}</td> <td title={fmtMoney(c.margin_fifo || 0, ccy)} style={{ textAlign: "right", color: c.margin_fifo > 0 ? "var(--shell-good)" : "var(--shell-bad)", fontWeight: 700, whiteSpace: "nowrap" }}>{fmtMoneyCompact(c.margin_fifo || 0, ccy)}</td> <td style={{ textAlign: "right", color: bookedPct >= 30 ? "var(--shell-good)" : bookedPct >= 15 ? "var(--shell-ink-2)" : "var(--shell-bad)", fontWeight: 600 }}>{bookedPct.toFixed(1)}%</td> <td style={{ textAlign: "right", color: fifoPct >= 30 ? "var(--shell-accent)" : fifoPct >= 15 ? "var(--shell-ink-2)" : "var(--shell-bad)", fontWeight: 600 }}>{fifoPct.toFixed(1)}%</td> <td style={{ textAlign: "right", color: estPct >= 30 ? "var(--shell-warn)" : estPct >= 15 ? "var(--shell-ink-2)" : "var(--shell-bad)", fontWeight: 600 }}>{estPct.toFixed(1)}%</td> <td style={{ textAlign: "right" }}>{c.product_count || 0}</td> </tr> ); })} </tbody> </table> </div> </Panel> </div> </div>116 unmodified lines117118119120120121122123124 unmodified lines24824925025125125225325448 unmodified lines303304305306306307307308309310311116 unmodified lines <Field label="Ordered">{h.order_date}</Field> <Field label="Promised">{h.delivery_date}</Field> <Field label="Status"> {boolChip(h.delivered, "Delivered", h.not_done ? "Open · not finalised" : "Open", "var(--shell-good)", "var(--shell-warn)")} {h.not_done ? <Chip text="Voided" color="var(--shell-muted)" /> : boolChip(h.delivered, "Delivered", "Open", "var(--shell-good)", "var(--shell-warn)")} </Field> <Field label="Total">{fx(h.total_fx, h.currency_code)}</Field> <Field label={`Total (${ccy})`}>{fmtMoney(h.total_sek, ccy)}</Field>124 unmodified lines <Field label="Ordered">{h.order_date}</Field> <Field label="Promised">{h.delivery_date}</Field> <Field label="Status"> {boolChip(h.delivered, "Delivered", h.not_done ? "Open · not finalised" : "Open", "var(--shell-good)", "var(--shell-warn)")} {h.not_done ? <Chip text="Voided" color="var(--shell-muted)" /> : boolChip(h.delivered, "Delivered", "Open", "var(--shell-good)", "var(--shell-warn)")} </Field> {h.is_internal ? <Field label="Kind"><Chip text="Internal (Produktion)" color="var(--shell-accent)" /></Field>48 unmodified lines <Field label="Issued">{h.offer_date}</Field> <Field label="Valid until">{h.valid_until}</Field> <Field label="Status"> {h.not_done ? <Chip text="Voided" color="var(--shell-muted)" /> {data.order ? <Chip text="Converted" color="var(--shell-good)" /> : <Chip text={h.not_done ? "Open · not finalised" : "Open"} color="var(--shell-warn)" />} : data.order ? <Chip text="Converted" color="var(--shell-good)" /> : <Chip text="Open" color="var(--shell-warn)" />} </Field> <Field label="Total excl. VAT">{fx(h.total_excl_vat_fx, h.currency_code)}</Field> <Field label={`Total (${ccy})`}>{fmtMoney(h.total_excl_vat_sek, ccy)}</Field>74 unmodified lines75767778798081827879808161 unmodified lines14314414515014614714814915015515615715815916016116216316415115215374 unmodified lines // a dimension filter and once the ledger has postings in the window. const costAvailable = kpis.freight_cost_available === true; const freightCost = costAvailable ? (kpis.freight_cost_sek || 0) : 0; // Freight Visma kept on cancelled invoices: nothing invoiced, carrier still // paid — a cost we absorbed. Attributable per invoice, so always available. const cancelledCost: number = kpis.freight_cancelled_cost_sek || 0; const cancelledInvoices: number = kpis.freight_cancelled_invoices || 0; const freightNet = costAvailable ? (kpis.freight_net_sek ?? (totalFreight - freightCost - cancelledCost)) : 0; const freightNet = costAvailable ? (kpis.freight_net_sek ?? (totalFreight - freightCost)) : 0; const freightNetPct = costAvailable && totalFreight > 0 ? (freightNet / totalFreight * 100) : null; const costFrom: string | null = kpis.freight_cost_from || null; const costSub = costAvailable61 unmodified lines value={costAvailable ? fmtMoneyCompact(freightNet, ccy) : '—'} fullValue={costAvailable ? fmtMoney(freightNet, ccy) : undefined} sub={costAvailable ? `invoiced − carrier cost${cancelledCost ? ' − cancelled-invoice freight' : ''}${freightNetPct != null ? ` · ${freightNetPct.toFixed(1)}% of invoiced` : ''}` ? `invoiced − carrier cost${freightNetPct != null ? ` · ${freightNetPct.toFixed(1)}% of invoiced` : ''}` : 'needs carrier cost from the ledger'} color={freightNet < 0 ? 'var(--shell-bad)' : 'var(--shell-good)'} danger={costAvailable && freightNet < 0} /> {cancelledInvoices > 0 && ( <KpiCard label="Cancelled-invoice Freight" value={fmtMoneyCompact(cancelledCost, ccy)} fullValue={fmtMoney(cancelledCost, ccy)} sub={`cost, not invoiced · ${fmtNum(cancelledInvoices)} cancelled invoices kept their freight`} color="var(--shell-bad)" danger /> )} <KpiCard label="Coded Freight" value={fmtMoneyCompact(codedFreight, ccy)}35 unmodified lines36373839404139404116 unmodified lines58596064616263646566716768697019 unmodified lines909192979899100101102103104939495112 unmodified lines20820921022322422522622721121221376 unmodified lines29029129231031131231331431531631729329429515 unmodified lines31131231333934034134234334434534631431531642 unmodified lines35936036139536236336427 unmodified lines39239339442943043143239539639739818 unmodified lines41741841945745845946046146246346446542042142242342442535 unmodified lines in_ledger: boolean; ledger_scope: string | null; billed: boolean; /** Freight Visma kept on a CANCELLED invoice — a cost we absorbed, never * revenue (revenue is null on that row). Null on every other row. */ cancelled_cost: number | null; supplier: string | null; item_id: number | null;};16 unmodified lines customer_country: string | null; customer_currency: string | null; customer_is_export: boolean | null; is_cancelled: boolean; }; totals: { net: number; vat: number; total_incl_vat: number; goods_gross: number; amount_paid: number; balance: number; settled: boolean; cargo: number; dispatch_fee: number; round_off: number; cargo_vat_code: string | null; dispatch_vat_code: string | null; cost: number; cancelled_freight_cost: number; margin_header: number; margin_lines: number; cost: number; margin_header: number; margin_lines: number; margin_pct: number | null; margin_divergence: number; line_sum: number; recon_diff: number; reconciled: boolean; line_count: number; hidden_line_count: number;19 unmodified lines 'Not shown by any of the Products / Service / Freight tabs — synthetic ' + 'reconciliation row, non-billed row, or a row type those scopes exclude.';
const CANCELLED_TIP = 'Cancelled in Visma: every line has nothing delivered or billed, the goods value is 0 and ' + 'no ledger voucher exists. Visma keeps the freight on the header — it is booked here as a ' + 'cost we absorbed, not as invoiced freight.';const CANCELLED_ROW_TIP = 'Freight Visma kept on this cancelled invoice. Nothing was invoiced, so this is a cost ' + '(the carrier was still paid), not revenue.';
const Fact = ({ label, children }: { label: string; children: React.ReactNode }) => ( <div> <div className="r-inv-fact-l">{label}</div>112 unmodified lines <div className="r-inv-title"> <h2>{h.invoice_number}</h2> {h.is_credit_note && <span className="r-tag bad">Credit note</span>} {h.is_cancelled && ( <span className="r-tag bad" title={CANCELLED_TIP} data-testid="invoice-drawer-cancelled"> Cancelled </span> )} <span className={`r-tag ${t.settled ? 'good' : 'warn'}`}> {t.settled ? 'Settled' : 'Open'} </span>76 unmodified lines <div className="r-inv-card"> <h3>Cost & margin (as posted)</h3> <Row k="Cost (kalkylpris)" v={money(t.cost)} /> {t.cancelled_freight_cost !== 0 && ( <Row k="Freight on cancelled invoice" v={money(t.cancelled_freight_cost)} cls="neg" tip={CANCELLED_ROW_TIP} /> )} <Row k="Margin — header" v={money(t.margin_header)} cls={signCls(t.margin_header)} /> <Row k="Margin — lines" v={money(t.margin_lines)} cls={signCls(t.margin_lines)} /> {Math.abs(t.margin_divergence) > 0.5 && (15 unmodified lines <div className="r-inv-card"> <h3>Reconciliation</h3> <Row k={`Sum of ${t.line_count} lines`} v={money(t.line_sum)} /> {t.cancelled_freight_cost !== 0 && ( <Row k="+ freight on cancelled invoice (cost)" v={money(t.cancelled_freight_cost)} cls="muted" tip="Visma leaves this freight in the header net of a cancelled invoice, so it is what makes the document add up — as a cost, not revenue" /> )} <Row k="Header net" v={money(t.net)} /> <Row k="Difference"42 unmodified lines { label: 'Revenue_SEK', value: (l: DetailLine) => l.revenue }, { label: 'Margin_SEK', value: (l: DetailLine) => l.margin }, { label: 'Margin_Pct', value: (l: DetailLine) => (l.margin_pct == null ? null : Math.round(l.margin_pct * 100) / 100) }, { label: 'Cancelled_Freight_Cost_SEK', value: (l: DetailLine) => l.cancelled_cost }, ]} rows={data.lines} />27 unmodified lines {!l.in_ledger && ( <span className="r-tag warn" title={HIDDEN_ROW_TIP}>Not in ledger</span> )} {l.cancelled_cost != null && ( <span className="r-tag bad" title={CANCELLED_ROW_TIP}>Cancelled · cost</span> )} {!l.billed && l.cancelled_cost == null && ( {!l.billed && ( <span className="r-tag" title="Ordered but nothing delivered or invoiced on this row"> Not billed </span>18 unmodified lines > {l.unit_cost != null ? fmtMoney(l.unit_cost, ccy) : '—'} </td> <td className="num-strong"> {l.cancelled_cost != null ? <span className="muted" title={CANCELLED_ROW_TIP}>not invoiced</span> : l.revenue != null ? fmtMoney(l.revenue, ccy) : '—'} </td> <td className={l.cancelled_cost != null ? 'neg' : signCls(l.margin)}> {l.cancelled_cost != null ? <span title={CANCELLED_ROW_TIP}>−{fmtMoney(l.cancelled_cost, ccy)} cost</span> : l.margin != null ? fmtMoney(l.margin, ccy) : '—'} <td className="num-strong">{l.revenue != null ? fmtMoney(l.revenue, ccy) : '—'}</td> <td className={signCls(l.margin)}> {l.margin != null ? fmtMoney(l.margin, ccy) : '—'} </td> <td className={l.margin_pct != null && l.margin_pct < 0 ? 'neg' : ''}> {l.margin_pct != null ? `${l.margin_pct.toFixed(1)}%` : '—'}30 unmodified lines31323334353634353614 unmodified lines515253575854555642 unmodified lines99100101107108109110102103104106 unmodified lines21121221322322422522622722822923023121421521683 unmodified lines30030130232132230330430530614 unmodified lines32132232334334434534632432532632717 unmodified lines34534634737037137237337434834935035130 unmodified lines revenue: number | null; margin: number | null; margin_pct: number | null; /** Freight Visma kept on a CANCELLED invoice — a cost, never revenue * (revenue is null on that row). Null on every other row. */ cancelled_cost: number | null; category: string | null; account_number: string | null; row_source: string | null;14 unmodified lines line_count: number; invoice_count: number; no_cost_count: number; cancelled_freight_cost: number; cancelled_freight_count: number; };};
42 unmodified lines// price to show — the whole amount sits in Invoiced freight.const HEADER_FREIGHT_TIP = 'Freight charged at the invoice-header level in Visma — no article, quantity or unit price exists. This synthetic line carries the whole amount so the invoice total reconciles with its lines.';const HEADER_FREIGHT_NA_TIP = 'Not applicable — header-level freight has no article, quantity or unit price; the whole amount is in Invoiced freight.';// 'cancelled_freight' rows (chip "X"): the invoice was cancelled in Visma// (nothing delivered or billed, no ledger voucher) but the header kept its// freight. That freight is a cost we absorbed — never invoiced freight.const CANCELLED_FREIGHT_TIP = 'Cancelled invoice: nothing was delivered or billed, yet Visma left the freight on the header. Booked as a cost we absorbed (the carrier was still paid) — not invoiced freight.';const colLabel = (c: ColumnDef, scope: LinesScope) => c.key === 'revenue' && scope === 'freight' ? 'Invoiced freight' : c.label;
106 unmodified lines fullValue={fmtMoney(kpis.revenue, ccy)} sub={scope === 'freight' ? 'charged to customers · incl. header-level freight' : `${fmtNum(kpis.invoice_count)} invoices`} /> {scope === 'freight' && (kpis.cancelled_freight_count || 0) > 0 && ( <KpiCard label="Cancelled-invoice freight" value={fmtMoneyCompact(kpis.cancelled_freight_cost, ccy)} fullValue={fmtMoney(kpis.cancelled_freight_cost, ccy)} sub={`cost, not invoiced · ${fmtNum(kpis.cancelled_freight_count)} cancelled invoices`} danger /> )} {scope !== 'freight' ? ( <> <KpiCard83 unmodified lines {data && data.rows.map((r) => { const m = r.margin; const marginCls = m == null ? 'muted' : m < 0 ? 'neg' : m > 0 ? 'pos' : 'muted'; const isCancelledFreight = r.row_source === 'cancelled_freight'; const isHeaderFreight = r.row_source === 'header_freight' || isCancelledFreight; const isHeaderFreight = r.row_source === 'header_freight'; return ( <tr key={r.id}14 unmodified lines {scope !== 'products' && ( <td className="l muted"> {r.category ?? '—'} {isCancelledFreight ? ( <span className="r-tag bad" style={{ marginLeft: 6 }} title={CANCELLED_FREIGHT_TIP}>Cancelled · cost</span> ) : isHeaderFreight && ( {isHeaderFreight && ( <span className="r-abc-chip C sm" style={{ marginLeft: 6 }} title={HEADER_FREIGHT_TIP}>H</span> )}17 unmodified lines {r.unit_cost != null ? fmtMoney(r.unit_cost, ccy) : '—'} </td> )} <td className={isCancelledFreight ? 'neg' : 'num-strong'}> {isCancelledFreight ? <span title={CANCELLED_FREIGHT_TIP}>−{fmtMoney(r.cancelled_cost ?? 0, ccy)} cost</span> : r.revenue != null ? fmtMoney(r.revenue, ccy) : '—'} </td> <td className="num-strong">{r.revenue != null ? fmtMoney(r.revenue, ccy) : '—'}</td> {scope !== 'freight' && ( <> <td className={marginCls} title={MARGIN_TIP}>29 unmodified lines30313233343536333435216 unmodified lines25225325425926026126226326426525525625729 unmodified lines reconciled: boolean; balance: number; settled: boolean; /** Cancelled in Visma — nothing delivered or billed; the freight it still * carries is booked as a cost, not as invoiced freight. */ cancelled: boolean; cancelled_freight_cost: number;};
type InvoicesResponse = {216 unmodified lines {r.invoice_type === 'K' && ( <span className="r-abc-chip C sm" style={{ marginLeft: 6 }} title="Credit note">K</span> )} {r.cancelled && ( <span className="r-tag bad" style={{ marginLeft: 6 }} title={`Cancelled in Visma — nothing delivered or billed. The ${fmtMoney(r.cancelled_freight_cost, ccy)} of freight left on the header is a cost, not revenue.`} >Cancelled</span> )} </td> <td className="l name">{r.customer_name ?? <span className="muted">—</span>}</td> <td className="l muted">{r.customer_country ?? '—'}</td>31 unmodified lines3233343535363781 unmodified lines11912012112312412512612712812913013113212212312437 unmodified lines16216316417617716516616716816931 unmodified lines status: OrderStatus; days_late: number; is_internal: boolean; not_finalised: boolean; // Visma "Ej klar" — open, not yet print-ready seller_code: string | null;}interface Backlog {81 unmodified lines d90_plus: "var(--shell-bad)",};
const NOT_FINALISED_TITLE = "Marked 'Ej klar' (not finalised) in Visma — still an open order, counted in the backlog";
function notFinalisedMark() { return ( <span title={NOT_FINALISED_TITLE} style={{ marginLeft: 6, fontSize: 10.5, fontWeight: 600, color: "var(--shell-muted)" }}> · not finalised </span> );}
function statusChip(status: OrderStatus, daysLate: number, internal = false) { if (status === "to_invoice") { // Goods are out the door; the order just has not been closed in Visma.37 unmodified lines : []), { key: "ordered", label: "Ordered", numeric: true, value: o => o.order_date }, { key: "promised", label: "Promised", numeric: true, value: o => o.delivery_date }, { key: "status", label: "Status", value: o => STATUS_META[o.status].label + (o.not_finalised ? " · not finalised" : ""), render: o => <>{statusChip(o.status, o.days_late, !withValue)}{o.not_finalised && notFinalisedMark()}</> }, { key: "status", label: "Status", value: o => STATUS_META[o.status].label, render: o => statusChip(o.status, o.days_late, !withValue) }, { key: "delivered", label: "Delivered", numeric: true, value: o => o.delivered_pct, render: o => (o.delivered_pct === null ? "—" : `${o.delivered_pct.toFixed(0)}%`) }, ];.dockerignore-5
Dockerfile-4
backend/alembic/versions/a1c5e7b93d20_customer_category.pyDeleted-35
backend/app_version.py+1-1
backend/backup.py-81
backend/etl_package.pyDeleted-144
backend/models.py-6
backend/release_notes.py-88
backend/routers/admin.py+6-21
backend/routers/dashboard.py+1-121
backend/routers/etl_sync.py+3-101
backend/routers/exports.py+6-39
backend/routers/imports.py+27-113
backend/routers/invoice_lines.py+7-40
backend/routers/invoices.py+9-37
backend/routers/management_dashboard.py+2-3
backend/routers/procurement.py+3-4
backend/routers/sales_insights.py+7-13
backend/schemas.py-2
backend/tests/test_customer_abc.pyDeleted-150
backend/tests/test_etl_package.pyDeleted-106
backend/tests/test_management_dashboard.py+6-8
backend/tests/test_portable_snapshot.pyDeleted-137
backend/tests/test_procurement.py+7-9
backend/tests/test_sales_insights.py+18-24
backend/tests/test_synthetic_rows.py-135
backend/tests/test_translation.py+2-10
docs/gateway_visma_pipeline_reference.md-1
etl/README.md-38
etl/force_sync_agent.py+5-214
etl/tests/test_agent_self_update.pyDeleted-138
etl/visma_unified_extractor.py+2-48
frontend/src/app/admin/page.tsx+1-30
frontend/src/app/page.tsx-7
frontend/src/components/analytics/CustomerAnalytics.tsx+194-243
frontend/src/components/analytics/DetailDrawer.tsx+5-4
frontend/src/components/analytics/FreightDashboard.tsx+2-16
frontend/src/components/analytics/InvoiceDetailDrawer.tsx+5-48
frontend/src/components/analytics/InvoiceLinesTable.tsx+3-29
frontend/src/components/analytics/InvoicesTable.tsx-11
frontend/src/components/analytics/SalesInsights.tsx+2-13