diff --git a/gestion/appinfo/routes.php b/gestion/appinfo/routes.php index c6ac860..4561da0 100644 --- a/gestion/appinfo/routes.php +++ b/gestion/appinfo/routes.php @@ -182,6 +182,7 @@ return [ ['name' => 'provider#provider', 'url' => '/provider', 'verb' => 'GET'], ['name' => 'provider#getProviders','url' => '/provider/list', 'verb' => 'PROPFIND'], ['name' => 'provider#createDefaultProvider','url' => '/provider/createDefaultProvider', 'verb' => 'POST'], + ['name' => 'provider#exportProvidersStatistic','url' => '/provider/exportStat', 'verb' => 'POST'], //orderProduct ['name' => 'order#orderProduct', 'url' => '/orderProduct', 'verb' => 'GET'], diff --git a/gestion/lib/Controller/ProviderController.php b/gestion/lib/Controller/ProviderController.php index 4fb9ce3..18bf115 100644 --- a/gestion/lib/Controller/ProviderController.php +++ b/gestion/lib/Controller/ProviderController.php @@ -4,9 +4,8 @@ namespace OCA\Gestion\Controller; use Exception; use OCA\Gestion\Service\ConfigurationService; use OCA\Gestion\Service\NavigationService; -use OCA\Gestion\Service\Order\OrderPdfService; -use OCA\Gestion\Service\Order\OrderService; use OCA\Gestion\Service\Provider\ProviderService; +use OCA\Gestion\Service\Provider\Statistic\ProviderStatisticService; use Psr\Log\LoggerInterface; defined("TAB1") or define("TAB1", "\t"); @@ -41,6 +40,8 @@ class ProviderController extends Controller { private $providerService; + private $providerStatisticService; + private $logger; /** @@ -59,7 +60,8 @@ class ProviderController extends Controller { NavigationService $navigationService, ConfigurationService $configurationService, LoggerInterface $logger, - ProviderService $providerService + ProviderService $providerService, + ProviderStatisticService $providerStatisticService ){ parent::__construct($AppName, $request); @@ -73,6 +75,7 @@ class ProviderController extends Controller { $this->configurationService = $configurationService; $this->logger = $logger; $this->providerService = $providerService; + $this->providerStatisticService = $providerStatisticService; if ($userSession->isLoggedIn()) { $this->user = $userSession->getUser(); @@ -123,4 +126,13 @@ class ProviderController extends Controller { return null; } } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function exportProvidersStatistic(array $providerIds,$year){ + $filenames = $this->providerStatisticService->exportProvidersStatisticByYear($providerIds,$year,$this->idNextcloud); + return json_encode($filenames); + } } diff --git a/gestion/lib/Db/OrderBdd.php b/gestion/lib/Db/OrderBdd.php index 4aa791c..092aa09 100644 --- a/gestion/lib/Db/OrderBdd.php +++ b/gestion/lib/Db/OrderBdd.php @@ -519,4 +519,47 @@ class OrderBdd { $this->addOrderItem($orderId,$lastOrderProductId,$defaultQuantity); return true; } + + public function getProviderOrdersByMonthAndYear($providerId,$month,$year){ + $sql = + "SELECT + orders.id, + orders.order_date, + orders.order_number, + orders.order_full_number, + orders.fk_order_status_key, + orders.fk_order_type_key, + orders.fk_provider_id + FROM ".$this->orderTablePrefix."orders as orders + WHERE + orders.fk_provider_id = ? AND + MONTH(orders.order_date) = ? AND + YEAR(orders.order_date) = ? AND + orders.fk_order_type_key = ? + ORDER BY orders.order_date ASC;"; + + $orders = $this->execSQLNoJsonReturn($sql,[ $providerId,$month,$year,OrderTypeConstant::ORDER_TYPE_PURCHASE]); + return $orders; + } + + public function getItemCountByOrderIdListAndOrderProductId($orderIdsList,$orderProductId){ + if(empty($orderIdsList)){ + return 0; + } + $sqlConditionsPlaceholder = implode(',', array_fill(0, count($orderIdsList), '?')); + $sql = "SELECT + SUM(order_item.quantity) as total_quantity + FROM ".$this->orderTablePrefix ."order_item as order_item + WHERE order_item.fk_order_id IN ($sqlConditionsPlaceholder) AND + order_item.fk_order_item_id = ?;"; + + $produitList = $this->execSQLNoJsonReturn( + $sql, + array_merge($orderIdsList,array($orderProductId))); + + if(!empty($produitList)){ + return $produitList[0]['total_quantity']; + } + return 0; + } } \ No newline at end of file diff --git a/gestion/lib/Db/ProviderRepository.php b/gestion/lib/Db/ProviderRepository.php index e027b81..909d709 100644 --- a/gestion/lib/Db/ProviderRepository.php +++ b/gestion/lib/Db/ProviderRepository.php @@ -71,4 +71,13 @@ class ProviderRepository { return $count; } + public function getProviderById($providerId){ + $sql = "SELECT * FROM ".$this->gestionTablePrefix."provider as provider WHERE provider.id = ?;"; + $result = $this->execSQLNoJsonReturn($sql,[$providerId]); + if(!empty($result)){ + return $result[0]; + } + return null; + } + } \ No newline at end of file diff --git a/gestion/lib/Service/Provider/Statistic/ProviderStatisticService.php b/gestion/lib/Service/Provider/Statistic/ProviderStatisticService.php new file mode 100644 index 0000000..20fd33e --- /dev/null +++ b/gestion/lib/Service/Provider/Statistic/ProviderStatisticService.php @@ -0,0 +1,167 @@ + + * + * @author Anna Larch + * @author Richard Steinmetz + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU AFFERO GENERAL PUBLIC LICENSE for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with this library. If not, see . + * + */ + +namespace OCA\Gestion\Service\Provider\Statistic; + +use OCA\Gestion\Constants\BddConstant; +use OCA\Gestion\Db\Bdd; +use OCA\Gestion\Db\OrderBdd; +use OCA\Gestion\Db\ProviderRepository; +use OCA\Gestion\Helpers\FileExportHelpers; +use OCP\Files\IRootFolder; +use Psr\Log\LoggerInterface; + +class ProviderStatisticService { + private $providerRepository; + + private $providerStatisticService; + + private $orderRepository; + private $gestionRepository; + + /** @var LoggerInterface */ + private $logger; + + /** @var \OCP\Files\IRootFolder */ + private $rootFolder; + + public function __construct( + ProviderRepository $providerRepository, + LoggerInterface $logger, + OrderBdd $orderBdd, + Bdd $gestionRepository, + IRootFolder $rootFolder) { + $this->logger = $logger; + $this->providerRepository = $providerRepository; + $this->orderRepository = $orderBdd; + $this->gestionRepository = $gestionRepository; + $this->rootFolder = $rootFolder; + } + + private function getProviderOrdersStatisticDataByYear($providerId,$year,$orderProducts){ + $monthLists = range(1,12); + $data = []; + $provider = $this->providerRepository->getProviderById($providerId); + if($provider == null){ + return []; + } + foreach($monthLists as $monthValue){ + if(!isset($data[$monthValue])){ + $data[$monthValue] = []; + } + $providerOrders = $this->orderRepository->getProviderOrdersByMonthAndYear($providerId,$monthValue,$year); + $providerOrderIds = []; + $statisticForeachProductPerMonth = []; + foreach($providerOrders as $currentOrder){ + $providerOrderIds[] = $currentOrder['id']; + } + $productTotalPrices = 0; + foreach($orderProducts as $currentProduct){ + if(!isset($statisticForeachProductPerMonth[$currentProduct->id])){ + $statisticForeachProductPerMonth[$currentProduct->id] = 0; + } + $productTotalCount = $this->orderRepository->getItemCountByOrderIdListAndOrderProductId($providerOrderIds,$currentProduct->id); + $totalWithoutVat = $productTotalCount * $currentProduct->ht_amount; + $statisticForeachProductPerMonth[$currentProduct->id] += $productTotalCount; + $productTotalPrices += $totalWithoutVat; + } + $data[$monthValue] = [ + 'products' => $statisticForeachProductPerMonth, + 'year' => $year, + 'total_price' => $productTotalPrices, + 'provider_name' => $provider['provider_name'] + ]; + } + return $data; + } + + private function getExportProviderStatisticFileHeader(array $orderProducts){ + $fileHeader = + 'FOURNISSEUR'.';'. + 'MOIS'.';'. + 'ANNEE'.';'; + + foreach($orderProducts as $currentProduct){ + $fileHeader .= FileExportHelpers::FormatTextForExport($currentProduct->reference).';'; + } + $fileHeader .= 'TOTAL HT'.';'."\n"; + return $fileHeader; + } + + private function exportProviderStatisticData($providerStatisticData,$orderProducts,$idNextCloud){ + if(empty($providerStatisticData)){ + return null; + } + $defaultConfig = $this->gestionRepository->getConfigurationByIdNextcloud(BddConstant::DEFAULT_ADMIN_APP_ID_NEXTCLOUD); + $racineFolder = html_entity_decode($defaultConfig['path']).'/'; + $statFolder = $racineFolder.'STATISTIQUES/FOURNISSEURS/'.$providerStatisticData[1]['year'].'/'; + $storage = $this->rootFolder->getUserFolder($idNextCloud); + try { + $storage->newFolder($statFolder); + } + catch(\OCP\Files\NotPermittedException $e) { + + } + $fileContent = $this->getExportProviderStatisticFileHeader($orderProducts); + $fileContent = $this->populateProviderStatisticDataIntoFileContent($providerStatisticData,$fileContent); + $filename = $providerStatisticData[1]['year'].'-'.$providerStatisticData[1]['provider_name']; + $filenamePath = $statFolder."STAT-FOURNISSEUR-".$filename.'.csv'; + $storage->newFile($filenamePath); + $file = $storage->get($filenamePath); + $file->putContent($fileContent); + return $filenamePath; + } + + private function populateProviderStatisticDataIntoFileContent(array $providerStatisticData,$fileContent){ + foreach($providerStatisticData as $monthValue => $currentMonthData){ + $fileContent .= FileExportHelpers::FormatTextForExport($currentMonthData['provider_name']).';'; + $fileContent .= $monthValue.';'; + $fileContent .= $currentMonthData['year'].';'; + foreach($currentMonthData['products'] as $currentProduct){ + $fileContent .= $currentProduct.';'; + } + $totalPrice = $currentMonthData['total_price']; + $fileContent .= "$totalPrice".";"."\n"; + } + return $fileContent; + } + + + public function exportProvidersStatisticByYear($providerIds,$year,$idNextCloud){ + $year = $year ?? date('Y'); + $filenames = []; + $orderProducts = $this->orderRepository->getOrderProducts(); + $orderProducts = json_decode($orderProducts); + foreach($providerIds as $providerId){ + $providerOrdersPerMonthInAYear = $this->getProviderOrdersStatisticDataByYear($providerId,$year,$orderProducts); + $filename = $this->exportProviderStatisticData($providerOrdersPerMonthInAYear,$orderProducts,$idNextCloud); + if($filename != null){ + $filenames[] = $filename; + } + } + return $filenames; + } +}