예제 #1
0
        public static void Main(string[] args)
        {
            // Datos de conexión
            String Url      = "http://localhost:8069";
            String Dbname   = "test_db";
            String Login    = "******";
            String Password = "******";

            // Login
            OpenERPConnect connection = new OpenERPConnect(Url, Dbname, Login, Password);

            connection.Login();
            Console.WriteLine(connection.UserId);

            byte[] pdf_content = File.ReadAllBytes("./Properties/prueba.pdf");
            String base64_pdf  = Convert.ToBase64String(pdf_content);

            // Se obtendría el id del albarán donde queremos añadir el adjunto
            // Cojo un id de un albarán cualquiera
            int picking = 209;
            // Creamos el adjunto
            XmlRpcStruct vals = new XmlRpcStruct();

            vals.Add("name", "Pdf prueba");                                // Nombre del pdf
            vals.Add("datas", base64_pdf);                                 // base64
            vals.Add("datas_fname", "Pdf prueba");                         // Nombre del pdf
            vals.Add("res_model", "stock.picking");                        // Valor fijo, modelo al que se asocia el pdf
            vals.Add("res_id", picking);                                   // Id del registro al que se asocia el pdf
            vals.Add("to_print", true);
            long attachment_id = connection.Create("ir.attachment", vals); // se crea
            // stock_custom.report_picking_with_attachments es el nombre del informe, valor fijo
            // 209 vuelve a ser el id del picking
            Object x = connection.Print("report", "stock_custom.report_picking_with_attachments", new long[] { 209 });
        }
 private void txt_server_config_TextChanged(object sender, EventArgs e)
 {
     try
     {
         OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
         OpenERPConnect       openerp_connect = openerp_outlook.Connection;
         openerp_connect.URL             = txt_server_config.Text;
         this.combo_config_database.Text = "";
         this.txt_dbname.Text            = "";
         try
         {
             openerp_connect.DBList();
             this.load_dbname_list();
             if (txt_dbname.Visible)
             {
                 txt_dbname.Visible = false;
             }
             combo_config_database.Visible = true;
         }
         catch
         {
             if (combo_config_database.Visible)
             {
                 combo_config_database.Visible = false;
             }
             this.txt_dbname.Visible = true;
         }
         this.txt_username.Text = "";
         this.txt_password.Text = "";
     }
     catch (Exception ex)
     {
         Connect.handleException(ex);
     }
 }
예제 #3
0
        public Boolean PushMail(outlook.MailItem mail, string model, int thread_id)
        {
            /*
             *
             * This will push the mail as per the selected items from the list.
             *  :Param outlook.MailItem mail: selected mail from the outlook.
             *  :Param string model : Model name to push.
             *  :Param int thread_id : Thread id of the mail.
             * If mail pushed successfully then it returns true.
             * return False if mail Already Exist.
             *
             */
            OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
            OpenERPConnect       openerp_connect = openerp_outlook.Connection;
            ArrayList            args            = new ArrayList();
            Hashtable            vals            = new Hashtable();
            string email = Tools.GetHeader(mail);     //TODO: Outlook.MailItem Should be Converted into MIME Message

            args.Add(model);
            args.Add(email.ToString());
            args.Add(thread_id);
            Hashtable attachments = Tools.GetAttachments(mail);

            args.Add(mail.Body);
            args.Add(mail.HTMLBody);
            args.Add(attachments);
            object push_mail = this.Connection.Execute("plugin.handler", "push_message_outlook", args.ToArray());

            object[] push = (object[])push_mail;
            this.RedirectWeb(push[2].ToString());
            return(true);
        }
 private void btn_server_ok_Click(object sender, EventArgs e)
 {
     try
     {
         OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
         OpenERPConnect       openerp_connect = openerp_outlook.Connection;
         string url = Tools.JoinURL(this.txt_server_host.Text, this.txt_server_port.Text, this.chkSSL.Checked);
         this.txtServerURL.Text = url;
         openerp_connect.check_connectivity();
         this.Close();
     }
     catch (Exception ex)
     {
         Connect.handleException(ex);
     }
 }
예제 #5
0
        public void SaveConfigurationSetting()
        {
            string filepath = Tools.GetAppFolderPath();
            OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
            OpenERPConnect       openerp_connect = openerp_outlook.Connection;

            filepath = Path.Combine(filepath, openerp_config_file);
            string[]     datas    = { "url=" + openerp_connect.URL, "userid=" + openerp_connect.UserId, "dbname=" + openerp_connect.DBName, "rempwd=" + openerp_connect.rempwd, "pswrd=" + openerp_connect.pswrd };
            StreamWriter userfile = new StreamWriter(filepath, false);

            foreach (string data in datas)
            {
                userfile.WriteLine(data);
            }
            userfile.Close();
        }
        private void frm_openerp_configuration_Load(object sender, EventArgs e)
        {
            try
            {
                this.config_manager = new ConfigManager();
                this.config_manager.LoadConfigurationSetting();


                OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
                OpenERPConnect       openerp_connect = openerp_outlook.Connection;
                if (this.txt_server_config.Text != "")
                {
                    openerp_connect.URL = this.txt_server_config.Text;
                }
                if (openerp_connect.rempwd == true)
                {
                    this.txt_password.Text = Tools.DecryptB64Pwd(openerp_connect.pswrd);
                    this.chkpwd.Checked    = true;
                }
                if (openerp_connect.URL != null)
                {
                    this.txt_server_config.Text = openerp_connect.URL;
                    this.txt_username.Text      = openerp_connect.UserId;
                    try
                    {
                        object[] res_dblist = openerp_connect.DBList();
                        foreach (string selection in res_dblist)
                        {
                            if (openerp_connect.DBName != "" && selection == openerp_connect.DBName)
                            {
                                this.combo_config_database.SelectedText = openerp_connect.DBName;
                            }
                        }
                        this.load_dbname_list();
                    }
                    catch
                    {
                        this.setdblist(openerp_connect.DBName);
                    }
                }
            }
            catch (Exception ex)
            {
                Connect.handleException(ex);
            }
        }
        private void btn_openerp_connect_Click(object sender, EventArgs e)
        {
            try
            {
                url = txt_server_config.Text;
                string dbname;
                if (txt_dbname.Visible == true)
                {
                    dbname = txt_dbname.Text;
                }
                else
                {
                    dbname = combo_config_database.Text;
                }
                OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
                OpenERPConnect       openerp_connect = openerp_outlook.Connection;
                openerp_connect.URL    = url;
                openerp_connect.DBName = dbname;
                openerp_connect.UserId = txt_username.Text;
                openerp_connect.rempwd = chkpwd.Checked;
                if (chkpwd.Checked)
                {
                    openerp_connect.pswrd = Tools.EncryptB64Pwd(txt_password.Text);
                }
                else
                {
                    openerp_connect.pswrd = "";
                }
                if (openerp_connect.Login(openerp_connect.DBName, openerp_connect.UserId, txt_password.Text) != 0)
                {
                    openerp_outlook.Connection = openerp_connect;
                    Cache.OpenERPOutlookPlugin = openerp_outlook;
                    this.config_manager.SaveConfigurationSetting();

                    Connect.displayMessage("Successfully login to OpenERP.");
                    this.Close();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Authentication Error!\nInvalid Database.", Form.ActiveForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
 private void btn_server_ok_Click(object sender, EventArgs e)
 {
     try
     {
         OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
         OpenERPConnect       openerp_connect = openerp_outlook.Connection;
         string url = Tools.JoinURL(this.txt_server_host.Text, this.txt_server_port.Text, this.chkSSL.Checked);
         this.txtServerURL.Text = url;
         if (this.chkSSL.Checked)
         {
             ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
         }
         this.Close();
     }
     catch (Exception ex)
     {
         Connect.handleException(ex);
     }
 }
예제 #9
0
        private void frm_push_mail_Load(object sender, EventArgs e)
        {
            try
            {
                Model[] document_models = Cache.OpenERPOutlookPlugin.GetMailModels();
                OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
                OpenERPConnect       openerp_connect = openerp_outlook.Connection;

                foreach (Model model in document_models)
                {
                    ListViewItem item = new ListViewItem();
                    item.Name = model.model;
                    item.Text = model.name;
                    cmboboxcreate.Items.Add(model);
                }
            }
            catch (Exception ex)
            {
                Connect.handleException(ex);
            }
        }
예제 #10
0
파일: Main.cs 프로젝트: ssanche/CMNT_004_15
        public static void Main(string[] args)
        {
            // Datos de conexión
            String Url      = "http://localhost:8069";
            String Dbname   = "test_db";
            String Login    = "******";
            String Password = "******";

            // Login
            OpenERPConnect connection = new OpenERPConnect(Url, Dbname, Login, Password);

            connection.Login();
            Console.WriteLine(connection.UserId);

            Object[] domain = new Object[3];             // Albaranes de salida ya asignados y sin incidencias
            domain[0] = new Object[3] {
                "picking_type_id.code", "=", "outgoing"
            };
            domain[1] = new Object[3] {
                "state", "=", "assigned"
            };
            domain[2] = new Object[3] {
                "with_incidences", "=", false
            };
            long[] picking_ids = connection.Search("stock.picking", domain);
            Console.WriteLine("Albaranes encontrados: {0}", picking_ids.Length);

            //Los recorremos y les escribimos a todos la misma incidencia
            foreach (long picking_id in picking_ids)
            {
                XmlRpcStruct vals = new XmlRpcStruct();
                vals.Add("with_incidences", true);                 //Lo marcamos como bajo incidencia
                connection.Write("stock.picking", new long[] { picking_id }, vals);

                //Escribimos el motivo de la incidencia
                connection.MessagePost("stock.picking", new long[] { picking_id }, "Stock Incorrecto");
            }

            Console.ReadLine();
        }
        void load_dbname_list()
        {
            combo_config_database.Items.Clear();
            OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
            OpenERPConnect       openerp_connect = openerp_outlook.Connection;

            try
            {
                if (openerp_connect.URL != null && openerp_connect.URL != "")
                {
                    object[] res_dblist = openerp_connect.DBList();
                    foreach (var selection in res_dblist)
                    {
                        combo_config_database.Items.Add(selection);
                    }
                }
            }
            catch
            {
                this.setdblist(openerp_connect.DBName);
            }
        }
예제 #12
0
파일: Main.cs 프로젝트: ssanche/CMNT_004_15
        public static void Main(string[] args)
        {
            // Datos de conexión
            String Url      = "http://localhost:8069";
            String Dbname   = "test_db";
            String Login    = "******";
            String Password = "******";

            // Login
            OpenERPConnect connection = new OpenERPConnect(Url, Dbname, Login, Password);

            connection.Login();
            Console.WriteLine(connection.UserId);

            //Listamos todos los productos almacenables con su stock inicial
            Object[] domain = new Object[1];             // [('type.code', '=', 'product')]
            domain[0] = new Object[3] {
                "type", "=", "product"
            };
            long[] product_ids = connection.Search("product.product", domain);
            Console.WriteLine("Productos encontrados: {0}", product_ids.Length);

            XmlRpcStruct context = new XmlRpcStruct();

            context.Add("lang", "es_ES");             // cargamos en contexto el idioma español
            XmlRpcStruct[] products_data = connection.Read("product.product", product_ids, new string[] { "name", "qty_available", "uom_id" }, context);

            Console.WriteLine("STOCK INICIAL");
            foreach (var product in products_data)
            {
                Console.WriteLine("Producto: {0} - Stock actual: {1} unidades", product["name"], product["qty_available"]);
            }

            Console.WriteLine("\n\n");
            // Con un inventario vamos a aumentarle una unidad a cada uno siempre que el stock no sea en negativo, si es negativo ponemos 0.

            //Creamos un inventario nuevo.
            XmlRpcStruct vals = new XmlRpcStruct();

            vals.Add("name", "Inventario de prueba");                 //Motivo de inventario
            long inv_id = connection.Create("stock.inventory", vals); // se crea

            // Necesitamos recuperar el id de la ubicación de stock del inventario
            XmlRpcStruct[] inv_data    = connection.Read("stock.inventory", new long[] { inv_id }, new string[] { "location_id" });
            long           location_id = Convert.ToInt64(((object[])inv_data[0]["location_id"])[0]);

            foreach (var product in products_data)            //Para cada producto creamos una linea en el inventario
            {
                XmlRpcStruct line_vals = new XmlRpcStruct();
                line_vals.Add("inventory_id", inv_id);
                line_vals.Add("product_id", product["id"]);
                line_vals.Add("location_id", location_id);
                if (Convert.ToDouble(product["qty_available"]) >= 0)
                {
                    line_vals.Add("product_qty", Convert.ToDouble(product["qty_available"]) + 1.0);                     // cantidad actual + 1
                }
                else
                {
                    line_vals.Add("product_qty", 0);                     // cantidad actual <= 0 entonces 0
                }

                line_vals.Add("product_uom_id", Convert.ToInt64(((object[])product["uom_id"])[0]));                  //unidad de medida
                connection.Create("stock.inventory.line", line_vals);
            }

            //Una vez rellenado lo confirmamos
            connection.Execute("stock.inventory", "prepare_inventory", new long[] { inv_id });
            connection.Execute("stock.inventory", "action_done", new long[] { inv_id });

            //Para comprobar el cambio volvemso a leer productos y mostrarlos por pantalla.
            long[] product_ids2 = connection.Search("product.product", domain);
            Console.WriteLine("Productos encontrados: {0}", product_ids2.Length);

            XmlRpcStruct[] products_data2 = connection.Read("product.product", product_ids2, new string[] { "name", "qty_available", "uom_id" }, context);

            Console.WriteLine("STOCK ACTUAL");
            foreach (var product in products_data2)
            {
                Console.WriteLine("Producto: {0} - Stock actual: {1} unidades", product["name"], product["qty_available"]);
            }

            Console.ReadLine();
        }
예제 #13
0
 public OpenERPOutlookPlugin(OpenERPConnect connection)
 {
     this.Connection = connection;
     //this.set_server_method();
 }
예제 #14
0
        public static void Main(string[] args)
        {
            // Datos de conexión
            String Url      = "http://localhost:8069";
            String Dbname   = "visiotech_devel";
            String Login    = "******";
            String Password = "******";

            // Login
            OpenERPConnect connection = new OpenERPConnect(Url, Dbname, Login, Password);

            connection.Login();
            Console.WriteLine(connection.UserId);

            Object[] domain = new Object[3];
            domain[0] = "|";             //OR
            domain[1] = new Object[3] {
                "state", "=", "confirmed"
            };                                                                 //Esperando materias primas
            domain[2] = new Object[3] {
                "state", "=", "ready"
            };                                                             //Lista para producir
            long[] production_ids = connection.Search("mrp.production", domain);
            var    prods_data     = connection.Read("mrp.production", production_ids, new string[] { "state", "move_lines", "move_created_ids", "name", "product_id" });


            foreach (var prod in prods_data)
            {
                Console.WriteLine("Procesando: {0}", prod ["name"]);
                if ((string)prod ["state"] == "confirmed")
                {
                    connection.Execute("mrp.production", "force_production", new long[] { Convert.ToInt64(((int)prod["id"])) });                    //Confirmado -> Listo para producir
                }

                // Recorremos las lineas a consumir y les ponemos nº serie
                int[] moves = (int[])prod["move_lines"];
                foreach (long move in moves)
                {
                    XmlRpcStruct[] move_data = connection.Read("stock.move", new long[] { (long)move }, new string[] { "product_id" });
                    //buscamos si hay un lote ya creado con el código 0001 para el producto del movimiento
                    Object[] lot_domain = new Object[2];

                    lot_domain[0] = new Object[3] {
                        "product_id", "=", Convert.ToInt64(((object[])move_data[0]["product_id"])[0])
                    };
                    lot_domain[1] = new Object[3] {
                        "name", "=", "0001"
                    };
                    long[] lot_ids = connection.Search("stock.production.lot", lot_domain);
                    long   lot_id  = 0;
                    if (lot_ids.Length > 0)
                    {
                        lot_id = lot_ids [0];
                    }
                    else
                    {
                        XmlRpcStruct vals = new XmlRpcStruct();
                        vals.Add("name", "0001");
                        vals.Add("product_id", Convert.ToInt64(((object[])move_data[0]["product_id"])[0]));
                        lot_id = connection.Create("stock.production.lot", vals);
                    }
                    XmlRpcStruct w_vals = new XmlRpcStruct();
                    w_vals.Add("restrict_lot_id", lot_id);
                    connection.Write("stock.move", new long[] { (long)move }, w_vals);
                }

                // Recorremos los productos finales y les ponemos nº serie
                int[] final_moves = (int[])prod["move_created_ids"];
                foreach (long fmove in final_moves)
                {
                    XmlRpcStruct[] fmove_data = connection.Read("stock.move", new long[] { (long)fmove }, new string[] { "product_id" });
                    //buscamos si hay un lote ya creado con el código 0001 para el producto del movimiento
                    Object[] flot_domain = new Object[2];

                    flot_domain[0] = new Object[3] {
                        "product_id", "=", Convert.ToInt64(((object[])fmove_data[0]["product_id"])[0])
                    };
                    flot_domain[1] = new Object[3] {
                        "name", "=", "0001"
                    };
                    long[] flot_ids = connection.Search("stock.production.lot", flot_domain);
                    long   flot_id  = 0;
                    if (flot_ids.Length > 0)
                    {
                        flot_id = flot_ids [0];
                    }
                    else
                    {
                        XmlRpcStruct fvals = new XmlRpcStruct();
                        fvals.Add("name", "0001");
                        fvals.Add("product_id", Convert.ToInt64(((object[])fmove_data[0]["product_id"])[0]));
                        flot_id = connection.Create("stock.production.lot", fvals);
                    }
                    XmlRpcStruct wf_vals = new XmlRpcStruct();
                    wf_vals.Add("restrict_lot_id", flot_id);
                    connection.Write("stock.move", new long[] { (long)fmove }, wf_vals);
                }

                connection.Execute("mrp.production", "action_production_end", new long[] { Convert.ToInt64(((int)prod["id"])) });
            }
        }
예제 #15
0
파일: Main.cs 프로젝트: ssanche/CMNT_004_15
        public static void Main(string[] args)
        {
            // Datos de conexión
            String Url      = "http://localhost:8069";
            String Dbname   = "test_db";
            String Login    = "******";
            String Password = "******";

            // Login
            OpenERPConnect connection = new OpenERPConnect(Url, Dbname, Login, Password);

            connection.Login();
            Console.WriteLine(connection.UserId);

            // Obtiene albranes de salida que se hayan cambiado o creado con posterioridad al 01/10/2014
            Object[] domain = new Object[4];             // [('picking_type_id.code', '=', 'outgoing'),'|',('write_date', '=', False),('write_date', '>=', '2014-10-01 00:00:00')]
            domain[0] = new Object[3] {
                "picking_type_id.code", "=", "outgoing"
            };
            domain[1] = "|";             // Operador OR
            domain[2] = new Object[3] {
                "write_date", "=", false
            };
            domain[3] = new Object[3] {
                "write_date", ">=", "2014-10-01 00:00:00"
            };                                                                                 //%Y-%m-%d %H:%M:%S
            long[] picking_ids = connection.Search("stock.picking", domain);
            Console.WriteLine("Albaranes encontrados: {0}", picking_ids.Length);

            XmlRpcStruct context = new XmlRpcStruct();

            context.Add("lang", "es_ES");
            ArrayList fields = new ArrayList();

            fields.Add("name");             // Num. albaran
            fields.Add("partner_id");       // Empresa asociada al albaran
            fields.Add("move_lines");       //Listado de los movimientos del albaran
            fields.Add("state");            // Estado del albarán
            fields.Add("write_date");       // Fecha de última modificación
            fields.Add("create_date");      // Fecha de creación
            XmlRpcStruct[] pickings_data = connection.Read("stock.picking", picking_ids, (string[])fields.ToArray(typeof(string)));
            foreach (var picking in pickings_data)
            {
                if (picking["write_date"] != null)
                {
                    Console.WriteLine("Albaran: {0} modificado por ultima vez el {1}", picking["name"], picking["write_date"]);
                }
                else
                {
                    Console.WriteLine("Albaran: {0} creado el {1}", picking["name"], picking["create_date"]);
                }
                if (!picking["partner_id"].Equals(false))
                {
                    XmlRpcStruct[] partner_data = connection.Read("res.partner", new long[] { Convert.ToInt64(((object[])picking["partner_id"])[0]) }, new string[] { "name" });                  //Obtenemos el nombre del cliente asociado
                    Console.WriteLine("Cliente: {0} || Estado: {1}", partner_data[0]["name"], picking["state"]);
                }
                else
                {
                    Console.WriteLine("Estado: {0}", picking["state"]);
                }

                Console.WriteLine("Movimientos");
                int[] moves = (int[])picking["move_lines"];
                foreach (var move in moves)
                {
                    XmlRpcStruct[] move_data    = connection.Read("stock.move", new long[] { (long)move }, new string[] { "product_id", "product_uom_qty" });
                    XmlRpcStruct[] product_data = connection.Read("product.product", new long[] { Convert.ToInt64(((object[])move_data[0]["product_id"])[0]) }, new string[] { "default_code", "name" }, context);
                    Console.WriteLine("[{0}] {1}, {2} Unidades", product_data[0]["default_code"], product_data[0]["name"], move_data[0]["product_uom_qty"]);
                }

                Console.WriteLine("\n\n");
            }

            Console.ReadLine();
        }
예제 #16
0
        public void LoadConfigurationSetting()
        {
            string filePath = Tools.GetAppFolderPath();

            filePath = Path.Combine(filePath, this.openerp_config_file);
            OpenERPConnect       openerp_connect = null;
            OpenERPOutlookPlugin openerp_outlook = null;

            openerp_outlook = Cache.OpenERPOutlookPlugin;
            if (openerp_outlook == null)
            {
                openerp_outlook = new OpenERPOutlookPlugin(openerp_connect);
            }
            openerp_connect = openerp_outlook.Connection;
            if (openerp_connect == null)
            {
                openerp_connect = new OpenERPConnect();
            }

            if (File.Exists(filePath))
            {
                string line;

                using (StreamReader file = new StreamReader(filePath))
                {
                    while ((line = file.ReadLine()) != null)
                    {
                        char[]   delimiters = new char[] { '=' };
                        string[] parts      = line.Split(delimiters, 2);

                        for (int i = 0; i < parts.Length; i += 2)
                        {
                            if (parts[i] == "url")
                            {
                                openerp_connect.URL = parts[i + 1].Trim();
                            }
                            else if (parts[i] == "userid")
                            {
                                openerp_connect.UserId = parts[i + 1].Trim();
                            }
                            else if (parts[i] == "dbname")
                            {
                                openerp_connect.DBName = parts[i + 1].Trim();
                            }
                            else if (parts[i] == "pswrd")
                            {
                                openerp_connect.pswrd = parts[i + 1].Trim();
                            }
                            else if (parts[i] == "rempwd")
                            {
                                openerp_connect.rempwd = false;
                                if (parts[i + 1].Trim().ToLower() == "true")
                                {
                                    openerp_connect.rempwd = true;
                                }
                            }
                        }
                    }
                    file.Close();
                }
            }
            openerp_outlook.Connection = openerp_connect;
            Cache.OpenERPOutlookPlugin = openerp_outlook;
        }
예제 #17
0
        public static void Main(string[] args)
        {
            // Datos de conexión
            String Url      = "http://localhost:8069";
            String Dbname   = "test_db";
            String Login    = "******";
            String Password = "******";

            // Login
            OpenERPConnect connection = new OpenERPConnect(Url, Dbname, Login, Password);

            connection.Login();
            Console.WriteLine(connection.UserId);

            // Tengo dos albaranes reconocidos en estado Esperando disponibilidad, en concreto son el id 40 y el id 48, que son sobre los que voy a hacer el ejemplo
            // Vstock tendrá que tener guardado en algún sitio el identificador del albarán en Odoo para poder mapearlos. En mi caso el 40 y 48, se pueden cambiar para ver el ejemplo.

            //Ejemplo de lectura para estos dos albaranes de los datos de dirección y de los datos de transportista
            ArrayList fields = new ArrayList();

            fields.Add("name");             // Núm. albaran
            fields.Add("partner_id");       // Empresa asociada al albarán
            fields.Add("state");            // Estado del albarán
            fields.Add("carrier_id");       // Transportista asociado
            long[]         picking_ids   = new long[] { 40, 48 };
            XmlRpcStruct[] pickings_data = connection.Read("stock.picking", picking_ids, (string[])fields.ToArray(typeof(string)));
            XmlRpcStruct   context       = new XmlRpcStruct();

            context.Add("lang", "es_ES");
            foreach (var picking in pickings_data)
            {
                Console.WriteLine("Albaran {0} en estado {1}", picking["name"], picking["state"]);
                if (!picking["partner_id"].Equals(false))                   // Si tiene una empresa asociada, obtenemos los datos que nos interesan
                {
                    Console.WriteLine("- Dirección de envío:");
                    XmlRpcStruct[] partner_data = connection.Read("res.partner", new long[] { Convert.ToInt64(((object[])picking["partner_id"])[0]) }, new string[] { "name", "street", "zip", "city", "state_id", "country_id" });             //Pedimos que nos devuelva los campos que nos interesan
                    Console.WriteLine("Nombre cliente: {0}", partner_data[0]["name"]);
                    Console.WriteLine("Dirección: {0}", partner_data[0]["street"]);
                    Console.WriteLine("Población: {0}", partner_data[0]["city"]);
                    Console.WriteLine("Cód. Postal: {0}", partner_data[0]["zip"]);
                    if (!partner_data[0]["state_id"].Equals(false))                       // Si tiene provincia
                    {
                        XmlRpcStruct[] state_data = connection.Read("res.country.state", new long[] { Convert.ToInt64(((object[])partner_data[0]["state_id"])[0]) }, new string[] { "name" }, context);
                        Console.WriteLine("Provincia: {0}", state_data[0]["name"]);
                    }
                    if (!partner_data[0]["country_id"].Equals(false))                       // Si tiene país
                    {
                        XmlRpcStruct[] country_data = connection.Read("res.country", new long[] { Convert.ToInt64(((object[])partner_data[0]["country_id"])[0]) }, new string[] { "name" }, context);
                        Console.WriteLine("País: {0}", country_data[0]["name"]);
                    }
                }
                if (!picking["carrier_id"].Equals(false))
                {
                    Console.WriteLine("- Datos de transporte:");
                    XmlRpcStruct[] carrier_data = connection.Read("delivery.carrier", new long[] { Convert.ToInt64(((object[])picking["carrier_id"])[0]) }, new string[] { "name" });                  // Leemos el nombre del transportista
                    Console.WriteLine("Transportista: {0}", carrier_data[0]["name"]);
                }
                Console.WriteLine("###########################");                 // Separación
                Console.WriteLine("###########################");                 // Separación
            }

            Console.WriteLine("\n\n");

            // Siguiendo con el ejemplo, voy a decirle a Odoo que compruebe disponibilidad. Quizás Vstock ya consultaría sólo albaranes disponibles o parcialmente disponibles
            // El botón de comprobar disponibilidad llama a un método de nombre action_assign
            connection.Execute("stock.picking", "action_assign", picking_ids);
            // Volvemos a imprimir los estados de estos albaranes para ver si ya los tenemos diponibles o parcialmente disponibles.
            XmlRpcStruct[] picking_data = connection.Read("stock.picking", picking_ids, new string[] { "name", "state", "move_lines" });
            foreach (var picking in picking_data)
            {
                Console.WriteLine("Albarán {0} en estado {1}. Id: {2}", picking["name"], picking["state"], picking["id"]);
                // En mi caso uno queda parcialmente diponible y otro totalmente disponible

                if (picking["state"].Equals("partially_available"))                   // En el caso de que esté parcialmente disponible listamos sus movimientos con la cantidad pedida y la cantidad que consiguió reservar del stock.
                {
                    int[] moves = (int[])picking["move_lines"];
                    foreach (var move in moves)
                    {
                        XmlRpcStruct[] move_data    = connection.Read("stock.move", new long[] { (long)move }, new string[] { "product_id", "product_uom_qty", "availability" });
                        XmlRpcStruct[] product_data = connection.Read("product.product", new long[] { Convert.ToInt64(((object[])move_data[0]["product_id"])[0]) }, new string[] { "default_code", "name" });
                        Console.WriteLine("[{0}] {1}, {2} Unidades pedidas. {3} unidades disponibles", product_data[0]["default_code"], product_data[0]["name"], move_data[0]["product_uom_qty"], move_data[0]["availability"]);
                        // En el caso de que las unidades disponibles no coincidan con las de Vstock habrá que generar una incidencia desde Vstock a Odoo para informar de este hecho
                        // La gestión de incidencias en albaranes no está desarrollada en este momento de la integración, por lo que para seguir con el ejemplo supongamos que coincide.
                    }
                }
            }

            Console.WriteLine("\n\n");

            // Como ejemplo vamos a cancelar el albarán que está parcialmente disponible, porque al final por lo que se no lo enviamos. Este albarán es el id: 40
            // El botón de Cancelar transferencia llama a un método de nombre action_cancel. Una vez cancelado el albarán no hay forma de recuperarlo para envío. Hay que irse al pedido asociado y crear uno nuevo.
            connection.Execute("stock.picking", "action_cancel", new long[] { 40 });
            // Comprobamos de nuevo su estado para ver que realmente se canceló bien.
            XmlRpcStruct[] cancel_picking_data = connection.Read("stock.picking", new long[] { 40 }, new string[] { "name", "state" });
            Console.WriteLine("Albarán {0} en estado {1}. Id: {2}", cancel_picking_data[0]["name"], cancel_picking_data[0]["state"], cancel_picking_data[0]["id"]);

            Console.WriteLine("\n\n");

            // Como último ejemplo vamos a procesar por completo el albarán con id 48. La forma que se expone es la forma sencilla, en la que queremos procesar el albarán integramente
            // Hay un forma más compleja en la que se permite procesar parcialmente pero la definiremos en un segundo paso.
            connection.Execute("stock.picking", "action_done", new long[] { 48 });

            // Una vez hecho el traspaso comprobamos de nuevo el estado del albarán, para ver que efectivamente se ha puesto como Realizado.
            XmlRpcStruct[] done_picking_data = connection.Read("stock.picking", new long[] { 48 }, new string[] { "name", "state" });
            Console.WriteLine("Albarán {0} en estado {1}. Id: {2}", done_picking_data[0]["name"], done_picking_data[0]["state"], done_picking_data[0]["id"]);

            Console.ReadLine();
        }
예제 #18
0
        public void OnStartupComplete(ref System.Array custom)
        {
            /*
             *
             * When outlook is opened it loads a Menu if Outlook plugin is installed.
             * OpenERP - > Push, Partner ,Documents, Configuration
             *
             */
            Microsoft.Office.Interop.Outlook.Application app = null;
            try
            {
                app = new Microsoft.Office.Interop.Outlook.Application();
                object omissing = System.Reflection.Missing.Value;
                menuBar = app.ActiveExplorer().CommandBars.ActiveMenuBar;
                ConfigManager config = new ConfigManager();
                config.LoadConfigurationSetting();
                OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
                OpenERPConnect       openerp_connect = openerp_outlook.Connection;
                try
                {
                    if (openerp_connect.URL != null && openerp_connect.DBName != null && openerp_connect.UserId != null && openerp_connect.pswrd != "")
                    {
                        string decodpwd = Tools.DecryptB64Pwd(openerp_connect.pswrd);
                        openerp_connect.Login(openerp_connect.DBName, openerp_connect.UserId, decodpwd);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Unable to connect remote Server ' " + openerp_connect.URL + " '.", "OpenERP Connection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                newMenuBar = (office.CommandBarPopup)menuBar.Controls.Add(office.MsoControlType.msoControlPopup, omissing, omissing, omissing, true);
                if (newMenuBar != null)
                {
                    newMenuBar.Caption = "OpenERP";
                    newMenuBar.Tag     = "My";

                    btn_open_partner         = (office.CommandBarButton)newMenuBar.Controls.Add(office.MsoControlType.msoControlButton, omissing, omissing, 1, true);
                    btn_open_partner.Style   = office.MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_partner.Caption = "Contact";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_partner.FaceId = 3710;
                    newMenuBar.Visible      = true;
                    btn_open_partner.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.btn_open_partner_Click);

                    btn_open_document         = (office.CommandBarButton)newMenuBar.Controls.Add(office.MsoControlType.msoControlButton, omissing, omissing, 2, true);
                    btn_open_document.Style   = office.MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_document.Caption = "Documents";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_document.FaceId = 258;
                    newMenuBar.Visible       = true;
                    btn_open_document.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.btn_open_document_Click);

                    btn_open_configuration_form         = (office.CommandBarButton)newMenuBar.Controls.Add(office.MsoControlType.msoControlButton, omissing, omissing, 3, true);
                    btn_open_configuration_form.Style   = office.MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_configuration_form.Caption = "Configuration";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_configuration_form.FaceId = 5644;
                    newMenuBar.Visible = true;
                    btn_open_configuration_form.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.btn_open_configuration_form_Click);
                }
            }
            catch (Exception)
            {
                object oActiveExplorer;
                oActiveExplorer = applicationObject.GetType().InvokeMember("ActiveExplorer", BindingFlags.GetProperty, null, applicationObject, null);
                oCommandBars    = (office.CommandBars)oActiveExplorer.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, oActiveExplorer, null);
            }
        }
예제 #19
0
        public static void Main(string[] args)
        {
            // Datos de conexión
            String Url      = "http://localhost:8069";
            String Dbname   = "demo_db";
            String Login    = "******";
            String Password = "******";

            // Login
            OpenERPConnect connection = new OpenERPConnect(Url, Dbname, Login, Password);

            connection.Login();
            Console.WriteLine(connection.UserId);

            // Tengo un albarán en estado asignado, en concreto el id 280, sobre el que voy a hacer el ejemplo

            ArrayList fields = new ArrayList();

            fields.Add("name");             // Núm. albaran
            fields.Add("partner_id");       // Empresa asociada al albarán
            fields.Add("state");            // Estado del albarán
            fields.Add("internal_notes");   // Notas internas
            fields.Add("move_lines");       // Lineas del albarán
            long[]         picking_ids   = new long[] { 280 };
            XmlRpcStruct[] pickings_data = connection.Read("stock.picking", picking_ids, (string[])fields.ToArray(typeof(string)));
            XmlRpcStruct   context       = new XmlRpcStruct();

            context.Add("lang", "es_ES");

            foreach (var picking in pickings_data)
            {
                Console.WriteLine("Albaran {0} en estado {1}", picking["name"], picking["state"]);
                if (!picking["partner_id"].Equals(false))                   // Si tiene una empresa asociada, obtenemos los datos que nos interesan
                {
                    Console.WriteLine("- Dirección de envío:");
                    XmlRpcStruct[] partner_data = connection.Read("res.partner", new long[] { Convert.ToInt64(((object[])picking["partner_id"])[0]) }, new string[] { "name", "street", "zip", "city", "state_id", "country_id" });             //Pedimos que nos devuelva los campos que nos interesan
                    Console.WriteLine("Nombre cliente: {0}", partner_data[0]["name"]);
                    Console.WriteLine("Dirección: {0}", partner_data[0]["street"]);
                    Console.WriteLine("Población: {0}", partner_data[0]["city"]);
                    Console.WriteLine("Cód. Postal: {0}", partner_data[0]["zip"]);
                    if (!partner_data[0]["state_id"].Equals(false))                       // Si tiene provincia
                    {
                        XmlRpcStruct[] state_data = connection.Read("res.country.state", new long[] { Convert.ToInt64(((object[])partner_data[0]["state_id"])[0]) }, new string[] { "name" }, context);
                        Console.WriteLine("Provincia: {0}", state_data[0]["name"]);
                    }
                    if (!partner_data[0]["country_id"].Equals(false))                       // Si tiene país
                    {
                        XmlRpcStruct[] country_data = connection.Read("res.country", new long[] { Convert.ToInt64(((object[])partner_data[0]["country_id"])[0]) }, new string[] { "name" }, context);
                        Console.WriteLine("País: {0}", country_data[0]["name"]);
                    }
                }
                if (!picking["internal_notes"].Equals(false))
                {
                    Console.WriteLine("Observaciones: {0}", picking["name"]);
                }
                Console.WriteLine("###########################");                 // Separación
                Console.WriteLine("###########################");                 // Separación

                int[] moves = (int[])picking["move_lines"];
                foreach (var move in moves)
                {
                    XmlRpcStruct[] move_data    = connection.Read("stock.move", new long[] { (long)move }, new string[] { "product_id", "product_uom_qty", "availability" });
                    XmlRpcStruct[] product_data = connection.Read("product.product", new long[] { Convert.ToInt64(((object[])move_data[0]["product_id"])[0]) }, new string[] { "default_code", "name", "track_outgoing" });
                    Console.WriteLine("[{0}] {1}, {2} Unidades pedidas. {3} unidades disponibles. Seriable; {4}", product_data[0]["default_code"], product_data[0]["name"], move_data[0]["product_uom_qty"], move_data[0]["availability"], product_data[0]["track_outgoing"]);

                    // Si es seriable hay que crearle numeros de serie
                    if (!product_data[0]["track_outgoing"].Equals(false))
                    {
                        // Nº de número de serie a crear
                        int          serialNo  = Convert.ToInt32(move_data[0]["product_uom_qty"]);
                        XmlRpcStruct move_vals = new XmlRpcStruct();
                        string       lots      = "";
                        int          cont      = 1;
                        // While hasta que no haya que crear ninguno más
                        while (serialNo > 0)
                        {
                            string serial = cont.ToString("000000");
                            if (lots.Equals(""))
                            {
                                lots = serial;
                            }
                            else
                            {
                                lots += "," + serial;                                 // Separamos por comas los números de serie
                            }
                            serialNo--;
                            cont++;
                        }
                        move_vals.Add("lots_text", lots);                         //Informamos de los número de serie del movimiento a Odoo
                        connection.Write("stock.move", new long[] { (long)move }, move_vals);
                    }
                }
            }
            // Procesamos el albarán como siempre pero el sistema debió de separarlo en tantas peraciones como números de serie.
            connection.Execute("stock.picking", "action_done", new long[] { 280 });
        }
예제 #20
0
파일: Main.cs 프로젝트: ssanche/CMNT_004_15
        public static void Main(string[] args)
        {
            // Datos de conexión
            String Url      = "http://localhost:8069";
            String Dbname   = "test_db";
            String Login    = "******";
            String Password = "******";

            // Login
            OpenERPConnect connection = new OpenERPConnect(Url, Dbname, Login, Password);

            connection.Login();
            Console.WriteLine(connection.UserId);

            // Nos devuelve todos los ids de empresas
            ArrayList filters = new ArrayList();

            long[]    partner_ids = connection.Search("res.partner", filters.ToArray());
            ArrayList fields      = new ArrayList();

            fields.Add("name");

            // Leemos para todos los ids de empresas obtenidos arriba el campo nombre. Read siempre nos devuelve el id y los campos pedidos.
            var partner_data = connection.Read("res.partner", partner_ids, (string[])fields.ToArray(typeof(string)));

            foreach (var partner in partner_data)
            {
                Console.WriteLine("Partner {0} with Id {1}", partner["name"], partner["id"]);
            }

            //Comprobarmos que no existe un partner con nombre Prueba
            Object[] domain = new Object[1];
            domain[0] = new Object[3] {
                "name", "=like", "Prueba%"
            };
            long[] prueba_partner_ids = connection.Search("res.partner", domain);
            if (prueba_partner_ids.Length > 0)
            {
                // El partner ya existe lo borramos
                Console.WriteLine("Partnes exists");
                bool deleted = connection.Unlink("res.partner", prueba_partner_ids);
                Console.WriteLine("Deleted: {0}", deleted);
            }
            else
            {
                // El partner no existe lo creamos
                Console.WriteLine("Partnes not exists");
                XmlRpcStruct vals = new XmlRpcStruct();
                vals.Add("name", "Prueba");
                vals.Add("is_company", true);
                vals.Add("vat", "ES33552390J");
                long new_partner_id = connection.Create("res.partner", vals);
                Console.WriteLine("New Partner created {0}", new_partner_id);

                // Le cambiamos el nombre
                XmlRpcStruct vals2 = new XmlRpcStruct();
                vals2.Add("name", "Prueba2");
                long[] ids_to_update = new long[1];
                ids_to_update[0] = new_partner_id;
                bool updated = connection.Write("res.partner", ids_to_update, vals2);
                Console.WriteLine("Updated: {0}", updated);

                //Mostramos el nuevo nombre
                var new_partner_data = connection.Read("res.partner", ids_to_update, new string[] { "name" });
                foreach (var partner in new_partner_data)
                {
                    Console.WriteLine("Partner {0} with Id {1}", partner["name"], partner["id"]);
                }

                // Como ejemplo del método execute comprobamos si el cif es válido
                var result = connection.Execute("res.partner", "button_check_vat", ids_to_update);
                Console.WriteLine("VAT valid: {0}", Convert.ToBoolean(result));
            }


            Console.ReadLine();
        }
        public void OnStartupComplete(ref System.Array custom)
        {
            //-----------------------------------------------------------------------------------------------------------------------------------------------------

            /* /*
             *
             * When outlook is opened it loads a Menu if Outlook plugin is installed.
             * OpenERP - > Push, Partner ,Documents, Configuration
             *
             #1#
             */
            Outlook.Application app = _outlookApplication;
            try
            {
                object omissing = System.Reflection.Missing.Value;
                menuBar = app.ActiveExplorer().CommandBars.ActiveMenuBar;
                ConfigManager config = new ConfigManager();
                config.LoadConfigurationSetting();
                OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
                OpenERPConnect       openerp_connect = openerp_outlook.Connection;
                try
                {
                    if (openerp_connect.URL != null && openerp_connect.DBName != null && openerp_connect.UserId != null && openerp_connect.pswrd != "")
                    {
                        string decodpwd = Tools.DecryptB64Pwd(openerp_connect.pswrd);
                        openerp_connect.Login(openerp_connect.DBName, openerp_connect.UserId, decodpwd);
                    }
                }
                catch (Exception)
                {
                    //just shallow exception
                }
                newMenuBar = (Office.CommandBarPopup)menuBar.Controls.Add(MsoControlType.msoControlPopup, omissing, omissing, omissing, true);
                if (newMenuBar != null)
                {
                    newMenuBar.Caption = "OpenERP";
                    newMenuBar.Tag     = "My";

                    btn_open_partner         = (Office.CommandBarButton)newMenuBar.Controls.Add(MsoControlType.msoControlButton, omissing, omissing, 1, true);
                    btn_open_partner.Style   = MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_partner.Caption = "Contact";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_partner.FaceId      = 3710;
                    newMenuBar.Visible           = true;
                    btn_open_partner.ClickEvent += new Office.CommandBarButton_ClickEventHandler(this.btn_open_partner_Click); //Core._CommandBarButtonEvents_ClickEventHandler(this.btn_open_partner_Click);

                    btn_open_document         = (Office.CommandBarButton)newMenuBar.Controls.Add(MsoControlType.msoControlButton, omissing, omissing, 2, true);
                    btn_open_document.Style   = MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_document.Caption = "Documents";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_document.FaceId      = 258;
                    newMenuBar.Visible            = true;
                    btn_open_document.ClickEvent += new Office.CommandBarButton_ClickEventHandler(this.btn_open_document_Click);

                    btn_open_configuration_form         = (Office.CommandBarButton)newMenuBar.Controls.Add(MsoControlType.msoControlButton, omissing, omissing, 3, true);
                    btn_open_configuration_form.Style   = MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_configuration_form.Caption = "Configuration";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_configuration_form.FaceId = 5644;
                    newMenuBar.Visible = true;
                    btn_open_configuration_form.ClickEvent += new Office.CommandBarButton_ClickEventHandler(this.btn_open_configuration_form_Click);
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An error occured.{0}{0}{1}", Environment.NewLine, ex.Message);
                MessageBox.Show(message, "OPENERP-Initialize menu", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }