Beispiel #1
0
        public static BusinessOrder CreateBusinessOrder()
        {
            var billingAddress = new BusinessBillingAddress(
                new BusinessReceiver("JEHO Consulting AB", "Josef Ottosson"),
                "Josef Ottosson",
                "Vägen 123",
                "12345",
                "Stockholm",
                "Sverige");
            var shippingAddress = new BusinessShippingAddress(
                new BusinessReceiver("JEHO Consulting AB", "Josef Ottosson"),
                "Company B",
                "Sveavägen 123",
                "12345",
                "Stockholm",
                "Sverige");

            var businessOrder = new BusinessOrder(
                2000,
                billingAddress,
                shippingAddress,
                new BusinessCustomer("1", "JEHO Consulting AB", "559164-7150"),
                new OrderDetails(new List <OrderRow>
            {
                new OrderRow("Apple iPad Pro 11", "APLIPPRO11", 1, 10000m, 25)
            }));

            return(businessOrder);
        }
        public List <ModelViewPrices> GetListPrices(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }

            List <int> lst = new List <int>();

            if (objCred.ProductID == 0)
            {
                lst = new BusinessOrder().GetListByProductID(dataUsuario.UserID, objCred.Date.Value);



                return(new RepositoryPrice().GetListPrice(lst, null));
            }
            else
            {
                lst.Add(objCred.ProductID);
                return(new RepositoryPrice().GetListPrice(lst, null));
            }
        }
Beispiel #3
0
        public void TestBusinessOrderSettersAndGetters(int id)
        {
            BusinessOrder order = new BusinessOrder();

            order.Id = id;

            Assert.Equal(id, order.Id);
        }
Beispiel #4
0
 /// <summary>组装货物vo</summary>
 private BusinessGoodsVo BuildGoodsVo(BusinessOrder order, double id, int type)
 {
     return(new BusinessGoodsVo()
     {
         id = id,
         baseId = order.goods_id,
         priceBuy = order.buy_price_ok,
         priceSell = order.sell_price_ok,
         count = type == 1 ? order.sell_count_max : order.buy_count_max
     });
 }
        /// <summary>
        /// Creates an order
        /// </summary>
        /// <param name="bOrder">
        /// The BusinessOrder which contains all the necessary information to create an order such as
        /// line items and updated inventory
        /// </param>
        public static void CreateOrder(BusinessOrder bOrder)
        {
            Log.Information($"Called the Data Access method to create an order with business order {bOrder}");
            using var context = new TThreeTeasContext(SQLOptions.options);

            Orders additionalOrder = new Orders()
            {
                LocationId = bOrder.StoreLocation.Id,
                CustomerId = bOrder.Customer.Id,
                OrderTime  = bOrder.OrderTime
            };

            context.Orders.Add(additionalOrder);
            context.SaveChanges();
            Log.Information($"Saved the additional order to the database");

            List <LineItem> additionalLineItems = new List <LineItem>();

            foreach (KeyValuePair <BusinessProduct, int> lineItem in bOrder.LineItems)
            {
                LineItem additionalLineItem = new LineItem()
                {
                    OrdersId  = additionalOrder.Id,
                    ProductId = lineItem.Key.Id,
                    Quantity  = lineItem.Value
                };
                additionalLineItems.Add(additionalLineItem);
            }
            foreach (LineItem additionalLineItem in additionalLineItems)
            {
                context.LineItem.Add(additionalLineItem);
            }
            context.SaveChanges();
            Log.Information($"Saved the additional line items to the database");

            List <Inventory> updatedInventories = new List <Inventory>();

            foreach (KeyValuePair <BusinessProduct, int> inventory in bOrder.StoreLocation.inventory)
            {
                Inventory updatedInventory = new Inventory()
                {
                    LocationId = bOrder.StoreLocation.Id,
                    ProductId  = inventory.Key.Id,
                    Stock      = inventory.Value
                };
                updatedInventories.Add(updatedInventory);
            }
            foreach (Inventory updatedInventory in updatedInventories)
            {
                context.Inventory.Update(updatedInventory);
            }
            context.SaveChanges();
            Log.Information($"Saved the updated inventories to the database");
        }
 public virtual void SaveBusinessOrder(int businessId, int orderId)
 {
     using (var context = new JPNFinalProjectContext()) {
         BusinessOrder entity = new BusinessOrder()
         {
             BusinessId = businessId, OrderId = orderId
         };
         context.BusinessOrder.Add(entity);
         context.SaveChanges();
     }
 }
Beispiel #7
0
 /// <summary>组装订单数据</summary>
 private void GetOrder(int goodsid, Int64 goodsmainid, BusinessOrder order, int sellprice, Int64 carmainid, int buyprice)
 {
     order.car_mainid    = carmainid;
     order.goods_main_id = goodsmainid;
     order.goods_id      = goodsid;
     order.sell_price_ok = sellprice;
     order.buy_price_ok  = buyprice;
     order.count         = 0;
     order.isbargain     = false;
     order.buy_bargain   = 0;
     order.sell_bargain  = 0;
 }
Beispiel #8
0
 /// <summary>组装跑商货物实体</summary>
 private tg_goods_business BuildEntity(BusinessOrder order, int numb, Int64 userid)
 {
     return(new tg_goods_business()
     {
         goods_id = order.goods_id,
         cid = order.car_mainid,
         goods_number = numb,
         price = order.buy_price_ok,
         ting_id = order.ting_base_id,
         user_id = userid
     });
 }
Beispiel #9
0
        public async Task <IHttpActionResult> DeleteBusinessOrder(int id)
        {
            BusinessOrder businessOrder = await db.BusinessOrders.FindAsync(id);

            if (businessOrder == null)
            {
                return(NotFound());
            }

            db.BusinessOrders.Remove(businessOrder);
            await db.SaveChangesAsync();

            return(Ok(businessOrder));
        }
        /// <summary>
        /// Submits an order to the system
        /// </summary>
        /// <param name="businessOrder">The order that was submitted to the context</param>
        /// <returns></returns>
        public async Task <BusinessOrder> submitOrderAsync(BusinessOrder businessOrder)
        {
            Order order = await _context.Orders.Where(o => o.OrderId == businessOrder.OrderId).FirstOrDefaultAsync();

            if (order != null && order.OrderDate == null)
            {
                order.OrderDate = DateTime.Now.ToString();
                _context.Update(order);
                await _context.SaveChangesAsync();

                businessOrder.OrderDate = order.OrderDate;
                return(businessOrder);
            }
            return(null);
        }
        public string Insert(ModelViewLog model)
        {
            if (model.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (model.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            var           User  = new BusinessUsers().GetUserByToken(model.TokenUser);
            List <string> token = new List <string>();

            foreach (var item in model.Detail)
            {
                var             Ods  = new BusinessOrder().GetByOrderID(item.OrderID);
                EntityLogMobile data = new EntityLogMobile()
                {
                    PK_LogMobileID = 0,
                    FK_OrderID     = Ods == null ? 0 : Ods.PK_OrderID,
                    FK_UserID      = User.UserID,
                    UserName       = User.UserName,
                    Name           = User.Name,
                    OrderID        = item.OrderID,
                    Module         = item.Module,
                    Message        = item.Message,
                    InnerException = item.InnerException,
                    StackTrace     = item.StackTrace,
                    SignType       = item.SignType,
                    Battery        = item.Battery,
                    SignPercentage = item.SignPercentage,
                    ConnectionType = item.ConnectionType,
                    version        = item.version,
                    MobileModel    = item.MobileModel,
                    MobileStorage  = item.MobileStorage,
                    Type           = item.Type,
                    Date           = DateTime.Parse(item.Date),
                    Status         = true,
                    CreateDate     = DateTime.UtcNow,
                    ModifyDate     = DateTime.UtcNow
                };
                data = new RepositoryLogMobile().Insert(data);
                token.Add(item.TokenLog);
            }

            string TokenLog = string.Join(",", token);

            return(TokenLog);
        }
Beispiel #12
0
        public void Insert(int FK_OrderID, int FK_StatusVisitID, int FK_StatusOrderID, double?LatitudeAddress, double?LogitudeAddress)
        {
            int?causeID      = null;
            var NegocioOrder = new BusinessOrder();
            var order        = NegocioOrder.GetByID(FK_OrderID);

            if (order != null)
            {
                causeID = order.PreOrder != true ? null : (int?)47;
            }
            var         objRepository = new RepositoryVisit();
            EntityVisit data          = new EntityVisit()
            {
                PK_VisitID         = 0,
                FK_OrderID         = FK_OrderID,
                FK_StatusVisitID   = FK_StatusVisitID,
                FK_StatusOrderID   = FK_StatusOrderID,
                FK_CauseOrderID    = causeID,
                SequenceVisit      = null,
                StartVisitDate     = null,
                EndVisitDate       = null,
                StartOrderDate     = null,
                EndOrderDate       = null,
                StartServiceDate   = null,
                EndServiceDate     = null,
                LatitudeAddress    = Convert.ToSingle(LatitudeAddress),
                LogitudeAddress    = Convert.ToSingle(LogitudeAddress),
                LatitudeStartVisit = null,
                LogitudeStartVisit = null,
                LatitudeEndVisit   = null,
                LogitudeEndVisit   = null,
                LatitudeStartOrder = null,
                LogitudeStartOrder = null,
                LatitudeEndOrder   = null,
                LogitudeEndOrder   = null,
                DurationVisit      = null,
                DurationOrder      = null,
                DurationExecute    = null,
                DurationTransport  = null,
                NoteVisit          = "",
                NoteOrder          = "",
                Status             = true,
                CreateDate         = DateTime.Now,
                ModifyDate         = DateTime.UtcNow
            };

            data = objRepository.Insert(data);
        }
Beispiel #13
0
 /// <summary>保存购买的货物数据</summary>
 private tg_goods_business BuyGoodsSave(tg_goods_business gb, BusinessOrder order, Int64 userid)
 {
     if (gb == null) //之前没有购买此货物
     {
         gb = BuildEntity(order, order.count, userid);
         gb.Insert();
     }
     else
     {
         var totalmoney = gb.goods_number * gb.price + order.GetTotalBuy(); //买货物总消费
         gb.goods_number += order.count;
         gb.price         = Convert.ToInt32(totalmoney / gb.goods_number);  //买货物的价格为平均价
         gb.Update();
     }
     return(gb);
 }
Beispiel #14
0
        /// <summary>验证町中是否已有改货物。已有的货物价格减半</summary>
        public void CheckGoodsPrice(BusinessOrder order)
        {
            var base_ting = Variable.BASE_TING.FirstOrDefault(q => q.id == order.ting_base_id);

            if (base_ting == null)
            {
                return;
            }
            var listgoods = base_ting.goods.Split(',').ToList();

            if (!listgoods.Contains(order.goods_id.ToString()))
            {
                return;
            }
            //order.sell_price = Convert.ToInt32(order.sell_price * 0.5);
            order.sell_price_ok = Convert.ToInt32(order.sell_price_ok * 0.5);
        }
Beispiel #15
0
        public async Task <IHttpActionResult> PostBusinessOrder(BusinessOrder businessOrder)
        {
            Book book = await db.Books.FindAsync(businessOrder.BookId);

            book.ResidueNumber = book.ResidueNumber - 1;
            book.BorrowNumber  = book.BorrowNumber + 1;
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            //更新书籍信息
            db.Entry(book).State = EntityState.Modified;
            //插入订单数据
            db.BusinessOrders.Add(businessOrder);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = businessOrder.Id }, businessOrder));
        }
        public void RegisterEvidence(ModelViewOrderEvidenceUpload data)
        {
            var dataODS = new BusinessOrder().GetByOrderID(data.OrderID);

            if (!Directory.Exists(Path.Combine(GlobalConfiguration.LocateEvidence, dataODS.FK_ModuleID.ToString())))
            {
                Directory.CreateDirectory(Path.Combine(GlobalConfiguration.LocateEvidence, dataODS.FK_ModuleID.ToString()));
            }

            string filePath = Path.Combine(GlobalConfiguration.LocateEvidence, dataODS.FK_ModuleID.ToString(), data.FileName);

            string relativePath = Path.Combine(GlobalConfiguration.LocateEvidenceRelative, dataODS.FK_ModuleID.ToString(), data.FileName);

            var bytes = Convert.FromBase64String(data.Content);

            using (var imageFile = new FileStream(filePath, FileMode.Create))
            {
                imageFile.Write(bytes, 0, bytes.Length);
                imageFile.Flush();
            }

            int MonitorID   = 0;
            var dataMonitor = new BusinessMonitor().GetByOrderID(dataODS.PK_OrderID); //.GetAll().Where(p => p.OrderID == dataODS.PK_OrderID).Single();

            if (dataMonitor != null)
            {
                MonitorID = dataMonitor.VisitID;
            }

            if (!Exists(data.OrderID, data.TypeEvidence, relativePath))
            {
                Insert(new EntityOrderEvidence()
                {
                    EvidenceID      = 0,
                    OrderID         = dataODS.PK_OrderID,
                    MonitorOrdersID = MonitorID,
                    TypeEvidence    = data.TypeEvidence,
                    URLEvidence     = relativePath,
                    Status          = true,
                    CreateDate      = DateTime.UtcNow,
                    ModifyDate      = DateTime.UtcNow
                });
            }
        }
Beispiel #17
0
        public async Task <IHttpActionResult> PutBusinessOrder(int id, BusinessOrder businessOrder)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != businessOrder.Id)
            {
                return(BadRequest());
            }

            if (businessOrder.OrderState == "finished")
            {
                Book book = await db.Books.FindAsync(businessOrder.BookId);

                book.ResidueNumber = book.ResidueNumber + 1;
                book.BorrowNumber  = book.BorrowNumber - 1;
                //更新书籍信息
                db.Entry(book).State = EntityState.Modified;
            }

            //更新订单信息
            db.Entry(businessOrder).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BusinessOrderExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public BusinessOrderResponseDto Create(BusinessOrder order)
        {
            var billingAddress = new BusinessAddressBillingResponseDto(
                order.Billing.Receiver.CompanyName,
                order.Billing.Receiver.Reference,
                order.Billing.CareOf,
                order.Billing.City,
                order.Billing.Street,
                order.Billing.Zip,
                order.Billing.Country);

            var shippingAddress = order.Shipping != null
                ? new BusinessAddressShippingResponseDto(
                order.Shipping.Receiver.CompanyName,
                order.Shipping.Receiver.Reference,
                order.Shipping.CareOf,
                order.Shipping.City,
                order.Shipping.Street,
                order.Shipping.Zip,
                order.Shipping.Country)
                : null;

            var orderDetailsResponseDto = new OrderDetailsResponseDto(
                order.OrderDetails.TotalPrice,
                order.OrderDetails.OrderRows.Select(x => new OrderRowResponseDto(
                                                        x.Name,
                                                        x.ProductId,
                                                        x.Quantity,
                                                        x.Price,
                                                        x.Vat,
                                                        x.VatPercentage
                                                        ))
                );

            return(new BusinessOrderResponseDto(
                       order.Id,
                       new BusinessAddressResponseDto(
                           billingAddress,
                           shippingAddress
                           ),
                       new BusinessCustomerResponseDto(order.Customer.Id, order.Customer.CompanyName, order.Customer.OrganizationalNumber),
                       orderDetailsResponseDto));
        }
        /// <summary>
        /// Handles displaying the details of an order - the location, the customer, and each of its
        /// line items.
        /// </summary>
        private static void HandleRequestDisplayDetailsOfOrder()
        {
            Console.WriteLine("[?] What is the order ID");
            string inputOrderId = Console.ReadLine();

            Log.Information($"User entered '{inputOrderId}' for order id");
            if (!Int32.TryParse(inputOrderId, out int orderId))
            {
                throw new FormatException("[!] Input for order ID is not an integer");
            }

            BusinessOrder order = OrderData.GetOrderWithId(orderId);

            if (order is null)
            {
                throw new BusinessOrderException($"[!] Order {orderId} does not exist in the database");
            }

            Console.WriteLine($"{order}\n");
        }
Beispiel #20
0
        /// <summary>出售货物时检查买卖类型任务</summary>
        /// <param name="user_id">玩家编号</param>
        /// <param name="order">货物实体</param>
        public void CheckWorkTaskSell(Int64 user_id, BusinessOrder order)
        {
            var _task = tg_task.GetWorkUnBusinessTask(user_id);

            if (_task == null)
            {
                return;
            }

            //解析
            var entity = (new Share.TGTask()).Ananalyze(_task.task_step_data);

            if (entity == null)
            {
                return;
            }
            //判断是否是任务出售町
            if (entity.ting != order.current_ting_base_id || entity.goods != order.goods_id)
            {
                return;
            }
            var _c = order.count + entity.count;

            if (entity.total > _c)
            {
                entity.count = _c;
            }
            else
            {
                entity.count     = entity.total;
                _task.task_state = (int)TaskStateType.TYPE_REWARD;
            }

            var step_data = entity.GetBusinessStepData();

            _task.task_step_data = step_data;
            _task.Save();

            //任务推送
            (new Work()).AdvancedWorkPush(user_id, _task);
        }
 public static void Assert(BusinessOrder businessOrder, BusinessOrderResponseDto result)
 {
     result.OrderId.ShouldBe(businessOrder.Id);
     result.Type.ShouldBe(businessOrder.Type);
     result.Address.Billing.Reference.ShouldBe(businessOrder.Billing.Receiver.Reference);
     result.Address.Billing.CompanyName.ShouldBe(businessOrder.Billing.Receiver.CompanyName);
     result.Address.Billing.CareOf.ShouldBe(businessOrder.Billing.CareOf);
     result.Address.Billing.City.ShouldBe(businessOrder.Billing.City);
     result.Address.Billing.Country.ShouldBe(businessOrder.Billing.Country);
     result.Address.Billing.Street.ShouldBe(businessOrder.Billing.Street);
     result.Address.Billing.Zip.ShouldBe(businessOrder.Billing.Zip);
     result.Address.Shipping.Reference.ShouldBe(businessOrder.Shipping.Receiver.Reference);
     result.Address.Shipping.CompanyName.ShouldBe(businessOrder.Shipping.Receiver.CompanyName);
     result.Address.Shipping.CareOf.ShouldBe(businessOrder.Shipping.CareOf);
     result.Address.Shipping.City.ShouldBe(businessOrder.Shipping.City);
     result.Address.Shipping.Country.ShouldBe(businessOrder.Shipping.Country);
     result.Address.Shipping.Street.ShouldBe(businessOrder.Shipping.Street);
     result.Address.Shipping.Zip.ShouldBe(businessOrder.Shipping.Zip);
     result.OrderDetails.TotalPrice.ShouldBe(businessOrder.OrderDetails.TotalPrice);
     result.OrderDetails.OrderRows.Count().ShouldBe(businessOrder.OrderDetails.OrderRows.Count);
     foreach (var row in businessOrder.OrderDetails.OrderRows)
     {
         result.OrderDetails.OrderRows.ShouldContain(
             x => x.Name == row.Name &&
             x.ProductId == row.ProductId &&
             x.Price == row.Price &&
             x.VatPercentage == row.VatPercentage &&
             x.Vat == row.Vat &&
             x.Quantity == row.Quantity);
     }
     result.OrderDetails.OrderRows.First().Name.ShouldBe(businessOrder.OrderDetails.OrderRows.First().Name);
     result.OrderDetails.OrderRows.First().ProductId.ShouldBe(businessOrder.OrderDetails.OrderRows.First().ProductId);
     result.OrderDetails.OrderRows.First().Price.ShouldBe(businessOrder.OrderDetails.OrderRows.First().Price);
     result.OrderDetails.OrderRows.First().Vat.ShouldBe(businessOrder.OrderDetails.OrderRows.First().Vat);
     result.OrderDetails.OrderRows.First().VatPercentage.ShouldBe(businessOrder.OrderDetails.OrderRows.First().VatPercentage);
     result.Customer.Id.ShouldBe(businessOrder.Customer.Id);
     result.Customer.Name.ShouldBe(businessOrder.Customer.CompanyName);
     result.Customer.OrganizationalNumber.ShouldBe(businessOrder.Customer.OrganizationalNumber);
 }
        /// <summary>
        /// Retrieves the BusinessOrder with the given order id
        /// </summary>
        /// <param name="orderId">The id of the order</param>
        /// <returns>The BusinessOrder object with the given order id</returns>
        public static BusinessOrder GetOrderWithId(int orderId)
        {
            Log.Information($"Called the Data Access method to get the order with order id {orderId}");
            using var context = new TThreeTeasContext(SQLOptions.options);

            Orders order = context.Orders.FirstOrDefault(o => o.Id == orderId);

            if (order is null)
            {
                return(null);
            }

            BusinessLocation bLocation = LocationData.GetLocationWithId(order.LocationId);
            BusinessCustomer bCustomer = CustomerData.GetCustomerWithId(order.CustomerId);
            BusinessOrder    bOrder    = new BusinessOrder
            {
                Id            = order.Id,
                StoreLocation = bLocation,
                Customer      = bCustomer,
                OrderTime     = order.OrderTime
            };

            Dictionary <BusinessProduct, int> lineItems = new Dictionary <BusinessProduct, int>();

            foreach (LineItem item in context.LineItem.Where(l => l.OrdersId == order.Id).ToList())
            {
                Product         product  = context.Product.Where(p => p.Id == item.ProductId).FirstOrDefault();
                BusinessProduct bProduct = new BusinessProduct()
                {
                    Id    = product.Id,
                    Name  = product.Name,
                    Price = product.Price
                };
                lineItems.Add(bProduct, item.Quantity);
            }
            bOrder.AddLineItems(lineItems);

            return(bOrder);
        }
        /// <summary>
        /// Updates the context inventory with information from an incoming order item
        /// </summary>
        /// <param name="businessOrder">The order that contains the order item</param>
        /// <param name="businessOrderItem">The order item to be added to the order</param>
        /// <returns>A representation of the updated order</returns>
        public async Task <BusinessOrder> updateOrderAsync(BusinessOrder businessOrder, BusinessOrderItem businessOrderItem)
        {
            Order order = await _context.Orders.Include(o => o.OrderItems)
                          .Where(o => o.OrderId == businessOrder.OrderId)
                          .FirstOrDefaultAsync();

            Inventory inventory = await _context.Inventories.Include(i => i.Product)
                                  .Where(i => i.Product.ProductId == businessOrderItem.Product.ProductId)
                                  .FirstOrDefaultAsync();

            OrderItem orderItem;

            if (businessOrderItem.OrderItemId == -1)
            {
                orderItem = new OrderItem {
                    Quantity = businessOrderItem.Quantity,
                    Order    = order,
                    Product  = await _context.Products.Where(p => p.ProductId == businessOrderItem.Product.ProductId).FirstOrDefaultAsync(),
                };
                order.OrderItems.Add(orderItem);
                businessOrder.OrderItems.Add(businessOrderItem);
                _context.Add(orderItem);
            }
            else
            {
                orderItem = await _context.OrderItems.Where(oi => oi.OrderItemId == businessOrderItem.OrderItemId).FirstOrDefaultAsync();

                orderItem.Quantity += businessOrderItem.Quantity;
                _context.Update(orderItem);
            }
            inventory.Quantity -= businessOrderItem.Quantity;
            order.Total         = businessOrder.Total;
            _context.Update(order);
            _context.Update(inventory);
            await _context.SaveChangesAsync();

            return(businessOrder);
        }
        public string SetRefQuotation(ModelViewUserG objCred, ModelViewBilling obj)
        {
            var objRepository            = new RepositoryOrder();
            var NegocioOrden             = new BusinessOrder();
            var objAlerta                = new BusinessNotification();
            var NegocioUsuario           = new BusinessUsers();
            var NegocioCliente           = new BusinessClient();
            var NegocioBase              = new BusinessInstalledBase();
            var NegocioProducto          = new BusinessProduct();
            var NegocioFallas            = new BusinessCodeFailure();
            var NegocioBOM               = new BusinessBuildOfMaterial();
            var NegocioCotizacion        = new BusinessQuotation();
            var NegocioCotizacionDetalle = new BusinessRefsellDetail();
            var NegocioCFP               = new BusinessCodeFailureByProduct();
            var NegocioCF                = new BusinessCodeFailure();
            var NegocioLugarCompra       = new BusinessShopPlace();
            var NegocioEmpleado          = new BusinessEmployee();
            var NegocioMonitor           = new BusinessVisit();
            var NegocioHistorico         = new BusinessHistory();
            var NegocioGarantia          = new BusinessGuaranty();
            var NegocioPayment           = new BusinessPayment();
            var NegocioInvoice           = new BusinessInvoice();
            var NegocioRefsell           = new BusinessRefsell();
            var dataUsuario              = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }

            var empleado = NegocioEmpleado.GetByUserID(dataUsuario.UserID);
            var orden    = NegocioOrden.GetByOrderID(obj.ODS);


            var cliente = NegocioCliente.GetByID(orden.FK_ClientID);

            var lugarcompra = NegocioLugarCompra.GetByShopPlaceID(obj.FK_ShopPlaceID.Value);
            var pro         = NegocioProducto.GetByID(obj.FK_ProductID.Value);

            SpreadsheetInfo.SetLicense("EQU2-3K5L-UZDC-SDYN");
            string         Origin = GlobalConfiguration.MabeAttachmentsLocal + "FormatoVentaRefacciones.xlsx";
            List <string>  result = obj.EMails.Split(new char[] { ';' }).ToList();
            ExcelFile      ef     = ExcelFile.Load(Origin);
            ExcelWorksheet ws     = ef.Worksheets[0];
            string         Folio  = "";

            ws.Cells["L7"].Value  = obj.ODS;
            ws.Cells["L9"].Value  = cliente.ClientID;
            ws.Cells["L11"].Value = cliente.FirstName.ToUpper() + " " + cliente.LastName.ToUpper();
            ws.Cells["L13"].Value = pro.Model + " / " + pro.ProductName.ToUpper();
            ws.Cells["U13"].Value = DateTime.Today.ToString("dd-MM-yyyy");

            ws.Cells["L80"].Value = obj.ODS;
            int cantidad  = 30;
            int cantidad1 = 31;

            foreach (var jko in obj.BillingDetails)
            {
                if (jko.SparePartsDescription.EndsWith("-R"))
                {
                    Folio = jko.SparePartsDescription;
                    ws.Cells["L6"].Value  = Folio;
                    ws.Cells["L79"].Value = Folio;
                }
                else
                {
                    if (cantidad == 60)
                    {
                        cantidad  = 85;
                        cantidad1 = 86;
                    }
                    var bom = NegocioBOM.GetByID(jko.ProductID);
                    if (bom != null)
                    {
                        ws.Cells["L" + cantidad1.ToString()].Value = bom.SparePartsID;
                        ws.Cells["L" + cantidad.ToString()].Value  = bom.SparePartDescription;
                    }
                    else
                    {
                        ws.Cells["L" + cantidad1.ToString()].Value = jko.RefManID;
                        ws.Cells["L" + cantidad.ToString()].Value  = jko.SparePartsDescription;
                    }
                    ws.Cells["J" + cantidad.ToString()].Value = jko.Quantity;
                    ws.Cells["T" + cantidad.ToString()].Value = Convert.ToDouble(jko.Price);
                    ws.Cells["V" + cantidad.ToString()].Value = Convert.ToDouble(jko.Totals);
                    cantidad  = cantidad + 3;
                    cantidad1 = cantidad1 + 3;
                }
            }

            double subtotal    = Convert.ToDouble(obj.SubTotal.Substring(1));
            double iva         = Convert.ToDouble(obj.IVA.Substring(1));
            double total       = Convert.ToDouble(obj.Total.Substring(1));
            double subtotalref = subtotal;
            string totalletras = NegocioOrden.enletras(total.ToString());

            ws.Cells["M16"].Value = subtotalref;
            ws.Cells["M17"].Value = subtotal;
            ws.Cells["M18"].Value = iva;
            ws.Cells["U17"].Value = total;
            ws.Cells["M19"].Value = totalletras;
            string file    = "Cotización_" + Folio + ".pdf";
            string quotion = "CotizacionesRefaccion_" + DateTime.Today.ToString("yyyyMMdd");
            string Destiny = GlobalConfiguration.MabeAttachmentsLocal + quotion + "/" + file;

            if (obj.BillingDetails.Count < 11)
            {
                ws.NamedRanges.SetPrintArea(ws.Cells.GetSubrange("J1", "W74"));
            }
            string Cotizaciones = new DirectoryInfo(GlobalConfiguration.MabeAttachmentsLocal).ToString() + quotion;

            if (!(Directory.Exists(Cotizaciones)))
            {
                Directory.CreateDirectory(Cotizaciones);
            }
            ef.Save(Destiny);
            string URL        = GlobalConfiguration.urlRequest + "Content/Attachments/" + quotion + "/" + file;
            var    cotizacion = NegocioCotizacion.GetByOrderFolio(orden.PK_OrderID, Folio);
            var    Payment    = NegocioPayment.GetPolicyPayment(orden.PK_OrderID, Folio);
            var    Invoice    = NegocioInvoice.GetPolicyInvoice(orden.PK_OrderID, Folio);


            var LsVenta = NegocioRefsell.GetByFolio(orden.PK_OrderID, Folio);

            if (obj.EMails != "")
            {
                if (cotizacion == null)
                {
                    cotizacion = NegocioCotizacion.Insert(orden.PK_OrderID, subtotal.ToString(), iva.ToString(), total.ToString(), Folio, URL, obj.EstimatedTipe, empleado[0].PK_EmployeeID);
                }
                else
                {
                    cotizacion.Folio         = Folio;
                    cotizacion.IVA           = iva.ToString();
                    cotizacion.SubTotal      = subtotal.ToString();
                    cotizacion.Total         = total.ToString();
                    cotizacion.URL           = URL;
                    cotizacion.ModifyDate    = DateTime.UtcNow;
                    cotizacion.TypeQuotation = obj.EstimatedTipe;
                    cotizacion.FK_EmployeeID = empleado[0].PK_EmployeeID;
                    NegocioCotizacion.Update(cotizacion);
                }

                string sb     = File.ReadAllText(GlobalConfiguration.LocateBodyMail + "NotificationCotizacion.txt");
                string lugCom = obj.ShopDate != null ? obj.ShopDate : "";
                sb = sb.Replace("#%Nombre%#", cliente.FirstName + " " + cliente.LastName);
                sb = sb.Replace("#%OrderID%#", obj.ODS);
                sb = sb.Replace("#%Folio%#", Folio);
                sb = sb.Replace("#%Modelo%#", pro.Model);
                sb = sb.Replace("#%Descripcion%#", pro.ProductName.ToUpper());
                sb = sb.Replace("#%Serie%#", obj.SerialNumber);
                sb = sb.Replace("#%Fecha%#", lugCom);
                sb = sb.Replace("#%Lugar%#", lugarcompra.ShopPlace1);
                //objAlerta.SendMails(result, "Cotización ServiPlus", sb.ToString(), Destiny);
                objAlerta.SendMailExchange(GlobalConfiguration.exchangeUserCotiza, GlobalConfiguration.exchangePwdCotiza, result, "Cotización ServiPlus", sb.ToString(), Destiny);
            }
            else
            {
                if (LsVenta.PK_RefSellID == 0)
                {
                    if (cotizacion == null)
                    {
                        cotizacion = NegocioCotizacion.Insert(orden.PK_OrderID, subtotal.ToString(), iva.ToString(), total.ToString(), Folio, URL, obj.EstimatedTipe, empleado[0].PK_EmployeeID);
                    }
                    else
                    {
                        cotizacion.Folio         = Folio;
                        cotizacion.IVA           = iva.ToString();
                        cotizacion.SubTotal      = subtotal.ToString();
                        cotizacion.Total         = total.ToString();
                        cotizacion.URL           = URL;
                        cotizacion.ModifyDate    = DateTime.UtcNow;
                        cotizacion.TypeQuotation = obj.EstimatedTipe;
                        cotizacion.FK_EmployeeID = empleado[0].PK_EmployeeID;
                        NegocioCotizacion.Update(cotizacion);
                    }
                    var NewRefSell = new EntityRefSell();
                    var NuevaVenta = new EntityRefSell();

                    NewRefSell.FK_OrderID     = orden.PK_OrderID;
                    NewRefSell.FK_ClientID    = cliente.PK_ClientID;
                    NewRefSell.FK_EmployeeID  = empleado[0].PK_EmployeeID;
                    NewRefSell.FK_PaymentID   = Payment.PK_PaymentID;
                    NewRefSell.FK_Invoice_ID  = Invoice.InvoicingID;
                    NewRefSell.FK_ProductID   = obj.FK_ProductID.Value;
                    NewRefSell.FK_ShopPlace   = obj.FK_ShopPlaceID.Value;
                    NewRefSell.FK_QuotationID = cotizacion.PK_QuotationID;
                    NewRefSell.IDRefSell      = Folio;
                    NuevaVenta = NegocioRefsell.Insert(NewRefSell);
                }
                else
                {
                    LsVenta.FK_OrderID     = orden.PK_OrderID;
                    LsVenta.FK_ClientID    = cliente.PK_ClientID;
                    LsVenta.FK_EmployeeID  = empleado[0].PK_EmployeeID;
                    LsVenta.FK_PaymentID   = Payment.PK_PaymentID;
                    LsVenta.FK_Invoice_ID  = Invoice.InvoicingID;
                    LsVenta.FK_QuotationID = LsVenta.FK_QuotationID;
                    LsVenta.FK_ProductID   = obj.FK_ProductID.Value;
                    LsVenta.FK_ShopPlace   = obj.FK_ShopPlaceID.Value;

                    NegocioRefsell.Update(LsVenta);

                    if (cotizacion == null)
                    {
                        cotizacion = NegocioCotizacion.Insert(orden.PK_OrderID, subtotal.ToString(), iva.ToString(), total.ToString(), Folio, URL, obj.EstimatedTipe, empleado[0].PK_EmployeeID);
                    }
                    else
                    {
                        cotizacion.Folio         = Folio;
                        cotizacion.IVA           = iva.ToString();
                        cotizacion.SubTotal      = subtotal.ToString();
                        cotizacion.Total         = total.ToString();
                        cotizacion.URL           = URL;
                        cotizacion.ModifyDate    = DateTime.UtcNow;
                        cotizacion.TypeQuotation = obj.EstimatedTipe;
                        cotizacion.FK_EmployeeID = empleado[0].PK_EmployeeID;
                        NegocioCotizacion.Update(cotizacion);
                    }
                }
                string[] lstADR = { "T002", "T012", "T024" };

                foreach (var jko in obj.BillingDetails)
                {
                    string ADRAnt   = "";
                    int    ADRCount = 0;
                    bool   AddFlete = false;

                    if (jko.SparePartsDescription != Folio)
                    {
                        switch (jko.SparePartsDescription)
                        {
                        case "Fletes":
                        {
                            var DetailCotation2 = NegocioCotizacionDetalle.GetList(cotizacion.PK_QuotationID);

                            foreach (var items in DetailCotation2)
                            {
                                if (lstADR.Contains(items.Origen))
                                {
                                    if (ADRAnt != items.Origen)
                                    {
                                        ADRAnt = items.Origen;
                                        ADRCount++;
                                        if (ADRCount < 3)
                                        {
                                            AddFlete = true;
                                        }
                                        else
                                        {
                                            AddFlete = false;
                                        }
                                    }
                                    if (AddFlete)
                                    {
                                        items.Flete      = true;
                                        items.CostoFlete = jko.Price;
                                        NegocioCotizacionDetalle.Update(items);
                                        AddFlete = false;
                                    }
                                }
                            }
                        }

                        break;

                        default:
                            var newDetailquotion = NegocioCotizacionDetalle.GetDetail(cotizacion.PK_QuotationID, jko.ProductID);

                            if (newDetailquotion == null)
                            {
                                NegocioCotizacionDetalle.Insert(cotizacion.PK_QuotationID, jko.ProductID, jko.Quantity.ToString(), jko.RefManID, jko.Origins, jko.Price);
                            }
                            break;
                        }
                    }
                }


                var Refacciones = new BusinessMabe().Orden_Venta(obj.ODS, obj.ServiceTypes, Folio);
            }
            return(obj.ODS);
        }
Beispiel #25
0
        public List <ModelViewSerialNumber> GetListModel(ModelViewUserG objCred)
        {
            var NegocioBase         = new BusinessInstalledBase();
            var NegocioUsuario      = new BusinessUsers();
            var NegocioOrdenes      = new BusinessOrder();
            var NegocioValidacionSN = new BusinessValidationsSerialNumber();
            var NegocioEmpleado     = new BusinessEmployee();
            var user         = NegocioUsuario.GetUserByToken(objCred.TokenUser);
            var empleado     = NegocioEmpleado.GetByUserID(user.UserID);
            var ordenes      = NegocioOrdenes.GetAll().Where(p => empleado.Select(q => q.PK_EmployeeID).ToList <int>().Contains(p.FK_EmployeeID.Value) && p.OrderExecuteDate >= objCred.Date);
            var prod         = NegocioBase.GetAll();
            var SerialNumber = GetAll();
            var Validation   = NegocioValidacionSN.GetAll();

            if (objCred.ProductID == 0)
            {
                var modelos = (from c in ordenes
                               join p in prod on c.FK_InstalledBaseID equals p.PK_InstalledBaseID
                               select p.FK_ProductID).Distinct().ToList();
                modelos = modelos.Where(x => x != null).ToList();
                var lt = (from c in SerialNumber
                          join p in Validation on c.PK_ModelSerialNumberID equals p.FK_ModelSerialNumberID
                          select new ModelViewSerialNumber()
                {
                    ModelSerialNumberID = c.PK_ModelSerialNumberID,
                    ProductID = c.FK_ProducID,
                    Model = c.Model,
                    ValidationFormatID = c.ValidationFormatID,
                    ValidDate = c.ValidDate,
                    InitialDate = c.InitialDate != null ? c.InitialDate.Value.ToString("yyyy-MM-dd") : "",
                    EndDate = c.EndDate != null ? c.EndDate.Value.ToString("yyyy-MM-dd") : "",
                    ValidationsSerialNumberID = p.PK_ValidationsSerialNumberID,
                    ValidationName = p.ValidationName,
                    InitialPosition = p.InitialPosition,
                    FinalPosition = p.FinalPosition,
                    Allowed = p.Allowed,
                    RankID = p.RankID
                }).ToList();


                return((from c in modelos
                        join p in lt on c equals p.ProductID
                        select p).ToList());
            }
            else
            {
                return((from c in SerialNumber.Where(p => p.FK_ProducID == objCred.ProductID)
                        join p in Validation on c.PK_ModelSerialNumberID equals p.FK_ModelSerialNumberID
                        select new ModelViewSerialNumber()
                {
                    ModelSerialNumberID = c.PK_ModelSerialNumberID,
                    ProductID = c.FK_ProducID,
                    Model = c.Model,
                    ValidationFormatID = c.ValidationFormatID,
                    ValidDate = c.ValidDate,
                    InitialDate = c.InitialDate != null ? c.InitialDate.Value.ToString("yyyy-MM-dd") : "",
                    EndDate = c.EndDate != null ? c.EndDate.Value.ToString("yyyy-MM-dd") : "",
                    ValidationsSerialNumberID = p.PK_ValidationsSerialNumberID,
                    ValidationName = p.ValidationName,
                    InitialPosition = p.InitialPosition,
                    FinalPosition = p.FinalPosition,
                    Allowed = p.Allowed,
                    RankID = p.RankID
                }).ToList());
            }



            //return lt;
        }
Beispiel #26
0
        public static ModelViewResultREST SetPayment(ModelViewPayment model)
        {
            try
            {
                var dataUsuario = new BusinessUsers().GetUserByToken(model.TokenUser);
                if (model.TokenApp != GlobalConfiguration.TokenWEB)
                {
                    if (model.TokenApp != GlobalConfiguration.TokenMobile)
                    {
                        throw new Exception("TokenInvalid");
                    }
                }
                if (dataUsuario == null)
                {
                    throw new Exception("UserPasswordInvalid");
                }
                var orden   = new BusinessOrder().GetByOrderID(model.OrderID);
                var payment = new BusinessPayment().GetPolicyPayment(orden.PK_OrderID, model.Folio);

                if (payment.OrderID == null)
                {
                    new BusinessPayment().Insert(new entities.Entity.Operation.EntityPayment()
                    {
                        PK_PaymentID         = 0,
                        FK_OrderID           = new BusinessOrder().GetByOrderID(model.OrderID).PK_OrderID,
                        AuthorizationPayment = model.AuthorizationPayment,
                        DatePayment          = Convert.ToDateTime(model.DatePayment),
                        MountPayment         = model.MountPayment,
                        TypePaymentID        = model.TypePaymentID,
                        Status           = true,
                        CreateDate       = DateTime.UtcNow,
                        ModifyDate       = DateTime.UtcNow,
                        Folio            = model.Folio,
                        Fk_TypeQuotation = model.EstimatedType
                    });
                }
                else
                {
                    new BusinessPayment().Update(new entities.Entity.Operation.EntityPayment()
                    {
                        PK_PaymentID         = payment.PK_PaymentID,
                        FK_OrderID           = new BusinessOrder().GetByOrderID(model.OrderID).PK_OrderID,
                        AuthorizationPayment = model.AuthorizationPayment,
                        DatePayment          = Convert.ToDateTime(model.DatePayment),
                        MountPayment         = model.MountPayment,
                        TypePaymentID        = model.TypePaymentID,
                        Status           = true,
                        CreateDate       = DateTime.UtcNow,
                        ModifyDate       = DateTime.UtcNow,
                        Folio            = model.Folio,
                        Fk_TypeQuotation = model.EstimatedType
                    });
                }
                return(new ModelViewResultREST()
                {
                    Result = "Success"
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #27
0
        public List <ModelViewFolios> GetLastFolio(ModelViewUserG objCred)
        {
            var NegocioPoliza   = new BusinessPolicy();
            var NegocioRef      = new BusinessRefsell();
            var NegocioOrden    = new BusinessOrder();
            var NegocioUsuario  = new BusinessUsers();
            var NegocioEmpleado = new BusinessEmployee();
            var dataUsuario     = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }


            DateTime date = objCred.Date.Value;


            List <ModelViewFolios> x = new List <ModelViewFolios>();

            var Empleado2 = NegocioEmpleado.GetEmployeUser(dataUsuario.UserID);
            var Empleado  = Empleado2[0];

            int Conteo;
            List <EntityQuotation> Cotizaciones;
            List <EntityPolicy>    Polizas;
            List <EntityRefSell>   Refacciones;

            string Tipo;
            int    count = 1;

            while (count < 4)
            {
                switch (count)
                {
                case 1:

                    Tipo         = "Cotizacion";
                    Conteo       = GetByEmpoyeeDate(Empleado.PK_EmployeeID, date).Count;
                    Cotizaciones = GetByEmpoyeeDate(Empleado.PK_EmployeeID, date);

                    var LastFolio = Cotizaciones.Count is 0 ? "": Cotizaciones[0].Folio;

                    x.Add(new ModelViewFolios(Tipo, Conteo, LastFolio));
                    count++;

                    break;

                case 2:
                    Tipo    = "Polizas";
                    Conteo  = NegocioPoliza.GetByEmpoyeeDate(Empleado.PK_EmployeeID, date).Count;
                    Polizas = NegocioPoliza.GetByEmpoyeeDate(Empleado.PK_EmployeeID, date);

                    LastFolio = Polizas.Count is 0 ? "" : Polizas[0].IDPolicy;

                    x.Add(new ModelViewFolios(Tipo, Conteo, LastFolio));
                    count++;
                    break;

                case 3:
                    Tipo        = "Refacciones";
                    Conteo      = NegocioRef.GetByEmpoyeeDate(Empleado.PK_EmployeeID, date).Count;
                    Refacciones = NegocioRef.GetByEmpoyeeDate(Empleado.PK_EmployeeID, date);
                    LastFolio   = Refacciones.Count is 0 ? "" : Refacciones[0].IDRefSell;

                    x.Add(new ModelViewFolios(Tipo, Conteo, LastFolio));
                    count++;
                    break;

                default:

                    count++;
                    break;
                }
            }



            return(x);
        }
        public string CreateReceipt(ModelViewUserG objCred, ModelViewReceiptRef obj)
        {
            var objRepository   = new RepositoryOrder();
            var NegocioOrden    = new BusinessOrder();
            var objAlerta       = new BusinessNotification();
            var NegocioUsuario  = new BusinessUsers();
            var NegocioCliente  = new BusinessClient();
            var NegocioContrato = new BusinessContrat();
            var NegocioEmpleado = new BusinessEmployee();
            var NegocioBOM      = new BusinessBuildOfMaterial();

            var dataUsuario = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }


            var empleado = NegocioEmpleado.GetByUserID(dataUsuario.UserID);
            var orden    = NegocioOrden.GetByOrderID(obj.FK_OrderID);
            var cliente  = NegocioCliente.GetByID(orden.FK_ClientID);


            SpreadsheetInfo.SetLicense("EQU2-3K5L-UZDC-SDYN");
            string         Origin = GlobalConfiguration.MabeAttachmentsLocal + "FormatoReciboRef.xlsx";
            List <string>  result = obj.EMails.Split(new char[] { ';' }).ToList();
            ExcelFile      ef     = ExcelFile.Load(Origin);
            ExcelWorksheet ws     = ef.Worksheets[0];


            ws.Cells["W9"].Value  = obj.Folio;
            ws.Cells["W12"].Value = DateTime.Today.ToString("dd-MM-yyyy");
            ws.Cells["L18"].Value = cliente.FirstName.ToUpper();
            ws.Cells["P18"].Value = cliente.LastName.ToUpper();
            ws.Cells["L21"].Value = cliente.PhoneNumber1;
            ws.Cells["T21"].Value = cliente.PhoneNumber2;
            ws.Cells["M23"].Value = cliente.Email;


            int cantidad = 29;


            foreach (var jko in obj.SpareParts)
            {
                if (cantidad == 60)
                {
                    cantidad = 85;
                }
                ////var bom = NegocioBOM.GetByID(jko.ProductID);
                //if (bom != null)
                //{
                //    ws.Cells["L" + cantidad1.ToString()].Value = bom.SparePartsID;
                //    ws.Cells["L" + cantidad.ToString()].Value = bom.SparePartDescription;
                //}
                else
                {
                    ws.Cells["K" + cantidad.ToString()].Value = jko.RefManID;
                    ws.Cells["M" + cantidad.ToString()].Value = jko.SparePartsDescription;
                }
                ws.Cells["R" + cantidad.ToString()].Value = jko.Quantity;
                ws.Cells["U" + cantidad.ToString()].Value = Convert.ToDouble(jko.Price);
                ws.Cells["W" + cantidad.ToString()].Value = Convert.ToDouble(jko.Totals);
                cantidad = cantidad + 1;
            }

            double subtotal    = Convert.ToDouble(obj.SubTotal);
            double iva         = Convert.ToDouble(obj.IVA);
            double total       = Convert.ToDouble(obj.Total);
            double subtotalref = subtotal;
            string totalletras = NegocioOrden.enletras(total.ToString());

            ws.Cells["W41"].Value = subtotalref;

            ws.Cells["W42"].Value = iva;
            ws.Cells["W43"].Value = total;

            string file    = "ReciboRef" + obj.Folio + ".pdf";
            string quotion = "RecibosRefaccion_" + DateTime.Today.ToString("yyyyMMdd");
            string Destiny = GlobalConfiguration.MabeAttachmentsLocal + quotion + "/" + file;

            if (obj.SpareParts.Count < 11)
            {
                ws.NamedRanges.SetPrintArea(ws.Cells.GetSubrange("J1", "X54"));
            }
            string Cotizaciones = new DirectoryInfo(GlobalConfiguration.MabeAttachmentsLocal).ToString() + quotion;

            if (!(Directory.Exists(Cotizaciones)))
            {
                Directory.CreateDirectory(Cotizaciones);
            }
            ef.Save(Destiny);
            string URL    = GlobalConfiguration.urlRequest + "Content/Attachments/" + quotion + "/" + file;
            var    Recibo = NegocioContrato.GetByOrderFolio(orden.PK_OrderID, obj.Folio);



            if (obj.EMails != "")
            {
                if (Recibo == null)
                {
                    Recibo = NegocioContrato.Insert(orden.PK_OrderID, obj.Folio, URL);
                }
                else
                {
                    Recibo.Fk_OrderID = orden.PK_OrderID;
                    Recibo.Folio      = obj.Folio;
                    Recibo.Ruta       = URL;
                    NegocioContrato.Update(Recibo);
                }

                string sb = File.ReadAllText(GlobalConfiguration.LocateBodyMail + "MaiReciboRef.txt");
                sb = sb.Replace("#%Nombre%#", cliente.FirstName + " " + cliente.LastName);
                sb = sb.Replace("#%Folio%#", obj.Folio);

                objAlerta.SendMailExchange(GlobalConfiguration.exchangeUserCotiza, GlobalConfiguration.exchangePwdCotiza, result, "Recibo Refacciones", sb.ToString(), Destiny);
                return(URL);
            }
            else
            {
                string Tipo     = "Recibo";
                var    EnvioSMS = SendNotification(obj.PhoneNumber, Tipo, URL);

                return(EnvioSMS);
            }
        }
        public List <ModelViewFailures> GetListCodeFailure(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }

            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }
            var NegocioOrdenes     = new BusinessOrder();
            var NegocioEmpleado    = new BusinessEmployee();
            var NegocioCodigoFalla = new BusinessCodeFailure();
            var NegocioBase        = new BusinessInstalledBase();
            var codefailure        = NegocioCodigoFalla.GetAll();
            var empleado           = NegocioEmpleado.GetByUserID(dataUsuario.UserID);

            if (objCred.ProductID == 0)
            {
                //var ordenes = NegocioOrdenes.GetAll().Where(p => empleado.Select(q => q.PK_EmployeeID).ToArray<int>().Contains(p.FK_EmployeeID.Value) && p.OrderExecuteDate >= objCred.Date.Value.Date);
                //var prod = NegocioBase.GetAll();
                //var modelos = (from c in ordenes
                //               join p in prod on c.FK_InstalledBaseID equals p.PK_InstalledBaseID
                //               select p.FK_ProductID).Distinct().ToList();
                //modelos = modelos.Where(x => x != null).ToList();
                var        ordenes       = NegocioOrdenes.GetAll(empleado.Select(q => q.PK_EmployeeID).ToList(), objCred.Date.Value, false);
                List <int> baseInstalada = ordenes.Select(p => p.FK_InstalledBaseID).ToList();
                var        modelos       = NegocioBase.GetAllByBI(baseInstalada).Select(p => p.FK_ProductID).Distinct();
                modelos = modelos.Where(x => x != null).ToList();
                List <int> modelo    = modelos.Where(x => x != null).Cast <int>().ToList();
                var        codfallas = new List <ModelViewFailures>();
                foreach (var item in modelos)
                {
                    var x = (from c in GetByProductID(item.Value)
                             join p in codefailure on c.FK_CodeFailureID equals p.PK_CodeFailureID
                             select new ModelViewFailures()
                    {
                        CodeFailureID = p.PK_CodeFailureID,
                        ProductID = c.FK_ProductID,
                        CodeFailure = p.CodeFailure1,
                        Failure = p.Failure,
                        Complexity = c.Complexity.GetValueOrDefault(),
                        Status = c.Status
                    }).ToList();

                    codfallas.AddRange(x);
                }
                return(codfallas);
                //return (from c in modelos
                //        join p in GetAll() on c equals p.FK_ProductID
                //        join d in  codefailure on p.FK_CodeFailureID equals d.PK_CodeFailureID
                //        select new ModelViewFailures()
                //        {
                //            CodeFailureID = p.FK_CodeFailureID,
                //            ProductID = p.FK_ProductID,
                //            CodeFailure = d.CodeFailure1,
                //            Failure = d.Failure,
                //            Complexity = p.Complexity.GetValueOrDefault(),
                //            Status = p.Status
                //        }).ToList();
            }
            else
            {
                return((from c in GetByProductID(objCred.ProductID)
                        join p in codefailure on c.FK_CodeFailureID equals p.PK_CodeFailureID
                        select new ModelViewFailures()
                {
                    CodeFailureID = p.PK_CodeFailureID,
                    ProductID = c.FK_ProductID,
                    CodeFailure = p.CodeFailure1,
                    Failure = p.Failure,
                    Complexity = c.Complexity.GetValueOrDefault(),
                    Status = c.Status
                }).ToList());
            }
        }
        //public List<ModelViewSpareParts> GetListSparePartsComplete(ModelViewUserG objCred)
        //{
        //    return new RepositoryBuildOfMaterial().GetList(objCred);
        //}


        public List <ModelViewSpareParts> GetListSpareParts(ModelViewUserG objCred)
        {
            var NegocioBase     = new BusinessInstalledBase();
            var NegocioUsuario  = new BusinessUsers();
            var NegocioOrdenes  = new BusinessOrder();
            var NegocioEmpleado = new BusinessEmployee();
            var NegocioManoObra = new BusinessWorkforce();
            var user            = NegocioUsuario.GetUserByToken(objCred.TokenUser);
            var empleado        = NegocioEmpleado.GetByUserID(user.UserID);


            var lista = new List <ModelViewSpareParts>();

            if (objCred.ProductID == 0)
            {
                //var ordenes1 = NegocioOrdenes.GetAll().Where(p => empleado.Select(q => q.PK_EmployeeID).ToArray<int>().Contains(p.FK_EmployeeID.Value) && p.OrderExecuteDate >= objCred.Date);
                var        ordenes       = NegocioOrdenes.GetAll(empleado.Select(q => q.PK_EmployeeID).ToList(), objCred.Date.Value, false);
                List <int> baseInstalada = ordenes.Select(p => p.FK_InstalledBaseID).ToList();
                //var prod = NegocioBase.GetAll();
                //var modelos = (from c in ordenes
                //               join p in prod on c.FK_InstalledBaseID equals p.PK_InstalledBaseID
                //               select p.FK_ProductID).Distinct();
                var modelos = NegocioBase.GetAllByBI(baseInstalada).Select(p => p.FK_ProductID).Distinct();
                modelos = modelos.Where(x => x != null).ToList();
                List <int> modelo = modelos.Where(x => x != null).Cast <int>().ToList();
                lista = GetListSparePartsByModel(modelo);
                //lista = (from c in modelos
                //         join p in GetAll() on c equals p.FK_ProductID
                //         select new ModelViewSpareParts()
                //         {
                //             BuildOfMaterialsID = p.PK_BuildOfMaterialsID,
                //             ProductID = p.FK_ProductID,
                //             Model = p.Model,
                //             SparePartsID = p.SparePartsID,
                //             Quantity = p.Quantity,
                //             SpartePartDescription = p.SparePartDescription,
                //             StatusBOM = p.StatusBOM,
                //             Status = p.Status
                //         }).ToList<ModelViewSpareParts>();
            }
            else
            {
                lista = GetAll().Where(p => p.FK_ProductID == objCred.ProductID).Select(p => new ModelViewSpareParts()
                {
                    BuildOfMaterialsID = p.PK_BuildOfMaterialsID,
                    ProductID          = p.FK_ProductID,
                    Model                 = p.Model,
                    SparePartsID          = p.SparePartsID,
                    Quantity              = p.Quantity,
                    SpartePartDescription = p.SparePartDescription,
                    StatusBOM             = p.StatusBOM,
                    Status                = p.Status
                }).ToList <ModelViewSpareParts>();
            }
            var demo2 = NegocioManoObra.GetAll().Where(p => p.WorkforceID == "8011161600000031").Select(p => new ModelViewSpareParts
            {
                BuildOfMaterialsID = 0,
                ProductID          = 0,
                Model                 = "",
                SparePartsID          = p.WorkforceID,
                Quantity              = 1,
                SpartePartDescription = p.Description,
                StatusBOM             = "",
                Status                = p.Status,
            }).First();

            var demo3 = NegocioManoObra.GetAll().Where(p => p.WorkforceID == "8011161600000032").Select(p => new ModelViewSpareParts
            {
                BuildOfMaterialsID = 0,
                ProductID          = 0,
                Model                 = "",
                SparePartsID          = p.WorkforceID,
                Quantity              = 1,
                SpartePartDescription = p.Description,
                StatusBOM             = "",
                Status                = p.Status,
            }).First();

            lista.Add(demo2);
            lista.Add(demo3);

            return(lista);
        }