← back to Dw Repair Debug TK11314

worklist_progress.py

64 lines

"""Read-only, product-specific repair progress. Importing this module does no I/O."""
import argparse
import json
import subprocess


def task_key(row):
    product = row.get('shopify_id') or row.get('product_id')
    fix = row.get('fix_type') or row.get('fix')
    if not product or not fix:
        return None  # An incomplete historical audit cannot complete another task.
    return str(product).rsplit('/', 1)[-1], fix


def split_work(work, audit):
    completed = {task_key(row) for row in audit
                 if row.get('status') in ('fixed', 'skipped') and task_key(row)}
    seen = set()
    unique = []
    for row in work:
        key = task_key(row)
        if key is None or key not in seen:
            unique.append(row)
        if key:
            seen.add(key)
    todo = [row for row in unique if task_key(row) not in completed]
    return unique, todo


def summarize(work, audit):
    unique, todo = split_work(work, audit)
    return {'source_rows': len(work), 'total': len(unique),
            'done': len(unique) - len(todo), 'remaining': len(todo)}


def load_current_worklist():
    query = """SELECT coalesce(json_agg(row_to_json(t)), '[]') FROM (
      SELECT shopify_id, dw_sku, fix_type FROM bulk_fivefield_worklist
      WHERE status='pending' AND lower(coalesce(vendor,'')) <> 'schumacher'
    ) t"""
    return json.loads(subprocess.check_output(
        ['psql', '-X', '-d', 'dw_unified', '-At', '-c', query], text=True))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--audit', required=True)
    parser.add_argument('--worklist-json')
    parser.add_argument('--counts', action='store_true')
    args = parser.parse_args()
    with open(args.audit) as handle:
        audit = json.load(handle)
    if args.worklist_json:
        with open(args.worklist_json) as handle:
            work = json.load(handle)
    else:
        work = load_current_worklist()
    result = summarize(work, audit)
    print(f"{result['total']} {result['done']} {result['remaining']}" if args.counts else json.dumps(result))


if __name__ == '__main__':
    main()