Beispiel #1
0
        private int GetBeginningBalance(ERPContext context, Warehouse warehouse, Item item)
        {
            var periodYearBalances = context.StockBalances.FirstOrDefault(e => e.ItemID.Equals(item.ID) && e.WarehouseID.Equals(warehouse.ID) && e.Year == _periodYear);

            if (periodYearBalances == null) return 0;

            switch (_period)
            {
                case 1:
                    return periodYearBalances.BeginningBalance;
                case 2:
                    return periodYearBalances.Balance1;
                case 3:
                    return periodYearBalances.Balance2;
                case 4:
                    return periodYearBalances.Balance3;
                case 5:
                    return periodYearBalances.Balance4;
                case 6:
                    return periodYearBalances.Balance5;
                case 7:
                    return periodYearBalances.Balance6;
                case 8:
                    return periodYearBalances.Balance7;
                case 9:
                    return periodYearBalances.Balance8;
                case 10:
                    return periodYearBalances.Balance9;
                case 11:
                    return periodYearBalances.Balance10;
                default:
                    return periodYearBalances.Balance11;
            }
        }
 public BoardInjector()
 {
     dock = new Dock();
     DockPath = new LinkedList<MainTrack>();
     SavePath = new LinkedList<MainTrack>();
     SecondPath = new LinkedList<MainTrack>();
     ConSwitch = new ConvergingSwitch[5];
     for (int x = 0; x < ConSwitch.Length; x++)
     {
         ConSwitch[x] = new ConvergingSwitch();
     }
     DevSwitch = new DevergingSwitch[5];
     for (int x = 0; x < DevSwitch.Length; x++)
     {
         DevSwitch[x] = new DevergingSwitch();
     }
     Basis = new MainTrack[10];
     for (int x = 0; x < Basis.Length; x++)
     {
         Basis[x] = new MainTrack();
     }
     Warehouses = new Warehouse[3];
     for (int x = 0; x < Warehouses.Length; x++)
     {
         Warehouses[x] = new Warehouse();
     }
 }
Beispiel #3
0
 public static ProductData Prev(this ProductData phoneBook, Warehouse PB)
 {
     UsersContext db = PB.db;
     var orderedPhoneBook = db.Warehouse.OrderByDescending(pBook => pBook.ProductName).ThenByDescending(pBook => pBook.ProductName).ThenByDescending(pBook => pBook.Id);
     var orderedPhoneBookLower = orderedPhoneBook.Where(pBook => pBook.ProductName.CompareTo(phoneBook.ProductName) < 0 || ((pBook.ProductName.CompareTo(phoneBook.ProductName) == 0 && pBook.Model.CompareTo(phoneBook.Model) < 0)) || (pBook.ProductName.CompareTo(phoneBook.ProductName) == 0 && pBook.Model.CompareTo(phoneBook.Model) == 0 && pBook.Id < phoneBook.Id));
     return orderedPhoneBookLower.Take(1).FirstOrDefault();
 }
Beispiel #4
0
        public async Task ProcessLogFileAsync(ILeasedLogFile logFile)
        {
            if (logFile == null)
                return;

            try
            {
                var packageStatistics = await ParseLogEntries(logFile);

                if (packageStatistics.Any())
                {
                    // replicate data to the statistics database
                    var warehouse = new Warehouse(_jobEventSource, _targetDatabase);
                    var downloadFacts = await warehouse.CreateAsync(packageStatistics, logFile.Blob.Name);
                    await warehouse.InsertDownloadFactsAsync(downloadFacts, logFile.Blob.Name);
                }

                await ArchiveBlobAsync(logFile);

                // delete the blob from the 'to-be-processed' container
                await DeleteSourceBlobAsync(logFile);
            }
            catch (Exception e)
            {
                await _deadLetterContainer.CreateIfNotExistsAsync();

                // copy the blob to a dead-letter container
                await EnsureCopiedToContainerAsync(logFile, _deadLetterContainer, e);

                // delete the blob from the 'to-be-processed' container
                await DeleteSourceBlobAsync(logFile);
            }
        }
Beispiel #5
0
 public static ProductData Next(this ProductData phoneBook, Warehouse PB)
 {
     UsersContext db = PB.db;
     var orderedPhoneBook = db.Warehouse.OrderBy(pBook => pBook.ProductName).ThenBy(pBook => pBook.Model).ThenBy(pBook => pBook.Id);
     var orderedPhoneBookGreater = orderedPhoneBook.Where(pBook => pBook.ProductName.CompareTo(phoneBook.ProductName) > 0 || ((pBook.ProductName.CompareTo(phoneBook.ProductName) == 0 && pBook.Model.CompareTo(phoneBook.Model) > 0)) || (pBook.ProductName.CompareTo(phoneBook.ProductName) == 0 && pBook.Model.CompareTo(phoneBook.Model) == 0 && pBook.Id > phoneBook.Id));
     return orderedPhoneBookGreater.Take(1).FirstOrDefault();
 }
Beispiel #6
0
 public List<Widget> OrderManyParts(Warehouse wh, List<String> widgetsOrdered, List<SpecedWidget> specedWidgets)
 {
     var orderedWidgetsThatAreSpeced = specedWidgets.Where(w => widgetsOrdered.Contains(w.WidgetName)); //Widgets that we know we have the spec for.
     var orderedWidgetsThatAreNotSpeced = widgetsOrdered.Except(orderedWidgetsThatAreSpeced.Select(s => s.WidgetName)); //Widgets that we do not have the spec for.
     var widgetsAssembled = new List<Widget>();
     foreach (var widgetThatWeCantOrder in orderedWidgetsThatAreNotSpeced)//Display messages to let users know that we cannot fulfill their order on these items
     {
         Trace.WriteLine(String.Format("We currently do not produce widget {0}. Please resubmit your request for this item at a later date.", widgetThatWeCantOrder));
     }
     foreach (var widget in orderedWidgetsThatAreSpeced)
     {
         var w = new Widget();
         var assembled = true;
         foreach (var part in widget.Parts)
         {
             try
             {
                 for (var i = 0; i < part.NumberOfPart; i++)
                 {
                     w.Parts.Add(OrderOnePart(part.PartId, widget.WidgetName, wh));
                 }
             }
             catch (PartOrderException)
             {
                 Trace.WriteLine(String.Format("Ordering failed for part {0}, for widget {1}. This part does not exist in our system at the moment.", part.PartId, widget.WidgetName));
                 assembled = false;
             }
         }
         if (assembled)
             widgetsAssembled.Add(w);
     }
     return widgetsAssembled;
 }
        public static void Main()
        {
            var warehouse = new Warehouse<Equipment>();

            var equipment1 = warehouse.GetEquipment();
            equipment1.EmployeeName = "Atos";
            Console.WriteLine(
                "Equipment 1 ordered on {0:MM/dd/yyyy hh:mm:ss.fff tt} used by {1}",
                equipment1.OrderedAt,
                equipment1.EmployeeName);
            Thread.Sleep(2000);

            var equipment2 = warehouse.GetEquipment();
            equipment1.EmployeeName = "Portos";
            Console.WriteLine(
                "Equipment 2 ordered on {0:MM/dd/yyyy hh:mm:ss.fff tt} used by {1}",
                equipment2.OrderedAt,
                equipment1.EmployeeName);
            Thread.Sleep(2000);

            warehouse.ReleaseEquipment(equipment1);

            var equipment3 = warehouse.GetEquipment();
            equipment1.EmployeeName = "Aramis";
            Console.WriteLine(
                "Equipment 3 ordered on {0:MM/dd/yyyy hh:mm:ss.fff tt} used by {1}",
                equipment3.OrderedAt,
                equipment1.EmployeeName);
            Thread.Sleep(2000);
        }
    public void updateUI()
    {
        if(buildingTarget == null)
            buildingTarget = Warehouse.getInstance ();

        textLVL.text = buildingTarget.level.ToString ();
        textPV.text = buildingTarget.PV.ToString ();

        if( buildingTarget.upgradeLink != null && buildingTarget.upgradeLink.upgradeLevel.Count > 0){
            buttonUpgrade.SetActive(true);

            string upgradeText = "Upgrade\n" + "Cout :";

            foreach(RessourceInQuantity riq in buildingTarget.upgradeLink.upgradeLevel[0].cost ){
                upgradeText += " "+riq.quantity+" "+riq.ressourceName;
            }

            textUpgrade.text = upgradeText;
        }
        else{
            buttonUpgrade.SetActive(false);
        }

        woodQuantityText.text = buildingTarget.getRessourceQuantityInBase (GameRessources.Wood).ToString ();
        metalQuantityText.text = buildingTarget.getRessourceQuantityInBase (GameRessources.Metal).ToString ();
    }
Beispiel #9
0
        static void LotSerialRegister(TransactionType source, int reference, Warehouse warehouse,
		                               Product product, decimal quantity)
        {
            var query = from x in LotSerialRequirement.Queryable
                        where x.Source == source &&
                            x.Reference == reference &&
                            x.Warehouse.Id == warehouse.Id &&
                            x.Product == product
                        select x;
            var rqmt = query.SingleOrDefault ();

            if (rqmt != null) {
                rqmt.Quantity += quantity;
                rqmt.Update ();
            } else {
                rqmt = new LotSerialRequirement {
                    Source = source,
                    Reference = reference,
                    Warehouse = warehouse,
                    Product = product,
                    Quantity = quantity
                };

                rqmt.Create ();
            }
        }
Beispiel #10
0
 public static int GetRemainingStock(Item item, Warehouse warehouse)
 {
     using (var context = new ERPContext())
     {
         var stock = context.Stocks.SingleOrDefault(e => e.ItemID.Equals(item.ID) && e.WarehouseID.Equals(warehouse.ID));
         return stock?.Pieces ?? 0;
     }
 }
Beispiel #11
0
 public Board()
 {
     Switches = new Switch[5];
     Warehouses = new Warehouse[3];
     OccupiedTracks = new List<BaseTrack>();
     RandomGenerator = new Random();
     Ship = new Ship();
 }
Beispiel #12
0
 public ChoppingWoodState(ChristmasTree _resource, Warehouse _warehouse, GameObject transform)
 {
     tree = _resource;
     warehouse = _warehouse;
     resourceManger = ResourceManager.GetManager();
     currentGameObject = transform;
     gathering = true;
 }
 public void GetInfo()
 {
     Warehouse = new Warehouse()
     {
         Code = tb1.Text.Trim(),
         //Name = tb2.Text.Trim(),
         Address = tb3.Text.Trim()
     };
 }
        public void WarehouseStockRemovedWhenSufficientStockAvailableForOrder()
        {
            Order order = new Order("milk", 20);
            Warehouse warehouse = new Warehouse();
            warehouse.Add("milk", 50);

            order.Fill(warehouse);

            Assert.That(warehouse.GetInventory("milk"), Is.EqualTo(30));
        }
Beispiel #15
0
 public List<Widget> OrderWidgetsFromParsedOrderFile(string pathToFile, List<String> widgetsOrdered, List<SpecedWidget> specedWidgets)
 {
     var wh = new Warehouse();
     if (widgetsOrdered.Count > 0)
     {
         var assembledWidgets = OrderManyParts(wh, widgetsOrdered, specedWidgets);
         return assembledWidgets;
     }
     throw new NoWidgetsException(pathToFile);
 }
        static void Main(string[] args)
        {
            var gridSize = GetGridSize();
            var warehouse = new Warehouse(gridSize[0], gridSize[1]);

            var robotProgram = new RobotProgram();
            while (true)
            {
                robotProgram.Run(warehouse);
            }
        }
Beispiel #17
0
        private void addButton_Click(object sender, EventArgs e)
        {
            WMScontext context = new WMScontext();
            Warehouse warehouse = new Warehouse
            {
                Name = this.nameTB.Text,
                Address = this.addressTB.Text,
            };

            context.Warehouses.Add(warehouse);
            context.SaveChanges();
        }
Beispiel #18
0
        public ActionResult Create(Warehouse item)
        {
            if (!ModelState.IsValid)
                return PartialView ("_Create", item);

            item.Store = Store.Find (item.StoreId);

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return PartialView ("_CreateSuccesful", item);
        }
        public void testChemicalBoxCannotGoInANuclearRoom()
        {
            Room nuclearStorage = new Room(100, false, HazmatFlags.NUCLEAR);
            Box box1 = new Box("box1", 10, HazmatFlags.NONE);
            Box box2 = new Box("box2", 10, HazmatFlags.CHEMICAL);
            Box box3 = new Box("box3", 10, HazmatFlags.NONE);

            Warehouse testObject = new Warehouse(new Room[] { nuclearStorage });

            Box[] rejectedBoxes = testObject.addBoxes(new Box[] { box1, box2, box3 });

            Assert.That(nuclearStorage.boxes, Is.EquivalentTo(new Box[] { box1, box3 }));
            Assert.That(rejectedBoxes, Is.EquivalentTo(new Box[] { box2 }));
        }
Beispiel #20
0
 public Customer(Warehouse.Customer customer)
     : base()
 {
     _type = "Customers";
     this.FirstName = customer.FirstName;
     this.LastName = customer.LastName;
     this.AddressLine1 = customer.Address1;
     this.AddressLine2 = customer.Address2;
     this.CityName = customer.City;
     this.RegionName = customer.State;
     this.Postcode = customer.ZipCode;
     this.Email = customer.Email;
     this.Phone = customer.Phone;
 }
Beispiel #21
0
        static void KardexRegister(TransactionType source, int reference, DateTime dt,
		                            Warehouse warehouse, Product product, decimal quantity)
        {
            var item = new LotSerialTracking {
                Source = source,
                Reference = reference,
                Date = DateTime.Now,
                Warehouse = warehouse,
                Product = product,
                Quantity = quantity
            };

            item.Create ();
        }
Beispiel #22
0
        public static void ChangeNotification(TransactionType source, int reference, DateTime dt,
			Warehouse origin, Warehouse destination, Product product, decimal quantity)
        {
            if (!product.IsStockable)
                return;

            if (!(product.IsPerishable || product.IsSeriable)) {
                KardexRegister (source, reference, dt, origin, product, quantity);

                if (destination != null) {
                    KardexRegister (source, reference, dt, destination, product, -quantity);
                }
            } else {
                LotSerialRegister (source, reference, origin, product, quantity);
            }
        }
        public void testOrderForBoxesIsPreservedWhenThereIsEnoughRoom()
        {
            Room vault = new Room(150, false, HazmatFlags.CHEMICAL | HazmatFlags.NUCLEAR);
            Room mainStorage = new Room(1000, false, HazmatFlags.NONE);
            Box box1 = new Box("box1", 60, HazmatFlags.NONE);
            Box box2 = new Box("box2", 60, HazmatFlags.NONE);
            Box box3 = new Box("box3", 60, HazmatFlags.NONE);
            Box box4 = new Box("box4", 30, HazmatFlags.NONE);
            Box box5 = new Box("box5", 60, HazmatFlags.CHEMICAL);

            Warehouse testObject = new Warehouse(new Room[] { vault, mainStorage });

            Box[] rejectedBoxes = testObject.addBoxes(new Box[] { box1, box2, box3, box4, box5 });

            Assert.That(vault.boxes, Is.EquivalentTo(new Box[] { box1, box4, box5 }));
            Assert.That(mainStorage.boxes, Is.EquivalentTo(new Box[] { box2, box3 }));
            Assert.True(rejectedBoxes.Length == 0);
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            var warehouse = new Warehouse<Equipment>();

            var ringPlate = warehouse.GetEquipment();
            ringPlate.CakeName = "Cupcake";
            Console.WriteLine(
                "Ring plate ordered on {0:MM/dd/yyyy hh:mm:ss.fff tt} used for {1}",
                ringPlate.OrderedAt,
                ringPlate.CakeName);

            warehouse.ReleaseEquipment(ringPlate);
            ringPlate.CakeName = "Birthday cake";
            Console.WriteLine(
                "Ring plate ordered on {0:MM/dd/yyyy hh:mm:ss.fff tt} used for {1}",
                ringPlate.OrderedAt,
                ringPlate.CakeName);
        }
        public void testDifferentHazmatBoxesCanBeStoredInDifferentRoomsWhileStillRespectingSizeAndStairs()
        {
            Room loadingDock = new Room(100, false, HazmatFlags.NONE);
            Room chemLoft = new Room(100, true, HazmatFlags.CHEMICAL);
            Room vault = new Room(150, false, HazmatFlags.CHEMICAL | HazmatFlags.NUCLEAR);
            Box box1 = new Box("box1", 10, HazmatFlags.CHEMICAL);
            Box box2 = new Box("box2", 60, HazmatFlags.CHEMICAL);
            Box box3 = new Box("box3", 10, HazmatFlags.NUCLEAR);
            Box box4 = new Box("box4", 10, HazmatFlags.NUCLEAR | HazmatFlags.CHEMICAL);
            Box box5 = new Box("box5", 50, HazmatFlags.CHEMICAL);
            Box box6 = new Box("box6", 50, HazmatFlags.CHEMICAL);

            Warehouse testObject = new Warehouse(new Room[] { loadingDock, chemLoft, vault });

            Box[] rejectedBoxes = testObject.addBoxes(new Box[] { box1, box2, box3, box4, box5, box6 });

            Assert.IsEmpty(loadingDock.boxes);
            Assert.That(chemLoft.boxes, Is.EquivalentTo(new Box[] { box1, box5 }));
            Assert.That(vault.boxes, Is.EquivalentTo(new Box[] { box2, box3, box4, box6 }));
            Assert.True(rejectedBoxes.Length == 0);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Create(int? id)
        {
            Warehouse warehouse = new Warehouse();

            if (id != null)
            {
                warehouse = this.WarehouseService.FindById(id.Value);
            }

            if (this.Request.IsPost())
            {
                TryUpdateModel(warehouse, new[]{"Name", "Address"});
                if (ModelState.IsValid)
                {
                    this.WarehouseService.SaveOrUpdate(warehouse);
                    return View("Details", warehouse);
                }
            }

            return View(warehouse);
        }
        public static IList<GoodsInRouteListResult> GetEquipmentsInRL(IUnitOfWork uow, RouteList routeList, Warehouse warehouse = null)
        {
            GoodsInRouteListResult resultAlias = null;
            Vodovoz.Domain.Orders.Order orderAlias = null;
            OrderItem orderItemsAlias = null;
            OrderEquipment orderEquipmentAlias = null;
            Nomenclature OrderItemNomenclatureAlias = null, OrderEquipmentNomenclatureAlias = null;
            Equipment equipmentAlias = null;

            var ordersQuery = QueryOver.Of<Vodovoz.Domain.Orders.Order> (() => orderAlias);

            var routeListItemsSubQuery = QueryOver.Of<RouteListItem> ()
                .Where (r => r.RouteList.Id == routeList.Id)
                .Select (r => r.Order.Id);
            ordersQuery.WithSubquery.WhereProperty (o => o.Id).In (routeListItemsSubQuery).Select (o => o.Id);

            var orderitemsQuery = uow.Session.QueryOver<OrderItem>(() => orderItemsAlias)
                .WithSubquery.WhereProperty(i => i.Order.Id).In(ordersQuery)
                .JoinAlias(() => orderItemsAlias.Nomenclature, () => OrderItemNomenclatureAlias)
                .Where(() => !OrderItemNomenclatureAlias.Serial);
            if (warehouse != null)
                orderitemsQuery.Where(() => OrderItemNomenclatureAlias.Warehouse == warehouse);

            var orderEquipmentsQuery = uow.Session.QueryOver<OrderEquipment>(() => orderEquipmentAlias)
                .WithSubquery.WhereProperty(i => i.Order.Id).In(ordersQuery)
                .JoinAlias(() => orderEquipmentAlias.Equipment, () => equipmentAlias)
                .Where(() => orderEquipmentAlias.Direction == Direction.Deliver)
                .JoinAlias(() => equipmentAlias.Nomenclature, () => OrderEquipmentNomenclatureAlias);
            if (warehouse != null)
                orderEquipmentsQuery.Where(() => OrderEquipmentNomenclatureAlias.Warehouse == warehouse);

            return orderEquipmentsQuery
                .SelectList (list => list
                    .SelectGroup (() => OrderEquipmentNomenclatureAlias.Id).WithAlias (() => resultAlias.NomenclatureId)
                    .SelectGroup (() => equipmentAlias.Id).WithAlias (() => resultAlias.EquipmentId)
                    .SelectSum (() => 1).WithAlias (() => resultAlias.Amount)
                )
                .TransformUsing (Transformers.AliasToBean <GoodsInRouteListResult> ())
                .List<GoodsInRouteListResult> ();
        }
Beispiel #28
0
 private static Part OrderOnePart(string partId, string widgetName, Warehouse wh)
 {
     if (!wh.Available(partId))
     {
         wh.Order(partId);
     }
     var part = wh.Retreive(partId);
     Trace.WriteLine(String.Format("We have successfully ordered part {0}, with serial number {1}, for widget {2}", part.Id, part.SerialNo, widgetName));
     return part;
 }
 public static WarehouseViewModel MapToViewModel(Warehouse item)
 {
     return(new WarehouseViewModel(item));
 }
 public EntityStates GetWarehouseEntityState(Warehouse item)
 {
     return(WarehouseSingletonRepository.Instance.GetWarehouseEntityState(item));
 }
 public void AddToWarehouseRepository(Warehouse item)
 {
     WarehouseSingletonRepository.Instance.AddToRepository(item);
 }
 public string Insert(Warehouse entity)
 {
     this.Context.Warehouses.Add(entity);
     this.Commit();
     return(entity.Id.ToString());
 }
Beispiel #33
0
        /// <summary>
        /// Create shipment packages (requests) from shopping cart
        /// </summary>
        /// <param name="cart">Shopping cart</param>
        /// <param name="shippingAddress">Shipping address</param>
        /// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
        /// <param name="shippingFromMultipleLocations">Value indicating whether shipping is done from multiple locations (warehouses)</param>
        /// <returns>Shipment packages (requests)</returns>
        public virtual IList <GetShippingOptionRequest> CreateShippingOptionRequests(IList <ShoppingCartItem> cart,
                                                                                     Address shippingAddress, int storeId, out bool shippingFromMultipleLocations)
        {
            //if we always ship from the default shipping origin, then there's only one request
            //if we ship from warehouses ("ShippingSettings.UseWarehouseLocation" enabled),
            //then there could be several requests

            //key - warehouse identifier (0 - default shipping origin)
            //value - request
            var requests = new Dictionary <int, GetShippingOptionRequest>();

            //a list of requests with products which should be shipped separately
            var separateRequests = new List <GetShippingOptionRequest>();

            foreach (var sci in cart)
            {
                if (!IsShipEnabled(sci))
                {
                    continue;
                }

                var product = _productService.GetProductById(sci.ProductId);

                if (product == null || !product.IsShipEnabled)
                {
                    var associatedProducts = _productAttributeParser.ParseProductAttributeValues(sci.AttributesXml)
                                             .Where(attributeValue => attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct)
                                             .Select(attributeValue => _productService.GetProductById(attributeValue.AssociatedProductId));
                    product = associatedProducts.FirstOrDefault(associatedProduct => associatedProduct != null && associatedProduct.IsShipEnabled);
                }

                if (product == null)
                {
                    continue;
                }

                //warehouses
                Warehouse warehouse = null;
                if (_shippingSettings.UseWarehouseLocation)
                {
                    if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock &&
                        product.UseMultipleWarehouses)
                    {
                        var allWarehouses = new List <Warehouse>();
                        //multiple warehouses supported
                        foreach (var pwi in _productService.GetAllProductWarehouseInventoryRecords(product.Id))
                        {
                            var tmpWarehouse = GetWarehouseById(pwi.WarehouseId);
                            if (tmpWarehouse != null)
                            {
                                allWarehouses.Add(tmpWarehouse);
                            }
                        }

                        warehouse = GetNearestWarehouse(shippingAddress, allWarehouses);
                    }
                    else
                    {
                        //multiple warehouses are not supported
                        warehouse = GetWarehouseById(product.WarehouseId);
                    }
                }

                var warehouseId = warehouse?.Id ?? 0;

                if (requests.ContainsKey(warehouseId) && !product.ShipSeparately)
                {
                    //add item to existing request
                    requests[warehouseId].Items.Add(new GetShippingOptionRequest.PackageItem(sci, product));
                }
                else
                {
                    //create a new request
                    var request = new GetShippingOptionRequest
                    {
                        //store
                        StoreId = storeId
                    };
                    //customer
                    request.Customer = _customerService.GetShoppingCartCustomer(cart);

                    //ship to
                    request.ShippingAddress = shippingAddress;
                    //ship from
                    Address originAddress = null;
                    if (warehouse != null)
                    {
                        //warehouse address
                        originAddress         = _addressService.GetAddressById(warehouse.AddressId);
                        request.WarehouseFrom = warehouse;
                    }

                    if (originAddress == null)
                    {
                        //no warehouse address. in this case use the default shipping origin
                        originAddress = _addressService.GetAddressById(_shippingSettings.ShippingOriginAddressId);
                    }

                    if (originAddress != null)
                    {
                        request.CountryFrom       = _countryService.GetCountryByAddress(originAddress);
                        request.StateProvinceFrom = _stateProvinceService.GetStateProvinceByAddress(originAddress);
                        request.ZipPostalCodeFrom = originAddress.ZipPostalCode;
                        request.CountyFrom        = originAddress.County;
                        request.CityFrom          = originAddress.City;
                        request.AddressFrom       = originAddress.Address1;
                    }

                    //whether this product should be shipped separately from other ones
                    if (product.ShipSeparately)
                    {
                        //whether product items should be shipped separately
                        if (_shippingSettings.ShipSeparatelyOneItemEach)
                        {
                            //add item with overridden quantity 1
                            request.Items.Add(new GetShippingOptionRequest.PackageItem(sci, product, 1));

                            //create separate requests for all product quantity
                            for (var i = 0; i < sci.Quantity; i++)
                            {
                                separateRequests.Add(request);
                            }
                        }
                        else
                        {
                            //all of product items should be shipped in a single box, so create the single separate request
                            request.Items.Add(new GetShippingOptionRequest.PackageItem(sci, product));
                            separateRequests.Add(request);
                        }
                    }
                    else
                    {
                        //usual request
                        request.Items.Add(new GetShippingOptionRequest.PackageItem(sci, product));
                        requests.Add(warehouseId, request);
                    }
                }
            }

            //multiple locations?
            //currently we just compare warehouses
            //but we should also consider cases when several warehouses are located in the same address
            shippingFromMultipleLocations = requests.Select(x => x.Key).Distinct().Count() > 1;

            var result = requests.Values.ToList();

            result.AddRange(separateRequests);

            return(result);
        }
Beispiel #34
0
 public bool ValidUpdateObject(Warehouse warehouse, IWarehouseService _warehouseService)
 {
     warehouse.Errors.Clear();
     VUpdateObject(warehouse, _warehouseService);
     return(isValid(warehouse));
 }
Beispiel #35
0
        private static void InsertCatalogueEntities()
        {
            using (TransactionScope lScope = new TransactionScope())
                using (BookStoreEntityModelContainer lContainer = new BookStoreEntityModelContainer())
                {
                    if (lContainer.Books.Count() == 0)
                    {
                        Warehouse lNeutralBay = new Warehouse()
                        {
                            Name    = "Neutral Bay",
                            Address = "1 Neutral Bay"
                        };

                        Warehouse lTheWarehouse = new Warehouse()
                        {
                            Name    = "The Warehouse",
                            Address = "1 The Warehouse"
                        };

                        Warehouse lStorageKing = new Warehouse()
                        {
                            Name    = "Storage King",
                            Address = "1 Storage King"
                        };

                        Warehouse lAmazon = new Warehouse()
                        {
                            Name    = "Amazon",
                            Address = "1 Amazon St"
                        };

                        Book lGreatExpectations = new Book()
                        {
                            Author = "Anonymous",
                            Genre  = "Fiction",
                            Price  = 10.0,
                            Title  = "The Great Expectations",
                        };

                        Book lSoloist = new Book()
                        {
                            Author = "Charles Dickens",
                            Genre  = "Fiction",
                            Price  = 15.0,
                            Title  = "The Solo"
                        };

                        Book lMuhitAnik = new Book()
                        {
                            Author = "Muhit Anik",
                            Genre  = "Philosophy",
                            Price  = 20.0,
                            Title  = "The Journey of Muhit Anik",
                        };


                        Stock lGreatExpectationNeutralBayStock   = CreateStock(lGreatExpectations, lNeutralBay, 10);
                        Stock lGreatExpectationTheWarehouseStock = CreateStock(lGreatExpectations, lTheWarehouse, 0);
                        Stock lGreatExpectationStorageKingStock  = CreateStock(lGreatExpectations, lStorageKing, 0);
                        Stock lGreatExpectationAmazonStock       = CreateStock(lGreatExpectations, lAmazon, 10);

                        Stock lSoloistNeutralBayStock   = CreateStock(lSoloist, lNeutralBay, 0);
                        Stock lSoloistTheWarehouseStock = CreateStock(lSoloist, lTheWarehouse, 10);
                        Stock lSoloistStorageKingStock  = CreateStock(lSoloist, lStorageKing, 0);
                        Stock lSoloistAmazonStock       = CreateStock(lSoloist, lAmazon, 10);


                        Stock lNoBookNeutralBayStock   = CreateStock(lMuhitAnik, lNeutralBay, 0);
                        Stock lNoBookTheWarehouseStock = CreateStock(lMuhitAnik, lTheWarehouse, 0);
                        Stock lNoBookStorageKingStock  = CreateStock(lMuhitAnik, lStorageKing, 10);
                        Stock lNoBookAmazonStock       = CreateStock(lMuhitAnik, lAmazon, 10);

                        lContainer.Books.Add(lGreatExpectations);
                        lContainer.Books.Add(lSoloist);
                        lContainer.Books.Add(lMuhitAnik);

                        lContainer.Stocks.Add(lGreatExpectationNeutralBayStock);
                        lContainer.Stocks.Add(lGreatExpectationTheWarehouseStock);
                        lContainer.Stocks.Add(lGreatExpectationStorageKingStock);
                        lContainer.Stocks.Add(lGreatExpectationAmazonStock);

                        lContainer.Stocks.Add(lSoloistNeutralBayStock);
                        lContainer.Stocks.Add(lSoloistStorageKingStock);
                        lContainer.Stocks.Add(lSoloistTheWarehouseStock);
                        lContainer.Stocks.Add(lSoloistAmazonStock);

                        lContainer.Stocks.Add(lNoBookNeutralBayStock);
                        lContainer.Stocks.Add(lNoBookTheWarehouseStock);
                        lContainer.Stocks.Add(lNoBookStorageKingStock);
                        lContainer.Stocks.Add(lNoBookAmazonStock);

                        for (int i = 5; i < 31; i++)
                        {
                            Book lItem = new Book()
                            {
                                Author = String.Format("Author {0}", i.ToString()),
                                Genre  = String.Format("Genre {0}", i),
                                Price  = i,
                                Title  = String.Format("Title {0}", i)
                            };

                            lContainer.Books.Add(lItem);

                            Warehouse lWarehouse = new Warehouse()
                            {
                                Name    = String.Format("The Warehouse {0}", i),
                                Address = String.Format("Warehouse {0}'s palace", i)
                            };

                            Stock lStock = new Stock()
                            {
                                Book     = lItem,
                                Quantity = 10 + i,
                                // Warehouse = String.Format("Warehouse {0}", i)
                                Warehouse = lWarehouse
                            };

                            lContainer.Warehouses.Add(lWarehouse);
                            lContainer.Stocks.Add(lStock);
                        }

                        lContainer.SaveChanges();
                        lScope.Complete();
                    }
                }
        }
Beispiel #36
0
 public Warehouse VUpdateObject(Warehouse warehouse, IWarehouseService _warehouseService)
 {
     return(VCreateObject(warehouse, _warehouseService));
 }
Beispiel #37
0
 public bool ValidCreateObject(Warehouse warehouse, IWarehouseService _warehouseService)
 {
     VCreateObject(warehouse, _warehouseService);
     return(isValid(warehouse));
 }
Beispiel #38
0
 public Warehouse VCreateObject(Warehouse warehouse, IWarehouseService _warehouseService)
 {
     VHasUniqueCode(warehouse, _warehouseService);
     return(warehouse);
 }
Beispiel #39
0
        public void SaveWarehouseOutMain(Sender sender, SaveWarehouseOutMainArgs args)
        {
            try
            {
                using (ObjectProxy op = new ObjectProxy(true))
                {
                    WarehouseOutMain obj = new WarehouseOutMain();
                    obj.OutID = args.WarehouseOutMain.OutID;
                    if (op.LoadWarehouseOutMainByOutID(obj) == 0)
                    {
                        args.WarehouseOutMain.Created    = DateTime.Now;
                        args.WarehouseOutMain.CreatedBy  = string.Format("{0}.{1}", sender.UserCode, sender.UserName);
                        args.WarehouseOutMain.Modified   = DateTime.Now;
                        args.WarehouseOutMain.ModifiedBy = string.Format("{0}.{1}", sender.UserCode, sender.UserName);
                        op.InsertWarehouseOutMain(args.WarehouseOutMain);
                    }
                    else
                    {
                        args.WarehouseOutMain.Modified   = DateTime.Now;
                        args.WarehouseOutMain.ModifiedBy = string.Format("{0}.{1}", sender.UserCode, sender.UserName);
                        op.UpdateWarehouseOutMainByOutID(args.WarehouseOutMain);
                    }
                    if (args.WarehouseOutDetails != null)
                    {
                        //出库数量
                        foreach (WarehouseOutDetail item in args.WarehouseOutDetails)
                        {
                            WarehouseOutDetail subObj = new WarehouseOutDetail();
                            subObj.DetailID = item.DetailID;
                            if (op.LoadWarehouseOutDetailByDetailID(subObj) == 0)
                            {
                                op.InsertWarehouseOutDetail(item);
                            }
                            else
                            {
                                op.UpdateWarehouseOutDetailByDetailID(item);
                            }

                            //出库
                            Warehouse wh = new Warehouse();
                            wh.MaterialID = item.MaterialID;
                            wh.LocationID = item.LocationID;
                            if (op.LoadWarehouseByMaterialID_LocationID(wh) == 0)
                            {
                                wh            = new Warehouse();
                                wh.MaterialID = item.MaterialID;
                                wh.LocationID = item.LocationID;
                                wh.Qty        = -item.Qty;
                                wh.Price      = 0;
                                op.InsertWarehouse(wh);
                            }
                            else
                            {
                                wh.Qty -= item.Qty;
                                //如果为0,则删除
                                if (wh.Qty == 0)
                                {
                                    op.DeleteWarehouseByMaterialID_LocationID(item.MaterialID, item.LocationID);
                                }
                                else
                                {
                                    op.UpdateWarehouseByMaterialID_LocationID(wh);
                                }
                            }
                        }
                    }
                    op.CommitTransaction();
                }
            }
            catch (Exception ex)
            {
                PLogger.LogError(ex);
                throw ex;
            }
        }
Beispiel #40
0
 public bool ValidDeleteObject(Warehouse warehouse, IWarehouseItemService _warehouseItemService, ICoreIdentificationService _coreIdentificationService, IBarringOrderService _barringOrderService)
 {
     warehouse.Errors.Clear();
     VDeleteObject(warehouse, _warehouseItemService, _coreIdentificationService, _barringOrderService);
     return(isValid(warehouse));
 }
 public virtual void UpdateOperation(Warehouse warehouse)
 {
     if(Difference < 0)
     {
         WarehouseChangeOperation.WriteoffWarehouse = warehouse;
         WarehouseChangeOperation.IncomingWarehouse = null;
         WarehouseChangeOperation.Amount = Math.Abs(Difference);
     }
     if(Difference > 0)
     {
         WarehouseChangeOperation.WriteoffWarehouse = null;
         WarehouseChangeOperation.IncomingWarehouse = warehouse;
         WarehouseChangeOperation.Amount = Math.Abs(Difference);
     }
 }
Beispiel #42
0
        private void SelectedWarehouseLocation_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {//these properties are not to be persisted we will igore them...
            if (e.PropertyName == "IsSelected" ||
                e.PropertyName == "IsExpanded" ||
                e.PropertyName == "IsValid" ||
                e.PropertyName == "NotValidMessage" ||
                e.PropertyName == "LastModifiedBy" ||
                e.PropertyName == "LastModifiedByDate" ||
                e.PropertyName == "PlantID")
            {//WarehouseID and PlantID or set from the WarehouseLocation selection...
                return;
            }
            //Key ID Logic...
            if (e.PropertyName == "WarehouseLocationID")
            {//make sure it is has changed...
                if (SelectedWarehouseLocationMirror.WarehouseLocationID != SelectedWarehouseLocation.WarehouseLocationID)
                {
                    //if their are no records it is a key change
                    if (WarehouseLocationList != null && WarehouseLocationList.Count == 0 &&
                        SelectedWarehouseLocation != null && !string.IsNullOrEmpty(SelectedWarehouseLocation.WarehouseLocationID))
                    {
                        ChangeKeyLogic();
                        return;
                    }

                    EntityStates entityState = GetWarehouseLocationState(SelectedWarehouseLocation);

                    if (entityState == EntityStates.Unchanged ||
                        entityState == EntityStates.Modified)
                    {                             //once a key is added it can not be modified...
                        if (Dirty && AllowCommit) //dirty record exists ask if save is required...
                        {
                            NotifySaveRequired("Do you want to save changes?", _saveRequiredResultActions.ChangeKeyLogic);
                        }
                        else
                        {
                            ChangeKeyLogic();
                        }

                        return;
                    }
                }
            }//end KeyID logic...
            //2ndary key logic... when this key is selected we will populate it upstream keys...
            if (e.PropertyName == "WarehouseID" &&
                SelectedWarehouseLocationMirror.WarehouseID != SelectedWarehouseLocation.WarehouseID)
            {
                //look up WarehouseLocation to fetch its upstream properties...
                Warehouse item = WarehouseList.Where(q => q.WarehouseID == SelectedWarehouseLocation.WarehouseID).FirstOrDefault();
                SelectedWarehouseLocation.PlantID = item.PlantID;
            }

            object propertyChangedValue = SelectedWarehouseLocation.GetPropertyValue(e.PropertyName);
            object prevPropertyValue    = SelectedWarehouseLocationMirror.GetPropertyValue(e.PropertyName);
            string propertyType         = SelectedWarehouseLocation.GetPropertyType(e.PropertyName);
            //in some instances the value is not really changing but yet it still is tripping property change..
            //This will ensure that the field has physically been modified...
            //As well when we revert back it constitutes a property change but they will be = and it will bypass the logic...
            bool objectsAreEqual;

            if (propertyChangedValue == null)
            {
                if (prevPropertyValue == null)//both values are null
                {
                    objectsAreEqual = true;
                }
                else//only one value is null
                {
                    objectsAreEqual = false;
                }
            }
            else
            {
                if (prevPropertyValue == null)//only one value is null
                {
                    objectsAreEqual = false;
                }
                else //both values are not null use .Equals...
                {
                    objectsAreEqual = propertyChangedValue.Equals(prevPropertyValue);
                }
            }
            if (!objectsAreEqual)
            {
                //Here we do property change validation if false is returned we will reset the value
                //Back to its mirrored value and return out of the property change w/o updating the repository...
                if (WarehouseLocationPropertyChangeIsValid(e.PropertyName, propertyChangedValue, prevPropertyValue, propertyType))
                {
                    Update(SelectedWarehouseLocation);
                    //set the mirrored objects field...
                    SelectedWarehouseLocationMirror.SetPropertyValue(e.PropertyName, propertyChangedValue);
                    SelectedWarehouseLocationMirror.IsValid         = SelectedWarehouseLocation.IsValid;
                    SelectedWarehouseLocationMirror.IsExpanded      = SelectedWarehouseLocation.IsExpanded;
                    SelectedWarehouseLocationMirror.NotValidMessage = SelectedWarehouseLocation.NotValidMessage;
                }
                else
                {
                    SelectedWarehouseLocation.SetPropertyValue(e.PropertyName, prevPropertyValue);
                    SelectedWarehouseLocation.IsValid         = SelectedWarehouseLocationMirror.IsValid;
                    SelectedWarehouseLocation.IsExpanded      = SelectedWarehouseLocationMirror.IsExpanded;
                    SelectedWarehouseLocation.NotValidMessage = SelectedWarehouseLocationMirror.NotValidMessage;
                }
            }
        }
Beispiel #43
0
        private void Perform()
        {
            Warehouse.db.Refresh(RefreshMode.StoreWins, Warehouse.db.Tournament);
            var _activeTournaments = Warehouse.GetActiveTournaments();

            if (_activeTournaments.Any())            //Проверка, есть ли запущенные турниры
            {
                foreach (Storage.Tournament t in _activeTournaments)
                {
                    var stage = Warehouse.GetTournamentStages(t.Tournament_ID).FirstOrDefault();                     // TODO: adjust for multiple stages
                    if (stage == null)
                    {
                        continue;
                    }
                    if (t.State_Code == (int)State.NotStarted && t.StartTime < DateTime.UtcNow || t.State_Code == (int)State.Started)
                    {
                        if (t.Player.Count < 2)
                        {
                            Warehouse.UpdateTournament(t.Tournament_ID, State.Finished);
                        }
                        else
                        {
                            if (t.State_Code == (int)State.NotStarted)
                            {
                                Warehouse.UpdateTournament(t.Tournament_ID, State.Started);
                            }
                            var games = Warehouse.GetListOfStageGames(stage.Stage_ID);
                            if (games.Any())
                            {
                                if (games.All(x => Warehouse.DoesMatchHasResult(x.Game_ID)))
                                {
                                    var scores = t.Player.ToDictionary(x => x.Account_ID, x => 0);
                                    // Считает очки, определяет победителей, формирует отчётность, завершает турнир.
                                    foreach (Game g in games)
                                    {
                                        // Добавляет очко победителю
                                        var replay = Warehouse.GetReplay(g.Game_ID);

                                        if (replay.Data.WinnerTeam != Guid.Empty)
                                        {
                                            var winner =
                                                g.Teams.First(x => x.Team_ID == replay.Data.WinnerTeam).Intellects.First
                                                    ().
                                                Account;

                                            scores[winner.Account_ID] += 1;
                                        }
                                    }

                                    foreach (var score in scores)
                                    {
                                        Warehouse.AddScore(stage, t.Player.First(x => x.Account_ID == score.Key),
                                                           score.Value);
                                    }

                                    //Публикует очки в базу, сортирует по очкам
                                    //Определяет победителей турнира, формирует отчёт
                                    // проверять все стейджЫ
                                    Warehouse.UpdateTournament(t.Tournament_ID, State.Finished);
                                }
                            }
                            else
                            {
                                var ints = stage.Intellects.ToList();
                                for (int i1 = 0; i1 < ints.Count; i1++)
                                {
                                    for (int i2 = i1 + 1; i2 < ints.Count; i2++)
                                    {
                                        var _intList = new List <Guid>();
                                        _intList.Add(ints[i1].Intellect_ID);
                                        _intList.Add(ints[i2].Intellect_ID);
                                        // todo: запускать больше 1 матча
                                        Warehouse.BeginMatch(_intList, t.Creator_ID,
                                                             string.Format("{0}: {1} vs. {2}", t.Tournament_Name,
                                                                           ints[i1].Intellect_Name, ints[i2].Intellect_Name),
                                                             stage.Stage_ID);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #44
0
        private bool ShouldKeep(PeriodicConsumptionItem periodicConsumptionItem, IEnumerable <InventoryItem> inventoryItems, Warehouse warehouse)
        {
            var wname         = warehouse.Name;
            var inventoryItem = inventoryItems.Single(y => y.Id == periodicConsumptionItem.InventoryItemId);

            return(inventoryItem.IsMappedToWarehouse(wname));
        }
 public void Add(Warehouse obj)
 {
     dataBase.Warehouses.Add(obj);
     Update();
 }
Beispiel #46
0
        public Parcel TrackParcel(string trackingId)
        {
            try
            {
                logger.LogInformation($"getting parcel {trackingId} from repo");
                Data.Parcel dataParcel     = parcelRepository.GetByTrackingId(trackingId);
                Parcel      businessParcel = this.mapper.Map <Parcel>(dataParcel);

                string senderGeoString    = businessParcel.Sender.ToGeoCodingString();
                string recipientGeoString = businessParcel.Recipient.ToGeoCodingString();
                logger.LogDebug($"converting sender geoCodingString '{senderGeoString}' to Location");
                logger.LogDebug($"converting recepient geoCodingString '{recipientGeoString}' to Location");

                Geocoding.Location senderAddress    = geoCodingAgent.EncodeAddress(senderGeoString);
                Geocoding.Location recipientAddress = geoCodingAgent.EncodeAddress(recipientGeoString);

                Data.Hop dataSenderHop;
                Data.Hop dataRecipientHop;
                try
                {
                    dataSenderHop    = hopRepository.GetByCoordinates(senderAddress.Latitude, senderAddress.Longitude);
                    dataRecipientHop = hopRepository.GetByCoordinates(recipientAddress.Latitude, recipientAddress.Longitude);
                }
                catch (DataAccessLayerException e)
                {
                    throw new BusinessLayerException("DAL Exception", e);
                }

                Data.Warehouse dataWarehouse;
                try
                {
                    logger.LogDebug("load full warehouse hierarchy");
                    dataWarehouse = wareHouseRepository.Read();
                }
                catch (DataAccessLayerException e)
                {
                    throw new BusinessLayerException("DAL Exception", e);
                }

                Hop       senderHop    = this.mapper.Map <Hop>(dataSenderHop);
                Hop       recipientHop = this.mapper.Map <Hop>(dataRecipientHop);
                Warehouse warehouse    = this.mapper.Map <Warehouse>(dataWarehouse);

                logger.LogDebug($"calculating route betweend sender {senderHop.Code} and recipeint {recipientHop.Code}");
                List <HopArrival> route = routeCalculator.CalculateRoute(warehouse, senderHop.Code, recipientHop.Code, businessParcel.EntryDate);

                //route    Datetime now
                List <HopArrival> soonHop = new List <HopArrival>();
                List <HopArrival> pastHop = new List <HopArrival>();
                foreach (HopArrival ha in route)
                {
                    if (ha.DateTime < DateTime.Now)
                    {
                        // beide listen befüllen
                        pastHop.Add(ha);

                        /*
                         *      try
                         *      {
                         *
                         *          logger.LogInformation($"updating parcel {trackingId}");
                         *          parcelRepository.Update(this.mapper.Map<Data.Parcel>(businessParcel));
                         *          List<Data.Webhook> dataWebhooks = webhookRepository.GetByTrackingId(trackingId);
                         *          List<Webhook> webhooks = new List<Webhook>();
                         *          dataWebhooks.ForEach(hook => webhooks.Add(this.mapper.Map<Webhook>(hook)));
                         *          NotifyAllSubscribers(webhooks);
                         *
                         *      }
                         *      catch (DataAccessLayerException e)
                         *      {
                         *          throw new BusinessLayerException("DAL Exception", e);
                         *      }
                         */
                    }
                    else
                    {
                        soonHop.Add(ha);
                    }
                }
                businessParcel.VisitedHops = pastHop;
                businessParcel.FutureHops  = soonHop;

                return(businessParcel);
            }
            catch (DataAccessLayerException e)
            {
                throw new BusinessLayerException();
            }
        }
Beispiel #47
0
        /// <summary>
        /// Create shipment packages (requests) from shopping cart
        /// </summary>
        /// <param name="cart">Shopping cart</param>
        /// <param name="shippingAddress">Shipping address</param>
        /// <param name="storeId">Load records allowed only in a specified store; pass "" to load all records</param>
        /// <param name="shippingFromMultipleLocations">Value indicating whether shipping is done from multiple locations (warehouses)</param>
        /// <returns>Shipment packages (requests)</returns>
        public virtual async Task <(IList <GetShippingOptionRequest> shippingOptionRequest, bool shippingFromMultipleLocations)> CreateShippingOptionRequests(Customer customer,
                                                                                                                                                              IList <ShoppingCartItem> cart, Address shippingAddress, Store store)
        {
            //if we always ship from the default shipping origin, then there's only one request
            //if we ship from warehouses ("ShippingSettings.UseWarehouseLocation" enabled),
            //then there could be several requests


            //key - warehouse identifier (0 - default shipping origin)
            //value - request
            var requests = new Dictionary <string, GetShippingOptionRequest>();

            //a list of requests with products which should be shipped separately
            var separateRequests = new List <GetShippingOptionRequest>();

            foreach (var sci in cart)
            {
                if (!sci.IsShipEnabled)
                {
                    continue;
                }

                var product = await _productService.GetProductById(sci.ProductId);

                //warehouses
                Warehouse warehouse = null;
                if (_shippingSettings.UseWarehouseLocation)
                {
                    if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock &&
                        product.UseMultipleWarehouses)
                    {
                        var allWarehouses = new List <Warehouse>();
                        //multiple warehouses supported
                        foreach (var pwi in product.ProductWarehouseInventory)
                        {
                            //TODO validate stock quantity when backorder is not allowed?
                            var tmpWarehouse = await GetWarehouseById(pwi.WarehouseId);

                            if (tmpWarehouse != null)
                            {
                                allWarehouses.Add(tmpWarehouse);
                            }
                        }
                        warehouse = await GetNearestWarehouse(shippingAddress, allWarehouses);
                    }
                    else
                    {
                        //multiple warehouses are not supported
                        warehouse = await GetWarehouseById(product.WarehouseId);
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(sci.WarehouseId))
                    {
                        warehouse = await GetWarehouseById(sci.WarehouseId);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(store?.DefaultWarehouseId))
                        {
                            warehouse = await GetWarehouseById(store.DefaultWarehouseId);
                        }
                    }
                }

                string warehouseId = warehouse != null ? warehouse.Id : "";

                if (requests.ContainsKey(warehouseId) && !product.ShipSeparately)
                {
                    //add item to existing request
                    requests[warehouseId].Items.Add(new GetShippingOptionRequest.PackageItem(sci));
                }
                else
                {
                    //create a new request
                    var request = new GetShippingOptionRequest();
                    //store
                    request.StoreId = store?.Id;
                    //add item
                    request.Items.Add(new GetShippingOptionRequest.PackageItem(sci));
                    //ship to
                    request.ShippingAddress = shippingAddress;
                    //ship from
                    Address originAddress = null;
                    if (warehouse != null)
                    {
                        //warehouse address
                        originAddress = await _addressService.GetAddressByIdSettings(warehouse.AddressId);

                        request.WarehouseFrom = warehouse;
                    }
                    if (originAddress == null)
                    {
                        //no warehouse address. in this case use the default shipping origin
                        originAddress = (await _addressService.GetAddressByIdSettings(_shippingSettings.ShippingOriginAddressId));
                    }
                    if (originAddress != null)
                    {
                        var country = await _countryService.GetCountryById(originAddress.CountryId);

                        var state = await _stateProvinceService.GetStateProvinceById(originAddress.StateProvinceId);

                        request.CountryFrom       = country;
                        request.StateProvinceFrom = state;
                        request.ZipPostalCodeFrom = originAddress.ZipPostalCode;
                        request.CityFrom          = originAddress.City;
                        request.AddressFrom       = originAddress.Address1;
                    }

                    if (product.ShipSeparately)
                    {
                        //ship separately
                        separateRequests.Add(request);
                    }
                    else
                    {
                        //usual request
                        requests.Add(warehouseId, request);
                    }
                }
            }

            //multiple locations?
            //currently we just compare warehouses
            //but we should also consider cases when several warehouses are located in the same address
            bool shippingFromMultipleLocations = requests.Select(x => x.Key).Distinct().Count() > 1;

            var result = requests.Values.ToList();

            result.AddRange(separateRequests);

            return(result, shippingFromMultipleLocations);
        }
Beispiel #48
0
        public static SimulationSystem SetupMockedWarehouseForPresentation()
        {
            var simulationSystem = new SimulationSystem();

            // Add a thread and a simulation engine to the simulation framework
            simulationSystem.AddSimulationThread(new SimulationThread(new SimulationEngine[] { new EmployeeMovementEngine() }.ToList()));
            simulationSystem.AddSimulationThread(new SimulationThread(new SimulationEngine[] { new RandomPickingTourGenerator() }.ToList()));
            simulationSystem.AddSimulationThread(new SimulationThread(new SimulationEngine[] { new EmployeeAdjustmentEngine() }.ToList()));
            simulationSystem.AddSimulationThread(new SimulationThread(new SimulationEngine[] { new PickingEngine() }.ToList()));

            var warehouse = new Warehouse();
            var employee1 = new Employee
            {
                Speed           = 5F, // change this?
                CurrentLocation = new Vector3(0, 0, 0),
                Status          = Employee.EmployeeStatus.Traveling,
            };

            var employee2 = new Employee
            {
                Speed           = 5F, // change this?
                CurrentLocation = new Vector3(0, 0, 0),
                Status          = Employee.EmployeeStatus.Traveling,
            };

            warehouse.Objects.Add(employee1);
            warehouse.Objects.Add(employee2);

            // Generate warehouseCompartments
            for (var i = 0; i < 17; i++)
            {
                for (var j = 0; j < 12; j++)
                {
                    if (i != 8)
                    {
                        for (var k = 0; k < 5; k++)
                        {
                            var warehouseCompartment = new WarehouseCompartment
                            {
                                Location = new Vector3(i + 2, j + 2, k),
                            };
                            var ips = new ItemProductStatic
                            {
                                Name = $"MuchAwesomeIps{i}-{j}-{k}",
                                WarehouseCompartment = warehouseCompartment,
                            };
                            warehouseCompartment.Objects.Add(ips);
                            warehouse.Objects.Add(warehouseCompartment);
                        }
                    }
                }
            }

            // Generate some trolleys
            for (var i = 0; i < 100; i++)
            {
                warehouse.Objects.Add(new Trolley());
            }

            simulationSystem.World.Objects.Add(warehouse);

            return(simulationSystem);
        }
Beispiel #49
0
        public void Deletion_ExpenseEmployeeDocumentTest()
        {
            NewSessionWithSameDB();
            var ask = Substitute.For <IInteractiveQuestion>();

            ask.Question(string.Empty).ReturnsForAnyArgs(true);
            var navigation = Substitute.For <INavigationManager>();

            using (var uow = UnitOfWorkFactory.CreateWithoutRoot()) {
                var warehouse = new Warehouse();
                uow.Save(warehouse);

                var nomenclatureType = new ItemsType {
                    Name = "Тестовый тип номенклатуры"
                };
                uow.Save(nomenclatureType);

                var nomenclature = new Nomenclature {
                    Type = nomenclatureType
                };
                uow.Save(nomenclature);

                var position1 = new StockPosition(nomenclature, 0, null, null);

                var nomenclature2 = new Nomenclature {
                    Type = nomenclatureType
                };
                uow.Save(nomenclature2);

                var position2 = new StockPosition(nomenclature2, 0, null, null);

                var protectionTools = new ProtectionTools {
                    Name = "СИЗ для тестирования"
                };
                protectionTools.AddNomeclature(nomenclature);
                uow.Save(protectionTools);

                var protectionTools2 = new ProtectionTools {
                    Name = "СИЗ для тестирования 2"
                };
                protectionTools2.AddNomeclature(nomenclature2);
                uow.Save(protectionTools2);

                var norm     = new Norm();
                var normItem = norm.AddItem(protectionTools);
                normItem.Amount      = 1;
                normItem.NormPeriod  = NormPeriodType.Year;
                normItem.PeriodCount = 1;
                var normItem2 = norm.AddItem(protectionTools2);
                normItem2.Amount      = 1;
                normItem2.NormPeriod  = NormPeriodType.Month;
                normItem2.PeriodCount = 1;
                uow.Save(norm);

                var employee = new EmployeeCard();
                employee.AddUsedNorm(norm);
                uow.Save(employee);
                uow.Commit();

                var income = new Income {
                    Warehouse = warehouse,
                    Date      = new DateTime(2017, 1, 1),
                    Operation = IncomeOperations.Enter
                };
                var incomeItem1 = income.AddItem(nomenclature);
                incomeItem1.Amount = 10;
                var incomeItem2 = income.AddItem(nomenclature2);
                incomeItem2.Amount = 5;
                income.UpdateOperations(uow, ask);
                uow.Save(income);

                var expense = new Expense {
                    Operation = ExpenseOperations.Employee,
                    Warehouse = warehouse,
                    Employee  = employee,
                    Date      = new DateTime(2018, 10, 22)
                };
                expense.AddItem(position1, 1);
                expense.AddItem(position2, 1);

                var baseParameters = Substitute.For <BaseParameters>();
                baseParameters.ColDayAheadOfShedule.Returns(0);

                expense.CreateIssuanceSheet(null);

                //Обновление операций
                expense.UpdateOperations(uow, baseParameters, ask);
                uow.Save(expense);
                uow.Save(expense.IssuanceSheet);
                uow.Commit();

                expense.UpdateEmployeeWearItems();
                uow.Commit();

                var docs = uow.GetAll <Expense>().ToList();
                Assert.That(docs.Count, Is.EqualTo(1));

                //Непосредственно удаление документа
                var cancel = new CancellationTokenSource();
                using (var uowDel = UnitOfWorkFactory.CreateWithoutRoot()) {
                    var deletionService = new DeleteCore(DeleteConfig.Main, uowDel);
                    deletionService.PrepareDeletion(typeof(Expense), expense.Id, cancel.Token);
                    Assert.That(deletionService.TotalLinks, Is.GreaterThan(0));
                    deletionService.RunDeletion(cancel.Token);
                }

                //Проверяем удаление
                var expenseId = expense.Id;
                using (var uowCheck = UnitOfWorkFactory.CreateWithoutRoot()) {
                    //Проверяем что удалили документ.
                    docs = uow.GetAll <Expense>().ToList();
                    Assert.That(docs.Count, Is.Zero);

                    //Проверяем что случайно не удалили СИЗ и номеклатуру.
                    var protections = uow.GetAll <ProtectionTools>().ToList();
                    Assert.That(protections.Count, Is.EqualTo(2));
                    var nomenclatures = uow.GetAll <Nomenclature>().ToList();
                    Assert.That(nomenclatures.Count, Is.EqualTo(2));
                }
            }
        }
Beispiel #50
0
        public void Move(UInt32 material, ConveyorBasic source, ConveyorBasic target)
        {
            // for input points
            try
            {
                if (source == target)
                {
                    return;
                }

                if (source == null)
                {
                    throw new ConveyorBasicException(String.Format("ConveyorBasic.Move source is null ({0}).", source.Name));
                }

                if (target == null)
                {
                    throw new ConveyorBasicException(String.Format("ConveyorBasic.Move target is null ({0}).", source.Name));
                }

                if (source.Place == null)
                {
                    throw new ConveyorBasicException(String.Format("ConveyorBasic.Move source({0}) is empty.", source.Name));
                }

                if (target.Place != null)
                {
                    throw new ConveyorBasicException(String.Format("ConveyorBasic.Move target ({0}) is not empty.", target.Name));
                }

                if (source.Place.Material != material)
                {
                    throw new ConveyorBasicException(String.Format("ConveyorBasic.Move wrong pallet ({0}!={1}) at source ({2}).", material, source.Place.Material, source.Name));
                }

                if (target is Conveyor && source is Conveyor)
                {
                    (target as Conveyor).Command = (source as Conveyor).Command;
                    (source as Conveyor).Command = null;
                }
                target.Place        = source.Place;
                target.Place.Place1 = Name;
                source.Place        = null;

                if (source is ConveyorJunction)
                {
                    (source as ConveyorJunction).ActiveRoute    = null;
                    (source as ConveyorJunction).ActiveMaterial = null;
                }
                if (target is ConveyorJunction)
                {
                    (target as ConveyorJunction).ActiveRoute    = null;
                    (target as ConveyorJunction).ActiveMaterial = null;
                }

                //                Warehouse.DBService.MaterialMove((int) material, source.Name, target.Name);
                Place ps = Warehouse.DBService.FindPlace(source.Name);
                Place pt = Warehouse.DBService.FindPlace(target.Name);
                if (target.WriteToDB == WriteToDB.Never)
                {
                    if (source.WriteToDB == WriteToDB.Always || (source.WriteToDB == WriteToDB.Try && ps != null))
                    {
                        Warehouse.DBService.MaterialDelete(source.Name, (int)material);
                    }
                }
                else if (target.WriteToDB == WriteToDB.Always || (target.WriteToDB == WriteToDB.Try && pt == null))
                {
                    if (source.WriteToDB == WriteToDB.Always || (source.WriteToDB == WriteToDB.Try && ps != null))
                    {
                        Warehouse.DBService.MaterialMove((int)material, source.Name, target.Name);
                    }
                    else
                    {
                        Warehouse.DBService.MaterialCreate(target.Name, (int)material, true);
                    }
                }

                Warehouse.OnMaterialMove?.Invoke(new Place {
                    Place1 = target.Name, Material = (int)material
                }, EnumMovementTask.Move);

                // add force UI notify
                source.DirectVMNotify();
                target.DirectVMNotify();
            }
            catch (Exception ex)
            {
                Warehouse.AddEvent(Event.EnumSeverity.Error, Event.EnumType.Exception, ex.Message);
                throw new ConveyorBasicException(String.Format("{0} ConveyorBasic.Move fault ({1},{2},{3}).", Name, material, source != null ? source.Name : "null", target != null ? target.Name : "null"));
            }
        }
 public void DeleteFromWarehouseRepository(Warehouse item)
 {
     WarehouseSingletonRepository.Instance.DeleteFromRepository(item);
 }
Beispiel #52
0
 public void OnSimpleCommandFinish(SimpleCommand cmd)
 {
     try
     {
         // automatic mode
         if (cmd.Command_ID.HasValue)
         {
             Command Command = Warehouse.DBService.FindCommandByID(cmd.Command_ID.Value);
             if (Command == null)
             {
                 throw new ConveyorBasicException(String.Format("{0} has no corresponding Command", cmd != null ? cmd.ToString() : "null"));
             }
             if (Command.Task == Database.Command.EnumCommandTask.Move)
             {
                 Place p = Warehouse.DBService.FindMaterial((Command as CommandMaterial).Material.Value);
                 if (p != null && p.Place1 == (Command as CommandMaterial).Target)
                 {
                     Command.Status = Database.Command.EnumCommandStatus.Finished;
                     Warehouse.DBService.UpdateCommand(Command);
                     Warehouse.OnCommandFinish?.Invoke(Command);
                 }
                 else
                 {
                     Conveyor conv = Warehouse.ConveyorList.FirstOrDefault(c => c.Name == (Command as CommandMaterial).Target);
                     if (conv != null && conv is ConveyorOutputDefault)
                     {
                         Command.Status = Database.Command.EnumCommandStatus.Finished;
                         Warehouse.DBService.UpdateCommand(Command);
                         Warehouse.OnCommandFinish?.Invoke(Command);
                     }
                 }
             }
             else if (cmd.Status == SimpleCommand.EnumStatus.Finished && Warehouse.DBService.AllSimpleCommandWithCommandIDFinished(cmd.Command_ID.Value))
             {
                 Command.Status = Database.Command.EnumCommandStatus.Finished;
                 Warehouse.DBService.UpdateCommand(Command);
                 Warehouse.OnCommandFinish?.Invoke(Command);
             }
             else if (cmd.Status == SimpleCommand.EnumStatus.Canceled &&
                      (cmd.Task == SimpleCommand.EnumTask.Create || cmd.Task == SimpleCommand.EnumTask.Delete ||
                       (cmd.Task == SimpleCommand.EnumTask.Move && Command.Task == Command.EnumCommandTask.SegmentHome)))
             {
                 if ((int)cmd.Reason > 100)
                 {
                     Command.Reason = Command.EnumCommandReason.PLC;
                 }
                 else
                 {
                     Command.Reason = Command.EnumCommandReason.MFCS;
                 }
                 Command.Status = Database.Command.EnumCommandStatus.Canceled;
                 Warehouse.DBService.UpdateCommand(Command);
                 Warehouse.OnCommandFinish?.Invoke(Command);
             }
         }
     }
     catch (Exception ex)
     {
         Warehouse.AddEvent(Event.EnumSeverity.Error, Event.EnumType.Exception, ex.Message);
         throw new ConveyorBasicException(String.Format("{0} ConveyorBasic.OnSimpleCommandFinish ({1}) fault.", Name, cmd != null ? cmd.ToString() : "null"));
     }
 }
 public void UpdateWarehouseRepository(Warehouse item)
 {
     WarehouseSingletonRepository.Instance.UpdateRepository(item);
 }
Beispiel #54
0
 public void Upd(Warehouse entity)
 {
     entity.LineId     = _unitWork.FindSingle <Line>(u => u.LineCode.Equals(entity.LineCode)).Id;
     entity.WorkshopId = _unitWork.FindSingle <Workshop>(u => u.Code.Equals(entity.WorkshopCode)).Id;
     _app.Update(entity);
 }
 public IEnumerable <Warehouse> GetWarehouses(Warehouse itemQuerryObject, string companyID)
 {
     return(WarehouseSingletonRepository.Instance.GetWarehouses(itemQuerryObject, companyID));
 }
Beispiel #56
0
 public TableData Load(PageReq pageRequest, Warehouse entity)
 {
     return(_app.Load(pageRequest, entity));
 }
 public virtual void CreateOperation(Warehouse warehouse, DateTime time)
 {
     if(Difference < 0)
     {
         WarehouseChangeOperation = new WarehouseMovementOperation
             {
                 WriteoffWarehouse = warehouse,
                 Amount = Math.Abs(Difference),
                 OperationTime = time,
                 Nomenclature = Nomenclature
             };
     }
     if(Difference > 0)
     {
         WarehouseChangeOperation = new WarehouseMovementOperation
             {
                 IncomingWarehouse = warehouse,
                 Amount = Math.Abs(Difference),
                 OperationTime = time,
                 Nomenclature = Nomenclature
             };
     }
 }
Beispiel #58
0
 public TableData ExportData(Warehouse entity)
 {
     return(_app.ExportData(entity));
 }
Beispiel #59
0
        public bool isValid(Warehouse obj)
        {
            bool isValid = !obj.Errors.Any();

            return(isValid);
        }
 /// <summary>
 /// Valida si existe el nuevo item
 /// </summary>
 /// <param name="description"></param>
 /// <param name="warehouse"></param>
 /// <returns></returns>
 private bool HallwayExists(string description, Warehouse warehouse)
 {
     return(_context.Hallways.Any(e => e.Description == description && e.Warehouse.Id == warehouse.Id));
 }