Esempio n. 1
0
    def get_client(self, database=False):
        """You should not use this function directly, you sould call
        get_connection"""

        _logger.info('Getting client for contract %s with database %s' % (
            self.name, database))
        self.ensure_one()
        try:
            if not database:
                return Client(self.server_host)
            else:
                return Client(
                    self.server_host,
                    db=database,
                    user=self.user,
                    password=self.contract_id)
        except Exception, e:
            raise Warning(_(
                "Unable to Connect to Server. Please contact your support "
                "provider.\n"
                "This probably means that your contact is expired!\n"
                "Other possible reasons: Module 'web_support_server' is not "
                "installed or user '%s' do not exists or there is no active "
                "contract with id '%s' on database '%s'.\n\n"
                "This is what we get: %s") % (
                    self.user, self.contract_id, database, e)
            )
Esempio n. 2
0
 def remove_tasks_for_patient(patient_id,
                              activity_models=[],
                              database='openeobs_quality_assurance_db',
                              user='******', password='******'):
     """
     Remove a specific task for a patient
     :param patient_id: The patient to remove tasks for
     :param activity_models: The activity model to remove
     :param database: database to run against
     :param user: the username to run as
     :param password: password for username
     """
     odoo_client = Client('http://localhost:8069', db=database,
                          user=user, password=password)
     activity_api = odoo_client.model('nh.activity')
     spells = activity_api.search([
         ['state', '=', 'started'],
         ['data_model', '=', 'nh.clinical.spell'],
         ['patient_id', '=', patient_id]
     ])
     activities = activity_api.search([
         ['data_model', 'in', activity_models],
         ['parent_id', 'in', spells]
     ])
     activity_api.unlink(activities)
Esempio n. 3
0
    def __init__(self, driver, config):
        self.driver = driver
        self.setup(config)

        self.url = util.parse_url(self.config["url"])

        if self.url is None:
            raise error.OdoleniumError("'{}' isn't valid URL".format(
                self.config["url"]))

        log.info("Setting up XML-RPC connection to {}".format(self.urlgen()))
        try:
            self.rpc = Client(self.url.geturl())
            log.info("Connection succeed")
        except:
            log.error("Connection failed")
            raise ConnectionRefusedError(
                "Can't connect to Odoo server")  # NoQA

        self.ver = self.rpc.db.server_version()
        log.info("Found version {} Odoo server".format(self.ver))

        if self.ver not in versions:
            raise error.OdoleniumError("Unsupported Odoo version '{}'".format(
                self.ver))
Esempio n. 4
0
    def dispatch(self, parsed_args, raw_args):
        from os import path
        from getpass import getpass

        from erppeek import Client

        from gronexctl.module_set import ModuleSet

        password = getpass()

        for yml in parsed_args.yml:
            client = Client(
                parsed_args.host_string,
                db=parsed_args.database,
                user=parsed_args.username,
                password=password,
            )

            ms = ModuleSet(
                path.join(
                    parsed_args.directory,
                    "{0}.yml".format(yml),
                ))

            ms.resolve()

            for l in ms.absolute_addon_dependencies:
                client.install(*l)
 def patient_helper(patient_id, database="openeobs_quality_assurance_db", user="******", password="******"):
     """
     use a patient id to get id for do a barcode scan
     :param patient_id: ID of patient to do foo
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client("http://localhost:8069", db=database, user=user, password=password)
     return odoo_client.model("nh.eobs.api").get_patients([int(patient_id)])
    def complete_stand_in(task_id, database="openeobs_quality_assurance_db", user="******", password="******"):
        """
        Complete a stand in task
        :param database: The database to complete stand in on
        :param user: User to complete stand in as
        :param password: Password for the user
        """
        odoo_client = Client("http://localhost:8069", db=database, user=user, password=password)

        activity_api = odoo_client.model("nh.activity")
        activity_api.complete(task_id)
Esempio n. 7
0
 def patient_helper(patient_id, database='openeobs_quality_assurance_db',
                    user='******', password='******'):
     """
     use a patient id to get id for do a barcode scan
     :param patient_id: ID of patient to do foo
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client('http://localhost:8069', db=database,
                          user=user, password=password)
     return odoo_client.model('nh.eobs.api').get_patients([int(patient_id)])
 def task_helper(task_id, database='openeobs_quality_assurance_db',
                 user='******', password='******'):
     """
     use a task id to get id for do a barcode scan
     :param task_id: ID of Task to do foo
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client('http://localhost:8069', db=database, user=user,
                          password=password)
     return odoo_client.model('nh.eobs.api').get_activities([task_id])
Esempio n. 9
0
    def complete_stand_in(task_id, database='openeobs_quality_assurance_db',
                          user='******', password='******'):
        """
        Complete a stand in task
        :param database: The database to complete stand in on
        :param user: User to complete stand in as
        :param password: Password for the user
        """
        odoo_client = Client('http://localhost:8069', db=database,
                             user=user, password=password)

        activity_api = odoo_client.model('nh.activity')
        activity_api.complete(task_id)
 def patient_scan_helper(patient_id, database="openeobs_quality_assurance_db", user="******", password="******"):
     """
     use a patient id to get id for do a barcode scan
     :param patient_id: ID of patient to do foo
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client("http://localhost:8069", db=database, user=user, password=password)
     patient_api = odoo_client.model("nh.clinical.patient")
     patient_record = patient_api.read(
         patient_id, ["other_identifier", "patient_identifier", "display_name", "current_location_id"]
     )
     return patient_record
 def add_high_risk_observation(patient_id, database="openeobs_quality_assurance_db", user="******", password="******"):
     """
     Add an observation that gives medium clinical risk due to 3in1
     :param patient_id: The patient to do observation for
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client("http://localhost:8069", db=database, user=user, password=password)
     activity_api = odoo_client.model("nh.activity")
     ews_api = odoo_client.model("nh.clinical.patient.observation.ews")
     ews_activity_id = ews_api.create_activity({}, {"patient_id": patient_id})
     activity_api.submit(ews_activity_id, HIGH_RISK_SCORE_11_EWS_DATA)
     activity_api.complete(ews_activity_id)
Esempio n. 12
0
 def test__measures_from_date__whenEmpty(self):
     c = Client(**config.erppeek)
     meter = '88300864'
     measures = measures_from_date(c, meter,
         beyond="2016-08-02 09:00:00",
         upto  ="2016-08-02 12:00:00")
     self.assertTimeSeriesEqual(measures,[])
Esempio n. 13
0
 def test__quarterly_filter_time(self):
     c = Client(**config.erppeek)
     meter = '44711885'
     measures = measures_from_date(c, meter,
         beyond="2020-09-09 08:00:00",
         upto  ="2020-09-09 09:00:00")
     self.assertListEqual(measures,[])
Esempio n. 14
0
def send_emails(**kwargs):
    setup_log('send_emails', '/tmp/send_emails.log')
    logger = logging.getLogger('send_emails'); print kwargs
    c = Client(
        '{0}:{1}'.format(kwargs['server'], kwargs['port']),
        kwargs['database'],
        kwargs['user'],
        kwargs['password']
    )
    if not c:
        logger.error('Bad ERP connection')
        return
    # lot_ids = get_current_lot(c)
    lot_ids = get_lots(c)
    print lot_ids
    for lot_id in lot_ids:
        lot = c.GiscedataFacturacioLot.get(lot_id)
        logger.info('*** Sending emails of lot {0}:'.format(lot.name))

        context = {'active_id': lot.id}
        wiz = c.WizardFacturesPerEmail.create({},context=context)
        logger.info(wiz.info)
        sys.stdout.write(wiz.info)
        sys.stdout.write('\n')
        res = c.WizardFacturesPerEmail.action_enviar_lot_per_mail([wiz.id], context=context)
        wiz = c.WizardFacturesPerEmail.get(wiz.id)
        logger.info(wiz.info)
        sys.stdout.write(wiz.info)
        sys.stdout.write('\n')
def generate_report(year, month, agent, sequence):
    report_name = 'SI_{}_{}_{}{}_{}.xml'.format(
        agent, 'E',
        year,
        month,
        sequence,
    )
    report_name_csv = 'SI_{}_{}_{}{}_{}.csv'.format(
        agent, 'E',
        year,
        month,
        sequence,
    )

    date_time_start = datetime.strptime(str(year) + '-' + str(month) + '-01', '%Y-%m-%d')
    last_day_month = str(calendar.monthrange(int(year), int(month))[1])
    date_time_end = datetime.strptime(str(year) + '-' + str(month) + '-' + last_day_month, '%Y-%m-%d')
    print {'file_type': 'SI', 'start_date': date_time_start.strftime('%Y-%m-%d'),  'end_date': date_time_end.strftime('%Y-%m-%d')}	

    c = Client(**dbconfig.erppeek)
    step("Collecting data...")
    wiz = c.WizardCnmcXmlReport.create({'file_type': 'SI',
        'start_date': date_time_start.strftime('%Y-%m-%d'),
        'end_date': date_time_end.strftime('%Y-%m-%d')
    })
    wiz.action_generate_file()

    step("Writing {}...".format(report_name))
    with open("/tmp/" + report_name, 'w') as f:
        f.write(base64.b64decode(wiz.file))

    step("Writing {}...".format(report_name_csv))
    with open("/tmp/" + report_name_csv, 'w') as f:
        f.write(base64.b64decode(wiz.file_csv))
Esempio n. 16
0
def main(fitxer, lot_facturacio, data_activacio):
    path, filename = os.path.split(fitxer)
    log_file = os.path.join(path, '{0}_{1}'.format('LOG', filename))
    logger = logging.getLogger('myapp')
    hdlr = logging.FileHandler(log_file)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    logger.info('#######Start now {0}'.format(datetime.today()))
    polisses = []
    with open(fitxer, 'r') as fpc:
        polreader = csv.reader(fpc)
        for lin in polreader:
            polisses.append(lin)

    vals = {'lot_facturacio': lot_facturacio}
    vals_mod = {'facturacio': 1}
    # data_activacio = '2015-07-01'

    O = Client('http://localhost:%d' % port, dbname, user, pwd)

    for pol in polisses:
        pol_id = int(pol[0])
        try:
            polissa = O.GiscedataPolissa.get(pol_id)
            if polissa.facturacio == 1:
                logger.warning(
                    '{} ({}) WARNING It is already monthly\n'.format(
                        pol[1], pol_id))
                continue
            polissa.send_signal('modcontractual')
            polissa.write(vals_mod)
            wz_crear_mc_obj = O.GiscedataPolissaCrearContracte
            ctx = {'active_id': pol_id, 'lang': 'es_ES'}
            params = {'duracio': 'actual', 'accio': 'nou'}

            wiz = wz_crear_mc_obj.create(params, ctx)
            wiz_id = wiz.id
            #wiz = wz_crear_mc_obj.get(wiz_id, ctx)
            res = wz_crear_mc_obj.onchange_duracio([wiz_id], data_activacio,
                                                   wiz.duracio, ctx)
            if res.get('warning', False):
                logger.warning('%s (%s) WARNING modcon no creada\n' %
                               (pol[1], pol_id))
                polissa.send_signal('undo_modcontractual')
            else:
                wiz.write({
                    'data_final': res['value']['data_final'] or '',
                    'data_inici': data_activacio
                })
                wiz.action_crear_contracte()
                logger.info('%s (%s) OK\n' % (pol[1], pol_id))
                polissa.write(vals)
        except Exception, e:
            logger.error('%s (%s) ERROR actualizando póliza: %s\n' %
                         (pol[1], pol_id, e))
            polissa.send_signal('undo_modcontractual')

        sys.stdout.flush()
Esempio n. 17
0
 def get_client(self, database=False):
     self.ensure_one()
     try:
         if not database:
             return Client('http://%s' % (self.server_host))
         else:
             return Client('http://%s' % (self.server_host),
                           db=database,
                           user=self.user,
                           password=self.number)
     except Exception, e:
         raise Warning(
             _("Unable to Connect to Server. Check that in db '%s' module\
              'web_support_server' is installed and user '%s' exists and\
              has a contract with code '%s'. This is what we get: %s") %
             (database, self.user, self.number, e))
Esempio n. 18
0
 def test__meter_connection_protocol__whenMeterMissing(self):
     c = Client(**config.erppeek)
     meter_ip = '88300864'
     meter_missing = 'NotAMeter'
     result = meter_connection_protocol(c, [meter_ip, meter_missing])
     self.assertEqual(result, {
         meter_ip: 'ip',
     })
Esempio n. 19
0
def connect_erp():
    global O
    if O:
        return O
    step("Connectant a l'erp")
    O = Client(**configdb.erppeek)
    step("connectat...")
    return O
Esempio n. 20
0
 def get_client(self, not_database=False):
     self.ensure_one()
     try:
         if not_database:
             return Client(self.instance_id.main_hostname)
     except Exception, e:
         raise except_orm(_("Unable to Connect to Database."),
                          _('Error: %s') % e)
Esempio n. 21
0
def main(server, days_ago):
    url = urlparse(server)
    server = '{p.scheme}://{p.hostname}:{p.port}'.format(p=url)
    db = url.path.lstrip('/')
    user = url.username
    password = url.password
    c = Client(server, db, user, password)
    logger.info('Connected to %s@%s', server, db)
    d = (date.today() - timedelta(days=days_ago)).strftime('%Y-%m-%d')

    export_p5d = c.model('wizard.export.comer.p5d')
    wiz = export_p5d.create({
        'date_from': d,
        'date_to': d,
        'file_format': 'cch_val'
    })
    wiz.export()
    logger.info('Queued P5D export for %s', d)
 def remove_tasks_for_patient(
     patient_id, activity_models=[], database="openeobs_quality_assurance_db", user="******", password="******"
 ):
     """
     Remove a specific task for a patient
     :param patient_id: The patient to remove tasks for
     :param activity_models: The activity model to remove
     :param database: database to run against
     :param user: the username to run as
     :param password: password for username
     """
     odoo_client = Client("http://localhost:8069", db=database, user=user, password=password)
     activity_api = odoo_client.model("nh.activity")
     spells = activity_api.search(
         [["state", "=", "started"], ["data_model", "=", "nh.clinical.spell"], ["patient_id", "=", patient_id]]
     )
     activities = activity_api.search([["data_model", "in", activity_models], ["parent_id", "in", spells]])
     activity_api.unlink(activities)
Esempio n. 23
0
def main(server, days_ago):
    url = urlparse(server)
    server = '{p.scheme}://{p.hostname}:{p.port}'.format(p=url)
    db = url.path.lstrip('/')
    user = url.username
    password = url.password
    c = Client(server, db, user, password)
    logger.info('Connected to %s@%s', server, db)
    d = (date.today() - timedelta(days=days_ago)).strftime('%Y-%m-%d')

    export_p5d = c.model('wizard.export.comer.p5d')
    wiz = export_p5d.create({
        'date_from': d,
        'date_to': d,
        'file_format': 'cch_val'
    })
    wiz.export()
    logger.info('Queued P5D export for %s', d)
 def add_no_risk_observation(
         patient_id, database='openeobs_quality_assurance_db', user='******',
         password='******'):
     """
     Add an observation that gives no clinical risk
     :param patient_id: The patient to do observation for
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client('http://localhost:8069', db=database,
                          user=user, password=password)
     activity_api = odoo_client.model('nh.activity')
     ews_api = odoo_client.model('nh.clinical.patient.observation.ews')
     ews_activity_id = ews_api.create_activity({},
                                               {'patient_id': patient_id})
     activity_api.submit(ews_activity_id, NO_RISK_EWS_DATA)
     activity_api.complete(ews_activity_id)
Esempio n. 25
0
 def add_no_risk_observation(
         patient_id, database='openeobs_quality_assurance_db', user='******',
         password='******'):
     """
     Add an observation that gives no clinical risk
     :param patient_id: The patient to do observation for
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client('http://localhost:8069', db=database,
                          user=user, password=password)
     activity_api = odoo_client.model('nh.activity')
     ews_api = odoo_client.model('nh.clinical.patient.observation.ews')
     ews_activity_id = ews_api.create_activity({},
                                               {'patient_id': patient_id})
     activity_api.submit(ews_activity_id, NO_RISK_EWS_DATA)
     activity_api.complete(ews_activity_id)
Esempio n. 26
0
def passar_revisio_antics():
    c = Client(**dbconfig.erppeek)
    grupVehicle = c.ClasseVehicle.search([('data_compra', '<', '1990-01-01')])
    wiz = c.WizardPassarRevisio.create({'data_revisio': '2000-12-12'},
                                       context={
                                           'active_id': grupVehicle[0],
                                           'active_ids': grupVehicle
                                       })
    wiz.passar_revisio()
Esempio n. 27
0
 def test__meter_connection_protocol_(self):
     c = Client(**config.erppeek)
     meter_ip = '88300864'
     meter_moxa = '8814894104'
     result = meter_connection_protocol(c, [meter_ip, meter_moxa])
     self.assertEqual(result, {
         meter_ip: 'ip',
         meter_moxa: 'moxa',
     })
    def add_stand_in(database="openeobs_quality_assurance_db", user="******", password="******"):
        """
        Add a stand in task
        :param database: The database to do stand in on
        :param user: User to create stand in as
        :param password: Password for the user
        """
        odoo_client = Client("http://localhost:8069", db=database, user=user, password=password)

        activity_api = odoo_client.model("nh.activity")
        ews_api = odoo_client.model("nh.clinical.patient.follow")
        user_pool = odoo_client.model("res.users")
        nurse_id = user_pool.search([["login", "=", "nasir"]])
        ews_activity_id = ews_api.create_activity({"user_id": nurse_id[0]}, {"patient_ids": [[6, 0, [4]]]})

        activity_api.submit(ews_activity_id, {})

        return ews_activity_id
Esempio n. 29
0
 def test__measures_from_date(self):
     c = Client(**config.erppeek)
     meter = '88300864'
     measures = measures_from_date(c, meter,
         beyond="2019-10-02 09:00:00",
         upto  ="2019-10-02 12:00:00")
     self.assertTimeSeriesEqual(measures,[
         ('2019-10-02 10:00:00', 1407, 0, 0, 9, 0, 0),
         ('2019-10-02 11:00:00', 1687, 0, 0, 22, 0, 0),
     ])
 def remove_observations_for_patient(
     patient_id, database="openeobs_quality_assurance_db", user="******", password="******"
 ):
     """
     Remove all the observations for the patient
     :param patient_id: The patient to remove obs for
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client("http://localhost:8069", db=database, user=user, password=password)
     activity_api = odoo_client.model("nh.activity")
     spells = activity_api.search(
         [["state", "=", "started"], ["data_model", "=", "nh.clinical.spell"], ["patient_id", "=", patient_id]]
     )
     obs = activity_api.search(
         [["data_model", "=", "nh.clinical.patient.observation.ews"], ["parent_id", "in", spells]]
     )
     activity_api.unlink(obs)
Esempio n. 31
0
def copy_f1_to_testing(csv_file, date_from, polissa_name, server):
    client_prod = Client(**configdb.erppeek)
    if server == 'perp01':
        client_test = Client(**configdb.erppeek_perp01)
    else:
        client_test = Client(**configdb.erppeek_testing)
    if not polissa_name:
        polissa_names = read_polissa_names(csv_file, client_prod)
    else:
        polissa_names = [polissa_name]
    polissa_ids = search_polissa_by_names(polissa_names, client_prod)
    info = []
    total_pols_ok = 0
    for pol_info in client_prod.GiscedataPolissa.read(polissa_ids, ['name']):
        pol_id = pol_info['id']
        pol_name = pol_info['name']
        try:
            f1_prod_info = get_f1_info(client=client_prod, pol_id=pol_id)
            f1_test_info = get_f1_info(client=client_test, pol_id=pol_id)
            to_import_f1, to_replace_att = get_f1_import_replace_att(
                f1_prod_info, f1_test_info, date_from)

            if len(f1_prod_info) < len(f1_test_info) + len(to_import_f1):
                txt = "hi ha algun F1 a testing que no hi és a real. No s'hi actua"
                error("Per la pòlissa {} {}".format(pol_name, txt))
                info.append({'pol': pol_name, 'info': txt})
                continue

            replace_att(to_replace_att, client_prod, client_test)
            import_f1_to_testing(to_import_f1, client_prod, client_test)
            txt = "importats {} F1 i {} adjunts actualitzats".format(
                len(to_import_f1), len(to_replace_att))
            step("Per la pòlissa {} {}".format(pol_name, txt))
            info.append({'pol': pol_name, 'info': txt})
            total_pols_ok += 1
        except Exception as e:
            error("Error en la pòlissa {}".format(pol_name))
            info.append({'pol': pol_name, 'info': "error inesperat"})

    success("S'ha encuat la importació dels fitxers de {} pòlisses".format(
        total_pols_ok))
    return info
 def patient_scan_helper(patient_id,
                         database='openeobs_quality_assurance_db',
                         user='******', password='******'):
     """
     use a patient id to get id for do a barcode scan
     :param patient_id: ID of patient to do foo
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client('http://localhost:8069', db=database,
                          user=user, password=password)
     patient_api = odoo_client.model('nh.clinical.patient')
     patient_record = patient_api.read(patient_id, [
         'other_identifier',
         'patient_identifier',
         'display_name',
         'current_location_id'
     ])
     return patient_record
Esempio n. 33
0
 def patient_scan_helper(patient_id,
                         database='openeobs_quality_assurance_db',
                         user='******', password='******'):
     """
     use a patient id to get id for do a barcode scan
     :param patient_id: ID of patient to do foo
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client('http://localhost:8069', db=database,
                          user=user, password=password)
     patient_api = odoo_client.model('nh.clinical.patient')
     patient_record = patient_api.read(patient_id, [
         'other_identifier',
         'patient_identifier',
         'display_name',
         'current_location_id'
     ])
     return patient_record
Esempio n. 34
0
 def get_client(self, not_database=False):
     self.ensure_one()
     try:
         if not_database:
             proto = 'https' if self.instance_id.type == u'secure' else 'http'
             return Client(
                 '%s://%s' % (proto, self.instance_id.main_hostname))
     except Exception, e:
         raise except_orm(
             _("Unable to Connect to Database."),
             _('Error: %s') % e
         )
def main():
    step("Connectant a l'erp")
    O = Client(**configdb.erppeek)
    success("Connectat a: {}".format(O))
    success("Usuaria: {}".format(O.user))

    fiscal_year_id = O.model('account.fiscalyear').search([('name', 'ilike',
                                                            '2021')])[0]
    fiscal_year = O.model('account.fiscalyear').browse(fiscal_year_id)

    step("Demanem el balanç per l'any {}".format(fiscal_year.name))

    O.wizard(
        'account.balance.full.report', {
            'form': {
                'company_id': 1,
                'account_list': [[6, 0, []]],
                'fiscalyear': fiscal_year_id,
                'display_account': 'bal_mouvement',
                'state': 'none',
                'periods': [(6, 0, [])],
                'all_accounts': True,
                'context': {},
                'display_account_level': 5
            }
        }, 'excelFile_async')
Esempio n. 36
0
def task_counter_erp():
    c = Client(**config.erppeek)
    flux_client = client_db(db=config.influx)
    utcnow = datetime.datetime.strftime(
        datetime.datetime.now(datetime.timezone.utc), "%Y-%m-%d %H:%M:%S")
    meter_names = telemeasure_meter_names(c)
    try:
        for meter in meter_names:
            transfer_meter_to_plantmonitor(c, flux_client, meter, utcnow)

    except Exception as err:
        logger.error("[ERROR] %s" % err)
        raise
Esempio n. 37
0
def main(doit=False):

    mongo_client = pymongo.MongoClient(**configdb.mongodb)
    mongo_db = mongo_client.somenergia
    erpclient = Client(**configdb.erppeek)
    cups_names = get_cups_names(erpclient)
    step("Trobats {} CUPS".format(len(cups_names)))
    for col in ['tg_cchfact', 'tg_cchval']:
        step("Tractant la coŀlecció {}".format(col))
        treat_duplicateds(mongo_db, col, cups_names, doit)

    if not doit:
        warn("S'ha executat sense el doit: mode consulta")
Esempio n. 38
0
    def add_stand_in(database='openeobs_quality_assurance_db', user='******',
                     password='******'):
        """
        Add a stand in task
        :param database: The database to do stand in on
        :param user: User to create stand in as
        :param password: Password for the user
        """
        odoo_client = Client('http://localhost:8069', db=database,
                             user=user, password=password)

        activity_api = odoo_client.model('nh.activity')
        ews_api = odoo_client.model('nh.clinical.patient.follow')
        user_pool = odoo_client.model('res.users')
        nurse_id = user_pool.search([
            ['login', '=', 'nasir'],
            ])
        ews_activity_id = ews_api.create_activity({'user_id': nurse_id[0]}, {
            'patient_ids': [[6, 0, [4]]]})

        activity_api.submit(ews_activity_id, {})

        return ews_activity_id
Esempio n. 39
0
 def test__measures_from_date__withNoBeyondDate__takesFromBegining(self):
     c = Client(**config.erppeek)
     meter = '88300864'
     measures = measures_from_date(c, meter,
         beyond=None,
         upto  ="2019-06-01 03:00:00")
     self.assertTimeSeriesEqual(measures,[
         # First measure is on 2019-06-01 (Madrid) all zeros (still not producing)
         ('2019-05-31 22:00:00', 0, 0, 0, 0, 0, 0),
         ('2019-05-31 23:00:00', 0, 0, 0, 0, 0, 0),
         ('2019-06-01 00:00:00', 0, 0, 0, 0, 0, 0),
         ('2019-06-01 01:00:00', 0, 0, 0, 0, 0, 0),
         ('2019-06-01 02:00:00', 0, 0, 0, 0, 0, 0),
         ])
Esempio n. 40
0
 def remove_observations_for_patient(
         patient_id, database='openeobs_quality_assurance_db', user='******',
         password='******'):
     """
     Remove all the observations for the patient
     :param patient_id: The patient to remove obs for
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client('http://localhost:8069', db=database,
                          user=user, password=password)
     activity_api = odoo_client.model('nh.activity')
     spells = activity_api.search([
         ['state', '=', 'started'],
         ['data_model', '=', 'nh.clinical.spell'],
         ['patient_id', '=', patient_id]
     ])
     obs = activity_api.search([
         ['data_model', '=', 'nh.clinical.patient.observation.ews'],
         ['parent_id', 'in', spells]
     ])
     activity_api.unlink(obs)
    def add_stand_in(database='openeobs_quality_assurance_db', user='******',
                     password='******'):
        """
        Add a stand in task
        :param database: The database to do stand in on
        :param user: User to create stand in as
        :param password: Password for the user
        """
        odoo_client = Client('http://localhost:8069', db=database,
                             user=user, password=password)

        activity_api = odoo_client.model('nh.activity')
        ews_api = odoo_client.model('nh.clinical.patient.follow')
        user_pool = odoo_client.model('res.users')
        nurse_id = user_pool.search([
            ['login', '=', 'nasir'],
            ])
        ews_activity_id = ews_api.create_activity({'user_id': nurse_id[0]}, {
            'patient_ids': [[6, 0, [4]]]})

        activity_api.submit(ews_activity_id, {})

        return ews_activity_id
 def remove_observations_for_patient(
         patient_id, database='openeobs_quality_assurance_db', user='******',
         password='******'):
     """
     Remove all the observations for the patient
     :param patient_id: The patient to remove obs for
     :param database: The database to do observation on
     :param user: User to carry out observation as
     :param password: Password for the user
     """
     odoo_client = Client('http://localhost:8069', db=database,
                          user=user, password=password)
     activity_api = odoo_client.model('nh.activity')
     spells = activity_api.search([
         ['state', '=', 'started'],
         ['data_model', '=', 'nh.clinical.spell'],
         ['patient_id', '=', patient_id]
     ])
     obs = activity_api.search([
         ['data_model', '=', 'nh.clinical.patient.observation.ews'],
         ['parent_id', 'in', spells]
     ])
     activity_api.unlink(obs)
class TestUnsusbcribeEmailMembers(TestCase):
    def setUp(self):
        self.erp_client = Client(**configdb.erppeek)
        self.IrModelData = self.erp_client.model('ir.model.data')
        self.Soci = self.erp_client.model('somenergia.soci')
        self.ResPartnerAddress = self.erp_client.model('res.partner.address')

    @skip("NO")
    def test__get_member_category_id(self):

        category_id = get_member_category_id()
        self.assertIsNotNone(category_id)

        category_name = self.erp_client.model('res.partner.category').read(
            category_id, ['name'])['name']
        self.assertEqual(category_name, 'Soci')

    @skip("NO")
    def test__get_not_members_addresses(self):
        category_id = 8
        query = [('category_id', 'not in', [category_id]),
                 ('ref', 'like', 'S%')]

        not_members = self.Soci.search(query)
        not_members_partner_ids = [
            soci['partner_id'][0]
            for soci in self.Soci.read(not_members, ['partner_id'])
        ]
        address_list = self.ResPartnerAddress.search([
            ('partner_id', 'in', not_members_partner_ids)
        ])
        emails_list = [
            address.get('email', 'not found')
            for address in self.ResPartnerAddress.read(address_list, ['email'])
        ]

        self.assertTrue(bool(emails_list))
Esempio n. 44
0
    def _have_signed_cla(self, users):
        """
            Connect to odoo backend to verify if the users have signed
            the OCA CLA
        """

        config = self.server.config

        client = Client(
            config['odoo_host'],
            config['odoo_database'],
            config['odoo_user'],
            config['odoo_password']
        )

        for user in users:
            condition = [
                (config['odoo_github_login_field'], '=', user),
                ('category_id', '=', config['odoo_cla_categ']),
            ]
            if not client.search('res.partner', condition):
                return False

        return True
Esempio n. 45
0
    def _check_cla(self, users, pull_request):

        config = self.server.config
        cache_conn = self.server.cache_conn
        cache_cr = self.server.cache_cr
        send_miss_notification = True
        users_no_sign = []
        users_oca_no_sign = []
        users_sign = []
        users_sign_notify = []

        if cache_cr:
            placeholders = ','.join('?' * len(users))
            res = cache_cr.execute(
                SQL_SELECT_HIT_CACHE % placeholders, users
            )
            users_cached = [r[0] for r in res.fetchall()]
            users = list(set(users) - set(users_cached))

        client = Client(
            config['odoo_host'],
            config['odoo_database'],
            config['odoo_user'],
            config['odoo_password']
        )
        for user in users:

            condition = [(config['odoo_github_login_field'], '=', user)]
            if not client.search('res.partner', condition):
                users_no_sign.append(user)
                continue

            condition.extend([
                '|',
                ('category_id', '=', config['odoo_icla_categ']),
                ('parent_id.category_id', '=', config['odoo_ecla_categ']),
            ])
            if not client.search('res.partner', condition):
                users_oca_no_sign.append(user)
            else:
                users_sign.append(user)

        if cache_cr:
            if users_sign:
                placeholders = ','.join('?' * len(users_sign))
                res = cache_cr.execute(
                    SQL_SELECT_MISS_CACHE_USERS % placeholders,
                    users_sign
                )
                if res:
                    users_sign_notify = res.fetchall()
                    cache_cr.execute(
                        SQL_DELETE_MISS_CACHE % placeholders,
                        users_sign
                    )

                hit_users = [(u,) for u in users_sign]
                cache_cr.executemany(SQL_INSERT_HIT_CACHE, hit_users)

            if users_no_sign or users_oca_no_sign:

                users = users_no_sign + users_oca_no_sign
                placeholders = ','.join('?' * len(users))
                res = cache_cr.execute(
                    SQL_SELECT_MISS_CACHE_USERS % placeholders, users
                )
                users_no_sign_hit = [r[0] for r in res.fetchall()]
                users_oca_no_sign = list(
                    set(users_oca_no_sign) - set(users_no_sign_hit))
                users_no_sign = list(
                    set(users_no_sign) - set(users_no_sign_hit))

                # Do not send again a notification
                res = cache_cr.execute(
                    SQL_SELECT_MISS_CACHE_PR, (pull_request,))
                send_miss_notification = not res.fetchone()

                login_pr = [(login, pull_request) for login in users_no_sign]
                cache_cr.executemany(SQL_INSERT_MISS_CACHE, login_pr)

        else:
            # the cache is not activated
            # so avoid sending notifications on all pull request commit
            users_sign_notify = None

        if cache_conn:
            cache_conn.commit()

        return users_sign_notify, users_no_sign, users_oca_no_sign, \
            send_miss_notification
# db = 'database'
# user = '******'
# pwd = 'pwd'
# port = 8069
# uri = 'http://{0}.erp.clients'.format(db)
# %load https://raw.githubusercontent.com/gisce/powerp-tools/master/profiles_assign_invoice.py

from erppeek import Client
erp = Client(server=uri+":"+str(port), user=user, password=pwd, db=db)

invoices = erp.model('giscedata.facturacio.factura')
profiles = erp.model('giscedata.perfils.perfil')

search_params = [
    ('state', 'in', ('open', 'paid')),
    ('invoice_id.journal_id.code', 'ilike', 'ENERGIA%')
]

search_params_cancelling = search_params[:]
search_params_cancelling.append(
    ('tipo_rectificadora', 'in' , ('R', 'A', 'B'))
)
        
cancelling_invoice_ids = invoices.search(search_params_cancelling)

if cancelling_invoice_ids:
    cancelling_invoices = invoices.read(
        cancelling_invoice_ids,
        ['ref']
    )
    cancelled_invoice_ids = [ x['ref'][0] for x in cancelling_invoices ]
# uri = 'http://{0}.erp.clients'.format(db)
#
#
# %load https://raw.githubusercontent.com/gisce/powerp-tools/master/extra_lines_change_rent_meter_cch.py

amount_per_day=-0.008857
description = "Abonament del cobrament indegut del lloguer de comptador sense CCH durant el 2016"
start_date = '2016-01-01'
end_date = '2016-12-31'

uos_id = 16 # ALQ/dia

products_ids = [193]

from erppeek import Client
erp = Client(server=uri+":"+str(port), user=user, password=pwd, db=db)

for product_id in products_ids:
    line_ids = erp.model('giscedata.facturacio.factura.linia').search(
        [
            ('product_id','=', product_id)
        ]
    )
    if line_ids:
        lines = erp.model('giscedata.facturacio.factura.linia').read(
            line_ids,
            ['factura_id','quantity','uos_id']
        )

        seen = set()
        for line in lines:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from erppeek import Client
from datetime import datetime, timedelta
from validacio_eines import  es_cefaco, copiar_lectures, validar_canvis
import configdb

#SCRIPT QUE SERVEIX PER DESBLOQUEJAR CASOS QUE NO TENEN LECTURA DE
# TANCAMENT DEL COMPTADOR DE BAIXA

O = Client(**configdb.erppeek)

#Objectes
pol_obj = O.GiscedataPolissa
clot_obj = O.GiscedataFacturacioContracte_lot
comp_obj = O.GiscedataLecturesComptador
lectF_obj = O.GiscedataLecturesLectura
lectP_obj = O.GiscedataLecturesLecturaPool
#fact_obj = O.GiscedataFacturacioFactura
#cups_obj = O.GiscedataCupsPs
mod_obj = O.GiscedataPolissaModcontractual
sw_obj = O.GiscedataSwitching
m105_obj = O.model('giscedata.switching.m1.05')

#constants:
lot_id = O.GiscedataFacturacioLot.search([('state','=','obert')])

#Inicicialitzadors
polisses_resoltes_alinear_dates = []
cefaco= []
errors = []
Esempio n. 49
0
import base64
from subprocess import call
import time
import tempfile

from erppeek import Client


url = urlparse(sys.argv[1])
report = sys.argv[2]
ids = literal_eval(sys.argv[3])
context = literal_eval(sys.argv[4])

O = Client(
    '{x.scheme}://{x.hostname}:{x.port}'.format(x=url),
    url.path.lstrip('/'),
    url.username,
    url.password
)

report_id = O.report(report, ids, {}, context)
sys.stdout.write("Waiting")
res = {'state': False}

while not res['state']:
    res = O.report_get(report_id)
    sys.stdout.write(".")
    time.sleep(0.1)
    sys.stdout.flush()

sys.stdout.write("\n")
# db = 'database'
# user = '******'
# pwd = 'pwd'
# port = 8069
# uri = 'http://{0}.erp.clients'.format(db)
#
# date = '2017-03-01'
#
# %load https://raw.githubusercontent.com/gisce/powerp-tools/master/get_cch_policies_without_tg_meter.py

from erppeek import Client
erp = Client(server=uri+":"+str(port), user=user, password=pwd, db=db)

policies = []

policy_amendment_ids = erp.model('giscedata.polissa.modcontractual').search(
    [
         ('data_inici', '=', date),
         ('tg', '=', 1)
    ],
    0,
    None,
    None,
    {'active_test': False}
)
if policy_amendment_ids:
    for policy_amendment in erp.model('giscedata.polissa.modcontractual').browse(
         policy_amendment_ids,
    ):
        meter_id = policy_amendment.polissa_id.comptadors_actius(date,date)
        meter = erp.model('giscedata.lectures.comptador').browse(meter_id)
Esempio n. 51
0
        def f_spawned(*args, **kwargs):
            if not os.getenv('SPAWNED', False):
                spawn.hash_lock.acquire()
                logger = netsvc.Logger()
                # self, cursor, uid, *args
                osv_object = args[0]
                cursor = args[1]
                uid = args[2]
                if self.n_args < 0:
                    self.n_args = len(args)
                if not self.link:
                    self.link = f.__name__
                hash_instance = compute_hash_instance(
                    cursor.dbname, osv_object, self.link, args[3:self.n_args]
                )
                spawn_proc = RUNNING_INSTANCES.get(hash_instance,
                                                   SpawnProc(-1, 0, 0))
                try:
                    if psutil.Process(spawn_proc.pid) and self.uniq:
                        if isinstance(args[-1], dict):
                            context = args[-1]
                        spawn.hash_lock.release()
                        raise except_osv("Error",
                            _(u"Already running pid: %s by user: %s at: %s")
                            % (spawn_proc.pid, spawn_proc.user,
                               spawn_proc.startup)
                        )
                except psutil.NoSuchProcess:
                    pass
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.bind(('127.0.0.1', 0))
                child_port = sock.getsockname()[1]
                sock.listen(1)
                sock.shutdown(socket.SHUT_RDWR)
                user_obj = osv_object.pool.get('res.users')
                # Aquí hem de fer l'spawn
                env = os.environ.copy()
                env['SPAWNED'] = '1'
                command = sys.argv[:]
                command[0] = os.path.join(config['root_path'],
                                          'openerp-server.py')
                command += ['--port=%i' % child_port, '--no-netrpc',
                            '--update=False',
                            '--database=%s' % cursor.dbname,
                            '--logfile=%s' % tempfile.mkstemp()[1],
                            '--pidfile=%s' % os.devnull]
                # Try to check if we have a conf file
                conf_found = [x for x in command if x.startswith('--conf=')]
                # If we don't found a conf file try to check if exists in
                # os env.
                # This is usefull spawning openerp instances from process that
                # aren't openerp instances. As a OORQ
                if not conf_found:
                    conf_path = os.getenv('OPENERP_SERVER', False)
                    if conf_path:
                        command += ['--conf=%s' % os.getenv('OPENERP_SERVER')]

                start = datetime.now()
                logger.notifyChannel('spawn_oop', netsvc.LOG_INFO, 'Spawned '
                                     'new process: %s' % ' '.join(command))
                p = psutil.Popen(command, env=env)
                user = user_obj.browse(cursor, uid, uid).login
                name = user_obj.browse(cursor, uid, uid).name
                pwd = user_obj.browse(cursor, uid, uid).password
                uri = self.get_uri(child_port)
                is_listen = False
                timeout = int(os.getenv('SPAWN_OOP_TIMEOUT', 20))
                while not is_listen:
                    if timeout <= 0:
                        if isinstance(args[-1], dict):
                            context = args[-1]
                        raise Exception(
                            _('Error timeout starting spawned instance.')
                        )
                    try:
                        Client(server=uri, db=cursor.dbname, user=user,
                               password=pwd)
                        is_listen = True
                    except:
                        time.sleep(0.1)
                        timeout -= 0.1
                        is_listen = False
                startup = datetime.now() - start
                if self.uniq:
                    RUNNING_INSTANCES[hash_instance] = SpawnProc(p.pid, start,
                                                                 name)
                logger.notifyChannel('spawn_oop', netsvc.LOG_INFO,
                    'Server started in %s. PID: %s. Listening on %s. '
                    'Hash instance: %s ' % (startup, p.pid, child_port,
                                            hash_instance)
                )
                spawn.hash_lock.release()
                start = datetime.now()
                c = Client(server=uri, db=cursor.dbname, user=user,
                               password=pwd)
                obj = c.model(osv_object._name)
                method = f.__name__
                newargs = args[3:]
                logger.notifyChannel('spawn_oop', netsvc.LOG_INFO,
                    'Calling %s.%s(%s)' % (
                        osv_object._name, method,
                        ', '.join([str(x) for x in newargs])
                    )
                )

                res = getattr(obj, method)(*newargs)
                duration = datetime.now() - start
                po = psutil.Process(p.pid)
                for child in po.get_children():
                    try:
                        child.kill()
                        child.wait(timeout=5)
                    except psutil.TimeoutExpired:
                        child.send_signal(psutil.signal.SIGKILL)
                po.kill()
                po.wait()
                if self.uniq:
                    del RUNNING_INSTANCES[hash_instance]
                logger.notifyChannel('spawn_oop', netsvc.LOG_INFO, 'Server '
                                     'stopped. PID: %s. Duration %s.'
                                     % (p.pid, duration))
                return res
            else:
                return f(*args, **kwargs)