viernes, 20 de febrero de 2015

Hilo de Ejecucion - BackgroundWorker

Cascaron DataLayerIng Cuando realizamos un aplicación es muy importare que esta no se quede pasmada si es que lanzamos una proceso muy pesado o tardado de realizar; ¿les ha pasado que sale diciendo la aplicación no responde ? y no por que su aplicación realmente de haya trabado es que el proceso es muy tardado y corre sobre el hilo principal de la aplicación lo cual parece dejarla trabada hasta que este proceso termine; ¿Como solucionarlo? con la complementación de  hilos de ejecución conocidos como Therads.

Hay muchas formas de implementar hilos pero la mas sencilla es usando el componente BackgroundWorker este fue introducido desde el framework 2.0 y permite realizas operaciones costosas o duraderas en un hilo diferente al de la interfaz por lo que nuestra aplicación no se vera afectada y continuara respondiendo.

Usando este control, la gestión de hilos está encapsulada en el control de manera que el no tenemos que lidiar con hilos (threads), invokes o delegados (delegates). Que suelen hacer la vida un poco complicada.

Ahora bien se puede usar el componente BackgroundWorker arrastrándolo de la paleta:

El componente tiene 3 funciones para controlar el funcionamiento:

Evento DoWork

Este es invocado cuando se ejecuta le función RunWorkerAsync() en ese momento se genera el segundo hilo de ejecucion; y dado que no es el hilo principal pues la aplicación segira respondiendo como si nada; es decir como lo dice le nombre de la función corre asincronamente por lo que es importante que se tome en cuenta que corre de forma asincrona por lo que el codigo no esperará el aproceso para continuar:

private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Visible = true;
            backgroundWorker1.RunWorkerAsync();   //este se llama y se ejecuta
            button1.Enabled = false;                               //Contiua esta instruccion sin esperar el hilo
            button2.Enabled = false;
}
Es importaten señalar cuando estemos codificando el DoWork que tomemos en cuenta que el valor  que regresamos queda guardado en la propiedad e.Result el cual podremos invocar despues  cuando el proceso este completo; en este ejemplolos uso para regresar el resultado de una consulta ala base dedatos que llega a demorar algún tiempo, y como se ve el resultado de la consulta lo almaceno en e.Result

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
 List queryResult = db.COMPROBANTE.Where(w => w.C_ENVIO == 0 && w.C_ENVIO != null).ToList();//&& w.CANCELA.Count < 0)
 var query = queryResult.Select(s => new DataBindingProjection
 {
  ID = s.C_ID,
  Cliente = s.RECEPTOR.R_NOMBRE,
  Correo = s.RECEPTOR.R_CORREO,
  SERIE = s.C_SERIE,
  FOLIO = s.C_FOLIO,
  FolioFiscal = s.C_FOLIOFISCAL,
  SubTotal = s.C_SUBTOTAL,
  Iva = s.C_IVA,
  Total = s.C_TOTAL,
  Saldo = decimal.Round((decimal)s.C_SALDO, 2),
  TIPOCAMBIO = s.C_TIPOCAMBIO,
  Moneda = s.C_TIPOCAMBIO == 1 ? "MXN" : "USD",
  FechaEmicion = s.C_FECHA,
  FechaVencimiento = s.C_VENCIMIETO
 }
 ).OrderBy(o=>o.SERIE).ThenBy(o=>o.FOLIO).ToList();
 e.Result = query.ToList();//regresa el arreglo oque voy a desplegar

}

Evento ProgressChanged

Este evento es lanzado en el hilo principal, por lo que aquí SI podemos acceder a controles del formulario de manera segura.

private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e)
{
   progressBar1.Value = e.ProgressPercentage; //actualizamos la barra de progreso
}

Evento RunWorkerCompleted


Este método se ejecuta cuando la el proceso ha concuido junto con el hilo de ejecuciony solo peude ser por 3 medio:


  1. El proceso termina de forma normal sin errores ni cancelaciones
  2. El proceso termina debido a un error durante su ejecucion
  3. Cancelado por el usuario/programador

En el objeto RunWorkerCompletedEventArgs nos brinda la información de como es que se completo el hilo y asi saber como trabajar con el valor de la propiedad Result,


private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
   if (e.Cancelled) {
     MessageBox.Show("La tarea fue cancelada");
   }
   else if (e.Error != null)
   {
     MessageBox.Show("Setermino con error: " + (e.Error as Exception).ToString());
   }
   else {
     MessageBox.Show("La busqueda a concluido ");
  if (e.Result != null)
  {
   dataGridView1.DataSource = e.Result;
   progressBar1.Visible = false;
   button1.Enabled = true;
   button2.Enabled = true;
  }

   }
}



Enviado las órdenes de cancelación al control.


Por ultimo pero no menos importante como podemos cancelar el proceso una ves que ha sido lanzado? pues es facil solo se invoca la funcion CancelAsync() y el proceso terminará

private void btoCancel_Click(object sender, EventArgs e)
{
   backgroundWorker1.CancelAsync();
}


En fin creo que eso es todo ojala les resulte útil is tienen dudas pregunten abajo...

martes, 17 de febrero de 2015

Clase para crear una ventana de dialogo con captura (ShowDialog)

Cascaron DataLayerIng Hola esta ves les traigo una muy util clase que genera un ventana tipo ShowDialog pero con una cmapo que valida que no este vacio un campo y que sea el mismo en mi casi la use para introducir un correo electronico; la clase la pongo a continuacion:
class Prompt
        {
            public static string ShowDialog(string text1, string text2, string caption, String OkButton)
            {
                Form prompt = new Form();
                prompt.Width = 450;
                prompt.Height = 180;
                prompt.Text = caption;
                prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
                prompt.TopLevel = true;
                prompt.ShowInTaskbar = true;
                prompt.MaximizeBox = false;
                prompt.MinimizeBox = false;


                Label textLabel = new Label() { Left = 10, Top = 10, Width = 400, Height = 20, Text = text1 };
                TextBox textBox = new TextBox() { Left = 10, Top = 30, Width = 400, Height = 20, };

                Label textLabel2 = new Label() { Left = 10, Top = 52, Width = 400, Height = 20, Text = text2 };
                TextBox textBox2 = new TextBox() { Left = 10, Top = 72, Width = 400, Height = 20, };

                Button confirmation = new Button() { Text = OkButton, Left = 290, Width = 100, Top = 102 };

                prompt.FormClosing += (sender, e) =>
                {
                    if (textBox.Text.Trim() == "")
                    {
                        MessageBox.Show("El correo esta vacio");
                        e.Cancel = true;
                    }
                    else
                    {
                        if (textBox.Text.Trim() == textBox2.Text.Trim())
                        {
                            e.Cancel = false;
                        }
                        else
                        {
                            MessageBox.Show("El correo no es igual");
                            e.Cancel = true;
                        }
                    }
                };

                confirmation.Click += (sender, e) => {

                    if (textBox.Text.Trim() == "")
                    {
                        MessageBox.Show("El correo estavacio");
                        return;
                    }
                    else
                    {
                        if (textBox.Text.Trim() == textBox2.Text.Trim())
                        {
                            prompt.Close();
                        }
                        else
                        {
                            MessageBox.Show("El correo no es igual");
                            return;
                        }
                    }
                };
                prompt.Controls.Add(confirmation);
                prompt.Controls.Add(textLabel);
                prompt.Controls.Add(textBox);
                prompt.Controls.Add(textLabel2);
                prompt.Controls.Add(textBox2);
                prompt.ShowDialog();
                prompt.Controls[
                prompt.Controls.IndexOf(textBox)].Focus();
                prompt.AcceptButton = confirmation;
                return textBox.Text;
            }
        }
Ahora el llamado es bastante sencillo:
String Respuesta = Prompt.ShowDialog("Mail", "Confirma Mail", "Captura Correo","Guardar");

miércoles, 11 de febrero de 2015

SAP BO9 Consulta de Existencias y precios mendiante WebService - Parte 2: WebService Consulta.asmx

Cascaron DataLayerIng Lo primero que debemos hacer es crear un proyecto web en Visual Studio y agregar un web Service agregando un nuevo elemento al proyecto "Servicio web (ASMX)"
Lo cual nos entrega un codigo como este:
Después Creamos la conexión a la base de SAP agregando un ADO.NET Entity Data Model
Seleccionamos el tipo de Modelo a crear:

Seleccionamos la conexión o la creamos si es necesario

Seleccionamos las tablas que se mencionaron en el post anterior OITM, ITM1 y OPLN

Así es como se ve el archivo edmx creado con las 3 tablas añadidas:
Como las tablas de SAP no tienen relaciones entre si el Entity Framework no crea las relaciones y para poder usar las consultas debemos crearlas a mano usando las herramientas de visual Studio
Después de esto guardaremos y compilaremos las solución para que las clases sean reconocidas por el compilador; ahora bien las funciones devuelven solo un valor y necesitamos devolver una serie de ellos por lo que se describen 2 clases para poder enviar la respuesta:
public class Parte
        {
            [Display(Name = "No. Parte")]
            public string NoParte { get; set; }

            [Display(Name = "Clave de Compañia")]
            public string ClaveCompania { get; set; }

            [Display(Name = "Descripcion")]
            public string Descripcion { get; set; }

            [Display(Name = "Existencia Fisica")]
            public decimal? ExistenciaFisica { get; set; }

            [Display(Name = "Disponible al arribo")]
            public decimal? DisponibleAlArribo { get; set; }

            [Display(Name = "X Surtir")]
            public decimal? XSurtir { get; set; }

            [Display(Name = "Ordenada a Proveedor")]
            public decimal? OrdenadoProveedor { get; set; }
            
            [Display(Name = "Precio")]
            public decimal? Precio { get; set; }
            [Display(Name = "Moneda")]
            public String Moneda { get; set; }


        }
        public class Resultado
        {
            public List Partes { get; set; }
            public String Mesanje;
            public String DetalleRespuesta;
        }

Y finalmente la funcion que trealizara la busqueda

[WebMethod]
        public Resultado GetExistencia(String NoParte, String Usuario, String Password)
        {
            using (ACDPartsSBOEntities db = new ACDPartsSBOEntities())
            {
                try
                {
                    List Auth = db.USUARIOS.Where(w => w.U_NICK == Usuario && w.U_PASS == Password).ToList(); // Validamos el Usuario en una tabla de usurio que se creo en SAP
                    if (Auth.Count > 0)
                    {
                        List _partes = db.OITM.Where(w => (string.IsNullOrEmpty(NoParte) || w.ItemCode.ToLower().Contains(NoParte.ToLower()))).ToList(); //Buscamos el no de parte envido y si es vacio se devuelve toda la tabla
                        List _result = new List(); //Creamos el arrelglo de salida
                        foreach (OITM item in _partes)
                        {
                            Parte P = new Parte(); //Creamos un objeto de nuestra clase para almacenar la informacion
                            P.NoParte = item.ItemCode;
                            P.Descripcion = item.ItemName;

                            P.ExistenciaFisica = item.OnHand;
                            P.XSurtir = item.IsCommited;
                            P.OrdenadoProveedor = item.OnOrder;
                            P.DisponibleAlArribo = (item.OnHand == null ? 0 : item.OnHand) - (item.IsCommited == null ? 0 : item.IsCommited) + (item.OnOrder == null ? 0 : item.OnOrder);

                            P.Precio = (item.ITM1.Where(w => w.PriceList == 7).ToList()[0].Price == null ? 0 : (Decimal)item.ITM1.Where(w => w.PriceList == 7).ToList()[0].Price); //Como se Menciono aqui se usala lista de precios 7 pero esto tb peude ser un valor enviado y calculado
                            P.Moneda = item.ITM1.Where(w => w.PriceList == 7).ToList()[0].Currency; //Como se Menciono aqui se usala lista de precios 7 pero esto tb peude ser un valor enviado y calculado
                            _result.Add(P);
                        }
                        Resultado _return = new Resultado();
                        _return.Partes = _result;
                        _return.Mesanje = "Busqueda realizada";
                        _return.DetalleRespuesta = "Se localizaron: " + _result.Count + " articulos";
                        return _return;
                    }
                    else
                    {
                        Resultado _return = new Resultado();
                        _return.Partes = new List();
                        _return.Mesanje = "Error";
                        _return.DetalleRespuesta = "Atenticacion de usuario fallida";
                        return _return;
                    }
                }
                catch (Exception ex)
                {
                    ERRORES_SW R = Errores_SW_B.ParseError(ex); //Estas con clases con las que controlo los errorres
                    int Id = Errores_SW_B.Insert(R);            //Estas con clases con las que almaceno los errorres
                    Resultado _return = new Resultado();
                    _return.Partes = new List();
                    _return.Mesanje = "Error";
                    _return.DetalleRespuesta = "Error generado en la aplicacion \nResporte el el Id No: " + Id;
                    return _return;
                }
            }
        }

Ala compilar lo y pobarlo prodras revisar que lo que entrega al cliente es un XML  con la informacion de nuestra base de SAP:



Espero les resulte util....

viernes, 6 de febrero de 2015

SAP BO9 Consulta de Existencias y precios mendiante WebService - Parte 1: Base de Datos de SAP BO Terminado

Si una empresa tiene o desea implementar SAP Bussines One siempre se topa con el problema de que a pesar de lo personalizable que es SAP BO no se puede compartir la información de manera fácil sin exponer la base de datos o el mismo SAP a un acceso remoto.

Para solucionar esto pensé en la aplicación de un web servicie que nos permita realizar esta consulta mediante un servidor web en este caso IIS ya que el desarrollo se lleva a cabo mediante C# .NET, y EntityFramework.

El primer paso para todo esto es identificar entre el mar de tablas de SAP las correspondientes a al catalogo de el inventario, la tabla de lista de precios y la tabla donde ambos se relacionan para conocer el precio del articulo en cada lista.

Catalogo de Artuculos


 El Catalogo de Artículos esta definido en la Tabla OITM  de la cual a continuación muestro la informacion de la misma que se obtiene de informacion que proporciona el SDK de SAP:

Table name: OITM

Field Description Type Size Related Default Value Constraints
ItemCode Item No. nVarChar 20 -
ItemName Item Description nVarChar 100 -
FrgnName Description in Foreign Lang. nVarChar 100 -
ItmsGrpCod Item Group Int 6 OITB 100
CstGrpCode Customs Group Int 6 OARG -1
VatGourpSa Sales Tax Definition nVarChar 8 OVTG
CodeBars Bar Code nVarChar 16 -
VATLiable Tax Definition VarChar 1 - Y Y Yes
N No
PrchseItem Purchase Item [Yes/No] VarChar 1 - Y Y Yes
N No
SellItem Sales Item [Yes/No] VarChar 1 - Y Y Yes
N No
InvntItem Inventory Item [Yes/No] VarChar 1 - Y Y Yes
N No
OnHand In Stock Num 19.6 -
IsCommited Qty Ordered by Customers Num 19.6 -
OnOrder Qty Ordered from Vendors Num 19.6 -
IncomeAcct Revenue Account nVarChar 15 OACT
ExmptIncom Exempt Revenue Account nVarChar 15 OACT
MaxLevel Maximum Inventory Level Num 19.6 -
DfltWH Default Warehouse nVarChar 8 -
CardCode Preferred Vendor nVarChar 15 OCRD
SuppCatNum Mfr Catalog No. nVarChar 17 -
BuyUnitMsr Purchasing UoM nVarChar 20 -
NumInBuy No. of Items per Purchase Unit Num 19.6 -
ReorderQty Pref. Qty in Purchase Units Num 19.6 -
MinLevel Minimum Inventory Level Num 19.6 -
LstEvlPric Last Evaluated Price Num 19.6 -
LstEvlDate Date of Last Reval. Price Date 8 -
CustomPer Customs Rate Num 19.6 -
Canceled Canceled Item [Yes/No] VarChar 1 - N Y Yes
N No
MnufctTime Production Date in Days Int 11 -
WholSlsTax Tax Rate for Wholesaler VarChar 1 -
RetilrTax Sales Tax in % VarChar 1 -
SpcialDisc Special Discount % Num 19.6 -
DscountCod Discount Code Int 6 -
TrackSales Follow-Up [Yes/No] VarChar 1 - N Y Yes
N No
SalUnitMsr Sales UoM nVarChar 20 -
NumInSale No. of Items per Sales Unit Num 19.6 -
Consig Consignment Goods Whse Num 19.6 -
QueryGroup Properties Int 11 - 0
Counted Quantity Counted in Inventory Num 19.6 -
OpenBlnc Initial Stock Num 19.6 -
EvalSystem Valuation Method VarChar 1 - A Moving Average
S Standard
F FIFO
UserSign User Signature Int 6 OUSR
FREE Free [Yes/No] VarChar 1 - N Y Yes
N No
PicturName Picture nVarChar 200 -
Transfered Year Transfer [Y/N] VarChar 1 - N Y Yes
N No
BlncTrnsfr Balances transferred [Yes/No] VarChar 1 - N Y Yes
N No
UserText Item Remarks Text 16 -
SerialNum Serial Number nVarChar 17 -
CommisPcnt % Commission for Item Num 19.6 -
CommisSum Total Commission for Item Num 19.6 -
CommisGrp Commission Group Int 6 - 0
TreeType BOM Type VarChar 1 - N N Not a BOM
A Assembly
S Sales
P Production
T Template
TreeQty No. of Units Num 19.6 -
LastPurPrc Last Purchase Price Num 19.6 -
LastPurCur Last Purchase Currency nVarChar 3 -
LastPurDat Last Purchase Date Date 8 -
ExitCur Issue Currency nVarChar 3 -
ExitPrice Issue Price Num 19.6 -
ExitWH Release Warehouse nVarChar 8 -
AssetItem Fixed Assets VarChar 1 - N Y Yes
N No
WasCounted Counted VarChar 1 - N Y Yes
N No
ManSerNum Serial No. Management VarChar 1 - N Y Yes
N No
SHeight1 Height 1 - Sales Unit Num 19.6 -
SHght1Unit Height 1 - UoM for Sales Int 6 -
SHeight2 Height 2 - Sales Unit Num 19.6 -
SHght2Unit Height 2 - UoM for Sales Int 6 -
SWidth1 Width 1 - Sales Unit Num 19.6 -
SWdth1Unit Width 1 - UoM for Sales Int 6 -
SWidth2 Width 2 - Sales Unit Num 19.6 -
SWdth2Unit Width 2 - UoM for Sales Int 6 -
SLength1 Length 1 - Sales Unit Num 19.6 -
SLen1Unit Length 1 - UoM for Sales Int 6 -
Slength2 Length 2 - Sales Unit Num 19.6 -
SLen2Unit Length 2 - UoM for Sales Int 6 -
SVolume Volume - Sales Unit Num 19.6 -
SVolUnit Volume - UoM for Sales Int 6 -
SWeight1 Weight 1 - Sales Unit Num 19.6 -
SWght1Unit Weight 1 - UoM for Sales Int 6 -
SWeight2 Weight 2 - Sales Unit Num 19.6 -
SWght2Unit Weight 2 - UoM for Sales Int 6 -
BHeight1 Height 1 - Purchasing Unit Num 19.6 -
BHght1Unit Height 1 - UoM for Purchasing Int 6 -
BHeight2 Height 2 - Purchasing Unit Num 19.6 -
BHght2Unit Height 2 - UoM for Purchasing Int 6 -
BWidth1 Width 1 - Purchasing Unit Num 19.6 -
BWdth1Unit Width 1 - UoM for Purchasing Int 6 -
BWidth2 Width 2 - Purchasing Unit Num 19.6 -
BWdth2Unit Width 2 - UoM for Purchasing Int 6 -
BLength1 Length 1 - Purchase Unit Num 19.6 -
BLen1Unit Length 1 - UoM for Purchasing Int 6 -
Blength2 Length 2 - Purchase Unit Num 19.6 -
BLen2Unit Length 2 - UoM for Purchasing Int 6 -
BVolume Quantity - Purchasing Unit Num 19.6 -
BVolUnit Volume - UoM for Purchasing Int 6 -
BWeight1 Weight 1 - Purchasing Unit Num 19.6 -
BWght1Unit Weight 1 - UoM for Purchasing Int 6 -
BWeight2 Weight 2 - Purchasing Unit Num 19.6 -
BWght2Unit Weight 2 - UoM for Purchasing Int 6 -
FixCurrCms Currency of Fixed Commission nVarChar 3 -
FirmCode Manufacturer Int 6 OMRC -1
LstSalDate Last Sale Date Date 8 -
QryGroup1 Property 1 VarChar 1 - N Y Yes
N No
QryGroup2 Property 2 VarChar 1 - N Y Yes
N No
QryGroup3 Property 3 VarChar 1 - N Y Yes
N No
QryGroup4 Property 4 VarChar 1 - N Y Yes
N No
QryGroup5 Property 5 VarChar 1 - N Y Yes
N No
QryGroup6 Property 6 VarChar 1 - N Y Yes
N No
QryGroup7 Property 7 VarChar 1 - N Y Yes
N No
QryGroup8 Property 8 VarChar 1 - N Y Yes
N No
QryGroup9 Property 9 VarChar 1 - N Y Yes
N No
QryGroup10 Property 10 VarChar 1 - N Y Yes
N No
QryGroup11 Property 11 VarChar 1 - N Y Yes
N No
QryGroup12 Property 12 VarChar 1 - N Y Yes
N No
QryGroup13 Property 13 VarChar 1 - N Y Yes
N No
QryGroup14 Property 14 VarChar 1 - N Y Yes
N No
QryGroup15 Property 15 VarChar 1 - N Y Yes
N No
QryGroup16 Property 16 VarChar 1 - N Y Yes
N No
QryGroup17 Property 17 VarChar 1 - N Y Yes
N No
QryGroup18 Property 18 VarChar 1 - N Y Yes
N No
QryGroup19 Property 19 VarChar 1 - N Y Yes
N No
QryGroup20 Property 20 VarChar 1 - N Y Yes
N No
QryGroup21 Property 21 VarChar 1 - N Y Yes
N No
QryGroup22 Property 22 VarChar 1 - N Y Yes
N No
QryGroup23 Property 23 VarChar 1 - N Y Yes
N No
QryGroup24 Property 24 VarChar 1 - N Y Yes
N No
QryGroup25 Property 25 VarChar 1 - N Y Yes
N No
QryGroup26 Property 26 VarChar 1 - N Y Yes
N No
QryGroup27 Property 27 VarChar 1 - N Y Yes
N No
QryGroup28 Property 28 VarChar 1 - N Y Yes
N No
QryGroup29 Property 29 VarChar 1 - N Y Yes
N No
QryGroup30 Property 30 VarChar 1 - N Y Yes
N No
QryGroup31 Property 31 VarChar 1 - N Y Yes
N No
QryGroup32 Property 32 VarChar 1 - N Y Yes
N No
QryGroup33 Property 33 VarChar 1 - N Y Yes
N No
QryGroup34 Property 34 VarChar 1 - N Y Yes
N No
QryGroup35 Property 35 VarChar 1 - N Y Yes
N No
QryGroup36 Property 36 VarChar 1 - N Y Yes
N No
QryGroup37 Property 37 VarChar 1 - N Y Yes
N No
QryGroup38 Property 38 VarChar 1 - N Y Yes
N No
QryGroup39 Property 39 VarChar 1 - N Y Yes
N No
QryGroup40 Property 40 VarChar 1 - N Y Yes
N No
QryGroup41 Property 41 VarChar 1 - N Y Yes
N No
QryGroup42 Property 42 VarChar 1 - N Y Yes
N No
QryGroup43 Property 43 VarChar 1 - N Y Yes
N No
QryGroup44 Property 44 VarChar 1 - N Y Yes
N No
QryGroup45 Property 45 VarChar 1 - N Y Yes
N No
QryGroup46 Property 46 VarChar 1 - N Y Yes
N No
QryGroup47 Property 47 VarChar 1 - N Y Yes
N No
QryGroup48 Property 48 VarChar 1 - N Y Yes
N No
QryGroup49 Property 49 VarChar 1 - N Y Yes
N No
QryGroup50 Property 50 VarChar 1 - N Y Yes
N No
QryGroup51 Property 51 VarChar 1 - N Y Yes
N No
QryGroup52 Property 52 VarChar 1 - N Y Yes
N No
QryGroup53 Property 53 VarChar 1 - N Y Yes
N No
QryGroup54 Property 54 VarChar 1 - N Y Yes
N No
QryGroup55 Property 55 VarChar 1 - N Y Yes
N No
QryGroup56 Property 56 VarChar 1 - N Y Yes
N No
QryGroup57 Property 57 VarChar 1 - N Y Yes
N No
QryGroup58 Property 58 VarChar 1 - N Y Yes
N No
QryGroup59 Property 59 VarChar 1 - N Y Yes
N No
QryGroup60 Property 60 VarChar 1 - N Y Yes
N No
QryGroup61 Property 61 VarChar 1 - N Y Yes
N No
QryGroup62 Property 62 VarChar 1 - N Y Yes
N No
QryGroup63 Property 63 VarChar 1 - N Y Yes
N No
QryGroup64 Property 64 VarChar 1 - N Y Yes
N No
CreateDate Production Date Date 8 -
UpdateDate Date of Update Date 8 -
ExportCode Data Export Code nVarChar 20 -
SalFactor1 Sales Factor 1 Num 19.6 -
SalFactor2 Sales Factor 2 Num 19.6 -
SalFactor3 Sales Factor 3 Num 19.6 -
SalFactor4 Sales Factor 4 Num 19.6 -
PurFactor1 Purchasing Factor 1 Num 19.6 -
PurFactor2 Purchasing Factor 2 Num 19.6 -
PurFactor3 Purchasing Factor 3 Num 19.6 -
PurFactor4 Purchasing Factor 4 Num 19.6 -
SalFormula Sales Formula nVarChar 40 -
PurFormula Purchasing Formula nVarChar 40 -
VatGroupPu Purchase Tax Definition nVarChar 8 OVTG
AvgPrice Item Cost Num 19.6 -
PurPackMsr Packaging UoM (Purchasing) nVarChar 8 -
PurPackUn Quantity per Packaging UoM Num 19.6 -
SalPackMsr Sales Pack nVarChar 8 -
SalPackUn Packaging UoM (Sales) Num 19.6 -
SCNCounter SCN Counter Int 6 -
ManBtchNum Manage Batch No. [Yes/No] VarChar 1 - N Y Yes
N No
ManOutOnly Manage SN Only on Exit VarChar 1 - N Y Yes
N No
DataSource Data Source VarChar 1 - N N Unknown
I Interface
U Update
M Import
O DI API
A Doc. Generation Wizard
D Restore Wizard
P Partner Implementation
T Year Transfer
validFor Active VarChar 1 - N Y Yes
N No
validFrom Valid From Date 8 -
validTo Valid to Date 8 -
frozenFor On Hold Period VarChar 1 - N Y Yes
N No
frozenFrom On Hold From Date 8 -
frozenTo On Hold End Date Date 8 -
BlockOut Force selection of serial no. VarChar 1 - Y Y Yes
N No
ValidComm Validity Remarks nVarChar 30 -
FrozenComm On Hold Remarks nVarChar 30 -
LogInstanc Log Instance Int 6 - 0
ObjType Object Type nVarChar 20 - 4
SWW Additional Identifier nVarChar 16 -
Deleted Deleted VarChar 1 - N Y Yes
N No
DocEntry Internal Number Int 11 -
ExpensAcct Expense Account nVarChar 15 OACT
FrgnInAcct Revenue Account - Foreign nVarChar 15 OACT
ShipType Shipping Type Int 6 -
GLMethod Set G/L Account by VarChar 1 - W W Warehouse
C Item Group
L Item Level
ECInAcct Revenue Account - EU nVarChar 15 -
FrgnExpAcc Expense Account - Foreign nVarChar 15 -
ECExpAcc Expense Account - EU nVarChar 15 -
TaxType Tax Type VarChar 1 - Y Y Regular Tax
U Use Tax
N No Tax
ByWh Inventory Management by Whse VarChar 1 -
WTLiable WTax Liable VarChar 1 - Y Y Yes
N No
ItemType Item Type VarChar 1 - I I Items
L Labor
T Travel
WarrntTmpl Warranty Template nVarChar 20 -
BaseUnit Base Unit Name nVarChar 20 -
CountryOrg Country of Origin nVarChar 3 -
StockValue Inventory Value Num 19.6 -
Phantom Phantom Item VarChar 1 - N Y Yes
N No
IssueMthd Issue Method VarChar 1 - B Backflush
M Manual
FREE1 Yield in % VarChar 1 -
PricingPrc Pricing Percentage Num 19.6 -
MngMethod Management Method VarChar 1 - R A On Every Transaction
R On Release Only
ReorderPnt Reorder Point Num 19.6 -
InvntryUom Inventory UoM nVarChar 20 -
PlaningSys Planning Method VarChar 1 - N M MRP
N None
PrcrmntMtd Procurement Method VarChar 1 - B B Buy
M Make
OrdrIntrvl Order Intervals Int 6 -
OrdrMulti Order Multiple Num 19.6 -
MinOrdrQty Minimum Order Quantity Num 19.6 -
LeadTime Lead Time Int 11 -
IndirctTax Indirect Tax VarChar 1 - N Y Yes
N No
TaxCodeAR Tax Code (A/R) nVarChar 8 OSTC
TaxCodeAP Tax Code (A/P) nVarChar 8 OSTC
OSvcCode Outgoing Service Code Int 11 OSCD
ISvcCode Incoming Service Code Int 11 OSCD
ServiceGrp Service Group Int 11 OSGP
NCMCode NCM Code Int 11 ONCM
MatType Material Type VarChar 1 - 1 1 Finished Goods
2 Goods in Process
3 Raw Material
MatGrp Material Group Int 11 OMGP -1
ProductSrc Product Source VarChar 1 - 1 1 Purchased from the domestic vendor
2 Imported by company
3 Imported goods purchased from the domestic vendor
4 Produced by the Company

Primary Key Unique Field
PRIMARY
Y
ItemCode
ITEM_NAME
N
ItemName
TREE_TYPE
N
TreeType
COM_GROUP
N
CommisGrp
SALE
N
SellItem
PURCHASE
N
PrchseItem
INVENTORY
N
InvntItem

De esta tabla usaremos principal mente los campos de 
  • ItemCode : Es el identificador de la tabla usualmente se usa como el numero que identifica el producto también es conocido como numero de parte.
  • ItemName: Esta es la descripción del producto
  • OnHand: La cantidad de artículos en existencia dentro del almacen
  • IsCommited: La cantidad de artículos comprometidos en algun pedido
  • OnOrder: La cantidad de articulos solicitados a proveedor.

Lista de Precios por articulo

La los precios de los articulos esta definida en la Tabla ITM1  de la cual a continuación muestro la informacion de la misma que se obtiene de informacion que proporciona el SDK de SAP:

Table name: ITM1

Field Description Type Size Related Default Value Constraints
ItemCode Item No. nVarChar 20 OITM
PriceList Price List No. Int 6 OPLN
Price List Price Num 19.6 -
Currency Currency for List Price nVarChar 3 OCRN
Ovrwritten Manual Price Entry VarChar 1 - N Y
N
Factor Factor Num 19.6 -
LogInstanc Log Instance Int 11 - 0
ObjType Object nVarChar 20 - 4
AddPrice1 Additional Price (1) Num 19.6 -
Currency1 Currency for Add. Price 1 nVarChar 3 OCRN
AddPrice2 Additional Price (2) Num 19.6 -
Currency2 Currency for Add. Price 2 nVarChar 3 OCRN
Ovrwrite1 Manual Price Entry (1) VarChar 1 - N Y
N
Ovrwrite2 Manual Price Entry (2) VarChar 1 - N Y
N


Primary Key Unique Field
PRIMARY
Y
ItemCode
PriceList
CURRENCY
N
Currency
PRICE_LIST
N
PriceList
MANUAL
N
Ovrwritten









De esta tabla  los siguientes campos:
  • PriceList: El Id de la tabla de lista de precios.
  • Price: Precio del articulo.
  • Currency: Moneda del precio id de la tabla OCRN
  • IsCommited: La cantidad de artículos comprometidos en algun pedido
  • OnOrder: La cantidad de articulos solicitados a proveedor.

Catalogo de Lista de Precios

SAP nos permite administrar varias listas de precios para realizar las ventas y cotizaciones  por ejemplo una puede ser la lista de publico en general y otra de distribuidores el cual se almacena en la tabla OPLN, de la cual a continuación muestro la información de la misma que se obtiene de información que proporciona el SDK de SAP:

Table name: OPLN

Field Description Type Size Related Default Value Constraints
ListNum Price List No. Int 6 -
ListName Price List Name nVarChar 32 -
BASE_NUM Base Price List Int 6 OPLN
Factor Factor Num 19.6 -
RoundSys Rounding Method Int 6 - 0 0
1
2
3
4
5
GroupCode Group No. Int 6 - 1 1
2
3
4
DataSource Data Source VarChar 1 - N N
I
U
M
O
A
D
P
T
SPPCounter SPP Counter Int 11 -
UserSign User Signature Int 6 OUSR
IsGrossPrc Gross Price? VarChar 1 - N Y
N
LogInstanc Log Instance Int 11 - 0
UserSign2 Updating User Int 6 OUSR
UpdateDate Update Date Date 8 -
ValidFor Active VarChar 1 - Y Y
N
ValidFrom Active From Date 8 -
ValidTo Active To Date 8 -
CreateDate Creation Date Date 8 -
PrimCurr Primary Default Currency nVarChar 3 -
AddCurr1 Additional Default Currency 1 nVarChar 3 -
AddCurr2 Additional Default Currency 2 nVarChar 3 -
RoundRule Rounding Rule VarChar 1 - R R
C
F
ExtAmount Fixed Amount (Ending/Interval) Num 19.6 -

Primary Key Unique Field
PRIMARY
Y
ListNum
LIST_NAME
Y
ListName





De esta tabla no usamos un campo directamente pero es importante conocer que existe pues puede que el valor del precio devuelto por el web service variara segun la lista de precios en este caso la lista estará fija en la de precios al publico por lo que no la consultaremos.



Y por ultimo la y no menos importate la tabla de la moneda..


Field Description Type Size Related Default Value Constraints
CurrCode Currency Code nVarChar 3 -
CurrName Currency nVarChar 20 -
ChkName Name on Printed Checks nVarChar 20 -
Chk100Name Name of 100's on checks nVarChar 20 -
DocCurrCod Name on Printed Docs. nVarChar 3 -
FrgnName English nVarChar 20 -
F100Name English Hundredth Name nVarChar 20 -
Locked Locked VarChar 1 - N Y
N
DataSource Data Source VarChar 1 - N N
I
U
M
O
A
D
P
T
UserSign User Signature Int 6 OUSR
RoundSys Rounding Int 6 - 0 0
4
1
2
3
UserSign2 Updating User Int 6 OUSR
Decimals Decimals Int 6 - -1 -1
0
1
2
3
4
5
6
ISRCalc ISR Calculation VarChar 1 - N Y
N
RoundPym Rounding in Pmnt VarChar 1 - N Y
N
ConvUnit Is a Conventional Unit VarChar 1 - N Y
N
BaseCurr Base Currency for Conv. Unit nVarChar 3 OCRN
Factor Factor Num 19.6 -
ChkNamePl Plural for Int.Description nVarChar 20 -
Chk100NPl Plural for Hundredth Name nVarChar 20 -
FrgnNamePl Plural for English nVarChar 20 -
F100NamePl Plural for Eng. Hundredth Name nVarChar 20 -
ISOCurrCod ISO Currency Code nVarChar 3 -
AED
AFN
ALL
AMD
ANG
AOA
ARS
AUD
AWG
AZM
AZN
BAM
BBD
BDT
BGN
BHD
BIF
BMD
BND
BOB
BRL
BSD
BTN
BWP
BYR
BZD
CAD
CDF
CHF
CLP
CNY
COP
CRC
CUP
CVE
CYP
CZK
DJF
DKK
DOP
DZD
EEK
EGP
ERN
ETB
EUR
FJD
FKP
GBP
GEL
GGP
GHC
GHS
GIP
GMD
GNF
GTQ
GYD
HKD
HNL
HRK
HTG
HUF
IDR
ILS
IMP
INR
IQD
IRR
ISK
JEP
JMD
JOD
JPY
KES
KGS
KHR
KMF
KPW
KRW
KWD
KYD
KZT
LAK
LBP
LKR
LRD
LSL
LTL
LVL
LYD
MAD
MDL
MGA
MKD
MMK
MNT
MOP
MRO
MTL
MUR
MVR
MWK
MXN
MYR
MZM
MZN
NAD
NGN
NIO
NOK
NPR
NZD
OMR
PAB
PEN
PGK
PHP
PKR
PLN
PYG
QAR
ROL
RON
RSD
RUB
RWF
SAR
SBD
SCR
SDD
SDG
SEK
SGD
SHP
SIT
SKK
SLL
SOS
SPL
SRD
STD
SVC
SYP
SZL
THB
TJS
TMM
TND
TOP
TRY
TTD
TVD
TWD
TZS
UAH
UGX
USD
UYU
UZS
VEB
VND
VUV
WST
XAF
XAG
XAU
XCD
XDR
XOF
XPD
XPF
XPT
YER
ZAR
ZMK
ZWD
MaxInDiff Incoming Amt Diff. Allowed Num 19.6 -
MaxOutDiff Outgoing Amt Diff. Allowed Num 19.6 -
MaxInPcnt Incoming % Diff. Allowed Num 19.6 -
MaxOutPcnt Outgoing % Diff. Allowed Num 19.6 -
ISOCurrNum ISO Currency Number nVarChar 3 -


Primary Key Unique Field
PRIMARY
Y
CurrCode
CUR_NAME
N
CurrName





En nuestro caso no usaremos esta tabla dado que el CurrCode es un descripción valida de moneda si en tu caso no es así llama a esta tabla y úsala para expresar la moneda.