Files
@ ac05762ef772
Branch filter:
Location: rattail-project/rattail/rattail/batches.py
ac05762ef772
14.2 KiB
text/x-python
bump version
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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 | #!/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.batches`` -- Batch Interface
"""
# import logging
from sqlalchemy import and_
from sqlalchemy.orm import object_session
import edbob
from edbob.db import needs_session
from edbob.util import requires_impl
import rattail
# from rattail.db import needs_session
# from rattail.util import get_entry_points, requires_impl
# log = logging.getLogger(__name__)
# # _registered_sources = None
# # def get_registered_sources():
# # """
# # Returns the entry point map for registered batch sources.
# # """
# # global _registered_sources
# # if _registered_sources is None:
# # _registered_sources = get_entry_points('rattail.batch_sources')
# # return _registered_sources
# # @needs_session
# # def get_sources(session):
# # """
# # Returns a dictionary of registered :class:`rattail.BatchSource` classes,
# # keyed by :attr:`BatchSource.name`.
# # """
# # sources = {}
# # for src in session.query(rattail.BatchSource):
# # sources[src.name] = src
# # return sources
class BatchTerminal(edbob.Object):
"""
Defines the interface for data batch terminals. Subclass this when
implementing new data awareness and/or integration with external systems.
"""
@property
@requires_impl()
def name(self):
pass
@property
@requires_impl()
def display(self):
pass
@property
@requires_impl()
def fieldmap_internal(self):
pass
@property
@requires_impl()
def fieldmap_user(self):
pass
@requires_impl()
def provide_rows(self, session, rowclass, dictionary, query=None, **kwargs):
"""
Generator which yields (new) batch row instances. This is used to
populate batches.
"""
raise NotImplementedError
# def get_elements(self, elements, fieldmap, *required):
# """
# Returns the proper element list according to current context.
# """
# if elements is None:
# elements = sorted(fieldmap)
# self.require_elements(elements, *required)
# return elements
# def require_elements(self, using, *required):
# """
# Officially require one or more elements when processing a batch.
# """
# for elements in required:
# elements = elements.split(',')
# for element in elements:
# if element not in using:
# raise sil.ElementRequiredError(element, using)
class RattailBatchTerminal(BatchTerminal):
"""
Defines the core batch terminal for Rattail.
"""
name = 'rattail'
description = "Rattail (local)"
source_columns = {
'ITEM_DCT': [
'F01',
'F02',
],
}
target_columns = {
'DEPT_DCT': [
'F03',
'F238',
],
'ITEM_DCT': [
'F01',
'F02',
'F03',
'F22',
'F155',
],
}
def provide_rows(self, session, rowclass, dictionary, query=None, **kwargs):
if dictionary.name == 'DEPT_DCT':
if not query:
query = session.query(rattail.Department)
for dept in query:
yield rowclass(
F03=dept.number,
F238=dept.name,
)
return
elif dictionary.name == 'ITEM_DCT':
if not query:
query = session.query(rattail.Product)
for product in query:
yield rowclass(
F01=int(product.upc),
F02=product.description[:20],
F155=product.brand.name if product.brand else None,
)
return
assert False, "FIXME"
# def import_main_item(self, session, elements=None, progress_factory=None):
# """
# Create a main item (ITEM_DCT) batch from current Rattail data.
# """
# elements = self.get_elements(elements, self.fieldname_map_main_item, 'F01')
# batch = make_batch(self.name, elements, session,
# description="Main item data from Rattail")
# products = session.query(rattail.Product)
# prog = None
# if progress_factory:
# prog = progress_factory("Creating batch", products.count())
# for i, prod in enumerate(products, 1):
# fields = {}
# for name in elements:
# fields[name] = row[self.fieldname_map_main_item[name]]
# batch.append(**fields)
# if prog:
# prog.update(i)
# if prog:
# prog.destroy()
# return batch
def add_departments(self, session, batch):
for row in batch.provide_rows():
dept = rattail.Department()
dept.number = row.F03
dept.name = row.F238
session.add(dept)
session.flush()
def add_replace_departments(self, session, batch):
for row in batch.provide_rows():
q = session.query(rattail.Department)
q = q.filter_by(number=row.F03)
if q.count():
prods = session.query(rattail.Product)
prods = prods.filter_by(department_uuid=q.first().uuid)
if prods.count():
prods.update(dict(department_uuid=None), synchronize_session='fetch')
q.delete(synchronize_session=False)
dept = rattail.Department()
dept.number = row.F03
dept.name = row.F238
session.add(dept)
session.flush()
def add_products(self, session, batch):
q = session.query(rattail.Department)
depts = {}
for dept in q:
depts[dept.number] = dept
q = session.query(rattail.Brand)
brands = {}
for brand in q:
brands[brand.name] = brand
for row in batch.provide_rows():
dept = None
if row.F03:
if row.F03 in depts:
dept = depts[row.F03]
else:
dept = rattail.Department(number=row.F03)
session.add(dept)
session.flush()
depts[dept.number] = dept
brand = None
if row.F155:
if row.F155 in brands:
brand = brands[row.F155]
else:
brand = rattail.Brand(name=row.F155)
session.add(brand)
session.flush()
brands[brand.name] = brand
prod = rattail.Product()
prod.upc = row.F01
prod.description = row.F02
prod.size = row.F22
prod.department = dept
prod.brand = brand
session.add(prod)
session.flush()
def add_replace_products(self, session, batch):
q = session.query(rattail.Department)
depts = {}
for dept in q:
depts[dept.number] = dept
q = session.query(rattail.Brand)
brands = {}
for brand in q:
brands[brand.name] = brand
products = session.query(rattail.Product)
for row in batch.provide_rows():
dept = None
if row.F03:
if row.F03 in depts:
dept = depts[row.F03]
else:
dept = rattail.Department(number=row.F03)
session.add(dept)
session.flush()
depts[dept.number] = dept
brand = None
if row.F155:
if row.F155 in brands:
brand = brands[row.F155]
else:
brand = rattail.Brand(name=row.F155)
session.add(brand)
session.flush()
brands[brand.name] = brand
q = products.filter_by(upc=row.F01)
if q.count():
q.delete(synchronize_session=False)
prod = rattail.Product()
prod.upc = row.F01
prod.description = row.F02
prod.size = row.F22
prod.department = dept
prod.brand = brand
session.add(prod)
session.flush()
def change_departments(self, session, batch):
depts = session.query(rattail.Department)
for row in batch.provide_rows():
dept = depts.filter_by(number=row.F03).first()
if dept:
dept.name = row.F238
session.flush()
def change_products(self, session, batch):
q = session.query(rattail.Department)
depts = {}
for dept in q:
depts[dept.number] = dept
products = session.query(rattail.Product)
for row in batch.provide_rows():
prod = products.filter_by(upc=row.F01).first()
if prod:
dept = None
if row.F03:
if row.F03 in depts:
dept = depts[row.F03]
else:
dept = rattail.Department(number=row.F03)
session.add(dept)
session.flush()
depts[dept.number] = dept
prod.dept = dept
prod.size = row.F22
session.flush()
def execute_batch(self, batch):
"""
Executes ``batch``, which should be a :class:`rattail.Batch` instance.
"""
session = object_session(batch)
if batch.action_type == rattail.BATCH_ADD:
if batch.dictionary.name == 'DEPT_DCT':
self.add_departments(session, batch)
return
if batch.dictionary.name == 'ITEM_DCT':
self.add_products(session, batch)
return
if batch.action_type == rattail.BATCH_ADD_REPLACE:
if batch.dictionary.name == 'DEPT_DCT':
return self.add_replace_departments(session, batch)
if batch.dictionary.name == 'ITEM_DCT':
return self.add_replace_products(session, batch)
if batch.action_type == rattail.BATCH_CHANGE:
if batch.dictionary.name == 'DEPT_DCT':
self.change_departments(session, batch)
return
if batch.dictionary.name == 'ITEM_DCT':
return self.change_products(session, batch)
if batch.action_type == rattail.BATCH_REMOVE:
if batch.dictionary.name == 'DEPT_DCT':
return self.remove_departments(session, batch)
if batch.dictionary.name == 'ITEM_DCT':
return self.remove_products(session, batch)
assert False, "FIXME"
def remove_departments(self, session, batch):
depts = session.query(rattail.Department)
products = session.query(rattail.Product)
for row in batch.provide_rows():
dept = depts.filter_by(number=row.F03).first()
if dept:
q = products.filter_by(department_uuid=dept.uuid)
if q.count():
q.update({'department_uuid': None}, synchronize_session=False)
session.delete(dept)
session.flush()
def remove_products(self, session, batch):
products = session.query(rattail.Product)
for row in batch.provide_rows():
prod = products.filter_by(upc=row.F01).first()
if prod:
session.delete(prod)
session.flush()
# def make_batch(source, elements, session, batch_id=None, **kwargs):
# """
# Create and return a new SIL-based :class:`rattail.Batch` instance.
# """
# if not batch_id:
# batch_id = next_batch_id(source, consume=True)
# kwargs['source'] = source
# kwargs['batch_id'] = batch_id
# kwargs['target'] = target
# kwargs['elements'] = elements
# kwargs.setdefault('sil_type', 'HM')
# kwargs.setdefault('action_type', rattail.BATCH_ADD_REPLACE)
# kwargs.setdefault('dictionary', rattail.BATCH_MAIN_ITEM)
# batch = rattail.Batch(**kwargs)
# session.add(batch)
# session.flush()
# batch.table.create()
# log.info("Created batch table: %s" % batch.table.name)
# return batch
@needs_session
def next_batch_id(session, source, consume=False):
"""
Returns the next available batch ID (as an integer) for the given
``source`` SIL ID.
If ``consume`` is ``True``, the "running" ID will be incremented so that
the next caller will receive a different ID.
"""
batch_id = edbob.get_setting('batch.next_id.%s' % source,
session=session)
if batch_id is None or not batch_id.isdigit():
batch_id = 1
else:
batch_id = int(batch_id)
while True:
q = session.query(rattail.Batch)
q = q.join((rattail.BatchTerminal,
rattail.BatchTerminal.uuid == rattail.Batch.source_uuid))
q = q.filter(and_(
rattail.BatchTerminal.sil_id == source,
rattail.Batch.batch_id == '%08u' % batch_id,
))
if not q.count():
break
batch_id += 1
if consume:
edbob.save_setting('batch.next_id.%s' % source, str(batch_id + 1),
session=session)
return batch_id
|