src/Service/Royalties/RoyaltyImporterFileService.php line 1663

Open in your IDE?
  1. <?php
  2. namespace App\Service\Royalties;
  3. use App\DTO\MMPZ\Royalty\ConsolidationDTO;
  4. use App\DTO\MMPZ\Royalty\EarningByCountryDTO;
  5. use App\DTO\MMPZ\Royalty\EarningByCountryResponseDTO;
  6. use App\DTO\MMPZ\Royalty\EarningByCompositionDTO;
  7. use App\DTO\MMPZ\Royalty\EarningByCompositionResponseDTO;
  8. use App\DTO\MMPZ\Royalty\EarningByMonthDTO;
  9. use App\DTO\MMPZ\Royalty\EarningByMonthResponseDTO;
  10. use App\DTO\MMPZ\Royalty\EarningByPlatformDTO;
  11. use App\DTO\MMPZ\Royalty\EarningByPlatformResponseDTO;
  12. use App\DTO\MMPZ\Royalty\EarningDTO;
  13. use App\DTO\MMPZ\Royalty\PublisherAdministratorEarningDTO;
  14. use App\DTO\MMPZ\Royalty\ServiceEarningDTO;
  15. use App\DTO\MMPZ\Song\DownloadSongParametersDTO;
  16. use App\Entity\App\Country;
  17. use App\Entity\App\Currency;
  18. use App\Entity\App\File;
  19. use App\Entity\ClickHouse\IncomeRawDataCH;
  20. use App\Entity\ClickHouse\RawDataCH;
  21. use App\Entity\ClickHouse\RawDataIncompleteCH;
  22. use App\Entity\Composition\Composition;
  23. use App\Entity\Composition\SongWriter;
  24. use App\Entity\Profile\Profile;
  25. use App\Entity\Profile\ProfileInformation;
  26. use App\Entity\Profile\Splits\RoyaltyDue;
  27. use App\Entity\Profile\Splits\RoyaltyDueAdjust;
  28. use App\Entity\Profile\Splits\RoyaltyImporterFile;
  29. use App\Entity\Profile\Splits\RoyaltySplits;
  30. use App\Entity\Publishing\Platform;
  31. use App\Entity\Song\Song;
  32. use App\Entity\User\User;
  33. use App\Enums\Constants;
  34. use App\Enums\Platforms;
  35. use App\Enums\RoyaltyDueType;
  36. use App\Enums\RoyaltyImporterFileStatus;
  37. use App\Enums\RoyaltyImporterFileType;
  38. use App\Enums\RoyaltyRawDataStatus;
  39. use App\Factory\EntityFactory;
  40. use App\Repository\App\CountryRepository;
  41. use App\Repository\Composition\CompositionRepository;
  42. use App\Repository\Composition\SongWriterRepository;
  43. use App\Repository\Profile\Splits\RoyaltyConsolidationRepository;
  44. use App\Repository\Profile\Splits\RoyaltyDueAdjustRepository;
  45. use App\Repository\Profile\Splits\RoyaltyDueRepository;
  46. use App\Repository\Profile\Splits\RoyaltyImporterFileRepository;
  47. use App\Repository\Publishing\PlatformRepository;
  48. use App\Service\ClickHouse\DataManager\IncomeRawDataCHManagerService;
  49. use App\Service\ClickHouse\DataManager\RawDataDailyCHManagerService;
  50. use App\Service\ClickHouse\DataManager\RawDataIncompleteCHManagerService;
  51. use App\Service\Feeds\MLC\MLCFeedService;
  52. use App\Service\FileService;
  53. use App\Service\GeneralService;
  54. use App\Service\ProfileService;
  55. use App\Service\RedisCaching\RedisDataManagerService;
  56. use App\Service\SongService;
  57. use Doctrine\ORM\EntityManagerInterface;
  58. use Psr\Log\LoggerInterface;
  59. use Ramsey\Uuid\Uuid;
  60. use Symfony\Component\HttpFoundation\File\UploadedFile;
  61. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  62. use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
  63. use Symfony\Component\Serializer\SerializerInterface;
  64. class RoyaltyImporterFileService
  65. {
  66.     /** @var array */
  67.     private $dataConsolidated = [];
  68.     /** @var array */
  69.     private $rawDataProcessed = [];
  70.     /** @var array */
  71.     private $incomeDataConsolidated = [];
  72.     /** @var EntityManagerInterface */
  73.     private $entityManager;
  74.     /** @var SerializerInterface */
  75.     private $serializer;
  76.     /** @var EntityFactory */
  77.     private $entityFactory;
  78.     /** @var RoyaltyImporterFileRepository */
  79.     private $royaltyImporterFileRepository;
  80.     /** @var RoyaltyDueRepository */
  81.     private $royaltyDueRepository;
  82.     /** @var RoyaltyConsolidationRepository */
  83.     private $royaltyConsolidationRepository;
  84.     /** @var RoyaltyDueAdjustRepository */
  85.     private $royaltyDueAdjustRepository;
  86.     /** @var PlatformRepository */
  87.     private $platformRepository;
  88.     /** @var CountryRepository */
  89.     private $countryRepository;
  90.     /** @var SongWriterRepository  */
  91.     private $songWriterRepository;
  92.     /** @var CompositionRepository */
  93.     private $compositionRepository;
  94.     /** @var GeneralService */
  95.     private $generalService;
  96.     /** @var FileService */
  97.     private $fileService;
  98.     /** @var RedisDataManagerService */
  99.     private $redisDataManagerService;
  100.     /** @var RawDataDailyCHManagerService */
  101.     private $rawDataDailyCHManagerService;
  102.     /** @var RawDataIncompleteCHManagerService */
  103.     private $rawDataIncompleteCHManagerService;
  104.     /** @var IncomeRawDataCHManagerService */
  105.     private $incomeRawDataCHManagerService;
  106.     /** @var RoyaltyImporterFileMCPSService */
  107.     private $royaltyImporterFileMCPSService;
  108.     /** @var RoyaltyImporterFileMLCService */
  109.     private $royaltyImporterFileMLCService;
  110.     /** @var RoyaltyImporterFilePRSService */
  111.     private $royaltyImporterFilePRSService;
  112.     /** @var SongService */
  113.     private $songService;
  114.     /** @var LoggerInterface */
  115.     private $logger;
  116.     public function __construct(
  117.         SerializerInterface $serializer,
  118.         EntityManagerInterface $entityManager,
  119.         EntityFactory $entityFactory,
  120.         RoyaltyImporterFileRepository $royaltyImporterFileRepository,
  121.         RoyaltyDueRepository $royaltyDueRepository,
  122.         RoyaltyDueAdjustRepository $royaltyDueAdjustRepository,
  123.         RoyaltyConsolidationRepository $royaltyConsolidationRepository,
  124.         PlatformRepository $platformRepository,
  125.         CountryRepository $countryRepository,
  126.         SongWriterRepository $songWriterRepository,
  127.         CompositionRepository $compositionRepository,
  128.         FileService $fileService,
  129.         GeneralService $generalService,
  130.         SongService $songService,
  131.         LoggerInterface $logger,
  132.         RedisDataManagerService $redisDataManagerService,
  133.         RawDataDailyCHManagerService $rawDataDailyCHManagerService,
  134.         RawDataIncompleteCHManagerService $rawDataIncompleteCHManagerService,
  135.         IncomeRawDataCHManagerService $incomeRawDataCHManagerService,
  136.         RoyaltyImporterFileMCPSService $royaltyImporterFileMCPSService,
  137.         RoyaltyImporterFileMLCService $royaltyImporterFileMLCService,
  138.         RoyaltyImporterFilePRSService $royaltyImporterFilePRSService
  139.     )
  140.     {
  141.         $this->serializer $serializer;
  142.         $this->entityManager $entityManager;
  143.         $this->entityFactory $entityFactory;
  144.         $this->royaltyImporterFileRepository $royaltyImporterFileRepository;
  145.         $this->royaltyDueRepository $royaltyDueRepository;
  146.         $this->royaltyDueAdjustRepository $royaltyDueAdjustRepository;
  147.         $this->royaltyConsolidationRepository $royaltyConsolidationRepository;
  148.         $this->platformRepository $platformRepository;
  149.         $this->countryRepository $countryRepository;
  150.         $this->songWriterRepository $songWriterRepository;
  151.         $this->compositionRepository $compositionRepository;
  152.         $this->fileService $fileService;
  153.         $this->generalService $generalService;
  154.         $this->songService $songService;
  155.         $this->logger $logger;
  156.         $this->redisDataManagerService $redisDataManagerService;
  157.         $this->rawDataDailyCHManagerService $rawDataDailyCHManagerService;
  158.         $this->rawDataIncompleteCHManagerService $rawDataIncompleteCHManagerService;
  159.         $this->incomeRawDataCHManagerService $incomeRawDataCHManagerService;
  160.         $this->royaltyImporterFileMCPSService $royaltyImporterFileMCPSService;
  161.         $this->royaltyImporterFileMLCService $royaltyImporterFileMLCService;
  162.         $this->royaltyImporterFilePRSService $royaltyImporterFilePRSService;
  163.     }
  164.     /**
  165.      * @param array $data
  166.      * @param User $user
  167.      * @param Profile $profile
  168.      * @return RoyaltyImporterFile
  169.      */
  170.     public function processToCreateRoyaltyImporterFile(
  171.         array $data,
  172.         User $user,
  173.         Profile $profile
  174.     ): RoyaltyImporterFile
  175.     {
  176.         /** @var Platform $platform */
  177.         $platform $this->platformRepository->findOneBy(["id" => $data['platform']['id']]);
  178.         /** @var RoyaltyImporterFile $royaltyImporterFile */
  179.         $royaltyImporterFile $this->entityFactory->createFromJson(
  180.             json_encode($data),
  181.             RoyaltyImporterFile::class,
  182.             ["royalty-importer-file:create"]
  183.         );
  184.         $royaltyImporterFile->setProfile($profile);
  185.         $royaltyImporterFile->setCreatedBy($user);
  186.         $royaltyImporterFile->setPlatform($platform);
  187.         switch ($platform->getName()){
  188.             case Platforms::MCPS:
  189.             case Platforms::MLC:
  190.                 $royaltyImporterFile->setType(RoyaltyImporterFileType::M);
  191.                 break;
  192.             case Platforms::PRS:
  193.                 $royaltyImporterFile->setType(RoyaltyImporterFileType::P);
  194.                 break;
  195.         }
  196.         /** @var RoyaltyImporterFile $royaltyImporterFile */
  197.         $royaltyImporterFile $this->royaltyImporterFileRepository->save($royaltyImporterFile);
  198.         return $royaltyImporterFile;
  199.     }
  200.     /**
  201.      * @param UploadedFile $uploadedFile
  202.      * @param RoyaltyImporterFile $royaltyImporterFile
  203.      * @return RoyaltyImporterFile
  204.      * @throws \League\Flysystem\FilesystemException
  205.      */
  206.     public function processToUploadTheFile(
  207.         RoyaltyImporterFile $royaltyImporterFile,
  208.         UploadedFile $uploadedFile null,
  209.         array $dataToReProcess null
  210.     )
  211.     {
  212.         $data = [];
  213.         if(!is_null($uploadedFile)){
  214.             /** @var File $file */
  215.             $file $this->fileService->upload(
  216.                 $uploadedFile,
  217.                 $royaltyImporterFile->getId(),
  218.                 RoyaltyImporterFile::class
  219.             );
  220.             /** @var RoyaltyImporterFile $royaltyImporterFileOlds */
  221.             foreach ($royaltyImporterFile->getProfile()->getRoyaltyImporterFiles() as $royaltyImporterFileOlds) {
  222.                 if (!is_null($royaltyImporterFileOlds->getFile())) {
  223.                     if ($royaltyImporterFileOlds->getFile()->getOriginalName() === $file->getOriginalName()) {
  224.                         $royaltyImporterFile->setStatus(RoyaltyImporterFileStatus::ERROR);
  225.                         $this->royaltyImporterFileRepository->flush($royaltyImporterFile);
  226.                         $this->processToDeleteRoyaltyImporterFile($royaltyImporterFile);
  227.                         throw new BadRequestHttpException("File already exists");
  228.                     }
  229.                 }
  230.             }
  231.             if ($file->getExtension() === "csv" || $file->getExtension() === "CSV") {
  232.                 $data $this->processCsvFile($file);
  233.             } else {
  234.                 $data $this->processTsvFile($file);
  235.             }
  236.             $royaltyImporterFile->setFile($file);
  237.         }
  238.         if(!is_null($dataToReProcess)){
  239.             $data $dataToReProcess;
  240.         }
  241.         $dataToCH = [];
  242.         $dataProcessed = [];
  243.         try {
  244.             switch ($royaltyImporterFile->getPlatform()->getName()) {
  245.                 case Platforms::MCPS:
  246.                     $this->royaltyImporterFileMCPSService->setDataFromFile($data);
  247.                     $dataProcessed =  $this->royaltyImporterFileMCPSService->processData($royaltyImporterFile);
  248.                     break;
  249.                 case Platforms::MLC:
  250.                     $this->royaltyImporterFileMLCService->setDataFromFile($data);
  251.                     $dataProcessed $this->royaltyImporterFileMLCService->processData($royaltyImporterFile);
  252.                     break;
  253.                 case Platforms::PRS:
  254.                     $this->royaltyImporterFilePRSService->setDataFromFile($data);
  255.                     $dataProcessed $this->royaltyImporterFilePRSService->processData($royaltyImporterFile);
  256.                     break;
  257.             }
  258.         }catch (\Exception $exception){
  259.             $royaltyImporterFile->setStatus(RoyaltyImporterFileStatus::ERROR);
  260.             $this->royaltyImporterFileRepository->flush($royaltyImporterFile);
  261.             throw new BadRequestHttpException("Please check the file");
  262.             $this->logger->info($e->getMessage() . " on line "$e->getLine(). " in " $e->getCode());
  263.         }
  264.         if(!is_null($dataToReProcess)){
  265.             if(count($dataToReProcess) <= count($dataProcessed['error'])){
  266.                 throw new BadRequestHttpException("The errors were not fixed");
  267.             }
  268.         }
  269.         $quantitySumImported 0;
  270.         $incomeSumImported 0;
  271.         /** @var RawDataCH $rawDataDailyCH */
  272.         foreach ($dataProcessed['success'] as $rawDataDailyCH) {
  273.             $quantitySumImported += (int)$rawDataDailyCH->getPerfNumber();
  274.             $incomeSumImported += (float)$rawDataDailyCH->getIncome();
  275.             $rawDataDailyCH json_decode(
  276.                 $this->serializer->serialize($rawDataDailyCH"json", ['groups' => 'clickhouse:raw-data']),
  277.                 true
  278.             );
  279.             try {
  280.                 $this->rawDataDailyCHManagerService->insertData(
  281.                     RawDataCH::TABLE_NAME,
  282.                     $rawDataDailyCH
  283.                 );
  284.             }catch (\Exception $exception){
  285.             }
  286.         }
  287.         $quantitySumError 0;
  288.         $incomeSumError 0.00;
  289.         /** @var RawDataIncompleteCH $rawDataIncompleteCH */
  290.         foreach ($dataProcessed['error'] as $rawDataIncompleteCH) {
  291.             $quantitySumError += (int)$rawDataIncompleteCH->getPerfNumber();
  292.             $incomeSumError += (float)$rawDataIncompleteCH->getIncome();
  293.             $rawDataIncompleteCH json_decode(
  294.                 $this->serializer->serialize($rawDataIncompleteCH"json", ['groups' => 'clickhouse:raw-data']),
  295.                 true
  296.             );
  297.             try {
  298.                 $this->rawDataIncompleteCHManagerService->insertData(
  299.                     RawDataIncompleteCH::TABLE_NAME,
  300.                     $rawDataIncompleteCH
  301.                 );
  302.             }catch (\Exception $exception){
  303.             }
  304.         }
  305.         if(!is_null($uploadedFile)){
  306.             $royaltyImporterFile->setTotalRows(count($data))
  307.                 ->setImportedRows(count($dataProcessed['success']))
  308.                 ->setErrorRows(count($dataProcessed['error']))
  309.                 ->setQuantitySumImported($quantitySumImported)
  310.                 ->setIncomeSumImported($incomeSumImported)
  311.                 ->setQuantitySumError($quantitySumError)
  312.                 ->setIncomeSumError($incomeSumError)
  313.                 ->setQuantitySum($quantitySumError $quantitySumImported)
  314.                 ->setIncomeSum($incomeSumError $incomeSumImported);
  315.             if(count($dataProcessed['rowWithErrors']) > && $dataProcessed['error'] > 0){
  316.                 $royaltyImporterFile->setErrorFile($this->processToCreateAnErrorFile(
  317.                     $dataProcessed['rowWithErrors'],
  318.                     $dataProcessed['error'],
  319.                     $royaltyImporterFile
  320.                 ));
  321.             }
  322.         }
  323.         if(!is_null($dataToReProcess)){
  324.             $errorRows $royaltyImporterFile->getErrorRows() - count($dataProcessed['success']);
  325.             $quantitySumError $royaltyImporterFile->getQuantitySumError() - $quantitySumImported;
  326.             $incomeSumError $royaltyImporterFile->getIncomeSumError() - $incomeSumImported;
  327.             $royaltyImporterFile->setImportedRows($royaltyImporterFile->getImportedRows() + count($dataProcessed['success']))
  328.                 ->setErrorRows($errorRows)
  329.                 ->setQuantitySumImported($royaltyImporterFile->getQuantitySumImported() + $quantitySumImported)
  330.                 ->setIncomeSumImported($royaltyImporterFile->getIncomeSumImported() + $incomeSumImported)
  331.                 ->setQuantitySumError($quantitySumError)
  332.                 ->setIncomeSumError($incomeSumError);
  333.             if(count($dataProcessed['rowWithErrors']) > && $dataProcessed['error'] > 0){
  334.                 $royaltyImporterFile->setErrorFile($this->processToCreateAnErrorFile(
  335.                     $dataProcessed['rowWithErrors'],
  336.                     $dataProcessed['error'],
  337.                     $royaltyImporterFile
  338.                 ));
  339.             }
  340.         }
  341.         if($royaltyImporterFile->getTotalRows() === $royaltyImporterFile->getErrorRows()){
  342.             $royaltyImporterFile->setStatus(RoyaltyImporterFileStatus::ERROR);
  343.         }else{
  344.             if(is_null($dataToReProcess)){
  345.                 $royaltyImporterFile->setStatus(RoyaltyImporterFileStatus::IMPORTED);
  346.             }
  347.         }
  348.         $this->royaltyImporterFileRepository->flush($royaltyImporterFile);
  349.         /** @var RoyaltyImporterFile $royaltyImporterFile */
  350.         $royaltyImporterFile $this->royaltyImporterFileRepository->find($royaltyImporterFile->getId());
  351.         return $royaltyImporterFile;
  352.     }
  353.     /**
  354.      * @param RoyaltyImporterFile $royaltyImporterFile
  355.      * @param array $data
  356.      * @return RoyaltyImporterFile
  357.      */
  358.     public function processToEditRoyaltyImporterFile(
  359.         RoyaltyImporterFile $royaltyImporterFile,
  360.         array $data
  361.     ): RoyaltyImporterFile
  362.     {
  363.         /** @var RoyaltyImporterFile $royaltyImporterFile */
  364.         $royaltyImporterFile $this->entityFactory->createFromJson(
  365.             json_encode($data),
  366.             RoyaltyImporterFile::class,
  367.             ["royalty-importer-file:edit"],
  368.             [AbstractObjectNormalizer::OBJECT_TO_POPULATE => $royaltyImporterFile,]
  369.         );
  370.         if(!isset($data['tax_country'])){
  371.             throw new BadRequestHttpException("Tax Country is required");
  372.         }
  373.         $country $this->countryRepository->find($data['tax_country']['id']);
  374.         $royaltyImporterFile->setTaxPercentage($royaltyImporterFile->getTaxPercentage()/100);
  375.         $royaltyImporterFile->setTaxCountry($country);
  376.         $royaltyImporterFile->setIncomeConversionRate($royaltyImporterFile->getGbp() / $royaltyImporterFile->getIncomeSumImported());
  377.         $royaltyImporterFile->setStatus(RoyaltyImporterFileStatus::DISTRIBUTED);
  378.         $this->royaltyImporterFileRepository->flush($royaltyImporterFile);
  379.         /** @var RoyaltyImporterFile $royaltyImporterFile */
  380.         $royaltyImporterFile $this->royaltyImporterFileRepository->find($royaltyImporterFile->getId());
  381.         return $royaltyImporterFile;
  382.     }
  383.     /**
  384.      * @param RoyaltyImporterFile $royaltyImporterFile
  385.      * @param bool $reImportation
  386.      * @return void
  387.      */
  388.     public function processToDeleteRoyaltyImporterFile(
  389.         RoyaltyImporterFile $royaltyImporterFile,
  390.         bool $reImportation false
  391.     ): void
  392.     {
  393.         $this->rawDataDailyCHManagerService->deleteData(
  394.             RawDataCH::TABLE_NAME,
  395.             ['report_id' => $royaltyImporterFile->getId()]
  396.         );
  397.         $this->rawDataIncompleteCHManagerService->deleteData(
  398.             RawDataIncompleteCH::TABLE_NAME,
  399.             ['report_id' => $royaltyImporterFile->getId()]
  400.         );
  401.         $this->incomeRawDataCHManagerService->deleteData(
  402.             IncomeRawDataCH::TABLE_NAME,
  403.             ['report_id' => $royaltyImporterFile->getId()]
  404.         );
  405.         /** @var RoyaltyDue $rawDataDue */
  406.         foreach ($this->royaltyDueRepository->findBy(['royaltyImporterFile' => $royaltyImporterFile]) as $rawDataDue) {
  407.             $this->royaltyDueRepository->remove($rawDataDue);
  408.             $this->royaltyDueRepository->flush();
  409.         }
  410.         $file $royaltyImporterFile->getFile();
  411.         $errorFile $royaltyImporterFile->getErrorFile();
  412.         if(!$reImportation){
  413.             $this->royaltyImporterFileRepository->remove($royaltyImporterFile);
  414.             $this->royaltyImporterFileRepository->flush();
  415.         }else{
  416.             $royaltyImporterFile->setFile(null);
  417.             $royaltyImporterFile->setErrorFile(null);
  418.             $this->royaltyImporterFileRepository->flush();
  419.         }
  420.         /*if($file){
  421.             $this->fileService->delete($file);
  422.         }
  423.         if($errorFile){
  424.             $this->fileService->delete($errorFile);
  425.         }*/
  426.     }
  427.     /**
  428.      * @param RoyaltyImporterFile $royaltyImporterFile
  429.      * @return void
  430.      */
  431.     public function processToCalculateRoyalties(RoyaltyImporterFile $royaltyImporterFile)
  432.     {
  433.         $royaltySE null;
  434.         $royaltyPA null;
  435.         $royaltySW null;
  436.         $royaltyPU null;
  437.         $data $this->rawDataDailyCHManagerService->getDataFromTable(
  438.             RawDataDailyCHManagerService::NAME,
  439.             ['*'],
  440.             [
  441.                 'report_id' => $royaltyImporterFile->getId(),
  442.                 'status'    => RoyaltyRawDataStatus::READING,
  443.             ]
  444.         );
  445.         $taxPercentege = (is_null($royaltyImporterFile->getTaxPercentage())) ? $royaltyImporterFile->getTaxPercentage();
  446.         $taxAmount = (is_null($royaltyImporterFile->getTaxAmount())) ? $royaltyImporterFile->getTaxAmount();
  447.         foreach($data  as $raw => $value){
  448.             $income = (float)$value['income'] * $royaltyImporterFile->getIncomeConversionRate();
  449.             $incomeGBP $income;
  450.             $incomePA 0;
  451.             $incomePU 0;
  452.             $incomeSW 0;
  453.             $incomeSe 0;
  454.             $songwritersArray json_decode($value['songwriters'], true);
  455.             $incomeExternal =  0.00;
  456.             foreach ($songwritersArray['external'] as $songwriterId){
  457.                 $songwriterRedis $this->redisDataManagerService->getSongWriterById($songwriterId);
  458.                 /** income here is updated with the percentage to songwriter, this is calculated with the songwriter composition share */
  459.                 $incomeExternal += $income * ((float)$songwriterRedis['share'] / 100);
  460.             }
  461.             foreach ($songwritersArray['internal'] as $songwriterId){
  462.                 $songwriterRedis $this->redisDataManagerService->getSongWriterById($songwriterId);
  463.                 /** @var Profile $profile */
  464.                 $profile $this->generalService->findProfileById($songwriterRedis['profile_id']);
  465.                 /** @var Profile $profilePAMysql */
  466.                 $profilePAMysql $this->generalService->findProfileById($profile->getPublisherAdministratorData()['id']);
  467.                 $royaltyPA $profilePAMysql->getRoyaltySplits();
  468.                 /** income here is updated with the percentage to songwriter, this is calculated with the songwriter composition share */
  469.                 if(count($songwritersArray['internal']) > 0){
  470.                     $income = ($income * ((float)$songwriterRedis['share'] / 100)) + ($incomeExternal count($songwritersArray['internal']));
  471.                 }else{
  472.                     $income $income * ((float)$songwriterRedis['share'] / 100);
  473.                 }
  474.                 $incomeShare $income;
  475.                 /** incomeSe is the value that this publisher administrator share with the Service */
  476.                 $incomeService $income * ($this->getRoyaltyPercentage($royaltyImporterFile$royaltyPAtrue) / 100);
  477.                 $income -= $incomeService;
  478.                 $id $value['id'] + $raw 1;
  479.                 $incomeRawData = (new IncomeRawDataCH())
  480.                     ->setId($id)
  481.                     ->setRawDataId($value['id'])
  482.                     ->setReportId($value['report_id'])
  483.                     ->setOldId($value['old_id'])
  484.                     ->setCompositionId($value['composition_id'])
  485.                     ->setSongWriterId($songwriterRedis['id'])
  486.                     ->setProfileId($profile->getId())
  487.                     ->setIncomeTotalGbp($incomeGBP)
  488.                     ->setShare((float)$songwriterRedis['share'] / 100)
  489.                     ->setIncomeTotalGbpShare($incomeShare)
  490.                     ->setTaxPercentage($taxPercentege)
  491.                     ->setTaxAmount($incomeShare $taxPercentege)
  492.                     ->setIncomeTotalGbpShareNet($incomeShare - ($incomeShare $taxPercentege))
  493.                     ->setIncomeSE($incomeService)
  494.                     ->setIncomeSeNet($incomeService - ($incomeService $taxPercentege))
  495.                     ->setConsolidated(0);
  496.                 $royaltySW $profile->getRoyaltySplits();
  497.                 if(is_null($royaltySW)){
  498.                     throw new BadRequestHttpException("Royalty SPLIT is not set for the profile {$profile->getProfileInformation()->getName()}");
  499.                 }
  500.                 if($profile->getParent()->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER){
  501.                     $royaltyPU $profile->getParent()->getRoyaltySplits();
  502.                     /** incomePA is the value that this publisher share with the Publisher Administrator */
  503.                     $incomePA $income * ($this->getRoyaltyPercentage($royaltyImporterFile$royaltyPUtrue) / 100);
  504.                     $income -= $incomePA;
  505.                     /** incomeSW is the songwriter income */
  506.                     $incomeSW $income * ($this->getRoyaltyPercentage($royaltyImporterFile$royaltySW) / 100);
  507.                     $income -= $incomeSW;
  508.                     /** incomePU is the value that this songwriter share with the Publisher */
  509.                     $incomePU $income;
  510.                 }else{
  511.                     /** incomePA is the value that this songwriter share with the Publisher Administrator */
  512.                     $incomePA $income * ($this->getRoyaltyPercentage($royaltyImporterFile$royaltySWtrue) / 100);
  513.                     $income -= $incomePA;
  514.                     /** incomeSW is the songwriter income */
  515.                     $incomeSW $income;
  516.                 }
  517.                 $incomeRawData->setIncomePA($incomePA)
  518.                     ->setIncomePaNet($incomePA - ($incomePA $taxPercentege))
  519.                     ->setIncomeSW($incomeSW)
  520.                     ->setIncomeSWNet($incomeSW - ($incomeSW $taxPercentege))
  521.                     ->setIncomePU($incomePU)
  522.                     ->setIncomePUNet($incomePU - ($incomePU $taxPercentege));
  523.                 $incomeRawData $this->serializer->serialize(
  524.                     $incomeRawData,
  525.                     "json",
  526.                     ['groups' => 'clickhouse:income-raw-data']
  527.                 );
  528.                 $incomeRawData json_decode($incomeRawDatatrue);
  529.                 $this->incomeRawDataCHManagerService->insertData(
  530.                     IncomeRawDataCH::TABLE_NAME,
  531.                     $incomeRawData
  532.                 );
  533.                 $royaltyPU null;
  534.                 $royaltySW null;
  535.                 /** The income return to the initial value to do the calculation to the next songwriter */
  536.                 $income $incomeGBP;
  537.             }
  538.         }
  539.         $this->flushRawDateProcessed($royaltyImporterFile);
  540.     }
  541.     /**
  542.      * @param RoyaltyImporterFile $royaltyImporterFile
  543.      * @return void
  544.      */
  545.     public function processToCalculateRoyaltiesForPRS(RoyaltyImporterFile $royaltyImporterFile)
  546.     {
  547.         $royaltySE null;
  548.         $royaltyPA null;
  549.         $royaltySW null;
  550.         $royaltyPU null;
  551.         $data $this->rawDataDailyCHManagerService->getDataFromTable(
  552.             RawDataDailyCHManagerService::NAME,
  553.             ['*'],
  554.             [
  555.                 'report_id' => $royaltyImporterFile->getId(),
  556.                 'status'    => RoyaltyRawDataStatus::READING,
  557.             ]
  558.         );
  559.         $taxPercentege = (is_null($royaltyImporterFile->getTaxPercentage())) ? $royaltyImporterFile->getTaxPercentage();
  560.         $taxAmount = (is_null($royaltyImporterFile->getTaxAmount())) ? $royaltyImporterFile->getTaxAmount();
  561.         foreach($data  as $raw => $value){
  562.             $income = (float)$value['income'] * $royaltyImporterFile->getIncomeConversionRate();
  563.             $incomeGBP $income;
  564.             $incomePA 0;
  565.             $incomePU 0;
  566.             $incomeSW 0;
  567.             $incomeSe 0;
  568.             $incomeRawDataArray = [];
  569.             $songwritersArray json_decode($value['songwriters'], true);
  570.             $incomeExternal =  0.00;
  571.             foreach ($songwritersArray['external'] as $songwriterId){
  572.                 $songwriterRedis $this->redisDataManagerService->getSongWriterById($songwriterId);
  573.                 /** income here is updated with the percentage to songwriter, this is calculated with the songwriter composition share */
  574.                 $incomeExternal += $income * ((float)$songwriterRedis['share'] / 100);
  575.             }
  576.             foreach ($songwritersArray['internal'] as $songwriterId){
  577.                 $songwriterRedis $this->redisDataManagerService->getSongWriterById($songwriterId);
  578.                 if(!is_null($songwriterRedis['profile_id']) && !empty($songwriterRedis['profile_id'])){
  579.                     /** @var Profile $profile */
  580.                     $profile $this->generalService->findProfileById($songwriterRedis['profile_id']);
  581.                     /** @var Profile $profilePAMysql */
  582.                     $profilePAMysql $this->generalService->findProfileById($profile->getPublisherAdministratorData()['id']);
  583.                     $royaltyPA $profilePAMysql->getRoyaltySplits();
  584.                     /** income here is updated with the percentage to songwriter, this is calculated with the songwriter composition share */
  585.                     $income = (($income) * ((float)$songwriterRedis['share'] / 100)) + ($incomeExternal count($songwritersArray['internal']));
  586.                     $incomeShare $income;
  587.                     /** incomeSe is the value that this publisher administrator share with the Service */
  588.                     $incomeService $income * ($this->getRoyaltyPercentage($royaltyImporterFile$royaltyPAtrue) / 100);
  589.                     $income -= $incomeService;
  590.                     $id $value['id'] + $raw 1;
  591.                     $incomeRawData = (new IncomeRawDataCH())
  592.                         ->setId($id)
  593.                         ->setRawDataId($value['id'])
  594.                         ->setReportId($value['report_id'])
  595.                         ->setOldId($value['old_id'])
  596.                         ->setCompositionId($value['composition_id'])
  597.                         ->setSongWriterId($songwriterRedis['id'])
  598.                         ->setProfileId($profile->getId())
  599.                         ->setIncomeTotalGbp($incomeGBP)
  600.                         ->setShare((float)$songwriterRedis['share'] / 100)
  601.                         ->setIncomeTotalGbpShare($incomeShare)
  602.                         ->setTaxPercentage($taxPercentege)
  603.                         ->setTaxAmount($incomeShare $taxPercentege)
  604.                         ->setIncomeTotalGbpShareNet($incomeShare - ($incomeShare $taxPercentege))
  605.                         ->setIncomeSE($incomeService)
  606.                         ->setIncomeSeNet($incomeService - ($incomeService $taxPercentege))
  607.                         ->setConsolidated(0);
  608.                     $royaltySW $profile->getRoyaltySplits();
  609.                     if(is_null($royaltySW)){
  610.                         throw new BadRequestHttpException("Royalty SPLIT is not set for the profile {$profile->getProfileInformation()->getName()}");
  611.                     }
  612.                     if($profile->getParent()->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER){
  613.                         $royaltyPU $profile->getParent()->getRoyaltySplits();
  614.                         if((float)$value['publisher_administrator_share'] === 100.00){
  615.                             /** incomePA is the value that this publisher share with the Publisher Administrator */
  616.                             $incomePA $income * ($this->getRoyaltyPercentage($royaltyImporterFile$royaltyPUtrue) / 100);
  617.                             $income -= $incomePA;
  618.                             /** incomeSW is the songwriter income */
  619.                             $incomeSW $income * ($this->getRoyaltyPercentage($royaltyImporterFile$royaltySW) / 100);
  620.                             $income -= $incomeSW;
  621.                             /** incomePU is the value that this songwriter share with the Publisher */
  622.                             $incomePU $income;
  623.                         }else{
  624.                             /** incomePA is the value that this publisher share with the Publisher Administrator */
  625.                             $incomePA $income;
  626.                         }
  627.                     }else{
  628.                         if((float)$value['publisher_administrator_share'] === 100.00){
  629.                             /** incomePA is the value that this songwriter share with the Publisher Administrator */
  630.                             $incomePA $income * ($this->getRoyaltyPercentage($royaltyImporterFile$royaltySWtrue) / 100);
  631.                             $income -= $incomePA;
  632.                             /** incomeSW is the songwriter income */
  633.                             $incomeSW $income;
  634.                         }else{
  635.                             /** incomePA is the value that this songwriter share with the Publisher Administrator */
  636.                             $incomePA $income;
  637.                         }
  638.                     }
  639.                     $incomeRawData->setIncomePA($incomePA)
  640.                         ->setIncomePaNet($incomePA - ($incomePA $taxPercentege))
  641.                         ->setIncomeSW($incomeSW)
  642.                         ->setIncomeSWNet($incomeSW - ($incomeSW $taxPercentege))
  643.                         ->setIncomePU($incomePU)
  644.                         ->setIncomePUNet($incomePU - ($incomePU $taxPercentege));
  645.                     $incomeRawData $this->serializer->serialize(
  646.                         $incomeRawData,
  647.                         "json",
  648.                         ['groups' => 'clickhouse:income-raw-data']
  649.                     );
  650.                     $incomeRawData json_decode($incomeRawDatatrue);
  651.                     $incomeRawDataArray[] = $incomeRawData;
  652.                     $this->incomeRawDataCHManagerService->insertData(
  653.                         IncomeRawDataCH::TABLE_NAME,
  654.                         $incomeRawData
  655.                     );
  656.                 }
  657.                 $royaltyPU null;
  658.                 $royaltySW null;
  659.                 /** The income return to the initial value to do the calculation to the next songwriter */
  660.                 $income $incomeGBP;
  661.             }
  662.         }
  663.         $this->flushRawDateProcessed($royaltyImporterFile);
  664.     }
  665.     /**
  666.      * @param RoyaltyImporterFile $royaltyImporterFile
  667.      * @param bool $reImport
  668.      * @return void
  669.      */
  670.     public function processToConsolidateOutstandingRoyalties(
  671.         RoyaltyImporterFile $royaltyImporterFile,
  672.         bool $reImport false
  673.     ): void
  674.     {
  675.         $data $this->incomeRawDataCHManagerService->getDataFromTable(
  676.             IncomeRawDataCHManagerService::NAME,
  677.             ['*'],
  678.             [
  679.                 'report_id'     => $royaltyImporterFile->getId(),
  680.                 'consolidated'  => 0
  681.             ]
  682.         );
  683.         foreach($data  as $raw => $value){
  684.             //echo $raw."\n";
  685.             $grossIncome = (float)$value['income_total_gbp'];
  686.             $income = (float)$value['income_total_gbp_share'];
  687.             $incomeNet = (float)$value['income_total_gbp_share_net'];
  688.             $profile $this->generalService->findProfileById((int)$value['profile_id']);
  689.             $royaltyDue $this->processToCreateOrUpdateRoyaltyConsolidation(
  690.                 $profile,
  691.                 $royaltyImporterFile,
  692.                 [
  693.                     'type'          => RoyaltyDueType::IMPORTED,
  694.                     'amount'        => (float)$value['income_sw'],
  695.                     'amountNet'     => (float)$value['income_sw_net'],
  696.                     'description'   => "Imported Royalties for {$royaltyImporterFile->getDateFrom()->format("M")} {$royaltyImporterFile->getDateFrom()->format("Y")}",
  697.                     'grossIncome'   => $grossIncome,
  698.                     'income'        => $income,
  699.                     'incomeNet'     => $incomeNet
  700.                 ]
  701.             );
  702.             $allParentProfile $this->generalService->findAllParentProfiles($profile);
  703.             /** @var Profile $parentProfile */
  704.             foreach ($allParentProfile as $parentProfile){
  705.                 $dataDue = [];
  706.                 if($parentProfile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER){
  707.                     $dataDue = [
  708.                         'type'          => RoyaltyDueType::IMPORTED,
  709.                         'amount'        => (float)$value['income_pu'],
  710.                         'amountNet'     => (float)$value['income_pu_net'],
  711.                         'description'   => "Imported Royalties for {$royaltyImporterFile->getDateFrom()->format("M")} {$royaltyImporterFile->getDateFrom()->format("Y")}",
  712.                         'grossIncome'   => $grossIncome,
  713.                         'income'        => $income,
  714.                         'incomeNet'     => $incomeNet
  715.                     ];
  716.                 }else if($parentProfile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR){
  717.                     $dataDue = [
  718.                         'type'          => RoyaltyDueType::IMPORTED,
  719.                         'amount'        => (float)$value['income_pa'],
  720.                         'amountNet'     => (float)$value['income_pa_net'],
  721.                         'description'   => "Imported Royalties for {$royaltyImporterFile->getDateFrom()->format("M")} {$royaltyImporterFile->getDateFrom()->format("Y")}",
  722.                         'grossIncome'   => $grossIncome,
  723.                         'income'        => $income,
  724.                         'incomeNet'     => $incomeNet
  725.                     ];
  726.                 }else{
  727.                     $dataDue = [
  728.                         'type'          => RoyaltyDueType::IMPORTED,
  729.                         'amount'        => (float)$value['income_se'],
  730.                         'amountNet'     => (float)$value['income_se_net'],
  731.                         'description'   => "Imported Royalties for {$royaltyImporterFile->getDateFrom()->format("M")} {$royaltyImporterFile->getDateFrom()->format("Y")}",
  732.                         'grossIncome'   => $grossIncome,
  733.                         'income'        => $income,
  734.                         'incomeNet'     => $incomeNet
  735.                     ];
  736.                 }
  737.                 $royaltyDue $this->processToCreateOrUpdateRoyaltyConsolidation(
  738.                     $parentProfile,
  739.                     $royaltyImporterFile,
  740.                     $dataDue
  741.                 );
  742.             }
  743.         }
  744.         $this->flushDataConsolidated($royaltyImporterFile);
  745.         $this->flushIncomeDataConsolidated($royaltyImporterFile);
  746.         if($reImport){
  747.             if($royaltyImporterFile->getPlatform()->getName() === Platforms::MLC){
  748.                 $income 0;
  749.                 $incomeNet 0;
  750.                 /** @var RoyaltyDue $royaltyDue */
  751.                 foreach ($this->royaltyDueRepository->findBy(['royaltyImporterFile' => $royaltyImporterFile]) as $royaltyDue){
  752.                     if($royaltyDue->getProfile()->getProfileType()->getName() === Constants::PROFILE_TYPE_SERVICE){
  753.                         $income $royaltyDue->getIncomeAmount();
  754.                         $incomeNet $royaltyDue->getIncomeAmountNet();
  755.                     }
  756.                 }
  757.                 /** @var RoyaltyDue $royaltyDue */
  758.                 foreach ($this->royaltyDueRepository->findBy(['royaltyImporterFile' => $royaltyImporterFile]) as $royaltyDue){
  759.                     if($royaltyDue->getProfile()->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR){
  760.                         $royaltyDue->setIncomeAmountNet($incomeNet);
  761.                         $royaltyDue->setIncomeAmount($income);
  762.                         $this->royaltyDueRepository->flush($royaltyDue);
  763.                     }
  764.                 }
  765.             }
  766.         }
  767.     }
  768.     /**
  769.      * @param Profile $profile
  770.      * @param RoyaltyImporterFile $royaltyImporterFile
  771.      * @param array $data
  772.      * @return RoyaltyDue|object|null
  773.      */
  774.     public function processToCreateOrUpdateRoyaltyConsolidation(
  775.         Profile $profile,
  776.         RoyaltyImporterFile $royaltyImporterFile,
  777.         array $data
  778.     )
  779.     {
  780.         $year = (int)$royaltyImporterFile->getEnteredAt()->format("Y");
  781.         $month = (int)$royaltyImporterFile->getEnteredAt()->format("m");
  782.         $cacheKey sprintf('%d-%d-%d'$profile->getId(), $royaltyImporterFile->getId(), $year 100 $month);
  783.         if (!isset($this->dataConsolidated[$cacheKey])) {
  784.             $royaltyDue $this->royaltyDueRepository->findOneBy([
  785.                 'profile'               => $profile,
  786.                 'royaltyImporterFile'   => $royaltyImporterFile,
  787.                 'year'                  => $year,
  788.                 'month'                 => $month
  789.             ]);
  790.             $this->dataConsolidated[$cacheKey] = $royaltyDue ?: 'none';
  791.         }
  792.         $royaltyDue $this->dataConsolidated[$cacheKey] !== 'none' $this->dataConsolidated[$cacheKey] : null;
  793.         if(
  794.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SONGWRITER ||
  795.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER
  796.         ){
  797.             if($royaltyImporterFile->getPlatform()->getName() === Platforms::PRS){
  798.                 if($data['amount'] === 0.00){
  799.                     return $royaltyDue;
  800.                 }
  801.             }
  802.         }
  803.         if(is_null($royaltyDue)){
  804.             $royaltyDue = (new RoyaltyDue())
  805.                 ->setProfile($profile)
  806.                 ->setRoyaltyImporterFile($royaltyImporterFile)
  807.                 ->setType($data['type'])
  808.                 ->setEarningAmount($data['amount'])
  809.                 ->setEarningAmountNet($data['amountNet'])
  810.                 ->setIncomeAmount($data['income'])
  811.                 ->setIncomeAmountNet($data['incomeNet'])
  812.                 ->setDescription($data['description'])
  813.                 ->setMonth((int)$royaltyImporterFile->getEnteredAt()->format("m"))
  814.                 ->setYear((int)$royaltyImporterFile->getEnteredAt()->format("Y"))
  815.                 ->setDatePaid($royaltyImporterFile->getEnteredAt());
  816.             $royaltyDue $this->royaltyDueRepository->save($royaltyDue);
  817.             $this->dataConsolidated[$cacheKey] = $royaltyDue;
  818.         }else{
  819.             $amount $royaltyDue->getEarningAmount() + $data['amount'];
  820.             $amountNet $royaltyDue->getEarningAmountNet() + $data['amountNet'];
  821.             $income $royaltyDue->getIncomeAmount() + $data['income'];
  822.             $incomeNet $royaltyDue->getIncomeAmountNet() + $data['incomeNet'];
  823.             $royaltyDue->setIncomeAmount($income);
  824.             $royaltyDue->setIncomeAmountNet($incomeNet);
  825.             $royaltyDue->setEarningAmount($amount);
  826.             $royaltyDue->setEarningAmountNet($amountNet);
  827.             $this->dataConsolidated[$cacheKey] = $royaltyDue;
  828.         }
  829.         /*if($profile->getId() === 2) {
  830.             echo "{$data['income']},{$data['incomeNet']},{$royaltyDue->getIncomeAmount()} \n";
  831.         }*/
  832.         return $royaltyDue;
  833.     }
  834.     /**
  835.      * @param array $data
  836.      * @param Profile $profile
  837.      * @return RoyaltyDueAdjust
  838.      */
  839.     public function processToCreateRoyaltyDueAdjust(array $dataProfile $profile): RoyaltyDueAdjust
  840.     {
  841.         /** @var RoyaltyDueAdjust $royaltyDueAdjust */
  842.         $royaltyDueAdjust $this->entityFactory->createFromJson(
  843.             json_encode($data),
  844.             RoyaltyDueAdjust::class,
  845.             ["royalty-adjust:create"]
  846.         );
  847.         $royaltyDueAdjust->setPayerUser($this->generalService->findTheCurrentUser());
  848.         $publisherAdministrator null;
  849.         /** @var Profile $parentProfile */
  850.         foreach ($this->generalService->findAllParentProfiles($profile) as $parentProfile){
  851.             if($profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SONGWRITER ||
  852.                 $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER){
  853.                 if($parentProfile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR){
  854.                     $publisherAdministrator $parentProfile;
  855.                 }
  856.             }else{
  857.                 if($parentProfile->getProfileType()->getName() === Constants::PROFILE_TYPE_SERVICE){
  858.                     $publisherAdministrator $parentProfile;
  859.                 }
  860.             }
  861.         }
  862.         if($profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SERVICE){
  863.             $publisherAdministrator $profile;
  864.         }
  865.         switch ($data['type']){
  866.             case RoyaltyDueType::PAYMENT:
  867.             case RoyaltyDueType::OTHER_PAYMENT:
  868.             case RoyaltyDueType::ROYALTY_PAYMENT:
  869.                 $royaltyDueAdjust->setPayerProfile($profile);
  870.                 $royaltyDueAdjust->setReceiverProfile($publisherAdministrator);
  871.                 break;
  872.             case RoyaltyDueType::RETURN_PAYMENT:
  873.             case RoyaltyDueType::OTHER_RECEIVED_PAYMENT:
  874.                 $royaltyDueAdjust->setPayerProfile($publisherAdministrator);
  875.                 $royaltyDueAdjust->setReceiverProfile($profile);
  876.                 break;
  877.         }
  878.         /** @var RoyaltyDueAdjust $royaltyDueAdjust */
  879.         $royaltyDueAdjust =$this->royaltyDueAdjustRepository->save($royaltyDueAdjust);
  880.         return $royaltyDueAdjust;
  881.     }
  882.     /**
  883.      * @param int $id
  884.      * @return RoyaltyDue|null
  885.      */
  886.     public function getRoyaltyDueById(int $id)
  887.     {
  888.         return $this->royaltyDueRepository->find($id);
  889.     }
  890.     /**
  891.      * @param int $id
  892.      * @return RoyaltyDueAdjust|null
  893.      */
  894.     public function getRoyaltyAdjustById(int $id)
  895.     {
  896.         return $this->royaltyDueAdjustRepository->find($id);
  897.     }
  898.     /**
  899.      * @param int $id
  900.      * @param Profile $profile
  901.      * @return array
  902.      */
  903.     public function getDateIntervalInRoyaltyAdjust(int $idProfile $profile)
  904.     {
  905.         $currentAdjust $this->getRoyaltyAdjustById($id);
  906.         $adjustCollection $this->royaltyDueAdjustRepository->createQueryBuilder("rda")
  907.             ->where('rda.payerProfile = :payerProfile')
  908.             ->andWhere('rda.type = :type')
  909.             ->andWhere('rda.datePaid < :value')
  910.             ->setParameter('payerProfile'$profile)
  911.             ->setParameter('type'$currentAdjust->getType())
  912.             ->setParameter('value'$currentAdjust->getDatePaid())
  913.             ->orderBy('rda.datePaid''DESC')
  914.             ->getQuery()
  915.             ->getResult();
  916.         if(isset($adjustCollection[0])){
  917.             return [
  918.                 'from'  => $adjustCollection[0]->getDatePaid(),
  919.                 'to'    => $currentAdjust->getDatePaid(),
  920.             ];
  921.         }else{
  922.             $dueCollection $this->royaltyDueRepository->createQueryBuilder("rda")
  923.                 ->where('rda.profile = :profile')
  924.                 ->setParameter('profile'$profile)
  925.                 ->orderBy('rda.datePaid''ASC')
  926.                 ->getQuery()
  927.                 ->getResult();
  928.             if(isset($dueCollection[0])){
  929.                 $firstDay $dueCollection[0]->getDatePaid();
  930.                 $lastDay $currentAdjust->getDatePaid();
  931.                 if($firstDay->format("Y-m-d") === $lastDay->format("Y-m-d")){
  932.                     $firstDay->modify("-1 day");
  933.                     $lastDay->modify('+1 day');
  934.                 }
  935.                 return [
  936.                     'from'  => $firstDay,
  937.                     'to'    => $lastDay,
  938.                 ];
  939.             }
  940.             throw new BadRequestHttpException("We don't find registers");
  941.         }
  942.     }
  943.     /**
  944.      * @param Profile $profile
  945.      * @return array
  946.      */
  947.     public function getRoyaltiesConsolidations(Profile $profile): array
  948.     {
  949.         return $this->royaltyConsolidationRepository->findBy(['profile' => $profile]);
  950.     }
  951.     /**
  952.      * @param array $data
  953.      * @param Profile $profile
  954.      * @return array
  955.      */
  956.     public function getEarningPaymentDetails(array $dataProfile $profile)
  957.     {
  958.         $dataToFile = [];
  959.         $dataEarnings = [];
  960.         if(isset($data['from']) && isset($data['to'])){
  961.             /** @var RoyaltyDue $royaltyDue */
  962.             $royaltyDueCollection $this->royaltyDueRepository->createQueryBuilder('r')
  963.                 ->where('r.profile = :profile')
  964.                 ->andWhere('r.datePaid BETWEEN :startDate AND :endDate')
  965.                 ->setParameter('profile'$profile)
  966.                 ->setParameter('startDate'$data['from'])
  967.                 ->setParameter('endDate'$data['to'])
  968.                 ->getQuery()
  969.                 ->getResult();
  970.         }else{
  971.             $royaltyDueCollection $this->royaltyDueRepository->findBy(['id' => $data['objectId']]);
  972.         }
  973.         if(count($royaltyDueCollection) <= 0){
  974.             throw new BadRequestHttpException("We don't found registers");
  975.         }
  976.         $totalAmountPaidByPlatform 0.00;
  977.         $totalServiceAmount 0.00;
  978.         $totalPublisherAdministratorAmount 0.00;
  979.         $totalAmountLeftAfterDeduction 0.00;
  980.         $totalPayableShareToSubProfile 0.00;
  981.         $totalPublisherAmount 0.00;
  982.         $totalSongWriterAmount 0.00;
  983.         $totalTaxAmountDeduced 0.00;
  984.         $totalTotal 0.00;
  985.         $platform null;
  986.         $dataRaw null;
  987.         /** @var RoyaltyDue $royaltyDue */
  988.         foreach ($royaltyDueCollection as $royaltyDue){
  989.             $royaltyImporterFileYear = (int)$royaltyDue->getRoyaltyImporterFile()->getEnteredAt()->format('Y');
  990.             $royaltyImporterFileMonth = (int)$royaltyDue->getRoyaltyImporterFile()->getEnteredAt()->format('m');
  991.             $dataIncome $this->incomeRawDataCHManagerService->getDataFromTable(
  992.                 IncomeRawDataCHManagerService::NAME,
  993.                 ['*'],
  994.                 ['report_id'    => $royaltyDue->getRoyaltyImporterFile()->getId()]
  995.             );
  996.             $platform $royaltyDue->getRoyaltyImporterFile()->getPlatform();
  997.             foreach ($dataIncome as $income) {
  998.                 /** @var SongWriter $songWriter */
  999.                 $songWriter $this->songWriterRepository->findOneBy([
  1000.                     'id' => $income['song_writer_id']
  1001.                 ]);
  1002.                 $ruleToIf false;
  1003.                 if($profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SONGWRITER){
  1004.                     $ruleToIf = ($profile->getId() === $songWriter->getProfile()->getId());
  1005.                 }else if($profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER){
  1006.                     $ruleToIf = ($profile->getId() === $songWriter->getProfile()->getParent()->getId());
  1007.                 }else if($profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR){
  1008.                     $profileParents $this->generalService->findAllParentProfiles($songWriter->getProfile());
  1009.                     $profileParentAux null;
  1010.                     /** @var Profile $profileParent */
  1011.                     foreach ($profileParents as $profileParent){
  1012.                         if($profileParent->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR){
  1013.                             $profileParentAux $profileParent;
  1014.                         }
  1015.                     }
  1016.                     if(!is_null($profileParentAux)){
  1017.                         $ruleToIf = ($profile->getId() === $profileParentAux->getId());
  1018.                     }
  1019.                 }else{
  1020.                     $ruleToIf = !$ruleToIf;
  1021.                 }
  1022.                 if($ruleToIf){
  1023.                     $dataRaw $this->rawDataDailyCHManagerService->getDataFromTable(
  1024.                         RawDataDailyCHManagerService::NAME,
  1025.                         ['*'],
  1026.                         ['id' => $income['raw_data_id']]
  1027.                     //[] TODO: Order by
  1028.                     );
  1029.                     $dataRaw $dataRaw[0];
  1030.                     /** @var Country $country */
  1031.                     $country $this->countryRepository->findOneBy(['id' => $dataRaw['country_id']]);
  1032.                     /** @var \App\Entity\Composition\Composition $composition */
  1033.                     $composition $this->compositionRepository->findOneBy(['id' => $income['composition_id']]);
  1034.                     $reportingPeriod $royaltyDue->getRoyaltyImporterFile()->getDateFrom()->format("Y-m-d")." to ".
  1035.                         $royaltyDue->getRoyaltyImporterFile()->getDateTo()->format("Y-m-d");
  1036.                     $publisherAdministratorPercentage 0;
  1037.                     $publisherSharePercentage 0;
  1038.                     $songWriterSharePercentage 0;
  1039.                     if($royaltyDue->getRoyaltyImporterFile()->getProfile()->getProfileType()->getName() !== Constants::PROFILE_TYPE_SERVICE){
  1040.                         $royaltyPA $royaltyDue->getRoyaltyImporterFile()->getProfile()->getRoyaltySplits();
  1041.                         $servicePercentage $this->getRoyaltyPercentage($royaltyDue->getRoyaltyImporterFile(), $royaltyPAtrue);
  1042.                         if($songWriter->getProfile()->getParent()->getId() !== $royaltyDue->getRoyaltyImporterFile()->getProfile()->getId()){
  1043.                             /** @var RoyaltySplits $royaltyPU */
  1044.                             $royaltyPU $songWriter->getProfile()->getParent()->getRoyaltySplits();
  1045.                             $publisherAdministratorPercentage $this->getRoyaltyPercentage(
  1046.                                 $royaltyDue->getRoyaltyImporterFile(),
  1047.                                 $royaltyPU,
  1048.                                 true
  1049.                             );
  1050.                             $publisherSharePercentage $this->getRoyaltyPercentage(
  1051.                                 $royaltyDue->getRoyaltyImporterFile(),
  1052.                                 $songWriter->getProfile()->getRoyaltySplits(),
  1053.                                 true
  1054.                             );
  1055.                         }else{
  1056.                             $publisherAdministratorPercentage =  $this->getRoyaltyPercentage(
  1057.                                 $royaltyDue->getRoyaltyImporterFile(),
  1058.                                 $songWriter->getProfile()->getRoyaltySplits(),
  1059.                                 true
  1060.                             );
  1061.                         }
  1062.                     }else{
  1063.                         $publisherAdministratorByProfileChild $this->generalService->findPublisherAdministratorByProfileChild($songWriter->getProfile());
  1064.                         if(!is_null($publisherAdministratorByProfileChild)){
  1065.                             $royaltyPA $publisherAdministratorByProfileChild->getRoyaltySplits();
  1066.                             $servicePercentage $this->getRoyaltyPercentage($royaltyDue->getRoyaltyImporterFile(), $royaltyPAtrue);
  1067.                             if($songWriter->getProfile()->getParent()->getId() !== $publisherAdministratorByProfileChild->getId()){
  1068.                                 /** @var RoyaltySplits $royaltyPU */
  1069.                                 $royaltyPU $songWriter->getProfile()->getParent()->getRoyaltySplits();
  1070.                                 $publisherAdministratorPercentage $this->getRoyaltyPercentage(
  1071.                                     $royaltyDue->getRoyaltyImporterFile(),
  1072.                                     $royaltyPU,
  1073.                                     true
  1074.                                 );
  1075.                                 $publisherSharePercentage $this->getRoyaltyPercentage(
  1076.                                     $royaltyDue->getRoyaltyImporterFile(),
  1077.                                     $songWriter->getProfile()->getRoyaltySplits(),
  1078.                                     true
  1079.                                 );
  1080.                             }else{
  1081.                                 $publisherAdministratorPercentage =  $this->getRoyaltyPercentage(
  1082.                                     $royaltyDue->getRoyaltyImporterFile(),
  1083.                                     $songWriter->getProfile()->getRoyaltySplits(),
  1084.                                     true
  1085.                                 );
  1086.                             }
  1087.                         }
  1088.                     }
  1089.                     $songWriterSharePercentage $this->getRoyaltyPercentage(
  1090.                         $royaltyDue->getRoyaltyImporterFile(),
  1091.                         $songWriter->getProfile()->getRoyaltySplits()
  1092.                     );
  1093.                     $taxPercentage $royaltyDue->getRoyaltyImporterFile()->getTaxPercentage() ?? 0;
  1094.                     $taxPercentage $taxPercentage 100;
  1095.                     switch ($profile->getProfileType()->getName()){
  1096.                         case Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR:
  1097.                             $earning = (new PublisherAdministratorEarningDTO())
  1098.                                 ->setSongWriterId($songWriter->getId())
  1099.                                 ->setReportDate($dataRaw['year_month'])
  1100.                                 ->setDateEntered($royaltyDue->getRoyaltyImporterFile()->getEnteredAt())
  1101.                                 ->setReportPeriod($reportingPeriod)
  1102.                                 ->setPlatform($royaltyDue->getRoyaltyImporterFile()->getPlatform()->getName())
  1103.                                 ->setPlatformType($dataRaw['rights_type'])
  1104.                                 ->setCountryOfSale($country->getCode())
  1105.                                 ->setPublisherProfile($royaltyDue->getRoyaltyImporterFile()->getProfile()->getProfileInformation()->getName())
  1106.                                 ->setSongWriterProfile($songWriter->getProfile()->getProfileInformation()->getName())
  1107.                                 ->setSongWriter($songWriter->getProfile()->getProfileInformation()->getName())
  1108.                                 ->setSongTitle($composition->getTitle())
  1109.                                 ->setIswc($composition->getIswc())
  1110.                                 ->setTunecode($composition->getTunecode())
  1111.                                 ->setIsrc(" ")//TODO: get the correct ISRC
  1112.                                 ->setQuantity($dataRaw['perf_number'])
  1113.                                 ->setAmountPaidByPlatform($income['income_total_gbp_share'])
  1114.                                 ->setServicePercentage($servicePercentage)
  1115.                                 ->setServiceAmount($income['income_se'])
  1116.                                 ->setAmountLeftAfterDeduction((float)$income['income_total_gbp_share'] - (float)$income['income_se'])
  1117.                                 ->setPublisherAdministratorPercentage($publisherAdministratorPercentage)
  1118.                                 ->setPublisherAdministratorAmount($income['income_pa'])
  1119.                                 ->setTaxCountry($royaltyDue->getRoyaltyImporterFile()->getTaxCountry()->getCode() ?? "")
  1120.                                 ->setTaxPercentage($taxPercentage)
  1121.                                 ->setTaxAmountDeduced($income['income_pa'] - $income['income_pa_net'])
  1122.                                 ->setTotal($income['income_pa_net']);
  1123.                             $totalAmountPaidByPlatform += $income['income_total_gbp_share'];
  1124.                             $totalServiceAmount += $income['income_se'];
  1125.                             $totalAmountLeftAfterDeduction += ((float)$income['income_total_gbp_share'] - (float)$income['income_se']);
  1126.                             $totalPublisherAdministratorAmount += $income['income_pa'];
  1127.                             $totalTaxAmountDeduced += ($income['income_pa'] - $income['income_pa_net']);
  1128.                             $totalTotal += $income['income_pa_net'];
  1129.                             break;
  1130.                         case Constants::PROFILE_TYPE_PUBLISHER:
  1131.                         case Constants::PROFILE_TYPE_SONGWRITER:
  1132.                         case Constants::PROFILE_TYPE_SERVICE:
  1133.                             $taxAmountDeduced $income['income_sw'] - $income['income_sw_net'];
  1134.                             $total $income['income_sw_net'];
  1135.                             if($profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SERVICE){
  1136.                                 $taxAmountDeduced $income['income_se'] - $income['income_se_net'];
  1137.                                 $total $income['income_se_net'];
  1138.                             }else if($profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER){
  1139.                                 $taxAmountDeduced $income['income_pu'] - $income['income_pu_net'];
  1140.                                 $total $income['income_pu_net'];
  1141.                             }
  1142.                             $earning = (new EarningDTO())
  1143.                                 ->setSongWriterId($songWriter->getId())
  1144.                                 ->setShare((float)$dataRaw['publisher_administrator_share'])
  1145.                                 ->setReportDate($dataRaw['year_month'])
  1146.                                 ->setDateEntered($royaltyDue->getRoyaltyImporterFile()->getEnteredAt())
  1147.                                 ->setReportPeriod($reportingPeriod)
  1148.                                 ->setPlatform($royaltyDue->getRoyaltyImporterFile()->getPlatform()->getName())
  1149.                                 ->setPlatformType($dataRaw['rights_type'])
  1150.                                 ->setCountryOfSale($country->getCode())
  1151.                                 ->setPublisherProfile($royaltyDue->getRoyaltyImporterFile()->getProfile()->getProfileInformation()->getName())
  1152.                                 ->setSongWriterProfile($songWriter->getProfile()->getProfileInformation()->getName())
  1153.                                 ->setSongWriter($songWriter->getProfile()->getProfileInformation()->getName())
  1154.                                 ->setSongTitle($composition->getTitle())
  1155.                                 ->setIswc($composition->getIswc())
  1156.                                 ->setTunecode($composition->getTunecode())
  1157.                                 ->setIsrc(" ")//TODO: get the correct ISRC
  1158.                                 ->setQuantity($dataRaw['perf_number'])
  1159.                                 ->setAmountPaidByPlatform($income['income_total_gbp_share'])
  1160.                                 ->setServicePercentage($servicePercentage)
  1161.                                 ->setServiceAmount($income['income_se'])
  1162.                                 ->setPublisherAdministratorPercentage($publisherAdministratorPercentage)
  1163.                                 ->setSongWriterSharePercentage($songWriterSharePercentage)
  1164.                                 ->setPublisherSharePercentage($publisherSharePercentage)
  1165.                                 ->setPublisherAdministratorAmount($income['income_pa'])
  1166.                                 ->setPayableShareToSubProfile((float)$income['income_pu'] + (float)$income['income_sw'])
  1167.                                 ->setPublisherAmount($income['income_pu'])
  1168.                                 ->setSongWriterAmount($income['income_sw'])
  1169.                                 ->setTaxCountry($royaltyDue->getRoyaltyImporterFile()->getTaxCountry()->getCode() ?? "")
  1170.                                 ->setTaxPercentage($taxPercentage)
  1171.                                 ->setTaxAmountDeduced($taxAmountDeduced)
  1172.                                 ->setTotal($total);
  1173.                             $totalAmountPaidByPlatform += $income['income_total_gbp_share'];
  1174.                             $totalServiceAmount += $income['income_se'];
  1175.                             $totalPublisherAdministratorAmount += $income['income_pa'];
  1176.                             $totalPayableShareToSubProfile += ((float)$income['income_pu'] + (float)$income['income_sw']);
  1177.                             $totalPublisherAmount += $income['income_pu'];
  1178.                             $totalSongWriterAmount += $income['income_sw'];
  1179.                             $totalTaxAmountDeduced += $taxAmountDeduced;
  1180.                             $totalTotal += $total;
  1181.                             if(
  1182.                                 $platform->getName() === Platforms::PRS &&
  1183.                                 $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SONGWRITER &&
  1184.                                 (float)$dataRaw['publisher_administrator_share'] < 100.00
  1185.                             ){
  1186.                                 $totalAmountPaidByPlatform -= $income['income_total_gbp_share'];
  1187.                                 $totalServiceAmount -= $income['income_se'];
  1188.                                 $totalPublisherAdministratorAmount -= $income['income_pa'];
  1189.                                 $totalPayableShareToSubProfile -= ((float)$income['income_pu'] + (float)$income['income_sw']);
  1190.                                 $totalPublisherAmount -= $income['income_pu'];
  1191.                                 $totalSongWriterAmount -= $income['income_sw'];
  1192.                                 $totalTaxAmountDeduced -= $taxAmountDeduced;
  1193.                                 $totalTotal -= $total;
  1194.                             }
  1195.                             break;
  1196.                     }
  1197.                     $dataEarnings[] = $earning;
  1198.                 }
  1199.             }
  1200.         }
  1201.         if(!is_null($platform) && !is_null($dataRaw)){
  1202.             foreach ($dataEarnings as $key => $earning) {
  1203.                 if(
  1204.                     $platform->getName() === Platforms::PRS &&
  1205.                     $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SONGWRITER &&
  1206.                     $earning->getShare() < 100.00
  1207.                 ){
  1208.                     unset($dataEarnings[$key]);
  1209.                 }
  1210.             }
  1211.         }
  1212.         switch ($profile->getProfileType()->getName()){
  1213.             case Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR:
  1214.                 $earningResult = (new PublisherAdministratorEarningDTO())
  1215.                     ->setAmountPaidByPlatform($totalAmountPaidByPlatform)
  1216.                     ->setServiceAmount($totalServiceAmount)
  1217.                     ->setAmountLeftAfterDeduction($totalAmountLeftAfterDeduction)
  1218.                     ->setPublisherAdministratorAmount($totalPublisherAdministratorAmount)
  1219.                     ->setTaxAmountDeduced($totalTaxAmountDeduced)
  1220.                     ->setTotal($totalTotal);
  1221.                 break;
  1222.             case Constants::PROFILE_TYPE_PUBLISHER:
  1223.             case Constants::PROFILE_TYPE_SONGWRITER:
  1224.             case Constants::PROFILE_TYPE_SERVICE:
  1225.                 $earningResult = (new EarningDTO())
  1226.                     ->setAmountPaidByPlatform($totalAmountPaidByPlatform)
  1227.                     ->setServiceAmount($totalServiceAmount)
  1228.                     ->setPublisherAdministratorAmount($totalPublisherAdministratorAmount)
  1229.                     ->setPayableShareToSubProfile($totalPayableShareToSubProfile)
  1230.                     ->setPublisherAmount($totalPublisherAmount)
  1231.                     ->setSongWriterAmount($totalSongWriterAmount)
  1232.                     ->setTaxAmountDeduced($totalTaxAmountDeduced)
  1233.                     ->setTotal($totalTotal);
  1234.                 break;
  1235.         }
  1236.         if(count($dataEarnings) > 0){
  1237.             $dataEarnings[] = $earningResult;
  1238.             $dataToFile = [
  1239.                 'earnings'      => $dataEarnings,
  1240.                 'royaltyDues'   => $royaltyDueCollection,
  1241.             ];
  1242.             if(isset($data['from']) && isset($data['to'])){
  1243.                 $dataToFile['from'] = $data['from'];
  1244.                 $dataToFile['to'] = $data['to'];
  1245.             }
  1246.         }
  1247.         return $dataToFile;
  1248.     }
  1249.     /**
  1250.      * @param array $row
  1251.      * @param Profile $profile
  1252.      * @param string $type
  1253.      * @return File|object
  1254.      * @throws \League\Flysystem\FilesystemException
  1255.      */
  1256.     public function processToBuildEarningPaymentCsv(array $rowProfile $profilestring $type)
  1257.     {
  1258.         $data = [];
  1259.         $dataResponse = [];
  1260.         /** @var RoyaltyDue $royaltyDue */
  1261.         $royaltyDue $row['royaltyDues'][0];
  1262.         foreach ($row['earnings'] as $earning) {
  1263.             $json $this->serializer->serialize($earning'json', ['groups' => 'royalty:earning']);
  1264.             $data[] = json_decode($jsontrue);
  1265.         }
  1266.         $tempFile tempnam(sys_get_temp_dir(), 'csv_');
  1267.         $fileHandle fopen($tempFile'w');
  1268.         $key array_keys($data[0]);
  1269.         fputcsv($fileHandle$key);
  1270.         foreach ($data as $rowFile) {
  1271.             $formattedRow array_map(function ($value) {
  1272.                 if (is_numeric($value)) {
  1273.                     return sprintf('%.10f'$value); // Format numbers with 10 decimal places
  1274.                 }
  1275.                 return $value;
  1276.             }, $rowFile);
  1277.             fputcsv($fileHandle$formattedRow);
  1278.         }
  1279.         fclose($fileHandle);
  1280.         if($type === RoyaltyDueType::IMPORTED){
  1281.             $fileName $profile->getProfileInformation()->getName()."-Earnings Report-".$royaltyDue->getYear()."-".$royaltyDue->getMonth().".csv";
  1282.         }else{
  1283.             $fileName $profile->getProfileInformation()->getName()."-Royalty Payment-".
  1284.                 $row['from']->format("Ymd")."-".
  1285.                 $row['to']->format("Ymd").".csv";
  1286.         }
  1287.         $mimeType 'text/csv';
  1288.         $uploadedFile = new UploadedFile(
  1289.             $tempFile,
  1290.             $fileName,
  1291.             $mimeType,
  1292.             null,
  1293.             true
  1294.         );
  1295.         return $this->fileService->upload(
  1296.             $uploadedFile,
  1297.             $royaltyDue->getId(),
  1298.             get_class($royaltyDue)
  1299.         );
  1300.     }
  1301.     /**
  1302.      * @param array $row
  1303.      * @param Profile $profile
  1304.      * @param int $reason
  1305.      * @return File|object
  1306.      * @throws \League\Flysystem\FilesystemException
  1307.      */
  1308.     public function processToBuildEarningSummaryCsv(array $rowsProfile $profileint $reason 1)
  1309.     {
  1310.         $data = [];
  1311.         foreach ($rows as $earning) {
  1312.             switch ($reason){
  1313.                 case 1:
  1314.                     $json $this->serializer->serialize($earning'json', ['groups' => 'royalty:earning-summary']);
  1315.                     break;
  1316.                 case 2:
  1317.                     $json $this->serializer->serialize($earning'json', ['groups' => 'royalty:earning-by-country-response']);
  1318.                     break;
  1319.                 case 3:
  1320.                     $json $this->serializer->serialize($earning'json', ['groups' => 'royalty:earning-by-composition-response']);
  1321.                     break;
  1322.                 case 4:
  1323.                     $json $this->serializer->serialize($earning'json', ['groups' => 'royalty:earning-by-platform-response']);
  1324.                     break;
  1325.                 case 5:
  1326.                     $json $this->serializer->serialize($earning'json', ['groups' => 'royalty:earning-by-month-response']);
  1327.                     break;
  1328.             }
  1329.             $data[] = json_decode($jsontrue);
  1330.         }
  1331.         $tempFile tempnam(sys_get_temp_dir(), 'csv_');
  1332.         $fileHandle fopen($tempFile'w');
  1333.         switch ($reason){
  1334.             case 1:
  1335.                 $key = ["Profile Type""Profile Name""Email""Minimum Payment""Paid Total""Seek Total""Current Due""Currency"];
  1336.                 break;
  1337.             case 2:
  1338.                 $key = ["Country""earnings"];
  1339.                 break;
  1340.             case 3:
  1341.                 $key = ["Composition""earnings"];
  1342.                 break;
  1343.             case 4:
  1344.                 $key = ["Platform""earnings"];
  1345.                 break;
  1346.             case 5:
  1347.                 $key = ["Month""Year""earnings"];
  1348.                 break;
  1349.         }
  1350.         fputcsv($fileHandle$key);
  1351.         foreach ($data as $rowFile) {
  1352.             switch ($reason){
  1353.                 case 1:
  1354.                     $formattedRow array_map(function ($value) {
  1355.                         return $value;
  1356.                     }, $rowFile);
  1357.                     fputcsv($fileHandle$formattedRow);
  1358.                     break;
  1359.                 case 2:
  1360.                     $formattedRow = [$rowFile['country']['country'], $rowFile['total_income_net']];
  1361.                     fputcsv($fileHandle$formattedRow);
  1362.                     break;
  1363.                 case 3:
  1364.                     $formattedRow = [$rowFile['composition']['title'], $rowFile['total_income_net']];
  1365.                     fputcsv($fileHandle$formattedRow);
  1366.                     break;
  1367.                 case 4:
  1368.                     $formattedRow = [$rowFile['platform']['name'], $rowFile['total_income_net']];
  1369.                     fputcsv($fileHandle$formattedRow);
  1370.                     break;
  1371.                 case 5:
  1372.                     $formattedRow = [$rowFile['month'], $rowFile['year'], $rowFile['total_income_net']];
  1373.                     fputcsv($fileHandle$formattedRow);
  1374.                     break;
  1375.             }
  1376.         }
  1377.         fclose($fileHandle);
  1378.         switch ($reason){
  1379.             case 1:
  1380.                 $fileName $profile->getProfileInformation()->getName()."-Earnings Summary-".date("Ymd").".csv";
  1381.                 break;
  1382.             case 2:
  1383.                 $fileName $profile->getProfileInformation()->getName()."-Country Earnings-".date("Ymd").".csv";
  1384.                 break;
  1385.             case 3:
  1386.                 $fileName $profile->getProfileInformation()->getName()."-Composition Earnings-".date("Ymd").".csv";
  1387.                 break;
  1388.             case 4:
  1389.                 $fileName $profile->getProfileInformation()->getName()."-Platforms Earnings-".date("Ymd").".csv";
  1390.                 break;
  1391.             case 5:
  1392.                 $fileName $profile->getProfileInformation()->getName()."-Months Earnings-".date("Ymd").".csv";
  1393.                 break;
  1394.         }
  1395.         $mimeType 'text/csv';
  1396.         $uploadedFile = new UploadedFile(
  1397.             $tempFile,
  1398.             $fileName,
  1399.             $mimeType,
  1400.             null,
  1401.             true
  1402.         );
  1403.         return $this->fileService->upload(
  1404.             $uploadedFile,
  1405.             $profile->getId(),
  1406.             get_class($profile)
  1407.         );
  1408.     }
  1409.     /**
  1410.      * @param UploadedFile $uploadedFile
  1411.      * @param \DateTime $dateEntered
  1412.      * @return array
  1413.      */
  1414.     public function processToUploadPaymentFile(UploadedFile $uploadedFile, \DateTime $dateEntered)
  1415.     {
  1416.         $dataToReturn = [];
  1417.         $filePath $uploadedFile->getPathname();
  1418.         $tempFilePath '/tmp/' uniqid() . '.csv';
  1419.         $uploadedFile->move(dirname($tempFilePath), basename($tempFilePath));
  1420.         $data $this->processCsvFileByPath($tempFilePath);
  1421.         foreach ($data as $row) {
  1422.             /** @var ProfileInformation $profileInformation */
  1423.             $profileInformation $this->generalService->findProfileInformationByName($row['Profile Name']);
  1424.             /** @var Currency $currency */
  1425.             $currency $this->generalService->getCurrencyByCode($row['Currency Code']);
  1426.             $receiverProfile $this->generalService->findLastAccessedProfileForUser($this->generalService->findTheCurrentUser());
  1427.             $royaltyAdjust = (new RoyaltyDueAdjust())
  1428.                 ->setDescription($row['Message to Recipient'])
  1429.                 ->setType(RoyaltyDueType::ROYALTY_PAYMENT)
  1430.                 ->setDatePaid($dateEntered)
  1431.                 ->setPayerUser($this->generalService->findTheCurrentUser())
  1432.                 ->setPayerProfile($profileInformation->getProfile())
  1433.                 ->setReceiverProfile($receiverProfile)
  1434.                 ->setAmount($row['Amount']);
  1435.             $royaltyAdjust $this->royaltyDueAdjustRepository->save($royaltyAdjust);
  1436.             $dataToReturn[] = $royaltyAdjust;
  1437.         }
  1438.         return $dataToReturn;
  1439.     }
  1440.     /**
  1441.      * @param RoyaltyImporterFile $royaltyImporterFile
  1442.      * @return array
  1443.      */
  1444.     public function reProcessErrorRows(RoyaltyImporterFile $royaltyImporterFile)
  1445.     {
  1446.         $originalFile $royaltyImporterFile->getFile();
  1447.         $dataOriginalFile = [];
  1448.         switch ($originalFile->getExtension()) {
  1449.             case 'csv':
  1450.             case 'CSV':
  1451.                 $dataOriginalFile $this->processCsvFile($originalFile);
  1452.                 break;
  1453.             case 'tsv':
  1454.             case 'TSV':
  1455.                 $dataOriginalFile $this->processTsvFile($originalFile);
  1456.                 break;
  1457.         }
  1458.         $dataToReProcess = [];
  1459.         $data $this->rawDataIncompleteCHManagerService->getDataFromTable(
  1460.             RawDataIncompleteCH::TABLE_NAME,
  1461.             ['*'],
  1462.             ['report_id' => $royaltyImporterFile->getId()]
  1463.         );
  1464.         foreach ($data as $errorRow) {
  1465.             if($royaltyImporterFile->getPlatform()->getName() === Platforms::MLC){
  1466.                 $dataToReProcess[] = $dataOriginalFile[$errorRow['old_id'] - 1];
  1467.                 $this->rawDataIncompleteCHManagerService->deleteData(
  1468.                     RawDataIncompleteCH::TABLE_NAME,
  1469.                     ['id' => $errorRow['id']]
  1470.                 );
  1471.             }else{
  1472.                 $key array_search($errorRow['old_id'], array_column($dataOriginalFile'Record Number'));
  1473.                 if(!is_bool($key)){
  1474.                     $dataToReProcess[] = $dataOriginalFile[$key];
  1475.                     $this->rawDataIncompleteCHManagerService->deleteData(
  1476.                         RawDataIncompleteCH::TABLE_NAME,
  1477.                         ['id' => $errorRow['id']]
  1478.                     );
  1479.                 }
  1480.             }
  1481.         }
  1482.         return $dataToReProcess;
  1483.     }
  1484.     /**
  1485.      * @param Profile $profile
  1486.      * @return array
  1487.      */
  1488.     public function getCompositionEarningsByProfile(Profile $profile)
  1489.     {
  1490.         $downloadSongParametersDTO = new DownloadSongParametersDTO();
  1491.         $IncomeRawData $this->incomeRawDataCHManagerService->getIncomeByComposition($profile->getProfileType());
  1492.         $result = [];
  1493.         $counter 1;
  1494.         $songs $this->songService->findAllUnderProfile($profile$downloadSongParametersDTO);
  1495.         $compositions = [];
  1496.         /** @var Song $song */
  1497.         foreach ($songs as $song){
  1498.             if(!in_array($song->getComposition(), $compositions)){
  1499.                 $compositions[] = $song->getComposition();
  1500.                 $resultByComposition =[
  1501.                     'composition'   => [
  1502.                         'id'    => $song->getComposition()->getId(),
  1503.                         'title' => $song->getComposition()->getTitle(),
  1504.                     ],
  1505.                     'earning'       => 0.00,
  1506.                     'id'            => $song->getId(),
  1507.                 ];
  1508.                 foreach ($IncomeRawData as $IncomeRawDataRegister){
  1509.                     if($song->getComposition()->getId() === $IncomeRawDataRegister['composition_id']){
  1510.                         $resultByComposition['earning'] += (float)$IncomeRawDataRegister['total_income_total_gbp_share_net'];
  1511.                         $result[] = $resultByComposition;
  1512.                     }
  1513.                 }
  1514.             }
  1515.         }
  1516.         unset($compositions);
  1517.         usort($result, function ($a$b) {
  1518.             return $b['earning'] <=> $a['earning'];
  1519.         });
  1520.         foreach ($result as $key => $row){
  1521.             if($counter 5){
  1522.                 unset($result[$key]);
  1523.             }
  1524.             $counter++;
  1525.         }
  1526.         return $result;
  1527.     }
  1528.     /**
  1529.      * @param Profile $profile
  1530.      * @param EarningByCountryDTO $earningByCountryDTO
  1531.      * @return array|\mixed[][]
  1532.      */
  1533.     public function getEarningsByCountry(Profile $profileEarningByCountryDTO $earningByCountryDTO)
  1534.     {
  1535.         $profileArray = [];
  1536.         if(
  1537.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SERVICE ||
  1538.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR ||
  1539.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER
  1540.         ){
  1541.             $profileArray $this->generalService->findAllSubProfiles($profile);
  1542.         }else{
  1543.             $profileArray[] = $profile;
  1544.         }
  1545.         $criteria = [
  1546.             'countries'     => null,
  1547.             'start_date'    => null,
  1548.             'end_date'      => null,
  1549.             'limit'         => 5,
  1550.             'page'          => 1
  1551.         ];
  1552.         if(!is_null($earningByCountryDTO->getCountries())){
  1553.             $aux = [];
  1554.             /** @var Country $country */
  1555.             foreach ($earningByCountryDTO->getCountries() as $country){
  1556.                 $aux[] = $country->getId();
  1557.             }
  1558.             if(count($aux) > 0){
  1559.                 $criteria['countries'] = $aux;
  1560.             }
  1561.         }
  1562.         if(!is_null($earningByCountryDTO->getStartDate())){
  1563.             $criteria['start_date'] = $earningByCountryDTO->getStartDate()->format('Y-m-d');
  1564.         }
  1565.         if(!is_null($earningByCountryDTO->getEndDate())){
  1566.             $criteria['end_date'] = $earningByCountryDTO->getEndDate()->format('Y-m-d');
  1567.         }
  1568.         if(!is_null($earningByCountryDTO->getLimit())){
  1569.             $criteria['limit'] = $earningByCountryDTO->getLimit();
  1570.         }
  1571.         if(!is_null($earningByCountryDTO->getPage())){
  1572.             $criteria['page'] = $earningByCountryDTO->getPage();
  1573.         }
  1574.         $finalResultAux = [];
  1575.         /** @var Profile $subProfile */
  1576.         foreach ($profileArray as $subProfile){
  1577.             $clickHouseResults $this->rawDataDailyCHManagerService->getEarningsByCountryAndProfile(
  1578.                 $subProfile,
  1579.                 $profile->getProfileType(),
  1580.                 $criteria
  1581.             );
  1582.             foreach ($clickHouseResults as $clickHouseResult){
  1583.                 if(!isset($finalResultAux[(int)$clickHouseResult['country_id']])){
  1584.                     $finalResultAux[(int)$clickHouseResult['country_id']] = $clickHouseResult;
  1585.                     $finalResultAux[(int)$clickHouseResult['country_id']]['country_id'] = (int)$clickHouseResult['country_id'];
  1586.                     $finalResultAux[(int)$clickHouseResult['country_id']]['total_income_net'] = (float)$clickHouseResult['total_income_net'];
  1587.                 }else{
  1588.                     $finalResultAux[(int)$clickHouseResult['country_id']]['total_income_net'] += (float)$clickHouseResult['total_income_net'];
  1589.                 }
  1590.             }
  1591.         }
  1592.         $finalResult = [];
  1593.         $orderCounter 1;
  1594.         foreach ($finalResultAux as $key => $row){
  1595.             $earningByCountryResponseDTO = new EarningByCountryResponseDTO();
  1596.             $earningByCountryResponseDTO->setId((int)$key)
  1597.                 ->setOrder($orderCounter)
  1598.                 ->setCountry($this->countryRepository->find($row['country_id']))
  1599.                 ->setTotalIncomeNet($row['total_income_net']);
  1600.             $orderCounter++;
  1601.             $finalResult[] = $earningByCountryResponseDTO;
  1602.         }
  1603.         return $finalResult;
  1604.     }
  1605.     /**
  1606.      * @param Profile $profile
  1607.      * @param EarningByCompositionDTO $earningByCompositionDTO
  1608.      * @return array|\mixed[][]
  1609.      */
  1610.     public function getEarningsByComposition(Profile $profileEarningByCompositionDTO $earningByCompositionDTO)
  1611.     {
  1612.         $profileArray = [];
  1613.         if(
  1614.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SERVICE ||
  1615.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR ||
  1616.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER
  1617.         ){
  1618.             $profileArray $this->generalService->findAllSubProfiles($profile);
  1619.         }else{
  1620.             $profileArray[] = $profile;
  1621.         }
  1622.         $criteria = [
  1623.             'compositions'  => null,
  1624.             'start_date'    => null,
  1625.             'end_date'      => null,
  1626.             'limit'         => 5,
  1627.             'page'          => 1
  1628.         ];
  1629.         if(!is_null($earningByCompositionDTO->getCompositions())){
  1630.             $aux = [];
  1631.             /** @var Composition $composition */
  1632.             foreach ($earningByCompositionDTO->getCompositions() as $composition){
  1633.                 $aux[] = $composition->getId();
  1634.             }
  1635.             if(count($aux) > 0){
  1636.                 $criteria['compositions'] = $aux;
  1637.             }
  1638.         }
  1639.         if(!is_null($earningByCompositionDTO->getStartDate())){
  1640.             $criteria['start_date'] = $earningByCompositionDTO->getStartDate()->format('Y-m-d');
  1641.         }
  1642.         if(!is_null($earningByCompositionDTO->getEndDate())){
  1643.             $criteria['end_date'] = $earningByCompositionDTO->getEndDate()->format('Y-m-d');
  1644.         }
  1645.         if(!is_null($earningByCompositionDTO->getLimit())){
  1646.             $criteria['limit'] = $earningByCompositionDTO->getLimit();
  1647.         }
  1648.         if(!is_null($earningByCompositionDTO->getPage())){
  1649.             $criteria['page'] = $earningByCompositionDTO->getPage();
  1650.         }
  1651.         $finalResultAux = [];
  1652.         /** @var Profile $subProfile */
  1653.         foreach ($profileArray as $subProfile){
  1654.             $clickHouseResults $this->rawDataDailyCHManagerService->getEarningsByCompositionAndProfile(
  1655.                 $subProfile,
  1656.                 $profile->getProfileType(),
  1657.                 $criteria
  1658.             );
  1659.             foreach ($clickHouseResults as $clickHouseResult){
  1660.                 if(!isset($finalResultAux[(int)$clickHouseResult['composition_identifier']])){
  1661.                     $finalResultAux[(int)$clickHouseResult['composition_identifier']] = $clickHouseResult;
  1662.                     $finalResultAux[(int)$clickHouseResult['composition_identifier']]['composition_identifier'] = (int)$clickHouseResult['composition_identifier'];
  1663.                     $finalResultAux[(int)$clickHouseResult['composition_identifier']]['total_income_net'] = (float)$clickHouseResult['total_income_net'];
  1664.                 }else{
  1665.                     $finalResultAux[(int)$clickHouseResult['composition_identifier']]['total_income_net'] += (float)$clickHouseResult['total_income_net'];
  1666.                 }
  1667.             }
  1668.         }
  1669.         $finalResult = [];
  1670.         $counter 1;
  1671.         foreach ($finalResultAux as $key => $row){
  1672.             $earningByCountryResponseDTO = new EarningByCompositionResponseDTO();
  1673.             $earningByCountryResponseDTO->setId((int)$key)
  1674.                 ->setOrder($counter)
  1675.                 ->setComposition($this->compositionRepository->find($row['composition_identifier']))
  1676.                 ->setTotalIncomeNet($row['total_income_net']);
  1677.             $finalResult[] = $earningByCountryResponseDTO;
  1678.             $counter ++;
  1679.         }
  1680.         return $finalResult;
  1681.     }
  1682.     /**
  1683.      * @param Profile $profile
  1684.      * @param EarningByPlatformDTO $earningByPlatformDTO
  1685.      * @return array|\mixed[][]
  1686.      */
  1687.     public function getEarningsByPlatform(Profile $profileEarningByPlatformDTO $earningByPlatformDTO)
  1688.     {
  1689.         $profileArray = [];
  1690.         if(
  1691.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SERVICE ||
  1692.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR ||
  1693.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER
  1694.         ){
  1695.             $profileArray $this->generalService->findAllSubProfiles($profile);
  1696.         }else{
  1697.             $profileArray[] = $profile;
  1698.         }
  1699.         $criteria = [
  1700.             'platforms'     => null,
  1701.             'start_date'    => null,
  1702.             'end_date'      => null,
  1703.             'limit'         => 5,
  1704.             'page'          => 1
  1705.         ];
  1706.         if(!is_null($earningByPlatformDTO->getPlatforms())){
  1707.             $aux = [];
  1708.             /** @var Platform $platform */
  1709.             foreach ($earningByPlatformDTO->getPlatforms() as $platform){
  1710.                 $aux[] = $platform->getId();
  1711.             }
  1712.             if(count($aux) > 0){
  1713.                 $criteria['platforms'] = $aux;
  1714.             }
  1715.         }
  1716.         if(!is_null($earningByPlatformDTO->getStartDate())){
  1717.             $criteria['start_date'] = $earningByPlatformDTO->getStartDate()->format('Y-m-d');
  1718.         }
  1719.         if(!is_null($earningByPlatformDTO->getEndDate())){
  1720.             $criteria['end_date'] = $earningByPlatformDTO->getEndDate()->format('Y-m-d');
  1721.         }
  1722.         if(!is_null($earningByPlatformDTO->getLimit())){
  1723.             $criteria['limit'] = $earningByPlatformDTO->getLimit();
  1724.         }
  1725.         if(!is_null($earningByPlatformDTO->getPage())){
  1726.             $criteria['page'] = $earningByPlatformDTO->getPage();
  1727.         }
  1728.         $platformIds = [];
  1729.         $finalResultAux = [];
  1730.         foreach ($this->platformRepository->findAll() as $platform) {
  1731.             $platformIds[] = $platform->getId();
  1732.             $finalResultAux[(int)$platform->getId()] = [
  1733.                 'platform_identifier'   => $platform->getId(),
  1734.                 'total_income_net'      => 0
  1735.             ];
  1736.         }
  1737.         /** @var Profile $subProfile */
  1738.         foreach ($profileArray as $subProfile){
  1739.             $clickHouseResults $this->rawDataDailyCHManagerService->getEarningsByPlatformAndProfile(
  1740.                 $subProfile,
  1741.                 $profile->getProfileType(),
  1742.                 $platformIds,
  1743.                 $criteria
  1744.             );
  1745.             foreach ($clickHouseResults as $key => $clickHouseResult){
  1746.                 $finalResultAux[$key]['total_income_net'] += (float)$clickHouseResult['total_income_net'];
  1747.             }
  1748.         }
  1749.         $finalResult = [];
  1750.         $counter 1;
  1751.         foreach ($finalResultAux as $key => $row){
  1752.             if ($row['total_income_net'] > 0) {
  1753.                 $earningByCountryResponseDTO = new EarningByPlatformResponseDTO();
  1754.                 $earningByCountryResponseDTO->setId((int)$key)
  1755.                     ->setOrder($counter)
  1756.                     ->setPlatform($this->platformRepository->find($row['platform_identifier']))
  1757.                     ->setTotalIncomeNet($row['total_income_net']);
  1758.                 $finalResult[] = $earningByCountryResponseDTO;
  1759.                 $counter ++;
  1760.             }
  1761.         }
  1762.         return $finalResult;
  1763.     }
  1764.     /**
  1765.      * @param Profile $profile
  1766.      * @param EarningByMonthDTO $earningByMonthDTO
  1767.      * @return array|\mixed[][]
  1768.      */
  1769.     public function getEarningsByMonth(Profile $profileEarningByMonthDTO $earningByMonthDTO)
  1770.     {
  1771.         $profileArray = [];
  1772.         if(
  1773.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_SERVICE ||
  1774.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR ||
  1775.             $profile->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER
  1776.         ){
  1777.             $profileArray $this->generalService->findAllSubProfiles($profile);
  1778.         }else{
  1779.             $profileArray[] = $profile;
  1780.         }
  1781.         $criteria = [
  1782.             'start_date'    => null,
  1783.             'end_date'      => null,
  1784.             'limit'         => 5,
  1785.             'page'          => 1
  1786.         ];
  1787.         if(!is_null($earningByMonthDTO->getStartDate())){
  1788.             $criteria['start_date'] = $earningByMonthDTO->getStartDate()->format('Y-m-d');
  1789.         }
  1790.         if(!is_null($earningByMonthDTO->getEndDate())){
  1791.             $criteria['end_date'] = $earningByMonthDTO->getEndDate()->format('Y-m-d');
  1792.         }
  1793.         if(!is_null($earningByMonthDTO->getLimit())){
  1794.             $criteria['limit'] = $earningByMonthDTO->getLimit();
  1795.         }
  1796.         if(!is_null($earningByMonthDTO->getPage())){
  1797.             $criteria['page'] = $earningByMonthDTO->getPage();
  1798.         }
  1799.         $finalResultAux = [];
  1800.         /** @var Profile $subProfile */
  1801.         foreach ($profileArray as $subProfile){
  1802.             $clickHouseResults $this->rawDataDailyCHManagerService->getEarningsByMonthAndProfile(
  1803.                 $subProfile,
  1804.                 $profile->getProfileType(),
  1805.                 $criteria
  1806.             );
  1807.             foreach ($clickHouseResults as $clickHouseResult){
  1808.                 if(!isset($finalResultAux[$clickHouseResult['month_period']])){
  1809.                     $finalResultAux[$clickHouseResult['month_period']] = $clickHouseResult;
  1810.                     $finalResultAux[$clickHouseResult['month_period']]['month_period'] = $clickHouseResult['month_period'];
  1811.                     $finalResultAux[$clickHouseResult['month_period']]['total_income_net'] = (float)$clickHouseResult['total_income_net'];
  1812.                 }else{
  1813.                     $finalResultAux[$clickHouseResult['month_period']]['total_income_net'] += (float)$clickHouseResult['total_income_net'];
  1814.                 }
  1815.             }
  1816.         }
  1817.         $finalResult = [];
  1818.         $counter 1;
  1819.         foreach ($finalResultAux as $key => $row){
  1820.             $yearMonthArray explode("-"$row['month_period']);
  1821.             $earningByCountryResponseDTO = new EarningByMonthResponseDTO();
  1822.             $earningByCountryResponseDTO->setId((int)$yearMonthArray[1] + (int)$yearMonthArray[0])
  1823.                 ->setOrder($counter)
  1824.                 ->setMonth($yearMonthArray[1])
  1825.                 ->setYear($yearMonthArray[0])
  1826.                 ->setTotalIncomeNet($row['total_income_net']);
  1827.             $finalResult[] = $earningByCountryResponseDTO;
  1828.             $counter ++;
  1829.         }
  1830.         return $finalResult;
  1831.     }
  1832.     //-------------------------------PRIVATE FUNCTIONS--------------------------------------------------------//
  1833.     /**
  1834.      * @param File $file
  1835.      * @return array
  1836.      */
  1837.     private function processCsvFile(File $file)
  1838.     {
  1839.         $data array_map('str_getcsv'file($file->getUrl(), FILE_SKIP_EMPTY_LINES));
  1840.         $keys array_shift($data);
  1841.         foreach ($data as $i => $row) {
  1842.             $data[$i] = array_combine($keys$row);
  1843.         }
  1844.         return $data;
  1845.     }
  1846.     /**
  1847.      * @param File $file
  1848.      * @return array
  1849.      */
  1850.     private function processTsvFile(File $file)
  1851.     {
  1852.         $array = [];
  1853.         $newArray = [];
  1854.         if (($handle fopen($file->getUrl(), 'r')) !== false) {
  1855.             while (($data fgetcsv($handlenull"\t")) !== false) {
  1856.                 $array[] = $data;
  1857.             }
  1858.             fclose($handle);
  1859.             $keys $array[0];
  1860.             unset($array[0]);
  1861.             foreach ($array as $i => $row) {
  1862.                 $newArray[] = array_combine($keys$row);
  1863.             }
  1864.         } else {
  1865.             throw new BadRequestHttpException("Unable to open " $file->getUrl());
  1866.         }
  1867.         return $newArray;
  1868.     }
  1869.     /**
  1870.      * @param array $data
  1871.      * @param array $dataErrorArrayObjects
  1872.      * @param RoyaltyImporterFile $royaltyImporterFile
  1873.      * @return File|object
  1874.      * @throws \League\Flysystem\FilesystemException
  1875.      */
  1876.     private function processToCreateAnErrorFile(
  1877.         array $data, array $dataErrorArrayObjectsRoyaltyImporterFile $royaltyImporterFile
  1878.     )
  1879.     {
  1880.         $tempFile tempnam(sys_get_temp_dir(), 'csv_');
  1881.         $fileHandle fopen($tempFile'w');
  1882.         $key array_keys($data[0]);
  1883.         $key[] = "observation";
  1884.         fputcsv($fileHandle$key);
  1885.         foreach ($data as $key => $row) {
  1886.             /** @var RawDataIncompleteCH $rawDataIncomplete */
  1887.             $rawDataIncomplete $dataErrorArrayObjects[$key];
  1888.             switch ($rawDataIncomplete->getErrorNumber()){
  1889.                 case 1:
  1890.                     $row[] = "Please check the IPI name number";
  1891.                     break;
  1892.                 case 2:
  1893.                     if($royaltyImporterFile->getPlatform()->getName() === Platforms::MLC){
  1894.                         $row[] = "Please check the composition Tunecode, ISWC OR ISRC";
  1895.                     }else{
  1896.                         $row[] = "Please check the composition Tunecode or ISWC";
  1897.                     }
  1898.                     break;
  1899.                 case 3:
  1900.                     $row[] = "Please check the songwriter information";
  1901.                     break;
  1902.                 case 4:
  1903.                     $row[] = "Please check the row information, general error in the register";
  1904.                 case 5:
  1905.                     $row[] = "Composition could not be found by ISWC OR ISRC";
  1906.                 case 6:
  1907.                     $row[] = "Composition is not published or taken down";
  1908.                     break;
  1909.             }
  1910.             fputcsv($fileHandle$row);
  1911.         }
  1912.         fclose($fileHandle);
  1913.         $arrFileName explode('.'$royaltyImporterFile->getFile()->getOriginalName());
  1914.         $fileName $arrFileName[0]."_errors.".$arrFileName[1];
  1915.         $mimeType 'text/csv';
  1916.         $uploadedFile = new UploadedFile(
  1917.             $tempFile,
  1918.             $fileName,
  1919.             $mimeType,
  1920.             null,
  1921.             true
  1922.         );
  1923.         return $this->fileService->upload(
  1924.             $uploadedFile,
  1925.             $royaltyImporterFile->getId(),
  1926.             get_class($royaltyImporterFile)
  1927.         );
  1928.     }
  1929.     /**
  1930.      * @param Profile $profile
  1931.      * @return float|int|mixed|string
  1932.      */
  1933.     private function getPaymentAndReceiverPayer(Profile $profile)
  1934.     {
  1935.         return $this->royaltyDueAdjustRepository->createQueryBuilder('r')
  1936.             ->where('r.payerProfile = :profileId')
  1937.             ->orWhere('r.receiverProfile = :profileId')
  1938.             ->setParameter('profileId'$profile->getId())
  1939.             ->getQuery()
  1940.             ->getResult();
  1941.     }
  1942.     /**
  1943.      * @param string $path
  1944.      * @return array
  1945.      */
  1946.     private function processCsvFileByPath(string $path)
  1947.     {
  1948.         $data array_map('str_getcsv'file($pathFILE_SKIP_EMPTY_LINES));
  1949.         $keys array_shift($data);
  1950.         foreach ($data as $i => $row) {
  1951.             $data[$i] = array_combine($keys$row);
  1952.         }
  1953.         return $data;
  1954.     }
  1955.     /**
  1956.      * @param RoyaltyImporterFile $royaltyImporterFile
  1957.      * @param RoyaltySplits $royaltySplits
  1958.      * @param bool $parent
  1959.      * @return float|int|null
  1960.      */
  1961.     private function getRoyaltyPercentage(
  1962.         RoyaltyImporterFile $royaltyImporterFile,
  1963.         RoyaltySplits $royaltySplits,
  1964.         bool $parent false
  1965.     )
  1966.     {
  1967.         $percentage 0;
  1968.         switch ($royaltyImporterFile->getType()){
  1969.             case RoyaltyImporterFileType::M:
  1970.                 $percentage = ($parent) ? $royaltySplits->getMechanicalRoyaltySplitParent() : $royaltySplits->getMechanicalRoyaltySplitProfile();
  1971.                 break;
  1972.             case RoyaltyImporterFileType::L:
  1973.                 $percentage = ($parent) ? $royaltySplits->getLyricsRoyaltySplitParent() : $royaltySplits->getLyricsRoyaltySplitProfile();
  1974.                 break;
  1975.             case RoyaltyImporterFileType::P:
  1976.                 $percentage = ($parent) ? $royaltySplits->getPerformanceRoyaltySplitParent() : $royaltySplits->getPerformanceRoyaltySplitProfile();
  1977.                 break;
  1978.             case RoyaltyImporterFileType::S:
  1979.                 $percentage = ($parent) ? $royaltySplits->getSyncRoyaltySplitParent() : $royaltySplits->getSyncRoyaltySplitProfile();
  1980.                 break;
  1981.         }
  1982.         return $percentage;
  1983.     }
  1984.     /**
  1985.      * @param RoyaltyImporterFile $royaltyImporterFile
  1986.      * @return void
  1987.      */
  1988.     private function flushDataConsolidated(RoyaltyImporterFile $royaltyImporterFile)
  1989.     {
  1990.         if($royaltyImporterFile->getPlatform()->getName() === Platforms::MLC){
  1991.             $income 0;
  1992.             $incomeNet 0;
  1993.             /**
  1994.              * @var  $key
  1995.              * @var RoyaltyDue  $royaltyDue
  1996.              */
  1997.             foreach ($this->dataConsolidated as  $key => $royaltyDue) {
  1998.                 if($royaltyDue->getProfile()->getProfileType()->getName() === Constants::PROFILE_TYPE_SERVICE){
  1999.                     $income $royaltyDue->getIncomeAmount();
  2000.                     $incomeNet $royaltyDue->getIncomeAmountNet();
  2001.                 }
  2002.             }
  2003.             /**
  2004.              * @var  $key
  2005.              * @var RoyaltyDue  $royaltyDue
  2006.              */
  2007.             foreach ($this->dataConsolidated as  $key => $royaltyDue) {
  2008.                 if($royaltyDue->getProfile()->getProfileType()->getName() === Constants::PROFILE_TYPE_PUBLISHER_ADMINISTRATOR){
  2009.                     $this->dataConsolidated[$key]->setIncomeAmountNet($incomeNet);
  2010.                     $this->dataConsolidated[$key]->setIncomeAmount($income);
  2011.                 }
  2012.             }
  2013.         }
  2014.         foreach ($this->dataConsolidated as $royaltyDue) {
  2015.             if ($royaltyDue instanceof RoyaltyDue) {
  2016.                 $this->entityManager->persist($royaltyDue);
  2017.             }
  2018.         }
  2019.         $this->entityManager->flush();
  2020.         $this->dataConsolidated = [];
  2021.     }
  2022.     /**
  2023.      * @param RoyaltyImporterFile $royaltyImporterFile
  2024.      * @return void
  2025.      */
  2026.     private function flushRawDateProcessed(RoyaltyImporterFile $royaltyImporterFile)
  2027.     {
  2028.         $this->rawDataDailyCHManagerService->updateSingleField(
  2029.             RawDataDailyCHManagerService::NAME,
  2030.             "status",
  2031.             RoyaltyRawDataStatus::PROCESSED,
  2032.             ['report_id' => $royaltyImporterFile->getId()]
  2033.         );
  2034.     }
  2035.     /**
  2036.      * @param RoyaltyImporterFile $royaltyImporterFile
  2037.      * @return void
  2038.      */
  2039.     private function flushIncomeDataConsolidated(RoyaltyImporterFile $royaltyImporterFile)
  2040.     {
  2041.         $this->incomeRawDataCHManagerService->updateSingleField(
  2042.             IncomeRawDataCH::TABLE_NAME,
  2043.             "consolidated",
  2044.             1,
  2045.             ['report_id' => $royaltyImporterFile->getId()]
  2046.         );
  2047.     }
  2048. }