public static Result <object> ReInsertInventoryToWarehouse(InvoiceDetail detail, IDataRepositoryFactory _repositoryFactory, Warehouse currentWarehouse)
        {
            var productUnitsRepo      = _repositoryFactory.GetDataRepositories <UnitProductEquivalence>();
            var inventoryRepo         = _repositoryFactory.GetDataRepositories <Inventory>();
            var warehouseMovementRepo = _repositoryFactory.GetDataRepositories <WarehouseMovement>();
            var productRepo           = _repositoryFactory.GetDataRepositories <Product>();

            Inventory currentInventory = inventoryRepo.Get(x => x.Where(y => y.ProductId == detail.ProductId && y.WarehouseId == currentWarehouse.Id && y.Active == true));

            if (currentInventory != null)
            {
                detail.Product.ProductUnits = detail.Product.ProductUnits ?? productUnitsRepo.GetAll(x => x.Where(y => y.Active && y.ProductId == detail.ProductId)).Data.ToList();

                var convertionResult = ProductsHelper.ConvertToProductPrincipalUnit(
                    currentInventory.Quantity,
                    detail.Product.ProductUnits.Where(pu => pu.IsPrimary).FirstOrDefault().UnitId,
                    detail.Product.ProductUnits
                    );
                if (convertionResult.Status < 0)
                {
                    return(convertionResult);
                }
                currentInventory.Quantity = (decimal)convertionResult.Data.FirstOrDefault();

                convertionResult = ProductsHelper.ConvertToProductPrincipalUnit(
                    detail.Quantity,
                    detail.UnitId.Value,
                    detail.Product.ProductUnits
                    );
                if (convertionResult.Status < 0)
                {
                    return(convertionResult);
                }

                detail.Quantity = (decimal)convertionResult.Data.FirstOrDefault();

                currentInventory.Quantity += detail.Quantity;
                Product Product = productRepo.Get(detail.ProductId).Data.FirstOrDefault();
                Product.Existence += detail.Quantity;
                productRepo.Update(Product);
                inventoryRepo.Update(currentInventory);
            }
            else
            {
                inventoryRepo.Add(new Inventory()
                {
                    Active      = true,
                    Quantity    = detail.Quantity,
                    WarehouseId = currentWarehouse.Id,
                    CreatedBy   = detail.CreatedBy,
                    CreatedDate = DateTime.Now,
                    ProductId   = detail.ProductId,
                    UnitId      = detail.Product.ProductUnits.Where(u => u.IsPrimary).FirstOrDefault().Id
                });
            }

            return(new Result <object>(0, 0, "ok_msg"));
        }
        public ActionResult InvoicePrint(long id, string language = "es")
        {
            this.httpContextAccessor.HttpContext.Request.Headers.Add("languageid", language);

            var invoiceRepo = dataRepository.GetDataRepositories <Invoice>();
            var invoice     = invoiceRepo.Get(x => x.Include(i => i.Customer).Include(i => i.Seller)
                                              .Include(i => i.Currency).Include(i => i.InvoiceDetails).ThenInclude(d => d.Product), y => y.Active == true && y.Id == id);
            var selectedLanguageKeys = languageKeys.Where(x => x.LanguageCode.ToLower() == language.ToLower()).ToList();

            invoice.InvoiceDetails  = invoice.InvoiceDetails.Where(x => x.Active == true).ToList();
            ViewBag.LanguageKeys    = selectedLanguageKeys;
            ViewBag.Invoice         = invoice;
            ViewBag.CurrentLanguage = language;
            return(View());
        }
Example #3
0
        public static void VerifyAdminUser(IDataRepositoryFactory dataRepositoryFactory)
        {
            var usersRepo = dataRepositoryFactory.GetDataRepositories <User>();
            var adminUser = usersRepo.Get(x => x.Where(y => y.UserName == "admin" && y.Active == true));

            if (adminUser == null)
            {
                adminUser = new User()
                {
                    Active        = true,
                    Address       = "",
                    BirthDay      = new DateTime(1900, 01, 01),
                    CreatedBy     = new Guid(),
                    CreatedDate   = DateTime.Now,
                    ContentType   = "",
                    CreatedByName = "admin",
                    Email         = "*****@*****.**",
                    Gender        = 'M',
                    UserName      = "******",
                    Password      = MD5.Encrypt("Admin@123", "uJ0TLb5KVx5C2qzcCdKwsynac18KBQ06"),
                    LastName      = "admin",
                    Phone         = "8095555555",
                    Name          = "admin",
                    Mobile        = "8095555555",
                };
                usersRepo.Add(adminUser);
            }
        }
Example #4
0
        public static void AddDetails(Invoice Invoice, IDataRepositoryFactory dataRepositoryFactory, bool updateTaxes = true)
        {
            var invoiceDetailRepo = dataRepositoryFactory.GetDataRepositories <InvoiceDetail>();

            Invoice.InvoiceDetails.ForEach(x =>
            {
                x.InvoiceId    = Invoice.Id;
                x.CreatedDate  = DateTime.Now;
                x.CreatedBy    = Invoice.CreatedBy;
                x.Active       = true;
                x.Date         = DateTime.Now;
                x.ModifiedDate = DateTime.Now;
                var result     = InventoryHelper.UpdateProductInventory(Invoice.BranchOffice, x, dataRepositoryFactory, Invoice);

                if (result.Status < 0)
                {
                    throw new Exception(result.Message);
                }
                else
                {
                    x = result.Data.FirstOrDefault();
                }

                if (x.SaveRegister)
                {
                    invoiceDetailRepo.Add(x);
                }
            });
            if (updateTaxes)
            {
                UpdateInvoiceTaxes(Invoice, dataRepositoryFactory);
            }
        }
 public LoginController(IMemoryCache cache, IOptions <AppSettings> appSettings, IDataRepositoryFactory repositoryFactory)
 {
     this._appSettings          = appSettings;
     this._cache                = cache;
     this.users                 = repositoryFactory.GetDataRepositories <User>();
     this.dataRepositoryFactory = repositoryFactory;
 }
Example #6
0
 public LogoutController(IMemoryCache cache, IOptions <AppSettings> appSettings, IDataRepositoryFactory repositoryFactory, IHttpContextAccessor httpContextAccessor)
 {
     this._httpContextAccessor = httpContextAccessor;
     this._appSettings         = appSettings;
     this._cache = cache;
     this.users  = repositoryFactory.GetDataRepositories <User>();
     this.dataRepositoryFactory = repositoryFactory;
     this.userRepository        = this.dataRepositoryFactory.GetCustomDataRepositories <IUserRepository>();
 }
        protected override Result <LeadDetail> ProcessDetail(long branchOfficeId, LeadDetail detail, IDataRepositoryFactory dataRepositoryFactory, InvoiceLead lead)
        {
            var detailService    = dataRepositoryFactory.GetCustomDataRepositories <IInvoiceDetailRepository>();
            var productRepo      = dataRepositoryFactory.GetDataRepositories <Product>();
            var productBasesRepo = dataRepositoryFactory.GetDataRepositories <CompositeProduct>();
            var productUnitRepo  = dataRepositoryFactory.GetDataRepositories <UnitProductEquivalence>();
            var productBases     = detail.Product.BaseCompositeProducts == null || detail.Product.BaseCompositeProducts.Count() == 0 ? productBasesRepo.GetAll(x => x.AsNoTracking().Where(y => y.Active == true && y.ProductId == detail.ProductId)).Data.ToList() :
                                   detail.Product.BaseCompositeProducts.ToList();

            detail.WarehouseId = null;
            detail.UnitId      = null;
            var detailResult = detailService.Add(detail);

            productBases.ForEach(p =>
            {
                var currentProduct = productRepo.Get(p.BaseProductId).Data.FirstOrDefault();

                var currentUnit = p.UnitProductEquivalence == null ? p.BaseProductUnitId.HasValue ?
                                  productUnitRepo.Get(p.BaseProductUnitId.Value).Data.FirstOrDefault() : null : p.UnitProductEquivalence;

                var instance = GetBillProductOrServiceInstance.GetBillingInstance(currentProduct);
                // decimal nuevaQuantity = p.Quantity * detail.Quantity;
                LeadDetail detailTemp = new LeadDetail(detail)
                {
                    Quantity  = p.Quantity * detail.Quantity,
                    UnitId    = currentUnit != null ? currentUnit.Unit.Id : p.BaseProductUnitId,
                    ProductId = p.BaseProductId,
                    ParentId  = detailResult.Id,
                    Product   = currentProduct,
                    Free      = true
                };
                var result = instance.ProcessProductService(branchOfficeId, detailTemp, dataRepositoryFactory, lead).Data.FirstOrDefault();
                if (result.SaveRegister)
                {
                    detailService.Add(result);
                }
            });
            detail.SaveRegister = false;
            return(new Result <LeadDetail>(0, 0, "ok_msg", new List <LeadDetail>()
            {
                detail
            }));
        }
        protected override Result <LeadDetail> ProcessReturnDetail(long branchOfficeId, LeadDetail detail, IDataRepositoryFactory dataRepositoryFactory, InvoiceLead lead)
        {
            var invoiceDetailRepo = dataRepositoryFactory.GetCustomDataRepositories <IInvoiceDetailRepository>();
            var productRepo       = dataRepositoryFactory.GetDataRepositories <Product>();
            var productBasesRepo  = dataRepositoryFactory.GetDataRepositories <CompositeProduct>();
            var productUnitRepo   = dataRepositoryFactory.GetDataRepositories <UnitProductEquivalence>();

            var baseDetails = invoiceDetailRepo.GetChildren(detail.Id).ToList();

            baseDetails.ForEach(p =>
            {
                var currentProduct = p.Product ?? productRepo.Get(p.ProductId).Data.FirstOrDefault();



                var instance = GetBillProductOrServiceInstance.GetBillingInstance(currentProduct);
                // decimal nuevaQuantity = p.Quantity * detail.Quantity;
                LeadDetail detailTemp = new LeadDetail()
                {
                    Id            = p.Id,
                    Active        = p.Active,
                    WarehouseId   = p.WarehouseId ?? null,
                    Quantity      = p.Quantity * (detail.ReturnAmount / detail.Quantity),
                    ReturnAmount  = p.Quantity * (detail.ReturnAmount / detail.Quantity),
                    ParentId      = p.ParentId ?? null,
                    Defective     = detail.Defective,
                    InvoiceLeadId = p.InvoiceLeadId,
                    Product       = p.Product,
                    ProductId     = p.ProductId,
                    Unit          = p.Unit,
                    UnitId        = p.UnitId
                };

                var resultado = instance.ReturnProductService(branchOfficeId, detailTemp, dataRepositoryFactory, lead);
            });

            return(new Result <LeadDetail>(0, 0, "ok_msg", new List <LeadDetail>()
            {
                detail
            }));
        }
 public ViewsController(IDataRepositoryFactory dataRepositoryFactory, IHttpContextAccessor context, IMemoryCache _cache) : base()
 {
     this.dataRepository      = dataRepositoryFactory;
     this.httpContextAccessor = context;
     this.memoryCache         = _cache;
     languageKeys             = memoryCache.Get <List <LanguageKey> >("languageKeysMem");
     if (languageKeys == null)
     {
         this.languageKeys = dataRepository.GetDataRepositories <LanguageKey>().GetAll(x => x, y => y.Active == true).Data.ToList();
         memoryCache.Set("languageKeysMem", languageKeys);
     }
 }
Example #10
0
 public BaseController(IOptions <AppSettings> appSettings, IDataRepositoryFactory repositoryFactory, IMemoryCache cache, IBase <T> customRepo = null)
 {
     this._cache           = cache;
     _appSettings          = appSettings;
     _repositoryFactory    = repositoryFactory;
     this.languageKeysRepo = repositoryFactory.GetDataRepositories <LanguageKey>();
     this.languageKeys     = _cache.Get <IEnumerable <LanguageKey> >("languageKeysMem");
     if (this.languageKeys == null)
     {
         this.languageKeys = this.languageKeysRepo.GetAll(x => x, y => y.Active == true).Data;
         this._cache.Set("languageKeysMem", this.languageKeys, DateTime.Now.AddHours(24));
     }
     this._baseRepo = customRepo ?? _repositoryFactory.GetDataRepositories <T>();
 }
Example #11
0
        public static Result <InvoiceDetail> UpdateProductInventory(BranchOffice branchOffice, InvoiceDetail detail, IDataRepositoryFactory _repositoryFactory, Invoice invoice)
        {
            InvoiceDetail newdetail     = new InvoiceDetail(detail);
            var           productRepo   = _repositoryFactory.GetDataRepositories <Product>();
            var           inventoryRepo = _repositoryFactory.GetDataRepositories <Inventory>();
            var           detailRepo    = _repositoryFactory.GetDataRepositories <InvoiceDetail>();

            var service = GetBillProductOrServiceInstance.GetBillingInstance(detail.Product);
            var result  = service.ProcessProductService(branchOffice.Id, detail, _repositoryFactory, invoice);

            if (result.Status >= 0)
            {
                result.Data = new List <InvoiceDetail>()
                {
                    newdetail
                }
            }
            ;


            return(result);
        }
    }
Example #12
0
 public CompanyStateController(IOptions <AppSettings> appSettings, IDataRepositoryFactory repositoryFactory, IMemoryCache cache)
 {
     this._customRepo      = repositoryFactory.GetCustomDataRepositories <IInvoiceRepository>();
     _repositoryFactory    = repositoryFactory;
     _appSettings          = appSettings;
     _cache                = cache;
     this.languageKeysRepo = repositoryFactory.GetDataRepositories <LanguageKey>();
     this.languageKeys     = _cache.Get <IEnumerable <LanguageKey> >("languageKeysMem");
     if (this.languageKeys == null)
     {
         this.languageKeys = this.languageKeysRepo.GetAll(x => x, y => y.Active == true).Data;
         this._cache.Set("languageKeysMem", this.languageKeys, DateTime.Now.AddHours(24));
     }
 }
Example #13
0
        public static bool InsertarImpuestos(Product product, IDataRepositoryFactory dataRepositoryFactory)
        {
            var taxesRepo = dataRepositoryFactory.GetDataRepositories <ProductTax>();

            product.Taxes.ForEach(u =>
            {
                u.CreatedBy   = product.CreatedBy;
                u.CreatedDate = DateTime.Now;
                u.Active      = true;
                u.ProductId   = product.Id;
                taxesRepo.Add(u);
            });

            return(true);
        }
Example #14
0
        public static bool AddUnits(Product product, IDataRepositoryFactory dataRepositoryFactory)
        {
            var unitsRepo = dataRepositoryFactory.GetDataRepositories <UnitProductEquivalence>();

            product.ProductUnits.ForEach(u =>
            {
                u.CreatedBy   = product.CreatedBy;
                u.CreatedDate = DateTime.Now;
                u.Active      = true;
                u.ProductId   = product.Id;
                unitsRepo.Add(u);
            });

            return(true);
        }
Example #15
0
        public static void AddQuoteDetails(Invoice invoice, IDataRepositoryFactory dataRepositoryFactory)
        {
            var detailsRepo = dataRepositoryFactory.GetDataRepositories <InvoiceDetail>();

            invoice.InvoiceDetails.ForEach(x =>
            {
                x.InvoiceId    = invoice.Id;
                x.CreatedDate  = DateTime.Now;
                x.CreatedBy    = invoice.CreatedBy;
                x.Active       = true;
                x.Date         = DateTime.Now;
                x.ModifiedDate = DateTime.Now;
                detailsRepo.Add(x);
            });

            UpdateInvoiceTaxes(invoice, dataRepositoryFactory);
        }
 public static string CreateExpensesControl(IDataRepositoryFactory dataRepositoryFactory)
 {
     try
     {
         var             repo        = dataRepositoryFactory.GetDataRepositories <SequenceControl>();
         string          result      = string.Empty;
         SequenceControl lastControl = repo.Get(x => x.AsNoTracking().Where(y => y.Active == true && y.Code == (short)SequenceTypes.Expenses));
         result = String.Format("{0}{1:00000}", lastControl.Code, (lastControl.NumericControl + 1));
         lastControl.NumericControl += 1;
         repo.Update(lastControl);
         return(result);
     }
     catch
     {
         throw new Exception($"sequenceError_msg");
     }
 }
Example #17
0
        public static bool AddBaseProducts(Product product, IDataRepositoryFactory dataRepositoryFactory)
        {
            var baseProductsRepo = dataRepositoryFactory.GetDataRepositories <CompositeProduct>();

            if (product.IsService && product.IsCompositeProduct)
            {
                product.BaseCompositeProducts.ForEach(u =>
                {
                    u.CreatedBy   = product.CreatedBy;
                    u.CreatedDate = DateTime.Now;
                    u.Active      = true;
                    u.ProductId   = product.Id;
                    baseProductsRepo.Add(u);
                });
            }

            return(true);
        }
Example #18
0
 public BaseController(IOptions <AppSettings> appSettings, IDataRepositoryFactory repositoryFactory)
 {
     _appSettings       = appSettings;
     _repositoryFactory = repositoryFactory;
     this._baseRepo     = _repositoryFactory.GetDataRepositories <T>();
 }
Example #19
0
 protected virtual IBase <K> GetDataRepo <K>() where K : class, ICommonData, new()
 {
     return(_repositoryFactory.GetDataRepositories <K>());
 }
        public override Result <CustomerReturn> Add(CustomerReturn entity)
        {
            var result     = new Result <CustomerReturn>(-1, -1, "error_msg");
            var warehouses = _Context.Warehouses.AsNoTracking().Where(x => x.Active == true).ToList();

            using (var transaction = _Context.Database.BeginTransaction())
            {
                try
                {
                    var invoice = repositoryFactory.GetCustomDataRepositories <IInvoiceRepository>().GetByInvoiceNumber(entity.InvoiceNumber);
                    if (string.IsNullOrEmpty(entity.InvoiceNumber))
                    {
                        transaction.Rollback();
                        return(new Result <CustomerReturn>(-1, -1, "invoiceNumberRequired_error"));
                    }
                    if (repositoryFactory.GetDataRepositories <CustomerReturn>().Get(x => x, y => y.Active == true && y.InvoiceNumber.ToUpper() == entity.InvoiceNumber.ToUpper()) != null)
                    {
                        transaction.Rollback();
                        return(new Result <CustomerReturn>(-1, -1, "returnAlreadyApplied_error"));
                    }
                    if (entity.ReturnDetails == null || entity.ReturnDetails.Count == 0 || !entity.ReturnDetails.Any(x => x.Quantity > 0))
                    {
                        transaction.Rollback();
                        return(new Result <CustomerReturn>(-1, -1, "detailsRequired_error"));
                    }
                    if (invoice == null)
                    {
                        transaction.Rollback();
                        return(new Result <CustomerReturn>(-1, -1, "invoiceDoesNotExist_error"));
                    }
                    var validStates = new char[] { (char)Enums.BillingStates.Paid, (char)Enums.BillingStates.FullPaid };
                    if (!validStates.Contains(invoice.State))
                    {
                        transaction.Rollback();
                        return(new Result <CustomerReturn>(-1, -1, "invalidInvoiceStateReturn_error"));
                    }
                    entity.CurrencyId        = invoice.CurrencyId;
                    entity.CustomerId        = invoice.CustomerId;
                    entity.InvoiceId         = invoice.Id;
                    entity.BranchOfficeId    = invoice.BranchOfficeId;
                    entity.Date              = DateTime.Now;
                    entity.Active            = true;
                    entity.BranchOffice      = null;
                    entity.Currency          = null;
                    entity.Customer          = null;
                    entity.Invoice           = null;
                    entity.BeforeTaxesAmount = entity.ReturnDetails.Sum(x => x.BeforeTaxesAmount);
                    entity.TaxesAmount       = entity.ReturnDetails.Sum(x => x.TaxesAmount);
                    entity.TotalAmount       = entity.BeforeTaxesAmount + entity.TaxesAmount;
                    entity.InvoiceNumber     = invoice.InvoiceNumber;
                    CreditNote creditNote = new CreditNote()
                    {
                        Active               = true,
                        Amount               = entity.ReturnDetails.Sum(x => x.TotalAmount),
                        Applied              = false,
                        OriginInvoiceNumber  = entity.InvoiceNumber,
                        AppliedInvoiceNumber = "",
                        CurrencyId           = invoice.CurrencyId,
                        CustomerId           = invoice.CustomerId,
                        Date     = DateTime.Now,
                        Sequence = Helpers.SequencesHelper.CreateCustomersReturnsControl(repositoryFactory)
                    };
                    var creditNoteResult = repositoryFactory.GetCustomDataRepositories <ICreditNoteRepository>().Add(creditNote);
                    if (creditNoteResult.Status < 0)
                    {
                        transaction.Rollback();
                        return(new Result <CustomerReturn>(-1, -1, "error_msg"));
                    }
                    entity.CreditNoteId     = creditNoteResult.Data.FirstOrDefault().Id;
                    entity.CreditNoteNumber = creditNote.Sequence;
                    foreach (var d in entity.ReturnDetails)
                    {
                        d.Active        = true;
                        d.CustomerId    = entity.CustomerId;
                        d.Date          = DateTime.Now;
                        d.InvoiceNumber = entity.InvoiceNumber;
                        d.Reference     = creditNote.Sequence;
                        d.WarehouseId   = d.Defective ? warehouses.FirstOrDefault(x => x.Code.ToLower() == "def")?.Id : d.WarehouseId;
                        if (d.WarehouseId.HasValue && d.WarehouseId > 0)
                        {
                            var inventoryResult = Helpers.InventoryHelper.ReInsertInventoryToWarehouse(new InvoiceDetail()
                            {
                                Active            = true,
                                BeforeTaxesAmount = d.BeforeTaxesAmount,
                                Amount            = 0,
                                CreditNoteAmount  = d.TotalAmount,
                                TaxesAmount       = d.TaxesAmount,
                                TotalAmount       = d.TotalAmount,
                                BranchOfficeId    = invoice.BranchOfficeId,
                                Date        = d.Date,
                                Defective   = d.Defective,
                                InvoiceId   = entity.InvoiceId,
                                ProductId   = d.ProductId,
                                UnitId      = d.UnitId,
                                WarehouseId = d.WarehouseId,
                                Quantity    = d.Quantity
                            }, repositoryFactory, warehouses.FirstOrDefault(x => x.Id == d.WarehouseId.Value), d.Reference);
                            if (inventoryResult.Status < 0)
                            {
                                transaction.Rollback();
                                return(new Result <CustomerReturn>(inventoryResult.Id, inventoryResult.Status, inventoryResult.Message));
                            }
                        }
                    }

                    entity.ReturnDetails.ForEach(d => {
                        d.Product   = null;
                        d.Customer  = null;
                        d.Warehouse = null;
                    });

                    result = base.Add(entity);
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    result = new Result <CustomerReturn>(-1, -1, "error_msg", null, ex);
                }
            }
            return(result);
        }
Example #21
0
        public static Result <ExpensesPayment> ApplyExpensePayment(ExpensesPayment payment, IDataRepositoryFactory dataRepositoryFactory)
        {
            var paymentRepo = dataRepositoryFactory.GetDataRepositories <ExpensesPayment>();

            return(paymentRepo.Add(payment));
        }
Example #22
0
        protected override Result <LeadDetail> ProcessReturnDetail(long branchOfficeId, LeadDetail detail, IDataRepositoryFactory dataRepositoryFactory, InvoiceLead invoice)
        {
            Inventory currentInventory = null;
            var       warehouseRepo    = dataRepositoryFactory.GetDataRepositories <Warehouse>();
            var       productRepo      = dataRepositoryFactory.GetDataRepositories <Product>();
            var       inventoryRepo    = dataRepositoryFactory.GetDataRepositories <Inventory>();
            var       productUnitsRepo = dataRepositoryFactory.GetDataRepositories <UnitProductEquivalence>();
            var       logMovementsRepo = dataRepositoryFactory.GetDataRepositories <WarehouseMovement>();

            if (detail.WarehouseId.HasValue)
            {
                detail.Product.ProductUnits = detail.Product.ProductUnits == null || detail.Product.ProductUnits.Count() == 0 ?
                                              productUnitsRepo.GetAll(x => x.AsNoTracking().Where(y => y.Active == true && y.ProductId == detail.ProductId)).Data.ToList() : detail.Product.ProductUnits;

                if (detail.Defective)
                {
                    var defectiveWarehouse = warehouseRepo.Get(x => x.AsNoTracking().Where(y => y.Active == true && y.Code == "DEF" && y.BranchOfficeId == branchOfficeId));
                    if (defectiveWarehouse == null)
                    {
                        return(new Result <LeadDetail>(-1, -1, $"defWarehouseNotExit_msg"));
                    }

                    currentInventory = inventoryRepo.Get(x => x.AsNoTracking().Where(y => y.Active == true && y.BranchOfficeId == branchOfficeId && y.ProductId == detail.ProductId &&
                                                                                     y.WarehouseId == defectiveWarehouse.Id)) ??
                                       new Inventory()
                    {
                        WarehouseId    = defectiveWarehouse.Id,
                        ProductId      = detail.ProductId,
                        Active         = true,
                        Quantity       = 0,
                        CreatedBy      = detail.CreatedBy,
                        CreatedDate    = DateTime.Now,
                        BranchOfficeId = branchOfficeId,
                        UnitId         = detail.Product.ProductUnits.FirstOrDefault(u => u.IsPrimary).UnitId,
                        Product        = detail.Product
                    };
                }
                else
                {
                    currentInventory = inventoryRepo.Get(x => x.AsNoTracking().Where(y => y.Active == true && y.ProductId == detail.ProductId && y.WarehouseId == detail.WarehouseId));
                }
                if (currentInventory != null)
                {
                    currentInventory.Product.ProductUnits = currentInventory.Product.ProductUnits == null || currentInventory.Product.ProductUnits.Count() == 0 ?
                                                            productUnitsRepo.GetAll(x => x.AsNoTracking().Where(y => y.Active == true && y.ProductId == currentInventory.ProductId)).Data.ToList(): currentInventory.Product.ProductUnits;

                    currentInventory.Quantity = (decimal)ProductsHelper.ConvertToProductPrincipalUnit(
                        currentInventory.Quantity,
                        detail.Product.ProductUnits.FirstOrDefault(pu => pu.IsPrimary).UnitId,
                        detail.Product.ProductUnits.ToList()
                        ).Data.FirstOrDefault();
                    detail.Quantity = (decimal)ProductsHelper.ConvertToProductPrincipalUnit(
                        detail.Quantity,
                        detail.UnitId.Value,
                        detail.Product.ProductUnits.ToList()
                        ).Data.FirstOrDefault();
                    var units = detail.Product.ProductUnits == null || detail.Product.ProductUnits.Count() == 0 ?
                                productUnitsRepo.GetAll(x => x.AsNoTracking().Where(y => y.Active == true && y.ProductId == detail.ProductId)).Data.ToList() : detail.Product.ProductUnits;

                    var warehouseMov = new WarehouseMovement(currentInventory.WarehouseId, detail.ProductId, detail.Quantity, true,
                                                             units.Where(u => u.IsPrimary).FirstOrDefault().UnitId, branchOfficeId, "IN", invoice.InvoiceNumber ?? invoice.DocumentNumber ?? string.Empty);
                    logMovementsRepo.Add(warehouseMov);

                    currentInventory.Quantity += detail.Quantity;
                    currentInventory.UnitId    = currentInventory.Product.ProductUnits.FirstOrDefault(x => x.IsPrimary).UnitId;
                    Product Product = productRepo.Get(detail.ProductId).Data.FirstOrDefault();
                    Product.Existence += detail.Quantity;
                    productRepo.Update(Product);
                    if (currentInventory.Id > 0)
                    {
                        inventoryRepo.Update(currentInventory);
                    }
                    else
                    {
                        inventoryRepo.Add(currentInventory);
                    }
                }
                else
                {
                    return(new Result <LeadDetail>(-1, -1, "outOfStock_msg"));
                }
            }

            return(new Result <LeadDetail>(0, 0, "ok_msg", new List <LeadDetail>()
            {
                detail
            }));
        }
Example #23
0
        protected override Result <LeadDetail> ProcessDetail(long branchOfficeId, LeadDetail detail, IDataRepositoryFactory dataRepositoryFactory, InvoiceLead invoiceLead)
        {
            var        inventoriesRepo  = dataRepositoryFactory.GetDataRepositories <Inventory>();
            var        warehouseRepo    = dataRepositoryFactory.GetDataRepositories <Warehouse>();
            var        productUnitsRepo = dataRepositoryFactory.GetDataRepositories <UnitProductEquivalence>();
            LeadDetail newDetail        = new LeadDetail(detail);

            detail.Product.ProductUnits = detail.Product.ProductUnits == null || detail.Product.ProductUnits.Count() == 0 ?
                                          productUnitsRepo.GetAll(x => x.AsNoTracking().Where(y => y.Active == true && y.ProductId == detail.ProductId)).Data.ToList() : detail.Product.ProductUnits;
            var convertionResult = ProductsHelper.ConvertToProductPrincipalUnit(
                newDetail.Quantity,
                newDetail.UnitId.Value,
                newDetail.Product.ProductUnits.ToList()
                );

            if (convertionResult.Status < 0)
            {
                return(new Result <LeadDetail>(-1, -1, convertionResult.Message));
            }

            decimal warehouseQuantity = (decimal)convertionResult.Data.FirstOrDefault();
            decimal quantitySumm      = warehouseQuantity;

            LeadDetail newDetailCustom = new LeadDetail(newDetail)
            {
                Quantity = warehouseQuantity
            };
            Warehouse warehouse = null;

            if ((invoiceLead.WarehouseId <= 0))
            {
                var branchOfficeWarehouses = warehouseRepo.GetAll(x => x.AsNoTracking().Where(y => y.Active == true && y.BranchOfficeId == branchOfficeId &&
                                                                                              y.Code.ToLower() != "DEF")).Data.ToList();
                // ojo ojo ojo
                var productInventory = inventoriesRepo.Get(x => x.AsNoTracking().Where(y => y.Active == true && y.ProductId == newDetail.ProductId &&
                                                                                       y.Quantity >= warehouseQuantity && branchOfficeWarehouses.Select(r => r.Id).ToList().Contains(y.WarehouseId)));

                if (productInventory == null)
                {
                    return(new Result <LeadDetail>(-1, -1, "outOfStock_msg"));
                }
                // ojo ojo ojo

                warehouse = branchOfficeWarehouses.FirstOrDefault(x => x.Id == productInventory.WarehouseId);
            }
            else
            {
                warehouse = warehouseRepo.Get(invoiceLead.WarehouseId).Data.FirstOrDefault();
            }


            if ((invoiceLead.WarehouseId > 0) && (inventoriesRepo.Get(x => x.AsNoTracking().Where(y => y.Active == true && y.ProductId == newDetail.ProductId &&
                                                                                                  y.Quantity >= warehouseQuantity && y.WarehouseId == invoiceLead.WarehouseId)) == null))
            {
                return(new Result <LeadDetail>(-1, -1, $"outOfStock_msg | {detail.Product?.Name?? ""}"));
            }

            if (warehouse == null)
            {
                var branchOfficeWarehouses = warehouseRepo.GetAll(x => x.AsNoTracking().Where(y => y.Active == true && y.BranchOfficeId == branchOfficeId &&
                                                                                              y.Code.ToLower() != "DEF")).Data.ToList();
                // ojo ojo ojo
                var branchOfficeInventory = inventoriesRepo.GetAll(x => x.AsNoTracking().Where(y => y.Active == true && y.ProductId == newDetail.ProductId &&
                                                                                               y.Quantity > 0 && branchOfficeWarehouses.Select(r => r.Id).ToList().Contains(y.WarehouseId))).Data.ToList();

                if (branchOfficeInventory == null)
                {
                    return(new Result <LeadDetail>(-1, -1, $"outOfStock_msg | {newDetail.Product.Name}"));
                }


                convertionResult = ProductsHelper.ConvertToProductPrincipalUnit(
                    branchOfficeInventory.Sum(p => p.Quantity),
                    branchOfficeInventory.FirstOrDefault().UnitId,
                    newDetail.Product.ProductUnits.ToList()
                    );
                if (convertionResult.Status < 0)
                {
                    return(new Result <LeadDetail>(-1, -1, convertionResult.Message));
                }

                decimal warehousesQuantitySumm = (decimal)convertionResult.Data.FirstOrDefault();

                if (warehousesQuantitySumm < warehouseQuantity)
                {
                    return(new Result <LeadDetail>(-1, -1, $"outOfStock_msg | {newDetail.Product.Name}"));
                }

                foreach (Inventory warehouseProduct in branchOfficeInventory)
                {
                    if (quantitySumm <= 0)
                    {
                        break;
                    }
                    decimal currentWarehouseQuantity = warehouseProduct.Quantity;
                    if (quantitySumm < currentWarehouseQuantity)
                    {
                        currentWarehouseQuantity = quantitySumm;
                    }

                    newDetailCustom          = new LeadDetail(newDetail);
                    newDetailCustom.Quantity = (decimal)ProductsHelper.ConvertFromProductPrincipalUnit(
                        currentWarehouseQuantity,
                        newDetail.UnitId.Value,
                        newDetail.Product.ProductUnits.ToList()
                        ).Data.FirstOrDefault();

                    newDetailCustom.WarehouseId = warehouseProduct.WarehouseId;
                    //  newDetailCustom.UnitId = newDetailCustom.Product.ProductUnits.FirstOrDefault(x => x.IsPrimary).UnitId;
                    InventoryHelper.UpdateInventory(newDetailCustom, warehouseRepo.Get(warehouseProduct.WarehouseId).Data.FirstOrDefault(), invoiceLead, dataRepositoryFactory);
                    newDetail.WarehouseId = warehouseProduct.WarehouseId;

                    quantitySumm -= currentWarehouseQuantity;
                }
            }
            else
            {
                newDetail.WarehouseId  = warehouse.Id;
                newDetailCustom.Unit   = newDetailCustom.Product.ProductUnits.FirstOrDefault(x => x.IsPrimary).Unit;
                newDetailCustom.UnitId = newDetailCustom.Unit.Id;
                InventoryHelper.UpdateInventory(newDetailCustom, warehouse, invoiceLead, dataRepositoryFactory);
            }

            return(new Result <LeadDetail>(0, 0, "ok_msg", new List <LeadDetail>()
            {
                newDetail
            }));
        }
Example #24
0
        public static Result <object> AddInventory(InvoiceDetail detail, Invoice invoice, IDataRepositoryFactory _repositoryFactory)
        {
            var warehouseMovementRepo = _repositoryFactory.GetDataRepositories <WarehouseMovement>();
            var productUnitsRepo      = _repositoryFactory.GetDataRepositories <UnitProductEquivalence>();
            var productRepo           = _repositoryFactory.GetDataRepositories <Product>();
            var inventoryRepo         = _repositoryFactory.GetDataRepositories <Inventory>();

            if (!detail.Product.IsService)
            {
                detail.Product.ProductUnits = detail.Product.ProductUnits ?? productUnitsRepo.GetAll(x => x.Where(y => y.Active == true && y.ProductId == detail.ProductId)).Data.ToList();


                if (detail.WarehouseId.HasValue)
                {
                    Inventory currentInventory = inventoryRepo.Get(x => x.Where(y => y.Active == true && y.ProductId == detail.ProductId && y.WarehouseId == detail.WarehouseId.Value));
                    if (currentInventory != null)
                    {
                        var convertionResult = ProductsHelper.ConvertToProductPrincipalUnit(
                            currentInventory.Quantity,
                            detail.Product.ProductUnits.Where(pu => pu.IsPrimary).FirstOrDefault().UnitId,
                            detail.Product.ProductUnits
                            );
                        if (convertionResult.Status < 0)
                        {
                            return(convertionResult);
                        }

                        currentInventory.Quantity = (decimal)convertionResult.Data.FirstOrDefault();

                        convertionResult = ProductsHelper.ConvertToProductPrincipalUnit(
                            detail.Quantity,
                            detail.UnitId.Value,
                            detail.Product.ProductUnits
                            );
                        if (convertionResult.Status < 0)
                        {
                            return(convertionResult);
                        }

                        detail.Quantity = (decimal)convertionResult.Data.FirstOrDefault();
                        var units = detail.Product.ProductUnits ?? productUnitsRepo.GetAll(x => x.Where(y => y.Active == true && y.ProductId == detail.ProductId)).Data.ToList();


                        currentInventory.Quantity += detail.Quantity;
                        Product Product = productRepo.Get(detail.ProductId).Data.FirstOrDefault();
                        Product.Existence += detail.Quantity;
                        productRepo.Update(Product);
                        inventoryRepo.Update(currentInventory);

                        WarehouseMovement movimientoAlmacen = new WarehouseMovement(currentInventory.WarehouseId, detail.ProductId, detail.Quantity, true,
                                                                                    units.Where(u => u.IsPrimary).FirstOrDefault().UnitId, 0, "IN", invoice.InvoiceNumber ?? invoice.DocumentNumber ?? string.Empty, currentInventory.Quantity);
                        warehouseMovementRepo.Add(movimientoAlmacen);
                        return(new Result <object>(0, 0, "ok_msg"));
                    }
                    else
                    {
                        return(new Result <object>(-1, -1, $"outOfStock_msg | {detail.Product.Name}"));
                    }
                }
            }

            return(new Result <object>(0, 0, "ok_msg"));
        }
Example #25
0
        public static Result <object> UpdateInventory(InvoiceDetail detail, Warehouse currentWarehouse, Invoice invoice, IDataRepositoryFactory _repositoryFactory)
        {
            var       warehouseMovementRepo = _repositoryFactory.GetDataRepositories <WarehouseMovement>();
            var       productUnitsRepo      = _repositoryFactory.GetDataRepositories <UnitProductEquivalence>();
            var       productRepo           = _repositoryFactory.GetDataRepositories <Product>();
            var       inventoryRepo         = _repositoryFactory.GetDataRepositories <Inventory>();
            Inventory currentInventory      = inventoryRepo.Get(x => x.Where(y => y.Active == true && y.ProductId == detail.ProductId && y.WarehouseId == currentWarehouse.Id));

            if (currentInventory != null)
            {
                var convertionResult = ProductsHelper.ConvertToProductPrincipalUnit(
                    detail.Quantity,
                    detail.UnitId.Value,
                    detail.Product.ProductUnits
                    );
                if (convertionResult.Status >= 0)
                {
                    detail.Quantity = (decimal)convertionResult.Data.FirstOrDefault();
                }
                else
                {
                    return(convertionResult);
                }

                detail.UnitId    = detail.Product.ProductUnits.FirstOrDefault(pu => pu.IsPrimary).UnitId;
                convertionResult = ProductsHelper.ConvertFromProductPrincipalUnit(
                    currentInventory.Quantity,
                    detail.Product.ProductUnits.Where(pu => pu.IsPrimary).FirstOrDefault().UnitId,
                    detail.Product.ProductUnits
                    );

                if (convertionResult.Status >= 0)
                {
                    currentInventory.Quantity = (decimal)convertionResult.Data.FirstOrDefault();
                }
                else
                {
                    return(convertionResult);
                }


                if (currentInventory.Quantity < detail.Quantity)
                {
                    return(new Result <object>(-1, -1, $"outOfStock_msg | {detail.Product.Name},{currentWarehouse.Name}"));
                }
                else
                {
                    currentInventory.Quantity -= detail.Quantity;
                    Product product = productRepo.Get(detail.ProductId).Data?.FirstOrDefault();
                    product.Existence -= detail.Quantity;
                    productRepo.Update(product);
                    inventoryRepo.Update(currentInventory);


                    var units = detail.Product.ProductUnits ?? productUnitsRepo.GetAll(x => x.Where(y => y.Active == true && y.ProductId == detail.ProductId)).Data;
                    WarehouseMovement movement = new WarehouseMovement(currentWarehouse.Id, detail.ProductId, detail.Quantity * -1,
                                                                       true, units.Where(u => u.IsPrimary).FirstOrDefault().UnitId, 0, "OUT",
                                                                       invoice.InvoiceNumber ?? invoice.DocumentNumber ?? string.Empty, currentInventory.Quantity);

                    warehouseMovementRepo.Add(movement);
                    return(new Result <object>(0, 0, "ok_msg"));
                }
            }
            else
            {
                return(new Result <object>(-1, -1, $"outOfStock_msg | {detail.Product.Name},{currentWarehouse.Name}"));
            }
        }