Packages

Elixir client for Polish GUS BIR (Baza Internetowa Regon) service. Search and retrieve business entity data from CEIDG, KRS, and RSPO registries.

Current section

Files

Jump to
gusex lib gusex.ex
Raw

lib/gusex.ex

defmodule Gusex do
@moduledoc """
Elixir client for Polish GUS BIR (Baza Internetowa Regon) service.
Gusex enables searching and retrieving business entity data from Polish registries
including CEIDG, KRS, and RSPO, which are synchronised into the BIR database.
## Installation
Add `gusex` to your list of dependencies in `mix.exs`:
def deps do
[{:gusex, "~> 1.0"}]
end
## Configuration
config :gusex,
api_key: "your_production_api_key",
environment: :production # or :test
For testing, the default test environment and key are used automatically.
### Session cache (optional)
The convenience API (e.g. `find_by_nip/1`) relies on `Gusex.SessionCache`,
a GenServer-backed ETS cache that holds authenticated sessions and reuses
them across calls, avoiding redundant logins against the BIR service.
Add it to your application's supervision tree:
defmodule MyApp.Application do
use Application
def start(_type, _args) do
children = [
Gusex.SessionCache,
# ... other children
]
Supervisor.start_link(children, strategy: :one_for_one)
end
end
The cache reads credentials from the same `:gusex` application config
(`:api_key`, `:environment`) and exposes a single tunable:
config :gusex,
session_ttl: 3000 # seconds; default 3000 (50 min, below the 60 min hard limit)
The low-level API (`zaloguj/2`, `dane_szukaj_podmioty/2`, etc.) does not
require the cache and can be used directly with manually managed sessions.
## Quick Start
# Low-level API with manual session management
{:ok, session} = Gusex.zaloguj()
{:ok, entities} = Gusex.dane_szukaj_podmioty(%{Nip: "5260001246"}, session)
{:ok, report} = Gusex.dane_pobierz_pelny_raport("000331501", "BIR12OsPrawna", session)
{:ok, true} = Gusex.wyloguj(session)
# Convenience API (requires Gusex.SessionCache in the supervision tree)
{:ok, entities} = Gusex.find_by_nip("5261040828")
## Main Functions
* `zaloguj/2` / `login/2` - Authenticate with the BIR service
* `dane_szukaj_podmioty/2` / `search_entities/2` - Search for business entities
* `dane_pobierz_pelny_raport/3` / `get_full_report/3` - Get detailed entity report
* `dane_pobierz_raport_zbiorczy/3` / `get_aggregate_report/3` - Get aggregate reports
* `get_value/2` - Retrieve service parameters
* `wyloguj/1` / `logout/1` - End session
* `find_by_nip/1` - Convenience lookup by NIP using the session cache
Both Polish (original API names) and English function names are provided.
"""
alias Gusex.Client
alias Gusex.Search
@doc """
Logs in to the BIR (Business Information Registry) service.
This function authenticates with the Polish GUS BIR service using the provided credentials.
If parameters are not provided, they will be read from the application configuration.
## Parameters
* `user_key` - The API key for authentication (optional). If not provided, reads from
`:gusex, :api_key` config.
* `environment` - The environment to connect to (optional). Can be `:test` or `:production`.
If not provided, reads from `:gusex, :environment` config, defaults to `:test`.
## Returns
* `{:ok, session}` - A Session struct containing the session ID, environment, and endpoint URL
* `{:error, :api_key_missing}` - When no API key is provided or configured
* `{:error, :login_failure}` - When authentication fails
* `{:error, reason}` - Other errors with specific reason
## Examples
# Using explicit parameters
{:ok, session} = Gusex.zaloguj("your_api_key", :production)
# Using test environment with test key
{:ok, session} = Gusex.zaloguj("abcde12345abcde12345", :test)
# Using application configuration
# In config/config.exs:
# config :gusex,
# api_key: "your_api_key",
# environment: :production
{:ok, session} = Gusex.zaloguj()
"""
defdelegate zaloguj(user_key \\ nil, environment \\ nil), to: Client
@doc """
Alias for `zaloguj/2`. Logs in to the BIR (Business Information Registry) service.
See `zaloguj/2` for full documentation.
"""
defdelegate login(user_key \\ nil, environment \\ nil), to: Client, as: :zaloguj
@doc """
Searches for entities in the BIR registry based on provided search parameters.
This function allows searching for business entities in the Polish business registry
using various identifiers like NIP, REGON, or KRS numbers.
## Parameters
* `search_params` - Search criteria as either a `ParametryWyszukiwania` struct or a map.
**At least one search key must be provided.** If multiple keys are provided, only
the first one (in the alphabetic order) will be used for the search. Available keys:
* `:Krs` - Single 10-digit Court Register number
* `:Krsy` - String of 10-digit KRS identifiers, separated by any non-digit separator
or without separators, max 20 identifiers
* `:Nip` - Single 10-digit Tax Identification Number
* `:Nipy` - String of 10-digit NIP identifiers, separated by any non-digit separator
or without separators, max 20 identifiers
* `:Regon` - Single REGON number (9 or 14 digits)
* `:Regony14zn` - String of 14-digit REGON identifiers, separated by any non-digit
separator or without separators, max 20 identifiers
* `:Regony9zn` - String of 9-digit REGON identifiers, separated by any non-digit
separator or without separators, max 20 identifiers
* `session` - A valid Session struct obtained from `zaloguj/2`
## Returns
* `{:ok, [Podmiot.t()]}` - List of found entities
* `{:error, map()}` - Error details from the BIR service
* `{:error, {:invalid_search_params, String.t()}}` - Invalid map keys provided
## Examples
# Search by single NIP
{:ok, session} = Gusex.zaloguj()
search_params = %{Nip: "5261040828"}
{:ok, entities} = Gusex.dane_szukaj_podmioty(search_params, session)
# Search by multiple REGONs
search_params = %{Regony9zn: "000331501 016128070"}
{:ok, entities} = Gusex.dane_szukaj_podmioty(search_params, session)
"""
defdelegate dane_szukaj_podmioty(search_params, session), to: Client
@doc """
Alias for `dane_szukaj_podmioty/2`. Searches for entities in the BIR registry.
See `dane_szukaj_podmioty/2` for full documentation.
"""
defdelegate search_entities(search_params, session), to: Client, as: :dane_szukaj_podmioty
@doc """
Retrieves a full report for a specific entity identified by REGON.
This function fetches various, detailed information sets about
a business entity from the BIR registry using its REGON number.
## Parameters
* `regon` - The REGON number of the entity (9 or 14 digits)
* `report_name` - The type of report to retrieve. Common types include:
* `"BIR12OsPrawna"` - Legal entity data
* `"BIR12OsFizycznaDaneOgolne"` - Natural person general data
* `"BIR12OsFizycznaDzialalnoscCeidg"` - Natural person CEIDG activity
* `"BIR12OsPrawnaListaJednLokalnych"` - Legal entity's local units list
* And many others (see BIR documentation for full list)
* `session` - A valid Session struct obtained from `zaloguj/2`
## Returns
* `{:ok, list()}` - Report data (structure depends on report type)
* `{:error, map()}` - Error details from the BIR service
## Examples
{:ok, session} = Gusex.zaloguj()
# Get legal entity report
{:ok, report} = Gusex.dane_pobierz_pelny_raport("000331501", "BIR12OsPrawna", session)
# Get natural person general data
{:ok, report} = Gusex.dane_pobierz_pelny_raport("123456789", "BIR12OsFizycznaDaneOgolne", session)
"""
defdelegate dane_pobierz_pelny_raport(regon, report_name, session), to: Client
@doc """
Alias for `dane_pobierz_pelny_raport/3`. Retrieves a full report for a specific entity.
See `dane_pobierz_pelny_raport/3` for full documentation.
"""
defdelegate get_full_report(regon, report_name, session), to: Client, as: :dane_pobierz_pelny_raport
@doc """
Retrieves an aggregate report for a specific date.
This function fetches collective/aggregate reports from the BIR registry that contain
information about multiple entities that changed on a specific date (new, updated, or deleted).
## Parameters
* `report_date` - The date for the report in "YYYY-MM-DD" format
* `report_name` - The type of aggregate report to retrieve. Types include:
* `"BIR11NoweJednostkiLokalne"` - New local units
* `"BIR11NowePodmiotyPrawneOrazDzialalnosciOsFizycznych"` - New legal entities and natural person activities
* `"BIR11AktualizowaneJednostkiLokalne"` - Updated local units
* `"BIR11AktualizowanePodmiotyPrawneOrazDzialalnosciOsFizycznych"` - Updated legal entities and natural person activities
* `"BIR11SkresloneJednostkiLokalne"` - Deleted local units
* `"BIR11SkreslonePodmiotyPrawneOrazDzialalnosciOsFizycznych"` - Deleted legal entities and natural person activities
* `session` - A valid Session struct obtained from `zaloguj/2`
## Returns
* `{:ok, list()}` - List of report entries (structure depends on report type)
* `{:error, map()}` - Error details from the BIR service
## Examples
{:ok, session} = Gusex.zaloguj()
# Get new entities for a specific date
{:ok, report} = Gusex.dane_pobierz_raport_zbiorczy("2024-01-15", "BIR11NowePodmiotyPrawneOrazDzialalnosciOsFizycznych", session)
# Get deleted local units for a specific date
{:ok, report} = Gusex.dane_pobierz_raport_zbiorczy("2024-01-15", "BIR11SkresloneJednostkiLokalne", session)
"""
defdelegate dane_pobierz_raport_zbiorczy(report_date, report_name, session), to: Client
@doc """
Alias for `dane_pobierz_raport_zbiorczy/3`. Retrieves an aggregate report for a specific date.
See `dane_pobierz_raport_zbiorczy/3` for full documentation.
"""
defdelegate get_aggregate_report(report_date, report_name, session), to: Client, as: :dane_pobierz_raport_zbiorczy
@doc """
Retrieves a system parameter value from the BIR service.
This function allows querying various system parameters and service status information
from the BIR registry. Some parameters can be retrieved without authentication.
## Parameters
* `param_name` - The name of the parameter to retrieve. Common parameters:
* `"KomunikatUslugi"` - Service message (can be retrieved without session)
* `"StatusSesji"` - Session status
* `"KomunikatKod"` - Message code
* `"KomunikatTresc"` - Message content
* `"StanDanych"` - Data state
* `session` - A valid Session struct or `nil` for parameters that don't require
authentication (currently only "KomunikatUslugi")
## Returns
* `{:ok, String.t()}` - The parameter value
* `{:error, any()}` - Error details if retrieval fails
## Examples
# Get service message without authentication
{:ok, message} = Gusex.get_value("KomunikatUslugi")
# Get session status with authentication
{:ok, session} = Gusex.zaloguj()
{:ok, status} = Gusex.get_value("StatusSesji", session)
"""
defdelegate get_value(param_name, session \\ nil), to: Client
@doc """
Logs out from the BIR service and terminates the session.
This function ends the authenticated session with the BIR registry service,
freeing up resources on the server side.
## Parameters
* `session` - A valid Session struct obtained from `zaloguj/2`
## Returns
* `{:ok, true}` - Logout was successful
* `{:ok, false}` - Logout was unsuccessful (but no error occurred)
* `{:error, :invalid_session}` - Invalid session provided
* `{:error, reason}` - Other logout failures
## Examples
{:ok, session} = Gusex.zaloguj()
# Do some operations...
{:ok, true} = Gusex.wyloguj(session)
"""
defdelegate wyloguj(session), to: Client
@doc """
Alias for `wyloguj/1`. Logs out from the BIR service.
See `wyloguj/1` for full documentation.
"""
defdelegate logout(session), to: Client, as: :wyloguj
@doc """
Finds a business entity by NIP using a cached session.
This is a convenience function that handles session management automatically
via `Gusex.SessionCache`. It obtains a cached session (or logs in if needed),
performs the search, and transparently retries once if the call fails with a
retriable error (an empty response or an HTTP-level failure).
Requires `Gusex.SessionCache` to be running in the supervision tree.
## Parameters
* `nip` - A 10-digit Polish Tax Identification Number (NIP) as a string
## Returns
* `{:ok, [%Gusex.Types.Podmiot{}]}` - List of matching entities (typically one)
* `{:error, :invalid_nip}` - The provided NIP failed validation
* `{:error, reason}` - Search failed, session could not be obtained, or cache not running
## Examples
{:ok, entities} = Gusex.find_by_nip("5261040828")
"""
@spec find_by_nip(String.t()) :: {:ok, [Gusex.Types.Podmiot.t()]} | {:error, term()}
defdelegate find_by_nip(nip), to: Search
end