# Phase 1 Implementation Summary

## Overview
Phase 1 is now **COMPLETE**. All files have been created and updated to support automatic parameter and config push when devices report missing versions (Scenario 1).

---

## Files Created

### 1. Migration Files
**File:** `priv/repo/migrations/20250131000001_add_version_columns_to_tms_terminals.exs`
- Adds 3 new columns to `tms_terminals` table:
  - `parameter_config_version` (varchar)
  - `emv_config_version` (varchar)
  - `keys_config_version` (varchar)

**File:** `priv/repo/migrations/20250131000002_extend_parameter_push_logs_for_configs.exs`
- Extends `parameter_push_logs` table with:
  - `config_type` (parameter, emv_config, keys_config, application)
  - `file_path`, `file_size`, `checksum` (for file tracking)
  - `version_sent`, `device_vendor`, `device_model`
  - `trigger_reason` (missing_version, version_mismatch, manual_push)

### 2. Service Files
**File:** `lib/da_product_app/terminal_management/auto_push_service.ex`
- **Key Functions:**
  - `trigger_missing_version_push/3` - Main entry point for auto-push
  - `has_missing_versions?/1` - Checks if any version is NULL/EMPTY
  - `find_best_template/2` - Finds Active template first, then Default (by vendor+model)
  - `push_template_parameters/5` - Pushes parameters from template
  - `push_device_setup_configs/4` - Pushes EMV, Keys, Application configs
  - `send_mqtt_parameter_push/5` - Sends MQTT command for parameters
  - `send_mqtt_config_push/5` - Sends MQTT command for config types

### 3. Seed File
**File:** `priv/repo/seeds/device_setup_parameters.exs`
- Creates Device Setup category if not exists
- Seeds 3 parameters:
  - `emv_config_version` (default: "1.6")
  - `keys_config_version` (default: "1.7")
  - `application_version` (default: "3.7")

---

## Files Modified

### 1. `lib/da_product_app/terminal_management/tms_terminal.ex`
- Added 3 new fields to schema:
  - `:parameter_config_version`
  - `:emv_config_version`
  - `:keys_config_version`
- Updated `@derive` JSON encoder to include new fields
- Updated changeset to cast new fields

### 2. `lib/da_product_app/parameter_management/parameter_push_log.ex`
- Added 8 new fields to schema for config type tracking
- Updated changeset to cast new fields

### 3. `lib/da_product_app/mqtt/handler.ex`
- Updated `handle_message/3` for "tms/status" topic to:
  - Extract `vendor` and `model` from status message
  - Extract version information (parameter_config, emv_config, keys_config, application)
  - Check for missing versions using AutoPushService
  - **Trigger auto-push immediately** if any version is missing (Scenario 1)
  - Update terminal with extracted vendor, model, and version fields
- Added helper functions:
  - `extract_versions/1` - Extracts version map from status items
  - `find_version_in_items/2` - Finds specific version in items list

---

## Scenario 1 Logic Flow

```
Device sends status message:
  ├─ Contains: vendor, model, org.device (with version items)
  │
  ├─ Handler extracts: vendor, model, versions
  │
  ├─ Check: Are any versions (parameter_config, emv_config, keys_config, application) NULL/EMPTY?
  │
  └─ IF YES:
      ├─ AutoPushService.trigger_missing_version_push()
      │  ├─ Find best template: Active first, then Default (by vendor+model)
      │  │
      │  ├─ Push template parameters:
      │  │  ├─ Create parameter_push_logs entry (config_type: "parameter")
      │  │  ├─ Get all parameters from template
      │  │  ├─ Send MQTT command to device
      │  │
      │  └─ Push device setup configs:
      │     ├─ For each: emv_config, keys_config, application
      │     ├─ Create parameter_push_logs entry
      │     └─ Send MQTT command to device
      │
      └─ Update terminal with versions and vendor/model
```

---

## Next Steps (Phase 2)

Phase 2 will implement **Scenario 2: Version Mismatch Detection**

The foundation is ready:
- Versions are now extracted and stored in `tms_terminals`
- Push logs track config types with timestamps
- MQTT handler can easily check for mismatches

Phase 2 will add:
- Scheduled version management (find latest version for each config)
- Comparison logic (device version vs latest available)
- Auto-push trigger for outdated versions

---

## How to Deploy Phase 1

### 1. Run Migrations
```bash
cd /home/prem/mercurypay/tmsuat
mix ecto.migrate
```

### 2. Seed Device Setup Parameters
```bash
mix run priv/repo/seeds/device_setup_parameters.exs
```

### 3. Restart Application
```bash
mix phx.server
```

---

## Testing Scenario 1

Send MQTT status message with missing versions:

```json
{
  "oid": "org_123",
  "sn": "61250904380091",
  "vendor": "MoreFun",
  "model": "MF919",
  "uploadTime": "2025-01-31T15:00:00Z",
  "org.device": [
    {"itemkey": "status", "value": "online", "timestamp": "2025-01-31T15:00:00Z", "message": "Status"},
    {"itemkey": "parameter_config", "value": "", "timestamp": "2025-01-31T15:00:00Z", "message": "Parameter Config"},
    {"itemkey": "emv_config", "value": null, "timestamp": "2025-01-31T15:00:00Z", "message": "EMV Config"},
    {"itemkey": "keys_config", "value": "", "timestamp": "2025-01-31T15:00:00Z", "message": "Keys Config"},
    {"itemkey": "application", "value": null, "timestamp": "2025-01-31T15:00:00Z", "message": "Application"}
  ]
}
```

**Expected Behavior:**
1. MQTT handler detects missing versions
2. AutoPushService triggers immediately
3. Finds matching template for MoreFun MF919
4. Pushes parameters + device setup configs
5. Creates 4 entries in `parameter_push_logs`
6. Terminal receives MQTT commands to apply configs

---

## Key Features Implemented

✅ Automatic version extraction from MQTT messages  
✅ Missing version detection (Scenario 1)  
✅ Immediate auto-push on missing versions  
✅ Template-based parameter resolution  
✅ Multi-config type support (parameter, emv_config, keys_config, application)  
✅ Push operation logging with trigger reasons  
✅ MQTT command generation and sending  
✅ Terminal state tracking (vendor, model, versions)  

---

**Phase 1 Status: ✅ COMPLETE**
