Last active
December 26, 2015 04:49
-
-
Save davidfraser/7095779 to your computer and use it in GitHub Desktop.
This is a script that will create online_id links for each account in a gnucash file, that correspond to the account ids generated by GnuCash for Android (https://github.com/codinguser/gnucash-android). It will alter the file in-place. After this, imports of OFX files exported by GnuCash for Android should automatically match accounts correctly.…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
from lxml import etree | |
import tempfile | |
import sys | |
current_file = sys.argv[1] | |
tree = etree.parse(current_file) | |
root = tree.getroot() | |
nsmap = root.nsmap | |
for account in root.xpath(".//gnc:account", namespaces=nsmap): | |
guid = account.xpath("./act:id[@type='guid']/text()", namespaces=nsmap)[0] | |
name = account.xpath("./act:name/text()", namespaces=nsmap)[0] | |
slots_list = account.xpath("./act:slots", namespaces=nsmap) | |
if not slots_list: | |
slots = etree.SubElement(account, "{%(act)s}slots" % nsmap) | |
else: | |
slots = slots_list[0] | |
slot_list = slots.xpath("./slot", namespaces=nsmap) | |
for slot in slot_list: | |
slot_key = slot.xpath("./slot:key/text()", namespaces=nsmap)[0] | |
if slot_key == "online_id": | |
online_id = slot.xpath("./slot:value/text()", namespaces=nsmap)[0] | |
if online_id.startswith("org.gnucas") and guid[:23] in online_id: | |
print("Account %s already has gnucash for android ID (%s)" % (name, online_id)) | |
else: | |
print("Account %s already has other ID (%s)" % (name, online_id)) | |
break | |
else: | |
slot = etree.SubElement(slots, "slot" % nsmap) | |
slot_key = etree.SubElement(slot, "{%(slot)s}key" % nsmap) | |
slot_key.text = "online_id" | |
slot_value = etree.SubElement(slot, "{%(slot)s}value" % nsmap, attrib={"type": "string"}) | |
slot_value.text = "org.gnucas %s" % guid[:23] | |
source = etree.tostring(tree, encoding=tree.docinfo.encoding, xml_declaration=True) | |
target_dir = os.path.dirname(os.path.abspath(current_file)) | |
tmp_fd, tmp_filename = tempfile.mkstemp(suffix=".gnucash", dir=target_dir) | |
with os.fdopen(tmp_fd, "wb") as tmp_file: | |
tmp_file.write(source) | |
os.rename(tmp_filename, current_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment