From 00f27eb3d97dfefe6973fbbe6edb3487ee649c5e Mon Sep 17 00:00:00 2001 From: Daniel Subiabre Date: Tue, 9 Apr 2024 13:07:31 +0200 Subject: [PATCH] Add invests pump --- src/Library/Benzina/Pump/InvestsPump.php | 147 +++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 src/Library/Benzina/Pump/InvestsPump.php diff --git a/src/Library/Benzina/Pump/InvestsPump.php b/src/Library/Benzina/Pump/InvestsPump.php new file mode 100644 index 0000000..5345651 --- /dev/null +++ b/src/Library/Benzina/Pump/InvestsPump.php @@ -0,0 +1,147 @@ +hasAllKeys($data[0], self::INVEST_KEYS); + } + + public function process(mixed $data): void + { + $invested = $this->getInvested($data); + $investors = $this->getInvestors($data); + + foreach ($data as $key => $data) { + // Ignore invests to non-migrated projects + // Shouldn't be much, as the non-migrated are projects that were never funded in any way + if (!\array_key_exists($data['project'], $invested)) { + continue; + } + + if ($data['amount'] === 0) { + continue; + } + + /** @var User */ + $user = $investors[$data['user']]; + + /** @var Project */ + $project = $invested[$data['project']]; + + $money = new Money($data['amount'] * 100, $data['currency']); + + $transaction = new Transaction; + $transaction->setMoney($money); + $transaction->setOrigin($user->getAccounting()); + $transaction->setTarget($project->getAccounting()); + $transaction->setGateway($data['method']); + $transaction->setGatewayReference($this->getGatewayReference($data)); + + $this->entityManager->persist($transaction); + } + + $this->entityManager->flush(); + $this->entityManager->clear(); + } + + private function getInvested(array $data): array + { + $projects = $this->projectRepository->findBy(['migratedReference' => \array_map(function ($data) { + return $data['project']; + }, $data)]); + + $invested = []; + foreach ($projects as $project) { + $invested[$project->getMigratedReference()] = $project; + } + + return $invested; + } + + private function getInvestors(array $data): array + { + $users = $this->userRepository->findBy(['migratedReference' => \array_map(function ($data) { + return $data['user']; + }, $data)]); + + $investors = []; + foreach ($users as $user) { + $investors[$user->getMigratedReference()] = $user; + } + + return $investors; + } + + private function getGatewayReference(array $data): string + { + if (!empty($data['transaction'])) { + return $data['transaction']; + } + + if (!empty($data['payment'])) { + return $data['payment']; + } + + if (!empty($data['preapproval'])) { + return $data['preapproval']; + } + + return ''; + } +}