def prepare_planning_db(domain): db_filepath = get_planning_db_filepath(domain) planning_db = PlanningDB.init(db_filepath) xform_ids = get_form_ids_by_type(domain, 'XFormInstance') xform_db = XFormInstance.get_db() for i, xform in enumerate(iter_docs(xform_db, xform_ids)): xform_id = xform['_id'] case_actions_by_case_id = collections.defaultdict(list) try: xml = _get_submission_xml(xform, xform_db) except ResourceNotFound: continue new_form_json = _get_new_form_json(xml, xform_id) case_updates = get_case_updates(new_form_json) xform_copy = deepcopy(xform) xform_copy['form'] = new_form_json xformdoc = XFormInstance.wrap(xform_copy) xformdoc_json = xformdoc.to_json() planning_db.add_form(xform_id, xformdoc_json) planning_db.add_diffs('form', xform_id, json_diff(xform, xformdoc_json)) case_actions = [ (case_update.id, action.xform_id, action.to_json()) for case_update in case_updates for action in case_update.get_case_actions(xformdoc) ] stock_report_helpers, stock_case_actions = get_stock_actions(xformdoc) case_actions.extend(stock_case_actions) for case_id, xform_id, case_action in case_actions: case_actions_by_case_id[case_id].append((xform_id, case_action)) for case_id, case_actions in case_actions_by_case_id.items(): planning_db.ensure_case(case_id) planning_db.add_case_actions(case_id, case_actions) planning_db.add_stock_report_helpers([ stock_report_helper.to_json() for stock_report_helper in stock_report_helpers ]) return prepare_case_json(planning_db)
def get_planning_db(domain): db_filepath = get_planning_db_filepath(domain) return PlanningDB.open(db_filepath)