def transform_extract(records):
    equiv_company_ids = [(3,2),(4,1),(1,3)]
    conn2 = Odoo(url=destination_host,session=destination_session)
    records_final = []
    for record in records:
        if record["user_ids"]:
            if record["user_id"]:
                if users_dict.get(str(record["user_id"]),False):
                    record["user_id"] = users_dict[str(record["user_id"])]["id"]

            if record["create_uid"]:
                if users_dict.get(str(record["create_uid"]),False):
                    record["create_uid"] = users_dict[str(record["create_uid"])]["id"]

            if record.get("company_id"):
                record["company_id"] = [eq[1] for eq in equiv_company_ids
                                                if record.get("company_id") == eq[0]][0]
                                                
            if len(record["user_ids"][0][2]) == 1:
                old_user_id = record["user_ids"][0][2][0]
                new_user_id = users_dict[str(old_user_id)]["id"]
                rec = conn2.call_kw("res.users","search_read",kwargs={"fields":["id","partner_id"],
                                                                "domain":[["id","=",int(new_user_id)]] })
                del record["user_ids"]
                record["write"] = True
                record["new_id"] = rec[0]["partner_id"][0]
                #record.update({"company_id":})
                
            records_final.append(record)

    return records_final
        if record.get("company_ids"):
            record["company_ids"] = [(6, 0, [
                eq[1] for c in record.get("company_ids")[0][2]
                for eq in equiv_company_ids if c == eq[0]
            ])]
        if record.get("company_id"):
            record["company_id"] = [
                eq[1] for eq in equiv_company_ids
                if record.get("company_id") == eq[0]
            ][0]

    return records


#Descargar datos en Json
conn1 = Odoo(origin_db, origin_user, origin_pass, origin_host)
conn1.authenticate()
fields = [
    "id", "name", "login", "email", "mobile", "phone", "employee", "tz_offset",
    "signature", "street", "active", "customer", "employee", "share",
    "company_ids", "company_id", "lang", "state"
]

file_name = conn1.download_json(
    "res.users",
    fields,
    limit=0,
    domain=['|', ["active", "=", True], ["active", "=", False]],
    transform=transform_extract)

#conn2 = Odoo(destination_db,destination_user,destination_pass,destination_host)
from odoo import Odoo
import json
import base64
from PIL import Image
from io import BytesIO
from datetime import datetime
import pandas as pd

#Establecer Parámetros
##################################################################
conn = Odoo(db="universal",login="******",password="******",
            url="localhost:8005",ssl=False)
##################################################################

conn.authenticate()


def fetch_product_ids(conn):
    res = conn.call_kw("product.template","search_read",[],{"domain":[],"fields":["id"]})
    return list(map(lambda r:r["id"],res))

def download_product_image(conn,product_id):
    error_logs = open("error_logs_{}.logs".format(datetime.now().strftime("%Y-%m-%d %H-%M-%S")),"w")
    res = conn.call_kw("product.template","search_read",[],{"domain":[["id","=",product_id]],"fields":["name","image"]})
    if len(res)>0:
        image_id = res[0]["id"]
        image_b64 = res[0]["image"]
        try:
            im = Image.open(BytesIO(base64.b64decode(image_b64)))
            im.save('images/{}.png'.format(image_id), 'PNG')
        except Exception as e:
from odoo import Odoo
import json
import time
import csv
from variables import *

uoms = open("product.uom_load_20200121.json","r")
uoms_dict = json.loads(uoms.read())
def transform(record,records):
    record["uom_id"] = uoms_dict[str(record["uom_id"])]["id"]
    record["uom_po_id"] = uoms_dict[str(record["uom_po_id"])]["id"]
    return record


#Descargar datos en Json
conn1 = Odoo(origin_db,origin_user,origin_pass,origin_host)
conn1.authenticate()
fields = ["id","name","sale_ok","purchase_ok","type","default_code","lst_price",
            "standard_price","uom_id","uom_po_id","active",
            "description_sale","image"]
                    
file_name = conn1.download_json("product.product",fields,
                                            limit=0,
                                            domain=['|',["active","=",0],["active","=",1]])


conn2 = Odoo(destination_db,destination_user,destination_pass,destination_host)
conn2.authenticate()
#Eliminar Productos
#recs = conn2.call_kw("product.product","search_read",kwargs={"fields":["id"]})
#conn2.call_kw("product.product","unlink",args=[[rec["id"] for rec in recs]])
            record["product_id"])]["id"])
        record["account_id"] = int(cuentas_dict[str(
            record["account_id"])]["id"])
        record["discount"] = round(record["discount"], 2)
        invoice_line_tax_ids = record.get("invoice_line_tax_ids", False)
        if invoice_line_tax_ids:
            record["invoice_line_tax_ids"] = [(6, 0, [
                int(impuestos_dict[str(tax_id)]["id"])
                for tax_id in invoice_line_tax_ids[0][2]
            ])]

    return records


#Descargar datos en Json
conn1 = Odoo(origin_db, origin_user, origin_pass, origin_host)

conn1.authenticate()
fields = [
    "id", "name", "origin", "invoice_id", "account_id", "quantity", "uom_id",
    "discount", "price_unit", "invoice_line_tax_ids", "sequence", "product_id",
    "currency_id"
]

file_name = conn1.download_json("account.invoice.line",
                                fields,
                                domain=[["invoice_id", "!=", False]],
                                transform=transform,
                                order="id ASC",
                                limit=0)
Example #6
0
from odoo import Odoo
conn = Odoo("santaclara_db_1","admin","admin","localhost:8827",False)
conn.authenticate()

l  =conn.call_kw("product.product","search_read",
                    kwargs={'fields':['name','product_tmpl_id',"list_price"],'limit':10,'domain':[['name','ilike','3XXX MARACUYA 1.8LT']]})

print(l)
l  =conn.call_kw("product.product","read",[[5494],["name",'display_name']],kwargs={"context":{"bin_size":True,"params":{"action":119}}})
                          
print(l)
conn.call_kw("product.template","write",[[5495],{"name":"3XXX MARACUYA 1.8LT *XYZ123*****","list_price":2003.33}])
#l  =conn.call_kw("product.template","read",args=[[5495],['name']])
#print(l)
#DOWNLOAD PARTNERS
"""
fields = ["id","type","name","catalog_06_id","vat","company_type","estado_contribuyente",
            "registration_name","street","mobile","email","zip","customer",
            "supplier","linea_credito","employee","parent_id","function","phone"]
"""
#conn.download_json("res.partner",fields,order="parent_id DESC",limit=0)



#DOWNLOAD LÍNEA DE COMPROBANTES
fields = []
#conn.download_json("account.invoice.line",fields)

#DOWNLOAD COMPROBANTES
"""
fields = ["id","number","move_name","date_order","partner_id","journal_id","tipo_operacion",
Example #7
0
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
handler = logging.FileHandler("/var/log/scheduler.log")
formatter = logging.Formatter(
    "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

# Initialize Pgsql service
pgsql = Pgsql()
pgsql.logger = logger
pgsql.connect()
logger.info("Connected to Pgsql!")

# Initialize Odoo service
odoo = Odoo()
odoo.logger = logger
odoo.connect()
logger.info("Connected to Odoo!")

# Get job_id passed via command line
job_id = sys.argv[1]
job = pgsql.query_one("SELECT * FROM unison_job WHERE id = " + str(job_id))
job_type = pgsql.query_one("SELECT * FROM unison_job_type WHERE id = " +
                           str(job.job_type_id))
logger.info("Processing job '" + job.name + "' for model " +
            job_type.model_name + " (id " + str(job.model_id) + ")")

finished = False
while not finished:
    # Get the first task which is not in execution yet
Example #8
0
from odoo import Odoo
import json
from variables import *

def transform(records):
    equiv_company_ids = [(3,2),(4,1),(1,3)]
    for record in records:
        if record.get("company_id"):
            record["company_id"] = [eq[1] for eq in equiv_company_ids
                                            if record.get("company_id") == eq[0]][0]
    return records


#Descargar datos en Json
conn1 = Odoo(origin_db,origin_user,origin_pass,origin_host)
conn1.authenticate()
fields = ["id","name","type","code","company_id","sequence_number_next"]
file_name = conn1.download_json("account.journal",fields,transform=transform,limit=0)


conn2 = Odoo(url=destination_host,session=destination_session)
conn2.load_json("account.journal",file_name,dup=True,field_code=True,field_name=True,field_company=True)
        if record.get("account_id",False):
            record["account_id"] = int(cuentas_dict[str(record["account_id"])]["id"])
        record["discount_rate"] = round(record["discount_rate"],2)
        
    return records
    
def transform_load(record,records):
    if record.get("refund_invoice_id",False):
        try:
            record["refund_invoice_id"] = records[record["refund_invoice_id"]]["id"]
        except Exception as e:
            pass
    return record

#Descargar datos en Json
conn1 = Odoo(origin_db,origin_user,origin_pass,origin_host)
conn1.authenticate()
fields = ["number","move_name","partner_id","journal_id","name",
            "user_id","tipo_comprobante","uso_cfdi","forma_pago","methodo_pago",
            "currency_id","origin","folio_fiscal","tipo_relacion",
            "reference","type","uuid_relacionado","fecha_factura",
            "refund_invoice_id","estado_factura","confirmacion",
            "date_due","date_invoice","state","company_id","account_id","discount_rate",
            "uuid_relacionado","confirmacion","discount","monto","precio_unitario",
            "monto_impuesto","decimales","desc","qr_value","invoice_datetime",
            "fecha_factura","rfc_emisor","name_emisor","serie_emisor","tipo_relacion",
            "numero_cetificado","cetificaso_sat","folio_fiscal","fecha_certificacion",
            "cadena_origenal","selo_digital_cdfi","selo_sat","moneda","tipocambio",
            "folio","version","number_folio","amount_to_text","pdf_cdfi_invoice",
            "qrcode_image","regimen_fiscal","xml_invoice_link","estado_factura",
            "factura_cfdi","tipo_comprobante","forma_pago"]
Example #10
0
from odoo import Odoo
import json

odoo = Odoo('*****@*****.**', 'test1')

odoo.connect()

# exemple : on cherche l'evenement avec un id de 2
#           et on affiche que la propriete name et
#           l organisateur de l evenement

# Ne pas oublier de rajouter au moins 2 evenements
#print(odoo.searchRead("event.event", [["id", "=", 2]], ["name", "organizer_id"]))
# exemple : sans filtre, on affiche tous les evenements
# verifier bien que l'id de la personne existe sinon
# changez l id

#print(odoo.searchRead("res.partner", [],
#                    ["name", "id", "birthdate"]))

#result = odoo.searchPartnerByBirthdate("1998-06-10")
#data = result[0]
#output = tuple(data.items())
#print(output)
#print(output[2][1]) #to get the email
#print(output[0][1]) #to get the user id
#print(output[1][1]) #to get the name

#odoo.createEvent("event_test23", "2022-12-28 20:18:18",
#                 "2022-12-29 20:18:18", 6)
conn1 = Odoo("5WI1q4kLj2_db","admin","admin","htc.facturacion.vip")
conn1.authenticate()
fields = ["id","name","cost_currency_id","currency_id"]

products = conn1.call_kw("product.template","search_read",kwargs={"fields":fields})

for x in products:
    print(x)

company = conn1.call_kw("res.company","search_read",kwargs={"fields":["name","currency_id"]})
print(company)
"""
#conn1 = Odoo("highlanddb_oct_final_migra","admin","admin","localhost:8827")
#conn1 = Odoo("5WI1q4kLj2_db","admin","admin","htc.facturacion.vip")

conn1 = Odoo("naomis_db_13_nov", "yeyson5", "Elbaronrojo5", "localhost:8827")
conn1.authenticate()

productos = conn1.call_kw(
    "product.product",
    "search_read",
    kwargs={"fields": ["id", "name", "categ_id", "standard_price"]})
productos_dict = {}
for product in productos:
    productos_dict.update({
        product["id"]:
        [product["name"], product["categ_id"][1], product["standard_price"]]
    })

pos_orders = conn1.call_kw("pos.order",
                           "search_read",
Example #12
0
                if record.get("company_id") == eq[0]
            ][0]
        if record["user_id"]:
            if users_dict.get(str(record["user_id"]), False):
                record["user_id"] = users_dict[str(record["user_id"])]["id"]

        if record["warehouse_id"]:
            if almacenes_dict.get(str(record["warehouse_id"]), False):
                record["warehouse_id"] = almacenes_dict[str(
                    record["warehouse_id"])]["id"]

    return records


#Descargar datos en Json
conn1 = Odoo(origin_db, origin_user, origin_pass, origin_host)
conn1.authenticate()
fields = [
    "id", "name", "partner_id", "confirmation_date", "tipo_documento", "state",
    "date_order", "company_id", "validity_date", "user_id", "uso_cfdi",
    "forma_pago", "methodo_pago", "discount_rate", "invoice_status", "origin",
    "warehouse_id", "payment_term_id"
]

file_name = conn1.download_json(
    "sale.order",
    fields,
    transform=transform_extract,
    order="id ASC",
    limit=0,
    domain=[["partner_id", "not in", [1, 2, 3, 4, 5, 6]]])
Example #13
0
            province_id = str(partner["province_id"][1] if partner["province_id"] else "")
            district_id = str(partner["district_id"][1] if partner["district_id"] else "")
            customer = str(partner["customer"])
            supplier = str(partner["supplier"])
            linea_credito = str(partner["linea_credito"])
            employee = str(partner["employee"])
            parent_id = partner["parent_id"][1] if partner["parent_id"] else ""
            function = str(partner["function"])
            phone = str(partner["phone"])
            
            row = [idx,tipo,name,catalog_06_id,vat,company_type,estado_contribuyente,
                    registration_name,street,mobile,email,ubigeo,country_id,
                    state_id,province_id,district_id,customer,supplier,linea_credito,
                    employee,parent_id,function,phone]

            partner_writer.writerow(row)
"""

conn = Odoo("IW94Do1PeS_db", "admin", "adm1n*2019-11", "erp.highlandtc.com",
            True)
conn.authenticate()

lista = conn.call_kw("res.partner",
                     "search_read",
                     kwargs={
                         "domain":
                         ['|', ["active", "=", 0], ["active", "=", 1]],
                         "fields": ["name", "active"]
                     })

print([x for x in lista if x["active"]])
boms_dict = json.loads(boms.read())

products = open("product.product_load_20200121.json", "r")
products_dict = json.loads(products.read())

uoms = open("product.uom_load_20200121.json", "r")
uoms_dict = json.loads(uoms.read())


def transform(record, records):
    record["bom_id"] = boms_dict[str(record["bom_id"])]["id"]
    record["product_id"] = products_dict[str(record["product_id"])]["id"]
    record["product_uom_id"] = uoms_dict[str(record["product_uom_id"])]["id"]
    return record


#Descargar datos en Json
conn1 = Odoo(origin_db, origin_user, origin_pass, origin_host)
conn1.authenticate()
fields = ["id", "product_qty", "product_id", "product_uom_id", "bom_id"]

file_name = conn1.download_json("mrp.bom.line", fields, limit=0, domain=[])

conn2 = Odoo(destination_db, destination_user, destination_pass,
             destination_host)
conn2.authenticate()
#Eliminar Productos
#recs = conn2.call_kw("product.product","search_read",kwargs={"fields":["id"]})
#conn2.call_kw("product.product","unlink",args=[[rec["id"] for rec in recs]])
#Cargar Nuevos
conn2.load_json("mrp.bom.line", file_name, transform=transform, threads=20)
        if record.get("cash_basis_base_account_id", False):
            record["cash_basis_base_account_id"] = int(cuentas_dict[str(
                record["cash_basis_base_account_id"])]["id"])
        if record.get("cash_basis_account_id", False):
            record["cash_basis_account_id"] = int(cuentas_dict[str(
                record["cash_basis_account_id"])]["id"])
        if record.get("company_id"):
            record["company_id"] = [
                eq[1] for eq in equiv_company_ids
                if record.get("company_id") == eq[0]
            ][0]
    return records


#Descargar datos en Json
conn1 = Odoo(origin_db, origin_user, origin_pass, origin_host)
conn1.authenticate()
fields = [
    "id", "company_id", "name", "type_tax_use", "account_type", "amount",
    "description", "account_id", "tax_exigibility", "cash_basis_account_id",
    "cash_basis_base_account_id", "tag_ids", "tax_group_id", "price_include",
    "incluse_base_amount", "impuesta", "tipo_factor", "active"
]

file_name = conn1.download_json(
    "account.tax",
    fields,
    transform=transform,
    limit=0,
    domain=['|', ["active", "=", 0], ["active", "=", 1]])
Example #16
0
# Configure Logger
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
handler = logging.FileHandler("/var/log/scheduler.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

# Initialize Pgsql service
pgsql = Pgsql()
pgsql.logger = logger
pgsql.connect()
logger.info("Connected to Pgsql!")

# Initialize Odoo service
odoo = Odoo()
odoo.logger = logger
odoo.connect()
logger.info("Connected to Odoo!")

# Get job_task_id passed via command line
job_task_id = sys.argv[1]

# Load information from database
job_task = pgsql.query_one("SELECT * FROM unison_job_task WHERE id = " + str(job_task_id))
job = pgsql.query_one("SELECT * FROM unison_job WHERE id = " + str(job_task.job_id))
job_type = pgsql.query_one("SELECT * FROM unison_job_type WHERE id = " + str(job.job_type_id))

# Execute job task (date_start was marked on execute_job.py script)
logger.info("Executing task '" + job_task.name + "' (calling to " + job_task.model_name + "." + job_task.function + "on id " + str(job_task.model_id) + ")...")
success = odoo.execute(job_task.model_name, job_task.model_id, job_task.function)
            if len(record["user_ids"][0][2]) == 1:
                old_user_id = record["user_ids"][0][2][0]
                new_user_id = users_dict[str(old_user_id)]["id"]
                rec = conn2.call_kw("res.users","search_read",kwargs={"fields":["id","partner_id"],
                                                                "domain":[["id","=",int(new_user_id)]] })
                del record["user_ids"]
                record["write"] = True
                record["new_id"] = rec[0]["partner_id"][0]
                #record.update({"company_id":})
                
            records_final.append(record)

    return records_final


#Descargar datos en Json
conn1 = Odoo(origin_db,origin_user,origin_pass,origin_host)
conn1.authenticate()
fields = ["id","type","name","vat","company_type","city","rfc","x_descuento","trust",
            "street2","street","mobile","email","zip","customer","active","user_id","company_id","over_credit",
            "supplier","employee","parent_id","function","phone","ref","create_uid","credit_limit","zip",
            "uso_cfdi","residencia_fiscal","registro_tributario","x_metodo_pago","x_forma_pago","comment","user_ids"]

file_name = conn1.download_json("res.partner",fields,order="parent_id DESC",
                                                    limit=0,
                                                    transform=transform_extract,
                                                    domain=['|','&',["active","=",0],["active","=",1],["id","not in",[4,5,6]]])

conn2 = Odoo(url=destination_host,session=destination_session)
#conn2.authenticate()
conn2.load_json("res.partner",file_name,dup=True,field_name=True,field_company=True,field_active=True)
        record["product_id"] = int(products_dict[str(
            record["product_id"])]["id"])

        tax_id = record.get("tax_id", False)
        if tax_id:
            record["tax_id"] = [(6, 0, [
                int(impuestos_dict[str(tax_id)]["id"])
                for tax_id in tax_id[0][2]
            ])]

        record["discount"] = round(record["discount"], 2)
    return records


#Descargar datos en Jsons
conn1 = Odoo(origin_db, origin_user, origin_pass, origin_host)
conn1.authenticate()
fields = [
    "id", "name", "product_id", "product_uom_qty", "product_uom", "price_unit",
    "tax_id", "purchase_price", "order_id", "discount", "customer_lead"
]
file_name = conn1.download_json(
    "sale.order.line",
    fields,
    domain=[["order_id", "!=", False],
            ["order_id.partner_id", "not in", [1, 2, 3, 4, 5, 6]]],
    transform=transform,
    order="id ASC",
    limit=0)

conn2 = Odoo(url=destination_host, session=destination_session)
from odoo import Odoo
import json
from variables import *

conn2 = Odoo(url=destination_host,session=destination_session)
#conn2 = Odoo(origin_db,origin_user,origin_pass,origin_host)
#conn2.authenticate()

recs = conn2.call_kw("account.invoice","search_read",kwargs={"fields":["id"]})
rec_ids = [rec["id"] for rec in recs]
print(rec_ids)
#print(conn2.call_kw("account.invoice","write",args=[rec,{"move_name":"","name":"","state":"draft"}]))
salto = 30
for rec in [rec_ids[x:x+salto] for x in range(0,len(rec_ids),salto)]:
    print(rec)
    conn2.call_kw("account.invoice","compute_taxes",args=[rec])