You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
189 lines
9.9 KiB
Python
189 lines
9.9 KiB
Python
"""Align observed saved answer fields with their current page forms.
|
|
|
|
No model calls. Dry-run by default. The three explicitly approved aggregate
|
|
answers replace conflicting step copies only with --approved-conflicts.
|
|
All affected answers and indexes are backed up before an apply transaction.
|
|
"""
|
|
import argparse
|
|
import copy
|
|
import datetime
|
|
import html
|
|
import json
|
|
from pathlib import Path
|
|
from urllib.parse import urlparse
|
|
from migrate_training_step_answers import ROOT, FIELD_MAP, connect
|
|
from repair_remaining_step_answers import synchronize_step
|
|
|
|
APPROVED_CONFLICTS = {'215bba6a-3301-4acb-847c-df321478bb77', '700f22bf-9254-4038-9c54-b70b86a22e84', '77724811-9c38-4a48-a5eb-81fcd59ef252'}
|
|
FIELDS = json.loads(FIELD_MAP.read_text(encoding='utf-8'))
|
|
|
|
|
|
def renamed(obj, old, new, convert=lambda x: x):
|
|
if old not in obj:
|
|
return
|
|
value = convert(obj[old])
|
|
if new in obj and obj[new] != value:
|
|
raise ValueError('Conflicting field values: ' + old + ' / ' + new)
|
|
obj[new] = value
|
|
del obj[old]
|
|
|
|
|
|
def attachment(url, name=''):
|
|
return {'url': url, 'name': name or Path(urlparse(url).path).name}
|
|
|
|
|
|
def normalize_urls(value, moves):
|
|
if isinstance(value, dict):
|
|
return {k: normalize_urls(v, moves) for k, v in value.items()}
|
|
if isinstance(value, list):
|
|
return [normalize_urls(v, moves) for v in value]
|
|
if isinstance(value, str) and value.startswith('http://120.79.161.177:'):
|
|
url = urlparse(value)
|
|
if url.path.startswith('/file/') and not url.query and not url.fragment:
|
|
moves[value] = url.path
|
|
return url.path
|
|
return value
|
|
|
|
|
|
def plan_row(row, approved=False, preview=None, questionnaire_text=''):
|
|
columns = {n: json.loads(row.get('step%d_answer' % n) or '{}') for n in range(1, 11)}
|
|
if any(not isinstance(v, dict) for v in columns.values()):
|
|
return {}, {}
|
|
original = copy.deepcopy(columns)
|
|
task = row['task_key']
|
|
if row['id'] in APPROVED_CONFLICTS:
|
|
if not approved:
|
|
return {}, {}
|
|
for n, fields in enumerate(FIELDS[task][1:], 2):
|
|
projected = {k: columns[1][k] for k in fields if k in columns[1]}
|
|
if projected:
|
|
columns[n] = projected
|
|
for k in projected:
|
|
columns[1].pop(k)
|
|
one, two, three, four = [columns[n] for n in range(1, 5)]
|
|
dynamic = json.loads(row.get('dynamic_step_answers') or '{}')
|
|
original_dynamic = copy.deepcopy(dynamic)
|
|
if task == 'target-user-profile':
|
|
renamed(one, 'excelUrl', 'profileFileUrl')
|
|
renamed(one, 'excelName', 'profileFileName')
|
|
if 'profileFileUrl' in one and 'profilePreview' not in one and preview is not None:
|
|
one['profilePreview'] = preview
|
|
if 'charts' in two:
|
|
charts = two['charts']
|
|
if not isinstance(charts, list) or any(not c.get('type') for c in charts):
|
|
raise ValueError('Unknown chart shape')
|
|
renamed(two, 'charts', 'rfmCharts', lambda rows: {c['type']: attachment(c.get('url', ''), c.get('name', '')) for c in rows})
|
|
renamed(three, 'insights', 'rfmInsights')
|
|
renamed(four, 'records', 'keyUserRecords')
|
|
if '5' in dynamic and isinstance(dynamic['5'], dict) and 'segments' in dynamic['5']:
|
|
fifth = copy.deepcopy(dynamic['5'])
|
|
renamed(fifth, 'segments', 'marketSegments')
|
|
if columns[5] and columns[5] != fifth:
|
|
raise ValueError('Conflicting fifth step')
|
|
columns[5] = fifth
|
|
del dynamic['5']
|
|
elif task == 'consumer-behavior':
|
|
renamed(one, 'hypotheses', 'targetHypotheses')
|
|
renamed(two, 'needs', 'kanoNeeds')
|
|
renamed(three, 'questions', 'questionnaireQuestions')
|
|
if 'importedDocumentUrl' in three:
|
|
url = three.pop('importedDocumentUrl')
|
|
if three.get('questionnaireImport', {}).get('url', url) != url:
|
|
raise ValueError('Conflicting questionnaire file')
|
|
three['questionnaireImport'] = {'url': url, 'name': three.get('questionnaireFileName') or Path(urlparse(url).path).name,
|
|
'previewContent': questionnaire_text}
|
|
if questionnaire_text and not three.get('questionnaireText'):
|
|
three['questionnaireText'] = ''.join('<p>' + html.escape(line) + '</p>' for line in questionnaire_text.splitlines() if line.strip())
|
|
renamed(four, 'rows', 'surveyReportRows')
|
|
elif task == 'purchase-demand-forecast':
|
|
renamed(one, 'items', 'linearForecastRows')
|
|
renamed(two, 'forecastChartUrl', 'demandForecastChart', attachment)
|
|
elif task == 'market-opportunity-selection':
|
|
renamed(four, 'visualizationUrl', 'visualization', attachment)
|
|
elif task == 'hardware-cost':
|
|
for key in ('smallBatchChart', 'largeBatchChart'):
|
|
renamed(four, key + 'Url', key, attachment)
|
|
elif task == 'business-feasibility':
|
|
if 'reportUrl' in three:
|
|
report = attachment(three.pop('reportUrl'), three.pop('reportName', ''))
|
|
if three.get('report', report) != report:
|
|
raise ValueError('Conflicting report')
|
|
three['report'] = report
|
|
elif task == 'requirements-doc':
|
|
if 'documentUrl' in three:
|
|
document = attachment(three.pop('documentUrl'), three.pop('documentName', ''))
|
|
document.update(fileType=Path(urlparse(document['url']).path).suffix.lstrip('.').upper(), size=0, previewContent='')
|
|
three['document'] = document
|
|
elif task == 'product-development-process':
|
|
renamed(one, 'list', 'items')
|
|
renamed(two, 'list', 'items')
|
|
moves = {}
|
|
columns = normalize_urls(columns, moves)
|
|
changes = {'step%d_answer' % n: json.dumps(value, ensure_ascii=False, separators=(',', ':')) for n, value in columns.items() if value != original[n]}
|
|
if dynamic != original_dynamic:
|
|
changes['dynamic_step_answers'] = json.dumps(dynamic, ensure_ascii=False, separators=(',', ':'))
|
|
return changes, moves
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--apply', action='store_true')
|
|
parser.add_argument('--approved-conflicts', action='store_true')
|
|
parser.add_argument('--backup', type=Path)
|
|
args = parser.parse_args()
|
|
if args.apply and not args.backup:
|
|
parser.error('--apply requires --backup')
|
|
preview_file = ROOT / 'target/field-repair/profile-preview.json'
|
|
preview = json.loads(preview_file.read_text(encoding='utf-8')) if preview_file.exists() else None
|
|
questionnaire_file = ROOT / 'target/field-repair/questionnaire-sections.json'
|
|
text = '\n'.join(s['text'] for s in json.loads(questionnaire_file.read_text(encoding='utf-8'))) if questionnaire_file.exists() else ''
|
|
conn = connect(ROOT / 'src/main/resources/application-dev.yml')
|
|
try:
|
|
with conn.cursor() as q:
|
|
q.execute('START TRANSACTION' if args.apply else 'START TRANSACTION READ ONLY')
|
|
q.execute('SELECT * FROM student_training_answer' + (' FOR UPDATE' if args.apply else ''))
|
|
plans = []
|
|
for row in q.fetchall():
|
|
changes, moves = plan_row(row, args.approved_conflicts, preview, text)
|
|
if changes:
|
|
plans.append((row, changes, moves))
|
|
print(json.dumps({'mode': 'apply' if args.apply else 'dry-run', 'rows': len(plans), 'changes': [dict(id=r['id'], task=r['task_key'], columns=list(c)) for r, c, _ in plans]}, ensure_ascii=False))
|
|
if not args.apply:
|
|
return
|
|
backup = {'answers': [r for r, _, _ in plans], 'details': [], 'files': [], 'chunks': []}
|
|
for row, _, _ in plans:
|
|
for table, name in [('student_training_step_answer', 'details'), ('training_knowledge_file', 'files'), ('training_knowledge_chunk', 'chunks')]:
|
|
q.execute('SELECT * FROM ' + table + ' WHERE student_user_id=%s AND task_key=%s', [row['student_user_id'], row['task_key']])
|
|
backup[name].extend(q.fetchall())
|
|
def encode(v):
|
|
if isinstance(v, bytes): return {'bytes_hex': v.hex()}
|
|
if isinstance(v, (datetime.datetime, datetime.date)): return v.isoformat()
|
|
return str(v)
|
|
with args.backup.open('x', encoding='utf-8') as out:
|
|
json.dump(backup, out, ensure_ascii=False, default=encode, indent=2)
|
|
for row, changes, moves in plans:
|
|
q.execute('UPDATE student_training_answer SET ' + ','.join(k + '=%s' for k in changes) + ' WHERE id=%s', list(changes.values()) + [row['id']])
|
|
for old, new in moves.items():
|
|
q.execute('SELECT * FROM training_knowledge_file WHERE student_user_id=%s AND task_key=%s AND file_url=%s', [row['student_user_id'], row['task_key'], old])
|
|
for record in q.fetchall():
|
|
q.execute('SELECT id FROM training_knowledge_file WHERE source_type=%s AND effective_config_id=%s AND student_user_id=%s AND file_url=%s',
|
|
[record['source_type'], record['effective_config_id'], record['student_user_id'], new])
|
|
if not q.fetchone():
|
|
q.execute('UPDATE training_knowledge_file SET file_url=%s WHERE id=%s', [new, record['id']])
|
|
for key, raw in changes.items():
|
|
if key.startswith('step'):
|
|
synchronize_step(q, row, key, raw)
|
|
q.execute('SELECT * FROM student_training_answer WHERE id=%s', [row['id']])
|
|
actual = q.fetchone()
|
|
if any(actual[k] != changes.get(k, v) for k, v in row.items()):
|
|
raise ValueError('Unexpected answer/score/status change: ' + row['id'])
|
|
conn.commit()
|
|
print(json.dumps({'aligned_rows': len(plans), 'backup': str(args.backup)}))
|
|
finally:
|
|
conn.rollback()
|
|
conn.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|