# MF919 Seed Files - Current DB Alignment

**Date:** March 10, 2026  
**PR:** #18 - MF919 Template Foundation

## Summary

The MF919 seed files have been updated to align with the current database structure while maintaining the new MF919-specific parameter organization.

## Current Database Structure (from currentdb-data.txt)

### Existing Resources

1. **Template (parameter_templates)**
   - ID: 3
   - Name: "MF919 Default Configuration"
   - Vendor: "Morefun"
   - Model: "MF919"
   - is_default: 1, is_active: 1

2. **Root Category (parameter_categories)**
   - ID: 20
   - Name: "Device Setup"
   - Code: "device_setup"
   - Parent: NULL (root category)

3. **Existing Category Structure**
   - Hierarchical design using `parent_id` for category relationships
   - Examples: Trade Module (id=1), Communication Module (id=2), etc.
   - Each with subcategories (Security, ID, Print, Session, etc.)

4. **Schema Fields (from Elixir schemas)**
   - **ParameterCategory**: name, code, description, sort_order, is_active, parent_id
   - **ParameterDefinition**: key, name, description, category_id, data_type, default_value, is_required, is_system (default: false), is_encrypted (deprecated/optional), validation_rules, display_order, is_active

## Changes Made

### 1. mf919_parameter_categories.exs

**Before:** Created MF919 categories as independent root categories  
**After:** Integrated MF919 categories as children of existing "Device Setup" (id=20)

```elixir
# Now fetches existing device_setup parent category
device_setup_parent = Repo.get_by(ParameterCategory, code: "device_setup")

# MF919 root becomes child of Device Setup
mf919_root = %ParameterCategory{
  # ...
  parent_id: device_setup_parent.id  # <-- Key integration point
}
```

**Category Hierarchy:**
```
Device Setup (device_setup, id=20) [EXISTING]
└── MF919 Device Setup (mf919_device_setup) [NEW ROOT FOR MF919]
    ├── MF919 Base / Merchant Defaults (mf919_base)
    ├── MF919 Merchant Overlay (mf919_merchant)
    ├── MF919 Communication (mf919_comm)
    ├── MF919 Transactions (mf919_transactions)
    ├── MF919 Printing (mf919_printing)
    ├── MF919 PINPAD (mf919_pinpad)
    ├── MF919 Scanner (mf919_scanner)
    └── MF919 Security (mf919_security)
```

### 2. mf919_default_template.exs

**Before:** Attempted to create new template "MF919 Default Parameters"  
**After:** References existing template "MF919 Default Configuration" (id=3)

```elixir
# Now looks for exact name match in current DB
template = Repo.get_by(ParameterTemplate, 
  vendor: "Morefun", 
  model: "MF919", 
  name: "MF919 Default Configuration"  # <-- Matches current DB
)
```

**Template Values:**
- Populates 42 base parameters (excluding merchant-specific: MERCHANT_ID, TERMINAL_ID, BATCH_NO)
- Merchant-specific values applied via DeviceParameterOverride (see mf919_merchant_overlay.exs)

### 3. mf919_parameter_definitions.exs

**Status:** ✅ Already compatible with current schema

- Uses correct field names: `key`, `name`, `description`, `category_id`, `data_type`, `default_value`, `is_required`, `validation_rules`, `display_order`, `is_active`
- `is_system` defaults to `false` (appropriate for device-specific params)
- `is_encrypted` not used (field may be deprecated or database-specific)

**Parameter Count:**
- 3 Merchant Overlay (per-terminal overrides)
- 5 Base / Merchant Defaults
- 6 PINPAD parameters
- 5 Printing parameters
- 7 Transaction toggles
- 6 Communication parameters
- 5 Scanner parameters
- 10 Security / Operational flags
- **Total: 47 parameter definitions**

### 4. mf919_merchant_overlay.exs

**Status:** ✅ No changes required

Correctly applies terminal-specific overrides using `DeviceParameterOverride`:
- MERCHANT_ID
- TERMINAL_ID
- BATCH_NO

## Execution Order

**IMPORTANT:** Run the schema alignment migration before running seed scripts:

```bash
# 0. Run migration to align parameter_definitions table with schema
mix ecto.migrate

# 1. Create category structure (integrates with existing device_setup)
mix run apps/da_product_app/priv/repo/seeds/mf919_parameter_categories.exs

# 2. Create parameter definitions (uses categories from step 1)
mix run apps/da_product_app/priv/repo/seeds/mf919_parameter_definitions.exs

# 3. Populate default template values (references existing template id=3)
mix run apps/da_product_app/priv/repo/seeds/mf919_default_template.exs

# 4. (Optional) Apply merchant-specific overrides for a test terminal
SAMPLE_TERMINAL_ID=<terminal_id> mix run apps/da_product_app/priv/repo/seeds/mf919_merchant_overlay.exs
```

### Schema Alignment Migration

**File:** `20260310000001_align_parameter_definitions_schema.exs`

This migration was created to fix the mismatch between the original migration and the current Elixir schema:

**Issues Fixed:**
1. **Missing field `key`**: Original migration didn't have key field, but schema and current DB use it
2. **Missing field `is_required`**: Schema defines this, but original migration didn't
3. **Missing field `is_system`**: Schema defines this, but original migration didn't  
4. **Missing field `is_encrypted`**: Current DB has this field
5. **Missing field `display_order`**: Schema defines this, but original migration didn't
6. **Field name mismatch**: Original migration used `active`, but schema uses `is_active`

The migration safely adds missing fields using `add_if_not_exists` and conditionally migrates data from `active` to `is_active` if needed.

## Verification Checklist

- [x] MF919 categories integrate under existing "Device Setup" category
- [x] Template references existing "MF919 Default Configuration" (id=3)
- [x] Parameter definitions use correct schema fields
- [x] Merchant overlay applies per-terminal overrides (not template values)
- [x] No duplicate categories or templates created
- [x] Hierarchical category structure preserved

## Database Integration Points

### Existing Resources Referenced
1. `parameter_categories.device_setup` (id=20) - Parent category
2. `parameter_templates` MF919 entry (id=3) - Template for values

### New Resources Created
1. `parameter_categories.mf919_*` - 9 new categories (1 root + 8 children)
2. `parameter_definitions` - 47 MF919-specific definitions
3. `parameter_template_values` - ~42 default values for template id=3
4. `device_parameter_overrides` - Per-terminal overrides (via overlay script)

## Notes

- The `is_encrypted` field appears in currentdb-data.txt but is not in the Elixir schema. It may be deprecated or a database-only field. The seed scripts don't set this field.
- All field names follow the Elixir schema conventions (`is_active`, `is_required`, etc.) rather than database column names if they differ.
- The integration maintains separation of concerns: template defaults vs. terminal-specific overrides.

## Migration Path for Existing Systems

If the current database already has MF919 parameters:

1. **Backup existing data**
2. **Run category seed** - Will create new hierarchy under device_setup
3. **Run definition seed** - Will skip existing keys and log them
4. **Run template seed** - Will populate existing template (id=3) with new values
5. **Verify** - Check logs for "already exists" messages

## References

- Current DB: `docs/tms_mf919_parameter_samples/currentdb-data.txt`
- Schema: `lib/da_product_app/parameter_management/parameter_*.ex`
- Original Migrations: `priv/repo/migrations/202401010000[19-20]_*.exs`
- Schema Alignment Migration: `priv/repo/migrations/20260310000001_align_parameter_definitions_schema.exs`

## Issues Identified and Resolved

### 1. Schema-Migration Mismatch
**Problem:** Original migration (20240101000020) used field name `active` but the Elixir schema uses `is_active`. Also missing fields: `key`, `is_required`, `is_system`, `is_encrypted`, `display_order`.

**Resolution:** Created migration `20260310000001_align_parameter_definitions_schema.exs` to:
- Add missing fields with safe `add_if_not_exists`
- Migrate data from `active` to `is_active` if the old column exists
- Add unique index on `key` field

### 2. Category Hierarchy Integration
**Problem:** New seed files created MF919 categories as root-level categories, not integrating with existing "Device Setup" structure.

**Resolution:** Updated `mf919_parameter_categories.exs` to:
- Fetch existing "Device Setup" category (id=20, code=device_setup)
- Make MF919 root a child of Device Setup using `parent_id`
- Maintain hierarchical organization

### 3. Template Name Mismatch  
**Problem:** Seed tried to create "MF919 Default Parameters" but current DB has "MF919 Default Configuration" (id=3).

**Resolution:** Updated `mf919_default_template.exs` to query for exact template name from current DB.

## Next Steps

After running the migration and seeds:

1. **Verify category hierarchy**: Check that MF919 categories appear under Device Setup
2. **Verify template population**: Confirm ~42 values added to template ID 3
3. **Test terminal override**: Run merchant overlay script with a test terminal
4. **Validate parameter resolution**: Ensure terminal inherits template values and overrides work correctly
