def parse_arguments():
    parser = argparse.ArgumentParser(
        description="modifica els contractes eliminant la figura del pagador")

    parser.add_argument('--file',
                        dest='csv_file',
                        required=True,
                        help="csv amb les polisses a modificar")

    parser.add_argument('--doit',
                        type=bool,
                        default=False,
                        const=True,
                        nargs='?',
                        help='realitza les accions')

    args = parser.parse_args()
    if args.doit:
        success("Es faran canvis a les polisses (--doit)")
    else:
        success("No es faran canvis a les polisses (sense opció --doit)")
    global doit
    doit = args.doit

    return args
Exemplo n.º 2
0
def parse_arguments():
    parser = argparse.ArgumentParser(
        description="Envia correus d'avis de mort al pagador")

    parser.add_argument('--file',
                        dest='csv_file',
                        required=True,
                        help="csv amb les polisses a avisar")

    parser.add_argument('--doit',
                        type=bool,
                        default=False,
                        const=True,
                        nargs='?',
                        help='realitza les accions')

    args = parser.parse_args()
    if args.doit:
        success("Es faran enviament de correus (--doit)")
    else:
        success("No es faran enviament de correus (sense opció --doit)")
    global doit
    doit = args.doit

    return args
def change_to_tg(pol_ids):
    success('')
    success('Modificant polisses:')
    res = ns()
    totals = len(pol_ids)
    for counter, pol_id in enumerate(pol_ids):

        polissa = ns(
            pol_obj.read(pol_id, [
                "name",
                "no_estimable",
                "observacions",
                "observacions_estimacio",
            ]))
        step("{}/{} polissa {}".format(counter + 1, totals, polissa.name))

        header = "[{}] ".format(str(datetime.today())[:19])

        if polissa.observacions:
            polissa.observacions = polissa.observacions.encode("utf-8")
        changes = {
            "observacions":
            header + missatge + "\n\n" + (polissa.observacions or ""),
            "observacions_estimacio":
            header + missatge,
            "no_estimable":
            True,
        }
        res[pol_id] = changes
        if doit:
            pol_obj.write(pol_id, changes)
            warn("modificat")
    return res
def main():
    state = 'draft'
    from_date = '2017-01-01'
    to_date = '2017-12-31'

    step("Getting drafts moves")
    draft_move_ids = get_draft_moves_ids(state, from_date, to_date)

    step("There are {} account moves to validate".format(len(draft_move_ids)))
    if draft_move_ids:
        step("Do you want to continue? (Y/n)")
        answer = raw_input()
        while answer.lower() not in ['y', 'n', '']:
            answer = raw_input()
            step("Do you want to continue? (Y/n)")
        if answer in ['n', 'N']:
            raise KeyboardInterrupt

    draft_move_ids_gen = (tuple(draft_move_ids[i:i + MAX_ELEMS])
                          for i in range(0, len(draft_move_ids), MAX_ELEMS))
    res = validate_moves(draft_move_ids_gen)
    failed = {
        move_ids: result
        for move_ids, result in res.iteritems() if result is False
    }
    while failed:
        warn("There were failed validation, tring again")
        res = validate_moves(failed)
        failed = {
            elem: result
            for elem, result in res.iteritems() if result is False
        }

    success("Done!")
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')
Exemplo n.º 6
0
def generate_and_save_pdf(id, name):
    try:
        pdf_data = generate_inv_pdf(id)
        step("saving pdf to {}", name)
        save_file(name, pdf_data)
        success("done!")
    except Exception as e:
        warn(str(e))
Exemplo n.º 7
0
def main():
    res = update_general_conditions()
    failed_contracts = [contract for contract in res if not contract[0]]
    if failed_contracts:
        contract_list = [contract[1] for contract in res]
        msg = "Achtung!! There folowing contracts failed:\n - {}"
        warn(msg.format(", ".join(contract_list)))

    success("Updated {} contracts".format(str(len(res))))
def output_results(result):
    success("Resultat final")
    success("----------------")
    success("Pòlisses analitzades: {}", len(pols_to_check_ids))

    success("Forats trobats: {}", len(result))

    success("Errors: ")
    step(','.join(errors_buscant))
Exemplo n.º 9
0
def treat_duplicateds(mongo_db, mongo_collection, cups, doit=False):
    total_deleted = 0
    for cups_name in cups:
        duplicateds = get_mongo_name_datetime_duplicateds(mongo_db, mongo_collection, cups_name)
        deleted_by_cups = duplicateds_by_cups(duplicateds, mongo_db, mongo_collection, doit)
        total_deleted += deleted_by_cups
        if deleted_by_cups:
            step("Trobats {} duplicats del CUPS {}".format(deleted_by_cups, cups_name))
    success("Eliminats {} registres".format(total_deleted))
def expire(
        member=None,
        contract=None,
        idmode=None,
        **_):
    member = preprocessMembers([member], idmode)[0]
    step("Markin as expired assignation between contract {} and member {}"
        .format(contract, member))
    c.GenerationkwhAssignment.expire(contract, member)
    success("Done.")
Exemplo n.º 11
0
def send_killing_payer_email_warning(pol_ids):
    first = True
    for batch in chunks(pol_ids, CONTRACTS_PER_BATCH):
        if not first:
            step("Esperant {} segons per no saturar", TIME_BETWEEN_BATCHS)
            time.sleep(TIME_BETWEEN_BATCHS)

        success("Enviant email a bloc de {} polisses.", len(batch))
        for pol_id in batch:
            send_contract_erp_email(pol_id)
def candidates_to_tg():
    res = search_candidates_to_tg_default()
    if not doit:
        return res
    ret1 = change_to_tg(res.candidates)
    ret2 = change_to_tg(res.esborranys_no_ultimalectura)
    ret3 = change_to_tg(res.activa_no_ultimalectura)
    ret = ret1.keys() + ret2.keys() + ret3.keys()
    success('')
    success("S'han modificat {} polisses", len(ret))
    return ret
def main():
    to_do = []

    with ThreadPoolExecutor() as executor:
        # to_do.append(executor.submit(delete_1006(test=False)))
        to_do.append(executor.submit(delete_2001(test=False)))

        while to_do:
            done, to_do = wait(to_do)

    success("Finish!!! I will drink a beer!")
Exemplo n.º 14
0
def search_known_errors(res, fact_id):
    errors = []
    for k in known_errors.keys():
        if k in res:
            errors.append(known_errors[k])
    if errors:
        success("S'ha trobat {} possible(s) error(s):", len(errors))
        for error in errors:
            success("POSSIBLE ERROR >> {}", error)
    else:
        warn("Error no reconegut, fes captura i obre incidència!!")
    step("Traça interna de l'error:")
    step(res)
    return errors
Exemplo n.º 15
0
def sendOverSmtp(config, sender, recipients, msg):
    if not config:
        from config import smtp
    else:
        import imp
        smtp = imp.load_source('config', config).smtp

    step("Connecting to {host}:{port} as {user}...".format(**smtp))
    import smtplib
    server = smtplib.SMTP(smtp['host'], smtp['port'])
    server.starttls()
    server.login(smtp['user'], smtp['password'])
    step("\tSending...")
    server.sendmail(sender, recipients, msg.as_string())
    success("\tMail sent")
    server.quit()
Exemplo n.º 16
0
def main(invoice_name, invoice_id, invoice_ids):
    fact_ids = []
    if invoice_name:
        fact_ids.append(search_invoice_by_name(invoice_name))
    if invoice_id:
        fact_ids.append(search_invoice_by_id(invoice_id))
    if invoice_ids:
        fact_ids.extend(search_invoice_by_ids(invoice_ids))

    for fact_id in fact_ids:
        if fact_id:
            print_invoice_data(fact_id)
            error, res = load_invoice_data(fact_id)
            if error:
                errors = search_known_errors(res, fact_id)
            else:
                success("La factura en pdf no te problemes a nivell de dades!")
Exemplo n.º 17
0
def fix_incoherent_cadastral_ref():
    '''
    Checks for incorrect cadastral reference format:
    in case of incorrect format, update it to a blank value.
    '''
    erp_client = Client(**configdb.erppeek)
    gcp_obj = erp_client.GiscedataCupsPs
    id_cups_list = gcp_obj.search([("active", "=", True)])
    n = 0
    for id_cups in id_cups_list:
        cadastral_ref = gcp_obj.read(id_cups,
                                     ["ref_catastral"])["ref_catastral"]
        try:
            incoherent_cadastral_ref = evalrefcatastral.validate(cadastral_ref)
        except:
            if cadastral_ref:
                gcp_obj.write(id_cups, {"ref_catastral": ""})
                n += 1
    success("{} incoherent cadastral references fixed", n)
def default(
        members=None,
        force=False,
        insist=False,
        idmode=None,
        all=None,
        mail=False,
        effectiveon=None,
        purchaseduntil=None,
        **_):
    members=preprocessMembers(members, idmode, all, effectiveon, purchaseduntil, force, insist)
    step("Generating default assignments for members: {}".format(
        ','.join(str(i) for i in members)))
    c.GenerationkwhAssignment.createDefaultForMembers(members)
    if mail:
        step("Sending notification mails for members: {}".format(
            ','.join(str(i) for i in members)))
        c.GenerationkwhAssignment.notifyAssignmentByMail(members)
    success("Done.")
Exemplo n.º 19
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)
def delete_2001(test=True):
    step("I will start with 2001 erros (this will be an odyssey)")
    warn_xmls = []

    importaciones_2001_f1 = get_f1s(error_code='2001')

    if test:
        warn("Test is ON!!")
        importaciones_2001_f1 = importaciones_2001_f1[:5]

    step("There are {} xml to delete".format(len(importaciones_2001_f1)))

    cnt = 0
    for xml_imported in importaciones_2001_f1:
        try:
            step("Checking xml {}".format(xml_imported.name))
            provider_bill = get_provider_bill_by_origin(
                xml_imported.invoice_number_text)
            if same_bill_dates(xml_imported, provider_bill):
                msg = "Xml {} has already provider bill with origin {}, i will delete it"
                success(
                    msg.format(xml_imported.name,
                               xml_imported.invoice_number_text))
                xml_imported.unlink()
                cnt += 1
            else:
                msg = "Provider bill with origin {} doesn't match with xml"
                warn(msg.format(provider_bill.reference, xml_imported.id))
                warn_xmls.append(xml_imported)
        except Exception as e:
            msg = "I couldn\'t get provider bill with origin {}"
            warn(msg.format(xml_imported.invoice_number_text))
            warn_xmls.append(xml_imported)

    step("{} xmls deleted".format(cnt))

    if warn_xmls:
        msg = "- Fitxer: {}\n\t Id: {}\n\t CUPS: {}\n\t Distri: {}\n\t Origen: {}"
        warn("\n".join([
            msg.format(xml.name, xml.id, xml.cups_text, xml.distribuidora,
                       xml.invoice_number_text) for xml in warn_xmls
        ]))
Exemplo n.º 21
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 validate_draft_invoices(polissa, generated_invoice_ids):

    generated_invoice_ids.reverse()
    success("\tFactures generades: {}", generated_invoice_ids)
    step("\tValidem factures creades")

    ko = False
    for draft_invoice_id in generated_invoice_ids:
        step("\t - Validant factura {}", draft_invoice_id)
        validation_warnings = Validator.validate_invoice(draft_invoice_id)
        for validation_warning in validation_warnings:
            v_warning_text = warning.read(validation_warning,
                                          ['message', 'name'])
            if v_warning_text['name'] != DELAYED_CONTRACT_WARNING_TEXT:
                ko = True  # validation error
                warn("   · {} {}", (v_warning_text['name']).encode('utf-8'),
                     (v_warning_text['message']).encode('utf-8'))
    if ko:
        result.contractsValidationError.append(polissa.id)
    return ko
def price(
        members=None,
        force=False,
        insist=False,
        idmode=None,
        all=None,
        mail=False,
        effectiveon=None,
        purchaseduntil=None,
        **_):
    members=preprocessMembers(members, idmode, all, effectiveon, purchaseduntil, force, insist)
    if mail:
        step("Sending advanced effectiveness notification for members: {}".format(
            ','.join(str(i) for i in members)))
        c.GenerationkwhAssignment.notifyAdvancedEffectiveDate(members)
    else:
        step("(Simulating) Sending advanced effectiveness notification for members: {}".format(
            ','.join(str(i) for i in members)))
        step("Use --mail to send")
    success("Done.")
def delete_1006(test=True):
    step("Deleting 1006")
    warn_xmls = []

    importaciones_1006_f1 = get_f1s(error_code='1006')

    if test:
        warn("Test is ON!!")
        importaciones_1006_f1 = importaciones_1006_f1[:5]

    step("There are {} xml to delete".format(len(importaciones_1006_f1)))

    cnt = 0
    for xml_imported in importaciones_1006_f1:
        try:
            step("Checking xml {}".format(xml_imported.name))
            match = ID_REGEX.match(xml_imported.critical_info)
            if match:
                old_xml_id = int(match.groupdict()['xml_id'])
                imp = FacturacioImportacioLinia.browse(old_xml_id)
                if imp and imp.cups_text == xml_imported.cups_text and imp.import_phase != '10':
                    msg = "Xml {} is already imported in {}, i will delete it"
                    success(msg.format(xml_imported.name, imp.id))
                    xml_imported.unlink()
                    cnt += 1
                else:
                    warn("I couldn\'t find xml {}".format(old_xml_id))
                    warn_xmls.append(xml_imported)
        except Exception as e:
            warn("I couldn\'t find xml {}".format(old_xml_id))
            warn_xmls.append(xml_imported)

    step("{} xmls deleted".format(cnt))

    if warn_xmls:
        msg = "- Fitxer: {}\n\t Id:{}\n\t CUPS: {}\n\t Distri:{}"
        warn('\n'.join([
            msg.format(xml.name, xml.id, xml.cups_text, xml.distribuidora)
            for xml in warn_xmls
        ]))
Exemplo n.º 25
0
def process_records(erp_data, pfilename):
    '''
    This function retrieves the incoherent data
    from ERP
    '''

    erp_data = [dict(data) for data in erp_data]
    filename = pfilename + datetime.now().strftime("%Y%m%d") + '.csv'
    if erp_data:
        error("\tThere are {} incoherent records in {}", len(erp_data),
              datetime.now().strftime("%Y-%m-%d"))
        error("\tSaving incoherent  data in {}", filename)
        header = {key for d in erp_data for key in d.keys()}
        with open(filename, "w") as loadsocis:
            writer = csv.DictWriter(loadsocis, header)
            writer.writeheader()
            writer.writerows(erp_data)
    else:
        success(
            "\tPerfect! There is nothing to do! No incoherent records found in {}",
            datetime.now().strftime("%Y-%m-%d"))
    return erp_data, filename
Exemplo n.º 26
0
def create_m1_chageowner(O, contract_number, cups, new_owner_vat, new_owner_id,
                         old_owner_id, member_id, address_id,
                         notification_address_id, bank_id, signature_date,
                         cnae_id, owner_change_type, lang, other_payer):

    contract_id = O.GiscedataPolissa.search([('name', 'ilike', contract_number)
                                             ])
    if not contract_id:
        raise Exception("Contract {} not found".format(contract_number))

    assert len(
        contract_id) <= 1, "More than one contract, I don't now what to do :("

    contract_info = O.GiscedataPolissa.read(contract_id, ['cups'])[0]
    msg = "Contract has diferent cups {} =/= {}"
    assert cups == contract_info['cups'][1], msg.format(
        cups, contract_info['cups'][1])

    res = create_m1_changeowner_case(
        t=O,
        contract_id=contract_id[0],
        new_owner_vat=new_owner_vat,
        new_owner_id=new_owner_id,
        old_owner_id=old_owner_id,
        member_id=member_id,
        address_id=address_id,
        notification_address_id=notification_address_id,
        bank_id=bank_id,
        signature_date=signature_date,
        cnae_id=cnae_id,
        owner_change_type=owner_change_type,
        lang=lang,
        other_payer=other_payer)
    if 'ERROR' in res[1].upper():
        raise Exception(res[1])

    success(res[1])
    return res
def crea_contractes(uri, filename):
    O = OOOP_WST(**configdb.ooop)
    contract_petitions = read_contracts_data_csv(filename)

    for petition in contract_petitions:
        msg = "Creating contract for vat {}, soci {}, CUPS {}"
        step(msg, petition['contract_owner']['vat'], petition['member_number'],
             petition['cups'])
        try:
            status, reason, text = add_contract(uri, petition)
            # comprovació manual ja que sempre retorna 200 el webforms
            if len(O.GiscedataPolissa.search([('cups', '=', petition['cups'])
                                              ])) == 0:
                raise requests.exceptions.HTTPError(
                    "Error en resposta del webforms")
        except requests.exceptions.HTTPError as e:
            msg = "I couldn\'t create a new contract for cups {}, reason {}"
            if 'cups exist' in e.message:
                warn(msg, petition['cups'], e)
            else:
                error(msg, petition['cups'], e)
        success("S'ha creat un nou contracte pel CUPS {}".format(
            petition['cups']))
def main():
    success('Obtaining all installed and to be updated modules ...')
    min_modules, all_modules = get_reduced_list_of_modules()

    success('set of {} modules found of total {}', len(min_modules),
            len(all_modules))

    d = max([len(m) for m in min_modules])
    for module in sorted(min_modules):
        step('{:' + str(d) + 's} --> {:2d} --> {:4.1f} --> {}', module,
             len(all_modules[module]),
             (len(all_modules[module]) * 100.0) / len(all_modules),
             (','.join(sorted(all_modules[module]))))

    success('set of {} modules found of total {}', len(min_modules),
            len(all_modules))
Exemplo n.º 29
0
def main():
    id_lot_obert = lot_obj.search([('state','=','obert')])[0]
    success("Lot actualment en us id {}", id_lot_obert)
    
    clot_2_ids = clot_obj.search([('lot_id', '=', id_lot_obert), ('tarifaATR','like', '2.%'),('status', 'like', '%[V001]%')])
    success("Factures 2.X amb V001 al lot actual trobades: {}", len(clot_2_ids))
    clot_3_ids = clot_obj.search([('lot_id', '=', id_lot_obert), ('tarifaATR','like', '3.%'),('status', 'like', '%[V001]%')])
    success("Factures 3.X amb V001 al lot actual trobades: {}", len(clot_3_ids))

    clot_ids = clot_2_ids + clot_3_ids

    csv_writer.writerow(['Nom polissa', 'Data ultima lectura facturada', 'Tarifa'])
    for clot_id in tqdm(clot_ids):
        cl = clot_obj.browse(clot_id)
        if encallat_volta_comptador(cl.polissa_id.cups.id, cl.polissa_id.data_ultima_lectura):
            csv_writer.writerow([cl.polissa_id.name, cl.polissa_id.data_ultima_lectura, cl.polissa_id.tarifa.name])
            step("trobada polissa {} - {} amb F1 tipus R amb data final coincident amb data lectura final {}", cl.polissa_id.name, cl.polissa_id.tarifa.name, cl.polissa_id.data_ultima_lectura)
Exemplo n.º 30
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import configdb
import base64
import time
from erppeek import Client
from consolemsg import step, success, warn
from subprocess import call

step("Connectant a l'erp")
O = Client(**configdb.erppeek)
success("Connectat")

# variables
ids = [2190972]


# Helpers
def generate_pdf_ErpPeek(model, id):
    report_id = O.report(model, id)
    res = {'state': False}
    while not res['state']:
        res = O.report_get(report_id)
        time.sleep(0.2)

    return base64.b64decode(res['result'])


def generate_pdf_OOOP(model, id):
    from ooop import OOOP
    oo = OOOP(**configdb.ooop)
Exemplo n.º 31
0
def sendMail(
        sender,
        to,
        subject,
        text=None,
        html=None,
        md=None,
        ansi=None,
        cc=[],
        bcc=[],
        replyto=[],
        attachments = [],
        template=None,
        config=None,
        stylesheets = [],
        dump = None,
        verbose=True
        ):

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email.mime.text import MIMEText
    from email.encoders import encode_base64
    from email.utils import formataddr, parseaddr
    if not config:
        from config import smtp
    else:
        import imp
        smtp=imp.load_source('config',config).smtp

    def formatAddress(address):
        return formataddr(parseaddr(address))
    def formatAddresses(addresses):
        return ', '.join(formatAddress(a) for a in addresses)

    # Headers
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = formatAddress(sender)
    msg['To'] = formatAddresses(to)
    if cc: msg['CC'] = formatAddresses(cc)
    if bcc: msg['BCC'] = formatAddresses(bcc)
    if replyto: msg['Reply-To'] = formatAddresses(replyto)

    recipients = to + (cc if cc else []) + (bcc if bcc else [])

    # Attachments

    for filename in attachments:
        step("Attaching {}...".format(filename))
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(filename, "rb").read())
        encode_base64(part)
        import os
        part.add_header(
            'Content-Disposition',
            'attachment; filename="{}"'.format(
                os.path.basename(filename.replace('"', ''))))

        msg.attach(part)

    # Content formatting

    style=''
    for stylesheet in stylesheets or []:
        with open(stylesheet) as stylefile:
            style+=stylefile.read()

    if md:
        step("Formating markdown input...")
        import markdown
        text = md # TODO: Format plain text
        html = htmltemplate.format(
            style = style,
            body = markdown.markdown(md, output_format='html')
            )

    if ansi:
        step("Formating ansi input...")
        import deansi
        text = ansi # TODO: Clean ansi sequences
        html = htmltemplate.format(
            style = deansi.styleSheet()+style,
            body = "<div class='ansi_terminal'>"+deansi.deansi(ansi)+"</div>",
            )

    content = MIMEMultipart('alternative')

    if text:
        content.attach(MIMEText(text,'plain','utf8'))

    if html:
        step("Adapting html to mail clients...")
        import premailer
        html = premailer.transform(html)
        content.attach(MIMEText(html,'html','utf8'))

        import sys
        #sys.stdout.write(html)

    msg.attach(content)

    if dump:
        with open(dump,'w') as dumpfile:
            dumpfile.write(msg.as_string())
        success("Email dumped as {}".format(dump))
        return
    return
    # Sending
    step("Connecting to {host}:{port} as {user}...".format(**smtp))
    server = smtplib.SMTP(smtp['host'], smtp['port'])
    server.starttls()
    server.login(smtp['user'], smtp['password'])
    step("\tSending...")
    server.sendmail(sender, recipients, msg.as_string())
    success("\tMail sent")
    server.quit()
    def create_employees(self, filename):
        O = Client(**configdb.erppeek_odoo)
        employee_lines = self.read_employees_data_csv(filename)

        for employee_data in employee_lines:
            print(employee_data)
            user_id = 0
            partner_id = 0

            # CREATE PARTNER
            #state_id = O.ResCountryState.search([('name','=',employee_data['provincia'].decode('utf8'))], context={'lang':'ca_ES'})
            partner_data = {
                'firstname': employee_data['nom'].decode('utf8'),
                'lastname': employee_data['cognoms'].decode('utf8'),
                #'name': employee_data['cognoms'] + ", " + employee_data['nom'],
                #'street': employee_data['carrer'].decode('utf8'),
                #'city': employee_data['poblacio'].decode('utf8'),
                #'state_id': state_id,
                #'country_id': 68,
                #'zip': employee_data['codi_postal'],
                #'mobile': employee_data['num_mobil'],
                #'phone': employee_data['num_fix'],
                'email': employee_data['email'],
                #'vat': employee_data['dni'],
            }
            try:
                if O.ResPartner.search([('email', '=', employee_data['email'])
                                        ]):
                    partner_id = O.ResPartner.search([
                        ('email', '=', employee_data['email'])
                    ])[0]
                    raise Exception("Partner already exist")
                partner_id = O.ResPartner.create(partner_data)
                success("Partner created: {}", partner_data['email'])
            except Exception as e:
                msg = "I couldn\'t create a new partner {}, reason {}"
                warn(msg, partner_data, e)

            # CREATE PARTNER ADDRESS: Not necessary anymore

            # CREATE USER
            # Get groups_ids
            # groups = employee_data['permisos'].split(',')
            # groups_id = []
            #for group in groups:
            #    group_id = O.ResGroups.search([('full_name','=',group)])
            #    if not group_id:
            #        warn("Grup no trobat {}", group.decode('utf8'))
            #    else:
            #        groups_id.append(group_id[0])
            #gropus_id = Attendance / Officer, Leaves / Officer, Employees / Officer
            #Testing: groups_id = [26,31, 16]
            groups_id = [75, 79, 16]
            # Create user
            user_data = {
                'firstname': employee_data['nom'].decode('utf8'),
                'lastname': employee_data['cognoms'].decode('utf8'),
                'login': employee_data['email'],
                'groups_id': groups_id,
                'password': '******',
                'lang': 'ca_ES',
                'tz': 'Europe/Andorra',
                'sel_groups_1_9_10': 1,
                #Testing: 'action_id': 191, #Attendance fixar
                'action_id': 557,  #Attendance fixar
                'partner_id': partner_id
            }
            try:
                if O.ResUsers.search([('login', '=', employee_data['email'])]):
                    user_id = O.ResUsers.search([('login', '=',
                                                  employee_data['email'])])[0]
                    raise Exception("User already exist")
                user_id = O.ResUsers.create(user_data)
                user_id = user_id.id
                # Add user to a group
                success("User created: {}", employee_data['email'])
            except Exception as e:
                msg = "I couldn\'t create a new user {}, reason {}"
                warn(msg, user_data, e)
            finally:
                for group in groups_id:
                    O.ResGroups.write(group, {'users': [(4, user_id)]})

            # CREATE EMPLOYEE
            # Get department id
            team_id = O.HrDepartment.search([
                ('complete_name', '=', employee_data['equips'].decode('utf8'))
            ])
            if not team_id:
                warn("Equip no trobat {}",
                     employee_data['equips'].decode('utf8'))
                continue
            # Get jornada
            jornada_id = 1
            if employee_data['jornada'] == '40':
                jornada_id = O.IrModelData.get_object_reference(
                    'somenergia', 'resource_calendar_som_40h_partida')[1]
            elif employee_data['jornada'] == '35':
                jornada_id = O.IrModelData.get_object_reference(
                    'somenergia', 'resource_calendar_som_35h')[1]
            elif employee_data['jornada'] == '32':
                jornada_id = O.IrModelData.get_object_reference(
                    'somenergia', 'resource_calendar_som_32h_dll_div')[1]
            elif employee_data['jornada'] == '30':
                jornada_id = O.IrModelData.get_object_reference(
                    'somenergia', 'resource_calendar_som_30h')[1]
            elif employee_data['jornada'] == '20':
                jornada_id = O.IrModelData.get_object_reference(
                    'somenergia', 'resource_calendar_som_20h')[1]
            elif employee_data['jornada'] == '10':
                jornada_id = O.IrModelData.get_object_reference(
                    'somenergia', 'resource_calendar_som_10h')[1]

            name = employee_data['cognoms'].decode(
                'utf8') + ", " + employee_data['nom'].decode('utf8')
            empleat_data = {
                'name': name,
                #'identification_id': employee_data['dni'],
                'work_email': employee_data['email'],
                'department_id': team_id[0],
                #'gender': employee_data['genere'],
                'user_id': user_id,
                'resource_calendar_id': jornada_id,
                #'birthday':  datetime.strftime(datetime.strptime(employee_data['data_neixement'], "%d/%m/%Y"), "%Y-%m-%d"),
                'theoretical_hours_start_date': '2021-05-01',
            }
            try:
                if O.HrEmployee.search([('work_email', '=',
                                         employee_data['email'])]):
                    raise Exception("Employee already exist")
                employee_id = O.HrEmployee.create(empleat_data)
                success("Employee created: {}", empleat_data['name'])
            except Exception as e:
                msg = "I couldn\'t create a new empoyee {}, reason {}"
                warn(msg, name, e)
                success("Employee created: {}", empleat_data['name'])
            except Exception as e:
                msg = "I couldn\'t create a new empoyee {}, reason {}"
                warn(msg, name, e)


def main(csv_file):
    impd = ImportData()
    impd.create_employees(csv_file)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Custom import Employees from csv Script')

    parser.add_argument('--file',
                        dest='csv_file',
                        required=True,
                        help="csv with employees data")

    args = parser.parse_args()
    try:
        main(args.csv_file)
    except Exception as e:
        traceback.print_exc(file=sys.stdout)
        error("Process failed: {}", str(e))
    else:
        success("Finished!")

# vim: et ts=4 sw=4
Exemplo n.º 34
0

def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in xrange(0, len(lst), n):
        yield lst[i:i + n]


def send_killing_payer_email_warning(pol_ids):
    first = True
    for batch in chunks(pol_ids, CONTRACTS_PER_BATCH):
        if not first:
            step("Esperant {} segons per no saturar", TIME_BETWEEN_BATCHS)
            time.sleep(TIME_BETWEEN_BATCHS)

        success("Enviant email a bloc de {} polisses.", len(batch))
        for pol_id in batch:
            send_contract_erp_email(pol_id)


if __name__ == '__main__':
    args = parse_arguments()
    O = connect_erp()

    pol_ids = get_polissa_ids_from_csv(args.csv_file)
    success("Extrets {} id's de polisses del csv", len(pol_ids))
    send_killing_payer_email_warning(pol_ids)
    success("Correus Enviats")

# vim: et ts=4 sw=4