# -*- coding: utf-8 -*- # Copyright 2026 Nexa Systems Inc. # License OPL-1 (Odoo Proprietary License v1.0) """Post-install hook — backfill new fields on existing live sensors. Runs once on every install/upgrade. Idempotent: checks before writing so re-runs don't overwrite user-edited values. What it does: 1. Populates `uuid` on any fp.tank.sensor record that doesn't have one (for sensors created BEFORE the uuid field existed — the create override only covers new records). 2. Sets a default `sensor_type_id` on sensors that don't have one yet, inferring from `device_kind` (DS18B20 / PT100 / PT1000 → Temperature, pH → pH probe, etc.). """ import logging import uuid as _uuid _logger = logging.getLogger(__name__) def post_init_hook(env): _backfill_uuids(env) _backfill_sensor_types(env) def _backfill_uuids(env): Sensor = env['fp.tank.sensor'] missing = Sensor.search([('uuid', '=', False)]) if not missing: return for s in missing: s.sudo().write({'uuid': _uuid.uuid4().hex}) _logger.info('fp.tank.sensor: populated UUID on %d existing records', len(missing)) def _backfill_sensor_types(env): Sensor = env['fp.tank.sensor'] Type = env['fp.sensor.type'] # Map device_kind → sensor-type code. Falls back to 'temperature' for # the rare case someone set device_kind='other' on a probe that IS # temperature (common on the pilot). kind_to_code = { 'ds18b20': 'temperature', 'pt100': 'temperature', 'pt1000': 'temperature', 'ph': 'ph', 'conductivity': 'conductivity', 'level': 'level', } missing = Sensor.search([('sensor_type_id', '=', False)]) if not missing: return # Resolve the types once up front type_cache = {} for code in set(kind_to_code.values()): t = Type.search([('code', '=', code)], limit=1) if t: type_cache[code] = t.id updated = 0 for s in missing: code = kind_to_code.get(s.device_kind) # Unmapped (device_kind='other') → try temperature as the most # common fallback. Admin can correct in the UI. type_id = type_cache.get(code) or type_cache.get('temperature') if type_id: s.sudo().write({'sensor_type_id': type_id}) updated += 1 _logger.info('fp.tank.sensor: set default sensor_type_id on %d records', updated)