Ejemplo n.º 1
0
 def __init__(self, user='******', pwd='admin', dbname='openerp',
     uri='http://localhost', port=8069, debug=False, **kwargs):
     OOOP.__init__(self, user=user, pwd=pwd, dbname=dbname, uri=uri,
                    port=port, debug=debug, **kwargs)
     self.transaction_id = False
     self.transsock = xmlrpclib.ServerProxy('%s:%i/xmlrpc/ws_transaction'
                                            % (self.uri, self.port))
Ejemplo n.º 2
0
def find_and_fix_soci_record(query, output):
    '''
    Find 'socis' that have no record in somenergia_soci and create one.
    '''
    O = OOOP(**configdb.ooop)
    with io.open(query) as f:
        query = f.read()

    step("Connecting to the ERP database...")
    db = psycopg2.connect(**configdb.psycopg)

    with db.cursor() as cursor:
        try:
            cursor.execute(query)
        except KeyError as e:
            fail("Missing variable '{key}'. Specify it in the YAML file or by using the --{key} option"
                .format(key=e.args[0]))
        erp_data =  nsList(cursor)

    erp_data = [dict(data) for data in erp_data]
    erp_ids = set(i['ids'] for i in erp_data)
    erp_soci = set(i['ref'] for i in erp_data)
    for partner_id in erp_ids:
        get_or_create_somenergia_soci(O, partner_id)

    with open(output, "w") as loadsocis:
         writer = csv.writer(loadsocis, delimiter = "\t")
         writer.writerows(zip(erp_ids, erp_soci))
Ejemplo n.º 3
0
 def __init__(self,
              user='******',
              pwd='admin',
              dbname='openerp',
              uri='http://localhost',
              port=8069,
              debug=False,
              **kwargs):
     OOOP.__init__(self,
                   user=user,
                   pwd=pwd,
                   dbname=dbname,
                   uri=uri,
                   port=port,
                   debug=debug,
                   **kwargs)
     self.transaction_id = False
     self.transsock = xmlrpclib.ServerProxy('%s:%i/xmlrpc/ws_transaction' %
                                            (self.uri, self.port))
Ejemplo n.º 4
0
 def validate_params(self, dbname, user, pwd, uri):
     """docstring for validate_conection"""
     try:
         o = OOOP(dbname=dbname, user=user, pwd=pwd, uri=uri)
     except:
         raise ErrorValidatingConection("Can't connect with openerp")
         
     module = o.IrModuleModule.filter(name='kooltuo_module')
     if not module or module[0].state <> 'installed':
         raise ErrorValidatingConection("The kooltuo module isn't installed")
     else:
         return True
Ejemplo n.º 5
0
def update_ERP(configdb, socis, data_baixa, codi, filename):
    '''
    Update 'data_baixa_soci' field in ERP.
    '''
    O = OOOP(**configdb.ooop)
    Partner = O.ResPartner
    Soci = O.SomenergiaSoci

    step("Update all Non-Active socis in {}", filename)
    baixas_id_no_activas = [Soci.search([((codi), "like", soci), ("active", "=", False)]) for soci in socis if Soci.search([((codi), "like", soci), ("active", "=", False)]) ]
    all_inactive_categories = [Soci.read(item)['category_id'] for idlist in baixas_id_no_activas for item in idlist]
    for soci in xrange(len(all_inactive_categories)):
        keep_inactive_categories = [category for category in all_inactive_categories[soci] if category <> 8]
        Soci.write(baixas_id_no_activas[soci] , {'active': False, 'baixa': True , 'category_id': [(6, 0, keep_inactive_categories)], 'data_baixa_soci': data_baixa[soci] } )
Ejemplo n.º 6
0
def update_dades_erp(data):

    O = OOOP(**dbconfig.ooop)
    for d in data:

        potencia = float(d[0]) * 0.001
        id_polissa = int(d[1])
        data_inici = d[2]
        potencia_activa = float(d[3]) * 0.001
        data_firma = O.GiscedataPolissa.read(
            id_polissa, ['data_firma_contracte'])['data_firma_contracte']

        step(
            "Actualizando el id polissa {} con la nueva potencia {}",
            id_polissa,
            potencia,
        )
        p = O.GiscedataPolissa.read(id_polissa)
        O.GiscedataPolissa.send_signal([id_polissa], 'modcontractual')
        O.GiscedataPolissa.write(id_polissa, {'potencia': potencia})
        observaciones_value = """
                                Data %s: Canvi potencia %s a potencia %s per
                                dades no coincidents entre dades distribuidora i ERP
                                """ % (data_inici, potencia_activa, potencia)

        step("Generando periodos para el id polissa {}", id_polissa)
        O.GiscedataPolissa.generar_periodes_potencia([id_polissa])
        step("Modificando polissa {}", p['name'])
        parameters = {
            'accio': 'modificar',
            'polissa_id': id_polissa,
            'observacions': observaciones_value,
            'data_inici': data_inici,
            'data_firma_contracte': data_firma
        }
        # en accio nou hay que tener en cuenta las fechas de data_inici y data_final del anterior registro
        # parameters = {'accio':'nou','polissa_id':id_polissa,'observacions':observaciones_value,'data_inici':'2019-01-22','data_firma_contracte':data_firma,'data_final':'2020-01-22'}
        wizard_id = O.GiscedataPolissaCrearContracte.create(parameters)
        O.GiscedataPolissaCrearContracte.action_crear_contracte([wizard_id],
                                                                {})
        success(
            "Polissa {} con potencia antigua {} actualizada con potencia distri {}",
            p['name'], potencia_activa, potencia)
Ejemplo n.º 7
0
def conn_ooop():
    """Connection OpenERP throught OOOP"""

    lang = LOCALES.get(get_language(), 'en_US')
    try:
        #o = OOOP(user='******',pwd='admin',dbname='oerp6_zoook',uri='http://localhost',port=8069,protocol='xmlrpc')
        #o = OOOP(user='******',pwd='admin',dbname='oerp6_zoook',uri='localhost',port=8071,protocol='pyro')
        conn = OOOP(
            user=OERP_CONF['username'],
            pwd=OERP_CONF['password'],
            dbname=OERP_CONF['dbname'],
            uri=OERP_CONF['uri'],
            port=OERP_CONF['port'],
            protocol=OERP_CONF['protocol'],
            lang=lang,
            debug=DEBUG,
        )
        return conn
    except:
        return False
Ejemplo n.º 8
0
 def __init__(self,
              dbname="openerp",
              user="******",
              pwd="admin",
              uri="http://localhost"):
     print "Starting openerp connector"
     self.ooop = OOOP(dbname=dbname, user=user, pwd=pwd, uri=uri)
     rec = self.ooop.KooltuoApplication.filter(name=record_name())
     print "\t buscando: %s" % record_name()
     if not rec:
         print "\t %s registro no encontrado"
         rec = self.ooop.KooltuoApplication.new()
         rec.computer_name = machinename()
         rec.name = record_name()
         rec.save()
         print "registro creado"
     else:
         rec = rec[0]
     self.oapp_id = rec
     print "end Starting openerp connector"
Ejemplo n.º 9
0
def generate_pdf_OOOP(model, id):
    from ooop import OOOP
    oo = OOOP(**configdb.ooop)
    return oo.report(model, [id])
Ejemplo n.º 10
0
from ooop import OOOP

o = OOOP(dbname="testv6")
partners = o.ResPartner.all()
for partner in partners:
    print "id: %d, name: %s" % (partner._ref, partner.name)
Ejemplo n.º 11
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from ooop import OOOP
import configdb
import os
from datetime import datetime, timedelta
from utils import *

O = OOOP(**configdb.ooop)


def dump(polissa_id, lects, header, n):
    try:
        print '------------ {header} ------ [{polissa_id}] ---------'.format(
            **locals())
        for idx in range(n):
            print '[{idx}] {date} {periode} {lectura} {origen}'.format(
                **{
                    'idx': idx,
                    'date': lects[idx]['name'],
                    'periode': lects[idx]['periode'][1],
                    'lectura': lects[idx]['lectura'],
                    'origen': lects[idx]['origen_id'][1]
                })
    except Exception as e:
        pass


def get_contract_amount_mean(polissa_id):
    def months_between(d1, d2):
        d1 = datetime.strptime(d1, "%Y-%m-%d")
conn_str = 'mongodb://{username}:{password}@{hostname}/{dbname}?replicaSet={replica}' \
    if 'replica' in config['mongodb'] \
    else 'mongodb://{username}:{password}@{hostname}/{dbname}'

db = MongoClient(conn_str.format(
    **{'username': config['mongodb']['username'],
       'password': config['mongodb']['password'],
       'hostname': config['mongodb']['hostname'],
       'port': config['mongodb']['port'],
       'dbname': config['mongodb']['dbname'],
       'replica': config['mongodb'].get('replica'),
}))

O = OOOP(dbname=config['erp']['dbname'],
         user=config['erp']['username'],
         pwd=config['erp']['password'],
         port=config['erp']['port'],
         uri=config['erp']['hostname'])

cch_stats = CCHStats(db, O)

today = datetime.datetime.today()
today_sof = datetime.datetime(today.year, today.month, today.day, 0, 0, 0)

out = {name: {} for name in NAMES}
results = []
for name in NAMES:
    results.append(run_test(name, cch_stats.get_n_entries,[name]))
    results.append(run_test(name, cch_stats.get_n_entries,[name, today_sof]))
    results.append(run_test(name, cch_stats.get_storage,[name]))
    results.append(run_test(name, cch_stats.get_providers,[name]))
Ejemplo n.º 13
0
 def test_ooop_instance(self):
     n = OOOP(dbname='test')
     self.assertEquals(n.__dict__.has_key('ResPartner'), True)
     self.assertEquals(n.__dict__.has_key('ResPartnerAddress'), True)
            F1['fechaHasta'] = fechaHasta_.childNodes[0].nodeValue

            return F1

        return None

    except Exception, e:
        print 'Error en la lectura del fitxer (%d) de la línia (%d)' % (
            fitxer_xml, F1_linia_failed_id)
        raise e


# ERP
O = None
try:
    O = OOOP(**dbconfig.ooop)
except Exception, e:
    print 'Failed initializing OpenERP connection'
    print e
    sys.exit()

# Cercar les línes d'importació de F1 en que s'ha donat l'error d'importació:
vals_search = [('state', '=', 'erroni'), ('info', 'like', 'La tarifa')]
F1_linia_failed_ids = O.GiscedataFacturacioImportacioLinia.search(vals_search)

if not F1_linia_failed_ids:
    print 'No hi ha línies amb errors d\'importació'
    sys.exit()

# Processar línies amb errors d'importació
print 'Processant %d línies amb errors d\'importació' % len(
    print "Per ara no refacturem"


dbcur = None
try:
    dbconn = psycopg2.connect(**configdb.psycopg)
    dbcur = dbconn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
except Exception, ex:
    print "Unable to connect to database"
    raise ex

O = None
try:
    O = OOOP(dbname=configdb.ooop['dbname'],
             user=configdb.ooop['user'],
             pwd=configdb.ooop['pwd'],
             port=configdb.ooop['port'],
             uri=configdb.ooop['uri'])
except Exception, ex:
    raise ex

lot_id = O.GiscedataFacturacioLot.search([('state', '=', 'obert')])[0]
lot_name = O.GiscedataFacturacioLot.read([lot_id], ['name'])[0]['name']
lots = [lot_name]

try:
    factures = get_factures_0energyLines(dbcur, lots)
    for factura in factures:
        if not factura['energia_kwh']:
            print int(factura['polissa_id'])
            eliminar_factures(O, int(factura['polissa_id']))
Ejemplo n.º 16
0
def main():
    url = 'http' + (secure and 's' or '') + '://' + server
    o = OOOP(user=username, pwd=password, dbname=dbname, uri=url, port=port)

    url = 'http' + (secure and 's' or '') + '://' + server + ':' + port
    common = xmlrpclib.ServerProxy(url + '/xmlrpc/common')
    uid = common.login(dbname, username, password)
    object = xmlrpclib.ServerProxy(url + '/xmlrpc/object')

    print dbname
    context = {}
    context['magento_app'] = MAGENTO_APP

    with ProductImages(MGN_URL, MGN_APIUSER,
                       MGN_APIPASSWORD) as product_image_api:
        args = [('magento_exportable', '=', True)]
        product_ids = object.execute(dbname, uid, password, 'product.product',
                                     'search', args)
        print len(product_ids)

        for product_id in product_ids:
            args = [('oerp_id', '=', product_id), ('model_id', '=', 109)]
            product = object.execute(dbname, uid, password,
                                     'magento.external.referential', 'search',
                                     args)
            if len(product) > 0:
                prod = object.execute(dbname, uid, password,
                                      'magento.external.referential', 'read',
                                      product, ['mgn_id', 'oerp_id'])
                try:
                    product_images = product_image_api.list(prod[0]['mgn_id'])
                    for product_image in product_images:
                        if 'url' in product_image:  #magento == 1.3
                            url = product_image['url']
                        else:  #magento < 1.5
                            url = product_image['filename']

                        splited_url = url.split('/')
                        filename = splited_url[len(splited_url) - 1]

                        imgs = o.ProductImages.filter(filename=filename)

                        for i in imgs:
                            if product_image['exclude'] == '1':
                                i.magento_exclude = True
                            else:
                                i.magento_exclude = False
                            if 'image' in product_image['types']:
                                i.magento_base_image = True
                            else:
                                i.magento_base_image = False
                            if 'small_image' in product_image['types']:
                                i.magento_small_image = True
                            else:
                                i.magento_small_image = False
                            if 'thumbnail' in product_image['types']:
                                i.magento_thumbnail = True
                            else:
                                i.magento_thumbnail = False

                            i.save()
                            print "[UPDATE] %s Mgn - Image filename %s" % (
                                prod[0]['mgn_id'], filename)

                except:
                    print "[ALERT] Not update images %s" % (prod[0]['mgn_id'])
                    continue

    return True
Ejemplo n.º 17
0
from models import F1ImportError, \
    codigoOrigen_to_O, \
    O_to_codigoOrigen
from errors import IMP_ERRORS

DB_NAME = ''
DB_USER = ''
DB_PASSWORD = ''
DB_URI = ''
DB_PORT = 8069

START_DATE = '2014-01-01'

O = OOOP(dbname=DB_NAME,
         user=DB_USER,
         pwd=DB_PASSWORD,
         port=int(DB_PORT),
         uri=DB_URI)
e_search = [('state', '=', 'erroni'), ('info', 'like', 'Divergència'),
            ('cups_id', '!=', False), ('data_carrega', '>', START_DATE)]
e_ids = O.GiscedataFacturacioImportacioLinia.search(e_search)
fields_to_read = ['cups_id']
e_cups = O.GiscedataFacturacioImportacioLinia.read(e_ids, fields_to_read)
cups_ids = {}
for e in e_cups:
    cups_id = e['cups_id'][0]
    cups_ids.setdefault(cups_id, [])
    bisect.insort(cups_ids[cups_id], e['id'])


def check_is_origen(e, origen):
Ejemplo n.º 18
0
from ooop import OOOP
print "###################### START ###########################################"
O = OOOP(dbname="test", port=8050)
print O.ProductProduct.fields_get()
product = O.ProductProduct.get(1)
print product.name
print product.categ_id.name
print "###################### END #############################################"