File: formats.py

package info (click to toggle)
python-csb43 0.9.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 560 kB
  • sloc: python: 6,233; sh: 9; makefile: 6
file content (277 lines) | stat: -rw-r--r-- 6,789 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# -*- coding: utf-8 -*-
from .i18n import tr as _
from .utils import messages as msg
from . import utils

import json
import warnings


class FormatWarning(UserWarning):
    pass


_ABSTRACT_HEADER = (
    msg.T_BANK_CODE,
    msg.T_BRANCH_CODE,
    msg.T_ACCOUNT_KEY,
    msg.T_ACCOUNT_NUMBER,
    msg.T_INFORMATION_MODE,
    msg.T_SHORT_NAME,
    msg.T_CURRENCY,
    msg.T_INITIAL_DATE,
    msg.T_FINAL_DATE,
    msg.T_INITIAL_BALANCE,
    msg.T_FINAL_BALANCE,
    msg.T_INCOME,
    msg.T_EXPENSES,
    msg.T_INCOME_ENTRIES,
    msg.T_EXPENSES_ENTRIES
)


_TRANSACTION_HEADER = (
    msg.T_BRANCH_CODE,
    msg.T_DOCUMENT_NUMBER,
    msg.T_SHARED_ITEM,
    msg.T_OWN_ITEM,
    msg.T_ITEM_1,
    msg.T_ITEM_2,
    msg.T_REFERENCE_1,
    msg.T_REFERENCE_2,
    msg.T_TRANSACTION_DATE,
    msg.T_VALUE_DATE,
    msg.T_AMOUNT,
    msg.T_ORIGINAL_CURRENCY,
    msg.T_ORIGINAL_AMOUNT
)


def _abstractRow(ac):
    return (
        ac.bankCode,
        ac.branchCode,
        ac.get_account_key(),
        ac.accountNumber,
        ac.informationMode,
        ac.shortName,
        ac.currency.alpha_3,
        str(ac.initialDate),
        str(ac.finalDate),
        ac.initialBalance,
        ac.abstract.balance,
        ac.abstract.income,
        ac.abstract.expense,
        ac.abstract.incomeEntries,
        ac.abstract.expenseEntries
    )


def _transactionRow(t, decimal_fallback):

    name = ", ".join(x.item1.rstrip(' ') for x in t.optionalItems)

    extdname = ", ".join(x.item2.rstrip(' ') for x in t.optionalItems)

    if t.exchange:
        o_currency = utils.export_currency_code(t.exchange.sourceCurrency)
        o_amount = utils.export_decimal(t.exchange.amount, fallback=decimal_fallback)
    else:
        o_currency = None
        o_amount = None

    return (
        t.branchCode,
        t.documentNumber,
        t.sharedItem,
        t.ownItem,
        name,
        extdname,
        t.reference1,
        t.reference2,
        utils.export_date(t.transactionDate),
        utils.export_date(t.valueDate),
        t.amount,
        o_currency or '',
        o_amount or ''
    )


try:
    import tablib
    #: formats supported by :mod:`tablib`
    if tablib.__version__.startswith("0."):
        # tablib < 1.0.0
        TABLIB_FORMATS = [f.title for f in tablib.formats.available]
    else:
        # tablib >= 1.0.0
        TABLIB_FORMATS = [f.title for f in tablib.formats.registry.formats()]
except ImportError:
    TABLIB_FORMATS = []
    warnings.warn(
        _("Package 'tablib' not found. Formats provided by 'tablib' will not be available."),
        FormatWarning
    )

#: dictionary formats
DICT_FORMATS = ['json']
try:
    import yaml
    DICT_FORMATS.append('yaml')
except ImportError:
    warnings.warn(
        _("Package 'yaml' not found. Hierarchical YAML format will not be available."),
        FormatWarning
    )

#: available formats
FORMATS = list(set(TABLIB_FORMATS + DICT_FORMATS))


DECIMAL_SUPPORTED = [
    "ods",
    "xls",
    "xlsx",
    "csv",
    "tsv",
    "df",
    "html",
    "latex",
]


def convertFromCsb(csb, expectedFormat, decimal_fallback=None):
    '''
    Convert a File file into an :mod:`tablib` data object or a \
    dictionary-like object

    :param csb: a csb file
    :type  csb: :class:`csb43.csb43.File`
    :param decimal_fallback: decimal number fallback representation:

    - 'float': use type `float`
    - 'str': represent decimal as a string
    - `None`: use default fallback ('str')

    :rtype: :class:`tablib.Databook`, :class:`tablib.Dataset` or a object \
    with an attribute named as `expectedFormat`
    '''
    decimal_supported = expectedFormat in DECIMAL_SUPPORTED
    d_conversion = decimal_fallback or 'str'
    if decimal_supported:
        d_conversion = None

    if expectedFormat in DICT_FORMATS:
        return convertFromCsb2Dict(csb, expectedFormat, decimal_fallback=d_conversion)
    else:
        return convertFromCsb2Tabular(csb, expectedFormat, decimal_fallback=d_conversion)


class _TablibSurrogate(object):

    def __init__(self, string, expectedFormat):
        setattr(self, expectedFormat, string)


def convertFromCsb2Dict(csb, expectedFormat='json', decimal_fallback=None):
    '''
    Convert from `CSB43` to a dictionary format

    :param csb: a csb file
    :type  csb: :class:`csb43.csb43.File`
    :param decimal_fallback: decimal number fallback representation

    :rtype: a object with an attribute named as `expectedFormat`

    :raises: :class:`csb43.utils.Csb43Exception` when the format is unknown \
    or unsupported

    >>> from csb43.csb43 import File
    >>> import csb43.formats as formats
    >>> f = File()
    >>> o = formats.convertFromCsb2Dict(f, 'yaml')
    >>> print(o.yaml)
    cuentas: []
    <BLANKLINE>


    >>> o = formats.convertFromCsb2Dict(f, 'json')
    >>> print(o.json)
    {
     "cuentas": []
    }

    '''
    csb_dict = csb.as_dict(decimal_fallback=decimal_fallback)

    if expectedFormat == 'yaml':
        return _TablibSurrogate(yaml.safe_dump(csb_dict), expectedFormat)
    elif expectedFormat == 'json':
        return _TablibSurrogate(
            json.dumps(csb_dict, indent=1, sort_keys=True),
            expectedFormat
        )
    else:
        utils.raiseCsb43Exception(
            _("unexpected format %s") % expectedFormat, True)


def convertFromCsb2Tabular(csb, expectedFormat='ods', decimal_fallback=None):
    '''
    Convert a File file into an :mod:`tablib` data object

    :param csb: a csb file
    :type  csb: :class:`csb43.csb43.File`
    :param decimal_fallback: decimal number fallback representation

    :rtype: :class:`tablib.Databook` or :class:`tablib.Dataset`

    '''
    datasets = []

    accountsAbstract = tablib.Dataset()

    accountsAbstract.title = _("Accounts")
    accountsAbstract.headers = _ABSTRACT_HEADER

    datasets.append(accountsAbstract)

    for ac in csb.accounts:

        accountId = (
            ac.bankCode,
            ac.branchCode,
            ac.get_account_key(),
            ac.accountNumber
        )

        accountsAbstract.append(_abstractRow(ac))

        tList = tablib.Dataset()
        tList.title = '-'.join(accountId)

        tList.headers = _TRANSACTION_HEADER

        for t in ac.transactions:
            tList.append(_transactionRow(t, decimal_fallback))

        datasets.append(tList)

    book = tablib.Databook(datasets)

    if hasattr(book, expectedFormat):
        return book

    dataset = tablib.Dataset()

    dataset.title = _("Transactions")
    dataset.headers = _ABSTRACT_HEADER + _TRANSACTION_HEADER

    for ac in csb.accounts:

        accountAbstract = _abstractRow(ac)

        for t in ac.transactions:
            dataset.append(accountAbstract + _transactionRow(t, decimal_fallback))

    return dataset