示例#1
0
        private void toolBar_btnNew_Click(object sender)
        {
            sales_rep sales_rep = new sales_rep();

            sales_rep.State      = EntityState.Added;
            sales_rep.IsSelected = true;
            sales_rep.timestamp  = DateTime.Now.AddDays(0);

            dbContext.Entry(sales_rep).State = EntityState.Added;
            sales_rep.State = EntityState.Added;
            sales_repViewSource.View.MoveCurrentToLast();
        }
示例#2
0
 private void toolBar_btnEdit_Click(object sender)
 {
     if (sales_repDataGrid.SelectedItem != null)
     {
         sales_rep sales_rep_rep = (sales_rep)sales_repDataGrid.SelectedItem;
         sales_rep_rep.IsSelected             = true;
         sales_rep_rep.State                  = EntityState.Modified;
         dbContext.Entry(sales_rep_rep).State = EntityState.Modified;
     }
     else
     {
         toolBar.msgWarning("Please Select a Record");
     }
 }
示例#3
0
        private void sync_SalesRep()
        {
            DataTable dt = exeDT("SELECT * FROM VENDEDOR");

            foreach (DataRow row in dt.Rows)
            {
                sales_rep sales_rep = new sales_rep();
                sales_rep.name       = (string)row["DESVENDEDOR"];
                sales_rep.id_company = id_company;
                sales_rep.is_active  = true;
                dbContext.sales_rep.Add(sales_rep);
            }
            dt.Clear();
            dbContext.SaveChanges();
        }
示例#4
0
 private void cbxSalesRepType_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     stackContact.Visibility = Visibility.Visible;
     if (cbxSalesRepType.SelectedItem != null)
     {
         sales_rep sales_rep = new sales_rep();
         contactViewSource.View.Filter = i =>
         {
             contact contact       = i as contact;
             int     SelectedIndex = (cbxSalesRepType.SelectedIndex) + 1;
             if (SelectedIndex == (int)sales_rep.SalesRepType.Salesman ||
                 SelectedIndex == (int)sales_rep.SalesRepType.Collector)
             {
                 if (contact.is_employee == true || contact.is_supplier == true)
                 {
                     return(true);
                 }
                 else
                 {
                     return(false);
                 }
             }
             else if (SelectedIndex == (int)sales_rep.SalesRepType.PurchaseAgent)
             {
                 if (contact.is_customer == true)
                 {
                     return(true);
                 }
                 else
                 {
                     return(false);
                 }
             }
             else
             {
                 return(false);
             }
         };
     }
 }
示例#5
0
文件: Sales.cs 项目: mercaditu/ERP
        public void sales()
        {
            string sql = " SELECT "
                         + " dbo.VENTAS.CODVENTA, dbo.VENTAS.NUMVENTA, dbo.VENTAS.FECHAVENTA, dbo.VENTAS.PORCENTAJEDESCUENTO,"
                         + " dbo.VENTAS.TOTALEXENTA, dbo.VENTAS.TOTALGRAVADA, dbo.VENTAS.TOTALIVA, dbo.VENTAS.TOTALDESCUENTO,"
                         + " dbo.VENTAS.MODALIDADPAGO, dbo.VENTAS.FECGRA, dbo.VENTAS.ESTADO, dbo.VENTAS.MOTIVOANULADO,"
                         + " dbo.VENTAS.FECHAANULADO, dbo.VENTAS.TIPOVENTA, dbo.VENTAS.TIPOPRECIO, dbo.VENTAS.NUMVENTATIMBRADO,"
                         + " dbo.VENTAS.TOTAL5, dbo.VENTAS.TOTAL10, dbo.VENTAS.CODPRESUPUESTO, dbo.VENTAS.METODO, dbo.VENTAS.ENVIADO,"
                         + " dbo.VENTAS.TOTALGRAVADO5, dbo.VENTAS.TOTALGRAVADO10, dbo.VENTAS.ASENTADO,"
                         + " dbo.VENTAS.TOTALVENTA, dbo.VENDEDOR.DESVENDEDOR, dbo.CLIENTES.NOMBRE, dbo.CLIENTES.RUC,"
                         + " dbo.SUCURSAL.DESSUCURSAL, dbo.VENTAS.COTIZACION1, FACTURACOBRAR_1.FECHAVCTO,"
                         + " dbo.FACTURACOBRAR.FECHAVCTO AS Expr1, dbo.FACTURACOBRAR.SALDOCUOTA, dbo.FACTURACOBRAR.IMPORTECUOTA, "
                         + " dbo.FACTURACOBRAR.COTIZACION, dbo.VENTASFORMACOBRO.IMPORTE, dbo.VENTASFORMACOBRO.DESTIPOCOBRO,"
                         + " dbo.VENTASFORMACOBRO.NUMDEVOLUCION, dbo.VENTASFORMACOBRO.TIPOCOBRO"
                         + " FROM  dbo.SUCURSAL RIGHT OUTER JOIN"
                         + " dbo.FACTURACOBRAR RIGHT OUTER JOIN"
                         + " dbo.VENTAS ON dbo.FACTURACOBRAR.CODVENTA = dbo.VENTAS.CODVENTA LEFT OUTER JOIN"
                         + " dbo.VENTASFORMACOBRO ON dbo.VENTAS.CODVENTA = dbo.VENTASFORMACOBRO.CODVENTA ON dbo.SUCURSAL.CODSUCURSAL = dbo.VENTAS.CODSUCURSAL"
                         + " LEFT OUTER JOIN dbo.VENDEDOR ON dbo.VENTAS.CODVENDEDOR = dbo.VENDEDOR.CODVENDEDOR LEFT OUTER JOIN"
                         + " dbo.CLIENTES ON dbo.VENTAS.CODCLIENTE = dbo.CLIENTES.CODCLIENTE LEFT OUTER JOIN"
                         + " dbo.FACTURACOBRAR AS FACTURACOBRAR_1 ON dbo.VENTAS.CODVENTA = FACTURACOBRAR_1.CODVENTA";

            SqlConnection conn = new SqlConnection(_connString);

            //Counts Total number of Rows we have to process
            SqlCommand cmd = new SqlCommand(sql, conn);

            conn.Open();
            cmd.CommandType = CommandType.Text;
            DataTable dt_sales = exeDT(sql);
            int       count    = (int)dt_sales.Rows.Count;

            conn.Close();

            int value = 0;

            Dispatcher.BeginInvoke((Action)(() => salesMaximum.Text = count.ToString()));
            Dispatcher.BeginInvoke((Action)(() => salesValue.Text = value.ToString()));
            Dispatcher.BeginInvoke((Action)(() => progSales.Maximum = count));
            Dispatcher.BeginInvoke((Action)(() => progSales.Value = value));

            //Sales Invoice Detail
            string sqlDetail = "SELECT"
                               + " dbo.PRODUCTOS.DESPRODUCTO,"           //0
                               + " dbo.VENTASDETALLE.CANTIDADVENTA,"     //1
                               + " dbo.VENTASDETALLE.PRECIOVENTANETO, "  //2
                               + " dbo.VENTASDETALLE.PRECIOVENTALISTA, " //3
                               + " dbo.VENTASDETALLE.COSTOPROMEDIO, "    //4
                               + " dbo.VENTASDETALLE.COSTOULTIMO, "      //5
                               + " dbo.VENTASDETALLE.IVA, "              //6
                               + " dbo.VENTAS.COTIZACION1, "             //7
                               + " dbo.MONEDA.DESMONEDA, "               //8
                               + " dbo.VENTASDETALLE.CODVENTA"
                               + " FROM dbo.VENTAS LEFT OUTER JOIN"
                               + " dbo.MONEDA ON dbo.VENTAS.CODMONEDA = dbo.MONEDA.CODMONEDA LEFT OUTER JOIN"
                               + " dbo.VENTASDETALLE ON dbo.VENTAS.CODVENTA = dbo.VENTASDETALLE.CODVENTA LEFT OUTER JOIN"
                               + " dbo.PRODUCTOS ON dbo.VENTASDETALLE.CODPRODUCTO = dbo.PRODUCTOS.CODPRODUCTO";

            DataTable dt_detail = exeDT(sqlDetail);

            int RoofValue  = 1000;
            int FloorValue = 0;

            //Run a Foreach Lap
            for (int i = FloorValue; i < RoofValue; i++)
            {
                using (SalesInvoiceDB db = new SalesInvoiceDB())
                {
                    db.Configuration.AutoDetectChangesEnabled = false;

                    List <entity.app_vat_group>  VATGroupList       = db.app_vat_group.Where(x => x.id_company == CurrentSession.Id_Company).ToList();
                    List <entity.contact>        ContactList        = db.contacts.Where(x => x.id_company == CurrentSession.Id_Company).ToList();
                    List <entity.sales_rep>      sales_repList      = db.sales_rep.Where(x => x.id_company == CurrentSession.Id_Company).ToList();
                    List <entity.app_branch>     BranchList         = db.app_branch.Where(x => x.id_company == CurrentSession.Id_Company).ToList();
                    List <entity.app_location>   LocationList       = db.app_location.Where(x => x.id_company == CurrentSession.Id_Company).ToList();
                    List <entity.app_terminal>   TerminalList       = db.app_terminal.Where(x => x.id_company == CurrentSession.Id_Company).ToList();
                    List <entity.item>           ItemList           = db.items.Where(x => x.id_company == CurrentSession.Id_Company).ToList();
                    List <entity.app_currencyfx> app_currencyfxList = db.app_currencyfx.Where(x => x.id_company == CurrentSession.Id_Company).ToList();

                    app_condition  app_conditionCrédito = db.app_condition.Where(x => x.name == "Crédito" && x.id_company == id_company).FirstOrDefault();
                    app_condition  app_conditionContado = db.app_condition.Where(x => x.name == "Contado" && x.id_company == id_company).FirstOrDefault();
                    app_currencyfx app_currencyfx       = null;
                    if (app_currencyfxList.Where(x => x.is_active).FirstOrDefault() != null)
                    {
                        app_currencyfx = app_currencyfxList.Where(x => x.is_active).FirstOrDefault();
                    }

                    app_vat_group app_vat_group10 = VATGroupList.Where(x => x.name.Contains("10")).FirstOrDefault();
                    app_vat_group app_vat_group5  = VATGroupList.Where(x => x.name.Contains("5")).FirstOrDefault();
                    app_vat_group app_vat_group0  = VATGroupList.Where(x => x.name.Contains("0")).FirstOrDefault();


                    foreach (DataRow InnerRow in dt_sales.Select("CODVENTA > " + FloorValue + " AND CODVENTA < " + RoofValue + ""))
                    {
                        sales_invoice sales_invoice = new entity.sales_invoice();
                        sales_invoice.State      = EntityState.Added;
                        sales_invoice.status     = Status.Documents_General.Pending;
                        sales_invoice.IsSelected = true;
                        sales_invoice.trans_type = Status.TransactionTypes.Normal;
                        sales_invoice.trans_date = DateTime.Now.AddDays(0);
                        sales_invoice.timestamp  = DateTime.Now;
                        sales_invoice.id_company = id_company;
                        sales_invoice.number     = (InnerRow["NUMVENTA"] is DBNull) ? null : InnerRow["NUMVENTA"].ToString();

                        sales_invoice.trans_date = (InnerRow["FECHAVENTA"] is DBNull) ? DateTime.Now :Convert.ToDateTime(InnerRow["FECHAVENTA"]);

                        //Customer
                        if (!(InnerRow["NOMBRE"] is DBNull))
                        {
                            string  _customer = InnerRow["NOMBRE"].ToString();
                            contact contact   = ContactList.Where(x => x.name == _customer && x.id_company == id_company).FirstOrDefault();

                            if (contact != null)
                            {
                                sales_invoice.id_contact = contact.id_contact;
                                sales_invoice.contact    = contact;
                            }
                        }

                        //Condition (Cash or Credit)
                        if (!(InnerRow["TIPOVENTA"] is DBNull) && Convert.ToByte(InnerRow["TIPOVENTA"]) == 0)
                        {
                            sales_invoice.id_condition = app_conditionContado.id_condition;
                            //Contract...

                            app_contract_detail app_contract_detail =
                                db.app_contract_detail.Where(x => x.id_company == id_company &&
                                                             x.app_contract.id_condition == app_conditionContado.id_condition)
                                .FirstOrDefault();

                            if (app_contract_detail != null)
                            {
                                sales_invoice.app_contract = app_contract_detail.app_contract;
                                sales_invoice.id_contract  = app_contract_detail.id_contract;
                            }
                            else
                            {
                                app_contract app_contract = GenerateDefaultContrat(app_conditionContado, 0);
                                db.app_contract.Add(app_contract);
                                sales_invoice.app_contract = app_contract;
                                sales_invoice.id_contract  = app_contract.id_contract;
                            }
                        }
                        else if (!(InnerRow["TIPOVENTA"] is DBNull) && Convert.ToByte(InnerRow["TIPOVENTA"]) == 1)
                        {
                            sales_invoice.id_condition = app_conditionCrédito.id_condition;

                            //Contract...
                            if (!(InnerRow["FECHAVCTO"] is DBNull))
                            {
                                DateTime _due_date = Convert.ToDateTime(InnerRow["FECHAVCTO"]);
                                int      interval  = (_due_date - sales_invoice.trans_date).Days;

                                app_contract_detail app_contract_detail =
                                    db.app_contract_detail.Where(x =>
                                                                 x.app_contract.id_condition == sales_invoice.id_condition &&
                                                                 x.app_contract.id_company == id_company &&
                                                                 x.interval == interval).FirstOrDefault();

                                if (app_contract_detail != null)
                                {
                                    sales_invoice.app_contract = app_contract_detail.app_contract;
                                    sales_invoice.id_contract  = app_contract_detail.id_contract;
                                }
                                else
                                {
                                    app_contract app_contract = GenerateDefaultContrat(app_conditionCrédito, interval);
                                    db.app_contract.Add(app_contract);
                                    sales_invoice.app_contract = app_contract;
                                    sales_invoice.id_contract  = app_contract.id_contract;
                                }
                            }
                            else
                            {
                                if (db.app_contract.Where(x => x.name == "0 Días").Count() == 0)
                                {
                                    app_contract app_contract = GenerateDefaultContrat(app_conditionCrédito, 0);
                                    db.app_contract.Add(app_contract);
                                    sales_invoice.app_contract = app_contract;
                                    sales_invoice.id_contract  = app_contract.id_contract;
                                }
                                else
                                {
                                    app_contract app_contract = db.app_contract.Where(x => x.name == "0 Días").FirstOrDefault();
                                    sales_invoice.app_contract = app_contract;
                                    sales_invoice.id_contract  = app_contract.id_contract;
                                }
                            }
                        }
                        else
                        {
                            sales_invoice.id_condition = app_conditionContado.id_condition;

                            if (db.app_contract.Where(x => x.name == "0 Días").Count() == 0)
                            {
                                app_contract app_contract = GenerateDefaultContrat(app_conditionContado, 0);
                                db.app_contract.Add(app_contract);
                                sales_invoice.app_contract = app_contract;
                                sales_invoice.id_contract  = app_contract.id_contract;
                            }
                            else
                            {
                                app_contract app_contract = db.app_contract.Where(x => x.name == "0 Días").FirstOrDefault();
                                sales_invoice.app_contract = app_contract;
                                sales_invoice.id_contract  = app_contract.id_contract;
                            }
                        }

                        //Sales Rep
                        if (!(InnerRow["DESVENDEDOR"] is DBNull))
                        {
                            string    _sales_rep = InnerRow["DESVENDEDOR"].ToString();
                            sales_rep sales_rep  = sales_repList.Where(x => x.name == _sales_rep && x.id_company == id_company).FirstOrDefault();
                            sales_invoice.id_sales_rep = sales_rep.id_sales_rep;
                        }

                        int          id_location  = 0;
                        app_location app_location = null;

                        //Branch
                        if (!(InnerRow["DESSUCURSAL"] is DBNull))
                        {
                            //Branch
                            string     _branch    = InnerRow["DESSUCURSAL"].ToString();
                            app_branch app_branch = BranchList.Where(x => x.name == _branch && x.id_company == id_company).FirstOrDefault();
                            sales_invoice.id_branch = app_branch.id_branch;

                            //Location
                            if (LocationList.Where(x => x.id_branch == app_branch.id_branch && x.is_default).FirstOrDefault() != null)
                            {
                                id_location  = LocationList.Where(x => x.id_branch == app_branch.id_branch && x.is_default).FirstOrDefault().id_location;
                                app_location = LocationList.Where(x => x.id_branch == app_branch.id_branch && x.is_default).FirstOrDefault();
                            }


                            //Terminal
                            sales_invoice.id_terminal = TerminalList.Where(x => x.app_branch.id_branch == app_branch.id_branch).FirstOrDefault().id_terminal;
                        }


                        if (app_currencyfx != null)
                        {
                            sales_invoice.id_currencyfx  = app_currencyfx.id_currencyfx;
                            sales_invoice.app_currencyfx = app_currencyfx;
                        }

                        DataTable dt_CurrentDetail = new DataTable();
                        if (dt_detail.Select("CODVENTA =" + InnerRow[0].ToString()).Count() > 0)
                        {
                            dt_CurrentDetail = dt_detail.Select("CODVENTA =" + InnerRow[0].ToString()).CopyToDataTable();
                        }

                        foreach (DataRow row in dt_CurrentDetail.Rows)
                        {
                            //db Related Insertion.
                            sales_invoice_detail sales_invoice_detail = new sales_invoice_detail();

                            string _prod_Name = row["DESPRODUCTO"].ToString();
                            item   item       = ItemList.Where(x => x.name == _prod_Name && x.id_company == id_company).FirstOrDefault();
                            sales_invoice_detail.id_item  = item.id_item;
                            sales_invoice_detail.quantity = Convert.ToDecimal(row["CANTIDADVENTA"]);

                            sales_invoice_detail.id_location  = id_location;
                            sales_invoice_detail.app_location = app_location;

                            string _iva = row["IVA"].ToString();
                            if (_iva == "10.00")
                            {
                                if (app_vat_group10 != null)
                                {
                                    sales_invoice_detail.id_vat_group = app_vat_group10.id_vat_group;
                                }
                            }
                            else if (_iva == "5.00")
                            {
                                if (app_vat_group5 != null)
                                {
                                    sales_invoice_detail.id_vat_group = app_vat_group5.id_vat_group;
                                }
                            }
                            else
                            {
                                if (app_vat_group0 != null)
                                {
                                    sales_invoice_detail.id_vat_group = app_vat_group0.id_vat_group;
                                }
                            }

                            decimal cotiz1 = Convert.ToDecimal((row["COTIZACION1"] is DBNull) ? 1 : Convert.ToDecimal(row["COTIZACION1"]));
                            if (cotiz1 == 0)
                            {
                                cotiz1 = 1;
                            }
                            sales_invoice_detail.unit_price = (Convert.ToDecimal(row["PRECIOVENTANETO"]) / sales_invoice_detail.quantity) / cotiz1;
                            sales_invoice_detail.unit_cost  = Convert.ToDecimal(row["COSTOPROMEDIO"]);

                            //Commit Sales Invoice Detail
                            sales_invoice.sales_invoice_detail.Add(sales_invoice_detail);
                        }

                        if (sales_invoice.Error == null)
                        {
                            sales_invoice.State      = System.Data.Entity.EntityState.Added;
                            sales_invoice.IsSelected = true;
                            db.sales_invoice.Add(sales_invoice);

                            if (!(InnerRow["ESTADO"] is DBNull))
                            {
                                int status = Convert.ToInt32(InnerRow["ESTADO"]);

                                if (status == 0)
                                {
                                    sales_invoice.status = Status.Documents_General.Pending;
                                }
                                else if (status == 1)
                                {
                                    db.Approve(true);
                                    sales_invoice.State      = System.Data.Entity.EntityState.Modified;
                                    sales_invoice.status     = Status.Documents_General.Approved;
                                    sales_invoice.IsSelected = true;

                                    add_paymnet_detail(db, sales_invoice, InnerRow["SALDOCUOTA"], InnerRow["IMPORTE"]);
                                }
                                else if (status == 2)
                                {
                                    sales_invoice.status = Status.Documents_General.Annulled;

                                    if (!(InnerRow["MOTIVOANULADO"] is DBNull))
                                    {
                                        sales_invoice.comment = InnerRow["MOTIVOANULADO"].ToString();
                                    }
                                }

                                try
                                {
                                    db.SaveChanges();
                                    sales_invoice.IsSelected = false;
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                            }
                        }
                        else
                        {
                            //Add code to include error contacts into
                            SalesInvoice_ErrorList.Add(sales_invoice);
                        }
                        // }
                        value += 1;
                        Dispatcher.BeginInvoke((Action)(() => progSales.Value = value));
                        Dispatcher.BeginInvoke((Action)(() => salesValue.Text = value.ToString()));
                    }
                }


                FloorValue = RoofValue;
                RoofValue += 1000;
            }
        }
示例#6
0
文件: Customer.cs 项目: mercaditu/ERP
        public void customer()
        {
            string sql = " SELECT "
                         + " VENDEDOR.DESVENDEDOR,"
                         + " TIPOCLIENTE.DESTIPOCLIENTE, "
                         + " ZONA.DESZONA, "
                         + " CIUDAD.DESCIUDAD, "
                         + " PAIS.DESPAIS, "
                         + " CLIENTES.NUMCLIENTE, " //5
                         + " CLIENTES.NOMBRE, "
                         + " CLIENTES.RUC,"
                         + " CLIENTES.DIRECCION, "
                         + " CLIENTES.TELEFONO,"
                         + " CLIENTES.CELULAR, " //10
                         + " CLIENTES.FAX, "
                         + " CLIENTES.EMAIL, "
                         + " CLIENTES.WEB, "
                         + " CLIENTES.LIMCREDITO, "
                         + " CLIENTES.PORCENTAJE, " //15
                         + " CLIENTES.OBSERVACION, "
                         + " CLIENTES.SEPSA, "
                         + " CLIENTES.RELACION, "  // 18
                         + " CLIENTES.TIPOVENTA, "
                         + " CLIENTES.TELEFONO1, " //20
                         + " CLIENTES.EMAIL1, "
                         + " CLIENTES.DIASVENCIMIENTO, "
                         + " CLIENTES.CONDICIONVENTA, "
                         + " CLIENTES.NUMEROTOL, "
                         + " CLIENTES.PROVEEDOR_ID, " //25
                         + " CLIENTES.PERSONAJURIDICA, "
                         + " CLIENTES.TIMBRADORETENCION, "
                         + " CLIENTES.CODCATEGORIACLIENTE, "
                         + " CATEGORIACLIENTE.DESCATEGORIACLIENTE,"
                         + " CLIENTES.NOMBREFANTASIA, " //30
                         + " CLIENTES.CUSTOMFIELD, "
                         + " CLIENTES.CODCLIENTE, "
                         + " CLIENTES.SEXO, "
                         + " CLIENTES.FECHANACIMIENTO,"
                         + " CLIENTES.FECHAINGRESO,"   //35
                         + " PRODUCTOS.DESPRODUCTO,"
                         + " CLIENTES.EMPPRESACLIENTE" //35
                         + " FROM VENDEDOR "
                         + " RIGHT OUTER JOIN  CIUDAD RIGHT OUTER JOIN ZONA ON CIUDAD.CODCIUDAD = ZONA.CODCIUDAD RIGHT OUTER JOIN"
                         + " TIPOCLIENTE RIGHT OUTER JOIN CLIENTES LEFT OUTER JOIN CATEGORIACLIENTE ON CLIENTES.CODCATEGORIACLIENTE = CATEGORIACLIENTE.CODCATEGORIACLIENTE ON "
                         + " TIPOCLIENTE.CODTIPOCLIENTE = CLIENTES.CODTIPOCLIENTE ON ZONA.CODZONA = CLIENTES.CODZONA ON "
                         + " VENDEDOR.CODVENDEDOR = CLIENTES.CODVENDEDOR LEFT OUTER JOIN"
                         + " PAIS ON CIUDAD.CODPAIS = PAIS.CODPAIS  LEFT OUTER JOIN"
                         + " PRODUCTOS ON CLIENTES.PROVEEDOR_ID = PRODUCTOS.CODPRODUCTO ";

            SqlConnection conn = new SqlConnection(_connString);

            //Counts Total number of Rows we have to process
            SqlCommand cmd = new SqlCommand(sql, conn);

            conn.Open();
            cmd.CommandText = "SELECT COUNT(*) FROM CLIENTES";
            cmd.CommandType = CommandType.Text;
            int count = (int)cmd.ExecuteScalar();

            conn.Close();

            int value = 0;

            Dispatcher.BeginInvoke((Action)(() => customerMaximum.Text = count.ToString()));
            Dispatcher.BeginInvoke((Action)(() => customerValue.Text = value.ToString()));
            Dispatcher.BeginInvoke((Action)(() => progCustomer.Maximum = count));
            Dispatcher.BeginInvoke((Action)(() => progCustomer.Value = value));

            cmd = new SqlCommand(sql, conn);
            conn.Open();
            cmd.CommandType = CommandType.Text;
            // SqlDataReader reader = cmd.ExecuteReader();
            DataTable dt_customer = exeDT(sql);

            foreach (DataRow reader in dt_customer.Rows)
            {
                using (entity.db db = new entity.db())
                {
                    db.Configuration.AutoDetectChangesEnabled = false;

                    contact contacts = new contact();
                    contacts.id_company = id_company;

                    contacts.is_active   = true;
                    contacts.is_customer = true;
                    contacts.is_supplier = false;
                    contacts.is_employee = false;

                    if (!(reader[6] is DBNull))
                    {
                        contacts.name = reader[6].ToString();
                    }
                    else
                    {
                        continue;
                    }

                    contacts.code         = (reader[5] is DBNull) ? null : reader[5].ToString();
                    contacts.gov_code     = (reader[7] is DBNull) ? "xxx" : reader[7].ToString();
                    contacts.credit_limit = (reader[14] is DBNull) ? 0 : (decimal)reader[14];
                    contacts.address      = (reader[8] is DBNull) ? null : reader[8].ToString();
                    contacts.telephone    = (reader[9] is DBNull) ? null : reader[9].ToString();
                    contacts.email        = (reader[12] is DBNull) ? null : reader[12].ToString();
                    contacts.alias        = (reader[30] is DBNull) ? null : reader[30].ToString();

                    int    _dias        = Convert.ToInt32((reader["DIASVENCIMIENTO"] is DBNull) ? 0 : reader["DIASVENCIMIENTO"]);
                    string contrat_name = _dias + " " + "Días";
                    if (db.app_contract.Where(x => x.name == contrat_name).FirstOrDefault() != null)
                    {
                        app_contract app_contract = db.app_contract.Where(x => x.name == contrat_name).FirstOrDefault();
                        contacts.id_contract  = app_contract.id_contract;
                        contacts.app_contract = app_contract;
                    }

                    contacts.id_contact_role = db.contact_role.Where(x => x.is_principal == true && x.id_company == id_company).FirstOrDefault().id_contact_role;

                    if (_connString.Contains("Angelius"))
                    {
                        if (!(reader[18] is DBNull))
                        {
                            contacts.timestamp = Convert.ToDateTime(reader[35]);
                        }

                        contacts.is_person = true;

                        string role_name = (reader[31] is DBNull) ? null : reader[31].ToString();
                        if (db.contact_role.Where(x => x.name == role_name && x.id_company == id_company).FirstOrDefault() != null)
                        {
                            contacts.id_contact_role = db.contact_role.Where(x => x.name == role_name && x.id_company == id_company).FirstOrDefault().id_contact_role;
                        }
                        else
                        {
                            if (db.app_field.Where(x => x.field_type == app_field.field_types.Account).FirstOrDefault() != null)
                            {
                                app_field           app_field           = db.app_field.Where(x => x.field_type == app_field.field_types.Account).FirstOrDefault();
                                contact_field_value contact_field_value = new entity.contact_field_value();
                                contact_field_value.contact  = contacts;
                                contact_field_value.value    = role_name;
                                contact_field_value.id_field = app_field.id_field;
                                contacts.contact_field_value.Add(contact_field_value);
                            }
                        }

                        int relationid = Convert.ToInt32((reader[18] is DBNull) ? null : reader[18].ToString());
                        int code       = Convert.ToInt32((reader[32] is DBNull) ? null : reader[32].ToString());
                        if (relationid != code)
                        {
                            DataTable dt_newcustomer = exeDT("select NOMBRE from CLIENTES where CODCLIENTE=" + relationid);
                            string    name           = (dt_newcustomer.Rows[0][0]).ToString();
                            if (db.contacts.Where(x => x.name == name).FirstOrDefault() != null)
                            {
                                contacts.parent = db.contacts.Where(x => x.name == name).FirstOrDefault();
                            }
                        }

                        var SEXO = Convert.ToInt32((reader[33] is DBNull) ? null : reader[33].ToString());
                        if (SEXO != null)
                        {
                            if (SEXO == 0)
                            {
                                contacts.gender = contact.Genders.Male;
                            }
                            else
                            {
                                contacts.gender = contact.Genders.Female;
                            }
                        }

                        DateTime FECHANACIMINETO = Convert.ToDateTime((reader[34] is DBNull) ? null : reader[34].ToString());

                        if (FECHANACIMINETO != null)
                        {
                            if (FECHANACIMINETO.Year < 2014)
                            {
                                contacts.date_birth = FECHANACIMINETO;
                            }
                        }
                        contact_subscription contact_subscription = new contact_subscription();
                        if (!(reader[33] is DBNull))
                        {
                            if (Convert.ToInt32((reader[33])) > 0)
                            {
                                contact_subscription.unit_price = Convert.ToInt32((reader[33]));
                            }
                        }

                        if (!(reader[25] is DBNull))
                        {
                            string name = reader[36].ToString();
                            if (db.items.Where(x => x.name == name).FirstOrDefault() != null)
                            {
                                contact_subscription.id_item = db.items.Where(x => x.name == name).FirstOrDefault().id_item;
                                if (db.items.Where(x => x.name == name).FirstOrDefault() != null)
                                {
                                    contact_subscription.id_vat_group = db.items.Where(x => x.name == name).FirstOrDefault().id_vat_group;
                                }
                                else
                                {
                                    if (db.app_vat_group.Where(x => x.is_default).FirstOrDefault() != null)
                                    {
                                        contact_subscription.id_vat_group = db.app_vat_group.Where(x => x.is_default).FirstOrDefault().id_vat_group;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (contacts.parent != null)
                            {
                                contact_subscription.id_item = contacts.parent.contact_subscription.FirstOrDefault().id_item;

                                contact_subscription.id_vat_group = contacts.parent.contact_subscription.FirstOrDefault().id_vat_group;
                            }
                        }
                        if (db.app_contract.Where(x => x.is_active).FirstOrDefault() != null)
                        {
                            contact_subscription.id_contract = db.app_contract.Where(x => x.is_active).FirstOrDefault().id_contract;
                        }
                        contacts.contact_subscription.Add(contact_subscription);

                        if (!(reader[37] is DBNull))
                        {
                            string name = reader[37].ToString();
                            if (db.contact_tag.Local.Where(x => x.name == name).FirstOrDefault() == null)
                            {
                                if (reader[37].ToString() != "")
                                {
                                    contact_tag contact_tag = new contact_tag();
                                    contact_tag.name = reader[37].ToString();
                                    db.contact_tag.Add(contact_tag);
                                    contact_tag_detail contact_tag_detail = new contact_tag_detail();
                                    contact_tag_detail.contact     = contacts;
                                    contact_tag_detail.contact_tag = contact_tag;
                                    db.contact_tag_detail.Add(contact_tag_detail);
                                }
                            }
                            else
                            {
                                contact_tag_detail contact_tag_detail = new contact_tag_detail();
                                contact_tag_detail.contact     = contacts;
                                contact_tag_detail.contact_tag = db.contact_tag.Local.Where(x => x.name == name).FirstOrDefault();
                                db.contact_tag_detail.Add(contact_tag_detail);
                            }
                        }
                    }

                    if (!(reader["DESZONA"] is DBNull))
                    {
                        string        name           = (string)reader["DESZONA"];
                        app_geography _app_geography = db.app_geography.Where(x => x.name == name).FirstOrDefault();
                        if (_app_geography != null)
                        {
                            contacts.app_geography = _app_geography;
                            contacts.id_geography  = _app_geography.id_geography;
                        }
                    }
                    else if (!(reader["DESCIUDAD"] is DBNull))
                    {
                        string        name           = (string)reader["DESCIUDAD"];
                        app_geography _app_geography = db.app_geography.Where(x => x.name == name).FirstOrDefault();
                        if (_app_geography != null)
                        {
                            contacts.app_geography = _app_geography;
                            contacts.id_geography  = _app_geography.id_geography;
                        }
                    }
                    else if (!(reader["DESPAIS"] is DBNull))
                    {
                        string        name           = (string)reader["DESPAIS"];
                        app_geography _app_geography = db.app_geography.Where(x => x.name == name).FirstOrDefault();
                        if (_app_geography != null)
                        {
                            contacts.app_geography = _app_geography;
                            contacts.id_geography  = _app_geography.id_geography;
                        }
                    }

                    //db Related Insertion.
                    if (!(reader[1] is DBNull))
                    {
                        string          _price     = reader[1].ToString();
                        item_price_list price_list = db.item_price_list.Where(x => x.name == _price && x.id_company == id_company).FirstOrDefault();
                        contacts.id_price_list = price_list.id_price_list;
                    }

                    if (!(reader[0] is DBNull))
                    {
                        string    _sales_rep = reader[0].ToString();
                        sales_rep sales_rep  = db.sales_rep.Where(x => x.name == _sales_rep && x.id_company == id_company).FirstOrDefault();
                        contacts.id_sales_rep = (short)sales_rep.id_sales_rep;
                    }

                    if (contacts.Error == null)
                    {
                        db.contacts.Add(contacts);
                        try
                        {
                            db.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        value += 1;
                        Dispatcher.BeginInvoke((Action)(() => progCustomer.Value = value));
                        Dispatcher.BeginInvoke((Action)(() => customerValue.Text = value.ToString()));
                    }
                    else
                    {
                        //Add code to include error contacts into
                        Contact_ErrorList.Add(contacts);
                    }
                }
            }


            //cmd.Dispose();
            conn.Close();

            _customer_Current = _customer_Max;
        }