Files
storage_fresco/DB.py
2019-07-06 14:22:27 +00:00

1819 lines
59 KiB
Python

#!/opt/local/bin/python3.0
import sqlite3 as sqlite
#from pysqlite2 import dbapi2 as sqlite
from sys import exit
from datetime import datetime, timedelta
import time
from locations import *
from types import *
import codecs
import os
def connectdb (dbfile):
"""
Create connection to database
return DB Object
user gets information if failure
"""
print ("Verbindung zu %s herstellen" %dbfile)
try:
db = sqlite.connect (dbfile)
return db
except:
print ("Konnte DB Verbindung nicht herstellen")
exit (1)
class DB:
# Database Stuff
# --------------
def __init__ (self, dbfile, talogfile):
self.db = connectdb (dbfile)
self.talogfile = talogfile
## Mainmethods
def setloggingmethods (self, log, message):
self.log = log
self.message = message
def message (self, level, msg):
"""
Dummy Message if not overloaded
"""
dt = datetime.now ()
print ("DB-LOG %4d-%02d-%02d %02d:%02d:%02d.%06d:" %(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond)),
print msg
def log (self, msg):
"""
Dummy Logging if not overloaded
"""
dt = datetime.now ()
print ("DB-LOG %4d-%02d-%02d %02d:%02d:%02d.%06d: " %(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond)),
print msg
def executesql (self, dbstring, arguments = ()):
"""
Fuehre den uebergebenen SQL-Befehl aus und liefere ein Cursor-Objekt
zurueck.
"""
done = False
try_count = 0.0
while not done:
try:
cursor = self.db.cursor ()
cursor.execute (dbstring, arguments)
done = True
except sqlite.IntegrityError, msg:
print ("SQLITE Double Entry :\n " + dbstring)
print (" -Details: " + msg[0])
raise Warning
except sqlite.Error, msg:
print ("SQLITE Error SQL\n" + dbstring)
print (" -Details: " + msg[0])
print (" -Retry %f" % try_count)
if try_count > 10.0:
raise Warning
time.sleep (0.05)
try_count += 0.05
except sqlite.OperationalError, msg:
print ("SQLITE Operational Error:\n " + dbstring)
print (" -Details: " + msg[0])
print (" -Retry %f" % try_count)
if try_count > 10.0:
raise Warning
time.sleep (0.05)
try_count += 0.05
except sqlite.ProgrammingError, msg:
print ("SQLITE Invalid SQL\n" + dbstring)
print (" -Details: " + msg[0])
raise Warning
except Warning: #, msg:
done = True
pass
#Build Transaction Log
if (dbstring.find ('DELETE') >= 0) or\
(dbstring.find ('INSERT') >= 0) or\
(dbstring.find ('UPDATE') >= 0):
file = codecs.open (self.talogfile, "a", "utf-8")
dt = datetime.now ()
file.write (u"%4d-%02d-%02d %02d:%02d:%02d.%06d: " %(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond))
try:
file.write (dbstring + ";\n")
except:
try:
file.write (dbstring.decode ("utf-8") + ";\n")
except:
print ("jetzt woas i a nimmer")
file.close ()
self.db.commit ()
return cursor
def executesqlscript (self, dbstring):
"""
Fuehre den uebergebenen SQL-Befehl aus und liefere ein Cursor-Objekt
zurueck.
"""
try:
cursor = self.db.cursor ()
self.db.executescript (dbstring)
except OperationalError: #, msg:
print ("Datenbankausfuehrung fehlgeschlagen. Ausgeloest durch: " + dbstring)
raise Warning
except IntegrityError: #, msg:
print ("Doppelter Eintrag. Ausgeloest durch: " + dbstring)
raise Warning
except ProgrammingError: #, msg:
print ("Fehlerhaftes SQL. Ausgeloest durch: " + dbstring)
raise Warning
except Warning: #, msg:
pass
#Build Transaction Log
if (dbstring.find ('DELETE') >= 0) or\
(dbstring.find ('INSERT') >= 0) or\
(dbstring.find ('UPDATE') >= 0):
file = codecs.open (self.talogfile, "a", "utf-8")
dt = datetime.now ()
file.write (u"%4d-%02d-%02d %02d:%02d:%02d.%06d: " %(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond))
file.write (dbstring + ";\n")
file.close ()
self.db.commit ()
return cursor
# Storage - Physics
#------------------
## Physics
def getphysics (self):
"""
Return Dict of Physics
"""
try:
cursor = self.executesql ("SELECT * FROM Physics;")
except:
return None
res = cursor.fetchall ()
config = {}
for key, value in res:
config[key] = value
for i in range (int (config["Storages"])):
storage = config ["Storage%d" % i]
if storage[0] == 'C':
_x = int (config["X_%s" % storage])
_y = int (config["Y_%s" % storage])
l = []
for i in range (1, _x + 1):
l.append ([])
for j in range (1, _y +1):
name = "Z_%s_%d_%d" %(storage, i, j)
l[i-1].append (int (config[name]))
del config[name]
config["Z_%s" % storage] = l
return config
def getstoragedict (self, physics = {}):
"""
Return Dict of StorageNumbers
"""
if physics == {}:
physics = self.getphysics ()
storages = {}
for i in range (int (physics.get ("Storages", 0))):
if "Storage%d" %i in physics:
storages [physics["Storage%d" %i]] = i
return storages
def setphysics (self, key, value):
"""
Set value in Phyiscs
"""
try:
cursor = self.executesql ("UPDATE Physics SET v='%s' WHERE k='%s';" % (value, key))
except:
print ("Couldn't write Value into Physics")
raise Warning
def addphysics (self, key, value):
"""
Add value to Phyiscs
"""
try:
cursor = self.executesql ("INSERT INTO Physics (v, k) VALUES ('%s', '%s');" % (value, key))
except:
print ("Couldn't write Value into Physics")
raise Warning
def gettransportmatrix_dstbysrc (self):
"""
Return Dict of Transportmatrix
with possible Transports from Source
"""
try:
cursor = self.executesql ("SELECT src, dst, rfz, mode, prio FROM Transportmatrix order by prio;")
except:
return None
res = cursor.fetchall ()
dstbysrc = {}
for src, dst, rfz, mode, prio in res:
rfzOut = ''
if '_' in rfz:
rfzNr, rfzOut = rfz.split ('_')
else:
rfzNr = rfz
if src not in dstbysrc:
dstbysrc[src] = []
dstbysrc[src].append ((dst, int (rfzNr), rfzOut, mode, prio))
return dstbysrc
def gettransportmatrix_srcbydst (self):
"""
Return Dict of Transportmatrix
with possible Transports to Destinations
"""
try:
cursor = self.executesql ("SELECT src, dst, rfz, mode, prio FROM Transportmatrix order by prio;")
except:
return None
res = cursor.fetchall ()
srcbydst = {}
for src, dst, rfz, mode, prio in res:
rfzOut = ''
if '_' in rfz:
rfzNr, rfzOut = rfz.split ('_')
else:
rfzNr = rfz
if dst not in srcbydst:
srcbydst[dst] = []
srcbydst[dst].append ((src, int (rfzNr), rfzOut, mode, prio))
return srcbydst
def checktransportmatrix (self, physics = {}, dstbysrc = {}, storages = {}):
"""
Check Transport matrix
"""
for src in dstbysrc:
self.log ("checktransportmatrix Checking Destinations for Source %s" %src)
for dst, rfzNr, rfzOut, mode, prio in dstbysrc [src]:
if (rfzNr - 1) not in range (int (physics['RFZs'])):
self.log ("checktransportmatrix Transport to %s by RFZ%s%s with prio %d%s is not possible, RFZ is not defined" %\
(dst, rfzNr, rfzOut and ' Outfeed %s' % rfzOut or '' , prio, mode and ' Mode %s' %mode or ''))
raise Warning
if dst in storages:
self.log ("checktransportmatrix Possible Transport to %s by RFZ%s%s with prio %d%s" %\
(dst, rfzNr, rfzOut and ' Outfeed %s' % rfzOut or '' , prio, mode and ' Mode %s' %mode or ''))
elif dst[0] == 'O':
self.log ("checktransportmatrix Possible Transport to Outpoint %s by RFZ%s%s with prio %d%s"%\
(dst, rfzNr, rfzOut and ' Outfeed %s' % rfzOut or '' , prio, mode and ' Mode %s' %mode or ''))
else:
self.log ("checktransportmatrix Transport to %s by RFZ%s%s with prio %d%s is not possible, dst is not defined" %\
(dst, rfzNr, rfzOut and ' Outfeed %s' % rfzOut or '' , prio, mode and ' Mode %s' %mode or ''))
raise Warning
def geterrordstbyposition (self):
"""
Get Errordestinations from Lockedslots and Transportmatrix
"""
try:
cursor = self.executesql ("SELECT src, dst, rfz, mode, prio FROM Transportmatrix order by prio;")
except:
print ("Couldn't read Transportmatrix")
raise Warning
errordst = {}
tm = cursor.fetchall ()
physics = self.getphysics ()
storageids = self.getstoragedict (physics)
for storage in storageids:
#FixMe slot = self.finderrorslot (storage)
slot = None
if slot:
x, y = slot
self.message (3, "Found errorslot in storageid %s at x:%s y:%s" % (storage, x, y))
for src, dst, rfz, mode, prio in tm:
if storage == dst:
if 'RFZ%s' % rfz not in errordst:
errordst ['RFZ%s' % rfz] = (dst, x, y, rfz)
for src, dst, rfz, mode, prio in tm:
if mode == 'error' and src not in errordst:
self.message (3, "Added Errortransport from Transportmatrix for %s to %s" % (src, dst))
if src != 'RFZ%s' % rfz:
self.log ("Bad Errortransport Source:%s, RFZ%s" % (src, rfz))
raise Warning
errordst [src] = (dst, 0, 0, rfz)
return errordst
def checkphysics (self, config):
"""
Check Physical Data
"""
if "RFZs" not in config:
print ("Number of RFZs not defined")
raise Warning
if int (config["RFZs"]) not in range (1,5):
print ("Number of configured RFZs %d invalid" % int (config["RFZs"]))
raise Warning
if "Storages" not in config:
print ("Number of storages not defined")
raise Warning
cnt = int (config["Storages"])
print ("%d Storages defined" % cnt)
for i in range (cnt):
if "Storage%d" % i not in config:
print ("Storage%d is not defined" %i)
raise Warning
storage = config["Storage%d" % i]
if not "X_%s" % storage in config:
print ("X Dimension missing")
raise Warning
if int (config ["X_%s" % storage]) <= 0:
print ("X Dimension invalid")
raise Warning
if not "Y_%s" % storage in config:
print ("Y Dimension missing")
raise Warning
if int (config ["Y_%s" % storage]) <= 0:
print ("Y Dimension invalid")
raise Warning
print ("Storage%d is %s" % (i, storage))
if storage[0] in ['S', 'T']:
print ("Check Zones for Singleplace or Throughfeed shelf")
if not "ZONES_%s" % storage in config:
print ("ZONES not defined for Storage %s" % storage)
raise Warning
_zonestart = 1
for i in range (1, int (config["ZONES_%s" % storage]) + 1):
if not "ZONESTART_%s_%d" % (storage, i) in config:
print ("ZONESTART not defined for storage %s" % storage)
raise Warning
if int (config["ZONESTART_%s_%d" % (storage, i)]) not in range (_zonestart, int (config ["X_%s" % storage]) + 1):
print ("ZONESTART_%s_%d has illegal value" % (storage, i))
raise Warning
if not "XMid_%s_%d" % (storage, i) in config:
print ("XMid not defined for storage %s ZONE %s" % (storage, i))
raise Warning
if int (config["XMid_%s_%d" % (storage, i)]) not in range (_zonestart, int (config ["X_%s" % storage]) + 1):
print ("XMid out of Zone")
raise Warning
if not "YMid_%s_%d" % (storage, i) in config:
print ("YMid not defined for storage %s ZONE %s" % (storage, i))
raise Warning
if int (config["YMid_%s_%d" % (storage, i)]) not in range (1, int (config ["Y_%s" % storage]) + 1):
print ("YMid out of Zone")
raise Warning
_zonestart = int (config ["ZONESTART_%s_%d" % (storage, i)]) + 1
if storage[0] == 'S':
print ("Check Singleplace shelf configuration")
elif storage[0] == 'T':
print ("Check Throughfeed configuration")
if not "Z_%s" % storage in config:
print ("Z Dimension missing")
raise Warning
if int (["Z_%s" % storage]) <= 0:
print ("Z Dimension invalid")
raise Warning
elif storage[0] == 'C':
print ("Check Commisioning shelf configuration")
for x in range (int (config ["X_%s" % storage])):
for y in range (int (config ["Y_%s" % storage])):
if not "Z_%s" % storage in config:
print ("Z dimension missing")
raise Warning
if int (config["Z_%s" % storage][x][y]) <= 0:
print ("Z dimenstion invalid")
raise Warning
else:
print ("Storage is from invalid type %s" % storage)
raise Warning
return
#Old style Storage checks to be removed or rewritten
#BE - Puffer - EN - Pick
if "ZONES" in config:
_z = int (config["ZONES"])
print ("Type 3 found %s ZONES" %_z)
_last = 1
if _z < 1:
print ("Type 3 invalid zone count")
raise Warning
for i in range (1, _z + 1):
if "ZONESTART%d" %i in config:
_b = int (config["ZONESTART%d" %i])
if (i == 1) and (_b != 1):
print ("Type 3 found ZONESTART%d invalid %d " %(i, _b))
raise Warning
elif (i >1) and (not (_b > _last) or not (_b < config["X_PU"])):
print ("Type 3 found ZONESTART%d invalid two %d " %(i, _b))
raise Warning
else:
print ("Type 3 found ZONESTART%d missing" %i)
raise Warning
_last = _b
return
def getunusableslots (self, storage):
"""
returnt Dict of unusable slots of storage
"""
filter = ''
if storage !='':
filter = "WHERE id='%s'" % storage
try:
cursor = self.executesql ("SELECT id, x, y, reason FROM Lockedslots %s;" % filter)
except:
return None
ret = {}
for id, x, y, reason in cursor.fetchall ():
ret[(id, x, y)] = reason
return ret
def addboxtrace (self, boxnr, article, lotnr, lotnr2, pieces, x, y, z, logmsg):
"""
Add tracemsg for a Box
"""
try:
cursor = self.executesql ("INSERT INTO Trace (boxnr, article, lotnr, lotnr2, pieces, x, y, z, rfzts, action) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' , current_timestamp, '%s')"\
%(boxnr, article, lotnr, lotnr2, pieces, x, y, z, logmsg))
except:
print ("Couldnt Trace Box")
raise Warning
def getpufferslotusage (self, x, y):
"""
Liefert die Belegung eines Pufferschaechts zurueck
"""
try:
cursor = self.executesql ("SELECT COUNT (z) FROM Puffer WHERE x='%d' AND y='%d';" %(x, y))
except:
print ("Konnte Belegung nicht ermitteln")
return cursor.fetchone ()
def addincomingbox (self, source, boxnr, article, gtin, lotnr, lotnr2, duedate, pieces, deststorage, destination):
"""
Saves box in Inqueue
"""
try:
cursor = self.executesql ("INSERT INTO Inqueue (location, boxnr, article, gtin, lotnr, lotnr2, duedate, pieces, deststorage, destination) \
VALUES ('%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)" \
%(source, boxnr, article, gtin, lotnr, lotnr2, duedate, pieces, deststorage, destination))
except:
self.log ("Couldn't store box in Inqueue")
self.addboxtrace (boxnr, article, lotnr, lotnr2, pieces, '', '', '', "in Inqueue %s reserved with storage %s destination %s" %(source, deststorage, destination))
def getincomingbox (self, boxnr):
"""
Search for a box in Inqueue
"""
try:
cursor = self.executesql ("SELECT location, boxnr, article, gtin, lotnr, lotnr2, duedate, pieces, deststorage, destination FROM Inqueue WHERE boxnr='%d';" % (boxnr))
except:
print ("Couldn't find box in Inqueue")
raise Warning
return cursor.fetchall ()
def getinqueuesize (self, deststorage):
"""
Returns Size of Inqueue
"""
try:
cursor = self.executesql ("SELECT COUNT (boxnr) FROM Inqueue WHERE deststorage='%s';" % (deststorage))
except:
print ("Couldn't get size of Inqueue")
raise Warning
return cursor.fetchone ()[0]
def checkinqueueforarticle (self, queueid, article):
"""
Checks if artcle is in an Inqueue
"""
try:
cursor = self.executesql ("SELECT * from Inqueue WHERE id = '%s' AND article = '%s';" % (queueid, article))
except:
self.log ("Couldn't get info for article in Inqueue")
return cursor.fetchall ()
def reservebox (self, position, source, sx, sy, sz, boxnr, article, lotnr, lotnr2, duedate, pieces, storage, x, y, z):
"""
Reserves new box into storage
or Outqueue - (in this case z dim is not used, just for 'O0' Outqueues
"""
if storage[0] == 'O':
_table = 'Outqueue';
else:
_table = 'Storage';
try:
cursor = self.executesql ("INSERT INTO %s (id, boxnr, article, lotnr, lotnr2, duedate, pieces, x, y, z, rfzts) VALUES ('%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', 0) " \
% (_table, storage, boxnr, article, lotnr, lotnr2, duedate, pieces, x, y, z))
except:
print ("Couldn't write Box to i%s")
raise Warning
try:
cursor = self.executesql ("INSERT INTO Trace (boxnr, article, lotnr, lotnr2, pieces, x, y, z, rfzts, action) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' , current_timestamp, 'in %s reserved %s')"\
% (boxnr, article, lotnr, lotnr2, pieces, x, y, z, storage,''))
except:
print ("Couldn't trace Box")
# Create TAUF for transportation
self.createtransport (boxnr, position, source, sx, sy, sz, storage, x, y, z)
return
def setboxtimefillgap (self, storageid, setboxnr, boxts = ''):
"""
Set timestamp for reserved box in storage (id) and remove ghosts
"""
boxes = self.searchbox (setboxnr, storageid)
box = None
if boxes:
box = boxes [0]
if box:
id, boxnr, article, lotnr, lotnr2, duedate, pieces, x, y, z, rfzts = box
if int (z) > 1:
self.message (6, "Not 1st Box in slot looking for ghosts")
try:
cursor = self.executesql ("SELECT boxnr, article, lotnr, lotnr2, pieces, x, y, z FROM Storage WHERE id='%s' AND x='%s' AND y='%s' AND z<'%s' AND rfzts=0 "\
% (storageid, x, y, z))
except:
print ("Couldn't find any ghosts")
raise Warning
_ret = cursor.fetchall ()
z_vals = [j[6] for j in _ret]
z_vals.sort ()
z_vals.reverse ()
for i in _ret:
_iboxnr, _iarticle, _ilotnr, _ilotnr2, _ipieces, _ix, _iy, _iz = i
self.addboxtrace (_iboxnr, _iarticle, _ilotnr, _ilotnr2, _ipieces, _ix, _iy, _iz, "as Ghost removed from %s" % storageid)
self.message (6, "Deleting Transports and Inqueue for box %d" % int (_iboxnr))
try:
self.deleteincomingbox (int (_iboxnr))
except:
self.message (3 , "setboxtimefillgap couldn't delete Inqueue for Ghost")
try:
self.deletealltransports (int (_iboxnr))
except:
self.message (3 , "setboxtimefillgap couldn't delete Transport for Ghost")
for i in z_vals:
try:
cursor = self.executesql ("DELETE FROM Storage WHERE id='%s' AND x='%s' AND y='%s' AND z = '%s'"\
% (storageid, x, y, i))
except:
self.log ("Couldn't delete Ghosts")
raise Warning
try:
#ORDER BY statement only supported and needed by MySQL to prevent from Indexerror on coordinates
#cursor = self.executesql ("UPDATE %s SET z=z-1, rfzts=rfzts WHERE x='%s' AND y='%s' AND z>'%s' ORDER BY z" % (storageid, x, y, i))
#cursor = self.executesql ("UPDATE Storage SET z=z-1, rfzts=rfzts WHERE id='%s' AND x='%s' AND y='%s' AND z>'%s'" % (storageid, x, y, i))
cursor = self.executesqlscript ("""UPDATE Storage SET z = z + 100, rfzts = rfzts WHERE id ='%s' AND x = '%s' AND y = '%s' AND z >'%s';
UPDATE Storage SET z = z - 101, rfzts = rfzts WHERE id = '%s' AND x = '%s' AND y = '%s' AND z >= 100;"""\
% (storageid, x, y, i, storageid, x, y))
except:
self.log ("Couldn't close Gap after Ghost deletion")
raise Warning
if boxts != '':
#Try to use given Timestamp
try:
cursor = self.executesql ("UPDATE Storage SET rfzts = '%s' WHERE id = '%s' AND boxnr = '%d';"\
% (boxts, storageid, setboxnr))
except:
self.log ("Couldn't update box so use current Timestamp")
try:
cursor = self.executesql ("UPDATE Storage SET rfzts = current_timestamp WHERE id='%s' and boxnr='%d';" % (storageid, setboxnr))
except:
self.log ("Couldn't update box")
raise Warning
else:
try:
cursor = self.executesql ("UPDATE Storage SET rfzts = current_timestamp WHERE id='%s' and boxnr='%d';" % (storageid, setboxnr))
except:
self.log ("Couldn't update box")
raise Warning
try:
cursor = self.executesql ("INSERT INTO Trace (boxnr, article, lotnr, lotnr2, pieces, x, y, z, rfzts, action) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', current_timestamp, 'in %s inserted')"\
% (setboxnr, '', '', '', '', '', '', '', storageid))
except:
print ("Couldn't trace box insertion")
# Box deleteions
def deletebox (self, where, boxnr, queueid = ''):
"""
Delete box from several Tables (Queues)
doesn't update z - Value
"""
if where not in ("Inqueue", "Outqueue"):
print ("Unable to delete from Table %s" % where)
raise Warning
_cond = queueid and " AND id = '%s'" % queueid or ''
try:
cursor = self.executesql ("DELETE FROM %s WHERE boxnr = '%d'%s;" % (where, boxnr, _cond))
except:
print ("Couldn't delete box from %s" % where)
raise Warning
try:
cursor2 = self.executesql ("INSERT INTO Trace (boxnr, article, lotnr, lotnr2, pieces, x, y, z, rfzts, action) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' , current_timestamp, 'from %s %s deleted')"\
%(boxnr, '', '', '', '', '', '', '', where.replace("'",""), _cond.replace("'","")))
except:
print ("Couldn't trace box deletion from %s" % where)
def deleteincomingbox (self, boxnr):
"""
Deletes box from Inqueue
"""
return self.deletebox ("Inqueue", boxnr)
def deleteoutgoingbox (self, boxnr, queueid = ''):
"""
Deletes box from Outqueue
"""
return self.deletebox ("Outqueue", boxnr, queueid)
def removebox (self, storageid, delboxnr):
"""
removebox from a storage or other location Inqueue, Outqueue
and shift remaining boxes
returns z value of Box in case of Storage or ordered Outqueue
"""
if storageid == "Inqueue":
self.deleteincomingbox (delboxnr)
return None
else:
boxes = self.searchbox (delboxnr, storageid)
# If box cannot be found simply return
if not boxes:
return None
bsid, boxnr, article, lotnr, lotnr2, duedate, pieces, x, y, z, rfzts = boxes [0]
if storageid == 'Outqueue' and bsid[0:2] == 'OP':
#OP - Quees aren't in order so simply delete
self.deleteoutgoingbox (delboxnr)
table = (storageid == 'Outqueue') and 'Outqueue' or 'Storage'
tableid = (storageid == 'Outqueue') and bsid or storageid
try:
cursor = self.executesql ("DELETE FROM %s WHERE id = '%s' AND boxnr = '%d';" % (table, tableid, delboxnr))
except:
self.log ("Couldn't remove box from %s" % table)
raise Warning
#Singleplaceshelf no need to shift
if storageid[0] != 'S':
try:
#ORDER BY z statement only supported and needed by MySQL to prevent from Indexerror on coordinates
#cursor = self.executesql ("UPDATE %s SET z = z - %d, rfzts = rfzts WHERE id = '%s' AND x = '%s' AND y = '%s' AND z > '%s';" \
# % (table, storageid[0] in ['C', 'O'] and z or 1, tableid, x, y, z))
cursor = self.executesqlscript ("""UPDATE %s SET z = z + 100, rfzts = rfzts WHERE id = '%s' AND x = '%s' AND y = '%s' AND z > '%s';
UPDATE %s SET z = z - (100 + %d), rfzts = rfzts WHERE id = '%s' AND x = '%s' AND y = '%s' AND z >= 100;"""\
% (table, tableid, x, y, z, table, storageid[0] in ['C', 'O'] and z or 1, tableid, x, y))
except:
self.log ("Couldn't shift remaining boxes")
raise Warning
self.addboxtrace (delboxnr, article, lotnr, lotnr2, pieces, x, y, z, "from %s removed%s" %(table, (storageid[0] <> 'S') and ' and shifted remaining boxes' or ''))
return z
def createtransport (self, boxnr, position, src, sx, sy, sz, dst, dx, dy, dz, state = 'New'):
"""
Add Transport to DB
with optional state
"""
# FixMe check Position
try:
cursor = self.executesql ("INSERT INTO Transports (boxnr, position, src, src_x, src_y, src_z, dst, dst_x, dst_y, dst_z, state, ts) VALUES ('%d', '%s', '%s', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%s', current_timestamp);"\
% (boxnr, position, src, sx, sy, sz, dst, dx, dy, dz, state))
except:
self.log ("Couldn't write transport to DB")
self.log("INSERT INTO Transports (boxnr, position, src, src_x, src_y, src_z, dst, dst_x, dst_y, dst_z, state, ts) VALUES ('%d', '%s', '%s', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%s', current_timestamp);"\
% (boxnr, position, src, sx, sy, sz, dst, dx, dy, dz, state))
raise Warning
def gettransport (self, position, boxnr, state = ''):
"""
Get Transport for a box on a specific loation from DB
optional with an special state
disable filter for boxnr = -1
"""
_filter = position and "position = '%s'" % position or ''
_filter += (boxnr > -1) and "%sboxnr = '%d'" % (_filter and " AND " or '', boxnr) or ''
_filter += state and "%sstate ='%s'" % (_filter and " AND " or '', state) or ''
try:
cursor = self.executesql ("SELECT boxnr, position, src, src_x, src_y, src_z, dst, dst_x, dst_y, dst_z, state, ts FROM Transports WHERE %s;"\
% _filter)
except:
print ("Couldn't get Transport from DB")
raise Warning
if cursor.rowcount > 1:
print ("gettransport found multiple Transports")
raise Warning
return cursor.fetchone ()
def getexpressboxes (self):
"""
Liefere alle Kisten fuer Expressauslagerung
"""
try:
cursor = self.executesql ("SELECT kistennummer, artikelnummer, charge, gewicht, x, y, z, rzfts FROM Express")
except:
print ("Konnte kisten nicht aus Express holen")
return cursor.fetchall ()
## Transports
def getmovetransport (self, position, state = ''):
"""
Get 1st Move Transports for RFZ
"""
_filter = state and " AND state = '%s' " % state or ''
try:
cursor = self.executesql ("SELECT * FROM Transports WHERE position = '%s' %s ORDER BY ts" % (position, _filter))
except:
print ("Couldn't get Transports from DB")
raise Warning
for boxnr, pos, src, srcx, srcy, srcz, dst, dstx, dsty, dstz, state, ts in cursor.fetchall():
if src[0] != 'I' and 'Trigger' not in state:
return [boxnr, pos, src, srcx, srcy, srcz, dst, dstx, dsty, dstz, state, ts]
def getnewmovetransportcount (self, position):
"""
Count number of movetransports
"""
try:
cursor = self.executesql ("SELECT COUNT (position) FROM Transports WHERE position = '%s' AND state = 'New' AND src NOT LIKE 'I00_' ORDER BY ts" % position)
except:
self.log ("Couldn't count Movetransports")
raise Warning
return cursor.fetchone ()
def getmovetransportsentcount (self, position):
"""
Count number of sent movetransports
"""
try:
cursor = self.executesql ("SELECT COUNT (position) FROM Transports WHERE position = '%s' AND state = 'Sent' AND src NOT LIKE 'I00_' ORDER BY ts" % position)
except:
self.log ("Couldn't count Movetransports")
raise Warning
return cursor.fetchone ()
def getsenttransport (self, position, src, src_x, src_y):
"""
getting a sent Transport
"""
try:
cursor = self.executesql ("SELECT boxnr FROM Transports WHERE position = '%s' AND state = 'Sent' AND src = '%s' AND src_x = %d AND src_y = %d;" % (position, src, src_x, src_y))
except:
self. log ("Couldn't get Transports")
raise Warning
return cursor.fetchone ()
def setsenttransportnew (self, position, boxnr = 0):
"""
Change state of Transport
"""
_filter = boxnr and "AND boxnr = '%d'" % boxnr or ''
#Check filter Dummytransports
try:
cursor = self.executesql ("UPDATE Transports SET state = 'New' WHERE position = '%s' %s AND state = 'Sent';" % (position, _filter))
except:
self.log ("Couldn't change state of Transport")
raise Warning
if cursor.rowcount > 1:
self.log ("More Transports in DB")
return cursor.fetchall ()
def setsendingtransportnew (self, position):
"""
Change state of Transport
"""
try:
cursor = self.executesql ("UPDATE Transports SET state = 'New' WHERE position = '%s' AND state='Sending';" % (position))
except:
print ("Couldn't change state of Transport")
raise Warning
if cursor.rowcount > 1:
print ("More Transports in DB")
return cursor.fetchall ()
def settransport (self, position, boxnr, state):
"""
Change state of Transport
"""
try:
cursor = self.executesql ("UPDATE Transports SET state = '%s' WHERE position = '%s' AND boxnr = '%d';" % (state, position, boxnr))
except:
print ("Couldn't change state of Transport")
raise Warning
if cursor.rowcount > 1:
print ("More Transports in DB")
return cursor.fetchall ()
def settransportsending (self, position, boxnr):
"""
Mark Transport as Sending
"""
self.settransport (position, boxnr, 'Sending')
def settransportsent (self, position, boxnr):
"""
Mark Transport as Sent
"""
self.settransport (position, boxnr, 'Sent')
def settransportnew (self, position, boxnr):
"""
Mark Transport as new
"""
self.settransport (position, boxnr, 'New')
def settransportpos (self, position_old, boxnr, position_new):
"""
Change position of a new Transport
"""
try:
cursor = self.executesql ("UPDATE Transports SET position = '%s' WHERE position = '%s' AND boxnr = '%d' AND state = 'New';" \
% (position_new, position_old, boxnr))
except:
self.log ("Couldn't change positon of Transport")
raise Warning
if cursor.rowcount > 1:
self.log ("More Transports in DB")
return cursor.fetchall ()
def deletetransport (self, position, boxnr):
"""
Delete Transport
"""
try:
cursor = self.executesql ("DELETE FROM Transports WHERE position = '%s' AND boxnr = '%d'" % (position, boxnr))
except:
print ("Couldn't delete Transport")
raise Warning
return cursor.fetchall ()
def deletealltransports (self, boxnr):
"""
Delete Transport
"""
try:
cursor = self.executesql ("SELECT boxnr, position, src, src_x, src_y, src_z, dst, dst_x, dst_y, dst_z, state, ts FROM Transports WHERE boxnr = '%d';" % boxnr)
except:
self.log ("Couldn't find Transports in delete all Transports")
for transport in cursor.fetchall ():
tboxnr, position, src, src_x, src_y, src_z, dst, dst_x, dst_y, dst_z, state, ts = transport
self.addboxtrace (boxnr, '', '', '', '', '', '', '', "Transport to %s x:%s y:%s z:%s by %s with state %s deleted by deleteallboxes"\
% (dst, dst_x, dst_y, dst_z, position, state))
try:
cursor = self.executesql ("DELETE FROM Transports WHERE boxnr = '%d';" % boxnr)
except:
self.log ("Couldn't delete all Transports")
raise Warning
return cursor.fetchall ()
def deletetaufbysrc (self, position, src, src_x, src_y):
"""
Delete Transports by source
"""
try:
cursor = self.executesql ("DELETE FROM Transports WHERE position = '%s' AND src = '%s' AND src_x = '%d' AND src_y = '%d'" \
% (position, src, src_x, src_y))
except:
self.log ("Couldn't delete tranports by source")
raise Warning
return cursor.fetchall ()
def getboxesslot (self, storageid, x, y, justreserved = 0):
"""
Get boxes (in raising Order) from a Storage slot
"""
_filter = justreserved and ' AND rfzts = 0' or ''
try:
cursor = self.executesql ("SELECT id, boxnr, article, lotnr, lotnr2, duedate, pieces, x, y, z, rfzts FROM Storage WHERE id = '%s' and x = %d AND y = %d%s ORDER BY z;" % (storageid, x, y, _filter))
except:
self.log ("Couldn't get boxes from Slot")
return None
return cursor.fetchall ()
def getboxbycoordinates (self, storageid, x, y, z):
"""
Returns a Box by its coordinates
"""
try:
cursor = self.executesql ("SELECT id, boxnr, article, lotnr, lotnr2, pieces, x, y, z, rfzts FROM Storage WHERE id = '%s' AND x = '%d' AND y = '%d' AND z = '%d';"\
% (storageid, x, y, z))
except:
print ("Couldn't get box with coordinates")
raise Warning
return cursor.fetchone ()
def searchbox (self, boxnr, id = '', excl = 0):
"""
Search for a box in Storage and Filter on id (optional exclusive search) if given
"""
if id in ['Inqueue']:
print ("Inqueue not in searchbox implemented")
raise Warning
elif id in ['Outqueue']:
_where = id
_filter = ''
else:
_where = 'Storage'
_comparator = excl and '<>' or '='
_operator = excl and 'AND ' or 'OR '
_filter = id and "AND (" or ''
if id != '':
if type (id) == ListType:
for item in id:
_filter += "id%s'%s' %s" %(_comparator, item, _operator)
_filter = _filter [:-len(_operator)]
else:
_filter += "id%s'%s'" %(_comparator, id)
_filter += id and ")" or ''
try:
cursor = self.executesql ("SELECT id, boxnr, article, lotnr, lotnr2, duedate, pieces, x, y, z, rfzts FROM %s WHERE boxnr='%d' %s;" % (_where, boxnr, _filter))
except:
print ("Couldn't find box")
raise Warning
return cursor.fetchall ()
def findarticle (self, storage, article):
"""
Finds article in a storage
"""
try:
cursor = self.executesql ("SELECT id, boxnr, article, lotnr, lotnr2, duedate, pieces, x, y, z, rfzts FROM Storage WHERE id='%s' AND article='%s'" % (storage, article))
except:
print ("Couldn't get Articles")
raise Warning
return cursor.fetchall ()
def usedstorageslots (self, storage):
"""
Returns all used slots (X,Y) from storage
"""
try:
cursor = self.executesql ("SELECT DISTINCT x,y FROM Storage where id='%s'" % storage)
except:
print ("Couldn't get used slots in storage")
raise Warning
return cursor.fetchall ()
def getfilllevel (self, storage):
"""
Returns Dict of x,y with fillevels of storage
"""
try:
cursor = self.executesql ("SELECT x, y, COUNT(z) FROM Storage WHERE id='%s' GROUP BY x, y;" % storage)
except:
print ("Couldn't get Fillevels")
raise Warning
res = cursor.fetchall ()
ret = {}
for i in res:
ret[(i[0], i[1])] = i[2]
return ret
def placeinthroughfeed (self, storage, artnr, zone, params):
"""
Search for new Place in given Throughfeed shelf
returns (0, 0, 0) if no place
in case of Storagetype "T" None is returned if article isn't in storage yet
"""
maxlen = int (params['Z_%s' % storage])
zones = int (params['ZONES_%s' % storage])
xstart = int (params['ZONESTART_%s_%d' % (storage, zone)])
if zone == zones:
xend = int (params['X_%s' % storage]) + 1
else:
xend = int (params['ZONESTART%d' %(destination + 1)])
if '%s_Managed' % storage in params:
self.message (6, "placeinthroughfeed for Managed Througfeed shelf %s" % storage)
if storage[0] == 'T':
_filter = ''
try:
cursor = self.executesql ("SELECT DISTINCT x,y FROM storage WHERE id ='%s' AND x >= %d AND x < %d AND article ='%s'%s;" \
% (storage, xstart, xend, artnr, _filter))
except:
print ("Could't get used slots of article from Database ")
raise Warning
articleslots = cursor.fetchall ()
allslotcount = len (articleslots)
if not allslotcount >= 1:
#article is not in puffer
return None
#look for slot with newest box and check if its partial used
try:
cursor = self.executesql ("SELECT x, y, MAX(z) as usage, MAX(rfzts) as age FROM storage WHERE id ='%s' AND x >= %d AND x < %d AND article='%s' %s GROUP BY x,y ORDER BY age, usage;" \
% (storage, xstart, xend, artnr, _filter))
except:
print ("Could't get slotusage of article from Database ")
raise Warning
# Quickly exit if no free slot at all
slotusage = list (cursor.fetchall ())
if not len (slotusage) >=1:
self.message (6, "placeinthroughfeed No Slot for Article")
return (0, 0, 0)
#Use 1st slot
sx, sy, susage, smaxts = slotusage [0]
if smaxts:
#already boxes inserted in slot
if allslotcount == 1:
#Just one slot so refill it
if int (susage) < maxlen:
return sx, sy, susage + 1
else:
self.message (6, "placeinthroughfeed 1 existing Slot for Article is full")
return (0, 0, 0)
else:
#More slots so just add boxes to oldest slot - no refill
sx, sy, susage, smaxts = slotusage [-1]
if int (susage) < maxlen:
return sx, sy, susage + 1
else:
self.message (6, "placeinthroughfeed All existing Slots for Article are full")
return (0, 0, 0)
else:
#just reservations
if int (susage) < maxlen:
return sx, sy, susage + 1
else:
if allslotcount == 1:
self.message (6, "placeinthroughfeed All existing Slots with just reservations for Article are full")
return (0, 0, 0)
else:
#More slots so just add boxes to oldest slot - no refill
sx, sy, susage, smaxts = slotusage [-1]
if int (susage) < maxlen:
return sx, sy, susage + 1
else:
self.message (6, "placeinthroughfeed even the old Slots for Article are full")
return (0, 0, 0)
def placeinmanaged (self, storage, article, maxlen):
"""
Search next free Place for given article in Managed shelf
Return (0, 0, 0) if no place
"""
try:
cursor = self.executesql ("SELECT DISTINCT x,y FROM Slotbase WHERE id = '%s' AND article = '%s'" % (storage, article))
except:
print ("Couldn't get Base")
raise Warning
slots = cursor.fetchall ()
if not len (slots) >= 1:
return None
try:
cursor = self.executesql ("SELECT x, y, MAX(z), rfzts FROM Storage WHERE id = '%s' AND article = '%s' GROUP BY x,y ORDER BY z DESC, rfzts" % (storage, article))
except:
print ("Couldn't get Usage")
raise Warning
unusable = self.getunusableslots (storage)
l = list (cursor.fetchall ())
used = {}
for i in l:
used [(i[0], i[1])] = (i[2], i[3])
for i in slots:
if i in used:
self.message (3, "Slot is Filled to level %d of %d" %(used[i][0], int ((storage[0] == 'C') and maxlen[int (i[0]) - 1][int (i[1] - 1)] or maxlen)))
if int (used[i][0]) >= int ((storage[0] == 'C') and maxlen[int (i[0]) - 1][int (i[1] - 1)] or maxlen):
continue
else:
z = used[i][0] + 1
else:
#so ther noboxes in the slot
z = 1
# Slot it blocked for some reason
if (storage, i[0], i[1]) in unusable:
print ("Not using slot: " + str ((i[0], i[1])) + " because " + str (unusable[(i[0], i[1])]))
continue
return i[0], i[1], z
# No suitable free slot
return (0,0,0)
def getslotbase (self, storage):
"""
Returns slotbase of a storage
"""
try:
cursor = self.executesql ("SELECT x, y, article FROM Slotbase WHERE id='%s';" % storage)
except:
print ("Couldn't read slotbase from DB")
raise Warning
ret = {}
for i in cursor.fetchall ():
ret[(i[0], i[1])] = i[2]
return ret
def getslotbasearticles (self, storage):
"""
Returns articles set in slotbase
"""
try:
cursor = self.executesql ("SELECT DISTINCT article FROM Slotbase WHERE id='%s';" % storage)
except:
self.log ("Couldn't get articles in slotbase")
ret = []
for i in cursor.fetchall ():
ret.append (i[0])
return ret
def getarticlemaster (self):
"""
Returns articlemaster data for article
FiXMe for masterapplication
('article') : ['caption', 'ammountunit','normweight', 'weightunit', 'normammount', 'RLZ', 'zone', 'weightcheck', 'lottype'],
'12345' : ['Testartikel', 'ST','1.0', 'KG', '1', '1', '1', '0', '0'],
'23456' : ['Testartikel2', 'ST','1.0', 'KG', '1', '1', '1', '0', '0']}
"""
try:
cursor = self.executesql ("SELECT article, caption, gtin, normammount, minammount, zone, dest FROM Articlemaster;")
except:
self.log ("Couldn't read articlemaster")
a = {}
for row in cursor.fetchall ():
article, caption, gtin, normammount, minammount, zone, dest = row
a [article] = [caption, gtin, normammount, minammount, zone, dest]
return a
##Orders
def addorder (self, orderid, customer_name, customer_address, deliverydate, state = 'New', destination = '', prio = 0):
"""
Adds new order into Database
"""
try:
cursor = self.executesql (u"INSERT INTO Orders (id, customer_name, customer_address, deliverydate, state, destination, prio) VALUES (%d, '%s', '%s', '%s', '%s', '%s', %s);" \
% (orderid, customer_name, customer_address, deliverydate, state, destination, prio))
except sqlite.Error, msg:
self.log ("Couldn't add Order %d to Database %s" % (orderid, msg))
def searchorder (self, id = 0, destination = '', state = ''):
"""
Returns Orders optional filterd by id, destination, state
"""
_filter = ''
if id:
_filter += (_filter and " AND " or "") + "id = %d" % id
if destination:
_filter += (_filter and " AND " or "") + "destination = '%s'" % destination
if state:
_filter += (_filter and " AND " or "") + "state = '%s'" % state
try:
cursor = self.executesql ("SELECT id, state, destination from Orders %s ORDER by prio;" % (_filter and 'WHERE %s' % _filter or ''))
except:
self.message (3, "Couldn't get Orders with filterstring '%s'" % (_filter and 'WHERE %s' % _filter or ''))
return cursor.fetchall ()
def getoldorders (self):
"""
Returns Done / Deleted Orders older than 4 Days
"""
try:
cursor = self.executesql ("SELECT id, deliverydate, state from Orders WHERE state IN ('Done', 'Deleted', 'Paused');")
except:
self.log ("Couldn't get Orders")
raise Warning
timebarrier = datetime.now () - timedelta (4)
border = timebarrier.year * 10000 + timebarrier.month * 100 + timebarrier.day
ret = []
for i in cursor.fetchall ():
orderid, ddate, state = i
try:
if int (ddate) < border:
ret.append (i)
except:
self.log ("Oldorder Deliverydate error")
return ret
def deleteorder (self, orderid):
"""
Deletes an Order by its Id
and its Orderlines
"""
try:
cursor = self.executesql ("DELETE FROM Orderlines WHERE orderid = '%d';" % orderid)
except:
self.log ("Couldn't delete Orderlines of order")
try:
cursor = self.executesql ("DELETE FROM Orders WHERE id = '%d';" % orderid)
except:
self.log ("Couldn't delete Order")
def setorderstate (self, orderid, state = 'Active'):
"""
Set State of an Order
"""
try:
cursor = self.executesql ("UPDATE Orders SET state='%s' WHERE id=%d;" % (state, orderid))
except:
self.log ("Couldn't update Order %d" % orderid)
def addorderline (self, orderid, article, caption, amount, amount_unit, weight, weight_unit, state = 'New'):
"""
Adds now orderline into Database
"""
try:
cursor = self.executesql ("INSERT INTO Orderlines (orderid, article, caption, amount, amount_unit, amount_delivered, weight, weight_unit, weight_delivered, state) VALUES (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');" \
% (orderid, article, caption, amount, amount_unit, '0.0', weight, weight_unit, '0.0', state))
except:
self.log ("Couldn't add Orderline to Order %d with article %d" % (orderid, article))
def searchorderline (self, orderid = 0, state = ''):
"""
Returns Orderline optional filterd by id, state
"""
_filter = ''
if state:
_filter += (_filter and " AND " or "") + "state = '%s'" % state
try:
cursor = self.executesql ("SELECT id, article, amount, amount_unit, amount_delivered, weight, weight_unit, weight_delivered, state from Orderlines WHERE orderid = %d %s;" \
% (orderid, (_filter and 'AND %s' % _filter or '')))
except:
self.message (3, "Couldn't get Orderlines to Order %d with filterstring '%s'" % (orderid, (_filter and 'AND %s' % _filter or '')))
return cursor.fetchall ()
def setorderlinestate (self, orderlineid, state = 'Active'):
"""
Set State of an Orderline
"""
try:
cursor = self.executesql ("UPDATE Orderlines SET state='%s' WHERE id=%d;" % (state, orderlineid))
except:
self.log ("Couldn't update Orderline %d" % orderlineid)
def orderlineaddweight (self, orderlineid, weight):
"""
Add Weight to an orderline
only if weightunit == kg !!!
"""
try:
cursor = self.executesql ("UPDATE Orderlines SET weight_delivered = weight_delivered + '%s' WHERE id = %d;"\
% (weight, orderlineid));
except:
self.log ("Couldn't add weight to Orderline %d" % orderlineid)
##Express
def addexpressjob (self, article):
"""
Add Expressjob for 1 Box
"""
try:
cursor = self.executesql ("INSERT INTO Expressjobs (source, state, customer, packlist, article, boxes, created) VALUES ('T001', 'New', 'Auto', '1', '%s', '1', current_timestamp)"\
%(article))
except:
print ("Couldnt add Expressjob")
raise Warning
def delexpressjob (self, id):
"""
Deletes a Expressjob
"""
try:
cursor = self.executesql ("DELETE FROM Expressjobs WHERE id = %d ;" %id);
except:
self.log ("Couldn't delete Expressjob")
raise Warning
return cursor.fetchall ()
def deldonexpressjobs (self):
"""
Deletes finished expressjobs
"""
try:
cursor = self.executesql ("DELETE FROM Expressjobs WHERE state = 'Done' ;");
except:
self.log ("Couldn't delete done Expressjobs")
raise Warning
return cursor.fetchall ()
def findexpressjob (self, id):
"""
Returns a Expressjob
"""
try:
cursor = self.executesql ("SELECT id, source, state, customer, packlist, article, boxes, boxes_delivered, created, info FROM Expressjobs WHERE id = %d ;" %id);
except:
self.log ("Couldn't find Expressjob")
raise Warning
return cursor.fetchone ()
def findnewexpressjobs (self):
"""
Returns new Expressjobs
"""
try:
cursor = self.executesql ("SELECT id, source, state, customer, packlist, article, boxes, boxes_delivered, created, info FROM Expressjobs WHERE state = 'New' ORDER BY created;");
except:
self.log ("Couldn't find new Expressjobs")
raise Warning
return cursor.fetchall ()
def findactiveexpressjob (self):
"""
Returns active Expressjob
"""
try:
cursor = self.executesql ("SELECT id, source, state, customer, packlist, article, boxes, boxes_delivered, created, info FROM Expressjobs WHERE state = 'Act';");
except:
self.log ("Couldn't find active expressjob")
raise Warning
return cursor.fetchone ()
def closeexpressjob (self, id, info):
"""
Closes an Expressjob
"""
try:
cursor = self.executesql ("UPDATE Expressjobs set state='Done', info ='%s' WHERE id=%d" %(info, id))
except:
self.log ("Couldn't close Expressjob")
return cursor.fetchone ()
def activateexpressjob (self, id):
"""
Activates an Expressjob
"""
try:
cursor = self.executesql ("UPDATE Expressjobs SET state='Act' WHERE id=%d" %id)
except:
self.log ("Couldn't activate Expressjob")
raise Warning
return cursor.fetchone ()
def expressjobaddbox (self, id):
"""
Increment Nr of boxes at expressjob
"""
try:
cursor = self.executesql ("UPDATE Expressjobs set boxes_delivered = boxes_delivered + 1 WHERE id=%d" %(id))
except:
self.log ("Couldn't add box to Expressjob")
raise Warning
return cursor.fetchone ()
def expresslogaddbox (self, expressjobid, boxnr, lotnr, lotnr2, pieces):
"""
Add tracemsg for a Box
"""
try:
cursor = self.executesql ("INSERT INTO Expresslog (expressjob, boxnr, lotnr, lotnr2, pieces, rfzts) VALUES ('%s', '%s', '%s', '%s', '%s', current_timestamp)"\
%(expressjobid, boxnr, lotnr, lotnr2, pieces))
except:
print ("Couldnt add Box to Expresslog")
raise Warning
def expressloggetdata (self, expressjobid):
"""
Add tracemsg for a Box
"""
try:
cursor = self.executesql ("SELECT boxnr, lotnr, lotnr2, pieces, rfzts FROM Expresslog WHERE expressjob = '%s'"\
%(expressjobid))
except:
print ("Couldnt get Expresslog")
raise Warning
return cursor.fetchall ()
##Compressionjobs
def addcompressionjob (self, article):
"""
Fuegt einen Komprimierjob hinzu
"""
try:
cursor = self.executesql ("INSERT INTO Compressionjobs (position, state, artikelnummer, created, info) VALUES ('TBC', 'New', '%s', current_timestamp, '');" \
%(article))
except:
print ("Konnte Komprimierjob nicht einfuegen")
raise Warning
return cursor.fetchall ()
def delcompressionjob (self, id):
"""
Loescht einen Komprimierjob
"""
try:
cursor = self.executesql ("DELETE FROM Compressionjobs WHERE id = %d ;" %id);
except:
print ("Konnte Komprimierjob nicht loeschen")
raise Warning
return cursor.fetchall ()
def closecompressionjob (self, id, info):
"""
Setzt einen Komprimierjob auf erledigt
"""
if not self.findcompressionjob (id):
print ("Komprimierjob nicht vorhanden")
return
try:
cursor = self.executesql ("UPDATE Compressionjobs set state='Done', info='%s' WHERE id=%d" %(info, id))
except:
print ("Konnte Komprimierjob nicht Updaten")
return cursor.fetchone ()
def assigncompressionjob (self, id, position):
"""
Ordnet einem Komprimierjob ein RFZ zu
"""
if position not in ['RFZ2', 'RFZ3']:
print ("Falsche position bei Komprimierjob assign angegeben")
raise Warning
if not self.findcompressionjob (id):
print ("Komprimierjob nicht vorhanden")
return
try:
cursor = self.executesql ("UPDATE Compressionjobs set position='%s', state='Act' WHERE id=%d" %(position, id))
except:
print ("Konnte Komprimierjob nich updaten")
raise Warning
return cursor.fetchone ()
def findcompressionjob (self, id):
"""
Liefert einen Komprimierjob
"""
try:
cursor = self.executesql ("SELECT position, state, artikelnummer, created, info FROM Compressionjobs WHERE id = %d ;" %id);
except:
print ("Konnte Komprimierjob nicht finden")
raise Warning
return cursor.fetchall ()
def findnewcompressionjobs (self):
"""
Liefert neue Komprimierjobs
"""
try:
cursor = self.executesql ("SELECT id, position, state, artikelnummer, created FROM Compressionjobs WHERE state = 'New' ORDER BY created;");
except:
print ("Konnte Komprimierjobs nicht finden")
raise Warning
return cursor.fetchall ()
##es
def addesmovejob (self, article, sourcex, sourcey):
"""
Adds an Singleplace Transfer
"""
try:
cursor = self.executesql ("INSERT INTO singlemovejobs (position, state, artikelnummer, src_idi, sourcex, sourcey, created, info) VALUES ('TBC', 'New', '%s', 'T001', '%d', '%d', current_timestamp, '');" \
%(article, sourcex, sourcey))
except:
print ("Couldn't insert Singleplace Transfer")
raise Warning
return cursor.fetchall ()
def delesmovejob (self, id):
"""
Deletes an Singleplace Transfer
"""
try:
cursor = self.executesql ("DELETE FROM singlemovejobs WHERE id = %d ;" %id);
except:
print ("Coulden't delete Singleplace Transfer")
raise Warning
return cursor.fetchall ()
def closeesmovejob (self, id, info):
"""
Sets an Singleplace Transfer done
"""
if not self.findesmovejob (id):
print ("Singleplacetransfer doesn't exist")
return
try:
cursor = self.executesql ("UPDATE singlemovejobs set state='Done', info='%s' WHERE id=%d" %(info, id))
except:
print ("Couldn't close singleplacetransfer")
return cursor.fetchone ()
def assignesmovejob (self, id, position):
"""
Assigns Singleplacetransfer to an RBG
"""
if position not in ['RFZ2']:
print ("Bad Position for Singleplacetransfer")
raise Warning
if not self.findesmovejob (id):
print ("Singleplacetransfer doesn't exist")
return
try:
cursor = self.executesql ("UPDATE singlemovejobs set position='%s', state='Act' WHERE id=%d" %(position, id))
except:
print ("Couldn't assign Singleplacetransfer")
raise Warning
return cursor.fetchone ()
def findesmovejob (self, id):
"""
Return a Singleplacetransfer
"""
try:
cursor = self.executesql ("SELECT position, state, artikelnummer, src_id, sourcex, sourcey, created, info FROM singlemovejobs WHERE id = %d ;" %id);
except:
print ("Couldn't find Singleplacetransfer")
raise Warning
return cursor.fetchall ()
def findnewesmovejobs (self):
"""
Return new Singleplacetransfers
"""
try:
cursor = self.executesql ("SELECT id, position, state, artikelnummer, src_id, sourcex, sourcey, created FROM singlemovejobs WHERE state = 'New' ORDER BY created;");
except:
print ("Couldn't find Singleplacetransfer")
raise Warning
return cursor.fetchall ()
def testta (self):
"""
Test Transaction
"""
try:
cursor = self.executesqlscript ("""update storage set z=z+100 where x=17 and y=7 and z>=1 and id='T001';
update storage set z=z-101 where x=17 and y=7 and z>=1 and id='T001';""")
except:
print ("TA Failed")
raise Warning
if __name__ == "__main__":
conn = DB ('/opt/data/storage.sqlite', '/tmp/storagetest_talog.sql')
print conn.getinqueuesize ('T001')
"""
conn.addexpressjob ('179')
exjob = conn.findexpressjob (23)
print exjob
explog = conn.expressloggetdata (23)
print explog
conn.expresslogaddbox (75, 123, '01219', 01234, 81)
for oldorder in conn.getoldorders ():
print oldorder
_orderid, _deldate, _state = oldorder
conn.deleteorder (int (_orderid))
print conn.findnewesmovejobs ()
print ("\n--Throughfeedslots--")
if ret: print "1", ret
if ret: print "1", ret
print ("\n--Unusable Slots--")
print conn.getunusableslots ('')
print ("\n--Outqueuesizes--")
print conn.getoutqueuesize ('O001')
print conn.getoutqueuesize ('O002')
print conn.getoutqueuesize ('O003')
print conn.getoutqueuesize ('O004')
print ("\n--GetTransport--")
print conn.gettransport ('', -1, state = 'Trigger-1234')
print conn.gettransport ('RFZ2', 1004264)
print conn.gettransport ('RFZ2', -1, state = 'Trigger-1234')
print ("\n--Searchbox--")
print conn.searchbox (1007144)
print conn.searchbox (1000472, 'T001')
print conn.searchbox (1000472, 'T002')
print conn.searchbox (1000472, ['T001', 'T002'])
print conn.searchbox (1000472, 'T001', excl = 1)
print conn.searchbox (1000472, 'T002', excl = 1)
print conn.searchbox (1000472, ['T002', 'S001'], excl = 1)
print ("\n--Searchorder--")
print conn.searchorder (id = 0, destination = '', state = '')
print conn.searchorder (id = 0, destination = '', state = 'New')
print conn.searchorder (id = 0, destination = '', state = 'Active')
print conn.searchorder (id = 0, destination = '', state = 'Paused')
print conn.searchorder (id = 1, destination = '', state = '')
print ("\n--Serachorderline--")
print conn.searchorderline (orderid = 1, state = '')
print conn.searchorderline (orderid = 80185505, state = 'New')
print ("\n--Transportmatrix--")
dstbysrc = conn.gettransportmatrix_dstbysrc ()
print ("Sources")
print dstbysrc.keys ()
print dstbysrc
srcbydst = conn.gettransportmatrix_srcbydst ()
print ("Destinations")
print srcbydst.keys ()
print srcbydst
physics = conn.getphysics ()
print ("\n--Pyhsics--")
print (physics)
print ("\n--Check-Pyhsics--")
#print (conn.checkphysics (physics))
print ("\n--Storages--")
storages = conn.getstoragedict ()
print storages
#conn.checktransportmatrix (physics, dstbysrc, storages)
print ("\n--Errordestinations by Src--")
print conn.geterrordstbyposition ()
print ("\n--Articlebase--")
print conn.getarticlemaster ()
print ("\--Transports--")
print conn.getmovetransport ('RFZ2', state = 'Sent')
#print conn.gettaufumlagerrefeeddests ('RFZ2')
#boxes =conn.getboxespufferslot (30, 5)
#for cbknr, cbanr, cblot,cbweight, cbx, cby, cbz, cbrfzts in boxes:
# print cbrfzts
# if not cbrfzts:
# print "hallo"
#conn.reserveenespibox ('RFZ2', 'Puffer', '24', '05', '01', 57494, '8888868', '123', '23456', '37', '01', '01')
#conn.addesmovejob ('8888868', 24, 5)
#stamminfo = conn.getschachtstammarticle ('88888698')
#if stamminfo:
# stx, sty, stanr, stbez, stzone = stamminfo[0]
# fill = conn.getfilllevel ('Pick')
# stz = fill.get ((stx, sty), 0)
# print stz
#else:
# print "ned gfundn"
"""