# Harmonize Installation and Admin Guide

This guide covers how to **install, configure, and deploy** Harmonize. For day-to-day usage, see [GUIDE.md](GUIDE.md).

---

## Contents

### Desktop Applications
1. [Requirements](#requirements)
2. [Database Setup](#database-setup)
3. [Desktop Application Installation](#desktop-application-installation)
4. [Connection Configuration](#connection-configuration)
5. [Verify Installation](#verify-installation)
6. [Excel Add-in Installation](#excel-add-in-installation)
7. [Python and R Setup](#python-and-r-setup)
8. [Data Management](#data-management)
9. [Access Control](#access-control)
10. [Timezone Configuration](#timezone-configuration)
11. [Admin Tool](#admin-tool)

### Web Site
12. [Web Databank Deployment](#web-databank-deployment)
13. [Web Configuration Files](#web-configuration-files)
14. [Language Configuration](#language-configuration)

### Reference
15. [Troubleshooting](#troubleshooting)
16. [Workflow Checklist](#workflow-checklist)
17. [Appendix: Create Database User](#appendix-create-database-user)

---

## Requirements

### Database (Required)

- **Microsoft SQL Server** (full version or SQL Server Express)
- Database schema: `Harmonize.sql`
- Backup file: `Harmonize.bak`

### Desktop Application (Optional but Recommended)

- Windows with .NET Framework 4.6.1
- Google Chrome or any modern browser (for chart rendering)
- Visual Studio (only if building from source)

### Web Databank (Optional)

- Web server with PHP (Apache with mod_php, or Nginx with PHP-FPM)
- No database connection needed — the web layer is file-based
- Highcharts JS library (loaded from CDN)

#### Local Testing with PHP

You can test the web databank locally without a full web server. Install PHP on Windows:

```
winget install PHP.PHP.NTS.8.4
```

Restart your terminal, then start a local server:

```
php -S localhost:8000 -t C:\HarmonizeCode\www
```

Browse to `http://localhost:8000/` to test. This is not needed for production — use Apache or Nginx there.

### Python / R Integration (Optional)

- Python 3 with `pyodbc` for SQL Server connectivity
- R with ODBC support

---

## Database Setup

### 1. Install SQL Server

Install Microsoft SQL Server on your machine or server. SQL Server Express works if a full version is not available.

### 2. Restore the Database

Log in as administrator (e.g. `sa`), use `master`, and restore:

```sql
USE master;
GO
RESTORE DATABASE Harmonize
FROM DISK = 'C:\path\to\Harmonize.bak'
WITH MOVE 'Harmonize' TO 'C:\SQLData\Harmonize.mdf',
     MOVE 'Harmonize_log' TO 'C:\SQLData\Harmonize_log.ldf';
GO
-- Fix ownership after restore
ALTER AUTHORIZATION ON DATABASE::Harmonize TO sa;
GO
```

### 3. Verify Connection

Connect to the database using SQL Server Management Studio (SSMS). Ensure the user credentials or trusted connection are working.

---

## Desktop Application Installation

### Option A: Setup Installer (Recommended)

1. Download the setup package
2. Extract files to a temporary folder
3. Run `Setup.exe` — default location: `C:\Harmonize\App\`
4. Administrator rights are required

### Option B: Manual Installation

1. Download and unzip files to `C:\Harmonize\App\`
2. Launch `Harmonize.exe` directly

### Installed Files

| File | Purpose |
|---|---|
| `Harmonize.exe` | Main application |
| `Harmonize.css` | Chart template styling |
| `Harmonize.bak` | Database backup |
| `Chart.html` | Single chart template |
| `MultiChart.html` | Multi-chart template |
| `YearChart.html` | Yearly overlay chart template |
| `Report.html` | Report template |
| `Releases.html` | Release notes |
| `connection.txt` | Database connection configuration |
| `Menues.csv` | Menu labels (multi-language) |

### Shared vs Local Installation

- **Shared folder** (recommended): Use a trusted database connection (no passwords in `connection.txt`). All users access the same installation with read access to the shared folder.
- **Local installation**: Required if using username/password in `connection.txt`. Each user gets their own copy.

### Browser Verification

Double-click `Releases.html` and verify it opens in Chrome or Edge. If HTML files open in Notepad or another non-browser application, change the default program for `.html` files (Windows Settings > Default Apps). Charts will not display if a browser is not the default handler for HTML files.

---

## Connection Configuration

Edit `connection.txt` in `C:\Harmonize\App\`. The file has 5 lines:

| Line | Purpose | Example |
|---|---|---|
| 1 | SQL Server connection string | `Data Source=myserver;Initial Catalog=Harmonize;Integrated Security=True` |
| 2 | Personal chart data folder | `C:\Harmonize\Chart` |
| 3 | Available languages (from Menues.csv) | `English,Norwegian` |
| 4 | Default language (0-based index) | `0` |
| 5 | Maximum rows per series | `100000` |

### Connection String

Use a **trusted connection** (Integrated Security) when possible — this is the safest and simplest setup. Personal usernames and passwords also work but require local installation per user.

### Chart Data Folder

`MyData.js` and temporary chart data are stored here. This folder must be **private per user**. Default: `C:\Harmonize\Chart\`.

If you change this path, update it in all HTML templates: `Chart.html`, `MultiChart.html`, `YearChart.html`, and `Report.html`.

---

## Verify Installation

1. Launch `Harmonize.exe`
2. Verify the connection string in the status bar
3. Check that the dataset tree shows available datasets
4. Open **Help > Releases** to confirm the browser launches correctly
5. Select a series, choose Chart — verify the chart opens in your browser
6. Test **Report** to confirm report generation

---

## Excel Add-in Installation

The Harmonize SQL Add-in requires:
- Excel installed
- Harmonize installed in `C:\Harmonize\App\` (shares `connection.txt`)
- Administrator rights

### Installation Steps

1. Extract the SQLAddin installation files to a temporary directory
2. Run `setup.exe`
3. After installation, the **Harmonize ribbon** appears in Excel

The add-in reads `connection.txt` from `C:\Harmonize\App\` to connect to the same database as the desktop application.

---

## Python and R Setup

Python and R scripts connect directly to SQL Server and call stored procedures.

### Python Setup

1. Install Python 3
2. Install `pyodbc`: `pip install pyodbc`
3. Configure connection in the script (reads from `connection.txt` or inline)

### Connection

Scripts typically read `connection.txt` from `C:\Harmonize\App\`:

```python
with open(r'C:\Harmonize\App\connection.txt') as f:
    conn_str = f.readline().strip()
```

### Available Scripts

| Script | Purpose |
|---|---|
| `ffi.py` | Generic CSV flat-file import to database |
| `download_cpi.py` | Download CPI from SSB (EN + NO descriptions) |
| `download_ppi.py` | Download PPI from SSB (EN + NO descriptions) |
| `download_travel.py` | Download travel statistics from SSB |
| `GetCurve2pythonChart.py` | Extract series and chart in Python |
| `PutDescrline.py` | Update series descriptions |
| `getJsonCurve.py` | JSON output helper |

### CSV Format for Import

The standard CSV format for `ffi.py` and bulk import from the Application:
Users who have write access to the dataset can right-click on the dataset and upload the CSV file.
Make sure to mark the correct dataset — you will get a preview of the file before starting the import.

```
name,unit,date,value,descr,descr2,doc
C00.IDX,20,2025-01-01,120.5,"Consumer prices, total","Konsumpriser, i alt",SSB
```

- Comma separator
- Descriptions with commas must be double-quoted
- `descr2` is the second language description
- `doc` is optional documentation/source

![CSV import file format](images/Import_csv_file_format.png)

---

## Web Databank Deployment

The web databank is independent of the SQL Server database. It reads only exported JSON files, so it can be hosted on any standard web host.

### Requirements

- Web server with PHP (Apache or Nginx with PHP-FPM)
- No database connection needed
- Highcharts JS loaded from CDN (`code.highcharts.com`)

### Download

The web databank is available as a standalone download from [GitHub Releases](https://github.com/eriksoeb/Harmonize/releases) — look for **Harmonize.Web.zip**. This contains everything needed to deploy the web site, including a demo dataset (Travel_Abroad).

### Deployment Steps

1. Download and extract `Harmonize.Web.zip`, or use the `www/` directory from the repository
2. Upload to your web server
3. Ensure PHP is enabled
4. Verify `.htaccess` files are processed (Apache: `AllowOverride All`)
5. Copy `GUIDE.md` and `INSTALL.md` from the repo root into `www/docs/` — these are rendered as web pages by `docview.php`

> **Note:** The master copies of `GUIDE.md` and `INSTALL.md` live in the repository root. When you update them, copy to `www/docs/` before deploying.

### Folder Structure

```
www/databank/
+-- index.php              Landing page (auto-discovers domains)
+-- series.php             Series browser
+-- table.php              Table report renderer
+-- card.php               KPI dashboard cards
+-- web_explorer.php       Interactive chart builder
+-- lang-config.php        Language/flag configuration
+-- databank.css           Shared styles
+-- .htaccess              Directory listing protection
|
+-- Prices_CPI_(2025)/     Example domain folder
|   +-- series/
|   |   +-- catalog.json   Series index
|   |   +-- c00.idx.json   Series data files
|   +-- chart.txt          Preview chart config
|   +-- table1.txt         Table report config
|   +-- card1.txt          KPI card config
|   +-- about.txt          Domain description (bilingual)
|   +-- contact.txt        Contact cards
|   +-- press/             Press releases (optional)
|       +-- 1_english/     Language 1 press releases
|       +-- 2_norwegian/   Language 2 press releases
|
+-- Travel_Abroad/         Another domain
    +-- series/
    +-- chart.txt
```

### Publishing a New Domain

1. In Harmonize.exe, load your series into the data grid
2. Click **Save as Catalog Webfiles**
3. Select target folder: `www/databank/<YourDomain>/series/`
4. The app generates one JSON per series plus `catalog.json`
5. Create config files (`chart.txt`, optionally `table1.txt`, `card1.txt`, `about.txt`, `contact.txt`)
6. Add a domain entry to `$domains` in `lang-config.php` for a bilingual name and subgroup
7. Deploy the folder to the web server

The domain **automatically appears** on the landing page — no code changes needed. The system discovers domains by scanning for folders containing `series/catalog.json`.

### Security

The `.htaccess` files provide:
- **HTTPS redirect:** Forces all HTTP traffic to HTTPS
- **CORS headers:** Allows cross-origin JSON fetches for external integrations
- **Directory listing protection:** `Options -Indexes` (returns 403 instead of listing files)
- **Custom 404 page:** Redirects to the landing page instead of the default Apache error

---

## Web Configuration Files

Each domain folder can contain text-based configuration files that control the series page layout. All text supports bilingual content using the pipe `|` separator. For detailed format documentation and examples, see the [User Guide](GUIDE.md).

| File | Section | Description |
|---|---|---|
| `chart.txt` | [Dashboard Chart](GUIDE.md#dashboard-chart) | Preview chart with series, colors, chart type, and stacking |
| `card*.txt` | [KPI Dashboard Cards](GUIDE.md#kpi-dashboard-cards) | KPI cards with percentage change or plain numbers |
| `table*.txt` | [Table Reports](GUIDE.md#table-reports) | Structured reports with derived columns and footnotes |
| `about.txt` | [About Section](GUIDE.md#about-section) | Descriptive paragraph about the statistical domain |
| `contact.txt` | [Contact Section](GUIDE.md#contact-section) | Contact cards with name, email, and phone |
| `press/` | [Press Releases](GUIDE.md#press-releases) | HTML/PDF press releases, auto-discovered by language |

---

## Language Configuration

The web databank supports two languages through a single config file: `www/databank/lang-config.php`. A dropdown selector in the navigation bar lets users switch between languages on all pages.

### Language Mapping

```php
$languages = [
    1 => ['label' => 'English', 'html_lang' => 'en', 'dec_point' => '.', 'thousands' => ' '],
    2 => ['label' => 'Norsk',   'html_lang' => 'no', 'dec_point' => ',', 'thousands' => ' '],
];
```

| Key | Purpose |
|---|---|
| `label` | Displayed in the language dropdown selector |
| `html_lang` | HTML `lang` attribute for the page |
| `dec_point` | Decimal separator for number formatting (`.` or `,`) |
| `thousands` | Thousands separator for number formatting |

- **lang=1** is the primary language — reads the `description` field from JSON files
- **lang=2** is the secondary language — reads the `desc2` field from JSON files
- URL parameter: `?lang=1` (default) or `?lang=2`

### Domain Display Names

Domain folders use technical names (e.g. `Prices_CPI_(2025)`). The `$domains` array provides bilingual display names, subgroup headings, and sort order for the landing page:

```php
$domains = [
    'Prices_CPI_(2025)' => [
        'subgroup' => 'Prices and price indices|Priser og prisindekser',
        'sort'     => 10,
        'label'    => ['Consumer Prices CPI', 'Konsumprisindeks KPI']
    ],
    'Travel_Abroad' => [
        'subgroup' => 'Tourism|Reiseliv',
        'sort'     => 10,
        'label'    => ['Travel Abroad', 'Utenlandsreiser']
    ],
];
```

| Key | Purpose |
|---|---|
| `label` | Bilingual display name (array: `[lang1, lang2]`) |
| `subgroup` | Group heading on the landing page (bilingual with `\|`) |
| `sort` | Sort order within the subgroup (lower = first) |

Folders not listed in `$domains` fall back to the folder name with underscores replaced by spaces. Domains without a `subgroup` appear ungrouped.

Helper functions:
- `domainLabel($folder, $lang)` — returns the display name for the current language
- `domainSubgroup($folder, $lang)` — returns the subgroup heading

### UI Labels

All user-facing text is defined in the `$labels` array:

```php
$labels = [
    'press_releases'     => ['Press Releases', 'Pressemeldinger'],
    'tables'             => ['Tables', 'Tabeller'],
    'name'               => ['Name', 'Navn'],
    'description'        => ['Description', 'Beskrivelse'],
    'updated'            => ['Updated (UTC)', 'Oppdatert (UTC)'],
    'search_placeholder' => ['Search name or description…', 'Søk navn eller beskrivelse…'],
    'show_more'          => ['Show all', 'Vis alle'],
    // ... more labels
];
```

The `label($key, $lang)` helper retrieves the correct text. Pages that use labels include `lang-config.php` at the top.

### Named Color Palette

The `$colors` array defines named colors used in `chart.txt`:

```php
$colors = [
    'blue' => '#628DCB', 'sand'   => '#C7B491', 'olive' => '#89A54E',
    'red'  => '#AA4643', 'orange' => '#f47835', 'navy'  => '#1A3A70',
    'yellow'=>'#e4d354', 'brown'  => '#D6995C', 'khaki' => '#CAC47F',
    'teal' => '#2b908f', 'green'  => '#339966', 'grey'  => '#808080',
    'black'=> '#333333',
];
```

To redesign the chart color scheme, change the hex codes here — all charts using named colors update automatically.

### Other Settings

```php
$discover_max = 50;   // Max results in Discover search
$series_max = 50;     // Max rows before "Show all" on series page

$buttons = [          // Which buttons to show on the series page
    'chart'    => true,
    'explorer' => true,
    'report'   => true,
    'json'     => true,
    'csv'      => false,
];
```

### Adapting for Another Country

1. Update `$languages` in `lang-config.php`:
   ```php
   $languages = [
       1 => ['label' => 'English', 'html_lang' => 'en', 'dec_point' => '.', 'thousands' => ','],
       2 => ['label' => 'Shqip',   'html_lang' => 'sq', 'dec_point' => ',', 'thousands' => '.'],
   ];
   ```
2. Add the new language as second element in each `$labels` array
3. Add domain entries to `$domains` with bilingual labels and subgroups
4. Populate `desc2` in your JSON files with the new language descriptions
5. Add translated text after `|` in config files (`chart.txt`, `card*.txt`, `table*.txt`, `about.txt`)
6. Create `press/2_albanian/` subfolder for press releases in the new language

### Desktop Application Languages

Desktop app languages are configured separately in `Menues.csv` and `connection.txt` (lines 3-4). See [Menus and Languages](GUIDE.md#menus-and-languages) in the User Guide.

---

## Data Management

### Utility Procedures

All data operations should go through stored procedures to ensure correct metadata updates and access control.

| Procedure | Purpose |
|---|---|
| `UTILS_PutTime` | Upsert a single observation (insert or update) |
| `UTILS_Create_Loadset` | Create a new dataset |
| `UTILS_Delete_Loadset` | Delete dataset — 3 modes (see below) |
| `Stp_DeleteCurveandData` | Delete a single series and its data |
| `Stp_DeleteCurveDataOnly` | Delete observations only (keep series definition) |
| `UTILS_UpdateCurveinfo` | Update description/unit for a series |
| `UTILS_BulkStagingInsert` | Bulk import from staging table |

### Delete Modes

```sql
-- Delete all data points, keep series names and dataset config
EXEC UTILS_Delete_Loadset 'DELETE_DATA', @loadsetId, 'DatasetName'

-- Delete data and series names, keep dataset config
EXEC UTILS_Delete_Loadset 'DELETE_SERIES', @loadsetId, 'DatasetName'

-- Delete everything including dataset config
EXEC UTILS_Delete_Loadset 'DELETE_ALL', @loadsetId, 'DatasetName'
```

### Intervals

Intervals are defined in database views. The procedures use `>=` start_date and `<` end_date. Additional intervals can be added and will automatically appear in the application dropdown.

### Units

Units are standardized via Unit IDs. Edit in the Admin form or directly in the database. When uploading via Excel or Python, the unit name must match a valid entry in the Unit table.

The idea with Unit IDs is to make it easier to use consistent units. Experience has shown that there are too many ways to spell "Index", "Degrees" (direction, Fahrenheit, or Celsius), or "kWh" — and Unit IDs provide an easy way to change names and descriptions later for all datasets in one place. Harmonize comes with some default Unit IDs, but users can add their own.



### Data Tables

Time series can be stored in multiple data tables. Each must have a `value_date` column in `date` or `datetime` format. Use `date` for daily or lower frequency; use `datetime` only for hourly or higher frequency data.

All data must be stored with proper date formats (e.g. `2025-12-01`), not text formats like `2020M12`.

---

## Access Control

### Read Access

| Table | Purpose |
|---|---|
| `LoadSet.AccessAll` | Flag — when set, all users can read the dataset |
| `LoadsetADr` | Per-user read access to specific datasets |

If a user lacks access, the dataset appears in the tree but no series are shown when searching.

### Write Access

| Table | Purpose |
|---|---|
| `LoadsetADw` | Per-user write access to specific datasets |

Write access is checked by the database function `IsAccessw`. Users who need to upload or modify data must be listed in `LoadsetADw`.

Datasets with write access are highlighted in **orange** in the desktop application.

### Shortcut for Getting Started

Initially, give all users write access to simplify setup. Restrict access later as needed by populating `LoadsetADr` and `LoadsetADw`.

### Note on Trusted Connections

The username for a trusted connection in SSMS may differ from the trusted username used by Python. In Python, the trusted user is typically what `whoami` returns in the command prompt.

---

## Timezone Configuration

Harmonize supports high-frequency data (hourly, sub-hourly) with correct daylight saving time handling.

### Rules

- All data must be stored in **UTC**
- Each dataset can be configured in the `LoadSet` table to **display** in a different timezone
- Timezone conversion happens **before** applying functions and aggregations

### Daylight Saving Effects

- Hourly spot prices: **25 observations** when shifting to winter time, **23 observations** when shifting to summer time
- Charts may show two observations at 02:00 once per year (when CET clocks are set back)
- Default report date format shows year-month-day — adjust the template if hours/minutes are needed

### Configuration

In the `LoadSet` table, set the timezone for each dataset:

| Column | Example Value |
|---|---|
| `TimeZone` | `Central European Standard Time` |

Leave as UTC if no timezone conversion is needed.

---

## Admin Tool

The Admin tool is a browser-based form for viewing database configuration tables:

- Units
- Access tables (LoadsetADr, LoadsetADw)
- Intervals
- Dataset configuration (LoadSet)

Tables open in **read mode** (normal display). Switching to **update mode** shows a red background as a visual warning. Updates are possible but depend on table constraints.

The Admin form uses stored procedures, allowing users to view data even without direct `SELECT` permissions on the tables.

For complex updates, use **SQL Server Management Studio** (SSMS) directly.

![Admin tool](images/Admin_tool.png)




---

## Troubleshooting

### Cannot Connect to Server

- Verify username/password or trusted connection in `connection.txt`
- Test with SSMS for more detailed error messages
- Check if the password has expired
- Try logging in with an admin user (sa)

### Cannot Upload Data

- Database access issue — check `LoadsetADw` permissions
- Running as `sa` (sysadmin) does not automatically grant write access to datasets
- Verify the user is listed in `LoadsetADw` for the target dataset

### No Data in Selected Interval

- Ensure data exists in the selected interval
- Check metadata for first/last observation dates
- A series with only one observation may appear as an empty chart
- A function or common base year may require data in a range that doesn't exist

### Charts Don't Open

- Verify HTML files open in a browser (not Notepad)
- Set Chrome or Edge as default for `.html` files: Windows+I > Default Apps
- Test by double-clicking `Releases.html`

### Installation Issues

- If a previous installation exists, uninstall first: Windows+I > Apps > Installed Apps > Harmonize > Uninstall
- Then run `Setup.exe` again

### Logging

Logging can be configured in the database. Check log tables for detailed operation history.

---

## Workflow Checklist

1. Install SQL Server and restore `Harmonize.bak`
2. Install Harmonize desktop app (`Setup.exe` or manual)
3. Configure `connection.txt` with your database connection
4. Launch Harmonize.exe — verify dataset tree, charts, and reports work
5. (Optional) Install Excel Add-in
6. (Optional) Deploy web databank to your web server
7. Use Python/R scripts to import your data
8. Configure access control (`LoadsetADr`, `LoadsetADw`) as needed
9. Customize HTML templates and CSS to match your standards
10. Add custom languages to `Menues.csv` if needed

---

## Appendix: Create Database User

Script to create a database user. Must be executed as administrator (sa):

```sql
USE master;
GO

-- Drop existing login if it exists
IF EXISTS (SELECT 1 FROM sys.server_principals WHERE name = 'demo')
BEGIN
    DROP LOGIN demo;
END
GO

-- Create login
CREATE LOGIN demo
WITH PASSWORD = 'YourStrongPassword',
     CHECK_POLICY = ON,
     CHECK_EXPIRATION = OFF,
     DEFAULT_DATABASE = master;
GO

USE Harmonize;
GO

-- Fix ownership after restore (important!)
ALTER AUTHORIZATION ON DATABASE::Harmonize TO sa;
GO

-- Create database user
DROP USER IF EXISTS demo;
GO
CREATE USER demo FOR LOGIN demo;
GO

-- Grant minimal permissions (connect + execute stored procedures)
GRANT CONNECT TO demo;
GRANT EXECUTE TO demo;
GO

USE master;
GO
ALTER LOGIN demo WITH DEFAULT_DATABASE = Harmonize;
GO
```

By design, users only need `CONNECT` and `EXECUTE` permissions. All data access goes through stored procedures, ensuring no ad-hoc queries hit the data tables directly. This keeps the system fast, secure, and ensures metadata is always updated correctly.
