コード例 #1
0
        public Portfolio CreatePortfolio(User user, string portfolioname, bool isSimulated, Tuple <string, AssetClass>[] tuples)
        {
            Portfolio portfolio = new Portfolio()
            {
                Name             = portfolioname,
                AssetAllocations = new List <AssetAllocation>(),
                UserId           = user.Id,
            };

            Portfolios.Add(portfolio);
            SaveChanges();

            foreach (var tuple in tuples)
            {
                AssetBase assetBase = GetAssetyBy(tuple.Item2, tuple.Item1);
                if (assetBase == null)
                {
                    assetBase = CreateAsset(tuple.Item2, tuple.Item1);
                }
                AssetAllocation assetAllocation = new AssetAllocation()
                {
                    Asset       = assetBase,
                    PortfolioId = portfolio.Id,
                };
                AssetAllocations.Add(assetAllocation);
                portfolio.AssetAllocations.Add(assetAllocation);
            }
            portfolio.UserId      = user.Id;
            portfolio.IsSimulated = true;
            Update(portfolio);
            return(portfolio);
        }
コード例 #2
0
        public IHttpActionResult DeleteAssetAllocationDetailsById(int id, int LastModifiedBy, string Comments)
        {
            long            AssetAllocId       = 0;
            AssetAllocation objAssetAllocation = db.AssetAllocations.Find(id);

            if (objAssetAllocation == null)
            {
                return(NotFound());
            }
            AssetAllocId = objAssetAllocation.AssetAllocationId;
            var qry = db.AssetAllocations.Where(x => x.AssetAllocationId == AssetAllocId).ToList();

            qry.ForEach(e => e.AssetCanceledOn      = System.DateTime.Now);
            qry.ForEach(y => y.LastModifiedBy       = LastModifiedBy);
            qry.ForEach(y => y.LastModifiedOn       = System.DateTime.Now);
            qry.ForEach(z => z.CancellationComments = Comments);
            db.Entry(objAssetAllocation).State      = EntityState.Modified;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AssetAllocationExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(Ok("Updated"));
        }
コード例 #3
0
        public IHttpActionResult UpdateAssetAllocations(AvailableAssetsModel assetAllocationArray)
        {
            string rtnMsg = string.Empty;

            try
            {
                if (assetAllocationArray.AssetAllocationArray.Count > 0 && assetAllocationArray.AssetId > 0)
                {
                    AssetAllocation assetAllocation = db.AssetAllocations.Where(x => x.AssetId == assetAllocationArray.AssetId).FirstOrDefault();
                    assetAllocation.LocationId         = assetAllocationArray.AssetAllocationArray.FirstOrDefault().LocationId;
                    assetAllocation.EmployeeId         = assetAllocationArray.AssetAllocationArray.FirstOrDefault().EmployeeId;
                    assetAllocation.AssetAllocatedOn   = System.DateTime.Now;
                    assetAllocation.AssetCanceledOn    = null;
                    assetAllocation.CreatedOn          = System.DateTime.Now;
                    assetAllocation.CreatedBy          = assetAllocationArray.CreatedBy;
                    assetAllocation.AllocationComments = assetAllocationArray.AssetAllocationArray.FirstOrDefault().Comments;
                    db.AssetAllocations.Add(assetAllocation);
                    db.Entry(assetAllocation).State = EntityState.Modified;
                    db.SaveChanges();
                    rtnMsg = "Inserted";
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
            return(Ok(rtnMsg));
        }
コード例 #4
0
        public IHttpActionResult UpdateAssetAllocationDetails(int AssetAllocationId, int LastModifiedBy, string Comments)
        {
            AssetAllocation assetAllocation = new AssetAllocation();

            assetAllocation = (from x in db.AssetAllocations
                               where x.AssetAllocationId == AssetAllocationId
                               select x).SingleOrDefault();

            if (AssetAllocationId != assetAllocation.AssetAllocationId)
            {
                return(BadRequest());
            }
            assetAllocation.LastModifiedBy       = LastModifiedBy;
            assetAllocation.LastModifiedOn       = System.DateTime.Now;
            assetAllocation.AssetCanceledOn      = System.DateTime.Now;
            assetAllocation.CancellationComments = Comments;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AssetAllocationExists(AssetAllocationId))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(StatusCode(HttpStatusCode.NoContent));
        }
コード例 #5
0
        public void Update(AssetAllocation allocation)
        {
            //TODO: FALTA CAMPO FECHA DE ACTUALIZACION

            AssetAllocations.Attach(allocation);
            Entry(allocation).State = EntityState.Modified;
            SaveChanges();
        }
コード例 #6
0
        public void GetPortionWithSmallestReminder_OneAsset()
        {
            var allocation = new AssetAllocation(new AssetPortion("AGG", 1.0M));

            var assetSize = allocation.GetAssetWithSmallestReminder(30.Dollars(), _prices);

            Assert.Equal("AGG", assetSize.Ticker);
            Assert.Equal(1, assetSize.Size);
        }
コード例 #7
0
        public void GetPortionWithSmallestReminder_PortfolioCostIsTooSmall()
        {
            var allocation = new AssetAllocation(new AssetPortion("AGG", 1.0M));

            var assetSize = allocation.GetAssetWithSmallestReminder(10.Dollars(), _prices);

            Assert.Equal("AGG", assetSize.Ticker);
            Assert.Equal(0, assetSize.Size);
        }
コード例 #8
0
ファイル: AssetsController.cs プロジェクト: xprasoulas/grid
        public ActionResult Edit(Asset asset)
        {
            if (ModelState.IsValid)
            {
                var selectedAsset = _assetRepository.Get(asset.Id);

                if (selectedAsset != null)
                {
                    // Log new Changes in Allocation Table
                    if (selectedAsset.State != asset.State || selectedAsset.AllocatedEmployeeId != asset.AllocatedEmployeeId)
                    {
                        var assetAllocation = new AssetAllocation
                        {
                            State = asset.State,
                            AllocatedEmployeeId   = asset.AllocatedEmployeeId,
                            AllocatedOn           = DateTime.UtcNow,
                            AllocatedByEmployeeId = WebUser.Id,
                            AssetId = selectedAsset.Id
                        };

                        _assetAllocationRepository.Create(assetAllocation);
                        _unitOfWork.Commit();

                        // Asset State Changed
                        #if !DEBUG
                        _emailComposerService.AssetStateChanged(selectedAsset.Id);
                        #endif
                    }

                    // Update main Asset

                    selectedAsset.SerialNumber        = asset.SerialNumber;
                    selectedAsset.Title               = asset.Title;
                    selectedAsset.Description         = asset.Description;
                    selectedAsset.Specifications      = asset.Specifications;
                    selectedAsset.Brand               = asset.Brand;
                    selectedAsset.Cost                = asset.Cost;
                    selectedAsset.ModelNumber         = asset.ModelNumber;
                    selectedAsset.IsBrandNew          = asset.IsBrandNew;
                    selectedAsset.State               = asset.State;
                    selectedAsset.PurchaseDate        = asset.PurchaseDate;
                    selectedAsset.WarrantyExpiryDate  = asset.WarrantyExpiryDate;
                    selectedAsset.AssetCategoryId     = asset.AssetCategoryId;
                    selectedAsset.DepartmentId        = asset.DepartmentId;
                    selectedAsset.VendorId            = asset.VendorId;
                    selectedAsset.AllocatedEmployeeId = asset.AllocatedEmployeeId;

                    _assetRepository.Update(selectedAsset);
                    _unitOfWork.Commit();

                    return(RedirectToAction("Index"));
                }
            }

            return(View(asset));
        }
コード例 #9
0
        public void Remove_UnknownTicker()
        {
            var allocation = new AssetAllocation(
                new AssetPortion("AGG", 0.55M),
                new AssetPortion("VTT", 0.45M));

            allocation = allocation.Remove("UTR");

            Assert.Equal(2, allocation.Portions.Count);
        }
コード例 #10
0
        public void Show(AssetAllocation alloc)
        {
            //I create a form for every request because maybe the user want to see several asset details at the same time
            APIResponse <Stock> response            = DataSourcesAPICaller.GetCompleteStockData(alloc.Asset.Ticker, alloc.Asset.Exchange, alloc.Asset.AssetClass, true, true);
            AssetDetailForm     showAssetDetailForm = new AssetDetailForm(response);

            showAssetDetailForms.Add(showAssetDetailForm);
            //showAssetDetailForm.MdiParent = this.ParentForm;
            showAssetDetailForm.Show();
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: yakimovim/finance-advicer
        private static void Main()
        {
            CurrencyConverter.ClearRates();
            CurrencyConverter.One(Dollars).Costs(73.67M.Rubles());

            var myPortfolio = new Portfolio(27070.4M.Rubles(),
                                            new AssetSize("FXMM", 265),
                                            new AssetSize("FXUS", 54),
                                            new AssetSize("FXDE", 62),
                                            new AssetSize("FXCN", 25),
                                            new AssetSize("FXGD", 106));

            var myAssetAllocation = new AssetAllocation(
                new AssetPortion("FXMM", 0.40M),
                new AssetPortion("FXUS", 0.25M),
                new AssetPortion("FXDE", 0.15M),
                new AssetPortion("FXCN", 0.10M),
                new AssetPortion("FXGD", 0.10M)
                );

            var prices = new[]
            {
                new AssetPrice("FXMM", 1646.8M.Rubles()),
                new AssetPrice("FXUS", 4949M.Rubles()),
                new AssetPrice("FXDE", 2668.5M.Rubles()),
                new AssetPrice("FXCN", 3917.5M.Rubles()),
                new AssetPrice("FXGD", 926.6M.Rubles())
            };

            var actions = new ActionsProvider().GetActions(
                myPortfolio,
                myAssetAllocation,
                prices
                );

            foreach (var action in actions)
            {
                Console.WriteLine(action);
            }

            var restCash = myPortfolio.Cash;

            foreach (var action in actions)
            {
                restCash = restCash - ((action.Type == ActionType.Buy)
                    ? action.Size * prices.Single(ap => ap.Ticker == action.Ticker).Value
                    : -action.Size * prices.Single(ap => ap.Ticker == action.Ticker).Value);
            }

            Console.WriteLine($"Rest of cash: {restCash}");

            Console.WriteLine();
            Console.WriteLine("Press ENTER to exit...");
            Console.ReadLine();
        }
コード例 #12
0
ファイル: AssetModel.cs プロジェクト: xprasoulas/grid
        public AssetModel(AssetAllocation asset)
        {
            Id = asset.Id;

            if (asset.AllocatedEmployee?.User.Person != null)
            {
                AllocatedEmployee = asset.AllocatedEmployee.User.Person.Name;
            }
            StateType   = GetEnumDescription(asset.State);
            AllocatedOn = asset.AllocatedOn;
        }
コード例 #13
0
        public void Remove_All()
        {
            var allocation = new AssetAllocation(
                new AssetPortion("AGG", 0.55M),
                new AssetPortion("VTT", 0.45M));

            allocation = allocation.Remove("VTT");
            allocation = allocation.Remove("AGG");

            Assert.Equal(0, allocation.Portions.Count);
        }
コード例 #14
0
        public void GetPortionWithSmallestReminder_SeveralAssets()
        {
            var allocation = new AssetAllocation(
                new AssetPortion("AGG", 0.55M),
                new AssetPortion("VTT", 0.45M));

            var assetSize = allocation.GetAssetWithSmallestReminder(100.Dollars(), _prices);

            Assert.Equal("VTT", assetSize.Ticker);
            Assert.Equal(3, assetSize.Size);
        }
コード例 #15
0
        public void Remove_ExistingTicker()
        {
            var allocation = new AssetAllocation(
                new AssetPortion("AGG", 0.55M),
                new AssetPortion("VTT", 0.45M));

            allocation = allocation.Remove("AGG");

            Assert.Equal(1, allocation.Portions.Count);
            Assert.Equal("VTT", allocation.Portions[0].Ticker);
            Assert.Equal(1.0M, allocation.Portions[0].Portion);
        }
コード例 #16
0
        private void dataGridViewAssets_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }

            if (e.ColumnIndex == dataGridViewAssets_ShowDetailColumn.Index)
            {
                AssetAllocation assetAllocation = (AssetAllocation)dataGridViewAssets.Rows[e.RowIndex].DataBoundItem;
                _callerForm.Show(assetAllocation);
            }
        }
コード例 #17
0
        public static bool UpdateAssetAllocation(AssetAllocation assetAllocation, out APIResponse <AssetAllocation> response, out string message)
        {
            string         uri            = $"api/Portfolios/updateassetallocation";
            HttpStatusCode httpStatusCode = HttpClientWebAPI.Post <int>(uri, assetAllocation.Id, out string jsonResponse, out string reasonPhrase);

            if (httpStatusCode == HttpStatusCode.OK)
            {
                response = JsonConvert.DeserializeObject <APIResponse <AssetAllocation> >(jsonResponse, jsonSerializerSettings);
                message  = response.ErrorMessage;
                return(response.Ok);
            }
            else
            {
                response = null;
                message  = reasonPhrase;
                return(false);
            }
        }
コード例 #18
0
        public RedirectToRouteResult AddToCart(Cart cart, int id, int?assetAllocationId, string returnUrl)
        {
            SaleProduct sp = applicationDataContext.SaleProducts.Expand("Product, Sale").Where(x => x.Id == id).FirstOrDefault();

            AssetAllocation aa = null;

            if (assetAllocationId.HasValue)
            {
                aa = applicationDataContext.AssetAllocations.Where(x => x.Id == assetAllocationId).Single();
            }

            if (sp != null)
            {
                cart.AddItem(sp, 1, aa);
            }

            return(RedirectToAction("Index", new { returnUrl }));
        }
コード例 #19
0
        public bool Update(int assetAllocationId, out AssetAllocation assetAllocation)
        {
            assetAllocation = portfoliosContext.GetAssetAllocationBy(assetAllocationId);
            AssetClass assetClass = assetAllocation.Asset.AssetClass;
            string     ticker     = assetAllocation.Asset.Ticker;
            Exchange?  exchange   = assetAllocation.Asset.Exchange;
            decimal?   costs      = assetAllocation.Costs.Value;

            if (assetClass == AssetClass.Stock || assetClass == AssetClass.ETF)
            {
                if (dataSource.TryGetLastPrice(ticker, exchange, assetClass, out HistoricalPrice price, out string message))
                {
                    decimal?marketValue = assetAllocation.UpdateMarketValue(price, costs);
                    portfoliosContext.Update(assetAllocation);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
コード例 #20
0
        public void PostOrder([FromBody] OrderAsset orderAsset)
        {
            var assetWithId      = new Dictionary <int, string>();
            var assetAllocations = new List <AssetAllocation>();

            using (var db = new EzTrackContext())
            {
                var order = new Order
                {
                    OrderName  = orderAsset.OrderName,
                    PickupDate = orderAsset.PickupDate,
                    Status     = orderAsset.Status
                };
                db.Orders.Add(order);
                db.SaveChanges();

                foreach (var item in orderAsset.ScannedAssets)
                {
                    var id = db.Assets.FirstOrDefault(x => x.BarcodeAlias == item).Id;
                    assetWithId.Add(id, item);
                }

                foreach (var item in assetWithId)
                {
                    var assetAllocation = new AssetAllocation
                    {
                        OrderId = order.Id,
                        AssetId = item.Key
                    };
                    assetAllocations.Add(assetAllocation);
                }

                db.AssetAllocations.AddRange(assetAllocations);
                db.SaveChanges();
            }
        }
コード例 #21
0
        public void AddItem(SaleProduct saleProduct, int quantity, AssetAllocation assetAllocation)
        {
            if (!this.SaleId.HasValue)
            {
                this.SaleId = saleProduct.Sale.Id;
            }

            CartLine line = lineCollection
                            .Where(sp => sp.SaleProduct.Id == saleProduct.Id)
                            .FirstOrDefault();

            if (line == null)
            {
                lineCollection.Add(new CartLine {
                    SaleProduct     = saleProduct,
                    AssetAllocation = assetAllocation,
                    Quantity        = quantity
                });
            }
            else if (assetAllocation == null)
            {
                line.Quantity += quantity;
            }
        }
コード例 #22
0
        public JsonResult Update(AssetModel assetModel)
        {
            ApiResult <Asset> apiResult;

            if (ModelState.IsValid)
            {
                if (assetModel.Id > 0)
                {
                    apiResult = TryExecute(() =>
                    {
                        var selectedAsset = _assetRepository.Get(assetModel.Id);
                        if (selectedAsset != null)
                        {
                            var employee = _employeeRepository.GetBy(u => u.UserId == WebUser.Id);

                            // Log new Changes in Allocation Table
                            if (selectedAsset.State != assetModel.State || selectedAsset.AllocatedEmployeeId != assetModel.AllocatedEmployeeId)
                            {
                                var assetAllocation = new AssetAllocation
                                {
                                    State = assetModel.State,
                                    AllocatedEmployeeId   = assetModel.AllocatedEmployeeId,
                                    AllocatedOn           = DateTime.UtcNow,
                                    AllocatedByEmployeeId = employee.Id,
                                    AssetId = selectedAsset.Id
                                };

                                _assetAllocationRepository.Create(assetAllocation);
                                _unitOfWork.Commit();
                            }
                            // Update main Asset

                            selectedAsset.SerialNumber        = assetModel.SerialNumber;
                            selectedAsset.Title               = assetModel.Title;
                            selectedAsset.Description         = assetModel.Description;
                            selectedAsset.Specifications      = assetModel.Specifications;
                            selectedAsset.Brand               = assetModel.Brand;
                            selectedAsset.Cost                = assetModel.Cost;
                            selectedAsset.TagNumber           = assetModel.TagNumber;
                            selectedAsset.ModelNumber         = assetModel.ModelNumber;
                            selectedAsset.IsBrandNew          = assetModel.IsBrandNew;
                            selectedAsset.State               = assetModel.State;
                            selectedAsset.PurchaseDate        = assetModel.PurchaseDate;
                            selectedAsset.WarrantyExpiryDate  = assetModel.WarrantyExpiryDate;
                            selectedAsset.AssetCategoryId     = assetModel.AssetCategoryId;
                            selectedAsset.DepartmentId        = assetModel.DepartmentId;
                            selectedAsset.VendorId            = assetModel.VendorId;
                            selectedAsset.AllocatedEmployeeId = assetModel.AllocatedEmployeeId;

                            _assetRepository.Update(selectedAsset);
                            _unitOfWork.Commit();
                        }

                        // Asset State Changed
#if !DEBUG
                        _emailComposerService.AssetStateChanged(selectedAsset.Id);
#endif

                        return(selectedAsset);
                    }, "Asset updated sucessfully");
                }
                else
                {
                    apiResult = TryExecute(() =>
                    {
                        var asset = new Asset
                        {
                            Title               = assetModel.Title,
                            SerialNumber        = assetModel.SerialNumber,
                            Description         = assetModel.Description,
                            Specifications      = assetModel.Specifications,
                            Brand               = assetModel.Brand,
                            Cost                = assetModel.Cost,
                            ModelNumber         = assetModel.ModelNumber,
                            IsBrandNew          = assetModel.IsBrandNew,
                            State               = assetModel.State,
                            PurchaseDate        = assetModel.PurchaseDate,
                            WarrantyExpiryDate  = assetModel.WarrantyExpiryDate,
                            AssetCategoryId     = assetModel.AssetCategoryId,
                            DepartmentId        = assetModel.DepartmentId,
                            VendorId            = assetModel.VendorId,
                            AllocatedEmployeeId = assetModel.AllocatedEmployeeId,
                            Id = assetModel.Id
                        };

                        _assetRepository.Create(asset);
                        _unitOfWork.Commit();

                        // Update Tag Number
                        var selectedAsset = _assetRepository.Get(asset.Id);
                        if (selectedAsset != null)
                        {
                            selectedAsset.TagNumber = $"LA{asset.Id.ToString("D" + 6)}";
                            _assetRepository.Update(selectedAsset);
                            _unitOfWork.Commit();
                        }
#if !DEBUG
                        if (selectedAsset != null)
                        {
                            _emailComposerService.AssetStateChanged(selectedAsset.Id);
                        }
#endif
                        return(asset);
                    }, "Asset created sucessfully");
                }
            }
            else
            {
                apiResult = ApiResultFromModelErrors <Asset>();
            }

            return(Json(apiResult, JsonRequestBehavior.AllowGet));
        }
コード例 #23
0
        public void Constructor_NoAssets()
        {
            var allocation = new AssetAllocation();

            Assert.NotNull(allocation);
        }
コード例 #24
0
        private void LaunchUpdateTask(Portfolio portfolio)
        {
            if (_updateTask != null)
            {
                MessageBox.Show("Task is already running", "Update proces", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (_selectedPortfolio == null)
            {
                MessageBox.Show("Must select a portfolio", "Update proces", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            _updateTask = Task.Factory.StartNew(() =>
            {
                try
                {
                    //update market values
                    int i         = 0;
                    decimal total = 0;
                    while (i < portfolio.AssetAllocations.Count)
                    {
                        AssetAllocation assetAllocation = portfolio.AssetAllocations[i];
                        try
                        {
                            bool ok = PortfoliosAPICaller.UpdateAssetAllocation(assetAllocation, out APIResponse <AssetAllocation> response, out string message);
                            decimal marketValue;
                            if (ok)
                            {
                                marketValue = response.Content.MarketValue.Value;
                                portfolio.AssetAllocations[i] = response.Content;
                            }
                            else
                            {
                                marketValue = 0;
                            }

                            total += marketValue;

                            Invoke(new Action(() => dataGridViewAssets.Refresh()));
                        }
                        catch (Exception ex)
                        {
                            _logger.Error($"LaunchUpdateTask failed for portfolio='{portfolio.Name}' (UserId='{portfolio.UserId}'), Ticker={assetAllocation.Asset.Ticker}: {ex.Message}", ex);
                        }
                        i++;
                    }

                    //pending to update percentages
                    foreach (AssetAllocation assetAllocation in portfolio.AssetAllocations)
                    {
                        if (assetAllocation.MarketValue.HasValue)
                        {
                            assetAllocation.Percentage = assetAllocation.MarketValue.Value / total * 100;
                        }
                        else
                        {
                            if (assetAllocation.Costs.HasValue)
                            {
                                assetAllocation.Percentage = assetAllocation.Costs.Value / total * 100;
                            }
                        }

                        Invoke(new Action(() => dataGridViewAssets.Refresh()));
                    }

                    Invoke(new Action(() =>
                    {
                        CalculateTotals(portfolio, true);
                    }));
                }
                catch (Exception ex)
                {
                    _logger.Error($"LaunchUpdateTask failed for portfolio='{portfolio.Name}' (UserId='{portfolio.UserId}'): {ex.Message}", ex);
                    MessageBox.Show(ex.Message, "Prices update failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    _updateTask = null;
                }
            });
        }