Debian Codegraph @

sepaxml/shared.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 """
2 Copyright (c) 2014 Congressus, The Netherlands
3 Copyright (c) 2017-2023 Raphael Michel and contributors
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is furnished
10 to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in all
13 copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 """
22 import xml.etree.ElementTree as ET
23 from collections import OrderedDict
24
25 from .utils import decimal_str_to_int, int_to_decimal_str, make_msg_id
26 from .validation import try_valid_xml
27
28
29 class SepaPaymentInitn:
30
31 def __init__(self, config, schema, clean=True):
32 """
33 Constructor. Checks the config, prepares the document and
34 builds the header.
35 @param param: The config dict.
36 @raise exception: When the config file is invalid.
37 """
38 self._config = None # Will contain the config file.
39 self._xml = None # Will contain the final XML file.
40 self._batches = OrderedDict() # Will contain the SEPA batches.
41 self._batch_totals = OrderedDict() # Will contain the total amount to debit per batch for checksum total.
42 self.schema = schema
43 self.msg_id = make_msg_id()
44 self.clean = clean
45
46 config_result = self.check_config(config)
47 if config_result:
48 self._config = config
49 if self.clean:
50 from text_unidecode import unidecode
51
52 self._config['name'] = unidecode(self._config['name'])[:70]
53
54 self._prepare_document()
55 self._create_header()
56
57 def _prepare_document(self):
•58 """
59 Build the main document node and set xml namespaces.
60 """
61 self._xml = ET.Element("Document")
62 self._xml.set("xmlns",
63 "urn:iso:std:iso:20022:tech:xsd:" + self.schema)
64 self._xml.set("xmlns:xsi",
65 "http://www.w3.org/2001/XMLSchema-instance")
66 ET.register_namespace("",
67 "urn:iso:std:iso:20022:tech:xsd:" + self.schema)
68 ET.register_namespace("xsi",
69 "http://www.w3.org/2001/XMLSchema-instance")
70 n = ET.Element(self.root_el)
71 self._xml.append(n)
72
73 def _create_header(self):
74 raise NotImplementedError()
75
76 def _finalize_batch(self):
77 raise NotImplementedError()
78
79 def export(self, validate=False, pretty_print=False):
80 """
81 Method to output the xml as string. It will finalize the batches and
82 then calculate the checksums (amount sum and transaction count),
83 fill these into the group header and output the XML.
84
85 @param pretty_print: uses Python's xml.dom.minidom.Node.toprettyxml to make it easier to read for humans
86 """
87 self._finalize_batch()
88
89 ctrl_sum_total = 0
90 nb_of_txs_total = 0
91
92 for ctrl_sum in self._xml.iter('CtrlSum'):
93 if ctrl_sum.text is None:
94 continue
95 ctrl_sum_total += decimal_str_to_int(ctrl_sum.text)
96
97 for nb_of_txs in self._xml.iter('NbOfTxs'):
98 if nb_of_txs.text is None:
99 continue
100 nb_of_txs_total += int(nb_of_txs.text)
101
102 n = self._xml.find(self.root_el)
103 GrpHdr_node = n.find('GrpHdr')
104 CtrlSum_node = GrpHdr_node.find('CtrlSum')
105 NbOfTxs_node = GrpHdr_node.find('NbOfTxs')
106 CtrlSum_node.text = int_to_decimal_str(ctrl_sum_total)
107 NbOfTxs_node.text = str(nb_of_txs_total)
108
109 # Prepending the XML version is hacky, but cElementTree only offers this
110 # automatically if you write to a file, which we don't necessarily want.
111 out = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + ET.tostring(
112 self._xml, "utf-8")
113
114 if pretty_print:
115 from xml.dom import minidom
116 out_minidom = minidom.parseString(out)
117 out = out_minidom.toprettyxml(encoding="utf-8")
118
119 if validate:
120 try_valid_xml(out, self.schema)
121 return out