public List<InventoryOperation> NotifySubmittingCharterInStart(CharterIn charterInStart)
        {
            try
            {
                //var res= this.inventoryOperationManager.ManageCharterInStart(charterInStart,
                //    //TODO: Fake ActorId
                //    1101);

                _addCharterInStartReceiptVoucher.Execute(charterInStart,new List<Receipt>()
                                                                        {
                                                                          new Receipt(1,40,2500,1.5m)
                                                                        },"001","050");

                return null;
            }
            catch (Exception)
            {

                throw;
            }

            return new List<InventoryOperation>(new InventoryOperation[]
                    {
                     new InventoryOperation(
                         312,
                     "INV# - " +DateTime.Now.Ticks,
                        DateTime.Now,
                        InventoryActionType.Issue,
                        (long? )null,
                        (long? )null)});
        }
 public List<InventoryOperation> NotifySubmittingCharterInStart(CharterIn charterInStart)
 {
     return new List<InventoryOperation>(new InventoryOperation[]
             {
              new InventoryOperation(
              "INV# - " +DateTime.Now.Ticks,
                 DateTime.Now,
                 InventoryActionType.Issue,
                 (long? )null,
                 (long? )null)});
 }
        public List<InventoryOperation> NotifySubmittingCharterInEnd(CharterIn charterInEnd)
        {
            //var charterInDto = charterInToDtoMapper.MapToDtoModel(charterInEnd);

            //charterInDto.CharterType = "In";

            //charterInDto.CharterItems = charterInEnd.CharterItems.Select(charterItemToDtoMapper.MapToDtoModel).ToList();

            //var inventoryOperationDtosResult = svc.NotifySubmittingCharterInEnd(charterInDto).ToList();

            //var result = inventoryOperationDtosResult.Select(mapInventoryOperationDtoToInventoryOperation);

            //return result.ToList();

            return null;
        }
        public List<InventoryOperation> NotifySubmittingCharterInEnd(CharterIn charterInEnd)
        {
            var charterInDto = charterInToDtoMapper.MapToDtoModel(charterInEnd);

            charterInDto.CharterType = CharterType.In;

            charterInDto.CharterItems = new  ObservableCollection<CharterItemDto>(charterInEnd.CharterItems.Select(charterItemToDtoMapper.MapToDtoModel));

            //var inventoryOperationDtosResult = svc.NotifySubmittingCharterInEnd(charterInDto).ToList();

            //var result = inventoryOperationDtosResult.Select(mapInventoryOperationDtoToInventoryOperation);

            //return result.ToList();

            var syncEvent = new AutoResetEvent(false);

            List<InventoryOperation> callResult = null;
            Exception callException = null;

            ClientHelper.Post<List<FuelReportInventoryOperationDto>, CharterDto>
                //(new Uri("http://localhost:65234/api/fuelevents", UriKind.Absolute),
                //(new Uri("http://evaluation-srv:9090/api/fuelevents", UriKind.Absolute),
                (MessageBrokerApiUri, (result, exp) =>
                {
                    callException = exp;
                    if (result != null)
                        callResult = result.Select(mapInventoryOperationDtoToInventoryOperation).ToList();

                    syncEvent.Set();

                    //if (exp != null) tcs.TrySetException(exp);
                    //else if (result != null)
                    //{
                    //    var mappedResult = result.Select(mapInventoryOperationDtoToInventoryOperation).ToList();
                    //    tcs.TrySetResult(mappedResult);
                    //}
                },
                charterInDto, ClientHelper.MessageFormat.Json, new Dictionary<string, string>(), "CharterDto");

            /////var inventoryOperationDtosResult.Select(mapInventoryOperationDtoToInventoryOperation).ToList();
            syncEvent.WaitOne();

            if (callException != null)
                throw callException;

            return callResult;
        }
        public List<InventoryOperation> NotifySubmittingCharterInStart(CharterIn charterInStart)
        {
            var charterInDto = charterInToDtoMapper.MapToDtoModel(charterInStart);

            charterInDto.CharterType = CharterType.In;

            charterInDto.CharterItems = charterInStart.CharterItems.Select(charterItemToDtoMapper.MapToDtoModel).ToList();

            //var inventoryOperationDtosResult = svc.NotifySubmittingCharterInStart(charterInDto).ToList();
            var inventoryOperationDtosResult = new List<FuelReportInventoryOperationDto>();

            ClientHelper.Post<List<FuelReportInventoryOperationDto>, CharterDto>
                (new Uri("http://localhost:65234/api/fuelevents", UriKind.Absolute),
                (result, exp) =>
                {
                    inventoryOperationDtosResult = result;
                    var ex = exp;
                },
                charterInDto, ClientHelper.MessageFormat.Json, new Dictionary<string, string>(), "CharterDto");

            return inventoryOperationDtosResult.Select(mapInventoryOperationDtoToInventoryOperation).ToList();

            //return result.ToList();
        }
        public void Execute(
            CharterIn charterIn, List<Receipt> receipts, string receiptNumber, string receiptWarehouseCode
            )
        {
            var voucherSeting =
                _voucherSetingRepository.Find(c => c.VoucherDetailTypeId == VoucherDetailType.CharterInStart.Id)
                    .FirstOrDefault();

            var voucher = new Voucher();
            voucher.LocalVoucherDate()
                .FinancialVoucherDate(new DateTime())
                .Description(voucherSeting.VoucherMainDescription)
                .ReferenceNo(receiptNumber)
                .LocalVoucherNo("01")
                .VoucherRef(voucherSeting.VoucherMainRefDescription)
                .SetReferenceType(ReferenceType.CharterIn)
                .SetCurrency(charterIn.Currency);

            receipts.ForEach(c =>
                             {
                                 var debiJournalEntry = new JournalEntry();
                                 debiJournalEntry.IrrAmount(c.ReceiptQuantity * c.ReceiptFee * c.Coefficient)
                                     .VoucherRef(voucherSeting.VoucherDebitRefDescription)
                                     .Description(voucherSeting.VoucherDebitDescription)
                                     .AccountNo(voucherSeting.DebitAccounts[0].Code)
                                     .ForeignAmount(c.ReceiptFee * c.ReceiptQuantity)
                                     .SetSegmentType(SegmentType.Vessel)
                                     .SetSegment(segment =>
                                     {
                                         if (segment.SegmentType.Id == 1)
                                         {
                                             segment.Code = receiptWarehouseCode;
                                         }
                                         else if (segment.SegmentType.Id == 4)
                                         {
                                             segment.Code = charterIn.Owner.Code;
                                         }
                                     }, debiJournalEntry.Segment);

                                 voucher.JournalEntrieses.Add(debiJournalEntry);

                                var creditJournalEntry = new JournalEntry();
                                 creditJournalEntry.IrrAmount(c.ReceiptQuantity * c.ReceiptFee * c.Coefficient)
                                     .VoucherRef(voucherSeting.VoucherCeditRefDescription)
                                     .Description(voucherSeting.VoucherCreditDescription)
                                     .AccountNo( voucherSeting.CreditAccounts[0].Code)
                                     .ForeignAmount(c.ReceiptFee * c.ReceiptQuantity)
                                     .SetSegmentType( SegmentType.Company)
                                     .SetSegment(segment =>
                                     {
                                         if (segment.SegmentType.Id == 1)
                                         {
                                             segment.Code = receiptWarehouseCode;
                                         }
                                         else if (segment.SegmentType.Id == 4)
                                         {
                                             segment.Code = charterIn.Owner.Code;
                                         }
                                     }, creditJournalEntry.Segment);

                                 voucher.JournalEntrieses.Add(creditJournalEntry);

                             });

            _voucherRepository.Add(voucher);
            _unitOfWorkScope.Commit();
        }
        public List<InventoryOperation> ManageCharterInStart(CharterIn charterInStart, int userId)
        {
            if (charterInStart.CharterType != CharterType.Start)
                throw new InvalidArgument("The given entity is not Charter In Start", "charterInStart");

            using (var dbContext = new InventoryDbContext())
            {
                using (var transaction = dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                {
                    var result = new List<Domain.Model.DomainObjects.InventoryOperation>();

                    var reference = findInventoryOperationReference(dbContext, InventoryOperationType.Receipt, CHARTER_IN_START_RECEIPT, charterInStart.Id.ToString());

                    //if (reference.OperationId == INVALID_ID)
                    if (reference == null)
                    {
                        activateWarehouse(dbContext, (int)charterInStart.VesselInCompany.VesselInInventory.Id, userId);

                        string transactionCode, transactionMessage;

                        var operationReference = receipt(
                                  dbContext,
                                  (int)charterInStart.VesselInCompany.CompanyId,
                                  (int)charterInStart.VesselInCompany.VesselInInventory.Id,
                                  1,
                                  convertCharterInTypeToStoreType(charterInStart),
                                    null,
                                  CHARTER_IN_START_RECEIPT,
                                  charterInStart.Id.ToString(),
                                  userId,
                                  out transactionCode,
                                  out transactionMessage);

                        //TODO: Items
                        string transactionItemMessage;

                        var transactionItems = new List<TransactionItem>();

                        foreach (var charterItem in charterInStart.CharterItems)
                        {

                            transactionItems.Add(new TransactionItem()
                                                 {
                                                     GoodId = (int)charterItem.Good.SharedGoodId,
                                                     CreateDate = DateTime.Now,
                                                     Description = "Charter In Start > " + charterItem.Good.Code,
                                                     QuantityAmount = charterItem.Rob,
                                                     QuantityUnitId = getMeasurementUnitId(dbContext, charterItem.GoodUnit.Abbreviation),
                                                     TransactionId = (int)operationReference.OperationId,
                                                     UserCreatorId = userId
                                                 });
                        }

                        addTransactionItems(dbContext, (int)operationReference.OperationId, transactionItems, userId, out transactionItemMessage);

                        //Manual Items Pricing
                        var registeredTransaction = dbContext.Transactions.Single(t => t.Id == (int)operationReference.OperationId);

                        var transactionItemPrices = new List<TransactionItemPrice>();

                        foreach (var charterItem in charterInStart.CharterItems)
                        {
                            var registeredTransactionItem = registeredTransaction.TransactionItems.Single(ti => ti.GoodId == charterItem.Good.SharedGoodId);

                            var transactionItemPrice = new TransactionItemPrice()
                                {
                                    TransactionItemId = registeredTransactionItem.Id,
                                    QuantityUnitId = getMeasurementUnitId(dbContext, charterItem.GoodUnit.Abbreviation),
                                    QuantityAmount = charterItem.Rob,
                                    PriceUnitId = getCurrencyId(dbContext, charterInStart.Currency.Abbreviation),
                                    Fee = charterItem.Fee,
                                    RegistrationDate = DateTime.Now,
                                    Description = "Charter In Start Pricing > " + charterItem.Good.Code,
                                    UserCreatorId = userId
                                };

                            transactionItemPrices.Add(transactionItemPrice);
                            //priceTransactionItemsManually(dbContext, transactionItemPrice, userId, out pricingMessage, CHARTER_IN_START_RECEIPT_PRICING, charterItem.Id.ToString());
                        }

                        string pricingMessage;
                        priceTransactionItemsManually(dbContext, transactionItemPrices, userId, out pricingMessage, CHARTER_IN_START_RECEIPT_PRICING, charterInStart.Id.ToString());

                        result.Add(new InventoryOperation(
                            inventoryOperationId: operationReference.OperationId,
                            actionNumber: string.Format("{0}/{1}", (InventoryOperationType)operationReference.OperationType, transactionCode),
                            actionDate: DateTime.Now,
                            actionType: InventoryActionType.Receipt,
                            fuelReportDetailId: null,
                            charterId: charterInStart.Id));
                    }
                    else
                    {
                        throw new InvalidOperation("CharterInStart disapprovement", "CharterInStart disapprovement is invalid.");

                        var transactionItems = dbContext.TransactionItems.Where(ti => ti.TransactionId == reference.OperationId);

                    }

                    transaction.Commit();

                    return result;
                }
            }
        }
        //================================================================================
        public List<InventoryOperation> ManageCharterInEnd(CharterIn charterInEnd, int userId)
        {
            if (charterInEnd.CharterType != CharterType.End)
                throw new InvalidArgument("The given entity is not Charter In End", "charterInEnd");

            using (var dbContext = new InventoryDbContext())
            {
                using (var transaction = new TransactionScope())
                {
                    var reference = findInventoryOperationReference(dbContext, InventoryOperationType.Receipt, CHARTER_IN_START_RECEIPT, charterInEnd.Id.ToString());

                    //if (reference.OperationId == INVALID_ID)
                    if (reference == null)
                    {

                    }
                    else
                    {
                        var transactionItems = dbContext.TransactionItems.Where(ti => ti.TransactionId == reference.OperationId);

                    }
                }
            }
            return null;
        }
        //================================================================================
        private int convertCharterInTypeToStoreType(CharterIn charterIn)
        {
            switch (charterIn.CharterType)
            {
                case CharterType.Start:
                    return 1;

                case CharterType.End:
                    return 17;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }