2026-10-22 16:18:37 +08:00
|
|
|
"""Initialize native CMVR tables and host menus only in the owned am-freescan database."""
|
|
|
|
|
import argparse
|
|
|
|
|
import hashlib
|
|
|
|
|
import json
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
import re
|
|
|
|
|
import sys
|
|
|
|
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
sys.path.insert(0, str(ROOT / '.tools/python'))
|
|
|
|
|
from bootstrap_db import META, OWNER, ensure_schema, finalize_permissions, insert_new, load_schema, validate_target
|
|
|
|
|
|
|
|
|
|
PREFIXES = ('ae_', 'aima_', 'cmvr_', 'evaluate_', 'inspection_', 'iot_', 'te_', 'ti_', 'tts_', 'vi_')
|
|
|
|
|
SCHEMA = ROOT / 'am-backend/yudao-module-cmvr/src/main/resources/sql/cmvr-schema.sql'
|
|
|
|
|
MENUS = [
|
|
|
|
|
(23000, '智能检测', '', 1, 5, 0, '/cmvr/intelligence-test', 'ep:cpu', None, None),
|
|
|
|
|
(23001, '测试用例', 'aima:testcase:list', 2, 1, 23000, 'test-case', 'ep:document', 'cmvr/intelligenceTest/testCase/index', 'CmvrTestCase'),
|
|
|
|
|
(23010, '资源中心', '', 1, 6, 0, '/cmvr/resource', 'ep:connection', None, None),
|
|
|
|
|
(23011, '机器人', 'resource:robot:list', 2, 1, 23010, 'robot', 'ep:aim', 'cmvr/resource/robot/index', 'CmvrRobot'),
|
|
|
|
|
(23012, '设备', 'resource:device:list', 2, 2, 23010, 'device', 'ep:monitor', 'cmvr/resource/device/index', 'CmvrDevice'),
|
|
|
|
|
(23013, '地图', 'resource:map:list', 2, 3, 23010, 'map', 'ep:map-location', 'cmvr/resource/map/index', 'CmvrMap'),
|
|
|
|
|
(23014, '边缘终端', 'resource:terminal:list', 2, 4, 23010, 'terminal', 'ep:connection', 'cmvr/resource/terminal/index', 'CmvrTerminal'),
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
# Preserve existing menu IDs and role assignments while changing their routes.
|
|
|
|
|
# Retired identities remain as soft-deleted rows so old INSERT-only seeds cannot
|
|
|
|
|
# resurrect an obsolete entry. Native task/log permissions remain usable by the
|
|
|
|
|
# unified execution page; unrelated vehicle/phone permissions are disabled.
|
|
|
|
|
MENU_REPARENTS = {
|
|
|
|
|
20310: (23000, 'execution', 2),
|
|
|
|
|
20210: (23010, 'sample-transfer', 10),
|
|
|
|
|
20220: (23010, 'device-reservation', 11),
|
|
|
|
|
20230: (23010, 'lab-reservation', 12),
|
|
|
|
|
20240: (23010, 'material-issue', 13),
|
|
|
|
|
20250: (23010, '', 14),
|
|
|
|
|
}
|
2026-11-06 10:50:49 +08:00
|
|
|
RETIRED_MENUS = (20200, 20300, 23002, 23003, 23004, 23005, 23015)
|
|
|
|
|
HIDDEN_MENU_IDS = (20210, 20240)
|
2026-10-22 16:18:37 +08:00
|
|
|
HOST_PERMISSION_PARENTS = {20310}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def apply_menu_topology(cursor):
|
|
|
|
|
"""Reparent only known owned menus, preserving permissions and role links."""
|
|
|
|
|
changed = 0
|
|
|
|
|
for identifier, (parent, path, sort) in MENU_REPARENTS.items():
|
|
|
|
|
cursor.execute('SELECT creator FROM system_menu WHERE id=%s', (identifier,))
|
|
|
|
|
existing = cursor.fetchone()
|
|
|
|
|
if not existing or existing[0] not in ('1', 'bootstrap', 'cmvr-port'):
|
|
|
|
|
raise RuntimeError(f'Expected owned host menu {identifier}; run base bootstrap first')
|
2026-11-06 10:50:49 +08:00
|
|
|
visible = 0 if identifier in HIDDEN_MENU_IDS else 1
|
|
|
|
|
cursor.execute('UPDATE system_menu SET parent_id=%s,path=%s,sort=%s,status=0,visible=%s,deleted=0 '
|
|
|
|
|
'WHERE id=%s AND (parent_id<>%s OR path<>%s OR sort<>%s OR status<>0 OR visible<>%s OR deleted<>0)',
|
|
|
|
|
(parent, path, sort, visible, identifier, parent, path, sort, visible))
|
2026-10-22 16:18:37 +08:00
|
|
|
changed += cursor.rowcount
|
|
|
|
|
# The old hidden interface diagnostic lives with integration, rather than
|
|
|
|
|
# beneath an otherwise empty execution group. Preserve its hidden setting.
|
|
|
|
|
cursor.execute("UPDATE system_menu SET parent_id=20700,path='execution-diagnostics' "
|
|
|
|
|
"WHERE id=20320 AND creator IN ('1','bootstrap','cmvr-port') "
|
|
|
|
|
"AND (parent_id<>20700 OR path<>'execution-diagnostics')")
|
|
|
|
|
changed += cursor.rowcount
|
|
|
|
|
for identifier in RETIRED_MENUS:
|
|
|
|
|
cursor.execute("UPDATE system_menu SET deleted=1,status=1,visible=0 WHERE id=%s "
|
|
|
|
|
"AND creator IN ('1','bootstrap','cmvr-port') AND (deleted<>1 OR status<>1 OR visible<>0)", (identifier,))
|
|
|
|
|
changed += cursor.rowcount
|
|
|
|
|
# The retired native task pages carried a list permission themselves.
|
|
|
|
|
# Their replacement is a button row with the same permission, so retain
|
|
|
|
|
# each role's existing access without granting another operation.
|
|
|
|
|
cursor.execute("INSERT INTO system_role_menu (role_id,menu_id,creator,updater,deleted,tenant_id) "
|
|
|
|
|
"SELECT DISTINCT old_grant.role_id,replacement.id,'cmvr-port','cmvr-port',0,old_grant.tenant_id "
|
|
|
|
|
"FROM system_role_menu old_grant JOIN system_menu retired ON retired.id=old_grant.menu_id "
|
|
|
|
|
"JOIN system_menu replacement ON replacement.permission=retired.permission "
|
|
|
|
|
"AND replacement.id<>retired.id AND replacement.deleted=0 AND replacement.status=0 "
|
|
|
|
|
"WHERE old_grant.deleted=0 AND retired.id IN (23002,23003) "
|
|
|
|
|
"AND NOT EXISTS (SELECT 1 FROM system_role_menu existing WHERE existing.role_id=old_grant.role_id "
|
|
|
|
|
"AND existing.menu_id=replacement.id AND existing.tenant_id=old_grant.tenant_id AND existing.deleted=0)")
|
|
|
|
|
# Give a role the new navigation ancestors only when it already has a
|
|
|
|
|
# child permission. Never grant a role an additional business operation.
|
|
|
|
|
cursor.execute("INSERT INTO system_role_menu (role_id,menu_id,creator,updater,deleted,tenant_id) "
|
|
|
|
|
"SELECT DISTINCT child.role_id,m.parent_id,'cmvr-port','cmvr-port',0,child.tenant_id "
|
|
|
|
|
"FROM system_role_menu child JOIN system_menu m ON m.id=child.menu_id "
|
|
|
|
|
"WHERE child.deleted=0 AND m.deleted=0 AND m.parent_id IN (23000,23010) "
|
|
|
|
|
"AND NOT EXISTS (SELECT 1 FROM system_role_menu ancestor WHERE ancestor.role_id=child.role_id "
|
|
|
|
|
"AND ancestor.menu_id=m.parent_id AND ancestor.tenant_id=child.tenant_id AND ancestor.deleted=0)")
|
|
|
|
|
return changed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_reference():
|
|
|
|
|
reference = json.loads((ROOT / 'config/cmvr-reference.json').read_text(encoding='utf-8'))
|
|
|
|
|
types = set()
|
|
|
|
|
for dictionary in reference['dictionaries']:
|
|
|
|
|
if not re.fullmatch(r'[a-z][a-z0-9_]+', dictionary['type']) or dictionary['type'] in types:
|
|
|
|
|
raise ValueError('Invalid or duplicate static dictionary type')
|
|
|
|
|
types.add(dictionary['type'])
|
|
|
|
|
values = [item['value'] for item in dictionary['items']]
|
|
|
|
|
if len(values) != len(set(values)):
|
|
|
|
|
raise ValueError(f"Duplicate static values in {dictionary['type']}")
|
|
|
|
|
parents = {menu[0] for menu in MENUS if menu[3] == 2} | HOST_PERMISSION_PARENTS
|
|
|
|
|
permissions = set()
|
|
|
|
|
button_ids = set()
|
|
|
|
|
for item in reference['permissions']:
|
|
|
|
|
permission = item['permission']
|
|
|
|
|
if not re.fullmatch(r'[A-Za-z][A-Za-z0-9]*(?::[A-Za-z][A-Za-z0-9-]*){2,}', permission):
|
|
|
|
|
raise ValueError('Invalid native permission key')
|
|
|
|
|
if permission in permissions or item['parentMenuId'] not in parents:
|
|
|
|
|
raise ValueError('Duplicate permission or invalid button parent')
|
|
|
|
|
permissions.add(permission)
|
|
|
|
|
identifier = button_id(permission)
|
|
|
|
|
if identifier in button_ids:
|
|
|
|
|
raise ValueError('Native permission menu ID collision')
|
|
|
|
|
button_ids.add(identifier)
|
|
|
|
|
groups = {group['groupId']: group['type'] for group in reference['groups']}
|
|
|
|
|
if groups.get(7) != 1 or not {1, 2, 3}.issubset(groups.values()):
|
|
|
|
|
raise ValueError('Native detection group 7 and task/device group types are required')
|
|
|
|
|
# Route cache names must match the actual migrated wrapper components.
|
|
|
|
|
for menu in MENUS:
|
|
|
|
|
if not menu[8]:
|
|
|
|
|
continue
|
|
|
|
|
wrapper = ROOT / 'am-web/src/views' / (menu[8] + '.vue')
|
|
|
|
|
if not wrapper.is_file() or not re.search(r"name:\s*['\"]" + re.escape(menu[9]) + r"['\"]", wrapper.read_text(encoding='utf-8')):
|
|
|
|
|
raise ValueError(f'CMVR wrapper component name does not match menu {menu[0]}')
|
|
|
|
|
return reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def button_id(permission):
|
|
|
|
|
# A stable hash keeps existing role assignments intact when annotations grow.
|
|
|
|
|
return 24_000_000 + int(hashlib.sha256(permission.encode('utf-8')).hexdigest()[:8], 16)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def ensure_menu(cursor, values):
|
|
|
|
|
cursor.execute('SELECT creator,permission FROM system_menu WHERE id=%s', (values['id'],))
|
|
|
|
|
existing = cursor.fetchone()
|
|
|
|
|
if existing and existing[0] != 'cmvr-port':
|
|
|
|
|
raise RuntimeError(f"Menu ID {values['id']} is not owned by the CMVR bootstrap")
|
|
|
|
|
if existing and values['type'] == 3 and existing[1] != values['permission']:
|
|
|
|
|
raise RuntimeError('Native permission menu ID collision with an existing record')
|
|
|
|
|
if insert_new(cursor, 'system_menu', values, ['id']):
|
|
|
|
|
return 1, 0
|
|
|
|
|
mutable = {key: value for key, value in values.items() if key not in ('id', 'creator')}
|
|
|
|
|
assignments = ','.join(f'`{key}`=%s' for key in mutable)
|
|
|
|
|
cursor.execute(f'UPDATE system_menu SET {assignments} WHERE id=%s', (*mutable.values(), values['id']))
|
|
|
|
|
return 0, cursor.rowcount
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def references(cursor, reference):
|
|
|
|
|
changes = dict(dictionaryTypes=0, dictionaryValues=0, groups=0, menus=0, buttons=0, menuUpdates=0)
|
|
|
|
|
for dictionary in reference['dictionaries']:
|
|
|
|
|
changes['dictionaryTypes'] += insert_new(cursor, 'system_dict_type', {'name': dictionary['name'], 'type': dictionary['type'], 'status': 0,
|
|
|
|
|
'creator': 'cmvr-port', 'updater': 'cmvr-port', 'deleted': 0}, ['type'])
|
|
|
|
|
for item in dictionary['items']:
|
|
|
|
|
changes['dictionaryValues'] += insert_new(cursor, 'system_dict_data', {'sort': item.get('sort', 1), 'label': item['label'],
|
|
|
|
|
'value': item['value'], 'dict_type': dictionary['type'], 'status': 0,
|
|
|
|
|
'color_type': item.get('color', 'default'), 'css_class': item.get('cssClass', ''),
|
|
|
|
|
'remark': 'Static CMVR reference; no historical business data',
|
|
|
|
|
'creator': 'cmvr-port', 'updater': 'cmvr-port', 'deleted': 0}, ['dict_type', 'value'])
|
|
|
|
|
for group in reference['groups']:
|
|
|
|
|
cursor.execute('SELECT type FROM cmvr_group WHERE group_id=%s', (group['groupId'],))
|
|
|
|
|
existing = cursor.fetchone()
|
|
|
|
|
if existing and existing[0] != group['type']:
|
|
|
|
|
raise RuntimeError(f"Native group {group['groupId']} has an incompatible group type")
|
|
|
|
|
changes['groups'] += insert_new(cursor, 'cmvr_group', {'group_id': group['groupId'], 'type': group['type'],
|
|
|
|
|
'group_name': group['name'], 'description': group['description'],
|
|
|
|
|
'create_by': 'cmvr-port', 'update_by': 'cmvr-port',
|
|
|
|
|
'remark': 'Independent default configuration; no original business rows'}, ['group_id'])
|
|
|
|
|
for menu in MENUS:
|
|
|
|
|
values = dict(zip(('id', 'name', 'permission', 'type', 'sort', 'parent_id', 'path', 'icon', 'component', 'component_name'), menu))
|
|
|
|
|
values.update(status=0, visible=1, keep_alive=1, always_show=1, creator='cmvr-port', updater='cmvr-port', deleted=0)
|
|
|
|
|
inserted, updated = ensure_menu(cursor, values)
|
|
|
|
|
changes['menus'] += inserted
|
|
|
|
|
changes['menuUpdates'] += updated
|
|
|
|
|
menu_permissions = {menu[2] for menu in MENUS if menu[2]}
|
|
|
|
|
action_names = {'list': '列表', 'query': '查询', 'add': '新增', 'edit': '编辑', 'remove': '删除',
|
|
|
|
|
'export': '导出', 'execute': '执行', 'review': '复核', 'report': '报告', 'volume': '音量'}
|
|
|
|
|
for sort, item in enumerate(reference['permissions'], 1):
|
|
|
|
|
if item['permission'] in menu_permissions:
|
|
|
|
|
continue
|
|
|
|
|
permission = item['permission']
|
|
|
|
|
action = action_names.get(permission.rsplit(':', 1)[-1], '操作')
|
|
|
|
|
enabled = item.get('enabled', True)
|
|
|
|
|
values = dict(id=button_id(permission), name=f'{action} {permission}', permission=permission,
|
|
|
|
|
type=3, sort=sort, parent_id=item['parentMenuId'], path='', icon='', component=None, component_name=None,
|
|
|
|
|
status=0 if enabled else 1, visible=1 if enabled else 0, keep_alive=0, always_show=0,
|
|
|
|
|
creator='cmvr-port', updater='cmvr-port', deleted=0 if enabled else 1)
|
|
|
|
|
inserted, updated = ensure_menu(cursor, values)
|
|
|
|
|
changes['buttons'] += inserted
|
|
|
|
|
changes['menuUpdates'] += updated
|
|
|
|
|
# Retain the earlier prototype as source history, not as the new primary detection interface.
|
|
|
|
|
cursor.execute('UPDATE system_menu SET visible=0 WHERE id IN (20900,20901)')
|
|
|
|
|
changes['topologyUpdates'] = apply_menu_topology(cursor)
|
|
|
|
|
finalize_permissions(cursor)
|
|
|
|
|
return changes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def verify_references(cursor, reference):
|
|
|
|
|
for dictionary in reference['dictionaries']:
|
|
|
|
|
cursor.execute('SELECT COUNT(*) FROM system_dict_type WHERE type=%s AND deleted=0 AND status=0', (dictionary['type'],))
|
|
|
|
|
if cursor.fetchone()[0] != 1:
|
|
|
|
|
raise RuntimeError(f"Dictionary type verification failed: {dictionary['type']}")
|
|
|
|
|
for item in dictionary['items']:
|
|
|
|
|
cursor.execute('SELECT COUNT(*) FROM system_dict_data WHERE dict_type=%s AND value=%s AND deleted=0 AND status=0',
|
|
|
|
|
(dictionary['type'], item['value']))
|
|
|
|
|
if cursor.fetchone()[0] != 1:
|
|
|
|
|
raise RuntimeError(f"Dictionary value verification failed: {dictionary['type']}")
|
|
|
|
|
for group in reference['groups']:
|
|
|
|
|
cursor.execute('SELECT type FROM cmvr_group WHERE group_id=%s', (group['groupId'],))
|
|
|
|
|
if cursor.fetchone() != (group['type'],):
|
|
|
|
|
raise RuntimeError('Native default group verification failed')
|
|
|
|
|
menu_permissions = {menu[2] for menu in MENUS if menu[2]}
|
|
|
|
|
for menu in MENUS:
|
|
|
|
|
cursor.execute('SELECT component_name,parent_id FROM system_menu WHERE id=%s AND deleted=0 AND status=0', (menu[0],))
|
|
|
|
|
if cursor.fetchone() != (menu[9], menu[5]):
|
|
|
|
|
raise RuntimeError('CMVR menu wrapper verification failed')
|
|
|
|
|
for item in reference['permissions']:
|
|
|
|
|
if item['permission'] in menu_permissions:
|
|
|
|
|
continue
|
|
|
|
|
cursor.execute('SELECT permission,parent_id,type,CAST(deleted AS UNSIGNED),status FROM system_menu WHERE id=%s', (button_id(item['permission']),))
|
|
|
|
|
disabled = 0 if item.get('enabled', True) else 1
|
|
|
|
|
if cursor.fetchone() != (item['permission'], item['parentMenuId'], 3, disabled, disabled):
|
|
|
|
|
raise RuntimeError('Native permission button verification failed')
|
|
|
|
|
for identifier, (parent, path, sort) in MENU_REPARENTS.items():
|
2026-11-06 10:50:49 +08:00
|
|
|
cursor.execute('SELECT parent_id,path,sort,CAST(deleted AS UNSIGNED),status,CAST(visible AS UNSIGNED) FROM system_menu WHERE id=%s', (identifier,))
|
|
|
|
|
visible = 0 if identifier in HIDDEN_MENU_IDS else 1
|
|
|
|
|
if cursor.fetchone() != (parent, path, sort, 0, 0, visible):
|
2026-10-22 16:18:37 +08:00
|
|
|
raise RuntimeError(f'Unified menu verification failed: {identifier}')
|
|
|
|
|
for identifier in RETIRED_MENUS:
|
|
|
|
|
cursor.execute('SELECT CAST(deleted AS UNSIGNED),status,CAST(visible AS UNSIGNED) FROM system_menu WHERE id=%s', (identifier,))
|
|
|
|
|
row = cursor.fetchone()
|
|
|
|
|
if row and row != (1, 1, 0):
|
|
|
|
|
raise RuntimeError(f'Retired menu was resurrected: {identifier}')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
|
|
|
parser.add_argument('--apply', action='store_true')
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
reference = load_reference()
|
|
|
|
|
schema = load_schema(SCHEMA, PREFIXES)
|
|
|
|
|
host_schema = load_schema(ROOT / 'am-backend/sql/freescan/004_cmvr_bridge_schema.sql')
|
|
|
|
|
if not args.apply:
|
|
|
|
|
print(f'DRY RUN: {len(schema)} native tables + {len(host_schema)} mapping table; '
|
|
|
|
|
f"{len(reference['dictionaries'])} dictionary types, {sum(len(item['items']) for item in reference['dictionaries'])} static values, "
|
|
|
|
|
f"{len(reference['groups'])} default groups, {len(reference['permissions'])} annotated permission keys; no database connection")
|
|
|
|
|
return
|
|
|
|
|
runtime = json.loads((ROOT / '.local/runtime.json').read_text(encoding='utf-8-sig'))
|
|
|
|
|
mysql = runtime['mysql']
|
|
|
|
|
validate_target(mysql)
|
|
|
|
|
import pymysql
|
|
|
|
|
connection = pymysql.connect(host=mysql['host'], port=mysql.get('port',3306), user=mysql['user'],
|
|
|
|
|
password=mysql['password'], database=mysql['database'], charset='utf8mb4', autocommit=True)
|
|
|
|
|
locked = False
|
|
|
|
|
try:
|
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
|
cursor.execute(f'SELECT value FROM `{META}` WHERE name=%s', ('owner',))
|
|
|
|
|
if cursor.fetchone() != (OWNER,):
|
|
|
|
|
raise RuntimeError('Independent database ownership verification failed')
|
|
|
|
|
cursor.execute('SELECT GET_LOCK(%s,10)', (OWNER + '/cmvr',))
|
|
|
|
|
locked = cursor.fetchone() == (1,)
|
|
|
|
|
if not locked:
|
|
|
|
|
raise RuntimeError('Another CMVR migration is running')
|
|
|
|
|
changes = ensure_schema(cursor, schema) + ensure_schema(cursor, host_schema)
|
|
|
|
|
seeded = references(cursor, reference)
|
|
|
|
|
verify_references(cursor, reference)
|
|
|
|
|
print(f'CMVR ready in am-freescan: {len(schema)} native tables; {changes} additive schema changes; '
|
|
|
|
|
f'static seed changes {json.dumps(seeded, sort_keys=True)}; references verified; original business rows were not imported')
|
|
|
|
|
finally:
|
|
|
|
|
if locked:
|
|
|
|
|
with connection.cursor() as cursor:
|
|
|
|
|
cursor.execute('SELECT RELEASE_LOCK(%s)', (OWNER + '/cmvr',))
|
|
|
|
|
connection.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
main()
|