Files
@ 11e295cfe42d
Branch filter:
Location: rattail-project/rattail/rattail/sil.py
11e295cfe42d
8.3 KiB
text/x-python
improve sil.val(), add sil.write_rows()
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 278 279 280 281 282 283 284 285 286 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# Rattail -- Retail Software Framework
# Copyright © 2010-2012 Lance Edgar
#
# This file is part of Rattail.
#
# Rattail is free software: you can redistribute it and/or modify it under the
# terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# Rattail is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Rattail. If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
``rattail.sil`` -- Standard Interchange Language
Please see the `Standard Interchange Language Specifications
<http://productcatalog.gs1us.org/Store/tabid/86/CategoryID/21/List/1/catpageindex/2/Level/a/ProductID/46/Default.aspx>`_
for more information.
"""
import datetime
from decimal import Decimal
import edbob
import rattail
def val(value):
"""
Returns a string version of ``value``, suitable for inclusion within a data
row of a SIL batch. The conversion is done as follows:
If ``value`` is ``None``, an empty string is returned.
If it is an ``int`` or ``decimal.Decimal`` instance, it is converted
directly to a string (i.e. not quoted).
If it is a ``datetime.date`` instance, it will be formatted as ``'%Y%j'``.
If it is a ``datetime.time`` instance, it will be formatted as ``'%H%M'``.
Otherwise, it is converted to a string if necessary, and quoted with
apostrophes escaped.
"""
if value is None:
return ''
if isinstance(value, int):
return str(value)
if isinstance(value, Decimal):
return str(value)
if isinstance(value, datetime.date):
return value.strftime('%Y%j')
if isinstance(value, datetime.time):
return value.strftime('%H%M')
if not isinstance(value, basestring):
value = str(value)
return "'%s'" % value.replace("'", "''")
def consume_batch_id():
"""
Returns the next available batch identifier, incrementing the number to
preserve uniqueness.
"""
config = edbob.AppConfigParser('rattail')
config_path = config.get_user_file('rattail.conf', create=True)
config.read(config_path)
batch_id = config.get('rattail.sil', 'next_batch_id', default='')
if not batch_id.isdigit():
batch_id = '1'
batch_id = int(batch_id)
config.set('rattail.sil', 'next_batch_id', str(batch_id + 1))
config_file = open(config_path, 'w')
config.write(config_file)
config_file.close()
return '%08u' % batch_id
def write_batch_header(fileobj, H03='RATAIL', **kwargs):
"""
Writes a SIL batch header string to ``fileobj``. All keyword arguments
correspond to the SIL specification for the Batch Header Dictionary.
If you do not override ``H03`` (Source Identifier), then Rattail will
provide a default value for ``H20`` (Software Revision) - that is, unless
you've supplied it yourself.
**Batch Header Dictionary:**
==== ==== ==== ===========
Name Type Size Description
==== ==== ==== ===========
H01 CHAR 2 Batch Type
H02 CHAR 8 Batch Identifier
H03 CHAR 6 Source Identifier
H04 CHAR 6 Destination Identifier
H05 CHAR 12 Audit File Name
H06 CHAR 12 Response File Name
H07 DATE 7 Origin Date
H08 TIME 4 Origin Time
H09 DATE 7 Execution (Apply) Date
H10 DATE 4 Execution (Apply) Time
H11 DATE 7 Purge Date
H12 CHAR 6 Action Type
H13 CHAR 50 Batch Description
H14 CHAR 30 User Defined
H15 CHAR 30 User Defined
H16 CHAR 30 User Defined
H17 NUMBER 1 Warning Level
H18 NUMBER 5 Maximum Error Count
H19 CHAR 7 SIL Level/Revision
H20 CHAR 4 Software Revision
H21 CHAR 50 Primary Key
H22 CHAR 512 System Specific Command
H23 CHAR 8 Dictionary Revision
Consult the SIL Specification for more information.
"""
kw = kwargs
# Provide default for H20 if batch origin is 'RATAIL'.
H20 = kw.get('H20')
if H03 == 'RATAIL' and H20 is None:
H20 = rattail.__version__[:4]
# Don't quote H09 if special "immediate" value.
H09 = kw.get('H09')
if H09 != '0000000':
H09 = val(H09)
# Don't quote H10 if special "immediate" value.
H10 = kw.get('H10')
if H10 != '0000':
H10 = val(H10)
row = [
val(kw.get('H01')),
val(kw.get('H02')),
val(H03),
val(kw.get('H04')),
val(kw.get('H05')),
val(kw.get('H06')),
val(kw.get('H07')),
val(kw.get('H08')),
H09,
H10,
val(kw.get('H11')),
val(kw.get('H12')),
val(kw.get('H13')),
val(kw.get('H14')),
val(kw.get('H15')),
val(kw.get('H16')),
val(kw.get('H17')),
val(kw.get('H18')),
val(kw.get('H19')),
val(H20),
val(kw.get('H21')),
val(kw.get('H22')),
val(kw.get('H23')),
]
fileobj.write('INSERT INTO HEADER_DCT VALUES\n')
write_row(fileobj, row, quote=False, last=True)
fileobj.write('\n')
def write_row(fileobj, row, quote=True, last=False):
"""
Writes a SIL row string to ``fileobj``.
``row`` should be a sequence of values.
If ``quote`` is ``True``, each value in ``row`` will be ran through the
:func:`val()` function before being written. If it is ``False``, the
values are written as-is.
If ``last`` is ``True``, then ``';'`` will be used as the statement
terminator; otherwise ``','`` is used.
"""
terminator = ';' if last else ','
if quote:
row = [val(x) for x in row]
fileobj.write('(' + ','.join(row) + ')' + terminator + '\n')
def write_rows(fileobj, rows):
"""
Writes a set of SIL row strings to ``fileobj``.
``rows`` should be a sequence of sequences, each of which should be
suitable for use with :func:`write_row()`.
(This funcion primarily exists to handle the mundane task of setting the
``last`` flag when calling :func:`write_row()`.)
"""
last = len(rows) - 1
for i, row in enumerate(rows):
write_row(fileobj, row, last=i == last)
# # from pkg_resources import iter_entry_points
# # import rattail
# # from rattail.batch import make_batch, RattailBatchTerminal
# from rattail.batches import RattailBatchTerminal
# # _junctions = None
# # class SILError(Exception):
# # """
# # Base class for SIL errors.
# # """
# # pass
# # class ElementRequiredError(SILError):
# # """
# # Raised when a batch import or export is attempted, but the element list
# # supplied is missing a required element.
# # """
# # def __init__(self, required, using):
# # self.required = required
# # self.using = using
# # def __str__(self):
# # return "The element list supplied is missing required element '%s': %s" % (
# # self.required, self.using)
# def default_display(field):
# """
# Returns the default UI display value for a SIL field, according to the
# Rattail field map.
# """
# return RattailBatchTerminal.fieldmap_user[field]
# # def get_available_junctions():
# # """
# # Returns a dictionary of available :class:`rattail.BatchJunction` classes,
# # keyed by entry point name.
# # """
# # global _junctions
# # if _junctions is None:
# # _junctions = {}
# # for entry_point in iter_entry_points('rattail.batch_junctions'):
# # _junctions[entry_point.name] = entry_point.load()
# # return _junctions
# # def get_junction_display(name):
# # """
# # Returns the ``display`` value for a registered
# # :class:`rattail.BatchJunction` class, given its ``name``.
# # """
# # juncs = get_available_junctions()
# # if name in juncs:
# # return juncs[name].display
# # return None
|