Пример #1
0
        public void CountItem(string locatorId, string productId, IDictionary <string, object> attributeSetInstance, decimal countedQuantity, long version, string commandId, string requesterId)
        {
            string attributeSetInstanceId = attributeSetInstance["attributeSetInstanceId"] as string;

            if (String.IsNullOrWhiteSpace(attributeSetInstanceId))
            {
                //todo
            }
            var notNullAttrSetInstId = String.IsNullOrEmpty(attributeSetInstanceId)
                ? InventoryItemIds.EmptyAttributeSetInstanceId : attributeSetInstanceId;
            var inventoryItemId = new InventoryItemId(productId, locatorId, notNullAttrSetInstId);
            var lineState       = State.PhysicalInventoryLines.Get(inventoryItemId, false, true);

            var e = NewPhysicalInventoryStateMergePatched(version, commandId, requesterId);

            if (lineState != null)
            {
                var lineE = e.NewPhysicalInventoryLineStateMergePatched(inventoryItemId);
                lineE.CountedQuantity = countedQuantity;
                e.AddPhysicalInventoryLineEvent(lineE);
                Apply(e);
            }
            else
            {
                var lineE = e.NewPhysicalInventoryLineStateCreated(inventoryItemId);
                lineE.CountedQuantity = countedQuantity;
                lineE.BookQuantity    = 0;
                e.AddPhysicalInventoryLineEvent(lineE);
                Apply(e);
            }
        }
        public override EventStream LoadEventStream(Type eventType, IEventStoreAggregateId eventStoreAggregateId, long version)
        {
            Type supportedEventType = typeof(InventoryItemEventBase);

            if (!eventType.IsAssignableFrom(supportedEventType))
            {
                throw new NotSupportedException();
            }
            InventoryItemId idObj    = (InventoryItemId)(eventStoreAggregateId as EventStoreAggregateId).Id;
            var             criteria = CurrentSession.CreateCriteria <InventoryItemEventBase>();

            criteria.Add(Restrictions.Eq("InventoryItemEventId.InventoryItemIdProductId", idObj.ProductId));
            criteria.Add(Restrictions.Eq("InventoryItemEventId.InventoryItemIdLocatorId", idObj.LocatorId));
            criteria.Add(Restrictions.Eq("InventoryItemEventId.InventoryItemIdAttributeSetInstanceId", idObj.AttributeSetInstanceId));
            criteria.Add(Restrictions.Le("InventoryItemEventId.Version", version));
            criteria.AddOrder(global::NHibernate.Criterion.Order.Asc("InventoryItemEventId.Version"));
            var es = criteria.List <IEvent>();

            foreach (InventoryItemEventBase e in es)
            {
                e.EventReadOnly = true;
            }
            return(new EventStream()
            {
                SteamVersion = es.Count > 0 ? ((InventoryItemEventBase)es.Last()).InventoryItemEventId.Version : default(long),
                Events = es
            });
        }
Пример #3
0
        /// <summary>
        /// Tries to add the given quantity to the inventory item with the given ID without going over the maximum quantity allowed for an item.
        /// </summary>
        /// <param name="itemId"></param>
        /// <param name="quantity"></param>
        /// <returns>The quantity actually added to the item.</returns>
        public async Task <int> AddStockAsync(InventoryItemId itemId, int quantity)
        {
            IReliableDictionary <InventoryItemId, InventoryItem> inventoryItems =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <InventoryItemId, InventoryItem> >(InventoryItemDictionaryName);

            int quantityAdded = 0;

            ServiceEventSource.Current.ServiceMessage(this, "Received add stock request. Item: {0}. Quantity: {1}.", itemId, quantity);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                // Try to get the InventoryItem for the ID in the request.
                ConditionalValue <InventoryItem> item = await inventoryItems.TryGetValueAsync(tx, itemId);

                // We can only update the stock for InventoryItems in the system - we are not adding new items here.
                if (item.HasValue)
                {
                    quantityAdded = item.Value.AddStock(quantity);
                    await inventoryItems.SetAsync(tx, item.Value.Id, item.Value);
                }

                await tx.CommitAsync();

                ServiceEventSource.Current.ServiceMessage(
                    this,
                    "Add stock complete. Item: {0}. Added: {1}. Total: {2}",
                    item.Value.Id,
                    quantityAdded,
                    item.Value.AvailableStock);
            }
            return(quantityAdded);
        }
Пример #4
0
        public static string ToIdString(InventoryItemId id)
        {
            var formatter = (new ValueObjectTextFormatter <InventoryItemId>());
            var idStr     = formatter.ToString(id);

            return(idStr);
        }
Пример #5
0
        public static void CreateDefaultInventoryPostingRules()
        {
            inventoryPostingRuleApplicationService = ApplicationContext.Current["inventoryPostingRuleApplicationService"] as IInventoryPostingRuleApplicationService;

            var triggerItemId = new InventoryItemId(InventoryItemIds.Wildcard, InventoryItemIds.Wildcard, InventoryItemIds.Wildcard);
            var outputItemId  = new InventoryItemId(InventoryItemIds.SameAsSource, InventoryItemIds.EmptyLocatorId, InventoryItemIds.EmptyAttributeSetInstanceId);

            // --------------------------------------------------------
            // S = OH - Oc + V - R + IT
            // --------------------------------------------------------
            // On-Hand
            CreatePRQuantityOnHandUpdateProductSellableTotal(triggerItemId, outputItemId);
            // Occupied
            CreatePRQuantityOccupiedUpdateProductSellableTotal(triggerItemId, outputItemId);
            // Reserved
            CreatePRQuantityReservedUpdateProductSellableTotal(triggerItemId, outputItemId);
            // Virtual
            CreatePRQuantityVirtualUpdateProductSellableTotal(triggerItemId, outputItemId);
            // In-Transit
            CreatePRQuantityInTransitUpdateProductSellableTotal(triggerItemId, outputItemId);

            // ---------------------------------------------------------------------------
            //需求数量 = 订单占用数量(Oc) - 在库数量(OH) + 保留数量(R) - 在途数量(IT)
            // ---------------------------------------------------------------------------
            // Occupied
            CreatePRQuantityOccupiedUpdateProductRequiredTotal(triggerItemId, outputItemId);
            // On-Hand
            CreatePRQuantityOnHandUpdateProductRequiredTotal(triggerItemId, outputItemId);
            // Reserved
            CreatePRQuantityReservedUpdateProductRequiredTotal(triggerItemId, outputItemId);
            // In-Transit
            CreatePRQuantityInTransitUpdateProductRequiredTotal(triggerItemId, outputItemId);
        }
Пример #6
0
        /// <summary>
        /// Removes the given quantity of stock from an in item in the inventory.
        /// </summary>
        /// <param name="request"></param>
        /// <returns>int: Returns the quantity removed from stock.</returns>
        public async Task <int> RemoveStockAsync(InventoryItemId itemId, int quantity, CustomerOrderActorMessageId amId)
        {
            int removed = 0;

            ServiceEventSource.Current.ServiceMessage(this, "inside remove stock {0}|{1}", amId.GetHashCode(), amId.GetHashCode());

            IReliableDictionary <InventoryItemId, InventoryItem> inventoryItems =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <InventoryItemId, InventoryItem> >(InventoryItemDictionaryName);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ConditionalValue <InventoryItem> item = await inventoryItems.TryGetValueAsync(tx, itemId);

                if (item.HasValue)
                {
                    removed = item.Value.RemoveStock(quantity);

                    await inventoryItems.SetAsync(tx, itemId, item.Value);

                    ServiceEventSource.Current.ServiceMessage(
                        this,
                        "Removed stock complete. Item: {0}. Removed: {1}. Remaining: {2}",
                        item.Value.Id,
                        removed,
                        item.Value.AvailableStock);

                    await tx.CommitAsync();

                    ServiceEventSource.Current.Message("Inventory Service Changes Committed");
                    ServiceEventSource.Current.Message("Removed {0} of item {1}", removed, itemId);
                }
            }
            return(removed);
        }
Пример #7
0
        private PhysicalInventoryLineEventId NewPhysicalInventoryLineEventId(InventoryItemId inventoryItemId)
        {
            var eId = new PhysicalInventoryLineEventId();

            eId.PhysicalInventoryDocumentNumber = this.PhysicalInventoryEventId.DocumentNumber;
            eId.InventoryItemId          = inventoryItemId;
            eId.PhysicalInventoryVersion = this.PhysicalInventoryEventId.Version;
            return(eId);
        }
        public IInventoryItemState Get(InventoryItemId id)
        {
            IInventoryItemState state = CurrentSession.Get <InventoryItemState>(id);

            if (ReadOnlyProxyGenerator != null && state != null)
            {
                return(ReadOnlyProxyGenerator.CreateProxy <IInventoryItemState>(state, new Type[] { typeof(ISaveable) }, _readOnlyPropertyNames));
            }
            return(state);
        }
        public IInventoryItemRequirementState Get(InventoryItemId id, bool nullAllowed)
        {
            IInventoryItemRequirementState state = CurrentSession.Get <InventoryItemRequirementState> (id);

            if (!nullAllowed && state == null)
            {
                state = new InventoryItemRequirementState();
                (state as InventoryItemRequirementState).InventoryItemRequirementId = id;
            }
            return(state);
        }
        public IEnumerable <IInventoryItemEntryState> FindByInventoryItemId(InventoryItemId inventoryItemId)
        {
            var criteria        = CurrentSession.CreateCriteria <InventoryItemEntryState>();
            var partIdCondition = Restrictions.Conjunction()
                                  .Add(Restrictions.Eq("InventoryItemEntryId.InventoryItemIdProductId", inventoryItemId.ProductId))
                                  .Add(Restrictions.Eq("InventoryItemEntryId.InventoryItemIdLocatorId", inventoryItemId.LocatorId))
                                  .Add(Restrictions.Eq("InventoryItemEntryId.InventoryItemIdAttributeSetInstanceId", inventoryItemId.AttributeSetInstanceId))
            ;

            return(criteria.Add(partIdCondition).List <InventoryItemEntryState>());
        }
        public ISellableInventoryItemState Get(InventoryItemId id, bool nullAllowed)
        {
            ISellableInventoryItemState state = CurrentSession.Get <SellableInventoryItemState> (id);

            if (!nullAllowed && state == null)
            {
                state = new SellableInventoryItemState();
                (state as SellableInventoryItemState).SellableInventoryItemId = id;
            }
            return(state);
        }
 public InventoryItem(
     string description, decimal price, int availableStock, int restockThreshold, int maxStockThreshold, InventoryItemId id = null,
     bool onReorder = false)
 {
     this.Id = id ?? new InventoryItemId();
     this.Description = description;
     this.Price = price;
     this.AvailableStock = availableStock;
     this.RestockThreshold = restockThreshold;
     this.MaxStockThreshold = maxStockThreshold;
     this.OnReorder = onReorder;
 }
Пример #13
0
        /// <summary>
        /// NOTE: This should not be used in published MVP code.
        /// This function allows us to remove inventory items from inventory.
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public async Task DeleteInventoryItemAsync(InventoryItemId itemId)
        {
            IReliableDictionary <InventoryItemId, InventoryItem> inventoryItems =
                await this.stateManager.GetOrAddAsync <IReliableDictionary <InventoryItemId, InventoryItem> >(InventoryItemDictionaryName);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                await inventoryItems.TryRemoveAsync(tx, itemId);

                await tx.CommitAsync();
            }
        }
Пример #14
0
        private InventoryItemId GetOutputInventoryItemId(IInventoryPostingRuleState pr, InventoryItemId triggerItemId)
        {
            var productId = pr.OutputInventoryItemId.ProductId == InventoryItemIds.SameAsSource ?
                            triggerItemId.ProductId : pr.OutputInventoryItemId.ProductId;
            var locatorId = pr.OutputInventoryItemId.LocatorId == InventoryItemIds.SameAsSource ?
                            triggerItemId.LocatorId : pr.OutputInventoryItemId.LocatorId;
            var attrInstSetId = pr.OutputInventoryItemId.AttributeSetInstanceId == InventoryItemIds.SameAsSource ?
                                triggerItemId.AttributeSetInstanceId : pr.OutputInventoryItemId.AttributeSetInstanceId;
            var outputItemId = new InventoryItemId(productId, locatorId, attrInstSetId);

            return(outputItemId);
        }
Пример #15
0
 private IEnumerable <IInventoryPostingRuleState> GetPostingRules(InventoryItemId triggerItemId)
 {
     //todo 这两个 GetByProperty 方法的效率太低,可以考虑使用缓存
     return(InventoryPostingRuleApplicationService.GetByProperty("OutputAccountName", InventoryPostingRuleIds.OutputAccountNameSellableQuantity)
            .Union(
                InventoryPostingRuleApplicationService.GetByProperty("OutputAccountName", InventoryPostingRuleIds.OutputAccountNameRequiredQuantity)
                ).Where(pr =>
                        (pr.TriggerInventoryItemId.ProductId == InventoryItemIds.Wildcard || pr.TriggerInventoryItemId.ProductId == triggerItemId.ProductId) &&
                        (pr.TriggerInventoryItemId.LocatorId == InventoryItemIds.Wildcard || pr.TriggerInventoryItemId.LocatorId == triggerItemId.LocatorId) &&
                        (pr.TriggerInventoryItemId.AttributeSetInstanceId == InventoryItemIds.Wildcard || pr.TriggerInventoryItemId.AttributeSetInstanceId == triggerItemId.AttributeSetInstanceId)
                        ));
 }
Пример #16
0
        private static void CreatePRQuantityInTransitUpdateProductSellableTotal(InventoryItemId triggerItemId, InventoryItemId outputItemId)
        {
            CreateInventoryPostingRule inventoryPostingRule_6 = new CreateInventoryPostingRule();

            inventoryPostingRule_6.InventoryPostingRuleId = InventoryPostingRuleIds.QuantityInTransitUpdateProductSellableTotal;
            inventoryPostingRule_6.TriggerInventoryItemId = triggerItemId;
            inventoryPostingRule_6.OutputInventoryItemId  = outputItemId;
            inventoryPostingRule_6.TriggerAccountName     = ReflectUtils.GetPropertyName <IInventoryItemStateCreated>(e => e.InTransitQuantity);//"QuantityInTransit";
            inventoryPostingRule_6.OutputAccountName      = InventoryPostingRuleIds.OutputAccountNameSellableQuantity;
            inventoryPostingRule_6.IsOutputNegated        = false;
            inventoryPostingRule_6.Active    = true;
            inventoryPostingRule_6.CommandId = Guid.NewGuid().ToString();
            inventoryPostingRuleApplicationService.When(inventoryPostingRule_6);
        }
Пример #17
0
        public async Task <IInventoryItemRequirementState> GetHistoryStateAsync(InventoryItemId inventoryItemRequirementId, long version)
        {
            var idObj         = InventoryItemRequirementProxyUtils.ToIdString(inventoryItemRequirementId);
            var uriParameters = new InventoryItemRequirementHistoryStateUriParameters();

            uriParameters.Id      = idObj;
            uriParameters.Version = version.ToString();

            var req  = new InventoryItemRequirementHistoryStateGetRequest(uriParameters);
            var resp = await _ramlClient.InventoryItemRequirementHistoryState.Get(req);

            InventoryItemRequirementProxyUtils.ThrowOnHttpResponseError(resp);
            return((resp.Content == null) ? null : resp.Content.ToInventoryItemRequirementState());
        }
Пример #18
0
        private static void CreatePRQuantityOnHandUpdateProductRequiredTotal(InventoryItemId triggerItemId, InventoryItemId outputItemId)
        {
            CreateInventoryPostingRule inventoryPostingRule_12 = new CreateInventoryPostingRule();

            inventoryPostingRule_12.InventoryPostingRuleId = InventoryPostingRuleIds.QuantityOnHandUpdateProductRequiredTotal;
            inventoryPostingRule_12.TriggerInventoryItemId = triggerItemId;
            inventoryPostingRule_12.OutputInventoryItemId  = outputItemId;
            inventoryPostingRule_12.TriggerAccountName     = ReflectUtils.GetPropertyName <IInventoryItemStateCreated>(e => e.OnHandQuantity);//"QuantityOnHand";
            inventoryPostingRule_12.OutputAccountName      = InventoryPostingRuleIds.OutputAccountNameRequiredQuantity;
            inventoryPostingRule_12.IsOutputNegated        = true;
            inventoryPostingRule_12.Active    = true;
            inventoryPostingRule_12.CommandId = Guid.NewGuid().ToString();
            inventoryPostingRuleApplicationService.When(inventoryPostingRule_12);
        }
        public async Task <ISellableInventoryItemEvent> GetStateEventAsync(InventoryItemId sellableInventoryItemId, long version)
        {
            var idObj         = SellableInventoryItemProxyUtils.ToIdString(sellableInventoryItemId);
            var uriParameters = new SellableInventoryItemStateEventUriParameters();

            uriParameters.Id      = idObj;
            uriParameters.Version = version.ToString();

            var req  = new SellableInventoryItemStateEventGetRequest(uriParameters);
            var resp = await _ramlClient.SellableInventoryItemStateEvent.Get(req);

            SellableInventoryItemProxyUtils.ThrowOnHttpResponseError(resp);
            return(resp.Content);
        }
Пример #20
0
        public IInventoryItemState Get(InventoryItemId id, bool nullAllowed)
        {
            IInventoryItemState state = CurrentSession.Get <InventoryItemState> (id);

            if (!nullAllowed && state == null)
            {
                state = new InventoryItemState();
                (state as InventoryItemState).InventoryItemId = id;
            }
            if (ReadOnlyProxyGenerator != null && state != null)
            {
                return(ReadOnlyProxyGenerator.CreateProxy <IInventoryItemState>(state, new Type[] { typeof(ISaveable) }, _readOnlyPropertyNames));
            }
            return(state);
        }
Пример #21
0
        public async Task <bool> IsItemInInventoryAsync(InventoryItemId itemId)
        {
            ServiceEventSource.Current.Message("checking item {0} to see if it is in inventory", itemId);
            IReliableDictionary <InventoryItemId, InventoryItem> inventoryItems =
                await this.stateManager.GetOrAddAsync <IReliableDictionary <InventoryItemId, InventoryItem> >(InventoryItemDictionaryName);

            PrintInventoryItems(inventoryItems);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                ConditionalResult <InventoryItem> item = await inventoryItems.TryGetValueAsync(tx, itemId);

                return(item.HasValue);
            }
        }
        public async Task <ISellableInventoryItemState> GetAsync(InventoryItemId sellableInventoryItemId)
        {
            ISellableInventoryItemState state = null;
            var idObj         = SellableInventoryItemProxyUtils.ToIdString(sellableInventoryItemId);
            var uriParameters = new SellableInventoryItemUriParameters();

            uriParameters.Id = idObj;

            var req = new SellableInventoryItemGetRequest(uriParameters);

            var resp = await _ramlClient.SellableInventoryItem.Get(req);

            SellableInventoryItemProxyUtils.ThrowOnHttpResponseError(resp);
            state = (resp.Content == null) ? null : resp.Content.ToSellableInventoryItemState();
            return(state);
        }
Пример #23
0
        public async Task <IInventoryItemRequirementState> GetAsync(InventoryItemId inventoryItemRequirementId)
        {
            IInventoryItemRequirementState state = null;
            var idObj         = InventoryItemRequirementProxyUtils.ToIdString(inventoryItemRequirementId);
            var uriParameters = new InventoryItemRequirementUriParameters();

            uriParameters.Id = idObj;

            var req = new InventoryItemRequirementGetRequest(uriParameters);

            var resp = await _ramlClient.InventoryItemRequirement.Get(req);

            InventoryItemRequirementProxyUtils.ThrowOnHttpResponseError(resp);
            state = (resp.Content == null) ? null : resp.Content.ToInventoryItemRequirementState();
            return(state);
        }
Пример #24
0
        internal static ICreateInventoryItemEntry CreateInventoryItemEntry(IMovementState movement, IMovementLineState movementLine, string locatorId, decimal quantity, int lineSubSeqId,
                                                                           Func <long> nextEntrySeqId, bool usingInTransitQty = false)
        {
            var entry     = new CreateInventoryItemEntry();
            var invItemId = new InventoryItemId(movementLine.ProductId, locatorId, movementLine.AttributeSetInstanceId);

            entry.InventoryItemId = invItemId;
            entry.EntrySeqId      = nextEntrySeqId();
            if (!usingInTransitQty)
            {
                entry.OnHandQuantity = quantity;
            }
            else
            {
                entry.InTransitQuantity = quantity;
            }
            entry.Source = new InventoryItemSourceInfo(DocumentTypeIds.Movement, movement.DocumentNumber, movementLine.LineNumber, lineSubSeqId);
            return(entry);
        }
Пример #25
0
        /// <summary>
        /// Tries to add the given quantity to the inventory item with the given ID without going over the maximum quantity allowed for an item.
        /// </summary>
        /// <param name="itemId"></param>
        /// <param name="quantity"></param>
        /// <returns>The quantity actually added to the item.</returns>
        public async Task <int> AddStockAsync(InventoryItemId itemId, int quantity)
        {
            IReliableDictionary <InventoryItemId, InventoryItem> inventoryItems =
                await this.stateManager.GetOrAddAsync <IReliableDictionary <InventoryItemId, InventoryItem> >(InventoryItemDictionaryName);

            int quantityAdded = 0;

            ServiceEventSource.Current.ServiceMessage(this, "Received add stock request. Item: {0}. Quantity: {1}.", itemId, quantity);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                // Try to get the InventoryItem for the ID in the request.
                ConditionalResult <InventoryItem> item = await inventoryItems.TryGetValueAsync(tx, itemId);

                // We can only update the stock for InventoryItems in the system - we are not adding new items here.
                if (item.HasValue)
                {
                    // Update the stock quantity of the item.
                    // This only updates the copy of the Inventory Item that's in local memory here;
                    // It's not yet saved in the dictionary.
                    quantityAdded = item.Value.AddStock(quantity);

                    // We have to store the item back in the dictionary in order to actually save it.
                    // This will then replicate the updated item for
                    await inventoryItems.SetAsync(tx, item.Value.Id, item.Value);
                }

                // nothing will happen unless we commit the transaction!
                await tx.CommitAsync();

                ServiceEventSource.Current.ServiceMessage(
                    this,
                    "Add stock complete. Item: {0}. Added: {1}. Total: {2}",
                    item.Value.Id,
                    quantityAdded,
                    item.Value.AvailableStock);
            }


            return(quantityAdded);
        }
        /// <summary>
        /// Tries to add the given quantity to the inventory item with the given ID without going over the maximum quantity allowed for an item.
        /// </summary>
        /// <param name="itemId"></param>
        /// <param name="quantity"></param>
        /// <returns>The quantity actually added to the item.</returns>
        public async Task<int> AddStockAsync(InventoryItemId itemId, int quantity)
        {
            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.stateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            int quantityAdded = 0;

            ServiceEventSource.Current.ServiceMessage(this, "Received add stock request. Item: {0}. Quantity: {1}.", itemId, quantity);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                // Try to get the InventoryItem for the ID in the request.
                ConditionalResult<InventoryItem> item = await inventoryItems.TryGetValueAsync(tx, itemId);

                // We can only update the stock for InventoryItems in the system - we are not adding new items here.
                if (item.HasValue)
                {
                    // Update the stock quantity of the item.
                    // This only updates the copy of the Inventory Item that's in local memory here;
                    // It's not yet saved in the dictionary.
                    quantityAdded = item.Value.AddStock(quantity);

                    // We have to store the item back in the dictionary in order to actually save it.
                    // This will then replicate the updated item for
                    await inventoryItems.SetAsync(tx, item.Value.Id, item.Value);
                }

                // nothing will happen unless we commit the transaction!
                await tx.CommitAsync();

                ServiceEventSource.Current.ServiceMessage(
                    this,
                    "Add stock complete. Item: {0}. Added: {1}. Total: {2}",
                    item.Value.Id,
                    quantityAdded,
                    item.Value.AvailableStock);
            }


            return quantityAdded;
        }
Пример #27
0
        public virtual IPhysicalInventoryLineState Get(InventoryItemId inventoryItemId, bool forCreation, bool nullAllowed)
        {
            PhysicalInventoryLineId globalId = new PhysicalInventoryLineId(_physicalInventoryState.DocumentNumber, inventoryItemId);

            if (_loadedPhysicalInventoryLineStates.ContainsKey(globalId))
            {
                var state = _loadedPhysicalInventoryLineStates[globalId];
                if (this._physicalInventoryState != null && this._physicalInventoryState.ReadOnly == false)
                {
                    ((IPhysicalInventoryLineState)state).ReadOnly = false;
                }
                return(state);
            }
            if (forCreation || ForReapplying)
            {
                var state = new PhysicalInventoryLineState(ForReapplying);
                state.PhysicalInventoryLineId = globalId;
                _loadedPhysicalInventoryLineStates.Add(globalId, state);
                if (this._physicalInventoryState != null && this._physicalInventoryState.ReadOnly == false)
                {
                    ((IPhysicalInventoryLineState)state).ReadOnly = false;
                }
                return(state);
            }
            else
            {
                var state = PhysicalInventoryLineStateDao.Get(globalId, nullAllowed);
                if (state != null)
                {
                    _loadedPhysicalInventoryLineStates.Add(globalId, state);
                }
                if (this._physicalInventoryState != null && this._physicalInventoryState.ReadOnly == false)
                {
                    ((IPhysicalInventoryLineState)state).ReadOnly = false;
                }
                return(state);
            }
        }
		public ISellableInventoryItemState Get(InventoryItemId id)
		{
			ISellableInventoryItemState state = CurrentSession.Get<SellableInventoryItemState>(id);
			return state;
		}
 public CustomerOrderItem(InventoryItemId itemId, int quantity)
 {
     this.ItemId = itemId;
     this.Quantity = quantity;
     this.FulfillmentRemaining = quantity;
 }
 public RestockRequest(InventoryItemId itemId, int quantity)
 {
     this.ItemId = itemId;
     this.Quantity = quantity;
 }
 public Task<int> RemoveStockAsync(InventoryItemId itemId, int quantity, CustomerOrderActorMessageId amId)
 {
     return this.RemoveStockAsyncFunc(itemId, quantity, amId);
 }
 public Task<bool> IsItemInInventoryAsync(InventoryItemId itemId)
 {
     return this.IsItemInInventoryAsyncFunc(itemId);
 }
 public Task<bool> IsItemInInventoryAsync(InventoryItemId itemId, CancellationToken cancellationToken)
 {
     return this.IsItemInInventoryAsyncFunc(itemId);
 }
 public IEnumerable <IInventoryItemRequirementEntryState> GetInventoryItemRequirementEntries(InventoryItemId inventoryItemRequirementId)
 {
     return(StateQueryRepository.GetInventoryItemRequirementEntries(inventoryItemRequirementId));
 }
        public virtual IInventoryItemRequirementState Get(InventoryItemId inventoryItemRequirementId)
        {
            var state = StateRepository.Get(inventoryItemRequirementId, true);

            return(state);
        }
        /// <summary>
        /// Removes the given quantity of stock from an in item in the inventory.
        /// </summary>
        /// <param name="request"></param>
        /// <returns>int: Returns the quantity removed from stock.</returns>
        public async Task<int> RemoveStockAsync(InventoryItemId itemId, int quantity, CustomerOrderActorMessageId amId)
        {
            ServiceEventSource.Current.ServiceMessage(this, "inside remove stock {0}|{1}", amId.GetHashCode(), amId.GetHashCode());

            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.stateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            IReliableDictionary<CustomerOrderActorMessageId, DateTime> recentRequests =
                await this.stateManager.GetOrAddAsync<IReliableDictionary<CustomerOrderActorMessageId, DateTime>>(ActorMessageDictionaryName);

            IReliableDictionary<CustomerOrderActorMessageId, Tuple<InventoryItemId, int>> requestHistory =
                await
                    this.stateManager.GetOrAddAsync<IReliableDictionary<CustomerOrderActorMessageId, Tuple<InventoryItemId, int>>>(RequestHistoryDictionaryName);

            int removed = 0;

            ServiceEventSource.Current.ServiceMessage(this, "Received remove stock request. Item: {0}. Quantity: {1}.", itemId, quantity);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                //first let's see if this is a duplicate request
                ConditionalResult<DateTime> previousRequest = await recentRequests.TryGetValueAsync(tx, amId);
                if (!previousRequest.HasValue)
                {
                    //first time we've seen the request or it was a dupe from so long ago we have forgotten

                    // Try to get the InventoryItem for the ID in the request.
                    ConditionalResult<InventoryItem> item = await inventoryItems.TryGetValueAsync(tx, itemId);

                    // We can only remove stock for InventoryItems in the system.
                    if (item.HasValue)
                    {
                        // Update the stock quantity of the item.
                        // This only updates the copy of the Inventory Item that's in local memory here;
                        // It's not yet saved in the dictionary.
                        removed = item.Value.RemoveStock(quantity);

                        // We have to store the item back in the dictionary in order to actually save it.
                        // This will then replicate the updated item
                        await inventoryItems.SetAsync(tx, itemId, item.Value);

                        //we also have to make a note that we have returned this result, so that we can protect
                        //ourselves from stale or duplicate requests that come back later
                        await requestHistory.SetAsync(tx, amId, new Tuple<InventoryItemId, int>(itemId, removed));

                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Removed stock complete. Item: {0}. Removed: {1}. Remaining: {2}",
                            item.Value.Id,
                            removed,
                            item.Value.AvailableStock);
                    }
                }
                else
                {
                    //this is a duplicate request. We need to send back the result we already came up with and hope they get it this time
                    //find the previous result and send it back
                    ConditionalResult<Tuple<InventoryItemId, int>> previousResponse = await requestHistory.TryGetValueAsync(tx, amId);

                    if (previousResponse.HasValue)
                    {
                        removed = previousResponse.Value.Item2;
                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Retrieved previous response for request {0}, from {1}, for Item {2} and quantity {3}",
                            amId,
                            previousRequest.Value,
                            previousResponse.Value.Item1,
                            previousResponse.Value.Item2);
                    }
                    else
                    {
                        //we've seen the request before but we don't have a record for what we responded, inconsistent state
                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Inconsistent State: recieved duplicate request {0} but don't have matching response in history",
                            amId);
                        this.ServicePartition.ReportFault(System.Fabric.FaultType.Transient);
                    }


                    //note about duplicate Requests: technically if a duplicate request comes in and we have 
                    //sufficient invintory to return more now that we did previously, we could return more of the order and decrement 
                    //the difference to reduce the total number of round trips. This optimization is not currently implemented
                }


                //always update the datetime for the given request
                await recentRequests.SetAsync(tx, amId, DateTime.UtcNow);

                // nothing will happen unless we commit the transaction!
                ServiceEventSource.Current.Message("Committing Changes in Inventory Service");
                await tx.CommitAsync();
                ServiceEventSource.Current.Message("Inventory Service Changes Committed");
            }

            ServiceEventSource.Current.Message("Removed {0} of item {1}", removed, itemId);
            return removed;
        }
        public async Task<bool> IsItemInInventoryAsync(InventoryItemId itemId)
        {
            ServiceEventSource.Current.Message("checking item {0} to see if it is in inventory", itemId);
            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.stateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            PrintInventoryItems(inventoryItems);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                ConditionalResult<InventoryItem> item = await inventoryItems.TryGetValueAsync(tx, itemId);
                return item.HasValue;
            }
        }
        /// <summary>
        /// NOTE: This should not be used in published MVP code. 
        /// This function allows us to remove inventory items from inventory.
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public async Task DeleteInventoryItemAsync(InventoryItemId itemId)
        {
            IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems =
                await this.stateManager.GetOrAddAsync<IReliableDictionary<InventoryItemId, InventoryItem>>(InventoryItemDictionaryName);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                await inventoryItems.TryRemoveAsync(tx, itemId);
                await tx.CommitAsync();
            }
        }
 public virtual IInventoryItemRequirementEntryState GetInventoryItemRequirementEntry(InventoryItemId inventoryItemRequirementId, long entrySeqId)
 {
     return(StateQueryRepository.GetInventoryItemRequirementEntry(inventoryItemRequirementId, entrySeqId));
 }
 public Task<int> AddStockAsync(InventoryItemId itemId, int quantity)
 {
     return this.AddStockAsyncFunc(itemId, quantity);
 }
 public abstract IEventStoreAggregateId ToEventStoreAggregateId(InventoryItemId aggregateId);
 public Task<bool> IsItemInInventoryAsync(InventoryItemId itemId, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }