本文整理匯總了Python中freppledb.common.models.Parameter.getValue方法的典型用法代碼示例。如果您正苦於以下問題:Python Parameter.getValue方法的具體用法?Python Parameter.getValue怎麽用?Python Parameter.getValue使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類freppledb.common.models.Parameter
的用法示例。
在下文中一共展示了Parameter.getValue方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: run
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def run(cls, database=DEFAULT_DB_ALIAS, **kwargs):
import frepple
# Determine log level
loglevel = int(Parameter.getValue('plan.loglevel', database, 0))
if cls.task and cls.task.user:
maxloglevel = cls.task.user.getMaxLoglevel(database)
if loglevel > maxloglevel:
loglevel = maxloglevel
# Propagate the operationplan status
frepple.solver_propagateStatus(
loglevel=loglevel
).solve()
# Update the feasibility flag of all operationplans
for oper in frepple.operations():
for opplan in oper.operationplans:
opplan.updateFeasible()
# Report the result
print ("Initial problems:")
probs = {}
for i in frepple.problems():
if i.name in probs:
probs[i.name] += 1
else:
probs[i.name] = 1
for i in sorted(probs.keys()):
print(" %s: %s" % (i, probs[i]))
示例2: createPlan
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def createPlan(database = DEFAULT_DB_ALIAS):
# Auxiliary functions for debugging
def debugResource(res,mode):
# if res.name != 'my favorite resource': return
print("=> Situation on resource", res.name)
for j in res.loadplans:
print("=> ", j.quantity, j.onhand, j.startdate, j.enddate, j.operation.name, j.operationplan.quantity, j.setup)
def debugDemand(dem,mode):
if dem.name == 'my favorite demand':
print("=> Starting to plan demand ", dem.name)
solver.loglevel = 2
else:
solver.loglevel = 0
# Create a solver where the plan type are defined by an environment variable
try: plantype = int(os.environ['FREPPLE_PLANTYPE'])
except: plantype = 1 # Default is a constrained plan
try: constraint = int(os.environ['FREPPLE_CONSTRAINT'])
except: constraint = 15 # Default is with all constraints enabled
solver = frepple.solver_mrp(name = "MRP", constraints = constraint,
plantype = plantype, loglevel=int(Parameter.getValue('plan.loglevel', database, 0))
#userexit_resource=debugResource,
#userexit_demand=debugDemand
)
print("Plan type: ", plantype)
print("Constraints: ", constraint)
solver.solve()
示例3: export_work_order
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def export_work_order(self, cursor):
if self.filteredexport:
filter_expression = 'and (%s) ' % Parameter.getValue('openbravo.filter_export_manufacturing_order', self.database, "")
else:
filter_expression = ""
try:
starttime = time()
if self.verbosity > 0:
print("Exporting work orders...")
cursor.execute('''
select operation.source, out_operationplan.quantity, startdate, enddate
from out_operationplan
inner join operation
on out_operationplan.operation = operation.name
and operation.type = 'routing'
where operation like 'Process%' %s ''' % filter_expression)
count = 0
body = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<ob:Openbravo xmlns:ob="http://www.openbravo.com">'
]
for i in cursor.fetchall():
# TODO generate documentno? <documentNo>10000000</documentNo>
body.append('''<ManufacturingWorkRequirement>
<organization id="%s" entity-name="Organization"/>
<active>true</active>
<processPlan id="%s" entity-name="ManufacturingProcessPlan"/>
<quantity>%s</quantity>
<startingDate>%s.0Z</startingDate>
<endingDate>%s.0Z</endingDate>
<closed>false</closed>
<insertProductsAndorPhases>true</insertProductsAndorPhases>
<includePhasesWhenInserting>true</includePhasesWhenInserting>
<processed>false</processed>
</ManufacturingWorkRequirement>
''' % (self.organization_id, i[0], i[1],
i[2].strftime("%Y-%m-%dT%H:%M:%S"), i[3].strftime("%Y-%m-%dT%H:%M:%S")
))
count += 1
if self.verbosity > 0 and count % 500 == 1:
print('.', end="")
if self.verbosity > 0:
print('')
body.append('</ob:Openbravo>')
post_data(
'\n'.join(body),
'/openbravo/ws/dal/ManufacturingWorkRequirement',
self.openbravo_host, self.openbravo_user, self.openbravo_password
)
if self.verbosity > 0:
print("Updated %d work orders in %.2f seconds" % (count, (time() - starttime)))
except Exception as e:
raise CommandError("Error updating work orders: %s" % e)
示例4: odoo_read
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def odoo_read(db=DEFAULT_DB_ALIAS):
'''
This function connects to a URL, authenticates itself using HTTP basic
authentication, and then reads data from the URL.
The data from the source must adhere to frePPLe's official XML schema,
as defined in the schema files bin/frepple.xsd and bin/frepple_core.xsd.
'''
odoo_user = Parameter.getValue("odoo.user", db)
if settings.OODO_PASSWORDS.get(db) == '':
odoo_password = Parameter.getValue("odoo.password", db)
else:
odoo_password = settings.OODO_PASSWORDS.get(db)
odoo_db = Parameter.getValue("odoo.db", db)
odoo_url = Parameter.getValue("odoo.url", db)
odoo_company = Parameter.getValue("odoo.company", db)
ok = True
if not odoo_user:
print("Missing or invalid parameter odoo.user")
ok = False
if not odoo_password:
print("Missing or invalid parameter odoo.password")
ok = False
if not odoo_db:
print("Missing or invalid parameter odoo.db")
ok = False
if not odoo_url:
print("Missing or invalid parameter odoo.url")
ok = False
if not odoo_company:
print("Missing or invalid parameter odoo.company")
ok = False
odoo_language = Parameter.getValue("odoo.language", db, 'en_US')
if not ok:
raise Exception("Odoo connector not configured correctly")
# Connect to the odoo URL to GET data
f = None
try:
request = Request("%sfrepple/xml/?%s" % (odoo_url, urlencode({
'database': odoo_db, 'language': odoo_language, 'company': odoo_company
})))
encoded = base64.encodestring(('%s:%s' % (odoo_user, odoo_password)).encode('utf-8'))[:-1]
request.add_header("Authorization", "Basic %s" % encoded.decode('ascii'))
f = urlopen(request)
except HTTPError as e:
print("Error connecting to odoo", e)
raise e
# Download and parse XML data
try:
frepple.readXMLdata(f.read().decode('utf-8'), False, False)
finally:
if f: f.close()
示例5: __init__
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def __init__(self, task, database=DEFAULT_DB_ALIAS, verbosity=0):
self.task = task
self.database = database
self.verbosity = verbosity
# Pick up configuration parameters
self.odoo_user = Parameter.getValue("odoo.user", self.database)
self.odoo_password = Parameter.getValue("odoo.password", self.database)
self.odoo_db = Parameter.getValue("odoo.db", self.database)
self.odoo_url = Parameter.getValue("odoo.url", self.database)
self.odoo_company = Parameter.getValue("odoo.company", self.database)
if not self.odoo_user:
raise CommandError("Missing or invalid parameter odoo.user")
if not self.odoo_password:
raise CommandError("Missing or invalid parameter odoo.password")
if not self.odoo_db:
raise CommandError("Missing or invalid parameter odoo.db")
if not self.odoo_url:
raise CommandError("Missing or invalid parameter odoo.url")
if not self.odoo_company:
raise CommandError("Missing or invalid parameter odoo.company")
self.odoo_language = Parameter.getValue("odoo.language", self.database, 'en_US')
self.context = {'lang': self.odoo_language}
示例6: odoo_write
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def odoo_write(db=DEFAULT_DB_ALIAS):
'''
Uploads operationplans to odoo.
- Sends all operationplans, meeting the criteria:
a) locked = False
The operationplans with locked equal to true are input to the plan,
and not output.
b) operationplan produces into a buffer whose source field is 'odoo'.
Only those results are of interest to odoo.
- We upload the following info in XML form:
- id: frePPLe generated unique identifier
- operation
- start
- end
- quantity
- location: This is the odoo id of the location, as stored in
buffer.location.subcategory.
- item: This is the odoo id of the produced item and its uom_id, as
stored in buffer.item.subcategory.
- criticality: 0 indicates a critical operationplan, 999 indicates a
redundant operationplan.
- The XML file uploaded is not exactly the standard XML of frePPLe, but a
slight variation that fits odoo better.
- This code doesn't interprete any of the results. An odoo addon module
will need to read the content, and take appropriate actions in odoo:
such as creating purchase orders, manufacturing orders, work orders,
project tasks, etc...
'''
odoo_user = Parameter.getValue("odoo.user", db)
odoo_password = Parameter.getValue("odoo.password", db)
odoo_db = Parameter.getValue("odoo.db", db)
odoo_url = Parameter.getValue("odoo.url", db)
odoo_company = Parameter.getValue("odoo.company", db)
ok = True
if not odoo_user:
print("Missing or invalid parameter odoo.user")
ok = False
if not odoo_password:
print("Missing or invalid parameter odoo.password")
ok = False
if not odoo_db:
print("Missing or invalid parameter odoo.db")
ok = False
if not odoo_url:
print("Missing or invalid parameter odoo.url")
ok = False
if not odoo_company:
print("Missing or invalid parameter odoo.company")
ok = False
odoo_language = Parameter.getValue("odoo.language", db, 'en_US')
if not ok:
raise Exception("Odoo connector not configured correctly")
boundary = email.generator._make_boundary()
# Generator function
# We generate output in the multipart/form-data format.
# We send the connection parameters as well as a file with the planning
# results in XML-format.
def publishPlan():
yield '--%s\r' % boundary
yield 'Content-Disposition: form-data; name="database"\r'
yield '\r'
yield '%s\r' % odoo_db
yield '--%s\r' % boundary
yield 'Content-Disposition: form-data; name="language"\r'
yield '\r'
yield '%s\r' % odoo_language
yield '--%s\r' % boundary
yield 'Content-Disposition: form-data; name="company"\r'
yield '\r'
yield '%s\r' % odoo_company
yield '--%s\r' % boundary
yield 'Content-Disposition: file; name="frePPLe plan"; filename="frepple_plan.xml"\r'
yield 'Content-Type: application/xml\r'
yield '\r'
yield '<?xml version="1.0" encoding="UTF-8" ?>'
yield '<plan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
# Export relevant operationplans
yield '<operationplans>'
for i in frepple.operationplans():
b = None
for j in i.flowplans:
if j.quantity > 0:
b = j.flow.buffer
if not b or b.source != 'odoo' or i.locked:
continue
yield '<operationplan id="%s" operation=%s start="%s" end="%s" quantity="%s" location=%s item=%s criticality="%d"/>' % (
i.id, quoteattr(i.operation.name),
i.start, i.end, i.quantity,
quoteattr(b.location.subcategory), quoteattr(b.item.subcategory),
int(i.criticality)
)
yield '</operationplans>'
yield '</plan>'
yield '--%s--\r' % boundary
yield '\r'
# Connect to the odoo URL to POST data
try:
req = Request("%s/frepple/xml/" % odoo_url.encode('ascii'))
#.........這裏部分代碼省略.........
示例7: odoo_read
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def odoo_read(db=DEFAULT_DB_ALIAS, mode=1):
'''
This function connects to a URL, authenticates itself using HTTP basic
authentication, and then reads data from the URL.
The data from the source must adhere to frePPLe's official XML schema,
as defined in the schema files bin/frepple.xsd and bin/frepple_core.xsd.
The mode is pass as an argument:
- Mode 1:
This mode returns all data that is loaded with every planning run.
- Mode 2:
This mode returns data that is loaded that changes infrequently and
can be transferred during automated scheduled runs at a quiet moment.
Which data elements belong to each category is determined in the odoo
addon module and can vary between implementations.
'''
odoo_user = Parameter.getValue("odoo.user", db)
if settings.ODOO_PASSWORDS.get(db) == '':
odoo_password = Parameter.getValue("odoo.password", db)
else:
odoo_password = settings.ODOO_PASSWORDS.get(db)
odoo_db = Parameter.getValue("odoo.db", db)
odoo_url = Parameter.getValue("odoo.url", db)
odoo_company = Parameter.getValue("odoo.company", db)
ok = True
if not odoo_user:
print("Missing or invalid parameter odoo.user")
ok = False
if not odoo_password:
print("Missing or invalid parameter odoo.password")
ok = False
if not odoo_db:
print("Missing or invalid parameter odoo.db")
ok = False
if not odoo_url:
print("Missing or invalid parameter odoo.url")
ok = False
if not odoo_company:
print("Missing or invalid parameter odoo.company")
ok = False
odoo_language = Parameter.getValue("odoo.language", db, 'en_US')
if not ok:
raise Exception("Odoo connector not configured correctly")
# Connect to the odoo URL to GET data
f = None
url = "%sfrepple/xml?%s" % (odoo_url, urlencode({
'database': odoo_db,
'language': odoo_language,
'company': odoo_company,
'mode': mode
}))
try:
request = Request(url)
encoded = base64.encodestring(('%s:%s' % (odoo_user, odoo_password)).encode('utf-8'))[:-1]
request.add_header("Authorization", "Basic %s" % encoded.decode('ascii'))
f = urlopen(request)
except HTTPError as e:
print("Error connecting to odoo at %s: %s" % (url, e))
raise e
# Download and parse XML data
try:
frepple.readXMLdata(f.read().decode('utf-8'), False, False)
finally:
if f: f.close()
示例8: handle
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def handle(self, **options):
# Pick up the options
if 'verbosity' in options:
self.verbosity = int(options['verbosity'] or '1')
else:
self.verbosity = 1
if 'user' in options:
user = options['user']
else:
user = ''
if 'database' in options:
self.database = options['database'] or DEFAULT_DB_ALIAS
else:
self.database = DEFAULT_DB_ALIAS
if self.database not in settings.DATABASES.keys():
raise CommandError("No database settings known for '%s'" % self.database )
# Pick up configuration parameters
self.openbravo_user = Parameter.getValue("openbravo.user", self.database)
# Passwords in djangosettings file are preferably used
if settings.OPENBRAVO_PASSWORDS.get(db) == '':
self.openbravo_password = Parameter.getValue("openbravo.password", self.database)
else:
self.openbravo_password = settings.OPENBRAVO_PASSWORDS.get(db)
self.openbravo_host = Parameter.getValue("openbravo.host", self.database)
self.openbravo_organization = Parameter.getValue("openbravo.organization", self.database)
if not self.openbravo_user:
raise CommandError("Missing or invalid parameter openbravo_user")
if not self.openbravo_password:
raise CommandError("Missing or invalid parameter openbravo_password")
if not self.openbravo_host:
raise CommandError("Missing or invalid parameter openbravo_host")
if not self.openbravo_organization:
raise CommandError("Missing or invalid parameter openbravo_organization")
# Make sure the debug flag is not set!
# When it is set, the django database wrapper collects a list of all SQL
# statements executed and their timings. This consumes plenty of memory
# and cpu time.
tmp_debug = settings.DEBUG
settings.DEBUG = False
now = datetime.now()
task = None
try:
# Initialize the task
if 'task' in options and options['task']:
try:
task = Task.objects.all().using(self.database).get(pk=options['task'])
except:
raise CommandError("Task identifier not found")
if task.started or task.finished or task.status != "Waiting" or task.name != 'Openbravo export':
raise CommandError("Invalid task identifier")
task.status = '0%'
task.started = now
else:
task = Task(name='Openbravo export', submitted=now, started=now, status='0%', user=user)
task.save(using=self.database)
# Create a database connection to the frePPLe database
cursor = connections[self.database].cursor()
# Look up the id of the Openbravo user
query = urllib.quote("name='%s'" % self.openbravo_user.encode('utf8'))
conn = self.get_data("/openbravo/ws/dal/ADUser?where=%s&includeChildren=false" % query)[0]
self.user_id = None
for event, elem in conn:
if event != 'end' or elem.tag != 'ADUser':
continue
self.user_id = elem.get('id')
if not self.user_id:
raise CommandError("Can't find user id in Openbravo")
# Look up the id of the Openbravo organization id
query = urllib.quote("name='%s'" % self.openbravo_organization.encode('utf8'))
conn = self.get_data("/openbravo/ws/dal/Organization?where=%s&includeChildren=false" % query)[0]
self.organization_id = None
for event, elem in conn:
if event != 'end' or elem.tag != 'Organization':
continue
self.organization_id = elem.get('id')
if not self.organization_id:
raise CommandError("Can't find organization id in Openbravo")
# Upload all data
self.export_procurement_order(cursor)
self.export_work_order(cursor)
self.export_sales_order(cursor)
# Log success
task.status = 'Done'
task.finished = datetime.now()
except Exception as e:
if task:
task.status = 'Failed'
task.message = '%s' % e
task.finished = datetime.now()
raise e
#.........這裏部分代碼省略.........
示例9: Upload
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def Upload(request):
'''
TODO we are doing lots of round trips to the database and openbravo to
read the configuration. There is considerable overhead in this.
'''
# Decode the data received from the client
data = json.loads(request.body.decode('utf-8'))
# Validate records which exist in the database
cleaned_records = []
for rec in data:
try:
if rec['type'] == 'PO':
obj = PurchaseOrder.objects.using(request.database).get(id=rec['id'])
obj.supplier = Supplier.objects.using(request.database).get(name=rec.get('origin') or rec.get('supplier'))
if not obj.supplier.source:
continue
else:
obj = DistributionOrder.objects.using(request.database).get(id=rec['id'])
#obj.destination = Location.objects.using(request.database).get(name=rec['destination'])
#obj.origin = Location.object.using(request.database).get(name=rec['origin'])
if obj.item.name != rec['item']:
obj.item = Item.objects.using(request.database).get(name=rec['item'])
if obj.status == 'proposed' and obj.item.source:
# Copy edited values on the database object. Changes aren't saved yet.
obj.startdate = datetime.strptime(rec['startdate'], "%Y-%m-%d %H:%M:%S")
obj.enddate = datetime.strptime(rec['enddate'], "%Y-%m-%d %H:%M:%S")
obj.quantity = abs(float(rec['quantity']))
obj.status = 'approved'
cleaned_records.append(obj)
except:
pass
if not cleaned_records:
return HttpResponse(content=_("No proposed data records selected"), status=500)
# Read the configuration data from the database.
openbravo_user = Parameter.getValue("openbravo.user", request.database)
# Passwords in djangosettings file are preferably used
if settings.OPENBRAVO_PASSWORDS.get(request.database) == '':
openbravo_password = Parameter.getValue("openbravo.password", request.database)
else:
openbravo_password = settings.OPENBRAVO_PASSWORDS.get(request.database)
openbravo_host = Parameter.getValue("openbravo.host", request.database)
openbravo_organization = Parameter.getValue("openbravo.organization", request.database)
exportPurchasingPlan = Parameter.getValue("openbravo.exportPurchasingPlan", request.database, default="false")
# Look up the id of the Openbravo organization id
if request.database not in openbravo_organization_ids:
query = urllib.parse.quote("name='%s'" % openbravo_organization)
data = get_data(
"/openbravo/ws/dal/Organization?where=%s&includeChildren=false" % query,
openbravo_host, openbravo_user, openbravo_password
)
conn = iterparse(StringIO(data), events=('start', 'end'))
for event, elem in conn:
if event == 'end' and elem.tag == 'Organization':
openbravo_organization_ids[request.database] = elem.get('id')
break
if request.database not in openbravo_organization_ids:
return HttpResponse(content="Can't find organization id in Openbravo", status=500)
# Build the data content to send
body = [
#'<?xml version="1.0" encoding="UTF-8"?>',
'<ob:Openbravo xmlns:ob="http://www.openbravo.com">',
]
now = datetime.now().strftime('%Y/%m/%d %H:%M:%S')
if exportPurchasingPlan:
identifier = uuid4().hex
url = "/openbravo/ws/dal/MRPPurchasingRun"
body.append('''<MRPPurchasingRun id="%s">
<organization id="%s" entity-name="Organization" identifier="%s"/>
<active>true</active>
<name>FREPPLE %s</name>
<description>Incremental export triggered by %s</description>
<timeHorizon>365</timeHorizon>
<timeHorizon>365</timeHorizon>
<safetyLeadTime>0</safetyLeadTime>
<mRPPurchasingRunLineList>''' % (
identifier, openbravo_organization_ids[request.database],
openbravo_organization, now, request.user.username
))
for obj in cleaned_records:
identifier2 = uuid4().hex
businessPartner = ''
if isinstance(obj, PurchaseOrder):
transaction_type = 'PO'
if obj.supplier and obj.supplier.source:
businessPartner = '<businessPartner id="%s"/>' % obj.supplier.source
# TODO: where to store the destination of a purchase order
else:
transaction_type = 'MF' # TODO Is this right?
# TODO: where to store the source and destination of a stock transfer order
# Possible transaction types in Openbravo are:
# - SO (Pending Sales Order)
# - PO (Pending Purchase Order)
# - WR (Pending Work Requirement)
# - SF (Sales Forecast)
# - MF (Material Requirement)
# - UD (User defined)
#.........這裏部分代碼省略.........
示例10: handle
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def handle(self, **options):
# Pick up the options
if 'verbosity' in options: self.verbosity = int(options['verbosity'] or '1')
else: self.verbosity = 1
if 'user' in options: user = options['user']
else: user = ''
if 'database' in options: self.database = options['database'] or DEFAULT_DB_ALIAS
else: self.database = DEFAULT_DB_ALIAS
if not self.database in settings.DATABASES.keys():
raise CommandError("No database settings known for '%s'" % self.database )
# Pick up configuration parameters
self.openerp_user = Parameter.getValue("openerp.user", self.database)
self.openerp_password = Parameter.getValue("openerp.password", self.database)
self.openerp_db = Parameter.getValue("openerp.db", self.database)
self.openerp_url = Parameter.getValue("openerp.url", self.database)
# Make sure the debug flag is not set!
# When it is set, the django database wrapper collects a list of all SQL
# statements executed and their timings. This consumes plenty of memory
# and cpu time.
tmp_debug = settings.DEBUG
settings.DEBUG = False
now = datetime.now()
ac = transaction.get_autocommit(using=self.database)
transaction.set_autocommit(False, using=self.database)
task = None
try:
# Initialize the task
if 'task' in options and options['task']:
try: task = Task.objects.all().using(self.database).get(pk=options['task'])
except: raise CommandError("Task identifier not found")
if task.started or task.finished or task.status != "Waiting" or task.name != 'OpenERP export':
raise CommandError("Invalid task identifier")
task.status = '0%'
task.started = now
else:
task = Task(name='OpenERP edport', submitted=now, started=now, status='0%', user=user)
task.save(using=self.database)
transaction.commit(using=self.database)
# Log in to the openerp server
sock_common = xmlrpclib.ServerProxy(self.openerp_url + 'xmlrpc/common')
self.uid = sock_common.login(self.openerp_db, self.openerp_user, self.openerp_password)
# Connect to openerp server
self.sock = xmlrpclib.ServerProxy(self.openerp_url + 'xmlrpc/object')
# Create a database connection to the frePPLe database
self.cursor = connections[self.database].cursor()
# Upload all data
self.export_procurement_order()
task.status = '50%'
task.save(using=self.database)
transaction.commit(using=self.database)
self.export_sales_order()
task.status = '100%'
task.save(using=self.database)
transaction.commit(using=self.database)
# Log success
task.status = 'Done'
task.finished = datetime.now()
except Exception as e:
if task:
task.status = 'Failed'
task.message = '%s' % e
task.finished = datetime.now()
raise e
finally:
if task: task.save(using=self.database)
try: transaction.commit(using=self.database)
except: pass
settings.DEBUG = tmp_debug
transaction.set_autocommit(ac, using=self.database)
示例11: export_purchasingplan
# 需要導入模塊: from freppledb.common.models import Parameter [as 別名]
# 或者: from freppledb.common.models.Parameter import getValue [as 別名]
def export_purchasingplan(self, cursor):
purchaseplan = '''<MRPPurchasingRun id="%s">
<organization id="%s" entity-name="Organization"/>
<active>true</active>
<name>FREPPLE %s</name>
<description>Bulk export</description>
<timeHorizon>365</timeHorizon>
<safetyLeadTime>0</safetyLeadTime>
<mRPPurchasingRunLineList>'''
purchasingplanline = '''<ProcurementRequisitionLine>
<active>true</active>
<requisition id="%s" entity-name="ProcurementRequisition"/>
<product id="%s" entity-name="Product"/>
<quantity>%s</quantity>
<uOM id="100" entity-name="UOM" identifier="Unit"/>
<requisitionLineStatus>O</requisitionLineStatus>
<needByDate>%s.0Z</needByDate>
<lineNo>%s</lineNo>
</ProcurementRequisitionLine>'''
try:
# Close the old purchasing plan generated by frePPLe
if self.verbosity > 0:
print("Closing previous purchasing plan generated from frePPLe")
body = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<ob:Openbravo xmlns:ob="http://www.openbravo.com">'
]
query = urllib.parse.quote("createdBy='%s' and purchasingPlan.description='Bulk export'" % self.openbravo_user_id)
data = delete_data(
"/openbravo/ws/dal/MRPPurchasingRunLine?where=%s" % query,
self.openbravo_host,
self.openbravo_user,
self.openbravo_password
)
query = urllib.parse.quote("createdBy='%s' and description='Bulk export'" % self.openbravo_user_id)
data = delete_data(
"/openbravo/ws/dal/MRPPurchasingRun?where=%s" % query,
self.openbravo_host,
self.openbravo_user,
self.openbravo_password
)
if self.filteredexport:
filter_expression_po = Parameter.getValue('openbravo.filter_export_purchase_order', self.database, "")
if filter_expression_po:
filter_expression_po = ' and (%s) ' %filter_expression_po
filter_expression_do = Parameter.getValue('openbravo.filter_export_distribution_order', self.database, "")
if filter_expression_do:
filter_expression_do = ' and (%s) ' %filter_expression_do
else:
filter_expression_po = ""
filter_expression_do = ""
# Create new purchase plan
starttime = time()
if self.verbosity > 0:
print("Exporting new purchasing plan...")
count = 0
now = datetime.now().strftime('%Y/%m/%d %H:%M:%S')
identifier = uuid4().hex
body = [purchaseplan % (identifier, self.organization_id, now),]
cursor.execute('''
select item.source, location.source, enddate, quantity
FROM purchase_order
inner JOIN buffer
ON buffer.item_id = purchase_order.item_id
AND buffer.location_id = purchase_order.location_id
AND buffer.subcategory = 'openbravo'
inner join item
ON item.name = purchase_order.item_id
and item.source is not null
and item.subcategory = 'openbravo'
inner join location
ON purchase_order.location_id = location.name
and location.source is not null
and location.subcategory = 'openbravo'
where status = 'proposed' %s
union all
select item.source, location.source, enddate, quantity
FROM distribution_order
inner JOIN buffer
ON buffer.item_id = distribution_order.item_id
AND buffer.location_id = distribution_order.destination_id
AND buffer.subcategory = 'openbravo'
inner join item
ON item.name = distribution_order.item_id
and item.source is not null
and item.subcategory = 'openbravo'
inner join location
ON distribution_order.destination_id = location.name
and location.source is not null
and location.subcategory = 'openbravo'
where status = 'proposed' %s
''' % (filter_expression_po,filter_expression_do))
for i in cursor.fetchall():
body.append(purchasingplanline % (identifier, i[0], i[3], i[2].strftime("%Y-%m-%dT%H:%M:%S"), count))
count += 1
body.append('</mRPPurchasingRunLineList>')
#.........這裏部分代碼省略.........