def search_product(productid=None): config.set_trytond(DATABASE_NAME, config_file=CONFIG) Product = Model.get('product.product') product = Product.find(['code', '=', productid]) list = [] for n in product: list.append({'id': str(n.id), 'code': n.code, 'name': n.name, 'price': str(n.list_price)}) return jsonify(result=list)
def get_customers(): config.set_trytond(DATABASE_NAME, config_file=CONFIG) customers = models.Customer.query.all() list = [] for c in customers: list.append({'id': str(c.id), 'city': c.city, 'name': c.name, 'zip': c.zip, 'country': c.country, 'subdivision': c.subdivision, 'street': c.street, 'streetbis': c.streetbis, 'active': c.active, 'delivery': c.delivery, 'invoice': c.invoice }) return jsonify(result=list)
def main(): config.set_trytond(DATABASE_NAME, config_file=CONFIG) trytontype = sys.argv[1] f = open(sys.argv[2], 'rb') if trytontype is None: print "Please provide a type to load" elif trytontype == 'customer': loadCustomers() elif trytontype == 'product': loadProducts() elif trytontype == 'image': loadImages() elif trytontype == 'shipment': loadInternalShipment()
def done(context): from trytond.modules.company.tests.tools import create_company, \ get_company from trytond.modules.account.tests.tools import create_fiscalyear, \ create_chart, get_accounts from.trytond.modules.account_invoice.tests.tools import \ set_fiscalyear_invoice_sequences, create_payment_term from trytond.modules.account_asset.tests.tools \ import add_asset_accounts #step('Create database') config = config.set_trytond() config.pool.test = True #step('Install account_asset') Module = Model.get('ir.module.module') module, = Module.find([ ('name', '=', 'account_asset'), ]) module.click('install') Wizard('ir.module.module.install_upgrade').execute('upgrade') #@step('Create company') _ = create_company() company = get_company() #@step('Reload the context') User = Model.get('res.user') config._context = User.get_preferences(True, config.context) #@step('Create fiscal year') fiscalyear = set_fiscalyear_invoice_sequences( create_fiscalyear(company)) fiscalyear.click('create_period') #@step('Create chart of accounts') _ = create_chart(company) accounts = add_asset_accounts(get_accounts(company), company) revenue = accounts['revenue'] asset_account = accounts['asset'] expense = accounts['expense'] depreciation_account = accounts['depreciation']
def main(options): # create database print u'\n>>> creando database...' con = connect(user='******', dbname='template1', password='******', host=options.host) con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = con.cursor() cur.execute('CREATE DATABASE %s' % options.database + ' WITH ENCODING = \'UTF8\'') cur.close() con.close() # init database print u'\n>>> inicializando...' os.environ["TRYTONPASSFILE"] = 'trytonpass' toptions = { 'configfile': options.config_file, 'database_names': [options.database], 'update': ['ir'], 'logconf': None, 'pidfile': None, } try: trytond.server.TrytonServer(Bunch(toptions)).run() except SystemExit: pass config = pconfig.set_trytond(options.database, config_file=options.config_file, language='es_AR') Lang = Model.get('ir.lang') (es_AR,) = Lang.find([('code', '=', 'es_AR')]) es_AR.translatable = True es_AR.save() try: trytond.server.TrytonServer(Bunch(toptions)).run() except SystemExit: pass install_modules() crear_company(config, es_AR) crear_scenario_tipo(config, es_AR) crear_account_invoice_ar_pos(config, es_AR) print "done."
def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('nombre-db', action="store", help="Nombre de la base de datos en la que insertar los registros.") parser.add_argument('password-admin-db', action="store", help="Password del usuario admin en la base de datos.") parser.add_argument('archivo-configuracion', action="store", help="Archivo trytond.conf que usas para correr el server. \n Si no sabes donde esta, escribi 'locate trytond.conf' en la consola, amigx.") parser.add_argument('-p','--productos', action="store", help="Crear productos a partir del archivo indicado.") parser.add_argument('-i','--impuestos', action="store", help="Crear impuestos a partir del archivo indicado.") parser.add_argument('-t','--tarifas', action="store", help="Crear tarifas a partir del archivo indicado.") parser.add_argument('-c','--consumos', action="store", help="Crear vinculo producto-consumos a partir del archivo indicado.") parsed = parser.parse_args() parsed = vars(parsed) print "Enhorabuena, los parametros son correctos!.\nConectando a trytond..." print "Activando GPS...detectando ubicación geoespacial...triangulando coordenadas...usted se encuentra en: EL SUCUCHITO" print "Los parametros son: nombre-db=%s password-admin-db=%s archivo-configuracion=%s" % (parsed["nombre-db"], parsed["password-admin-db"], parsed["archivo-configuracion"]) c = config.set_trytond( database_name=sys.argv[1], database_type="postgresql", password=sys.argv[2], config_file=sys.argv[3]) print "Conectado" #Ojo que el orden importa keys = [ ("impuestos", translate_to_tax), ("productos", translate_to_product), ("tarifas", translate_to_price_list_line), ("consumos", translate_to_producto_consumo) ] for key, translator in keys: arch = parsed[key] if arch: print "Vamos a crear las entidades de: %s" % arch with open(arch) as fi: create_entities(csv.DictReader(fi, delimiter=";"), translator, False)
def uninstall_task(database, modules, config_file=os.environ.get('TRYTOND_CONFIG')): """ Uninstall the supplied modules (separated by coma) from database. """ if not database or not modules: return if isinstance(modules, basestring): modules = modules.replace(" ", "").split(',') if not modules: return print t.bold("uninstall: ") + ", ".join(modules) if not check_database(database, {}): return config = pconfig.set_trytond(database=database, config_file=config_file) if proteus_version < '3.5': Module = Model.get('ir.module.module') else: Module = Model.get('ir.module') modules_to_uninstall = Module.find([('name', 'in', modules), ('state', '=', 'installed')]) Module.uninstall([m.id for m in modules_to_uninstall], config.context) if proteus_version < '3.5': module_install_upgrade = Wizard('ir.module.module.install_upgrade') else: module_install_upgrade = Wizard('ir.module.install_upgrade') module_install_upgrade.execute('upgrade') module_install_upgrade.execute('config') print ""
def _get_config(): cfg = pconfig.set_trytond() cfg.pool.test = True return cfg
def main(database, config_file=None): config.set_trytond(database, config_file=config_file) update_currencies()
def get_pconfig(): """Returns a tryton configuration settings""" return pconfig.set_trytond(TRYTONCONF['dbname'], user='******', config_file=TRYTONCONF['conffile'])
property.company = get_company() property.save() modelfield = ModelField.find([('name', '=', 'account_stock_customer'), ('model', '=', pcmodel[0].id)]) property = Property() property.field = modelfield[0] property.value = get_account(stockaccountlist, 'Stock Customer') property.company = get_company() property.save() def main(): company = get_company() fiscalyear = create_fiscalyear(company) _ = create_chart(company) accounts = get_accounts(company) payable = accounts['payable'] expense = accounts['expense'] tax = accounts['tax'] tax = create_tax(Decimal(DEFAULT_VAT_TAX_PERCENTAGE)) create_account_configuration(accounts, company) create_payment_terms() supplier = create_supplier() # create product config create_product_config() create_product_category(accounts) if __name__ == '__main__': config.set_trytond(DATABASE_NAME, config_file=CONFIG) main()
settings.database = option.database settings.module = option.module settings.lang = option.lang settings.url = option.url settings.path = option.path else: print usage return settings if __name__ == "__main__": settings = parse_arguments(sys.argv[1:]) if settings.database: config.set_trytond(database=settings.database) else: config.set_xmlrpc(settings.url) Module = Model.get('ir.module.module') if settings.module == 'all': modules = Module.find([('state', '=', 'installed')]) else: modules = Module.find([ ('state', '=', 'installed'), ('name', '=', settings.module), ]) Lang = Model.get('ir.lang') language, = Lang.find([('code', '=', settings.lang)])
def __init__(self): self.config = config.set_trytond(database_type=settings.TRYTON_DB_TYPE, database_name=settings.TRYON_DB) self.module = Model.get('ir.module.module')
if not db_name: db_name = DEFAULT_DB_NAME password = getpass.getpass( "Ingrese el password de admin a utilizar en la base '%s' [%s]: " % (db_name, DEFAULT_PASSWORD) ) if not password: password = DEFAULT_PASSWORD #if database doesn't exists, proteus creates it config = config.set_trytond( db_name, 'admin', 'postgresql', LANGUAGE, password, CONFIG_FILE ) #Tryton throw a lot of deprecation warnings, we turn these off with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=DeprecationWarning) Module = Model.get('ir.module.module') #Get all installed modules modules = Module.find() Module.install([m.id for m in modules], config.context) Wizard('ir.module.module.install_upgrade').execute('upgrade')
def make_sale(): print_payslip = False payslip = request.get_json(force=True) payslip_customer = payslip['customer'] payslip_info = payslip['payslip_info'] payslip_items = payslip['items'] # create sale order config.set_trytond(DATABASE_NAME, config_file=CONFIG) Party = Model.get('party.party') partylist = Party.find([('id', '=', payslip_customer['customerid'])]) party = partylist[0] Sale = Model.get('sale.sale') sale = Sale() if (sale.id < 0): sale.party = party sale.reference = '[' + payslip_info[ 'username'] + '] - ' + payslip_info['order_date'] sale.number = payslip_info['order_id'] Currency = Model.get('currency.currency') (currency, ) = Currency.find([('code', '=', payslip_info['currency'])]) sale.currency = currency sale.description = 'uuid: ' + payslip_info['payslip_uuid'] # check if sale has been processed SaleOld = Model.get('sale.sale') saleold = SaleOld.find([('description', '=', 'uuid: ' + payslip_info['payslip_uuid'])]) if len(saleold) > 0: print('Order has already been processed.') listold = [{ 'id': str(saleold[0].id), 'party': str(saleold[0].party.id) }] return jsonify(result=listold) sale.sale_date = date.today() Paymentterm = Model.get('account.invoice.payment_term') paymentterm = Paymentterm.find([('name', '=', 'cash')]) sale.payment_term = paymentterm[0] for idx, payslip_line in enumerate(payslip_items): Product = Model.get('product.product') product = Product.find(['id', '=', payslip_line['id']]) # remove products if app.config['DEACTIVATE_PRODUCT_WHEN_SOLD']: attribute_dict = product[0].attributes if attribute_dict is not None: for key in attribute_dict.keys(): if key == 'available': attribute_dict[key] = False product[0].attributes = attribute_dict product[0].save() line = sale.lines.new(quantity=1) line.product = product[0] line.description = product[0].name line.quantity = int(payslip_line['item_qty']) line.sequence = idx sale.save() try: sale.click('quote') sale.click('confirm') sale.click('process') except Exception, e: print 'make_sale.Exception %s' % e saleId = sale.id
def ipn(): try: arg = '' request.parameter_storage_class = ImmutableOrderedMultiDict values = request.form for x, y in values.iteritems(): arg += "&{x}={y}".format(x=x,y=y) validate_url = 'https://www.sandbox.paypal.com' \ '/cgi-bin/webscr?cmd=_notify-validate{arg}' \ .format(arg=arg) r = requests.get(validate_url) if r.text == 'VERIFIED': try: payer_email = request.form.get('payer_email') unix = int(time.time()) payment_date = request.form.get('payment_date') saleid = request.form.get('custom') last_name = request.form.get('last_name') payment_gross = request.form.get('mc_gross') payment_fee = request.form.get('mc_fee') payment_currency = request.form.get('mc_currency') payment_net = float(payment_gross) - float(payment_fee) payment_status = request.form.get('payment_status') txn_id = request.form.get('txn_id') except Exception as e: with open('/tmp/ipnout.txt','a') as f: data = 'ERROR WITH IPN DATA\n'+str(values)+'\n' f.write(data) with open('/tmp/ipnout.txt','a') as f: data = 'SUCCESS\n'+str(values)+'\n' f.write(data) # user_name, mc_gross, mc_fee, mc_currency need to be checked in database # mark order in tryton as paid # c.execute("INSERT INTO ipn (unix, payment_date, username, last_name, payment_gross, payment_fee, payment_net, payment_status, txn_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", # (unix, payment_date, username, last_name, payment_gross, payment_fee, payment_net, payment_status, txn_id)) config.set_trytond(DATABASE_NAME, config_file=CONFIG) Sale = Model.get('sale.sale') saleList = Sale.find(['id', '=', saleid]) if saleList is not None: check_order = True if (saleList[0].state != 'draft'): check_order = False if (saleList[0].currency.symbol != payment_currency): check_order = False saleLine = saleList[0].lines saleTotal = Decimal(0.00) for n in saleLine: saleTotal += n.unit_price * Decimal(n.quantity) if (Decimal(payment_gross) < saleTotal): check_order = False if check_order: # change sale state to 'confirmed' Attachments = Model.get('ir.attachment') attachment = Attachments() attachment.name = 'PAYPAL IPN DATA' attachment.resource = saleList[0] attachment.description = 'PAYPAL IPN DATA\n'+str(values)+'\n' attachment.save() # saleList[0].save() try: saleList[0].click('quote') except Exception as e: print 'Exception: Could not update sale state '+str(e) else: # add note that something failed in payment Attachments = Model.get('ir.attachment') attachment = Attachments() attachment.name = 'PAYPAL IPN DATA' attachment.resource = saleList[0] attachment.description = 'ERROR WITH PAYPAL IPN DATA\n'+str(values)+'\n' attachment.save() else: with open('/tmp/ipnout.txt','a') as f: data = 'FAILURE\n'+str(values)+'\n' f.write(data) return r.text except Exception as e: return str(e)
def export_translations(database, modules, langs=None, host=None, port=None, dbuser=None, dbpassword=None, config_file=os.environ.get('TRYTOND_CONFIG')): """ Creates translation files for the given modules and the specified languages. If no languages are specified, the ones marked as translatable in the database are used. """ print t.bold('export_translations: %s, %s, %s') % (database, modules, langs) if not _check_database(database, host, port, dbuser, dbpassword): return config.set_trytond(database=database, config_file=config_file) try: Module = Model.get('ir.module') except KeyError: # Compatibility with versions older than 3.8 Module = Model.get('ir.module.module') if modules == 'all': ir_modules = Module.find([ ('state', '=', 'installed'), ]) else: modules = modules.split(',') ir_modules = Module.find([ ('state', '=', 'installed'), ('name', 'in', modules), ]) missing_modules = set(modules) - set(m.name for m in ir_modules) if missing_modules: print t.bold('Invalid modules: %s') % missing_modules return Lang = Model.get('ir.lang') if langs is None: languages = Lang.find([ ('translatable', '=', True), ]) else: langs = langs.split(',') languages = Lang.find([ ('code', 'in', langs), ]) if set(langs) != set(l.code for l in languages): print 'Invalid languages: %s' % languages return for module in ir_modules: module_locale_path = os.path.abspath( os.path.normpath( os.path.join(os.getcwd(), 'modules', module.name, 'locale'))) if not os.path.exists(module_locale_path): os.makedirs(module_locale_path) for language in languages: if language.code == 'en_US': continue translation_export = Wizard('ir.translation.export') translation_export.form.language = language translation_export.form.module = module translation_export.execute('export') if not translation_export.form.file: continue file_path = os.path.join(module_locale_path, '%s.po' % language.code) with open(file_path, 'w') as f: f.write(str(translation_export.form.file)) translation_export.execute('end') print('Translation of "%s" in "%s" exported successfully.' % (module.name, language.code))
def checkout(): config.set_trytond(DATABASE_NAME, config_file=CONFIG) page_topic = gettext(u'Checkout') page_content = gettext(u'Please enter your address here:') productlist = getProductFromSession() form = CheckoutForm() if form.validate_on_submit(): try: partyid = session['partyid'] Party = Model.get('party.party') party = Party.find([('id', '=', partyid)])[0] except KeyError: Party = Model.get('party.party') party = Party() if party.id < 0: party.name = form.name.data Lang = Model.get('ir.lang') (en,) = Lang.find([('code', '=', 'en_US')]) party.lang = en party.addresses[0].name = form.name.data party.addresses[0].street = form.street.data party.addresses[0].streetbis = form.street2.data party.addresses[0].zip = form.zip.data party.addresses[0].city = form.city.data Country = Model.get('country.country') (ch, ) = Country.find([('code', '=', 'CH')]) party.addresses[0].country = ch # address.subdivision = None party.addresses[0].invoice = form.invoice.data party.addresses[0].delivery = form.delivery.data party.save() else: party.addresses[0].name = form.name.data party.addresses[0].street = form.street.data party.addresses[0].streetbis = form.street2.data party.addresses[0].zip = form.zip.data party.addresses[0].city = form.city.data Country = Model.get('country.country') (ch, ) = Country.find([('code', '=', 'CH')]) party.addresses[0].country = ch # address.subdivision = None party.addresses[0].invoice = form.invoice.data party.addresses[0].delivery = form.delivery.data party.save() Sale = Model.get('sale.sale') sale = Sale() if (sale.id < 0): sale.party = party Paymentterm = Model.get('account.invoice.payment_term') paymentterm = Paymentterm.find([('name', '=', 'cash')]) sale.payment_term = paymentterm[0] for p in productlist: line = sale.lines.new(quantity=1) line.product = p line.description = p.name + ' - ' + p.code line.quantity = 1 line.sequence = 1 sale.save() session['sale_id'] = sale.id flash('Checkout started successfully name="%s", name2=%s, saleid=%s' % (form.name.data, str(form.name2.data), sale.id)) return redirect('/payment') if form.name.data is None: try: partyid = session['partyid'] Party = Model.get('party.party') party = Party.find([('id', '=', partyid)])[0] form.name.data = party.addresses[0].name form.street.data = party.addresses[0].street form.street2.data = party.addresses[0].streetbis form.zip.data = party.addresses[0].zip form.city.data = party.addresses[0].city form.invoice.data = party.addresses[0].invoice form.delivery.data = party.addresses[0].delivery except KeyError: print('user is not logged in') return render_template('checkout.html', pt=page_topic, pc=page_content, product=productlist, title="Milliondog", page=gettext(u'Checkout'), form=form)
def product_categories(): config.set_trytond(DATABASE_NAME, config_file=CONFIG) ProductCategory = Model.get('product.category') categories = ProductCategory.find(['id', '>=', '0']) idlist = [c.name for c in categories] return render_template('productcategories.html', db_model='Product Categories', db_list=idlist, title="Milliondog", page='Product Categories')
def setUp(self): self.config = config.set_trytond()
def set_config(database, password): return pconfig.set_trytond(database, password=password)
#!/usr/bin/python # -*- coding: iso-8859-15 -*- from proteus import config, Model import os import unicodecsv from cStringIO import StringIO from decimal import Decimal from datetime import datetime config = config.set_trytond('sqlite://') Address = Model.get('party.address') Bank = Model.get('bank') BankAccount = Model.get('bank.account') BankAccountNumber = Model.get('bank.account.number') Category = Model.get('party.category') Company = Model.get('company.company') CondoFactor = Model.get('condo.factor') CondoPain = Model.get('condo.payment.pain') CondoParty = Model.get('condo.party') CondoPayment = Model.get('condo.payment') CondoPaymentGroup = Model.get('condo.payment.group') CondoUnit = Model.get('condo.unit') ContactMechanism = Model.get('party.contact_mechanism') Country = Model.get('country.country') Currency = Model.get('currency.currency') Identifier = Model.get('party.identifier') Lang = Model.get('ir.lang') Mandate = Model.get('condo.payment.sepa.mandate')
def main(database, codes, config_file=None): config.set_trytond(database, config_file=config_file) do_import(codes)
import csv from proteus import config, Model, Wizard import random from random import randrange import os import binascii from datetime import datetime, timedelta from decimal import Decimal from decimal import Decimal import time #categories = csv.reader(open('categories.csv', 'r')) config = config.set_trytond( database='toners_catamayo', user='******', language='es_EC.UTF-8', password='******', config_file= '/home/noduxdev/.noduxenvs/nodux34devpymes/etc/nodux34pymes-server.conf') Category = Model.get('product.category') def InitDatabase(): Module = Model.get('ir.module.module') (product, ) = Module.find([('name', '=', 'product')]) Module.install([product.id], config.context) Wizard('ir.module.module.install_upgrade').execute('upgrade') InitDatabase()
def make_sale(): print_payslip = False payslip = request.get_json(force=True) payslip_customer = payslip['customer'] payslip_items = payslip['items'] # create sale order config.set_trytond(DATABASE_NAME, config_file=CONFIG) Party = Model.get('party.party') partylist = Party.find([('id', '=', payslip_customer['customerid'])]) party = partylist[0] Sale = Model.get('sale.sale') sale = Sale() if (sale.id < 0): sale.party = party Paymentterm = Model.get('account.invoice.payment_term') paymentterm = Paymentterm.find([('name', '=', 'cash')]) sale.payment_term = paymentterm[0] for payslip_line in payslip_items: Product = Model.get('product.product') product = Product.find(['id', '=', payslip_line['id']]) line = sale.lines.new(quantity=1) line.product = product[0] line.description = product[0].name line.quantity = 1 line.sequence = 1 sale.save() saleId = sale.id if print_payslip: # max line: Epson.text("012345678901234567890123456789012345678901\n") Epson = printer.Usb(0x04b8, 0x0202) # Print image Epson.text("\n\n") with app.open_resource('logo.gif') as f: Epson.image(f) # Print Header Epson.text("\n\n") Epson.set(align='center') Epson.text("Milliondog - the cosy company\n") Epson.text(time.strftime('%X %x %Z') + "\n") # Print text Epson.set(align='left') Epson.text("\n\n") Epson.text("Pos Beschreibung Betrag \n") Epson.text(" \n") total = decimal.Decimal(0.00) for counter, payslip_line in enumerate(payslip): pos_left = str(counter) + " " + payslip_line[ 'code'] + " " + payslip_line['name'] pos_right = payslip_line['price'] + " CHF\n" Epson.text(pos_left + pos_right.rjust(42 - len(pos_left))) total = total + decimal.Decimal(payslip_line['price']) Epson.text(" \n") Epson.text("------------------------------------------\n") payslip_total = str(total) + " CHF\n" Epson.text("Total : " + payslip_total.rjust(42 - 10)) # Print text Epson.text("\n\n") Epson.set(font='b', align='center') Epson.text("Powered by Semilimes\n") # Cut paper Epson.text("\n\n") Epson.cut() # create response SaleResult = Model.get('sale.sale') saleResult = SaleResult.find(['id', '=', saleId]) list = [] for n in saleResult: list.append({'id': str(n.id), 'party': str(n.party.id)}) return jsonify(result=list)
def main(database, config_file=None): config.set_trytond(database, config_file=config_file) with config.get_config().set_context(active_test=False): do_import()
#!/usr/bin/env python3.8 # not an import from Dolibarr but from my custom system but still putting it here cuz it is easier import sys import codecs import csv from proteus import config, Model, Wizard, Report pcfg = config.set_trytond(database='tryton', config_file='/etc/tryton/trytond.conf') #ENCODING = 'iso-8859-15' ENCODING = 'utf-8' DEBUG = True LOG_STDOUT = True ######################### # misc helper functions # ######################### flog = None if not LOG_STDOUT: flog = open('blv_import.log', 'w') def log(message, print_anyway=False): if LOG_STDOUT: print(message) else: flog.write(message + '\n')
'doc-update-modules.py [options]') parser.add_option('-d', '--database', dest='database', help='Database to get modules installed') parser.add_option('-c', '--config-file', dest='config', help='Config File to update modules') (option, arguments) = parser.parse_args(arguments) # Remove first argument because it's application name arguments.pop(0) return option options = parse_arguments(sys.argv) config = config.set_trytond(options.database, database_type='postgresql', password='******') Module = Model.get('ir.module.module') modules = Module.find([('state', '=', 'installed')]) config = ConfigParser.ConfigParser() f = open(options.config, 'rw') config.readfp(f) f.close() modules = [module.name for module in modules] op = config.options('modules') for module in modules:
#unsued files import FSERP import os from proteus import Model, config conf = config.set_trytond('testdbkitchen', user='******', config_file=os.path.join(os.getcwd(), 'FSERP', 'trytond', 'etc', 'trytond.conf')) Employee = Model.get('company.employee') Company = Model.get('company.company') Department = Model.get('department.department') Designation = Model.get('employee.designation') SalarySettings = Model.get('payroll.salarysettings') Salary = Model.get('payroll.salary') Days = Model.get('attendance.days') ShiftDetails = Model.get('attendance.shiftdetails') Attendance = Model.get('attendance.attendance') Payroll = Model.get('payroll.payroll') Water = Model.get('health_and_hygiene.water_control_test') Pest = Model.get('health_and_hygiene.pest_control_test') HealtReport = Model.get('health_and_hygiene.health_report') # %run psetup.py # from employee_tryton import PayrollManagement # from datetime import datetime,timedelta # payroll=PayrollManagement() # today=datetime.today()+timedelta(days=1)
# # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys sys.path.insert(0, '/home/projects/new/new/') import FSERP import os from proteus import Model, config conf = config.set_trytond( 'testdbkitchen', user='******', config_file='/home/projects/new/new/FSERP/trytond/etc/trytond.conf') # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones.
def set_config(database, config_file): return pconfig.set_trytond(database, config_file=config_file)
def set_config(database): return pconfig.set_trytond(database)
def make_sale(): print_payslip = False payslip = request.get_json(force=True) payslip_customer = payslip['customer'] payslip_items = payslip['items'] # create sale order config.set_trytond(DATABASE_NAME, config_file=CONFIG) Party = Model.get('party.party') partylist = Party.find([('id', '=', payslip_customer['customerid'])]) party = partylist[0] Sale = Model.get('sale.sale') sale = Sale() if (sale.id < 0): sale.party = party Paymentterm = Model.get('account.invoice.payment_term') paymentterm = Paymentterm.find([('name', '=', 'cash')]) sale.payment_term = paymentterm[0] for payslip_line in payslip_items: Product = Model.get('product.product') product = Product.find(['id', '=', payslip_line['id']]) line = sale.lines.new(quantity=1) line.product = product[0] line.description = product[0].name line.quantity = 1 line.sequence = 1 sale.save() saleId = sale.id if print_payslip: # max line: Epson.text("012345678901234567890123456789012345678901\n") Epson = printer.Usb(0x04b8,0x0202) # Print image Epson.text("\n\n") with app.open_resource('logo.gif') as f: Epson.image(f) # Print Header Epson.text("\n\n") Epson.set(align='center') Epson.text("Milliondog - the cosy company\n") Epson.text(time.strftime('%X %x %Z')+"\n") # Print text Epson.set(align='left') Epson.text("\n\n") Epson.text("Pos Beschreibung Betrag \n") Epson.text(" \n") total = decimal.Decimal(0.00) for counter, payslip_line in enumerate(payslip): pos_left = str(counter) + " " + payslip_line['code'] + " " + payslip_line['name'] pos_right = payslip_line['price'] + " CHF\n" Epson.text(pos_left + pos_right.rjust(42 - len(pos_left))) total = total + decimal.Decimal(payslip_line['price']) Epson.text(" \n") Epson.text("------------------------------------------\n") payslip_total = str(total) + " CHF\n" Epson.text("Total : " + payslip_total.rjust(42 - 10)) # Print text Epson.text("\n\n") Epson.set(font='b', align='center') Epson.text("Powered by Semilimes\n") # Cut paper Epson.text("\n\n") Epson.cut() # create response SaleResult = Model.get('sale.sale') saleResult = SaleResult.find(['id', '=', saleId]) list = [] for n in saleResult: list.append({'id': str(n.id), 'party': str(n.party.id)}) return jsonify(result=list)
def import_product_template(filename): f = open(filename, 'rb') config.set_trytond(app.config['TRYTON_DATABASE_NAME'], config_file=app.config['TRYTON_CONFIG_FILE']) try: print('Testing csv file structure for product templates') readertest = csv.DictReader(f) print(readertest.fieldnames) for row in readertest: print(row['name'], row['default_uom'], row['consumable'], row['type'], row['attribute_set'], row['taxes_category'], row['accounts_category'], row['account_category'], row['purchasable'], row['purchase_uom'], row['salable'], row['sale_uom']) f.seek(0) print('Start import') reader = csv.DictReader(f) ProductUOM = Model.get('product.uom') productUOMList = ProductUOM.find([('id', '>', 0)]) Attributeset = Model.get('product.attribute.set') attributesetlist = Attributeset.find([('id', '>', 0)]) Category = Model.get('product.category') categorylist = Category.find([('id', '>', 0)]) for row in reader: print(row['name'], row['default_uom'], row['consumable'], row['type'], row['attribute_set'], row['taxes_category'], row['accounts_category'], row['account_category'], row['purchasable'], row['purchase_uom'], row['salable'], row['sale_uom']) ProductTemplate = Model.get('product.template') Product = Model.get('product.product') duplicate = ProductTemplate.find([('name', '=', row['name'])]) if duplicate: print('Existing product template found: ' + row['name']) else: producttemplate = ProductTemplate() producttemplate.name = row['name'] producttemplate.default_uom = getUOM(productUOMList, row['default_uom']) if row['consumable'] == 'TRUE': producttemplate.consumable = True else: producttemplate.consumable = False producttemplate.type = row['type'] producttemplate.attribute_set = getProductAttributeset( attributesetlist, row['attribute_set']) if row['taxes_category'] == 'TRUE': producttemplate.taxes_category = True else: producttemplate.taxes_category = False if row['accounts_category'] == 'TRUE': producttemplate.accounts_category = True else: producttemplate.accounts_category = False producttemplate.account_category = getProductCategory( categorylist, row['account_category']) Category = Model.get('product.category') category = Category.find([('name', '=', row['account_category'])]) producttemplate.categories.append(category[0]) if row['purchasable'] == 'TRUE': producttemplate.purchasable = True else: producttemplate.purchasable = False producttemplate.purchase_uom = getUOM(productUOMList, row['purchase_uom']) if row['salable'] == 'TRUE': producttemplate.salable = True else: producttemplate.salable = False producttemplate.sale_uom = getUOM(productUOMList, row['sale_uom']) producttemplate.list_price = Decimal(row['list_price']) producttemplate.cost_price = Decimal(row['cost_price']) producttemplate.save() '''product = Product() product.code = '' product.description = '' product.template = producttemplate product.save()''' finally: f.close()
def setUp(self): config.set_trytond(database_type='sqlite')
def import_shipment_in(filename): f = open(filename, 'rb') config.set_trytond(app.config['TRYTON_DATABASE_NAME'], config_file=app.config['TRYTON_CONFIG_FILE']) try: print('Testing csv file structure for product supplier shipment') readertest = csv.DictReader(f) print(readertest.fieldnames) for row in readertest: print(row['code'], row['name'], row['description'], row['quantity'], row['product.template_name'], row['stock.location_warehouse'], row['stock.location_from'], row['stock.location_to'], row['stock.move_effective_date'], row['stock.move_planned_date'], row['stock.move_unit_price'], row['stock.move_cost_price'], row['supplier']) f.seek(0) print('Start import') StockShipmentIn = Model.get('stock.shipment.in') duplicate = StockShipmentIn.find([('reference', '=', filename)]) if duplicate: print('Existing supplier shipment found: ' + str(duplicate[0].id) + ' - ' + filename) raise ValueError( 'Existing supplier shipment found with the same filename: ' + str(duplicate[0].id) + ' - ' + filename) else: stockshipmentin = StockShipmentIn() stockshipmentin.reference = filename Location = Model.get('stock.location') locationlist = Location.find([('id', '>', 0)]) Party = Model.get('party.party') supplier = Party.find([('name', '=', DEFAULT_PARTY_SUPPLIER)], limit=1) PartyAddress = Model.get('party.address') supplier_address = PartyAddress.find( [('party', '=', supplier[0].id)], limit=1) if row['stock.move_planned_date'] == 'today': planned_date = date.today() else: planned_date = date.strptime(row['stock.move_planned_date'], "%Y-%m-%dT") stockshipmentin.planned_date = planned_date if row['stock.move_effective_date'] == 'today': effective_date = date.today() else: effective_date = date.strptime( row['stock.move_effective_date'], "%Y-%m-%dT") stockshipmentin.effective_date = effective_date stockshipmentin.supplier = supplier[0] stockshipmentin.contact_address = supplier_address[0] stockshipmentin.warehouse = getLocation( locationlist, row['stock.location_warehouse']) stockshipmentin.save() ProductUOM = Model.get('product.uom') productUOMList = ProductUOM.find([('id', '>', 0)]) reader = csv.DictReader(f) moves = [] if stockshipmentin.id > 0: StockInventoryLine = Model.get('stock.inventory.line') stockinventoryline = StockInventoryLine() for row in reader: print(row['code'], row['name'], row['description'], row['quantity'], row['product.template_name']) # internal SUP -> IN stockmove = stockinventoryline.moves.new() stockmove.shipment = stockshipmentin Product = Model.get('product.product') product = Product.find([('code', '=', row['code'])]) stockmove.product = product[0] stockmove.quantity = Decimal(row['quantity']) stockmove.uom = getUOM(productUOMList, row['stock.move_uom']) stockmove.from_location = getLocation(locationlist, 'SUP') stockmove.to_location = getLocation( locationlist, row['stock.location_from']) stockmove.planned_date = planned_date stockmove.effective_date = effective_date stockmove.unit_price = Decimal( row['stock.move_unit_price']) if row['stock.move_cost_price'] == 'default': stockmove.cost_price = product[0].cost_price else: stockmove.cost_price = Decimal( row['stock.move_cost_price']) stockmove.save() moves.append(stockmove) finally: f.close()
def connect_database(database, password='******', database_type='postgresql'): return pconfig.set_trytond(database, password=password, config_file=os.environ.get( 'TRYTOND_CONFIG', 'trytond.conf'))
def import_customers(filename): f = open(filename, 'rb') config.set_trytond(app.config['TRYTON_DATABASE_NAME'], config_file=app.config['TRYTON_CONFIG_FILE']) try: print('Testing csv file structure for customers') readertest = csv.DictReader(f) for row in readertest: print(row['first_name'], row['last_name'], row['company_name'], row['address'], row['city'], row['country'], row['state'], row['zip'], row['phone'], row['mobile'], row['email'], row['website']) f.seek(0) print('Start import') reader = csv.DictReader(f) for row in reader: countrycode = row['country'] Lang = Model.get('ir.lang') (en, ) = Lang.find([('code', '=', 'en_US')]) Country = Model.get('country.country') (cc, ) = Country.find([('code', '=', countrycode)]) print(row['first_name'], row['last_name'], row['company_name'], row['address'], row['city'], row['country'], row['state'], row['zip']) Party = Model.get('party.party') party = Party() if party.id < 0: party.name = row['company_name'] party.lang = en party.addresses[ 0].name = row['first_name'] + ' ' + row['last_name'] party.addresses[0].street = row['address'] party.addresses[0].streetbis = None party.addresses[0].zip = row['zip'] party.addresses[0].city = row['city'] party.addresses[0].country = cc if row['state'] is not None: try: Subdivision = Model.get('country.subdivision') if countrycode == 'GB': (subdivision, ) = Subdivision.find([ ('name', '=', row['state']), ('country', '=', 13) ]) else: (subdivision, ) = Subdivision.find([ ('code', 'like', row['country'] + '-' + row['state'] + '%') ]) party.addresses[0].subdivision = subdivision except ValueError: print('***** Error: could not find subdivision: ' + row['state'] + ' for country ' + row['country']) if row['invoice'] == 'TRUE': party.addresses[0].invoice = True else: party.addresses[0].invoice = False if row['delivery'] == 'TRUE': party.addresses[0].delivery = True else: party.addresses[0].delivery = False party.addresses[0] party.save() # Contact contactmechanismlist = [] if row['phone'] is not None: ContactMechanism = Model.get('party.contact_mechanism') contactmechanism = ContactMechanism() contactmechanism.party = party contactmechanism.type = 'phone' contactmechanism.value = row['phone'] contactmechanismlist.append(contactmechanism) contactmechanism.save() if row['mobile'] is not None: ContactMechanism = Model.get('party.contact_mechanism') contactmechanism = ContactMechanism() contactmechanism.party = party contactmechanism.type = 'mobile' contactmechanism.value = row['mobile'] contactmechanismlist.append(contactmechanism) contactmechanism.save() if row['email'] is not None: ContactMechanism = Model.get('party.contact_mechanism') contactmechanism = ContactMechanism() contactmechanism.party = party contactmechanism.type = 'email' contactmechanism.value = row['email'] contactmechanismlist.append(contactmechanism) contactmechanism.save() if row['website'] is not None: ContactMechanism = Model.get('party.contact_mechanism') contactmechanism = ContactMechanism() contactmechanism.party = party contactmechanism.type = 'website' contactmechanism.value = row['website'] contactmechanism.save() contactmechanismlist.append(contactmechanism) party.contact_mechanism = contactmechanismlist finally: f.close()
"order by r.NRO_MEDIDOR ") cur.execute(sql) for row in cur: mensaje='Importando Medidor Nro. ' print mensaje, row[0] new_med = Model.get('sigcoop_medidor.medidor')() new_med.servicio = 'Agua' new_med.name = str(row[0]).strip() #new_med.numero_serie = str(row[1]).strip() new_med.marca = str(row[2]).strip() new_med.cantidad_esferas = str(row[1]).strip() new_med.modelo = str(row[2]).strip() new_med.save() if __name__ == "__main__": from proteus import config c = config.set_trytond( database_name="sigcoop", database_type="postgresql", password="******", config_file="/home/fer/tryton/trytond.conf" ) crear_medidores()
def load_internal_shipment(filename): f = open(filename, 'rb') config.set_trytond(app.config['TRYTON_DATABASE_NAME'], config_file=app.config['TRYTON_CONFIG_FILE']) try: print('Testing csv file structure for internal shipment') readertest = csv.DictReader(f) for row in readertest: print(row['code'], row['name'], row['description'], row['quantity'], row['product.template_name'], row['stock.location_from'], row['stock.location_to'], row['stock.move_effective_date'], row['stock.move_planned_date'], row['stock.move_unit_price'], row['stock.move_cost_price']) f.seek(0) print('Start import') StockShipmentInternal = Model.get('stock.shipment.internal') stockshipmentinternal = StockShipmentInternal() stockshipmentinternal.reference = filename LocationFrom = Model.get('stock.location') locationfrom = LocationFrom.find([('code', '=', row['stock.location_from'])]) stockshipmentinternal.from_location = locationfrom[0] LocationTo = Model.get('stock.location') locationto = LocationTo.find([('code', '=', row['stock.location_to'])]) stockshipmentinternal.to_location = locationto[0] stockshipmentinternal.effective_date = date.today() stockshipmentinternal.planned_date = date.today() stockshipmentinternal.save() reader = csv.DictReader(f) moves = [] if stockshipmentinternal.id > 0: for row in reader: print(row['code'], row['name'], row['description'], row['quantity'], row['stock.location_from'], row['stock.location_to']) StockMove = Model.get('stock.move') stockmove = StockMove() stockmove.shipment = stockshipmentinternal Product = Model.get('product.product') product = Product.find([('code', '=', row['code'])]) stockmove.product = product[0] stockmove.quantity = int(row['quantity']) stockmove.from_location = locationfrom[0] stockmove.to_location = locationto[0] if row['stock.move_effective_date'] == 'today': effective_date = date.today() else: effective_date = date.strptime( row['stock.move_effective_date'], "%Y-%m-%dT") stockmove.effective_date = effective_date if row['stock.move_planned_date'] == 'today': planned_date = date.today() else: planned_date = date.strptime( row['stock.move_planned_date'], "%Y-%m-%dT") stockmove.planned_date = planned_date stockmove.unit_price = Decimal(row['stock.move_unit_price']) if row['stock.move_cost_price'] == 'default': stockmove.cost_price = product[0].cost_price else: stockmove.cost_price = Decimal( row['stock.move_cost_price']) stockmove.save() moves.append(stockmove) finally: f.close()
#!/bin/python import os from proteus import config, Model, Wizard, Report DB_NAME = os.environ.get('DATABASE_NAME') CONFIG_FILE_PATH = '/tryton/config.ini' INSTALLED = [] FAILED = [] SKIPPED = [] BLACKLIST = ["product_classification_taxonomic", "purchase_request"] config = config.set_trytond(DB_NAME, config_file=CONFIG_FILE_PATH) def main(): Module = Model.get("ir.module") not_installed_modules = Module.find([("state", "!=", "installed")]) for not_installed_module in not_installed_modules: # double check in case this module was installed as dependency if not_installed_module.state != u"installed": install_module(not_installed_module) print 'Done. \n' \ 'Installed modules: \n%s\n' \ 'Skipped modules: \n%s\n' \
def setup(database, language, industry): """ This is the setup command for Kalenis LIMS """ click.echo('Setup Kalenis for %s...' % industry) click.echo('Creating user config file...') config_file = get_config() click.echo('Creating the database...') process = subprocess.run(['createdb', database], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if process.returncode != 0: err = process.stdout.decode('utf-8') if len(err) == 0: err = process.stderr.decode('utf-8') click.echo(click.style(err.format(ERROR_COLOR), fg=ERROR_COLOR)) return process.returncode click.echo('Initializing the database...') subprocess.run( ['trytond-admin', '-d', database, '-c', config_file, '--all']) click.echo('Installing modules...') subprocess.run([ 'trytond-admin', '-d', database, '-c', config_file, '-u', ' '.join(MODULES[industry]), '--activate-dependencies' ]) if language == 'es': click.echo('Loading translations for spanish language...') config.set_trytond(database, config_file=config_file) User = Model.get('res.user') Lang = Model.get('ir.lang') lang, = Lang.find([('code', '=', language)]) lang.translatable = True lang.save() subprocess.run( ['trytond-admin', '-d', database, '-c', config_file, '--all']) user = User.find()[0] user.language = lang user.save() click.echo('Downloading front-end...') front_end_dir = '%s/kalenis_front_end' % os.environ.get('HOME', '') front_end_file = 'frontend_dist_5.6.tar.gz' Path(front_end_dir).mkdir(exist_ok=True) subprocess.run([ 'wget', 'https://downloads.kalenislims.com/%s' % front_end_file, '-O', '%s/%s' % (front_end_dir, front_end_file) ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) subprocess.run([ 'tar', 'xzvf', '%s/%s' % (front_end_dir, front_end_file), '--directory', front_end_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) click.echo( click.style( 'Congratulations, the setup process has finished ok. Now you can ' 'execute "kalenis-cli run" to start Kalenis LIMS server'.format( OK_COLOR), fg=OK_COLOR))
import csv from proteus import config, Model, Wizard database = 'database_name' user = '******' password = '******' config_file = 'path_to_file_nodux_config' config = config.set_trytond(database=database, user=user, language='es_EC.UTF-8', password=password, config_file=config_file) usuarios = csv.reader(open('usuarios.csv', 'r')) Lang = Model.get('ir.lang') Company = Model.get('company.company') Employe = Model.get('company.employee') def LoadUser(): User = Model.get('res.user') users = csv.reader(open('usuarios.csv', 'r')) header = True inicio = 1 if (inicio == 1): inicio = 2 for i in range(inicio - 1): users.next()
# -*- coding: utf-8 -*- from flask_shop import app, models from flask import Flask, jsonify, request from proteus import config, Model, Wizard, Report from datetime import date, datetime from decimal import Decimal import time import decimal import json import urlparse from escpos import * import psycopg2 CONFIG = app.config['TRYTON_CONFIG_FILE'] DATABASE_NAME = app.config['TRYTON_DATABASE_NAME'] config.set_trytond(DATABASE_NAME, config_file=CONFIG) def getProductDirect(hideoutofstockitems): category_condition = 'and 1 = 1 ' size_condition = 'and 1 = 1 ' outofstock_condition = 'and 1 = 1 ' if hideoutofstockitems == 'True': outofstock_condition = "and product.attributes like '%\"available\": true%' " con = None result = None try: result = urlparse.urlparse(app.config['SQLALCHEMY_DATABASE_URI']) con = psycopg2.connect(database=result.path[1:], host=result.hostname, user=result.username,