|
| 1 | +import Foundation |
| 2 | +import CollectionConcurrencyKit |
| 3 | + |
| 4 | +class InvestmentDTOMapper { |
| 5 | + private let currencyDTOMapper: CurrencyDTOMapper |
| 6 | + private let tickerRepository: TickerRepository |
| 7 | + private let priceService: PriceService |
| 8 | + |
| 9 | + init(currencyDTOMapper: CurrencyDTOMapper, |
| 10 | + tickerRepository: TickerRepository, |
| 11 | + priceService: PriceService) { |
| 12 | + self.currencyDTOMapper = currencyDTOMapper |
| 13 | + self.priceService = priceService |
| 14 | + self.tickerRepository = tickerRepository |
| 15 | + } |
| 16 | + |
| 17 | + func investments(from transactions: [Transaction]) async throws -> [InvestmentDTO] { |
| 18 | + let investments: [InvestmentDTO] = try await transactions |
| 19 | + .grouped { $0.ticker } |
| 20 | + .asyncCompactMap { (ticker, transactions) in |
| 21 | + let name = try await tickerRepository.tickers(for: ticker)?.name ?? "" |
| 22 | + let latestPrice = try await priceService.price(for: ticker) |
| 23 | + var pricePerPurchase: [Decimal: Decimal] = [:] |
| 24 | + var numberOfShares: Decimal = 0 |
| 25 | + var totalCost: Decimal = 0 |
| 26 | + transactions.forEach { transaction in |
| 27 | + pricePerPurchase[transaction.pricePerShareAtPurchase] = transaction.numberOfShares |
| 28 | + numberOfShares += transaction.numberOfShares |
| 29 | + totalCost += (transaction.pricePerShareAtPurchase * transaction.numberOfShares) + transaction.fees |
| 30 | + } |
| 31 | + let currentValue = numberOfShares * latestPrice |
| 32 | + let avgBuyPrice = pricePerPurchase.keys.reduce(0) { $0 + $1 } / Decimal(pricePerPurchase.count) |
| 33 | + let profit = currentValue - totalCost |
| 34 | + let totalReturn = (totalCost == 0 ? 0 : profit / totalCost).ro |
| 35 | + |
| 36 | + return InvestmentDTO(name: name, |
| 37 | + shortName: ticker, |
| 38 | + avgBuyPrice: avgBuyPrice, |
| 39 | + latestPrice: latestPrice, |
| 40 | + totalReturn: totalReturn, |
| 41 | + profit: profit, |
| 42 | + value: currentValue, |
| 43 | + numberOfShares: numberOfShares, |
| 44 | + currency: currencyDTOMapper.currency(from: transactions.first!.currency)) |
| 45 | + } |
| 46 | + |
| 47 | + return investments |
| 48 | + } |
| 49 | +} |
0 commit comments