PetroNet SystemDocumentation
Introduction

Overview

9 min readdocs/README_EN.mdEdit on GitHub

Mongolia's integrated fuel monitoring and management platform

This page has not been translated yet — it is shown in Mongolian, the language it is written in.

PetroNet collects the import, storage, distribution and retail of petroleum products across Mongolia into one data flow, watches it in real time, and gives the regulator, the fuel companies and the driver the same numbers. It is built for the Mineral Resources and Petroleum Authority (MRPAM) and replaces the current mpetro system.

PetroNet System is not one application — it is an ecosystem. A driver, a station, a fuel company and the regulator are doing four different jobs, and each has a platform built for that job. Underneath, all of them share one set of data, one identity and one audit trail.


01Contents


02The problem

Mongolia has more than 200 fuel companies, over 110 storage depots and more than 1,500 filling stations. Their data lives in two systems that do not talk to each other, and most of it is typed in by hand, once or twice a week.

There is no single place that can answer, right now, how many litres of which grade are where. So national reserves are managed by estimate, and when supply tightens the only instruments left are blunt ones — odd-and-even plate days, a flat ₮50,000 cap per fill, queues.

That is not only a supply problem. It is an information problem, and information problems are the kind software can actually solve.

03What the platform does

Public page
1Chain of custody — import contract → customs → laboratory → terminal → transport → station tank → nozzle → customer. Every litre is traceable back to the batch it came from./supply
2Station POS — a driver layer that speaks to dispensers and tank gauges of any make, from a modern forecourt controller down to a pulse counter, and keeps selling when the network is gone./supply#pos
3Vouchers — entitlements minted only from fuel that has physically arrived, then allocated by proximity, need and time waited./vouchers
4State oversight — stock, price, quality, tax and discrepancy on one board, over an audit trail that cannot be rewritten./supply#oversight

It runs in two modes on one set of rails. In a crisis it rations: limits and quotas change in minutes, priority classes keep their reserve, vouchers go out with a time window. The rest of the time it supervises: tax, price, quality and stock monitoring, automatic import-to-sale reconciliation, demand forecasting and strategic-reserve alerts.

04The ecosystem

PlatformFor whomWhat it carries
Citizen platformDrivers and citizensThe nearest station, its grades, how full it is, the daily entitlement and the voucher. Identity comes from eID
Company portalFuel companiesDepot and station registry, tank balances, and the flow for filing and correcting each reporting period
Regulator's command centreMRPAM and inspectorsThe national daily aggregate, days of stock, coverage gaps, reconciliation discrepancies and alerts
Station POS and edge agentFilling stationsNozzles, tanks, shifts, payment and receipts, over a local database: the sale does not stop when the network does
Warehouse and analyticsAnalysts and managementFed daily from the operational systems, cleaned and modelled in business language, with BI and forecasting on top
Console and monitoringOperatorsOrganisations, permissions and audit behind their own sign-in, beside metrics, alerts and backups

Under all of them sit one Go binary, one database and one identity: an ecosystem here means many workspaces, not many servers. Outward it connects to customs, the state registry, e-Barimt, eID and the tank gauges in the field.

05The design decision

A voucher is not a promise. It is a reserved litre.

A voucher comes into existence only after fuel has physically entered a station's tank and the automatic tank gauge has confirmed the level rise.

Two things follow. The system can never promise more than it holds, so the queue has nothing to form around. And a station that does not report its deliveries generates no vouchers, so nobody is sent to it — compliance is enforced by the design rather than by an inspector.

06Chain of custody

StageWhat is recordedWhere it comes from
ImportContract, supplier, grade, tonnage, Incoterms, price, expected dateImporter portal / API
BorderDeclaration number, HS code, duties, crossing pointCustoms
QualityOctane, density, sulphur, water, laboratory certificateAccredited laboratory
MetrologyObserved litres, temperature, density → litres at 15 °CASTM D1250 / API MPMS 11.1
TerminalTank, capacity, level, free capacity, strategic-reserve transfersTank gauges
TransportTanker, driver, loaded volume, destination, GPS track, e-sealCarrier module
StationReceived volume, level rise, discrepancy, receiving staffTank gauge + confirmation
NozzleTotalizer, per-transaction litres and amount, shift readingsForecourt controller
CustomerEntitlement, voucher, redemption, receipt, VATPetroNet + e-Barimt

Each node reconciles against the one before it, so a discrepancy names when, where and in whose custody it appeared.

07What already exists

Not a plan — a record of what is in the repository, with tests, run against a real PostgreSQL.

  • Registry of depots and stations, plate numbers, status, XYP verification
  • Product reference with JODI classification, seven grades
  • Regulator permissions, with a row-level policy behind them
  • Policy as data — limits, tolerances, deadlines, changeable without a release
  • Station technical inventory (classes A–D)
  • Reporting periods, submissions, lines and conclusions
  • Validation rules — balance, continuity, capacity, deviation, metrology
  • 15 °C volume correction (ASTM D1250 / API MPMS 11.1)
  • Report versioning and a hash chain over it
  • Excel template export and import
  • Review workflow — approve, return, four-eyes
  • Movements, with plate number, closing state and discrepancy
  • National daily aggregate, coverage, days of stock remaining
  • Missing-data detection and a coverage-gap report
  • Reconciliation ΔA–ΔE
  • Seven reports as Excel and CSV, scheduled and emailed
  • Open data: the daily national aggregate at /api/v1/petro/public/daily
  • The company reporting screen and the regulator screen

08How it is built

PetroNet is a Level 2 distribution of the Gerege Nexus platform. There is no core code in this repository: core.lock pins the core's tag (backend/v1.96.0) and go.mod requires the same version. deploy/prepare-core.sh checks that tag out into .build/core and overlays PetroNet's map, operator screens and public pages (brand/frontend, deploy/core-frontend.patch) on the core's frontend. What lives here is the fuel business logic (modules/petro/) and those screens.

The module registers its own routes, menus, permissions and migrations through the public pkg/nexus contract and compiles into a single Go binary. Identity, tenancy, RBAC, SSO, reporting and the audit trail come from the platform and are not rewritten here.

The deployment authenticates people itself: its own sign-in, its own OIDC issuer, its own database. Citizens are identified through eID Mongolia rather than a password this system would have to keep.

09Repository layout

text
main.go                   Registers the petro module and starts the platform hostmodules/petro/            The fuel module: registry, reports, oversight, vouchers  migrations/             This module's SQL, one historycmd/migrate/              Core schema, then petro's (goose_db_version_petro)cmd/petro-import/         Importer for the existing mpetro datacatalog/                  App catalogue, manifests and version chroniclebrand/                    PetroNet's screens over the core frontend, sign-in copycore.lock                 The core tag this distribution builds ondeploy/                   Dockerfile, prepare-core.sh, brand-frontend.sh, design exportsnative-apps/              macOS, Windows, iOS/iPadOS and Android clientsdocs/                     This documentation, in Mongolian and English

10Getting started

Prerequisites: Go 1.26+, Node.js 20+, PostgreSQL 16+ (or Docker).

bash
# The APIgo run . # The web client: the core's frontend with PetroNet's screens over itdeploy/prepare-core.shcd .build/core/frontend && npm ci && npm run dev

The web client answers on http://localhost:3000.

A deployment with no organisation yet sends every visitor to /setup. The token that wizard asks for is written to the API log once, at boot:

bash
cd /opt/petronet && docker compose logs backend 2>&1 | grep -i "setup token"

11Configuration

Production's compose file is stack/petronet/docker-compose.yml in erdenebatt/proxmox-gerege-net; its secrets are in the host's /opt/petronet/.env. The values that decide how a deployment behaves:

VariableDescription
PUBLIC_ORIGINWhere this instance answers. Defines CORS, the OIDC issuer and the eID callback in one place
POSTGRES_PASSWORD / API_DB_PASSWORDThis stack's own database: the owner, and the unprivileged gerege_nexus_api role the backend connects as
SSO_DEFAULT_CLIENT_SECRETThe platform refuses to start in production without it
BRAND_*The deployment's name, description, colours and icons
*_HOSTWhich app each hostname opens: CONTROL_PLANE_HOST, DEVELOPER_HOST, MONITOR_HOST, REPORTS_HOST, BACKUPS_HOST, DOCS_HOST
EID_RP_UUID / EID_RP_SECRETThe eID relying-party pair. Without them eID sign-in is unavailable
CONTROL_PLANE_HOSTThe hostname the operator console answers on, and nowhere else
PROMETHEUS_URLWhere the core's monitoring app reads from — the stack's own Prometheus

12Deployment

Production is core-app-02 (10.130.0.21) in the Proxmox core-dev pool: the stack in /opt/petronet, backend on 8220 and web on 3220, behind the edge core-nginx-01, which terminates TLS for *.petronet.mn. Nobody changes anything on the host by hand — the only path to production is:

text
commit → PR → main → CI (ci.yml) ✓ → images ghcr.io/…/{backend,frontend}:<sha>  → Deploy (deploy.yml, runner [self-hosted, core-dev])  → deploy@10.130.0.21: brand/copy.json → docker compose pull && up -d  → health: 8220, 3220, https://petronet.mn

CI builds both images from one commit, so the API, the map and the operator screens always ship at one revision.

The hostnames: the platform (petronet.mn), the operator console (admin.), the developer portal (developer.), monitoring (monitoring.), the warehouse and reports (reports.), backups (backups.) and this documentation (docs.) — all one frontend and API, each host opening its own app. Four device lines (desktop., mobile., kiosk., pos.) serve the native clients. What each is, and what is backed up, is in this deployment's document.

13Testing

bash
go vet ./... && go test -race ./...     # Go: unit and PostgreSQL integrationdeploy/prepare-core.sh && cd .build/core/frontend && npm ci && npx tsc --noEmit && npm run lint && npm run build

CI runs both on every push and pull request, and builds both Docker images beside the tests.

14Security

  • Session tokens are random 256-bit values; only their SHA-256 digest is stored.
  • Passwords are hashed with bcrypt, and sign-in attempts are rate limited.
  • Tenant data is isolated by a database role, a tenant context and row-level security on the declared tables. The regulator's reach is a policy in SQL, not a check in a handler.
  • Report versions are chained by hash, so an approved submission cannot be edited without the chain saying so.
  • The operator console has its own identity, cookie, audit trail and database role, and answers only on CONTROL_PLANE_HOST.

Report vulnerabilities as described in SECURITY.md.

15Documentation index

DocumentDescription
Documentation hubEvery document
This deploymentHostnames, ports, backups — only this deployment
ArchitectureThe planes, the schemas, how data is isolated
Writing a moduleThe pkg/nexus contract
OperationsDeployment, monitoring, backup and restore
RunbooksWhen something breaks
TranslationThe language policy and the generator
Contributing · Security · Code of conductProject conduct

16License

Copyright (c) 2026 Gerege Systems Development Team, Gerege Nomadica Foundation. Distributed under the Apache 2.0 License — see LICENSE.

Flag icons by Flaticon (attribution).

Was this page helpful?Your answer helps improve the docs.
    DEV · Хөгжүүлэлтийн орчин