Small performance fix + cleanup of account_invoice

Two separate commits.

The first one adds a small performance improvement: there are two writes being performed: the first optional, the second one always. Instead of writing twice, we keep the values of the optional write in a dictionary, and merge it with the values for the second write so we only need to write to the DB once.

The second one is just cleaning up unused imports and variables.