From a2ca0345073fb73248b30629fb0d23dec038f8f3 Mon Sep 17 00:00:00 2001 From: ezway Date: Thu, 4 Sep 2025 17:03:53 +0200 Subject: [PATCH] HOTFIX pdf facture --- gestion/lib/Controller/PageController.php | 6692 +++++++++++---------- gestion/lib/Db/Bdd.php | 2568 ++++---- gestion/lib/Service/InvoicePdfHandler.php | 18 + 3 files changed, 4681 insertions(+), 4597 deletions(-) diff --git a/gestion/lib/Controller/PageController.php b/gestion/lib/Controller/PageController.php index 9f4afdf..9f503c2 100644 --- a/gestion/lib/Controller/PageController.php +++ b/gestion/lib/Controller/PageController.php @@ -2,8 +2,8 @@ namespace OCA\Gestion\Controller; -use FPDF; -use Datetime; +use \FPDF; +use \Datetime; use Exception; use OCA\Gestion\Constants\DevisExportTypeConstant; use OCP\IConfig; @@ -15,8 +15,8 @@ use OCP\IUserSession; use OCP\Mail\IMailer; use OCP\IGroupManager; use OCP\IURLGenerator; -use DatetimeImmutable; -use IntlDateFormatter; +use \DatetimeImmutable; +use \IntlDateFormatter; use OCA\Gestion\Db\Bdd; use OCP\Files\IRootFolder; use OCP\AppFramework\Controller; @@ -38,94 +38,95 @@ use OCA\Gestion\Service\Certificate\CertificateService; date_default_timezone_set('Europe/Paris'); -class PageController extends Controller -{ - private $idNextcloud; - private Bdd $myDb; - // private $src_path = "/var/www/html/apps/gestion/img/"; - private $src_path = "/var/www/html/custom_apps/gestion/img/"; +class PageController extends Controller { - private $sharedImagePath = "/var/www/html/data/"; - private $defaultImagePath; + private $idNextcloud; + private Bdd $myDb; + // private $src_path = "/var/www/html/apps/gestion/img/"; + private $src_path = "/var/www/html/custom_apps/gestion/img/"; - private const HYTHA_35_DEFAULT_ADMIN = "Johann"; - private const H2F_DEFAULT_ADMIN = "Emmanuelle"; - private const DEFAULT_NEXTCLOUD_ADMIN = "admin"; - private $urlGenerator; - private $mailer; - private $config; + private $sharedImagePath = "/var/www/html/data/"; + private $defaultImagePath; - /** @var IRootStorage */ - private $storage; + private const HYTHA_35_DEFAULT_ADMIN = "Johann"; + private const H2F_DEFAULT_ADMIN = "Emmanuelle"; + private const DEFAULT_NEXTCLOUD_ADMIN = "admin"; + private $urlGenerator; + private $mailer; + private $config; - private $user; - private $groups = []; + /** @var IRootStorage */ + private $storage; - /** @var ExportThanatoStatisticService */ - private $exportThanatoStatisticService; + private $user; + private $groups = []; - /** @var \OCA\Gestion\Service\ExportClientStatisticService */ - private $exportClientStatisticService; + /** @var ExportThanatoStatisticService */ + private $exportThanatoStatisticService; - /** @var InvoicePdfService */ - private $invoicePdfService; + /** @var \OCA\Gestion\Service\ExportClientStatisticService */ + private $exportClientStatisticService; - /** @var CertificateService */ - private $certificateService; + /** @var InvoicePdfService */ + private $invoicePdfService; - private $adminStorage; + /** @var CertificateService */ + private $certificateService; - /** @var TalkService */ - private $talkService; + private $adminStorage; - /** @var DevisPdfService */ - private $devisPdfService; - private $rootFolder; + /** @var TalkService */ + private $talkService; - private $mailerService; + /** @var DevisPdfService */ + private $devisPdfService; + private $rootFolder; + + private $mailerService; - /** - * Constructor - */ - public function __construct( - $AppName, - IRequest $request, - $UserId, - Bdd $myDb, - IRootFolder $rootFolder, - IURLGenerator $urlGenerator, - IMailer $mailer, - Iconfig $config, - IUserSession $userSession, - IGroupManager $groupManager, - ExportThanatoStatisticService $exportThanatoStatisticService, - ExportClientStatisticService $exportClientStatisticService, - InvoicePdfService $invoicePdfService, - CertificateService $certificateService, - TalkService $talkService, - DevisPdfService $devisPdfService, - MailerService $mailerService, - ) { + /** + * Constructor + */ + public function __construct($AppName, - parent::__construct($AppName, $request); + IRequest $request, + $UserId, + Bdd $myDb, + IRootFolder $rootFolder, + IURLGenerator $urlGenerator, + IMailer $mailer, + Iconfig $config, + IUserSession $userSession, + IGroupManager $groupManager, + ExportThanatoStatisticService $exportThanatoStatisticService, + ExportClientStatisticService $exportClientStatisticService, + InvoicePdfService $invoicePdfService, + CertificateService $certificateService, + TalkService $talkService, + DevisPdfService $devisPdfService, + MailerService $mailerService, + + ) { - $this->idNextcloud = $UserId; - $this->myDb = $myDb; - $this->urlGenerator = $urlGenerator; - $this->mailer = $mailer; - $this->config = $config; - $this->exportThanatoStatisticService = $exportThanatoStatisticService; - $this->exportClientStatisticService = $exportClientStatisticService; - $this->invoicePdfService = $invoicePdfService; - $this->certificateService = $certificateService; - $this->defaultImagePath = $this->sharedImagePath.self::DEFAULT_NEXTCLOUD_ADMIN.'/files/.gestion/'; - $this->talkService = $talkService; - $this->devisPdfService = $devisPdfService; - $this->rootFolder = $rootFolder; - $this->mailerService = $mailerService; - //$this->fpdf = $fpdf; + parent::__construct($AppName, $request); + + $this->idNextcloud = $UserId; + $this->myDb = $myDb; + $this->urlGenerator = $urlGenerator; + $this->mailer = $mailer; + $this->config = $config; + $this->exportThanatoStatisticService = $exportThanatoStatisticService; + $this->exportClientStatisticService = $exportClientStatisticService; + $this->invoicePdfService = $invoicePdfService; + $this->certificateService = $certificateService; + $this->defaultImagePath = $this->sharedImagePath.self::DEFAULT_NEXTCLOUD_ADMIN.'/files/.gestion/'; + $this->talkService = $talkService; + $this->devisPdfService = $devisPdfService; + $this->rootFolder = $rootFolder; + $this->mailerService = $mailerService; + //$this->fpdf = $fpdf; if ($userSession->isLoggedIn()) { $this->user = $userSession->getUser(); @@ -139,269 +140,269 @@ class PageController extends Controller } } - try { - $this->storage = $rootFolder->getUserFolder($this->idNextcloud); - } catch(\OC\User\NoUserException $e) { + try{ + $this->storage = $rootFolder->getUserFolder($this->idNextcloud); + }catch(\OC\User\NoUserException $e){ - } + } - try { - $this->adminStorage = $rootFolder->getUserFolder(self::DEFAULT_NEXTCLOUD_ADMIN); - } catch(\OC\User\NoUserException $e) { + try{ + $this->adminStorage = $rootFolder->getUserFolder(self::DEFAULT_NEXTCLOUD_ADMIN); + }catch(\OC\User\NoUserException $e){ - } + } + + } - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * + /** + * @NoAdminRequired + * @NoCSRFRequired + * */ - public function index() - { - return new TemplateResponse('gestion', 'index', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/index.php - } + public function index() { - /** - * @NoAdminRequired - * @NoCSRFRequired - * + return new TemplateResponse('gestion', 'index', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/index.php + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * */ - public function defunt() - { + public function defunt() { + return new TemplateResponse('gestion', 'defunt', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/thanatopracteur.php } - /** - * @NoAdminRequired - * @NoCSRFRequired - * + /** + * @NoAdminRequired + * @NoCSRFRequired + * */ - public function thanatopracteur() - { + public function thanatopracteur() { + $this->denyIfNotAdmin(); return new TemplateResponse('gestion', 'thanatopracteur', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/thanatopracteur.php } - /** - * @NoAdminRequired - * @NoCSRFRequired + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function devis() - { - return new TemplateResponse('gestion', 'devis', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/devis.php - } + public function devis() { - /** - * @NoAdminRequired - * @NoCSRFRequired + return new TemplateResponse('gestion', 'devis', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/devis.php + } + + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function trajet() - { + public function trajet() { + $this->denyIfNotAdmin(); - return new TemplateResponse('gestion', 'trajet', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/trajet.php - } + return new TemplateResponse('gestion', 'trajet', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/trajet.php + } - /** - * @NoAdminRequired - * @NoCSRFRequired + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function lieu() - { - return new TemplateResponse('gestion', 'lieu', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/lieu.php - } + public function lieu() { - /** - * @NoAdminRequired - * @NoCSRFRequired + return new TemplateResponse('gestion', 'lieu', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/lieu.php + } + + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function facture() - { + public function facture() { + $this->denyIfNotAdmin(); - $facturePaymentTypeList = $this->myDb->getFacturePaymentList(); - return new TemplateResponse('gestion', 'facture', array( - 'groups' => $this->groups, - 'user' => $this->user, - 'path' => $this->idNextcloud, - 'paymentTypes' => json_decode($facturePaymentTypeList), - 'url' => $this->getNavigationLink())); // templates/facture.php - } + $facturePaymentTypeList = $this->myDb->getFacturePaymentList(); + return new TemplateResponse('gestion', 'facture', array( + 'groups' => $this->groups, + 'user' => $this->user, + 'path' => $this->idNextcloud, + 'paymentTypes' => json_decode($facturePaymentTypeList), + 'url' => $this->getNavigationLink())); // templates/facture.php + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function article() { - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function article() - { $this->denyIfNotAdmin(); - return new TemplateResponse('gestion', 'article', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/produit.php - } + return new TemplateResponse('gestion', 'article', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/produit.php + } - /** - * @NoAdminRequired - * @NoCSRFRequired + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function produit() - { + public function produit() { + $this->denyIfNotAdmin(); - return new TemplateResponse('gestion', 'produit', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/produit.php - } + return new TemplateResponse('gestion', 'produit', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/produit.php + } - /** - * @NoAdminRequired - * @NoCSRFRequired + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function bibliotheque() - { + public function bibliotheque() { + $this->denyIfNotAdmin(); return new TemplateResponse('gestion', 'bibliotheque', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/produit.php } - /** - * @NoAdminRequired - * @NoCSRFRequired + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function statistique() - { + public function statistique() { + $this->denyIfNotAdmin(); - return new TemplateResponse('gestion', 'statistique', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/statistique.php - } + return new TemplateResponse('gestion', 'statistique', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/statistique.php + } - /** - * @NoAdminRequired - * @NoCSRFRequired + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function legalnotice($page) - { - return new TemplateResponse('gestion', 'legalnotice', array('groups' => $this->groups, 'user' => $this->user, 'page' => 'content/legalnotice', 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/legalnotice.php - } + public function legalnotice($page) { - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function france() - { - return new TemplateResponse('gestion', 'legalnotice', array('groups' => $this->groups, 'user' => $this->user, 'page' => 'legalnotice/france', 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/legalnotice.php - } + return new TemplateResponse('gestion', 'legalnotice', array('groups' => $this->groups, 'user' => $this->user, 'page' => 'content/legalnotice', 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/legalnotice.php + } - /** - * @NoAdminRequired - * @NoCSRFRequired + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function config() - { - $this->myDb->checkConfig($this->idNextcloud); - return new TemplateResponse('gestion', 'configuration', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/configuration.php - } + public function france() { - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numdevis - */ - public function devisshow($numdevis) - { - $devis = $this->myDb->getOneDevis($numdevis, $this->idNextcloud); - $articles = $this->myDb->getListArticle($numdevis, $this->idNextcloud); - $produits = $this->myDb->getListProduit($numdevis, $this->idNextcloud); - return new TemplateResponse('gestion', 'devisshow', array( 'groups' => $this->groups, 'user' => $this->user, 'configuration' => $this->getConfiguration(), - 'devis' => json_decode($devis), - 'produit' => json_decode($produits), - 'article' => json_decode($articles), - 'path' => $this->idNextcloud, - 'url' => $this->getNavigationLink(), - 'logo' => $this->getLogo() - )); - } + return new TemplateResponse('gestion', 'legalnotice', array('groups' => $this->groups, 'user' => $this->user, 'page' => 'legalnotice/france', 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/legalnotice.php + } - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numdefunt + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function defuntshow($numdefunt) - { - $defunt = $this->myDb->getOneDefunt($numdefunt, $this->idNextcloud, true); - $coverProducts = $this->myDb->getCoverProducts(); - return new TemplateResponse('gestion', 'defuntshow', array( 'groups' => $this->groups, 'user' => $this->user, 'configuration' => $this->getConfiguration(), - 'defunt' => json_decode($defunt), - 'path' => $this->idNextcloud, - 'url' => $this->getNavigationLink(), - 'logo' => $this->getLogo(), - 'coverProducts' => json_decode($coverProducts) - )); - } + public function config() { - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numtrajet + $this->myDb->checkConfig($this->idNextcloud); + return new TemplateResponse('gestion', 'configuration', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/configuration.php + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numdevis */ - public function trajetdetails($numtrajet) - { + public function devisshow($numdevis) { + + $devis = $this->myDb->getOneDevis($numdevis,$this->idNextcloud); + $articles = $this->myDb->getListArticle($numdevis, $this->idNextcloud); + $produits = $this->myDb->getListProduit($numdevis, $this->idNextcloud); + return new TemplateResponse('gestion', 'devisshow', array( 'groups' => $this->groups, 'user' => $this->user, 'configuration'=> $this->getConfiguration(), + 'devis'=>json_decode($devis), + 'produit'=>json_decode($produits), + 'article'=>json_decode($articles), + 'path' => $this->idNextcloud, + 'url' => $this->getNavigationLink(), + 'logo' => $this->getLogo() + )); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numdefunt + */ + public function defuntshow($numdefunt) { + + $defunt = $this->myDb->getOneDefunt($numdefunt,$this->idNextcloud,true); + $coverProducts = $this->myDb->getCoverProducts(); + return new TemplateResponse('gestion', 'defuntshow', array( 'groups' => $this->groups, 'user' => $this->user, 'configuration'=> $this->getConfiguration(), + 'defunt'=>json_decode($defunt), + 'path' => $this->idNextcloud, + 'url' => $this->getNavigationLink(), + 'logo' => $this->getLogo(), + 'coverProducts' =>json_decode($coverProducts) + )); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numtrajet + */ + public function trajetdetails($numtrajet) { + $this->denyIfNotAdmin(); - $trajet = $this->myDb->getTrajetById($numtrajet, $this->idNextcloud); - return new TemplateResponse('gestion', 'trajetdetails', array( + $trajet = $this->myDb->getTrajetById($numtrajet, $this->idNextcloud); + return new TemplateResponse('gestion', 'trajetdetails', array( 'groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, - 'url' => $this->getNavigationLink(), - 'trajet' => json_decode($trajet) - ));// templates/trajetdetails.php - } + 'url' => $this->getNavigationLink(), + 'trajet' => json_decode($trajet) + ));// templates/trajetdetails.php + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numfacture + */ + public function factureshow($numfacture) { - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numfacture - */ - public function factureshow($numfacture) - { $this->denyIfNotAdmin(); - $facture = $this->myDb->getOneFacture($numfacture, $this->idNextcloud); - return new TemplateResponse('gestion', 'factureshow', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, - 'configuration' => $this->getConfiguration(), - 'facture' => json_decode($facture), - 'url' => $this->getNavigationLink(), - 'logo' => $this->getLogo() - )); - } + $facture = $this->myDb->getOneFacture($numfacture,$this->idNextcloud); + return new TemplateResponse('gestion', 'factureshow', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, + 'configuration'=> $this->getConfiguration(), + 'facture'=>json_decode($facture), + 'url' => $this->getNavigationLink(), + 'logo' => $this->getLogo() + )); + } - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function apercustousdevis() - { - $devisMentionsFilter = [ - DevisMentionConstant::FACTURED, - DevisMentionConstant::FACTURED_FORMATTED, - DevisMentionConstant::MENTION, - DevisMentionConstant::NEW - ]; - $devis = json_decode($this->myDb->getDevis($this->idNextcloud, $devisMentionsFilter)); - foreach ($devis as $key => $d) { - $d->dproduits = []; - $produits = json_decode($this->myDb->getListProduit($d->id, $this->idNextcloud)); - $d->dproduits = $produits; - } - $clients = json_decode($this->myDb->getClientsAndClientGroupFacturations(includeClientInsideGroup:false)); - usort($clients, function ($a, $b) { - return strcmp($a->nom, $b->nom); - }); - return new TemplateResponse('gestion', 'apercustousdevis', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, - 'configuration' => $this->getConfiguration(), - 'devis' => $devis, - 'clients' => $clients, - 'url' => $this->getNavigationLink(), - 'logo' => $this->getLogo() - )); - } + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function apercustousdevis() { + + $devisMentionsFilter = [ + DevisMentionConstant::FACTURED, + DevisMentionConstant::FACTURED_FORMATTED, + DevisMentionConstant::MENTION, + DevisMentionConstant::NEW + ]; + $devis = json_decode($this->myDb->getDevis($this->idNextcloud,$devisMentionsFilter)); + foreach ($devis as $key => $d) { + $d->dproduits = []; + $produits = json_decode($this->myDb->getListProduit($d->id, $this->idNextcloud)); + $d->dproduits = $produits; + } + $clients = json_decode($this->myDb->getClientsAndClientGroupFacturations(includeClientInsideGroup:false )); + usort($clients, function($a, $b) { + return strcmp($a->nom, $b->nom); + }); + return new TemplateResponse('gestion', 'apercustousdevis', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, + 'configuration'=> $this->getConfiguration(), + 'devis'=> $devis, + 'clients'=> $clients, + 'url' => $this->getNavigationLink(), + 'logo' => $this->getLogo() + )); + } + + protected function denyIfNotAdmin() { - protected function denyIfNotAdmin() - { /* if(empty($this->groups) || !in_array("admin", $this->groups)) { http_response_code(403); @@ -411,52 +412,52 @@ class PageController extends Controller */ } - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function apercustoutesfactures() - { + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function apercustoutesfactures() { + $this->denyIfNotAdmin(); - $factures = json_decode($this->myDb->getFactures($this->idNextcloud)); - foreach ($factures as $key => $facture) { - $facture->dproduits = []; - $produits = json_decode($this->myDb->getListProduit($facture->id_devis, $this->idNextcloud)); - $facture->dproduits = $produits; - } - $clients = json_decode($this->myDb->getClientsAndClientGroupFacturations()); - usort($clients, function ($a, $b) { - return strcmp($a->nom, $b->nom); - }); - return new TemplateResponse('gestion', 'apercustoutesfactures', array( 'groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, - 'configuration' => $this->getConfiguration(), - 'factures' => $factures, - 'clients' => $clients, - 'url' => $this->getNavigationLink(), - 'logo' => $this->getLogo() - )); - } + $factures = json_decode($this->myDb->getFactures($this->idNextcloud)); + foreach ($factures as $key => $facture) { + $facture->dproduits = []; + $produits = json_decode($this->myDb->getListProduit($facture->id_devis, $this->idNextcloud)); + $facture->dproduits = $produits; + } + $clients = json_decode($this->myDb->getClientsAndClientGroupFacturations()); + usort($clients, function($a, $b) { + return strcmp($a->nom, $b->nom); + }); + return new TemplateResponse('gestion', 'apercustoutesfactures', array( 'groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, + 'configuration'=> $this->getConfiguration(), + 'factures'=> $factures, + 'clients'=> $clients, + 'url' => $this->getNavigationLink(), + 'logo' => $this->getLogo() + )); + } - /** - * @NoAdminRequired - * @NoCSRFRequired + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function isConfig() - { - $idNextcloud = "admin"; - return $this->myDb->isConfig($idNextcloud); - } + public function isConfig() { + + $idNextcloud = "admin"; + return $this->myDb->isConfig($idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getNavigationLink(){ - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getNavigationLink() - { return array( "index" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.index"), - "clientGroups" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.clientGroups"), - "clientGroupFacturation" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.clientGroupFacturation"), + "clientGroups" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.clientGroups"), + "clientGroupFacturation" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.clientGroupFacturation"), "defunt" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.defunt"), "devis" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.devis"), "thanatopracteur" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.thanatopracteur"), @@ -464,7 +465,7 @@ class PageController extends Controller "lieu" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.lieu"), "facture" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.facture"), "produit" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.produit"), - "clientGroupDiscount" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.clientGroupDiscount"), + "clientGroupDiscount" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.clientGroupDiscount"), "article" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.article"), "bibliotheque" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.bibliotheque"), "config" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.config"), @@ -473,1462 +474,1466 @@ class PageController extends Controller "legalnotice" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.legalnotice"), "france" => $this->urlGenerator->linkToRouteAbsolute("gestion.page.france"), ); - } + } - /** - * @NoAdminRequired - * @NoCSRFRequired + /** + * @NoAdminRequired + * @NoCSRFRequired */ - public function getClients() - { - // $this->myDb->init_trajets_data($this->idNextcloud); - $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); - // if(strcmp(strtolower($current_config[0]->id_nextcloud), 'delphine')!=0) { - // $today = date('d-m-Y'); - // $lastDayThisMonth = date('t-m-Y'); - // if ($today == $lastDayThisMonth) { - // $this->generer_document_comptable($today); - // $this->generer_recap_ogf($today); - // } - // } - return $this->myDb->getClients($this->idNextcloud); - } + public function getClients() { - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getThanatopracteurs() - { - return $this->myDb->getThanatopracteurs($this->idNextcloud); - } + // $this->myDb->init_trajets_data($this->idNextcloud); + $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); + // if(strcmp(strtolower($current_config[0]->id_nextcloud), 'delphine')!=0) { + // $today = date('d-m-Y'); + // $lastDayThisMonth = date('t-m-Y'); + // if ($today == $lastDayThisMonth) { + // $this->generer_document_comptable($today); + // $this->generer_recap_ogf($today); + // } + // } + return $this->myDb->getClients($this->idNextcloud); + } - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function ajaxGetThanatopracteurs() - { - return $this->myDb->getThanatopracteurs($this->idNextcloud); - } + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getThanatopracteurs() { - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function insertThanatopracteur() - { - return $this->myDb->insertThanatopracteur($this->idNextcloud); - } + return $this->myDb->getThanatopracteurs($this->idNextcloud); + } - private function generer_indemnite_kilometrique($date) - { - $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); - $clean_folder = html_entity_decode($current_config[0]->path).'/'; + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function ajaxGetThanatopracteurs() { - $formatter_ds = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::NONE); - $formatter_ds->setPattern('dd-MMM'); + return $this->myDb->getThanatopracteurs($this->idNextcloud); + } - try { - try { - $data_trajets = json_decode($this->myDb->getCurrentMonthTrajet($this->idNextcloud, $date)); - $data_trajets = array_filter($data_trajets, function ($trajet) {return $trajet->lieu_depart != null && $trajet->lieu_arrivee != null;}); + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function insertThanatopracteur() { - $ik_txt = 'Date'.TAB1.utf8_decode('Départ').TAB1.utf8_decode('Arrivée').TAB1.'Distance'.PHP_EOL; - $ik_csv = 'Date'.';'.utf8_decode('Départ').';'.utf8_decode('Arrivée').';'.'Distance'.';'."\n"; + return $this->myDb->insertThanatopracteur($this->idNextcloud); + } - $date_trajet = $data_trajets[0]->date; - $annee = explode('-', $date_trajet)[0]; - $mois = explode('-', $date_trajet)[1]; + private function generer_indemnite_kilometrique($date) { - $_clean_folder = $clean_folder.'INDEMNITES KILOMETRIQUES/'.$annee.'/'.strtoupper($trajet->id_nextcloud).'/'; + $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); + $clean_folder = html_entity_decode($current_config[0]->path).'/'; - try { - $this->storage->newFolder($_clean_folder); - } catch(\OCP\Files\NotPermittedException $e) { - } + $formatter_ds = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::NONE); + $formatter_ds->setPattern('dd-MMM'); - foreach ($data_trajets as $key => $trajet) { + try { + try { + $data_trajets = json_decode($this->myDb->getCurrentMonthTrajet($this->idNextcloud, $date)); + $data_trajets = array_filter($data_trajets, function($trajet) {return $trajet->lieu_depart !=NULL && $trajet->lieu_arrivee != NULL;}); - $date_trajet_temp = new DateTime($trajet->date); + $ik_txt = 'Date'.TAB1.utf8_decode('Départ').TAB1.utf8_decode('Arrivée').TAB1.'Distance'.PHP_EOL; + $ik_csv = 'Date'.';'.utf8_decode('Départ').';'.utf8_decode('Arrivée').';'.'Distance'.';'."\n"; - $ik_txt = $ik_txt.utf8_decode($formatter_ds->format($date_trajet_temp)).TAB1.$trajet->lieu_depart.TAB1.$trajet->lieu_arrivee.TAB1.$trajet->distance.PHP_EOL; - $ik_csv = $ik_csv.utf8_decode($formatter_ds->format($date_trajet_temp)).';'.$trajet->lieu_depart.';'.$trajet->lieu_arrivee.';'.$trajet->distance."\n"; + $date_trajet = $data_trajets[0]->date; + $annee = explode('-', $date_trajet)[0]; + $mois = explode('-', $date_trajet)[1]; - } - $ff = $_clean_folder.'IK_'.strtoupper($trajet->id_nextcloud).'_'.$mois.'_'.$annee.'.csv'; - $this->storage->newFile($ff); - $file = $this->storage->get($ff); - $file->putContent($ik_csv); + $_clean_folder = $clean_folder.'INDEMNITES KILOMETRIQUES/'.$annee.'/'.strtoupper($trajet->id_nextcloud).'/'; - $ff_txt = $_clean_folder.'IK_'.strtoupper($trajet->id_nextcloud).'_'.$mois.'_'.$annee.'.txt'; - $this->storage->newFile($ff_txt); - $file_txt = $this->storage->get($ff_txt); - $file_txt->putContent($ik_txt); + try { + $this->storage->newFolder($_clean_folder); + } catch(\OCP\Files\NotPermittedException $e) { } - } catch(\OCP\Files\NotFoundException $e) { - } + + foreach ($data_trajets as $key => $trajet) { + + $date_trajet_temp = new DateTime($trajet->date); + + $ik_txt = $ik_txt.utf8_decode($formatter_ds->format($date_trajet_temp)).TAB1.$trajet->lieu_depart.TAB1.$trajet->lieu_arrivee.TAB1.$trajet->distance.PHP_EOL; + $ik_csv = $ik_csv.utf8_decode($formatter_ds->format($date_trajet_temp)).';'.$trajet->lieu_depart.';'.$trajet->lieu_arrivee.';'.$trajet->distance."\n"; + + } + $ff = $_clean_folder.'IK_'.strtoupper($trajet->id_nextcloud).'_'.$mois.'_'.$annee.'.csv'; + $this->storage->newFile($ff); + $file = $this->storage->get($ff); + $file->putContent($ik_csv); + + $ff_txt = $_clean_folder.'IK_'.strtoupper($trajet->id_nextcloud).'_'.$mois.'_'.$annee.'.txt'; + $this->storage->newFile($ff_txt); + $file_txt = $this->storage->get($ff_txt); + $file_txt->putContent($ik_txt); + + } catch(\OCP\Files\NotFoundException $e) { } + } catch(\OCP\Files\NotPermittedException $e) { } + + } + + + private function generer_recap_ogf($date) { + + $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); + try { + try { + $data_factures = array(); + $factures = json_decode($this->myDb->getCurrentMonthFactures_COGF($this->idNextcloud, $date)); + $factures = array_filter($factures, function($facture) {return $facture->id_client != NULL; }); + foreach ($factures as $key => $facture) { + $facture_temp = array( + 'num' => $facture->num, + 'id_client' => $facture->id_client, + 'client' => $facture->entreprise, + 'adresse_client' => $facture->adresse_client, + 'adresse_devis' => $facture->lieu, + 'nom_client' => html_entity_decode($facture->nom), + 'prenoms_client' => html_entity_decode($facture->prenom), + 'date_soin' => $facture->date_soin, + 'numero_commande' => $facture->numero_commande, + 'date' => $facture->date, + 'date_facture' => $facture->date_paiement, + 'defunt' => $facture->nom_defunt, + 'montant_htc' => 0, + 'tva' => $current_config[0]->tva_default, + 'montant_tva' => 0, + 'montant_ttc' => 0, + ); + $produits = json_decode($this->getProduitsById($facture->id_devis)); + foreach ($produits as $key => $produit) { + $facture_temp['montant_htc'] += $produit->prix_unitaire * $produit->quantite; + }; + $facture_temp['montant_tva'] = ($facture_temp['montant_htc'] * $facture_temp['tva'])/100; + $facture_temp['montant_ttc'] = $facture_temp['montant_tva'] + $facture_temp['montant_htc']; + + array_push($data_factures, $facture_temp); + }; + + $data_temp = array(); + foreach ($data_factures as $key => $facture) { + $datesplit = explode('-', $facture['date_facture']); + if($data_temp[strval($datesplit[0])][strval($datesplit[1])]==NULL) { + $data_temp[strval($datesplit[0])][strval($datesplit[1])] = array(0=>$facture); + } else { + array_push($data_temp[strval($datesplit[0])][strval($datesplit[1])], $facture); + } + } + + foreach ($data_temp as $key_annee => $annee) { + foreach ($annee as $key_mois => $mois) { + $pdf = new FPDF(); + + $date_facture = $mois[0]['date_facture']; + $date_temp = date("t-m-Y", strtotime($date_facture)); + $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE); + $date_formated = $formatter->format(DateTime::createFromFormat('d-m-Y', $date_temp)); + + try { + $this->storage->newFolder(html_entity_decode($current_config[0]->path).'/DOCUMENTS RECAPITULATIFS/'.$key_annee.'/'.$key_mois.' '.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'/'); + } catch(\OCP\Files\NotPermittedException $e) { } + + + $pdf->AddPage(); + // on sup les 2 cm en bas + $pdf->SetAutoPagebreak(False); + $pdf->SetMargins(0,0,0); + + // logo : 80 de largeur et 55 de hauteur + $pdf->Image($this->src_path."logo.png", 4, 2, 50, 35); + // adresse du facture + $pdf->SetFont('Arial','B',11); $_x = 122 ; $_y = 40; + $pdf->SetXY( $_x, $_y ); $pdf->Cell( 100, 8, utf8_decode('Groupe COGF'), 0, 0, ''); $_y += 8; + + + + + // date facture + $pdf->SetFont('Arial','',11); $pdf->SetXY( 122, 60 ); + + $pdf->Cell( 60, 8, "Bourges France le, ".utf8_decode($date_formated), 0, 0, ''); + + // observations + $pdf->SetFont( "Arial", "BU", 10 ); $pdf->SetXY( 10, 85 ) ; $pdf->Cell($pdf->GetStringWidth("Objet:"), 0, "Objet:", 0, "L"); + + + $objet = utf8_decode("Récapitulatif Facturation du mois de ").strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])); + $pdf->SetFont( "Arial", "", 10 ); $pdf->SetXY( $pdf->GetStringWidth("Objet")+15, 85 ) ; $pdf->Cell($pdf->GetStringWidth($objet), 0, $objet, 0, "L"); + + + + $pdf->SetFont( "Arial", "", 10 ); $pdf->SetXY( $pdf->GetStringWidth("Objet")+15, 95 ); $pdf->Cell($pdf->GetStringWidth("Madame, Monsieur"), 0, "Madame, Monsieur", 0, "L"); + + + + $text1 = utf8_decode("Veuillez trouver ci-dessous le récapitulatif de la facturation du mois de ").strtoupper($this->convert_special_char(explode(' ', $date_formated)[1]))."."; + $text2 = utf8_decode("Vous en souhaitant bonne réception."); + $text3 = utf8_decode("Veuillez agréer, Madame, Monsieur, mes salutations les meilleures."); + + $pdf->SetFont( "Arial", "", 10 ); $pdf->SetXY( $pdf->GetStringWidth("Objet")+15, 105 ) ; $pdf->Cell($pdf->GetStringWidth($text1), 0, $text1, 0, "L"); + $pdf->SetFont( "Arial", "", 10 ); $pdf->SetXY( $pdf->GetStringWidth("Objet")+15, 110 ) ; $pdf->Cell($pdf->GetStringWidth($text2), 0, $text2, 0, "L"); + $pdf->SetFont( "Arial", "", 10 ); $pdf->SetXY( $pdf->GetStringWidth("Objet")+15, 120 ) ; $pdf->Cell($pdf->GetStringWidth($text3), 0, $text3, 0, "L"); + + + + + + + + // signature + $pdf->SetFont('Arial','',11); $pdf->SetXY( 122, 145 ); + + $pdf->Cell( $pdf->GetStringWidth($current_config[0]->nom.' '.$current_config[0]->prenom), 0, utf8_decode(html_entity_decode($current_config[0]->nom.' '.$current_config[0]->prenom)), 0, 0, 'L'); + $pdf->Image($this->src_path."sign.png", 122, 150, 55, 30); + + $y0 = 260; + $pageWidth = $pdf->GetPageWidth(); + //Positionnement en bas et tout centrer + $pdf->SetFont('Arial','',6); + + $pdf->SetXY( 1, $y0 + 4 ); $pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_one)), 0, 0, 'C'); + $pdf->SetXY( 1, $y0 + 8 ); $pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_two)), 0, 0, 'C'); + $pdf->SetXY( 1, $y0 + 12 ); $pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->telephone)), 0, 0, 'C'); + + + + + /*$pdf->SetXY( 1, $y0 + 16 ); + $pdf->Cell( $pageWidth, 5, utf8_decode("SIREN 751621293"), 0, 0, 'C');*/ + + $num_page = 1; + $nb_page = ceil(sizeof($mois) / 26); + $index_facture_position = 0; + $max_nb_toget = (sizeof($mois)<=26)?sizeof($mois):26; + + $montant_ht_total = 0; + $montant_tva_total = 0; + $montant_ttc_total = 0; + + while ($num_page <= $nb_page) { + $pdf->AddPage(); + // on sup les 2 cm en bas + $pdf->SetAutoPagebreak(False); + $pdf->SetMargins(0,0,0); + + $pdf->Image($this->src_path."logo.png", 4, 2, 50, 35); + + // n° page en haute à droite + if($nb_page>1){ + $pdf->SetXY( 120, 5 ); $pdf->SetFont( "Arial", "B", 9 ); $pdf->Cell( 160, 8, $num_page . '/' . $nb_page, 0, 0, 'C'); + + + } + + // date facture + $pdf->SetFont('Arial','',11); $pdf->SetXY( 122, 15 ); + + $pdf->Cell( 60, 8, "Bourges France, le ".utf8_decode($date_formated), 0, 0, ''); + + // n° facture, date echeance et reglement et obs + $pdf->SetLineWidth(0.1); $pdf->SetFillColor(255); $pdf->Rect(100, 30, 85, 8, "DF"); + $pdf->SetXY( 100, 30 ); $pdf->SetFont( "Arial", "B", 12 ); $pdf->Cell( 85, 8, 'FACTURE N'.utf8_decode('°').' ETS/'.$key_annee.'/'.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])), 0, 0, 'C'); + + + + + + // adresse du facture + $pdf->SetFont('Arial','B',11); $x = 122 ; $y = 50; + + + // $pdf->SetXY( $x, $y ); $pdf->Cell( 100, 8, 'doit', 0, 0, ''); $y += 8; + $pdf->SetXY( $x, $y ); $pdf->MultiCell( 80, 4, 'Groupe OGF', 0, 0, ''); + + + // *********************** + // le cadre des articles + // *********************** + // cadre avec 18 lignes max ! et 118 de hauteur --> 80 + 118 = 198 pour les traits verticaux + $pdf->SetLineWidth(0.1); $pdf->Rect(5, 80, 200, 153, "D"); + + // cadre titre des colonnes + $pdf->Line(5, 90, 205, 90); + // les traits verticaux colonnes + $pdf->Line(145, 80, 145, 233); $pdf->Line(163, 80, 163, 233); + if($num_page == $nb_page) $pdf->Line(183, 80, 183, 240); + else $pdf->Line(183, 80, 183, 233); + + + + + // titre colonne + $pdf->SetXY( 1, 81 ); $pdf->SetFont('Arial','B',8); $pdf->Cell( 140, 8, "OBJET", 0, 0, 'C'); + $pdf->SetXY( 147, 81 ); $pdf->SetFont('Arial','B',8); $pdf->Cell( 13, 8, "H.T.", 0, 0, 'C'); + $pdf->SetXY( 168, 81 ); $pdf->SetFont('Arial','B',8); $pdf->Cell( 10, 8, "TVA 20%", 0, 0, 'C'); + $pdf->SetXY( 183, 81 ); $pdf->SetFont('Arial','B',8); $pdf->Cell( 22, 8, "T.T.C", 0, 0, 'C'); + + + + + + + + + + // (new DateTime($facture['date_soin']))->format('d-M') + $formatter_ds = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::NONE); + + // Set the pattern for the formatter to "d-MMMM" to display the day and month name in French + $formatter_ds->setPattern('dd-MMM'); + + //recuperation des factures + $y_facture = 90; + + $init_index = $index_facture_position; + + for ($index_facture_position; $index_facture_position < ($init_index + $max_nb_toget) ; $index_facture_position++) { + $date_soin_temp = new DateTime($mois[$index_facture_position]['date_soin']); + + $pdf->SetXY( 6, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 28, 8, $mois[$index_facture_position]['num'], 0, 0, ''); + $pdf->SetXY( 32, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 28, 8, $mois[$index_facture_position]['numero_commande'], 0, 0, ''); + $pdf->SetXY( 53, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 18, 8, utf8_decode($formatter_ds->format($date_soin_temp)), 0, 0, ''); + $pdf->SetXY( 65, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 38, 8, $mois[$index_facture_position]['prenoms_client'].' '.$mois[$index_facture_position]['nom_client'], 0, 0, ''); + $pdf->SetXY( 100, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 28, 8, utf8_decode(html_entity_decode($mois[$index_facture_position]['defunt'])), 0, 0, ''); + $pdf->SetXY( 147, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 13, 8, $mois[$index_facture_position]['montant_htc'].chr(128), 0, 0, 'C'); + $pdf->SetXY( 168, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 10, 8, $mois[$index_facture_position]['montant_tva'].chr(128), 0, 0, 'C'); + $pdf->SetXY( 183, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 22, 8, $mois[$index_facture_position]['montant_ttc'].chr(128), 0, 0, 'C'); + + + + + + + + + + + + + + + + + + $montant_ht_total = $montant_ht_total+$mois[$index_facture_position]['montant_htc']; + $montant_tva_total = $montant_tva_total+$mois[$index_facture_position]['montant_tva']; + $montant_ttc_total = $montant_ttc_total+$mois[$index_facture_position]['montant_ttc']; + + $y_facture=$y_facture+5; + } + + $nb_facture_chargee = $index_facture_position+1; + $reste_a_chargee = sizeof($mois) - $nb_facture_chargee; + $max_nb_toget = ($reste_a_chargee <= 26) ? $reste_a_chargee+1 : 26; + + // si derniere page alors afficher cadre des TVA + if ($num_page == $nb_page) + { + $pdf->Line(5, 225, 205, 225); + $pdf->SetFont('Arial','B',8); $pdf->SetXY( 5, 225 ); $pdf->Cell( 140, 8, 'TOTAL', 0, 0, 'C'); + $pdf->SetFont('Arial','',8); $pdf->SetXY( 147, 225 ); $pdf->Cell( 13, 8, $montant_ht_total.chr(128), 0, 0, 'C'); + $pdf->SetFont('Arial','',8); $pdf->SetXY( 168, 225 ); $pdf->Cell( 10, 8, $montant_tva_total.chr(128), 0, 0, 'C'); + $pdf->SetFont('Arial','',8); $pdf->SetXY( 183, 225 ); $pdf->Cell( 22, 8, $montant_ttc_total.chr(128), 0, 0, 'C'); + + + + + + + + + + $pdf->Rect(145, 233, 60, 7, "D"); + $pdf->SetFont('Arial','B',8); $pdf->SetXY( 147, 233 ); $pdf->Cell( 30, 6.5, 'TOTAL TTC', 0, 0, 'C'); + $pdf->SetFont('Arial','B',8); $pdf->SetXY( 183, 233 ); $pdf->SetFillColor(255, 255, 0); $pdf->SetTextColor(255, 0, 0); $pdf->Cell( 22, 6.5, $montant_ttc_total.chr(128), 0, 0, 'C', true); + + + + + + + } + + $y1 = 245; + + $pdf->SetFillColor(255); + $pdf->SetTextColor(0, 0, 0); + + $pdf->SetFont('Arial','',9); + + $pdf->SetXY( 10, $y1 ); $pdf->Cell( $pdf->GetPageWidth(), 4, utf8_decode("Loi N° 92-442 du 31 décembre 1992: La présente facture est payable en comptant a réception."), 0, 0, 'L'); + $pdf->SetXY( 10, $y1 + 4 ); $pdf->Cell( $pdf->GetPageWidth(), 4, utf8_decode("Indemnité forfaitaire pour frais de recouvrement due en cas de retard de paiement: 40").chr(128), 0, 0, 'L'); + $pdf->SetXY( 10, $y1 + 8 ); $pdf->Multicell( $pdf->GetPageWidth()-20, 4, utf8_decode("Toute somme non payée dans les trente jours est susceptible de porter intérets à un taux égal à une fois et demi le taux de l'intéret légal."), 0, 0, 'L'); + + + + + // ************************** + // pied de page + // ************************** + + $pdf->SetFont('Arial','',6); + $pdf->SetXY( 1, $y0 + 4 ); $pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_one)), 0, 0, 'C'); + $pdf->SetXY( 1, $y0 + 8 ); $pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_two)), 0, 0, 'C'); + $pdf->SetXY( 1, $y0 + 12 ); $pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->telephone)), 0, 0, 'C'); + + + + + /*$pdf->SetXY( 1, $y0 + 16 ); + $pdf->Cell( $pageWidth, 5, utf8_decode("SIREN 751621293"), 0, 0, 'C');*/ + + $num_page++; + } + + $ff_pdf = html_entity_decode($current_config[0]->path).'/DOCUMENTS RECAPITULATIFS/'.$key_annee.'/'.$key_mois.' '.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'/GROUPE_OGF_RECAP_FACTURE_'.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'_'.$key_annee.'.pdf'; + $this->storage->newFile($ff_pdf); + $pdfContent = $pdf->Output('','S'); + + $file_pdf = $this->storage->get($ff_pdf); + $file_pdf->putContent($pdfContent); + } + } + + } catch(\OCP\Files\NotFoundException $e) { } + } catch(\OCP\Files\NotPermittedException $e) { } + } + + + + + private function generer_document_comptable_client($date, $filter,$filterType) { + + try { + $this->invoicePdfService->generateInvoiceRecap($filter,$filterType,$date,$this->idNextcloud); + } catch(\OCP\Files\NotPermittedException $e) { } + } + + + private function generer_document_comptable($date) { + + $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); + try { + try { + $data_factures = array(); + $factures = json_decode($this->myDb->getCurrentMonthFactures($this->idNextcloud, $date)); + $factures = array_filter($factures, function($facture) {return $facture->id_client != NULL; }); + foreach ($factures as $key => $facture) { + $facture_temp = array( + 'num' => $facture->num, + 'id_client' => $facture->id_client, + 'client' => $facture->entreprise, + 'adresse_client' => $facture->adresse_client, + 'mail_client' => $facture->mail_client, + 'adresse_devis' => $facture->lieu, + 'nom_client' => html_entity_decode($facture->nom), + 'prenoms_client' => html_entity_decode($facture->prenom), + 'numero_commande' => $facture->numero_commande, + 'date_soin' => $facture->date_soin, + 'date' => $facture->date, + 'date_facture' => $facture->date_paiement, + 'defunt' => $facture->nom_defunt, + 'montant_htc' => 0, + 'tva' => $current_config[0]->tva_default, + 'montant_tva' => 0, + 'montant_ttc' => 0, + ); + $produits = json_decode($this->getProduitsById($facture->id_devis)); + foreach ($produits as $key => $produit) { + $facture_temp['montant_htc'] += $produit->prix_unitaire * $produit->quantite; + }; + $facture_temp['montant_tva'] = ($facture_temp['montant_htc'] * $facture_temp['tva'])/100; + $facture_temp['montant_ttc'] = $facture_temp['montant_tva'] + $facture_temp['montant_htc']; + + array_push($data_factures, $facture_temp); + }; + $data_temp = array(); + foreach ($data_factures as $key => $facture) { + $datesplit = explode('-', $facture['date_facture']); + if($data_temp[strval($datesplit[0])][strval($datesplit[1])][$facture['id_client']]==NULL) { + $data_temp[strval($datesplit[0])][strval($datesplit[1])][$facture['id_client']] = array(0=>$facture); + } else { + array_push($data_temp[strval($datesplit[0])][strval($datesplit[1])][$facture['id_client']], $facture); + } + } + foreach ($data_temp as $key_annee => $annee) { + foreach ($annee as $key_mois => $mois) { + foreach ($mois as $key_client => $client) { + $pdf = new FPDF(); + // $pdf->AddFont('Arial','','Comic Sans MS.php'); + // $pdf->AddFont('Arial','B','comic-sans-bold.php'); + $current_client = ''; + $adresse = ''; + $date_facture = ''; + $j=1; + foreach ($client as $key => $facture) { + if($j==1) { + $current_client = $facture['prenoms_client'].' '.$facture['nom_client']; + $adresse = $facture['adresse_client']; + $date_facture = $facture['date_facture']; + } + $j++; + } + $date_temp = date("t-m-Y", strtotime($date_facture)); + $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE); + $date_formated = $formatter->format(DateTime::createFromFormat('d-m-Y', $date_temp)); + + try { + $this->storage->newFolder(html_entity_decode($current_config[0]->path).'/DOCUMENTS RECAPITULATIFS/'.$key_annee.'/'.$key_mois.' '.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'/'); + } catch(\OCP\Files\NotPermittedException $e) { } + + + $pdf->AddPage(); + // on sup les 2 cm en bas + $pdf->SetAutoPagebreak(False); + $pdf->SetMargins(0,0,0); + + // logo : 80 de largeur et 55 de hauteur + $pdf->Image($this->src_path."logo.png", 4, 2, 50, 35); + // adresse du facture + $pdf->SetFont('Arial','B',11); $_x = 122 ; $_y = 40; + $pdf->SetXY( $_x, $_y ); $pdf->Cell( 100, 8, utf8_decode($current_client), 0, 0, ''); $_y += 8; + $pdf->SetXY( $_x, $_y ); $pdf->MultiCell( 80, 4, utf8_decode(html_entity_decode($adresse)), 0, 0, ''); + + + + + + // date facture + $pdf->SetFont('Arial','',11); $pdf->SetXY( 122, 60 ); + + $pdf->Cell( 60, 8, "Bourges France le, ".utf8_decode($date_formated), 0, 0, ''); + + // observations + $pdf->SetFont( "Arial", "BU", 10 ); $pdf->SetXY( 10, 85 ) ; $pdf->Cell($pdf->GetStringWidth("Objet:"), 0, "Objet:", 0, "L"); + + + $objet = utf8_decode("Récapitulatif Facturation du mois de ").strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])); + $pdf->SetFont( "Arial", "", 10 ); $pdf->SetXY( $pdf->GetStringWidth("Objet")+15, 85 ) ; $pdf->Cell($pdf->GetStringWidth($objet), 0, $objet, 0, "L"); + + + + $pdf->SetFont( "Arial", "", 10 ); $pdf->SetXY( $pdf->GetStringWidth("Objet")+15, 95 ); $pdf->Cell($pdf->GetStringWidth("Madame, Monsieur"), 0, "Madame, Monsieur", 0, "L"); + + + + $text1 = utf8_decode("Veuillez trouver ci-dessous le récapitulatif de la facturation du mois de ").strtoupper($this->convert_special_char(explode(' ', $date_formated)[1]))."."; + $text2 = utf8_decode("Vous en souhaitant bonne réception."); + $text3 = utf8_decode("Veuillez agréer, Madame, Monsieur, mes salutations les meilleures."); + + $pdf->SetFont( "Arial", "", 10 ); $pdf->SetXY( $pdf->GetStringWidth("Objet")+15, 105 ) ; $pdf->Cell($pdf->GetStringWidth($text1), 0, $text1, 0, "L"); + $pdf->SetFont( "Arial", "", 10 ); $pdf->SetXY( $pdf->GetStringWidth("Objet")+15, 110 ) ; $pdf->Cell($pdf->GetStringWidth($text2), 0, $text2, 0, "L"); + $pdf->SetFont( "Arial", "", 10 ); $pdf->SetXY( $pdf->GetStringWidth("Objet")+15, 120 ) ; $pdf->Cell($pdf->GetStringWidth($text3), 0, $text3, 0, "L"); + + + + + + + + // signature + $pdf->SetFont('Arial','',11); $pdf->SetXY( 122, 145 ); + + $pdf->Cell( $pdf->GetStringWidth($current_config[0]->nom.' '.$current_config[0]->prenom), 0, utf8_decode(html_entity_decode($current_config[0]->nom.' '.$current_config[0]->prenom)), 0, 0, 'L'); + $pdf->Image($this->src_path."sign.png", 122, 150, 55, 30); + + $y0 = 260; + $pageWidth = $pdf->GetPageWidth(); + //Positionnement en bas et tout centrer + $pdf->SetFont('Arial','',6); + $pdf->SetXY( 1, $y0 + 4 );$pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_one)), 0, 0, 'C'); + $pdf->SetXY( 1, $y0 + 8 );$pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_two)), 0, 0, 'C'); + $pdf->SetXY( 1, $y0 + 12 );$pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->telephone)), 0, 0, 'C'); + + + + + /*$pdf->SetXY( 1, $y0 + 16 ); + $pdf->Cell( $pageWidth, 5, utf8_decode("SIREN 751621293"), 0, 0, 'C');*/ + + $num_page = 1; + $nb_page = ceil(sizeof($client) / 26); + $index_facture_position = 0; + $max_nb_toget = (sizeof($client)<=26)?sizeof($client):26; + + $montant_ht_total = 0; + $montant_tva_total = 0; + $montant_ttc_total = 0; + + while ($num_page <= $nb_page) { + $pdf->AddPage(); + // on sup les 2 cm en bas + $pdf->SetAutoPagebreak(False); + $pdf->SetMargins(0,0,0); + + $pdf->Image($this->src_path."logo.png", 4, 2, 50, 35); + + // n° page en haute à droite + if($nb_page>1){ + $pdf->SetXY( 120, 5 ); $pdf->SetFont( "Arial", "B", 9 ); $pdf->Cell( 160, 8, $num_page . '/' . $nb_page, 0, 0, 'C'); + + + } + + // date facture + $pdf->SetFont('Arial','',11); $pdf->SetXY( 122, 15 ); + + $pdf->Cell( 60, 8, "Bourges France le, ".utf8_decode($date_formated), 0, 0, ''); + + // n° facture, date echeance et reglement et obs + $pdf->SetLineWidth(0.1); $pdf->SetFillColor(255); $pdf->Rect(100, 30, 85, 8, "DF"); + $pdf->SetXY( 100, 30 ); $pdf->SetFont( "Arial", "B", 12 ); $pdf->Cell( 85, 8, 'FACTURE N'.utf8_decode('°').' ETS/'.$key_annee.'/'.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])), 0, 0, 'C'); + + + + + + // adresse du facture + $pdf->SetFont('Arial','B',11); $x = 122 ; $y = 45; + $pdf->SetXY( $x, $y ); $pdf->Cell( 100, 8, utf8_decode($current_client), 0, 0, ''); $y += 8; + $pdf->SetXY( $x, $y ); $pdf->Cell( 100, 8, utf8_decode(html_entity_decode($facture['mail_client'])), 0, 0, ''); $y += 8; + $pdf->SetXY( $x, $y ); $pdf->MultiCell( 80, 4, utf8_decode(html_entity_decode($adresse)), 0, 0, ''); + + + + + + + + + // *********************** + // le cadre des articles + // *********************** + // cadre avec 18 lignes max ! et 118 de hauteur --> 80 + 118 = 198 pour les traits verticaux + $pdf->SetLineWidth(0.1); $pdf->Rect(5, 80, 200, 153, "D"); + + // cadre titre des colonnes + $pdf->Line(5, 90, 205, 90); + // les traits verticaux colonnes + $pdf->Line(145, 80, 145, 233); + $pdf->Line(163, 80, 163, 233); + if($num_page == $nb_page) $pdf->Line(183, 80, 183, 240); + else $pdf->Line(183, 80, 183, 233); + + + + // titre colonne + $pdf->SetXY( 1, 81 ); $pdf->SetFont('Arial','B',8); $pdf->Cell( 140, 8, "OBJET", 0, 0, 'C'); + $pdf->SetXY( 147, 81 ); $pdf->SetFont('Arial','B',8); $pdf->Cell( 13, 8, "H.T.", 0, 0, 'C'); + $pdf->SetXY( 168, 81 ); $pdf->SetFont('Arial','B',8); $pdf->Cell( 10, 8, "TVA 20%", 0, 0, 'C'); + $pdf->SetXY( 183, 81 ); $pdf->SetFont('Arial','B',8); $pdf->Cell( 22, 8, "T.T.C", 0, 0, 'C'); + + + + + + + + + + // (new DateTime($facture['date_soin']))->format('d-M') + $formatter_ds = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::NONE); + + // Set the pattern for the formatter to "d-MMMM" to display the day and month name in French + $formatter_ds->setPattern('dd-MMM'); + + //recuperation des factures + $y_facture = 90; + + $init_index = $index_facture_position; + + for ($index_facture_position; $index_facture_position < ($init_index + $max_nb_toget) ; $index_facture_position++) { + $date_soin_temp = new DateTime($client[$index_facture_position]['date_soin']); + + $pdf->SetXY( 6, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 28, 8, $client[$index_facture_position]['num'], 0, 0, ''); + $pdf->SetXY( 32, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 28, 8, $client[$index_facture_position]['numero_commande'], 0, 0, ''); + $pdf->SetXY( 53, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 18, 8, utf8_decode($formatter_ds->format($date_soin_temp)), 0, 0, ''); + $pdf->SetXY( 65, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 38, 8, utf8_decode(html_entity_decode($client[$index_facture_position]['adresse_devis'])), 0, 0, ''); + $pdf->SetXY( 100, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 28, 8, utf8_decode(html_entity_decode($client[$index_facture_position]['defunt'])), 0, 0, ''); + $pdf->SetXY( 147, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 13, 8, $client[$index_facture_position]['montant_htc'].chr(128), 0, 0, 'C'); + $pdf->SetXY( 168, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 10, 8, $client[$index_facture_position]['montant_tva'].chr(128), 0, 0, 'C'); + $pdf->SetXY( 183, $y_facture ); $pdf->SetFont('Arial','',8); $pdf->Cell( 22, 8, $client[$index_facture_position]['montant_ttc'].chr(128), 0, 0, 'C'); + + + + + + + + + + + + + + + + + + $montant_ht_total = $montant_ht_total+$client[$index_facture_position]['montant_htc']; + $montant_tva_total = $montant_tva_total+$client[$index_facture_position]['montant_tva']; + $montant_ttc_total = $montant_ttc_total+$client[$index_facture_position]['montant_ttc']; + + $y_facture=$y_facture+5; + } + + $nb_facture_chargee = $index_facture_position+1; + $reste_a_chargee = sizeof($client) - $nb_facture_chargee; + $max_nb_toget = ($reste_a_chargee <= 26) ? $reste_a_chargee+1 : 26; + + // si derniere page alors afficher cadre des TVA + if ($num_page == $nb_page) + { + $pdf->Line(5, 225, 205, 225); + $pdf->SetFont('Arial','B',8); $pdf->SetXY( 5, 225 ); $pdf->Cell( 140, 8, 'TOTAL', 0, 0, 'C'); + $pdf->SetFont('Arial','',8); $pdf->SetXY( 147, 225 ); $pdf->Cell( 13, 8, $montant_ht_total.chr(128), 0, 0, 'C'); + $pdf->SetFont('Arial','',8); $pdf->SetXY( 168, 225 ); $pdf->Cell( 10, 8, $montant_tva_total.chr(128), 0, 0, 'C'); + $pdf->SetFont('Arial','',8); $pdf->SetXY( 183, 225 ); $pdf->Cell( 22, 8, $montant_ttc_total.chr(128), 0, 0, 'C'); + + + + + + + + + + $pdf->Rect(145, 233, 60, 7, "D"); + $pdf->SetFont('Arial','B',8); $pdf->SetXY( 147, 233 ); $pdf->Cell( 30, 6.5, 'TOTAL TTC', 0, 0, 'C'); + $pdf->SetFont('Arial','B',8); $pdf->SetXY( 183, 233 ); $pdf->SetFillColor(255, 255, 0); $pdf->SetTextColor(255, 0, 0); $pdf->Cell( 22, 6.5, $montant_ttc_total.chr(128), 0, 0, 'C', true); + + + + + + + } + + $y1 = 245; + + $pdf->SetFillColor(255); + $pdf->SetTextColor(0, 0, 0); + + $pdf->SetFont('Arial','',9); + + $pdf->SetXY( 10, $y1 ); $pdf->Cell( $pdf->GetPageWidth(), 4, utf8_decode("Loi N° 92-442 du 31 décembre 1992: La présente facture est payable en comptant a réception."), 0, 0, 'L'); + $pdf->SetXY( 10, $y1 + 4 ); $pdf->Cell( $pdf->GetPageWidth(), 4, utf8_decode("Indemnité forfaitaire pour frais de recouvrement due en cas de retard de paiement: 40").chr(128), 0, 0, 'L'); + $pdf->SetXY( 10, $y1 + 8 ); $pdf->Multicell( $pdf->GetPageWidth()-20, 4, utf8_decode("Toute somme non payée dans les trente jours est susceptible de porter intérets à un taux égal à une fois et demi le taux de l'intéret légal."), 0, 0, 'L'); + + + + + // ************************** + // pied de page + // ************************** + + $pdf->SetFont('Arial','',6); + $pdf->SetXY( 1, $y0 + 4 );$pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_one)), 0, 0, 'C'); + $pdf->SetXY( 1, $y0 + 8 );$pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_two)), 0, 0, 'C'); + $pdf->SetXY( 1, $y0 + 12 );$pdf->Cell( $pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->telephone)), 0, 0, 'C'); + + + + + $num_page++; + } + + $ff_pdf = html_entity_decode($current_config[0]->path).'/DOCUMENTS RECAPITULATIFS/'.$key_annee.'/'.$key_mois.' '.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'/'.strtoupper($this->convert_special_char($current_client)).'_RECAP_FACTURE_'.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'_'.$key_annee.'.pdf'; + $this->storage->newFile($ff_pdf); + $pdfContent = $pdf->Output('','S'); + + $file_pdf = $this->storage->get($ff_pdf); + $file_pdf->putContent($pdfContent); + } + } + } + } catch(\OCP\Files\NotFoundException $e) { } + } catch(\OCP\Files\NotPermittedException $e) { } + + } + + + private function convert_special_char($str) { + + $unwanted_array = array( + 'Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', + 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', + 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', + 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', + 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' + ); + return strtr( $str, $unwanted_array ); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getConfiguration() { + + $idNextcloud = self::DEFAULT_NEXTCLOUD_ADMIN; + return $this->myDb->getConfiguration($idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getDevis($mentionFilters = []) { + + return $this->myDb->getDevis($this->idNextcloud,$mentionFilters); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getDevisWithProduits(){ + + return $this->myDb->getDevisWithProduits($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getDevisDelphine($idtrajetdetails) { + + return $this->myDb->getDevisDelphine($idtrajetdetails, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getTrajets() { + + return $this->myDb->getTrajets($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numtrajet + */ + public function getTrajetsdetails($numtrajet) { + + $result = $this->myDb->getTrajetsdetails($numtrajet, $this->idNextcloud); + return $result; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getLieux() { + + return $this->myDb->getLieux($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function ajaxGetLieux() { + + return $this->myDb->getLieux($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function ajaxGetClientsName() { + + return $this->myDb->getClientsName(); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getFactures() { + + //$this->synchronize_facture(); + $result = $this->myDb->getFactures($this->idNextcloud); + $this->refreshFEC(); + return $result; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getFacturesWithProduits() { + + $result = $this->myDb->getFacturesWithProduits(); + $this->refreshFEC(); + return $result; + } + + + + private function synchronize_facture() { + + $factures = json_decode($this->myDb->getFactures($this->idNextcloud)); + foreach ($factures as $key => $facture) { + if($facture->id_devis) { + $deviscourant = json_decode($this->myDb->getOneDevis($facture->id_devis, $this->idNextcloud))[0]; + $this->myDb->gestion_update('facture', 'date', $deviscourant->date, $facture->id, $this->idNextcloud); + $this->myDb->gestion_update('facture', 'version', html_entity_decode($deviscourant->version), $facture->id, $this->idNextcloud); + $this->myDb->gestion_update('facture', 'type_paiement', 'comptant', $facture->id, $this->idNextcloud); + } + } + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getProduits() { + + return $this->myDb->getProduits($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function ajaxGetProduits($orderDirection = null) { + + if($orderDirection == null){ + $orderDirection = 'DESC'; + } + return $this->myDb->getProduits($this->idNextcloud,$orderDirection); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numdevis + */ + public function getProduitsById($numdevis) { + + return $this->myDb->getListProduit($numdevis, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getBibliotheques() { + + return $this->myDb->getBibliotheques($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $id + */ + public function getClient($id) { + + return $this->myDb->getClient($id, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $id + */ + public function getClientbyiddevis($id) { + + return $this->myDb->getClientbyiddevis($id, $this->idNextcloud); + } + + /** + * @NoAdminRequired + */ + public function getServerFromMail(){ + + return new DataResponse(['mail' => $this->config->getSystemValue('mail_from_address').'@'.$this->config->getSystemValue('mail_domain')],200, ['Content-Type' => 'application/json']); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function insertClient() { + + // try { + // return new DataResponse($this->myDb->insertClient($this->idNextcloud), Http::STATUS_OK, ['Content-Type' => 'application/json']); + // } + // catch( PDOException $Exception ) { + // return new DataResponse($Exception, 500, ['Content-Type' => 'application/json']); + // } + return $this->myDb->insertClient($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function insertLieu(){ + + return $this->myDb->insertLieu($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function insertTrajet(){ + + return $this->myDb->insertTrajet($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numtrajet + * + */ + public function insertTrajetdetails($numtrajet){ + + return $this->myDb->insertTrajetdetails($numtrajet, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numtrajet + * + */ + public function saveTrajetdetails($numtrajet){ + + $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); + $clean_folder = html_entity_decode($current_config[0]->path).'/'; + + try { + + $trajet = json_decode($this->myDb->getOneTrajet($numtrajet, $this->idNextcloud))[0]; + + $formatter_ds = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::NONE); + // Set the pattern for the formatter to "d-MMMM" to display the day and month name in French + $formatter_ds->setPattern('dd-MMM'); + + $monthName = $this->month_toString(intval($trajet->mois)); + $fullnameThanato = (($trajet->nom_thanato != NULL) ? $trajet->nom_thanato : '').' '.(($trajet->prenom_thanato != NULL) ? $trajet->prenom_thanato : ''); + + $_clean_folder = $clean_folder.'INDEMNITES KILOMETRIQUES/'.$trajet->annee.'/'.strtoupper($fullnameThanato).'/'; + try { + $this->storage->newFolder($_clean_folder); + } catch(\OCP\Files\NotPermittedException $e) { } + + + $trajetdetails = json_decode($this->myDb->getTrajetsdetails_orderByDate($numtrajet, $idNextcloud)); + $distance_temp = 0; + $distances = array(); + $last_point = NULL; + + $ik_temp = 'CLIENTS'.';'.'JOUR'.';'.'LIEU'.';'.'TOTAL'."\n"; + for ($i=0; $i < sizeof($trajetdetails); $i++) { + $date_temp = new DateTime($trajetdetails[$i]->date); + if(strcmp(explode('-', $trajetdetails[$i]->date)[2], explode('-', $trajetdetails[$i+1]->date)[2])!=0) { + array_push($distances, $distance_temp); + $ik_temp = $ik_temp.utf8_decode(html_entity_decode($trajetdetails[$i]->cprenoms.' '.$trajetdetails[$i]->cnom)).';'.utf8_decode($formatter_ds->format($date_temp)).';'.utf8_decode(html_entity_decode($trajetdetails[$i]->lieu)).';'.$distance_temp."\n"; + $distance_temp = 0; + $last_point = NULL; + } else { + $currentDistance = 0; + if($trajetdetails[$i]->lid != NULL) $last_point = $trajetdetails[$i]; + if($last_point->lid != NULL && $trajetdetails[$i+1]->lid != NULL){ + + + $currentDistance = $this->myDb->calcul_distance(floatval($last_point->latitude), floatval($last_point->longitude), floatval($trajetdetails[$i+1]->latitude), floatval($trajetdetails[$i+1]->longitude)); + $distance_temp += $currentDistance; + } + $ik_temp = $ik_temp.utf8_decode(html_entity_decode($trajetdetails[$i]->cprenoms.' '.$trajetdetails[$i]->cnom)).';'.utf8_decode($formatter_ds->format($date_temp)).';'.utf8_decode(html_entity_decode($trajetdetails[$i]->lieu)).';'.$currentDistance."\n"; + } + } + + // distance total + $distance_final = 0; + foreach ($distances as $key => $valdistance) { + $distance_final += $valdistance; + } + + $ik_temp = $ik_temp."\n\n\n\n".''.';'.''.';'.'sous total'.';'.$distance_final; + + $total_ik = $distance_final * floatval($current_config[0]->coefficient_ik); + $ik_temp = $ik_temp."\n\n".''.';'.'TOTAL'.';'.$current_config[0]->coefficient_ik.';'.$total_ik; + $ik_temp = $ik_temp."\n".''.';'.'ELECTRIQUE'.';'.''.';'.round($total_ik, 2); + + $nom_thanato = html_entity_decode($trajet->nom_thanato).' '.html_entity_decode($trajet->prenom_thanato); + $ff = $_clean_folder.'IK_'.$trajet->annee.'_'.$monthName.'_'.strtoupper($fullnameThanato).'_'.strtoupper($nom_thanato).'.csv'; + $this->storage->newFile($ff); + $file = $this->storage->get($ff); + $file->putContent($ik_temp); + + } catch(\OCP\Files\NotFoundException $e) { } + + + return true; + } + + private function month_toString($monthnumber) { + + $result = ''; + switch ($monthnumber) { + case 1: + $result = '01JANVIER'; + break; + case 2: + $result = '02FEVRIER'; + break; + case 3: + $result = '03MARS'; + break; + case 4: + $result = '04AVRIL'; + break; + case 5: + $result = '05MAI'; + break; + case 6: + $result = '06JUIN'; + break; + case 7: + $result = '07JUILLET'; + break; + case 8: + $result = '08AOUT'; + break; + case 9: + $result = '09SEPTEMBRE'; + break; + case 10: + $result = '10OCTOBRE'; + break; + case 11: + $result = '11NOVEMBRE'; + break; + case 12: + $result = '12DECEMBRE'; + break; + } + return $result; + } + + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function insertDevis(){ + + return $this->myDb->insertDevis($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function insertFacture(){ + + $result = $this->myDb->insertFacture($this->idNextcloud); + $this->refreshFEC(); + return $result; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function insertProduit(){ + + return $this->myDb->insertProduit($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $id + */ + public function insertProduitDevis($id){ + + return $this->myDb->insertProduitDevis($id, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $id + */ + public function insertArticleDevis($id){ + + return $this->myDb->insertArticleDevis($id, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $id + */ + public function insertObservationDefunt($id){ + + return $this->myDb->insertObservationDefunt($id, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $id + */ + public function insertBijouDefunt($id){ + + return $this->myDb->insertBijouDefunt($id, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $id + */ + public function insertHypoDefunt($id){ + + return $this->myDb->insertHypoDefunt($id, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function insertBibliotheque(){ + + return $this->myDb->insertBibliotheque($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $table + * @param string $column + * @param string $data + * @param string $id + */ + public function update($table, $column, $data, $id) { + + if(strcmp($table, 'facture')==0 || strcmp($table, 'produit')==0 || strcmp($table, 'devis')==0) { + if(strcmp($column, 'id_devis')==0) { + $facturecourant = json_decode($this->myDb->getOneFacture($id, $this->idNextcloud))[0]; + $this->myDb->gestion_update('devis', 'mentions', 'facturé', $data, $this->idNextcloud); + $this->myDb->gestion_update('devis', 'mentions', 'Nouveau', $facturecourant->id_devis, $this->idNextcloud); + $result = $this->myDb->gestion_update($table, $column, $data, $id, $this->idNextcloud); + + } else { + $facturecourant = json_decode($this->myDb->getOneFacture($id, $this->idNextcloud))[0]; + if(strcmp($column, 'date_paiement')==0) { + $datecourant = $facturecourant->date_paiement; + $nouveaudate = $data; + $result = $this->myDb->gestion_update($table, $column, $data, $id, $this->idNextcloud); + // $this->generer_document_comptable($datecourant); + // $this->generer_document_comptable($nouveaudate); + } else { + if(strcmp($column, 'date')==0) { + if(strcmp($table, 'facture')){ + $datetime = new Datetime($data); + $factureNumber = $this->myDb->getFactureNumberByDate($datetime); + $this->myDb->gestion_update($table, "facture_number", $factureNumber, $id, $this->idNextcloud); + $factureFullNumber = $this->myDb->getFactureFullNumberByDate($datetime); + $this->myDb->gestion_update($table, "num", $factureFullNumber, $id, $this->idNextcloud); + } + if(strcmp($table, 'devis')){ + $datetime = new Datetime($data); + $devisNumber = $this->myDb->getDevisNumberByDate($datetime); + $this->myDb->gestion_update($table, "devis_number", $devisNumber, $id, $this->idNextcloud); + $devisFullNumber = $this->myDb->getDevisFullNumberByDate($datetime); + $this->myDb->gestion_update($table, "num", $devisFullNumber, $id, $this->idNextcloud); + } + } + $result = $this->myDb->gestion_update($table, $column, $data, $id, $this->idNextcloud); + // $this->generer_document_comptable($facturecourant->date_paiement); + } + } + $this->refreshFEC(); + return $result; + } + return $this->myDb->gestion_update($table, $column, $data, $id, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param array $devisToFacture + * @param string $paymentDate + */ + public function exportDevisToFacture($devisToFacture,$paymentDate,$type = FactureTypeConstant::TYPE_SINGLE) { + + $response = true; + $factureIdsGenerated = []; + if($type == FactureTypeConstant::TYPE_GROUP){ + $doDevisIdsListIdsBelongsToTheSameClientFacturationGroup = $this->myDb->doDevisIdsListIdsBelongsToTheSameClientFacturationGroup($devisToFacture); + if($doDevisIdsListIdsBelongsToTheSameClientFacturationGroup == false){ + return "Les devis fournis ne sont pas dans la même groupe de facturation"; + } + $factureIdsGenerated = $this->myDb->generateGroupFactureForMultipleDevis($devisToFacture,$paymentDate); + } + else{ + $factureIdsGenerated = $this->myDb->insertFactureForeEachDevisId($this->idNextcloud,$devisToFacture,$paymentDate); + } + $this->invoicePdfService->generateFacturePdfByFactureIds($factureIdsGenerated,$this->idNextcloud); + $this->refreshFEC(); + return $response; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $table + * @param string $id + */ + public function delete($table, $id) { + + if(strcmp($table, 'facture')==0 || strcmp($table, 'produit')==0 || strcmp($table, 'devis')==0 || strcmp($table, 'client')==0) { + if(strcmp($table, 'facture')==0) { + $facturecourant = json_decode($this->myDb->getOneFacture($id, $this->idNextcloud))[0]; + $this->myDb->gestion_update('devis', 'mentions', 'Nouveau', $facturecourant->id_devis, $this->idNextcloud); + $result = $this->myDb->gestion_delete($table, $id, $this->idNextcloud); + } else { + $result = $this->myDb->gestion_delete($table, $id, $this->idNextcloud); + } + $this->refreshFEC(); + return $result; + } + return $this->myDb->gestion_delete($table, $id, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $content + * @param string $name + * @param string $subject + * @param string $body + * @param string $to + * @param string $Cc + */ + public function sendPDF($content, $name, $subject, $body, $to, $Cc){ + + $clean_name = html_entity_decode($name); + try { + $data = base64_decode($content); + $message = $this->mailer->createMessage(); + $message->setSubject($subject); + $message->setTo((array) json_decode($to)); + $myrrCc = (array) json_decode($Cc); + + if($myrrCc[0] != ""){ + $message->setCc($myrrCc); + } + $message->setHtmlBody($body); + $content = $this->mailer->createAttachment($data,$clean_name.".pdf","x-pdf"); + $message->attach($content); + $this->mailer->send($message); + return new DataResponse("", 200, ['Content-Type' => 'application/json']); + } catch (Exception $e) { + return new DataResponse("Is your global mail server configured in Nextcloud ?", 500, ['Content-Type' => 'application/json']); + } + + } + + public function sendAttachmentToClientByDefunt($defuntId, $ff_pdf, $to,$subject, $body, $addName = false){ + + $devis = $this->myDb->getDevisOfDefunt($defuntId); + if($devis != null){ + // try { + $senderEmailAddress = $this->config->getSystemValue('mail_from_address') ?? null; + $senderEmailDomain = $this->config->getSystemValue('mail_domain') ?? null; + $senderEmail = null; + if($senderEmailAddress && $senderEmailDomain){ + $senderEmail = $senderEmailAddress.'@'.$senderEmailDomain; + } + $client_email = $to; + $client_nom = $devis['client_nom']; + $data = $this->storage->get($ff_pdf)->getContent(); + $message = $this->mailer->createMessage(); + $message->setTo(recipients: [$client_email => $client_nom]); + // $message->setFrom([$client_email => $client_nom]); + $content = $this->mailer->createAttachment($data, basename($ff_pdf), "application/pdf"); + $message->attach($content); + $message->setSubject($subject); + $body_text = $addName ? ($body." de ".$devis['defunt_nom'] ) : $body; + $signature = $this->mailerService->getFooterContent($this->getUserNameForEmailSignature()); + $message->setHtmlBody( + "

Bonjour.

". + "

$body_text

". + $signature + ); + + $appAdminEmail = $this->myDb->getUserEmailByNextcloudId(BddConstant::DEFAULT_ADMIN_APP_ID_NEXTCLOUD); + if ($appAdminEmail) { + $message->setCc([$appAdminEmail]); + } + $this->mailer->send($message); + return new DataResponse("", 200, ['Content-Type' => 'application/json']); + // } catch (Exception $e) { + // return new DataResponse("Is your global mail server configured in Nextcloud ?", 500, ['Content-Type' => 'application/json']); + // } + } + } + public function getUserNameForEmailSignature (){ + $configs = json_decode($this->myDb->getConfiguration(BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD)); + + $currentConfig = $configs[0]; + return $currentConfig->nom . " " . $currentConfig->prenom; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $content + * @param string $folder + * @param string $name + */ + public function savePDF($content, $folder, $name){ + + + $clean_folder = html_entity_decode($this->convert_special_char($folder)); + $clean_name = html_entity_decode($this->convert_special_char($name)); + try { + $this->storage->newFolder($clean_folder); } catch(\OCP\Files\NotPermittedException $e) { - } - } - - private function generer_recap_ogf($date) - { - $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); - try { - try { - $data_factures = array(); - $factures = json_decode($this->myDb->getCurrentMonthFactures_COGF($this->idNextcloud, $date)); - $factures = array_filter($factures, function ($facture) {return $facture->id_client != null; }); - foreach ($factures as $key => $facture) { - $facture_temp = array( - 'num' => $facture->num, - 'id_client' => $facture->id_client, - 'client' => $facture->entreprise, - 'adresse_client' => $facture->adresse_client, - 'adresse_devis' => $facture->lieu, - 'nom_client' => html_entity_decode($facture->nom), - 'prenoms_client' => html_entity_decode($facture->prenom), - 'date_soin' => $facture->date_soin, - 'numero_commande' => $facture->numero_commande, - 'date' => $facture->date, - 'date_facture' => $facture->date_paiement, - 'defunt' => $facture->nom_defunt, - 'montant_htc' => 0, - 'tva' => $current_config[0]->tva_default, - 'montant_tva' => 0, - 'montant_ttc' => 0, - ); - $produits = json_decode($this->getProduitsById($facture->id_devis)); - foreach ($produits as $key => $produit) { - $facture_temp['montant_htc'] += $produit->prix_unitaire * $produit->quantite; - }; - $facture_temp['montant_tva'] = ($facture_temp['montant_htc'] * $facture_temp['tva']) / 100; - $facture_temp['montant_ttc'] = $facture_temp['montant_tva'] + $facture_temp['montant_htc']; - - array_push($data_factures, $facture_temp); - }; - - $data_temp = array(); - foreach ($data_factures as $key => $facture) { - $datesplit = explode('-', $facture['date_facture']); - if($data_temp[strval($datesplit[0])][strval($datesplit[1])] == null) { - $data_temp[strval($datesplit[0])][strval($datesplit[1])] = array(0 => $facture); - } else { - array_push($data_temp[strval($datesplit[0])][strval($datesplit[1])], $facture); - } - } - - foreach ($data_temp as $key_annee => $annee) { - foreach ($annee as $key_mois => $mois) { - $pdf = new FPDF(); - - $date_facture = $mois[0]['date_facture']; - $date_temp = date("t-m-Y", strtotime($date_facture)); - $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE); - $date_formated = $formatter->format(DateTime::createFromFormat('d-m-Y', $date_temp)); - - try { - $this->storage->newFolder(html_entity_decode($current_config[0]->path).'/DOCUMENTS RECAPITULATIFS/'.$key_annee.'/'.$key_mois.' '.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'/'); - } catch(\OCP\Files\NotPermittedException $e) { - } - - $pdf->AddPage(); - // on sup les 2 cm en bas - $pdf->SetAutoPagebreak(false); - $pdf->SetMargins(0, 0, 0); - - // logo : 80 de largeur et 55 de hauteur - $pdf->Image($this->src_path."logo.png", 4, 2, 50, 35); - // adresse du facture - $pdf->SetFont('Arial', 'B', 11); - $_x = 122 ; - $_y = 40; - $pdf->SetXY($_x, $_y); - $pdf->Cell(100, 8, utf8_decode('Groupe COGF'), 0, 0, ''); - $_y += 8; - // date facture - $pdf->SetFont('Arial', '', 11); - $pdf->SetXY(122, 60); - $pdf->Cell(60, 8, "Bourges France le, ".utf8_decode($date_formated), 0, 0, ''); - - // observations - $pdf->SetFont("Arial", "BU", 10); - $pdf->SetXY(10, 85) ; - $pdf->Cell($pdf->GetStringWidth("Objet:"), 0, "Objet:", 0, "L"); - $objet = utf8_decode("Récapitulatif Facturation du mois de ").strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])); - $pdf->SetFont("Arial", "", 10); - $pdf->SetXY($pdf->GetStringWidth("Objet") + 15, 85) ; - $pdf->Cell($pdf->GetStringWidth($objet), 0, $objet, 0, "L"); - - $pdf->SetFont("Arial", "", 10); - $pdf->SetXY($pdf->GetStringWidth("Objet") + 15, 95); - $pdf->Cell($pdf->GetStringWidth("Madame, Monsieur"), 0, "Madame, Monsieur", 0, "L"); - - $text1 = utf8_decode("Veuillez trouver ci-dessous le récapitulatif de la facturation du mois de ").strtoupper($this->convert_special_char(explode(' ', $date_formated)[1]))."."; - $text2 = utf8_decode("Vous en souhaitant bonne réception."); - $text3 = utf8_decode("Veuillez agréer, Madame, Monsieur, mes salutations les meilleures."); - - $pdf->SetFont("Arial", "", 10); - $pdf->SetXY($pdf->GetStringWidth("Objet") + 15, 105) ; - $pdf->Cell($pdf->GetStringWidth($text1), 0, $text1, 0, "L"); - $pdf->SetFont("Arial", "", 10); - $pdf->SetXY($pdf->GetStringWidth("Objet") + 15, 110) ; - $pdf->Cell($pdf->GetStringWidth($text2), 0, $text2, 0, "L"); - $pdf->SetFont("Arial", "", 10); - $pdf->SetXY($pdf->GetStringWidth("Objet") + 15, 120) ; - $pdf->Cell($pdf->GetStringWidth($text3), 0, $text3, 0, "L"); - - // signature - $pdf->SetFont('Arial', '', 11); - $pdf->SetXY(122, 145); - $pdf->Cell($pdf->GetStringWidth($current_config[0]->nom.' '.$current_config[0]->prenom), 0, utf8_decode(html_entity_decode($current_config[0]->nom.' '.$current_config[0]->prenom)), 0, 0, 'L'); - $pdf->Image($this->src_path."sign.png", 122, 150, 55, 30); - - $y0 = 260; - $pageWidth = $pdf->GetPageWidth(); - //Positionnement en bas et tout centrer - $pdf->SetFont('Arial', '', 6); - - $pdf->SetXY(1, $y0 + 4); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_one)), 0, 0, 'C'); - $pdf->SetXY(1, $y0 + 8); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_two)), 0, 0, 'C'); - $pdf->SetXY(1, $y0 + 12); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->telephone)), 0, 0, 'C'); - - /*$pdf->SetXY( 1, $y0 + 16 ); - $pdf->Cell( $pageWidth, 5, utf8_decode("SIREN 751621293"), 0, 0, 'C');*/ - - $num_page = 1; - $nb_page = ceil(sizeof($mois) / 26); - $index_facture_position = 0; - $max_nb_toget = (sizeof($mois) <= 26) ? sizeof($mois) : 26; - - $montant_ht_total = 0; - $montant_tva_total = 0; - $montant_ttc_total = 0; - - while ($num_page <= $nb_page) { - $pdf->AddPage(); - // on sup les 2 cm en bas - $pdf->SetAutoPagebreak(false); - $pdf->SetMargins(0, 0, 0); - - $pdf->Image($this->src_path."logo.png", 4, 2, 50, 35); - - // n° page en haute à droite - if($nb_page > 1) { - $pdf->SetXY(120, 5); - $pdf->SetFont("Arial", "B", 9); - $pdf->Cell(160, 8, $num_page . '/' . $nb_page, 0, 0, 'C'); - } - - // date facture - $pdf->SetFont('Arial', '', 11); - $pdf->SetXY(122, 15); - $pdf->Cell(60, 8, "Bourges France, le ".utf8_decode($date_formated), 0, 0, ''); - - // n° facture, date echeance et reglement et obs - $pdf->SetLineWidth(0.1); - $pdf->SetFillColor(255); - $pdf->Rect(100, 30, 85, 8, "DF"); - $pdf->SetXY(100, 30); - $pdf->SetFont("Arial", "B", 12); - $pdf->Cell(85, 8, 'FACTURE N'.utf8_decode('°').' ETS/'.$key_annee.'/'.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])), 0, 0, 'C'); - - // adresse du facture - $pdf->SetFont('Arial', 'B', 11); - $x = 122 ; - $y = 50; - // $pdf->SetXY( $x, $y ); $pdf->Cell( 100, 8, 'doit', 0, 0, ''); $y += 8; - $pdf->SetXY($x, $y); - $pdf->MultiCell(80, 4, 'Groupe OGF', 0, 0, ''); - - // *********************** - // le cadre des articles - // *********************** - // cadre avec 18 lignes max ! et 118 de hauteur --> 80 + 118 = 198 pour les traits verticaux - $pdf->SetLineWidth(0.1); - $pdf->Rect(5, 80, 200, 153, "D"); - // cadre titre des colonnes - $pdf->Line(5, 90, 205, 90); - // les traits verticaux colonnes - $pdf->Line(145, 80, 145, 233); - $pdf->Line(163, 80, 163, 233); - if($num_page == $nb_page) { - $pdf->Line(183, 80, 183, 240); - } else { - $pdf->Line(183, 80, 183, 233); - } - // titre colonne - $pdf->SetXY(1, 81); - $pdf->SetFont('Arial', 'B', 8); - $pdf->Cell(140, 8, "OBJET", 0, 0, 'C'); - $pdf->SetXY(147, 81); - $pdf->SetFont('Arial', 'B', 8); - $pdf->Cell(13, 8, "H.T.", 0, 0, 'C'); - $pdf->SetXY(168, 81); - $pdf->SetFont('Arial', 'B', 8); - $pdf->Cell(10, 8, "TVA 20%", 0, 0, 'C'); - $pdf->SetXY(183, 81); - $pdf->SetFont('Arial', 'B', 8); - $pdf->Cell(22, 8, "T.T.C", 0, 0, 'C'); - - // (new DateTime($facture['date_soin']))->format('d-M') - $formatter_ds = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::NONE); - - // Set the pattern for the formatter to "d-MMMM" to display the day and month name in French - $formatter_ds->setPattern('dd-MMM'); - - //recuperation des factures - $y_facture = 90; - - $init_index = $index_facture_position; - - for ($index_facture_position; $index_facture_position < ($init_index + $max_nb_toget) ; $index_facture_position++) { - $date_soin_temp = new DateTime($mois[$index_facture_position]['date_soin']); - - $pdf->SetXY(6, $y_facture); - $pdf->SetFont('Arial', '', 8); - $pdf->Cell(28, 8, $mois[$index_facture_position]['num'], 0, 0, ''); - $pdf->SetXY(32, $y_facture); - $pdf->SetFont('Arial', '', 8); - $pdf->Cell(28, 8, $mois[$index_facture_position]['numero_commande'], 0, 0, ''); - $pdf->SetXY(53, $y_facture); - $pdf->SetFont('Arial', '', 8); - $pdf->Cell(18, 8, utf8_decode($formatter_ds->format($date_soin_temp)), 0, 0, ''); - $pdf->SetXY(65, $y_facture); - $pdf->SetFont('Arial', '', 8); - $pdf->Cell(38, 8, $mois[$index_facture_position]['prenoms_client'].' '.$mois[$index_facture_position]['nom_client'], 0, 0, ''); - $pdf->SetXY(100, $y_facture); - $pdf->SetFont('Arial', '', 8); - $pdf->Cell(28, 8, utf8_decode(html_entity_decode($mois[$index_facture_position]['defunt'])), 0, 0, ''); - $pdf->SetXY(147, $y_facture); - $pdf->SetFont('Arial', '', 8); - $pdf->Cell(13, 8, $mois[$index_facture_position]['montant_htc'].chr(128), 0, 0, 'C'); - $pdf->SetXY(168, $y_facture); - $pdf->SetFont('Arial', '', 8); - $pdf->Cell(10, 8, $mois[$index_facture_position]['montant_tva'].chr(128), 0, 0, 'C'); - $pdf->SetXY(183, $y_facture); - $pdf->SetFont('Arial', '', 8); - $pdf->Cell(22, 8, $mois[$index_facture_position]['montant_ttc'].chr(128), 0, 0, 'C'); - - $montant_ht_total = $montant_ht_total + $mois[$index_facture_position]['montant_htc']; - $montant_tva_total = $montant_tva_total + $mois[$index_facture_position]['montant_tva']; - $montant_ttc_total = $montant_ttc_total + $mois[$index_facture_position]['montant_ttc']; - - $y_facture = $y_facture + 5; - } - - $nb_facture_chargee = $index_facture_position + 1; - $reste_a_chargee = sizeof($mois) - $nb_facture_chargee; - $max_nb_toget = ($reste_a_chargee <= 26) ? $reste_a_chargee + 1 : 26; - - // si derniere page alors afficher cadre des TVA - if ($num_page == $nb_page) { - $pdf->Line(5, 225, 205, 225); - $pdf->SetFont('Arial', 'B', 8); - $pdf->SetXY(5, 225); - $pdf->Cell(140, 8, 'TOTAL', 0, 0, 'C'); - $pdf->SetFont('Arial', '', 8); - $pdf->SetXY(147, 225); - $pdf->Cell(13, 8, $montant_ht_total.chr(128), 0, 0, 'C'); - $pdf->SetFont('Arial', '', 8); - $pdf->SetXY(168, 225); - $pdf->Cell(10, 8, $montant_tva_total.chr(128), 0, 0, 'C'); - $pdf->SetFont('Arial', '', 8); - $pdf->SetXY(183, 225); - $pdf->Cell(22, 8, $montant_ttc_total.chr(128), 0, 0, 'C'); - - $pdf->Rect(145, 233, 60, 7, "D"); - $pdf->SetFont('Arial', 'B', 8); - $pdf->SetXY(147, 233); - $pdf->Cell(30, 6.5, 'TOTAL TTC', 0, 0, 'C'); - $pdf->SetFont('Arial', 'B', 8); - $pdf->SetXY(183, 233); - $pdf->SetFillColor(255, 255, 0); - $pdf->SetTextColor(255, 0, 0); - $pdf->Cell(22, 6.5, $montant_ttc_total.chr(128), 0, 0, 'C', true); - } - - $y1 = 245; - - $pdf->SetFillColor(255); - $pdf->SetTextColor(0, 0, 0); - - $pdf->SetFont('Arial', '', 9); - - $pdf->SetXY(10, $y1); - $pdf->Cell($pdf->GetPageWidth(), 4, utf8_decode("Loi N° 92-442 du 31 décembre 1992: La présente facture est payable en comptant a réception."), 0, 0, 'L'); - $pdf->SetXY(10, $y1 + 4); - $pdf->Cell($pdf->GetPageWidth(), 4, utf8_decode("Indemnité forfaitaire pour frais de recouvrement due en cas de retard de paiement: 40").chr(128), 0, 0, 'L'); - $pdf->SetXY(10, $y1 + 8); - $pdf->Multicell($pdf->GetPageWidth() - 20, 4, utf8_decode("Toute somme non payée dans les trente jours est susceptible de porter intérets à un taux égal à une fois et demi le taux de l'intéret légal."), 0, 0, 'L'); - - // ************************** - // pied de page - // ************************** - - $pdf->SetFont('Arial', '', 6); - $pdf->SetXY(1, $y0 + 4); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_one)), 0, 0, 'C'); - $pdf->SetXY(1, $y0 + 8); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_two)), 0, 0, 'C'); - $pdf->SetXY(1, $y0 + 12); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->telephone)), 0, 0, 'C'); - - /*$pdf->SetXY( 1, $y0 + 16 ); - $pdf->Cell( $pageWidth, 5, utf8_decode("SIREN 751621293"), 0, 0, 'C');*/ - - $num_page++; - } - - $ff_pdf = html_entity_decode($current_config[0]->path).'/DOCUMENTS RECAPITULATIFS/'.$key_annee.'/'.$key_mois.' '.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'/GROUPE_OGF_RECAP_FACTURE_'.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'_'.$key_annee.'.pdf'; - $this->storage->newFile($ff_pdf); - $pdfContent = $pdf->Output('', 'S'); - - $file_pdf = $this->storage->get($ff_pdf); - $file_pdf->putContent($pdfContent); - } - } - - } catch(\OCP\Files\NotFoundException $e) { - } - } catch(\OCP\Files\NotPermittedException $e) { - } - } - - private function generer_document_comptable_client($date, $filter, $filterType) - { - try { - $this->invoicePdfService->generateInvoiceRecap($filter, $filterType, $date, $this->idNextcloud); - } catch(\OCP\Files\NotPermittedException $e) { - } - } - - private function generer_document_comptable($date) - { - $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); - try { - try { - $data_factures = array(); - $factures = json_decode($this->myDb->getCurrentMonthFactures($this->idNextcloud, $date)); - $factures = array_filter($factures, function ($facture) {return $facture->id_client != null; }); - foreach ($factures as $key => $facture) { - $facture_temp = array( - 'num' => $facture->num, - 'id_client' => $facture->id_client, - 'client' => $facture->entreprise, - 'adresse_client' => $facture->adresse_client, - 'mail_client' => $facture->mail_client, - 'adresse_devis' => $facture->lieu, - 'nom_client' => html_entity_decode($facture->nom), - 'prenoms_client' => html_entity_decode($facture->prenom), - 'numero_commande' => $facture->numero_commande, - 'date_soin' => $facture->date_soin, - 'date' => $facture->date, - 'date_facture' => $facture->date_paiement, - 'defunt' => $facture->nom_defunt, - 'montant_htc' => 0, - 'tva' => $current_config[0]->tva_default, - 'montant_tva' => 0, - 'montant_ttc' => 0, - ); - $produits = json_decode($this->getProduitsById($facture->id_devis)); - foreach ($produits as $key => $produit) { - $facture_temp['montant_htc'] += $produit->prix_unitaire * $produit->quantite; - }; - $facture_temp['montant_tva'] = ($facture_temp['montant_htc'] * $facture_temp['tva']) / 100; - $facture_temp['montant_ttc'] = $facture_temp['montant_tva'] + $facture_temp['montant_htc']; - - array_push($data_factures, $facture_temp); - }; - $data_temp = array(); - foreach ($data_factures as $key => $facture) { - $datesplit = explode('-', $facture['date_facture']); - if($data_temp[strval($datesplit[0])][strval($datesplit[1])][$facture['id_client']] == null) { - $data_temp[strval($datesplit[0])][strval($datesplit[1])][$facture['id_client']] = array(0 => $facture); - } else { - array_push($data_temp[strval($datesplit[0])][strval($datesplit[1])][$facture['id_client']], $facture); - } - } - foreach ($data_temp as $key_annee => $annee) { - foreach ($annee as $key_mois => $mois) { - foreach ($mois as $key_client => $client) { - $pdf = new FPDF(); - $pdf->AddFont('ComicSans', '', 'Comic Sans MS.php'); - $pdf->AddFont('ComicSans', 'B', 'comic-sans-bold.php'); - $current_client = ''; - $adresse = ''; - $date_facture = ''; - $j = 1; - foreach ($client as $key => $facture) { - if($j == 1) { - $current_client = $facture['prenoms_client'].' '.$facture['nom_client']; - $adresse = $facture['adresse_client']; - $date_facture = $facture['date_facture']; - } - $j++; - } - $date_temp = date("t-m-Y", strtotime($date_facture)); - $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE); - $date_formated = $formatter->format(DateTime::createFromFormat('d-m-Y', $date_temp)); - - try { - $this->storage->newFolder(html_entity_decode($current_config[0]->path).'/DOCUMENTS RECAPITULATIFS/'.$key_annee.'/'.$key_mois.' '.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'/'); - } catch(\OCP\Files\NotPermittedException $e) { - } - - $pdf->AddPage(); - // on sup les 2 cm en bas - $pdf->SetAutoPagebreak(false); - $pdf->SetMargins(0, 0, 0); - - // logo : 80 de largeur et 55 de hauteur - $pdf->Image($this->src_path."logo.png", 4, 2, 50, 35); - // adresse du facture - $pdf->SetFont('ComicSans', 'B', 11); - $_x = 122 ; - $_y = 40; - $pdf->SetXY($_x, $_y); - $pdf->Cell(100, 8, utf8_decode($current_client), 0, 0, ''); - $_y += 8; - $pdf->SetXY($_x, $_y); - $pdf->MultiCell(80, 4, utf8_decode(html_entity_decode($adresse)), 0, 0, ''); - // date facture - $pdf->SetFont('ComicSans', '', 11); - $pdf->SetXY(122, 60); - $pdf->Cell(60, 8, "Bourges France le, ".utf8_decode($date_formated), 0, 0, ''); - - // observations - $pdf->SetFont("ComicSans", "BU", 10); - $pdf->SetXY(10, 85) ; - $pdf->Cell($pdf->GetStringWidth("Objet:"), 0, "Objet:", 0, "L"); - $objet = utf8_decode("Récapitulatif Facturation du mois de ").strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])); - $pdf->SetFont("ComicSans", "", 10); - $pdf->SetXY($pdf->GetStringWidth("Objet") + 15, 85) ; - $pdf->Cell($pdf->GetStringWidth($objet), 0, $objet, 0, "L"); - - $pdf->SetFont("ComicSans", "", 10); - $pdf->SetXY($pdf->GetStringWidth("Objet") + 15, 95); - $pdf->Cell($pdf->GetStringWidth("Madame, Monsieur"), 0, "Madame, Monsieur", 0, "L"); - - $text1 = utf8_decode("Veuillez trouver ci-dessous le récapitulatif de la facturation du mois de ").strtoupper($this->convert_special_char(explode(' ', $date_formated)[1]))."."; - $text2 = utf8_decode("Vous en souhaitant bonne réception."); - $text3 = utf8_decode("Veuillez agréer, Madame, Monsieur, mes salutations les meilleures."); - - $pdf->SetFont("ComicSans", "", 10); - $pdf->SetXY($pdf->GetStringWidth("Objet") + 15, 105) ; - $pdf->Cell($pdf->GetStringWidth($text1), 0, $text1, 0, "L"); - $pdf->SetFont("ComicSans", "", 10); - $pdf->SetXY($pdf->GetStringWidth("Objet") + 15, 110) ; - $pdf->Cell($pdf->GetStringWidth($text2), 0, $text2, 0, "L"); - $pdf->SetFont("ComicSans", "", 10); - $pdf->SetXY($pdf->GetStringWidth("Objet") + 15, 120) ; - $pdf->Cell($pdf->GetStringWidth($text3), 0, $text3, 0, "L"); - - // signature - $pdf->SetFont('ComicSans', '', 11); - $pdf->SetXY(122, 145); - $pdf->Cell($pdf->GetStringWidth($current_config[0]->nom.' '.$current_config[0]->prenom), 0, utf8_decode(html_entity_decode($current_config[0]->nom.' '.$current_config[0]->prenom)), 0, 0, 'L'); - $pdf->Image($this->src_path."sign.png", 122, 150, 55, 30); - - $y0 = 260; - $pageWidth = $pdf->GetPageWidth(); - //Positionnement en bas et tout centrer - $pdf->SetFont('ComicSans', '', 6); - $pdf->SetXY(1, $y0 + 4); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_one)), 0, 0, 'C'); - $pdf->SetXY(1, $y0 + 8); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_two)), 0, 0, 'C'); - $pdf->SetXY(1, $y0 + 12); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->telephone)), 0, 0, 'C'); - - /*$pdf->SetXY( 1, $y0 + 16 ); - $pdf->Cell( $pageWidth, 5, utf8_decode("SIREN 751621293"), 0, 0, 'C');*/ - - $num_page = 1; - $nb_page = ceil(sizeof($client) / 26); - $index_facture_position = 0; - $max_nb_toget = (sizeof($client) <= 26) ? sizeof($client) : 26; - - $montant_ht_total = 0; - $montant_tva_total = 0; - $montant_ttc_total = 0; - - while ($num_page <= $nb_page) { - $pdf->AddPage(); - // on sup les 2 cm en bas - $pdf->SetAutoPagebreak(false); - $pdf->SetMargins(0, 0, 0); - - $pdf->Image($this->src_path."logo.png", 4, 2, 50, 35); - - // n° page en haute à droite - if($nb_page > 1) { - $pdf->SetXY(120, 5); - $pdf->SetFont("ComicSans", "B", 9); - $pdf->Cell(160, 8, $num_page . '/' . $nb_page, 0, 0, 'C'); - } - - // date facture - $pdf->SetFont('ComicSans', '', 11); - $pdf->SetXY(122, 15); - $pdf->Cell(60, 8, "Bourges France le, ".utf8_decode($date_formated), 0, 0, ''); - - // n° facture, date echeance et reglement et obs - $pdf->SetLineWidth(0.1); - $pdf->SetFillColor(255); - $pdf->Rect(100, 30, 85, 8, "DF"); - $pdf->SetXY(100, 30); - $pdf->SetFont("ComicSans", "B", 12); - $pdf->Cell(85, 8, 'FACTURE N'.utf8_decode('°').' ETS/'.$key_annee.'/'.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])), 0, 0, 'C'); - - // adresse du facture - $pdf->SetFont('ComicSans', 'B', 11); - $x = 122 ; - $y = 45; - $pdf->SetXY($x, $y); - $pdf->Cell(100, 8, utf8_decode($current_client), 0, 0, ''); - $y += 8; - $pdf->SetXY($x, $y); - $pdf->Cell(100, 8, utf8_decode(html_entity_decode($facture['mail_client'])), 0, 0, ''); - $y += 8; - $pdf->SetXY($x, $y); - $pdf->MultiCell(80, 4, utf8_decode(html_entity_decode($adresse)), 0, 0, ''); - - // *********************** - // le cadre des articles - // *********************** - // cadre avec 18 lignes max ! et 118 de hauteur --> 80 + 118 = 198 pour les traits verticaux - $pdf->SetLineWidth(0.1); - $pdf->Rect(5, 80, 200, 153, "D"); - // cadre titre des colonnes - $pdf->Line(5, 90, 205, 90); - // les traits verticaux colonnes - $pdf->Line(145, 80, 145, 233); - $pdf->Line(163, 80, 163, 233); - if($num_page == $nb_page) { - $pdf->Line(183, 80, 183, 240); - } else { - $pdf->Line(183, 80, 183, 233); - } - // titre colonne - $pdf->SetXY(1, 81); - $pdf->SetFont('ComicSans', 'B', 8); - $pdf->Cell(140, 8, "OBJET", 0, 0, 'C'); - $pdf->SetXY(147, 81); - $pdf->SetFont('ComicSans', 'B', 8); - $pdf->Cell(13, 8, "H.T.", 0, 0, 'C'); - $pdf->SetXY(168, 81); - $pdf->SetFont('ComicSans', 'B', 8); - $pdf->Cell(10, 8, "TVA 20%", 0, 0, 'C'); - $pdf->SetXY(183, 81); - $pdf->SetFont('ComicSans', 'B', 8); - $pdf->Cell(22, 8, "T.T.C", 0, 0, 'C'); - - // (new DateTime($facture['date_soin']))->format('d-M') - $formatter_ds = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::NONE); - - // Set the pattern for the formatter to "d-MMMM" to display the day and month name in French - $formatter_ds->setPattern('dd-MMM'); - - //recuperation des factures - $y_facture = 90; - - $init_index = $index_facture_position; - - for ($index_facture_position; $index_facture_position < ($init_index + $max_nb_toget) ; $index_facture_position++) { - $date_soin_temp = new DateTime($client[$index_facture_position]['date_soin']); - - $pdf->SetXY(6, $y_facture); - $pdf->SetFont('ComicSans', '', 8); - $pdf->Cell(28, 8, $client[$index_facture_position]['num'], 0, 0, ''); - $pdf->SetXY(32, $y_facture); - $pdf->SetFont('ComicSans', '', 8); - $pdf->Cell(28, 8, $client[$index_facture_position]['numero_commande'], 0, 0, ''); - $pdf->SetXY(53, $y_facture); - $pdf->SetFont('ComicSans', '', 8); - $pdf->Cell(18, 8, utf8_decode($formatter_ds->format($date_soin_temp)), 0, 0, ''); - $pdf->SetXY(65, $y_facture); - $pdf->SetFont('ComicSans', '', 8); - $pdf->Cell(38, 8, utf8_decode(html_entity_decode($client[$index_facture_position]['adresse_devis'])), 0, 0, ''); - $pdf->SetXY(100, $y_facture); - $pdf->SetFont('ComicSans', '', 8); - $pdf->Cell(28, 8, utf8_decode(html_entity_decode($client[$index_facture_position]['defunt'])), 0, 0, ''); - $pdf->SetXY(147, $y_facture); - $pdf->SetFont('ComicSans', '', 8); - $pdf->Cell(13, 8, $client[$index_facture_position]['montant_htc'].chr(128), 0, 0, 'C'); - $pdf->SetXY(168, $y_facture); - $pdf->SetFont('ComicSans', '', 8); - $pdf->Cell(10, 8, $client[$index_facture_position]['montant_tva'].chr(128), 0, 0, 'C'); - $pdf->SetXY(183, $y_facture); - $pdf->SetFont('ComicSans', '', 8); - $pdf->Cell(22, 8, $client[$index_facture_position]['montant_ttc'].chr(128), 0, 0, 'C'); - - $montant_ht_total = $montant_ht_total + $client[$index_facture_position]['montant_htc']; - $montant_tva_total = $montant_tva_total + $client[$index_facture_position]['montant_tva']; - $montant_ttc_total = $montant_ttc_total + $client[$index_facture_position]['montant_ttc']; - - $y_facture = $y_facture + 5; - } - - $nb_facture_chargee = $index_facture_position + 1; - $reste_a_chargee = sizeof($client) - $nb_facture_chargee; - $max_nb_toget = ($reste_a_chargee <= 26) ? $reste_a_chargee + 1 : 26; - - // si derniere page alors afficher cadre des TVA - if ($num_page == $nb_page) { - $pdf->Line(5, 225, 205, 225); - $pdf->SetFont('ComicSans', 'B', 8); - $pdf->SetXY(5, 225); - $pdf->Cell(140, 8, 'TOTAL', 0, 0, 'C'); - $pdf->SetFont('ComicSans', '', 8); - $pdf->SetXY(147, 225); - $pdf->Cell(13, 8, $montant_ht_total.chr(128), 0, 0, 'C'); - $pdf->SetFont('ComicSans', '', 8); - $pdf->SetXY(168, 225); - $pdf->Cell(10, 8, $montant_tva_total.chr(128), 0, 0, 'C'); - $pdf->SetFont('ComicSans', '', 8); - $pdf->SetXY(183, 225); - $pdf->Cell(22, 8, $montant_ttc_total.chr(128), 0, 0, 'C'); - - $pdf->Rect(145, 233, 60, 7, "D"); - $pdf->SetFont('ComicSans', 'B', 8); - $pdf->SetXY(147, 233); - $pdf->Cell(30, 6.5, 'TOTAL TTC', 0, 0, 'C'); - $pdf->SetFont('ComicSans', 'B', 8); - $pdf->SetXY(183, 233); - $pdf->SetFillColor(255, 255, 0); - $pdf->SetTextColor(255, 0, 0); - $pdf->Cell(22, 6.5, $montant_ttc_total.chr(128), 0, 0, 'C', true); - } - - $y1 = 245; - - $pdf->SetFillColor(255); - $pdf->SetTextColor(0, 0, 0); - - $pdf->SetFont('ComicSans', '', 9); - - $pdf->SetXY(10, $y1); - $pdf->Cell($pdf->GetPageWidth(), 4, utf8_decode("Loi N° 92-442 du 31 décembre 1992: La présente facture est payable en comptant a réception."), 0, 0, 'L'); - $pdf->SetXY(10, $y1 + 4); - $pdf->Cell($pdf->GetPageWidth(), 4, utf8_decode("Indemnité forfaitaire pour frais de recouvrement due en cas de retard de paiement: 40").chr(128), 0, 0, 'L'); - $pdf->SetXY(10, $y1 + 8); - $pdf->Multicell($pdf->GetPageWidth() - 20, 4, utf8_decode("Toute somme non payée dans les trente jours est susceptible de porter intérets à un taux égal à une fois et demi le taux de l'intéret légal."), 0, 0, 'L'); - - // ************************** - // pied de page - // ************************** - - $pdf->SetFont('ComicSans', '', 6); - $pdf->SetXY(1, $y0 + 4); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_one)), 0, 0, 'C'); - $pdf->SetXY(1, $y0 + 8); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->legal_two)), 0, 0, 'C'); - $pdf->SetXY(1, $y0 + 12); - $pdf->Cell($pageWidth, 5, utf8_decode(html_entity_decode($current_config[0]->telephone)), 0, 0, 'C'); - - $num_page++; - } - - $ff_pdf = html_entity_decode($current_config[0]->path).'/DOCUMENTS RECAPITULATIFS/'.$key_annee.'/'.$key_mois.' '.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'/'.strtoupper($this->convert_special_char($current_client)).'_RECAP_FACTURE_'.strtoupper($this->convert_special_char(explode(' ', $date_formated)[1])).'_'.$key_annee.'.pdf'; - $this->storage->newFile($ff_pdf); - $pdfContent = $pdf->Output('', 'S'); - - $file_pdf = $this->storage->get($ff_pdf); - $file_pdf->putContent($pdfContent); - } - } - } - } catch(\OCP\Files\NotFoundException $e) { - } - } catch(\OCP\Files\NotPermittedException $e) { - } - } - - private function convert_special_char($str) - { - $unwanted_array = array( - 'Š' => 'S', 'š' => 's', 'Ž' => 'Z', 'ž' => 'z', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E', - 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U', - 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c', - 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', - 'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y' - ); - return strtr($str, $unwanted_array); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getConfiguration() - { - $idNextcloud = self::DEFAULT_NEXTCLOUD_ADMIN; - return $this->myDb->getConfiguration($idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getDevis($mentionFilters = []) - { - return $this->myDb->getDevis($this->idNextcloud, $mentionFilters); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getDevisWithProduits() - { - return $this->myDb->getDevisWithProduits($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getDevisDelphine($idtrajetdetails) - { - return $this->myDb->getDevisDelphine($idtrajetdetails, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getTrajets() - { - return $this->myDb->getTrajets($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numtrajet - */ - public function getTrajetsdetails($numtrajet) - { - $result = $this->myDb->getTrajetsdetails($numtrajet, $this->idNextcloud); - return $result; - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getLieux() - { - return $this->myDb->getLieux($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function ajaxGetLieux() - { - return $this->myDb->getLieux($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function ajaxGetClientsName() - { - return $this->myDb->getClientsName(); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getFactures() - { - //$this->synchronize_facture(); - $result = $this->myDb->getFactures($this->idNextcloud); - $this->refreshFEC(); - return $result; - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getFacturesWithProduits() - { - $result = $this->myDb->getFacturesWithProduits(); - $this->refreshFEC(); - return $result; - } - - - - private function synchronize_facture() - { - $factures = json_decode($this->myDb->getFactures($this->idNextcloud)); - foreach ($factures as $key => $facture) { - if($facture->id_devis) { - $deviscourant = json_decode($this->myDb->getOneDevis($facture->id_devis, $this->idNextcloud))[0]; - $this->myDb->gestion_update('facture', 'date', $deviscourant->date, $facture->id, $this->idNextcloud); - $this->myDb->gestion_update('facture', 'version', html_entity_decode($deviscourant->version), $facture->id, $this->idNextcloud); - $this->myDb->gestion_update('facture', 'type_paiement', 'comptant', $facture->id, $this->idNextcloud); - } - } - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getProduits() - { - return $this->myDb->getProduits($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function ajaxGetProduits($orderDirection = null) - { - if($orderDirection == null) { - $orderDirection = 'DESC'; - } - return $this->myDb->getProduits($this->idNextcloud, $orderDirection); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numdevis - */ - public function getProduitsById($numdevis) - { - return $this->myDb->getListProduit($numdevis, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getBibliotheques() - { - return $this->myDb->getBibliotheques($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $id - */ - public function getClient($id) - { - return $this->myDb->getClient($id, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $id - */ - public function getClientbyiddevis($id) - { - return $this->myDb->getClientbyiddevis($id, $this->idNextcloud); - } - - /** - * @NoAdminRequired - */ - public function getServerFromMail() - { - return new DataResponse(['mail' => $this->config->getSystemValue('mail_from_address').'@'.$this->config->getSystemValue('mail_domain')], 200, ['Content-Type' => 'application/json']); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function insertClient() - { - // try { - // return new DataResponse($this->myDb->insertClient($this->idNextcloud), Http::STATUS_OK, ['Content-Type' => 'application/json']); - // } - // catch( PDOException $Exception ) { - // return new DataResponse($Exception, 500, ['Content-Type' => 'application/json']); - // } - return $this->myDb->insertClient($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function insertLieu() - { - return $this->myDb->insertLieu($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function insertTrajet() - { - return $this->myDb->insertTrajet($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numtrajet - * - */ - public function insertTrajetdetails($numtrajet) - { - return $this->myDb->insertTrajetdetails($numtrajet, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numtrajet - * - */ - public function saveTrajetdetails($numtrajet) - { - $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); - $clean_folder = html_entity_decode($current_config[0]->path).'/'; - - try { - - $trajet = json_decode($this->myDb->getOneTrajet($numtrajet, $this->idNextcloud))[0]; - - $formatter_ds = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::NONE); - // Set the pattern for the formatter to "d-MMMM" to display the day and month name in French - $formatter_ds->setPattern('dd-MMM'); - - $monthName = $this->month_toString(intval($trajet->mois)); - $fullnameThanato = (($trajet->nom_thanato != null) ? $trajet->nom_thanato : '').' '.(($trajet->prenom_thanato != null) ? $trajet->prenom_thanato : ''); - - $_clean_folder = $clean_folder.'INDEMNITES KILOMETRIQUES/'.$trajet->annee.'/'.strtoupper($fullnameThanato).'/'; - try { - $this->storage->newFolder($_clean_folder); - } catch(\OCP\Files\NotPermittedException $e) { - } - - $trajetdetails = json_decode($this->myDb->getTrajetsdetails_orderByDate($numtrajet, $idNextcloud)); - $distance_temp = 0; - $distances = array(); - $last_point = null; - - $ik_temp = 'CLIENTS'.';'.'JOUR'.';'.'LIEU'.';'.'TOTAL'."\n"; - for ($i = 0; $i < sizeof($trajetdetails); $i++) { - $date_temp = new DateTime($trajetdetails[$i]->date); - if(strcmp(explode('-', $trajetdetails[$i]->date)[2], explode('-', $trajetdetails[$i + 1]->date)[2]) != 0) { - array_push($distances, $distance_temp); - $ik_temp = $ik_temp.utf8_decode(html_entity_decode($trajetdetails[$i]->cprenoms.' '.$trajetdetails[$i]->cnom)).';'.utf8_decode($formatter_ds->format($date_temp)).';'.utf8_decode(html_entity_decode($trajetdetails[$i]->lieu)).';'.$distance_temp."\n"; - $distance_temp = 0; - $last_point = null; - } else { - $currentDistance = 0; - if($trajetdetails[$i]->lid != null) { - $last_point = $trajetdetails[$i]; - } - if($last_point->lid != null && $trajetdetails[$i + 1]->lid != null) { - $currentDistance = $this->myDb->calcul_distance(floatval($last_point->latitude), floatval($last_point->longitude), floatval($trajetdetails[$i + 1]->latitude), floatval($trajetdetails[$i + 1]->longitude)); - $distance_temp += $currentDistance; - } - $ik_temp = $ik_temp.utf8_decode(html_entity_decode($trajetdetails[$i]->cprenoms.' '.$trajetdetails[$i]->cnom)).';'.utf8_decode($formatter_ds->format($date_temp)).';'.utf8_decode(html_entity_decode($trajetdetails[$i]->lieu)).';'.$currentDistance."\n"; - } - } - - // distance total - $distance_final = 0; - foreach ($distances as $key => $valdistance) { - $distance_final += $valdistance; - } - - $ik_temp = $ik_temp."\n\n\n\n".''.';'.''.';'.'sous total'.';'.$distance_final; - - $total_ik = $distance_final * floatval($current_config[0]->coefficient_ik); - $ik_temp = $ik_temp."\n\n".''.';'.'TOTAL'.';'.$current_config[0]->coefficient_ik.';'.$total_ik; - $ik_temp = $ik_temp."\n".''.';'.'ELECTRIQUE'.';'.''.';'.round($total_ik, 2); - - $nom_thanato = html_entity_decode($trajet->nom_thanato).' '.html_entity_decode($trajet->prenom_thanato); - $ff = $_clean_folder.'IK_'.$trajet->annee.'_'.$monthName.'_'.strtoupper($fullnameThanato).'_'.strtoupper($nom_thanato).'.csv'; - $this->storage->newFile($ff); - $file = $this->storage->get($ff); - $file->putContent($ik_temp); - - } catch(\OCP\Files\NotFoundException $e) { + } - return true; - } - - private function month_toString($monthnumber) - { - $result = ''; - switch ($monthnumber) { - case 1: - $result = '01JANVIER'; - break; - case 2: - $result = '02FEVRIER'; - break; - case 3: - $result = '03MARS'; - break; - case 4: - $result = '04AVRIL'; - break; - case 5: - $result = '05MAI'; - break; - case 6: - $result = '06JUIN'; - break; - case 7: - $result = '07JUILLET'; - break; - case 8: - $result = '08AOUT'; - break; - case 9: - $result = '09SEPTEMBRE'; - break; - case 10: - $result = '10OCTOBRE'; - break; - case 11: - $result = '11NOVEMBRE'; - break; - case 12: - $result = '12DECEMBRE'; - break; - } - return $result; - } - - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function insertDevis() - { - return $this->myDb->insertDevis($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function insertFacture() - { - $result = $this->myDb->insertFacture($this->idNextcloud); - $this->refreshFEC(); - return $result; - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function insertProduit() - { - return $this->myDb->insertProduit($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $id - */ - public function insertProduitDevis($id) - { - return $this->myDb->insertProduitDevis($id, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $id - */ - public function insertArticleDevis($id) - { - return $this->myDb->insertArticleDevis($id, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $id - */ - public function insertObservationDefunt($id) - { - return $this->myDb->insertObservationDefunt($id, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $id - */ - public function insertBijouDefunt($id) - { - return $this->myDb->insertBijouDefunt($id, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $id - */ - public function insertHypoDefunt($id) - { - return $this->myDb->insertHypoDefunt($id, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function insertBibliotheque() - { - return $this->myDb->insertBibliotheque($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $table - * @param string $column - * @param string $data - * @param string $id - */ - public function update($table, $column, $data, $id) - { - if(strcmp($table, 'facture') == 0 || strcmp($table, 'produit') == 0 || strcmp($table, 'devis') == 0) { - if(strcmp($column, 'id_devis') == 0) { - $facturecourant = json_decode($this->myDb->getOneFacture($id, $this->idNextcloud))[0]; - $this->myDb->gestion_update('devis', 'mentions', 'facturé', $data, $this->idNextcloud); - $this->myDb->gestion_update('devis', 'mentions', 'Nouveau', $facturecourant->id_devis, $this->idNextcloud); - $result = $this->myDb->gestion_update($table, $column, $data, $id, $this->idNextcloud); - - } else { - $facturecourant = json_decode($this->myDb->getOneFacture($id, $this->idNextcloud))[0]; - if(strcmp($column, 'date_paiement') == 0) { - $datecourant = $facturecourant->date_paiement; - $nouveaudate = $data; - $result = $this->myDb->gestion_update($table, $column, $data, $id, $this->idNextcloud); - // $this->generer_document_comptable($datecourant); - // $this->generer_document_comptable($nouveaudate); - } else { - if(strcmp($column, 'date') == 0) { - if(strcmp($table, 'facture')) { - $datetime = new Datetime($data); - $factureNumber = $this->myDb->getFactureNumberByDate($datetime); - $this->myDb->gestion_update($table, "facture_number", $factureNumber, $id, $this->idNextcloud); - $factureFullNumber = $this->myDb->getFactureFullNumberByDate($datetime); - $this->myDb->gestion_update($table, "num", $factureFullNumber, $id, $this->idNextcloud); - } - if(strcmp($table, 'devis')) { - $datetime = new Datetime($data); - $devisNumber = $this->myDb->getDevisNumberByDate($datetime); - $this->myDb->gestion_update($table, "devis_number", $devisNumber, $id, $this->idNextcloud); - $devisFullNumber = $this->myDb->getDevisFullNumberByDate($datetime); - $this->myDb->gestion_update($table, "num", $devisFullNumber, $id, $this->idNextcloud); - } - } - $result = $this->myDb->gestion_update($table, $column, $data, $id, $this->idNextcloud); - // $this->generer_document_comptable($facturecourant->date_paiement); - } - } - $this->refreshFEC(); - return $result; - } - return $this->myDb->gestion_update($table, $column, $data, $id, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param array $devisToFacture - * @param string $paymentDate - */ - public function exportDevisToFacture($devisToFacture, $paymentDate, $type = FactureTypeConstant::TYPE_SINGLE) - { - $response = true; - $factureIdsGenerated = []; - if($type == FactureTypeConstant::TYPE_GROUP) { - $doDevisIdsListIdsBelongsToTheSameClientFacturationGroup = $this->myDb->doDevisIdsListIdsBelongsToTheSameClientFacturationGroup($devisToFacture); - if($doDevisIdsListIdsBelongsToTheSameClientFacturationGroup == false) { - return "Les devis fournis ne sont pas dans la même groupe de facturation"; - } - $factureIdsGenerated = $this->myDb->generateGroupFactureForMultipleDevis($devisToFacture, $paymentDate); - } else { - $factureIdsGenerated = $this->myDb->insertFactureForeEachDevisId($this->idNextcloud, $devisToFacture, $paymentDate); - } - $this->invoicePdfService->generateFacturePdfByFactureIds($factureIdsGenerated, $this->idNextcloud); - $this->refreshFEC(); - return $response; - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $table - * @param string $id - */ - public function delete($table, $id) - { - if(strcmp($table, 'facture') == 0 || strcmp($table, 'produit') == 0 || strcmp($table, 'devis') == 0 || strcmp($table, 'client') == 0) { - if(strcmp($table, 'facture') == 0) { - $facturecourant = json_decode($this->myDb->getOneFacture($id, $this->idNextcloud))[0]; - $this->myDb->gestion_update('devis', 'mentions', 'Nouveau', $facturecourant->id_devis, $this->idNextcloud); - $result = $this->myDb->gestion_delete($table, $id, $this->idNextcloud); - } else { - $result = $this->myDb->gestion_delete($table, $id, $this->idNextcloud); - } - $this->refreshFEC(); - return $result; - } - return $this->myDb->gestion_delete($table, $id, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $content - * @param string $name - * @param string $subject - * @param string $body - * @param string $to - * @param string $Cc - */ - public function sendPDF($content, $name, $subject, $body, $to, $Cc) - { - $clean_name = html_entity_decode($name); - try { - $data = base64_decode($content); - $message = $this->mailer->createMessage(); - $message->setSubject($subject); - $message->setTo((array) json_decode($to)); - $myrrCc = (array) json_decode($Cc); - - if($myrrCc[0] != "") { - $message->setCc($myrrCc); - } - $message->setHtmlBody($body); - $content = $this->mailer->createAttachment($data, $clean_name.".pdf", "x-pdf"); - $message->attach($content); - $this->mailer->send($message); - return new DataResponse("", 200, ['Content-Type' => 'application/json']); - } catch (Exception $e) { - return new DataResponse("Is your global mail server configured in Nextcloud ?", 500, ['Content-Type' => 'application/json']); - } - - } - - public function sendAttachmentToClientByDefunt($defuntId, $ff_pdf, $to, $subject, $body, $addName = false) - { - $devis = $this->myDb->getDevisOfDefunt($defuntId); - if($devis != null) { - // try { - $senderEmailAddress = $this->config->getSystemValue('mail_from_address') ?? null; - $senderEmailDomain = $this->config->getSystemValue('mail_domain') ?? null; - $senderEmail = null; - if($senderEmailAddress && $senderEmailDomain) { - $senderEmail = $senderEmailAddress.'@'.$senderEmailDomain; - } - $client_email = $to; - $client_nom = $devis['client_nom']; - $data = $this->storage->get($ff_pdf)->getContent(); - $message = $this->mailer->createMessage(); - $message->setTo(recipients: [$client_email => $client_nom]); - // $message->setFrom([$client_email => $client_nom]); - $content = $this->mailer->createAttachment($data, basename($ff_pdf), "application/pdf"); - $message->attach($content); - $message->setSubject($subject); - $body_text = $addName ? ($body." de ".$devis['defunt_nom']) : $body; - $signature = $this->mailerService->getFooterContent($this->getUserNameForEmailSignature()); - $message->setHtmlBody( - "

Bonjour.

". - "

$body_text

". - $signature - ); - - $appAdminEmail = $this->myDb->getUserEmailByNextcloudId(BddConstant::DEFAULT_ADMIN_APP_ID_NEXTCLOUD); - if ($appAdminEmail) { - $message->setCc([$appAdminEmail]); - } - $this->mailer->send($message); - return new DataResponse("", 200, ['Content-Type' => 'application/json']); - // } catch (Exception $e) { - // return new DataResponse("Is your global mail server configured in Nextcloud ?", 500, ['Content-Type' => 'application/json']); - // } - } - } - public function getUserNameForEmailSignature() - { - $configs = json_decode($this->myDb->getConfiguration(BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD)); - $currentConfig = $configs[0]; - return $currentConfig->nom . " " . $currentConfig->prenom; - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $content - * @param string $folder - * @param string $name - */ - public function savePDF($content, $folder, $name) - { - - $clean_folder = html_entity_decode($this->convert_special_char($folder)); - $clean_name = html_entity_decode($this->convert_special_char($name)); - try { - $this->storage->newFolder($clean_folder); - } catch(\OCP\Files\NotPermittedException $e) { - - } - - try { - try { - $ff = $clean_folder . $clean_name . ".pdf"; - $this->storage->newFile($ff); - $file = $this->storage->get($ff); - $data = base64_decode($content); - $file->putContent($data); - } catch(\OCP\Files\NotFoundException $e) { - + try { + try { + $ff = $clean_folder . $clean_name . ".pdf"; + $this->storage->newFile($ff); + $file = $this->storage->get($ff); + $data = base64_decode($content); + $file->putContent($data); + } catch(\OCP\Files\NotFoundException $e) { + } } catch(\OCP\Files\NotPermittedException $e) { - + } - //work - // try { + //work + // try { // try { // $file = $this->storage->get('/test/myfile2.txt'); // } catch(\OCP\Files\NotFoundException $e) { - // + // // $file = $this->storage->get('/myfile.txt'); // } @@ -1940,71 +1945,71 @@ class PageController extends Controller // throw new StorageException('Cant write to file'); // } - // // - // $userFolder->touch('/test/myfile2345.txt'); - // $file = $userFolder->get('/test/myfile2345.txt'); - // $file->putContent('test'); - // //$file = $userFolder->get('myfile2.txt'); - } + // // + // $userFolder->touch('/test/myfile2345.txt'); + // $file = $userFolder->get('/test/myfile2345.txt'); + // $file->putContent('test'); + // //$file = $userFolder->get('myfile2.txt'); + } - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $filter - * @param string $year - * @param string $month - * @param string $filterType - */ - public function saveDocumentRecap($filter, $year, $month, $filterType = MultipleFactureTypeConstant::CLIENT_FILTER_TYPE) - { - $dateString = '15-'.$month.'-'.$year; - $date_temp = DateTime::createFromFormat('d-m-Y', $dateString); - $date = $date_temp->format('d-m-Y'); - $this->generer_document_comptable_client($date, $filter, $filterType); - } + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $filter + * @param string $year + * @param string $month + * @param string $filterType + */ + public function saveDocumentRecap($filter, $year, $month, $filterType = MultipleFactureTypeConstant::CLIENT_FILTER_TYPE) { - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $content - * @param array $folders - * @param string $name - */ - public function saveNewPDF($content, $folders, $name) - { - foreach ($folders as $key => $folder) { - $clean_folder = html_entity_decode($folder); - $clean_name = html_entity_decode($name); - try { - $this->storage->newFolder($clean_folder); - } catch(\OCP\Files\NotPermittedException $e) { + $dateString = '15-'.$month.'-'.$year; + $date_temp = DateTime::createFromFormat('d-m-Y', $dateString); + $date = $date_temp->format('d-m-Y'); + $this->generer_document_comptable_client($date, $filter,$filterType); + } - } + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $content + * @param array $folders + * @param string $name + */ + public function saveNewPDF($content, $folders, $name){ - try { - try { - $ff = $clean_folder . $clean_name . ".pdf"; - $this->storage->newFile($ff); - $file = $this->storage->get($ff); - $data = base64_decode($content); - $file->putContent($data); - } catch(\OCP\Files\NotFoundException $e) { + foreach ($folders as $key => $folder) { + $clean_folder = html_entity_decode($folder); + $clean_name = html_entity_decode($name); + try { + $this->storage->newFolder($clean_folder); + } catch(\OCP\Files\NotPermittedException $e) { + + } - } + try { + try { + $ff = $clean_folder . $clean_name . ".pdf"; + $this->storage->newFile($ff); + $file = $this->storage->get($ff); + $data = base64_decode($content); + $file->putContent($data); + } catch(\OCP\Files\NotFoundException $e) { + + } - } catch(\OCP\Files\NotPermittedException $e) { + } catch(\OCP\Files\NotPermittedException $e) { + + } + } + + - } - } - - - - //work - // try { + //work + // try { // try { // $file = $this->storage->get('/test/myfile2.txt'); // } catch(\OCP\Files\NotFoundException $e) { - // + // // $file = $this->storage->get('/myfile.txt'); // } @@ -2016,400 +2021,409 @@ class PageController extends Controller // throw new StorageException('Cant write to file'); // } - // // - // $userFolder->touch('/test/myfile2345.txt'); - // $file = $userFolder->get('/test/myfile2345.txt'); - // $file->putContent('test'); - // //$file = $userFolder->get('myfile2.txt'); - } + // // + // $userFolder->touch('/test/myfile2345.txt'); + // $file = $userFolder->get('/test/myfile2345.txt'); + // $file->putContent('test'); + // //$file = $userFolder->get('myfile2.txt'); + } - private function refreshFEC() - { - $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); - $defaultTvaValue = $current_config[0]->tva_default; - $clean_folder = html_entity_decode($current_config[0]->path).'/'; + private function refreshFEC() { - try { - try { - $data_factures = array(); - $factures = json_decode($this->myDb->getFacturesListWithDependencies()); + $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); - foreach ($factures as $key => $facture) { - $factureIsSingle = $facture->facture_type == FactureTypeConstant::TYPE_SINGLE; - $currentTvaValue = $defaultTvaValue; + $clean_folder = html_entity_decode($current_config[0]->path).'/'; - $facture_temp = array( - 'num' => $facture->num, - 'client' => $facture->entreprise, - 'nom_client' => $facture->nom, - 'date' => $facture->date, - 'date_facture' => $facture->date_paiement, - 'defunt' => $facture->nom_defunt, - 'montant_htc' => 0, - 'tva' => $defaultTvaValue, - 'montant_tva' => 0, - 'montant_ttc' => 0, - ); + try { + try { + $data_factures = array(); + $factures = json_decode($this->myDb->getFacturesListWithDependencies()); - if($factureIsSingle) { - // Vérifier le statut TVA du client pour les factures individuelles - $devis = json_decode($this->myDb->getOneDevis($facture->id_devis, $this->idNextcloud))[0]; - $client = $this->myDb->getClientById($devis->id_client); - - if(isset($client['tva']) && $client['tva'] == 0) { - $currentTvaValue = 0; - $facture_temp['tva'] = 0; - } - - $produits = json_decode($this->getProduitsById($facture->id_devis)); - foreach ($produits as $key => $produit) { - $htPrice = $produit->prix_unitaire; - if($facture->fk_client_group_id != null || $facture->fk_client_group_id != 0) { - $price = $this->myDb->getProductPriceByClientGroupId($facture->fk_client_group_id, $produit->id); - if($price != null) { - $htPrice = $price; - } - } - $facture_temp['montant_htc'] += $htPrice * $produit->quantite; - }; - - if($currentTvaValue > 0) { - $facture_temp['montant_tva'] = ($facture_temp['montant_htc'] * $currentTvaValue) / 100; - } else { - $facture_temp['montant_tva'] = 0; - } - $facture_temp['montant_ttc'] = $facture_temp['montant_tva'] + $facture_temp['montant_htc']; - - } else { - // Pour les factures groupées, logique existante mais avec vérification TVA par devis - $devis = $this->myDb->getDevisByFkFactureId($facture->id); - $factureGroupIsRelatedToAnyDevis = $devis != null; - $mentionFilters = [ - DevisMentionConstant::FACTURED, - DevisMentionConstant::FACTURED_FORMATTED - ]; - - $isFactureGroupForSingleClient = $facture->facture_client_id != null && $facture->facture_client_id != 0; - if($isFactureGroupForSingleClient) { - $facture_temp["client"] = $facture->facture_client_entreprise; - $facture_temp["nom_client"] = $facture->facture_client_name; - - if(!$factureGroupIsRelatedToAnyDevis) { - $devisList = $this->myDb->getDevisByClientIdAndMonthYear( - $facture->facture_client_id, - $facture->facture_month, - $facture->facture_year, - $mentionFilters - ); - } - } else { - $facture_temp["client"] = $facture->group_code_comptable ?? '-'; - $facture_temp["nom_client"] = $facture->facture_group_name; - - if(!$factureGroupIsRelatedToAnyDevis) { - $devisList = $this->myDb->getDevisByClientGroupFacturationIdAndMonthYear( - $facture->facture_client_group_facturation_id, - $facture->facture_month, - $facture->facture_year, - $mentionFilters - ); - } - } - - if($factureGroupIsRelatedToAnyDevis) { - $devisList = $this->myDb->getDevisByClientIdByFactureId($facture->id, $mentionFilters); - } - - foreach($devisList as $currentDevis) { - // Vérifier la TVA pour chaque devis dans le groupe - $devisClient = $this->myDb->getClientById($currentDevis['id_client']); - $devisTvaValue = $defaultTvaValue; - - if(isset($devisClient['tva']) && $devisClient['tva'] == 0) { - $devisTvaValue = 0; - } - - $produits = json_decode($this->getProduitsById($currentDevis['id'])); - foreach ($produits as $key => $produit) { - $htPrice = $produit->prix_unitaire; - if($currentDevis["fk_client_group_id"] != null || $currentDevis["fk_client_group_id"] != 0) { - $price = $this->myDb->getProductPriceByClientGroupId($currentDevis["fk_client_group_id"], $produit->id); - if($price != null) { - $htPrice = $price; - } - } - $facture_temp['montant_htc'] += $htPrice * $produit->quantite; - - // Calculer la TVA pour ce produit spécifiquement - if($devisTvaValue > 0) { - $facture_temp['montant_tva'] += ($htPrice * $produit->quantite * $devisTvaValue) / 100; - } - }; - } - $facture_temp['montant_ttc'] = $facture_temp['montant_tva'] + $facture_temp['montant_htc']; - } - - array_push($data_factures, $facture_temp); - }; - $data_temp = array(); - foreach ($data_factures as $key => $facture) { - $datesplit = explode('-', $facture['date_facture']); - if($data_temp[strval($datesplit[0])] == null) { - $data_temp[strval($datesplit[0])][strval($datesplit[1])] = array(0 => $facture); - } else { - if($data_temp[strval($datesplit[0])][strval($datesplit[1])] == null) { - $data_temp[strval($datesplit[0])][strval($datesplit[1])] = array(0 => $facture); - } else { - array_push($data_temp[strval($datesplit[0])][strval($datesplit[1])], $facture); - } - } - } - // var_dump($data_temp); - //parcours annee - foreach ($data_temp as $key_annee => $annee) { - //parcours annee - $_clean_folder = $clean_folder.'FEC/'.$key_annee.'/'; - try { - $this->storage->newFolder($_clean_folder); - } catch(\OCP\Files\NotPermittedException $e) { - } - foreach ($annee as $key_mois => $mois) { - $fec_temp_txt = 'Code journal'.TAB1.utf8_decode('Date écriture').TAB1.'Code compte'.TAB1.utf8_decode('Intitulé compte').TAB1.utf8_decode('Pièce').TAB1.utf8_decode('Libellé écriture').TAB1.utf8_decode('Débit origine').TAB1.utf8_decode('Crédit origine').TAB1.utf8_decode('Débit euro').TAB1.utf8_decode('Crédit euro').TAB1.'Lettrage'.TAB1.'Lettrage n+1'.TAB1.'Lettrage partiel'.TAB1.'Monnaie'.TAB1.'ISO Monnaie'.TAB1.'taux change'.TAB1.'Section analytique 1'.TAB1.'Section analytique 2'.TAB1.'Section analytique 3'.PHP_EOL.PHP_EOL; - // $fec_temp = 'NUMERO'.';'.'CLIENT'.';'.'DEFUNT'.';'.'DATE'.';'.'MONTANTHTC'.';'.'TVA'.';'.'MONTANTTVA'.';'.'MONTANTTTC'."\n"; - $fec_temp = 'Code journal'.';'.utf8_decode('Date écriture').';'.'Code compte'.';'.utf8_decode('Intitulé compte').';'.utf8_decode('Pièce').';'.utf8_decode('Libellé écriture').';'.utf8_decode('Débit origine').';'.utf8_decode('Crédit origine').';'.utf8_decode('Débit euro').';'.utf8_decode('Crédit euro').';'.'Lettrage'.';'.'Lettrage n+1'.';'.'Lettrage partiel'.';'.'Monnaie'.';'.'ISO Monnaie'.';'.'taux change'.';'.'Section analytique 1'.';'.'Section analytique 2'.';'.'Section analytique 3'."\n\n"; - foreach ($mois as $key => $facture) { - $fec_temp_txt = $fec_temp_txt.'VT'.TAB1.$facture['date_facture'].TAB1.$facture['client'].TAB1.$facture['client'].TAB1.$facture['num'].TAB1.$facture['nom_client'].TAB1.$facture['montant_ttc'].TAB1.'0'.TAB1.$facture['montant_htc'].TAB1.'0'.TAB1.''.TAB1.'FAUX'.TAB1.'FAUX'.TAB1.'E'.TAB1.''.TAB1.'1'.TAB1.''.TAB1.''.TAB1.''.PHP_EOL.PHP_EOL; - $fec_temp_txt = $fec_temp_txt.'VT'.TAB1.$facture['date_facture'].TAB1.'706000'.TAB1.'VENTES DE MARCHANDISES'.TAB1.$facture['num'].TAB1.$facture['client'].TAB1.'0'.TAB1.$facture['montant_htc'].TAB1.'0'.TAB1.$facture['montant_htc'].TAB1.''.TAB1.'FAUX'.TAB1.'FAUX'.TAB1.'E'.TAB1.''.TAB1.'1'.TAB1.''.TAB1.''.TAB1.''.PHP_EOL.PHP_EOL; - $fec_temp_txt = $fec_temp_txt.'VT'.TAB1.$facture['date_facture'].TAB1.'445710'.TAB1.''.TAB1.$facture['num'].TAB1.$facture['client'].TAB1.''.TAB1.$facture['montant_tva'].TAB1.''.TAB1.$facture['montant_tva'].TAB1.''.TAB1.''.TAB1.''.TAB1.''.TAB1.''.TAB1.''.TAB1.''.TAB1.''.PHP_EOL.PHP_EOL; - - $fec_temp = $fec_temp.'VT'.';'.$facture['date_facture'].';'.$facture['client'].';'.$facture['client'].';'.$facture['num'].';'.$facture['nom_client'].';'.$facture['montant_ttc'].';0;'.$facture['montant_htc'].';0;'.''.';'.'FAUX'.';'.'FAUX'.';'.'E'.';'.''.';'.'1'.';'.''.';'.''.';'.''."\n\n"; - $fec_temp = $fec_temp.'VT'.';'.$facture['date_facture'].';706000;VENTES DE MARCHANDISES;'.$facture['num'].';'.$facture['client'].';0;'.$facture['montant_htc'].';0;'.$facture['montant_htc'].';'.''.';'.'FAUX'.';'.'FAUX'.';'.'E'.';'.''.';'.'1'.';'.''.';'.''.';'.''."\n\n"; - $fec_temp = $fec_temp.'VT'.';'.$facture['date_facture'].';445710;;'.$facture['num'].';'.$facture['client'].';;'.$facture['montant_tva'].';;'.$facture['montant_tva'].";;;;;;;;;\n\n"; - } - $ff = $_clean_folder.'FEC_'.$key_mois.'_'.$key_annee.'.csv'; - $this->storage->newFile($ff); - $file = $this->storage->get($ff); - $file->putContent($fec_temp); - - $ff_txt = $_clean_folder.'FEC_'.$key_mois.'_'.$key_annee.'.txt'; - $this->storage->newFile($ff_txt); - $file_txt = $this->storage->get($ff_txt); - $file_txt->putContent($fec_temp_txt); - // $file->putContent(implode(';', array('Jane Smith', 'janesmith@example.com', '555-5678')) . "\n"); - } - } - - } catch(\OCP\Files\NotFoundException $e) { - } - - } catch(\OCP\Files\NotPermittedException $e) { - } - } - - private function signatureImageExists(string $signatureImageName) - { - $signatureExist = true; - try { - if(isset($this->adminStorage)) { - $file = $this->adminStorage->get("/.gestion/".$signatureImageName); - } else { - $signatureExist = false; - } - } catch(\OCP\Files\NotFoundException $e) { - $signatureExist = false; - } - return $signatureExist; - } + foreach ($factures as $key => $facture) { + $factureIsSingle = $facture->facture_type == FactureTypeConstant::TYPE_SINGLE; - private function getLogo() - { - try { - if(isset($this->adminStorage)) { - $file = $this->adminStorage->get('/.gestion/logo.png'); - } else { - return "nothing"; - } - } catch(\OCP\Files\NotFoundException $e) { - return "nothing"; + $facture_temp = array( + 'num' => $facture->num, + 'client' => $facture->entreprise, + 'nom_client' => $facture->nom, + 'date' => $facture->date, + 'date_facture' => $facture->date_paiement, + 'defunt' => $facture->nom_defunt, + 'montant_htc' => 0, + 'tva' => $current_config[0]->tva_default, + 'montant_tva' => 0, + 'montant_ttc' => 0, + ); + + if($factureIsSingle){ + + + + + + + + + + $produits = json_decode($this->getProduitsById($facture->id_devis)); + foreach ($produits as $key => $produit) { + $htPrice = $produit->prix_unitaire; + if($facture->fk_client_group_id != null || $facture->fk_client_group_id != 0){ + $price = $this->myDb->getProductPriceByClientGroupId($facture->fk_client_group_id,$produit->id); + if($price != null){ + $htPrice = $price; + } + } + $facture_temp['montant_htc'] += $htPrice * $produit->quantite; + }; + $facture_temp['montant_tva'] = ($facture_temp['montant_htc'] * $facture_temp['tva'])/100; + $facture_temp['montant_ttc'] = $facture_temp['montant_tva'] + $facture_temp['montant_htc']; + + + + } + else{ + + + + $devis = $this->myDb->getDevisByFkFactureId($facture->id); + $factureGroupIsRelatedToAnyDevis = $devis != null; + $mentionFilters = [ + DevisMentionConstant::FACTURED, + DevisMentionConstant::FACTURED_FORMATTED + ]; + + + $isFactureGroupForSingleClient = $facture->facture_client_id != null && $facture->facture_client_id != 0; + if($isFactureGroupForSingleClient){ + $facture_temp["client"] = $facture->facture_client_entreprise; + $facture_temp["nom_client"] = $facture->facture_client_name; + + if(!$factureGroupIsRelatedToAnyDevis ){ + $devisList = $this->myDb->getDevisByClientIdAndMonthYear( + $facture->facture_client_id, + $facture->facture_month, + $facture->facture_year, + $mentionFilters + ); + } + } + else{ + $facture_temp["client"] = $facture->group_code_comptable ??'-'; + $facture_temp["nom_client"] = $facture->facture_group_name; + + if(!$factureGroupIsRelatedToAnyDevis ){ + $devisList = $this->myDb->getDevisByClientGroupFacturationIdAndMonthYear( + $facture->facture_client_group_facturation_id, + $facture->facture_month, + $facture->facture_year, + [ + DevisMentionConstant::FACTURED, + DevisMentionConstant::FACTURED_FORMATTED + ] + ); + } + } + + if($factureGroupIsRelatedToAnyDevis){ + $devisList = $this->myDb->getDevisByClientIdByFactureId($facture->id, $mentionFilters ); + } + + foreach($devisList as $currentDevis){ + + + + + + + + + $produits = json_decode($this->getProduitsById($currentDevis['id'])); + foreach ($produits as $key => $produit) { + $htPrice = $produit->prix_unitaire; + if($currentDevis["fk_client_group_id"] != null || $currentDevis["fk_client_group_id"] != 0){ + $price = $this->myDb->getProductPriceByClientGroupId($currentDevis["fk_client_group_id"],$produit->id); + if($price != null){ + $htPrice = $price; + } + } + $facture_temp['montant_htc'] += $htPrice * $produit->quantite; + + + + + + }; + } + $facture_temp['montant_tva'] = ($facture_temp['montant_htc'] * $facture_temp['tva'])/100; + $facture_temp['montant_ttc'] = $facture_temp['montant_tva'] + $facture_temp['montant_htc']; + } + + array_push($data_factures, $facture_temp); + }; + $data_temp = array(); + foreach ($data_factures as $key => $facture) { + $datesplit = explode('-', $facture['date_facture']); + if($data_temp[strval($datesplit[0])]==NULL) { + $data_temp[strval($datesplit[0])][strval($datesplit[1])] = array(0=>$facture); + } else { + if($data_temp[strval($datesplit[0])][strval($datesplit[1])]==NULL) { + $data_temp[strval($datesplit[0])][strval($datesplit[1])] = array(0=>$facture); + } else { + array_push($data_temp[strval($datesplit[0])][strval($datesplit[1])], $facture); + } + } + } + // var_dump($data_temp); + //parcours annee + foreach ($data_temp as $key_annee => $annee) { + //parcours annee + $_clean_folder = $clean_folder.'FEC/'.$key_annee.'/'; + try { + $this->storage->newFolder($_clean_folder); + } catch(\OCP\Files\NotPermittedException $e) { } + + foreach ($annee as $key_mois => $mois) { + $fec_temp_txt = 'Code journal'.TAB1.utf8_decode('Date écriture').TAB1.'Code compte'.TAB1.utf8_decode('Intitulé compte').TAB1.utf8_decode('Pièce').TAB1.utf8_decode('Libellé écriture').TAB1.utf8_decode('Débit origine').TAB1.utf8_decode('Crédit origine').TAB1.utf8_decode('Débit euro').TAB1.utf8_decode('Crédit euro').TAB1.'Lettrage'.TAB1.'Lettrage n+1'.TAB1.'Lettrage partiel'.TAB1.'Monnaie'.TAB1.'ISO Monnaie'.TAB1.'taux change'.TAB1.'Section analytique 1'.TAB1.'Section analytique 2'.TAB1.'Section analytique 3'.PHP_EOL.PHP_EOL; + // $fec_temp = 'NUMERO'.';'.'CLIENT'.';'.'DEFUNT'.';'.'DATE'.';'.'MONTANTHTC'.';'.'TVA'.';'.'MONTANTTVA'.';'.'MONTANTTTC'."\n"; + $fec_temp = 'Code journal'.';'.utf8_decode('Date écriture').';'.'Code compte'.';'.utf8_decode('Intitulé compte').';'.utf8_decode('Pièce').';'.utf8_decode('Libellé écriture').';'.utf8_decode('Débit origine').';'.utf8_decode('Crédit origine').';'.utf8_decode('Débit euro').';'.utf8_decode('Crédit euro').';'.'Lettrage'.';'.'Lettrage n+1'.';'.'Lettrage partiel'.';'.'Monnaie'.';'.'ISO Monnaie'.';'.'taux change'.';'.'Section analytique 1'.';'.'Section analytique 2'.';'.'Section analytique 3'."\n\n"; + foreach ($mois as $key => $facture) { + $fec_temp_txt = $fec_temp_txt.'VT'.TAB1.$facture['date_facture'].TAB1.$facture['client'].TAB1.$facture['client'].TAB1.$facture['num'].TAB1.$facture['nom_client'].TAB1.$facture['montant_ttc'].TAB1.'0'.TAB1.$facture['montant_htc'].TAB1.'0'.TAB1.''.TAB1.'FAUX'.TAB1.'FAUX'.TAB1.'E'.TAB1.''.TAB1.'1'.TAB1.''.TAB1.''.TAB1.''.PHP_EOL.PHP_EOL; + $fec_temp_txt = $fec_temp_txt.'VT'.TAB1.$facture['date_facture'].TAB1.'706000'.TAB1.'VENTES DE MARCHANDISES'.TAB1.$facture['num'].TAB1.$facture['client'].TAB1.'0'.TAB1.$facture['montant_htc'].TAB1.'0'.TAB1.$facture['montant_htc'].TAB1.''.TAB1.'FAUX'.TAB1.'FAUX'.TAB1.'E'.TAB1.''.TAB1.'1'.TAB1.''.TAB1.''.TAB1.''.PHP_EOL.PHP_EOL; + $fec_temp_txt = $fec_temp_txt.'VT'.TAB1.$facture['date_facture'].TAB1.'445710'.TAB1.''.TAB1.$facture['num'].TAB1.$facture['client'].TAB1.''.TAB1.$facture['montant_tva'].TAB1.''.TAB1.$facture['montant_tva'].TAB1.''.TAB1.''.TAB1.''.TAB1.''.TAB1.''.TAB1.''.TAB1.''.TAB1.''.PHP_EOL.PHP_EOL; + + $fec_temp = $fec_temp.'VT'.';'.$facture['date_facture'].';'.$facture['client'].';'.$facture['client'].';'.$facture['num'].';'.$facture['nom_client'].';'.$facture['montant_ttc'].';0;'.$facture['montant_htc'].';0;'.''.';'.'FAUX'.';'.'FAUX'.';'.'E'.';'.''.';'.'1'.';'.''.';'.''.';'.''."\n\n"; + $fec_temp = $fec_temp.'VT'.';'.$facture['date_facture'].';706000;VENTES DE MARCHANDISES;'.$facture['num'].';'.$facture['client'].';0;'.$facture['montant_htc'].';0;'.$facture['montant_htc'].';'.''.';'.'FAUX'.';'.'FAUX'.';'.'E'.';'.''.';'.'1'.';'.''.';'.''.';'.''."\n\n"; + $fec_temp = $fec_temp.'VT'.';'.$facture['date_facture'].';445710;;'.$facture['num'].';'.$facture['client'].';;'.$facture['montant_tva'].';;'.$facture['montant_tva'].";;;;;;;;;\n\n"; + } + $ff = $_clean_folder.'FEC_'.$key_mois.'_'.$key_annee.'.csv'; + $this->storage->newFile($ff); + $file = $this->storage->get($ff); + $file->putContent($fec_temp); + + $ff_txt = $_clean_folder.'FEC_'.$key_mois.'_'.$key_annee.'.txt'; + $this->storage->newFile($ff_txt); + $file_txt = $this->storage->get($ff_txt); + $file_txt->putContent($fec_temp_txt); + // $file->putContent(implode(';', array('Jane Smith', 'janesmith@example.com', '555-5678')) . "\n"); + } + } + + } catch(\OCP\Files\NotFoundException $e) { } + + + } catch(\OCP\Files\NotPermittedException $e) { } + } + + + private function signatureImageExists(string $signatureImageName){ + + $signatureExist = true; + try{ + if(isset($this->adminStorage)){ + $file = $this->adminStorage->get("/.gestion/".$signatureImageName); + }else{ + $signatureExist = false; + } + } + catch(\OCP\Files\NotFoundException $e) { + $signatureExist = false; + } + return $signatureExist; + } + + + private function getLogo(){ + + try{ + if(isset($this->adminStorage)){ + $file = $this->adminStorage->get('/.gestion/logo.png'); + }else{ + return "nothing"; + } + } + catch(\OCP\Files\NotFoundException $e) { + return "nothing"; + } + + return base64_encode($file->getContent()); + } + private function getSignature(){ + + try{ + if(isset($this->adminStorage)){ + $file = $this->adminStorage->get('/.gestion/sign.jpg'); + return $file->getContent(); + } + + } + catch(\OCP\Files\NotFoundException $e) {} + + return false; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getStats(){ + + + $isThanato = in_array('Thanatos',$this->groups); + $isAdmin = in_array('admin',$this->groups); + $isUserThanatoOnly = $isThanato && !$isAdmin; + $res = array(); + $res['client'] = json_decode($this->myDb->numberClient($this->idNextcloud))[0]->c; + $res['defunt'] = $this->myDb->numberDefunt($this->idNextcloud,$isUserThanatoOnly); + $res['thanato'] = json_decode($this->myDb->numberThanato($this->idNextcloud))[0]->c; + $res['devis'] = json_decode($this->myDb->numberDevis($this->idNextcloud))[0]->c; + $res['lieu'] = json_decode($this->myDb->numberLieu($this->idNextcloud))[0]->c; + $res['trajet'] = json_decode($this->myDb->numberTrajet($this->idNextcloud))[0]->c; + $res['facture'] = json_decode($this->myDb->numberFacture($this->idNextcloud))[0]->c; + $res['produit'] = json_decode($this->myDb->numberProduit($this->idNextcloud))[0]->c; + $res['article'] = json_decode($this->myDb->numberArticle($this->idNextcloud))[0]->c; + $res['bibliotheque'] = json_decode($this->myDb->numberBibliotheque($this->idNextcloud))[0]->c; + $res['clientGroup'] = json_decode($this->myDb->getClientGroupCount())[0]->c; + $res['clientGroupDiscount'] = json_decode($this->myDb->getClientGroupDiscountCount())[0]->c; + $res['clientGroupFacturation'] = json_decode($this->myDb->getClientGroupFacturationCount())[0]->c; + return json_encode($res); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getAnnualTurnoverPerMonthNoVat(){ + + return $this->myDb->retrieveTotalInvoicesForTheYear(); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param integer $annee + */ + public function getStatArticleAnnuel($annee) { + + return $this->myDb->getStatArticleAnnuel($this->idNextcloud, $annee); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param integer $annee + */ + public function getStatSoinsThanatoAnnuel($annee) { + + $result = $this->myDb->getStatSoinsThanatoAnnuel($this->idNextcloud, $annee); + return html_entity_decode($result); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param integer $annee + * @param integer $mois + */ + public function getStatSoinsThanatoWeekend($annee, $mois) { + + $result = $this->myDb->getStatSoinsThanatoWeekend($this->idNextcloud, $annee, $mois); + return html_entity_decode($result); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getDefunts() { + + $isThanato = in_array('Thanatos',$this->groups); + $isAdmin = in_array('admin',$this->groups); + $isUserThanatoOnly = $isThanato && !$isAdmin; + return $this->myDb->getDefunts($this->idNextcloud,$isUserThanatoOnly); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getUnusedDefunts() { + + return $this->myDb->getUnusedDefunts($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function insertDefunt() { + + return $this->myDb->insertDefunt($this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numdefunt + */ + public function getObservationsById($numdefunt) { + + return $this->myDb->getListObservations($numdefunt, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numdefunt + */ + public function getHypodermiquesById($numdefunt) { + + return $this->myDb->getListHypodermiques($numdefunt, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numdefunt + */ + public function getBijouxById($numdefunt) { + + return $this->myDb->getListBijoux($numdefunt, $this->idNextcloud); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getArticles() { + + return $this->myDb->getArticles($this->idNextcloud); } - return base64_encode($file->getContent()); - } - private function getSignature() - { - try { - if(isset($this->adminStorage)) { - $file = $this->adminStorage->get('/.gestion/sign.jpg'); - return $file->getContent(); - } - } catch(\OCP\Files\NotFoundException $e) { + public function ajaxGetArticles() { + + return $this->myDb->getArticles($this->idNextcloud); } - return false; - } + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numdevis + */ + public function getArticlesById($numdevis) { - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getStats() - { + return $this->myDb->getListArticle($numdevis, $this->idNextcloud); + } - $isThanato = in_array('Thanatos', $this->groups); - $isAdmin = in_array('admin', $this->groups); - $isUserThanatoOnly = $isThanato && !$isAdmin; - $res = array(); - $res['client'] = json_decode($this->myDb->numberClient($this->idNextcloud))[0]->c; - $res['defunt'] = $this->myDb->numberDefunt($this->idNextcloud, $isUserThanatoOnly); - $res['thanato'] = json_decode($this->myDb->numberThanato($this->idNextcloud))[0]->c; - $res['devis'] = json_decode($this->myDb->numberDevis($this->idNextcloud))[0]->c; - $res['lieu'] = json_decode($this->myDb->numberLieu($this->idNextcloud))[0]->c; - $res['trajet'] = json_decode($this->myDb->numberTrajet($this->idNextcloud))[0]->c; - $res['facture'] = json_decode($this->myDb->numberFacture($this->idNextcloud))[0]->c; - $res['produit'] = json_decode($this->myDb->numberProduit($this->idNextcloud))[0]->c; - $res['article'] = json_decode($this->myDb->numberArticle($this->idNextcloud))[0]->c; - $res['bibliotheque'] = json_decode($this->myDb->numberBibliotheque($this->idNextcloud))[0]->c; - $res['clientGroup'] = json_decode($this->myDb->getClientGroupCount())[0]->c; - $res['clientGroupDiscount'] = json_decode($this->myDb->getClientGroupDiscountCount())[0]->c; - $res['clientGroupFacturation'] = json_decode($this->myDb->getClientGroupFacturationCount())[0]->c; - return json_encode($res); - } + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function insertArticle() { - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getAnnualTurnoverPerMonthNoVat() - { - return $this->myDb->retrieveTotalInvoicesForTheYear(); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param integer $annee - */ - public function getStatArticleAnnuel($annee) - { - return $this->myDb->getStatArticleAnnuel($this->idNextcloud, $annee); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param integer $annee - */ - public function getStatSoinsThanatoAnnuel($annee) - { - $result = $this->myDb->getStatSoinsThanatoAnnuel($this->idNextcloud, $annee); - return html_entity_decode($result); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param integer $annee - * @param integer $mois - */ - public function getStatSoinsThanatoWeekend($annee, $mois) - { - $result = $this->myDb->getStatSoinsThanatoWeekend($this->idNextcloud, $annee, $mois); - return html_entity_decode($result); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getDefunts() - { - $isThanato = in_array('Thanatos', $this->groups); - $isAdmin = in_array('admin', $this->groups); - $isUserThanatoOnly = $isThanato && !$isAdmin; - return $this->myDb->getDefunts($this->idNextcloud, $isUserThanatoOnly); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getUnusedDefunts() - { - return $this->myDb->getUnusedDefunts($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function insertDefunt() - { - return $this->myDb->insertDefunt($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numdefunt - */ - public function getObservationsById($numdefunt) - { - return $this->myDb->getListObservations($numdefunt, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numdefunt - */ - public function getHypodermiquesById($numdefunt) - { - return $this->myDb->getListHypodermiques($numdefunt, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numdefunt - */ - public function getBijouxById($numdefunt) - { - return $this->myDb->getListBijoux($numdefunt, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getArticles() - { - return $this->myDb->getArticles($this->idNextcloud); - } - - public function ajaxGetArticles() - { - return $this->myDb->getArticles($this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numdevis - */ - public function getArticlesById($numdevis) - { - return $this->myDb->getListArticle($numdevis, $this->idNextcloud); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function insertArticle() - { - return $this->myDb->insertArticle($this->idNextcloud); - } + return $this->myDb->insertArticle($this->idNextcloud); + } /** * @NoAdminRequired @@ -2445,1171 +2459,1201 @@ class PageController extends Controller } } - private function calculAge($dateNaissance) - { - // Convertir la date de naissance en objet DateTime - $dateNaissance = new DateTime($dateNaissance); - // Obtenir la date actuelle - $dateActuelle = new DateTime(); - // Calculer la différence entre les deux dates - $difference = $dateActuelle->diff($dateNaissance); - // Renvoyer l'âge - return $difference->y; - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numdefunt - */ - public function saveRapportSoin($numdefunt, $email = '') - { - $defaultConfig = json_decode($this->myDb->getConfiguration(BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD)); - $defunt = json_decode($this->myDb->getOneDefunt($numdefunt, $this->idNextcloud))[0]; - $observations = json_decode($this->myDb->getListObservations($numdefunt, $this->idNextcloud)); - $hypodermiques = json_decode($this->myDb->getListHypodermiques($numdefunt, $this->idNextcloud)); - - // print_r(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $current_config[0]->legal_one)); - - if($defunt->id_devis != null) { - try { - $numFacture = ($defunt->numero_facture == null) ? '-' : $defunt->numero_facture; - $nomDefunt = $defunt->nom_defunt; - $age = $this->calculAge($defunt->date_naissance); - - $date_devis_temp = date("d-m-Y", strtotime($defunt->date)); - $date_temp = date("d-m-Y", strtotime(date('Y-m-d'))); - - $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE); - $date_devis = $formatter->format(DateTime::createFromFormat('d-m-Y', $date_devis_temp)); - $today = $formatter->format(DateTime::createFromFormat('d-m-Y', $date_temp)); - - $folderDestination = FileExportHelpers::GetDefuntsFolder( - $defunt->nom, - $defunt->nom_defunt, - $defaultConfig[0]->path.'/' - ); - $folderDestination .= 'RAPPORTS/'; - try { - $this->storage->newFolder($folderDestination); - } catch(\OCP\Files\NotPermittedException $e) { - } - - // TODO: init pdf - $pdf = new FPDF(); - $pdf->AddFont('ComicSans', '', 'Comic Sans MS.php'); - $pdf->AddFont('ComicSans', 'B', 'comic-sans-bold.php'); - $pdf->AddPage(); - - $pdf->SetAutoPagebreak(false); - $pdf->SetMargins(15, 15, 15); - - // logo : 80 de largeur et 55 de hauteur - $logo = $this->getLogo(); - if($logo != 'nothing') { - $pdf->Image($this->defaultImagePath."logo.png", 4, 2, 50, 35); - } - $pdf->setXY(15, 15); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("N : ".$numFacture)), '', 'R'); - - $pdf->setXY(15, 55); - $pdf->SetFont('ComicSans', 'B', 15); - $pdf->Cell(80, 10, 'RAPPORT DE SOIN', 1, 1, 'C'); - - $pdf->SetY(68); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->adresse.", le ".$today), '', 'R'); - - $rapportInfoHeaderY = $pdf->GetY() + 15; - $rapportDefuntInfoY = $rapportInfoHeaderY; - $rapportDevisInfoY = $rapportInfoHeaderY; - $pdf->SetY(y: $rapportDefuntInfoY); - $pdf->SetFont('ComicSans', '', 10); - $pdf->Cell(0, 5, FileExportHelpers::FormatTextForExport($nomDefunt)); - $rapportDefuntInfoY += 5; - $pdf->SetY($rapportDefuntInfoY); - $pdf->Cell(0, 5, FileExportHelpers::FormatTextForExport($age. " ans")); - $rapportDefuntInfoY += 5; - $pdf->SetY($rapportDefuntInfoY); - $sexeText = strcmp($defunt->sexe, 'm') == 0 ? 'Masculin' : 'Féminin'; - $pdf->Cell(0, 5, FileExportHelpers::FormatTextForExport($sexeText)); - - //devis info - $rapportDevisInfoX = 115; - $maxWidth = $pdf->GetPageWidth(); - $availableWidhtForDevisInfo = $maxWidth - 10 - $rapportDevisInfoX; - $pdf->SetXY($rapportDevisInfoX, $rapportDevisInfoY); - $pdf->MultiCell(0, 5, FileExportHelpers::FormatTextForExport("Éffectuées le ".$date_devis)); - $rapportDevisInfoY += 5; - $pdf->SetXY($rapportDevisInfoX, $rapportDevisInfoY); - $addressText = "à ".$defunt->adresse_lieu; - $pdf->MultiCell(0, 5, FileExportHelpers::FormatTextForExport($addressText), 0, 'L'); - $addressLineCount = FileExportHelpers::GetLineCountForATextInAMaxWidth($pdf, $addressText, $availableWidhtForDevisInfo); - $rapportDevisInfoY += 5 * $addressLineCount; - $pdf->SetXY($rapportDevisInfoX, $rapportDevisInfoY); - $pdf->Cell(0, 5, FileExportHelpers::FormatTextForExport("de ".$defunt->heure_debut." à ".$defunt->heure_fin)); - - $pdf->SetY($pdf->GetY() + 10); - $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth() - 15, $pdf->GetY()); - $pdf->SetY($pdf->GetY() + 10); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("ÉTAT DU CORPS")), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Corpulence : ".$defunt->corpulence)), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Rigidité : ".$defunt->rigidite)), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Observations du corps : ".$defunt->observations_corps)), '', 'L'); - - $pdf->SetY($pdf->GetY() + 5); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("ACCÈS")), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Arteriel : ".$defunt->acces)), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Recherche : ".$defunt->acces_recherche)), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("État : ".$defunt->acces_etat)), '', 'L'); - - $pdf->SetY($pdf->GetY() + 5); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("INJECTION")), '', 'L'); - $pdf->SetY($pdf->GetY() + 3); - $col_width = round(($pdf->GetPageWidth() - 30) / 3); - $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth() - 15, $pdf->GetY()); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("")), 'LR', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Quantité (l)")), 'LR', 'C'); - $pdf->SetXY(($col_width * 2) + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Diffusion")), 'LR', 'C'); - $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth() - 15, $pdf->GetY()); // --- - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Pré-injection")), 'LR', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->preinjection_qte)), 'LR', 'C'); - $pdf->SetXY(($col_width * 2) + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->preinjection_diffusion)), 'LR', 'C'); - $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth() - 15, $pdf->GetY()); // --- - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Injection")), 'LR', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->injection_qte)), 'LR', 'C'); - $pdf->SetXY(($col_width * 2) + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->injection_diffusion)), 'LR', 'C'); - $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth() - 15, $pdf->GetY()); // --- - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Co-injection")), 'LR', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->coinjection_qte)), 'LR', 'C'); - $pdf->SetXY(($col_width * 2) + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->coinjection_diffusion)), 'LR', 'C'); - $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth() - 15, $pdf->GetY()); - - $pdf->SetY($pdf->GetY() + 10); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("DRAINAGE")), '', 'L'); - $pdf->SetY($pdf->GetY() + 3); - $col_width = round(($pdf->GetPageWidth() - 30) / 3); - $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth() - 15, $pdf->GetY()); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("")), 'LR', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Quantité (l)")), 'LR', 'C'); - $pdf->SetXY(($col_width * 2) + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("État")), 'LR', 'C'); - $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth() - 15, $pdf->GetY()); // --- - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->drainage)), 'LR', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->drainage_qte)), 'LR', 'C'); - $pdf->SetXY(($col_width * 2) + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->drainage_etat)), 'LR', 'C'); - $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth() - 15, $pdf->GetY()); - - $pdf->SetY(-20); - $pdf->SetFont('ComicSans', '', 8); - $pdf->MultiCell($pdf->GetPageWidth() - 30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->legal_one), '', 'C'); - $pdf->SetFont('ComicSans', '', 8); - $pdf->MultiCell($pdf->GetPageWidth() - 30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->adresse), '', 'C'); - - $pdf->AddPage(); - - $pdf->SetAutoPagebreak(true); - $pdf->SetMargins(15, 15, 15); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("PONCTION")), '', 'L'); - $pdf->SetY($pdf->GetY() + 3); - $col_width = round(($pdf->GetPageWidth() - 30) / 3); - $pdf->Line(15, $pdf->GetY(), ($col_width + 7) * 2, $pdf->GetY()); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("")), 'LR', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Quantité (l)")), 'LR', 'C'); - $pdf->Line(15, $pdf->GetY(), ($col_width + 7) * 2, $pdf->GetY()); // --- - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->ponction)), 'LR', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->ponction_qte)), 'LR', 'C'); - $pdf->Line(15, $pdf->GetY(), ($col_width + 7) * 2, $pdf->GetY()); - - $pdf->SetY($pdf->GetY() + 15); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("CAVITÉ")), '', 'L'); - $pdf->SetY($pdf->GetY() + 3); - $col_width = round(($pdf->GetPageWidth() - 30) / 3); - $pdf->Line(15, $pdf->GetY(), ($col_width + 7) * 2, $pdf->GetY()); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("")), 'LR', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Quantité (l)")), 'LR', 'C'); - $pdf->Line(15, $pdf->GetY(), ($col_width + 7) * 2, $pdf->GetY()); // --- - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->cavite)), 'LR', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->cavite_qte)), 'LR', 'C'); - $pdf->Line(15, $pdf->GetY(), ($col_width + 7) * 2, $pdf->GetY()); - - $pdf->SetY($pdf->GetY() + 10); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("AUTRES TRAITEMENTS")), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Hypodermiques : ")), '', 'L'); - foreach ($hypodermiques as $key => $hypo) { - $pdf->setX($pdf->GetX() + 5); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, "- ".utf8_decode(html_entity_decode($hypo->qte." ".$hypo->designation." sur ".$hypo->endroit)), '', 'L'); - } - - $pdf->SetY($pdf->GetY() + 10); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("HYGIÈNE")), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Désinfection : ".$defunt->desinfection)), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Lavage : ".$defunt->lavage)), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Rasage : ".(($defunt->rasage == 0) ? 'Non' : 'Oui'))), '', 'L'); - - $pdf->SetY($pdf->GetY() + 10); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("PRÉSENTATION")), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Cosmétiques : ".$defunt->presentation_cosmetique)), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Sur : ".$defunt->presentation_sur)), '', 'L'); - - $pdf->SetY($pdf->GetY() + 10); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("TEMPS")), '', 'L'); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Total : ".$this->calculHeureTotal($defunt->heure_debut, $defunt->heure_fin))), '', 'L'); - - $pdf->SetY($pdf->GetY() + 10); - - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("OBSERVATIONS")), '', 'L'); - $pdf->SetY($pdf->GetY() + 3); - $col_width = round(($pdf->GetPageWidth() - 30) / 2); - foreach ($observations as $key => $obs) { - if($pdf->getY() >= ($pdf->GetPageHeight() - 45)) { - $pdf->SetY(-20); - $pdf->SetFont('ComicSans', '', 8); - $pdf->MultiCell($pdf->GetPageWidth() - 30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->legal_one), '', 'C'); - $pdf->SetFont('ComicSans', '', 8); - $pdf->MultiCell($pdf->GetPageWidth() - 30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->adresse), '', 'C'); - $pdf->AddPage(); - } - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($obs->designation)), 'LTRB', 'L'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($obs->commentaire)), 'LTRB', 'L'); - } - - $pdf->setY($pdf->GetY() + 10); - - if($pdf->getY() >= ($pdf->GetPageHeight() - 45)) { - $pdf->SetY(-20); - $pdf->SetFont('ComicSans', '', 8); - $pdf->MultiCell($pdf->GetPageWidth() - 30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->legal_one), '', 'C'); - $pdf->SetFont('ComicSans', '', 8); - $pdf->MultiCell($pdf->GetPageWidth() - 30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->adresse), '', 'C'); - $pdf->AddPage(); - } - - // signature - $pdf->SetFont('ComicSans', '', 11); - $pdf->setY($pdf->GetY() + 10); - $pdf->Cell($pdf->GetPageWidth() - 30, 0, utf8_decode(html_entity_decode($defaultConfig[0]->nom).' '.html_entity_decode($defaultConfig[0]->prenom)), 0, 0, 'L'); - $pdf->setY($pdf->GetY() + 5); - - $signatureExist = $this->signatureImageExists('sign.png'); - if($signatureExist) { - $pdf->Image($this->defaultImagePath."sign.png", 15, $pdf->GetY(), 55, 30); - } - - $pdf->setY($pdf->GetY() - 5); - $pdf->SetFont('ComicSans', '', 11); - $pdf->Cell($pdf->GetPageWidth() - 80, 0, "Pour :", 0, 0, 'R'); - - $pdf->SetY(-20); - $pdf->SetFont('ComicSans', '', 8); - $pdf->MultiCell($pdf->GetPageWidth() - 30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->legal_one), '', 'C'); - $pdf->SetFont('ComicSans', '', 8); - $pdf->MultiCell($pdf->GetPageWidth() - 30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->adresse), '', 'C'); - - $pdf->AddPage(); - $pdf->Image($this->src_path.(($defunt->sexe == 'm' ? 'facehomme.jpg' : 'facefemme.jpg')), 0, 0, $pdf->GetPageWidth(), $pdf->GetPageHeight()); - $pdf->AddPage(); - $pdf->Image($this->src_path.(($defunt->sexe == 'm' ? 'doshomme.jpg' : 'dosfemme.jpg')), 0, 0, $pdf->GetPageWidth(), $pdf->GetPageHeight()); - - $ff_pdf = $folderDestination.'RAPPORT_SOIN_'.strtoupper($nomDefunt).'.pdf'; - $this->storage->newFile($ff_pdf); - $pdfContent = $pdf->Output('', 'S'); - - $file_pdf = $this->storage->get($ff_pdf); - $file_pdf->putContent($pdfContent); - - if($ff_pdf != null && trim($email) != '') { - //send email - $this->sendAttachmentToClientByDefunt($defunt->id, $ff_pdf, $email, "Rapport soins", "Vous trouverez en pièce jointe le rapport de soins de ", true); - } - - $res = array(); - $res['path'] = $folderDestination; - return json_encode($res); - } catch(\OCP\Files\NotFoundException $e) { - return $e; - } - } else { - return false; - } - } - - public function calculHeureTotal($heureDebut, $heureFin) - { - // Extraction des heures et des minutes de l'heure de début - list($heureDebutHeures, $heureDebutMinutes) = explode(':', $heureDebut); - $heureDebutHeures = (int)$heureDebutHeures; - $heureDebutMinutes = (int)$heureDebutMinutes; - - // Extraction des heures et des minutes de l'heure de fin - list($heureFinHeures, $heureFinMinutes) = explode(':', $heureFin); - $heureFinHeures = (int)$heureFinHeures; - $heureFinMinutes = (int)$heureFinMinutes; - - // Calculer la différence en heures et minutes - $diffHeures = $heureFinHeures - $heureDebutHeures; - $diffMinutes = $heureFinMinutes - $heureDebutMinutes; - - // Gérer le cas où la différence des minutes est négative - if ($diffMinutes < 0) { - $diffHeures--; - $diffMinutes += 60; - } - return sprintf("%02dh%02d", $diffHeures, $diffMinutes); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $numdefunt - */ - public function saveRapportBijoux($numdefunt, $withPhotos = false, $email = '') - { - if($withPhotos != null && $withPhotos == 1) { - $withPhotos = true; - } else { - $withPhotos = false; - } - $defaultConfig = json_decode($this->myDb->getConfiguration(self::DEFAULT_NEXTCLOUD_ADMIN)); - $defunt = json_decode($this->myDb->getOneDefunt($numdefunt, $this->idNextcloud))[0]; - $bijoux = json_decode($this->myDb->getListBijoux($numdefunt, $this->idNextcloud)); - try { - $nomDefunt = $defunt->nom_defunt; - $date_temp = new Datetime($defunt->date); - $date_temp = $date_temp->format('d-m-Y'); - $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE); - $today = $formatter->format(DateTime::createFromFormat('d-m-Y', $date_temp)); - - // $folderDestination = html_entity_decode($defaultConfig[0]->path).'/CLIENTS/'.strtoupper($defunt->entreprise).'/DEFUNTS/'.strtoupper($nomDefunt).'/RAPPORTS/'; - $folderDestination = FileExportHelpers::GetDefuntsFolder( - $defunt->nom, - $defunt->nom_defunt, - $defaultConfig[0]->path.'/' - ); - $folderDestination .= 'RAPPORTS/'; - try { - $this->storage->newFolder($folderDestination); - } catch(\OCP\Files\NotPermittedException $e) { - } - - // TODO: init pdf - $pdf = new FPDF(); - $pdf->AddFont('ComicSans', '', 'Comic Sans MS.php'); - $pdf->AddFont('ComicSans', 'B', 'comic-sans-bold.php'); - $pdf->AddPage(); - - // on sup les 2 cm en bas - $pdf->SetAutoPagebreak(true); - - // logo : 80 de largeur et 55 de hauteur - $logo = $this->getLogo(); - if($logo != 'nothing') { - $pdf->Image($this->defaultImagePath."logo.png", 4, 2, 50, 35); - } - $pdf->SetY(45); - $pdf->SetFont('ComicSans', 'B', 15); - $pdf->Cell(0, 10, utf8_decode(html_entity_decode("ATTESTATION BIJOU(X)")), 0, 0, 'C'); - - $pdf->SetMargins(15, 15, 15); - - $pdf->SetY(65); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Je soussignée ".$defunt->prenom_thanato." ".strtoupper($defunt->nom_thanato).", Thanatopracteur, agissant pour le compte de la société ".strtoupper($defaultConfig[0]->entreprise)." titulaire de l'habilitation n° ".$defunt->reference_habilitation." atteste par la présente que : - ".(strcmp($defunt->sexe, 'm') == 0 ? 'Monsieur' : 'Madame').". ".$defunt->nom_defunt." - a été pris(e) en charge par nos services pour des soins mortuaires.")), '', 'J', 0); - - $pdf->setY($pdf->GetY() + 10); - - $hasTaker = false; - foreach ($bijoux as $key => $bijou) { - $currentBijouHasTaker = $bijou->taker_name != null && $bijou->taker_name != "" && $bijou->taker_name != "-"; - if($currentBijouHasTaker) { - $hasTaker = true; - break; - } - } - $columnNumber = $hasTaker ? 3 : 2; - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("À la suite de notre prise en charge, une liste des bijoux appartenant au défunt a été établie comme suit :")), '', 'J', 0); - $pdf->setY($pdf->GetY() + 5); - $col_width = round(($pdf->GetPageWidth() - 30) / $columnNumber); - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Désignation")), 'LTRB', 'C'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Commentaire")), 'LTRB', 'C'); - if($hasTaker) { - $pdf->SetXY($col_width + 75, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', 'B', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Prise en charge des bijoux par")), 'LTRB', 'C'); - } - foreach ($bijoux as $key => $bijou) { - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($bijou->designation)), 'LTRB', 'L'); - $pdf->SetXY($col_width + 15, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($bijou->commentaire)), 'LTRB', 'L'); - if($hasTaker) { - $pdf->SetXY($col_width + 75, $pdf->GetY() - 8); - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($bijou->taker_name)), 'LTRB', 'L'); - } - } - $photosCount = 0; - if($withPhotos) { - $photosCountLimitToGoToNewLine = 3; - $currentUserFolder = "/var/www/html/data/".BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD."/files/"; - $clientName = $defunt->nom; - if($clientName != null) { - $bijouxPhotosFolder = FileExportHelpers::GetBijouxOfDefuntFolder($clientName, $defunt->nom_defunt, $defaultConfig[0]->path); - $pdf->setXY($pdf->GetX(), $pdf->GetY() + 5); - $pdf->Cell(0, 5, "Photos :", 0, 1); - $pdf->setXY($pdf->GetX(), $pdf->GetY() + 5); - foreach ($bijoux as $key => $bijou) { - if($bijou->photo == null) { - continue; - } - try { - $fullPhotoPath = $currentUserFolder.$bijouxPhotosFolder.$bijou->photo; - $pdf->Image($fullPhotoPath, $pdf->GetX(), $pdf->GetY(), 50, 30); - $pdf->SetXY($pdf->GetX() + 60, $pdf->GetY()); - $photosCount++; - if($photosCount == $photosCountLimitToGoToNewLine) { - $pdf->SetY($pdf->GetY() + 35); - } - } catch(Exception) { - - } - } - } - if($photosCount > 0) { - $pdf->SetY($pdf->GetY() + 30); - } - } - - $pdf->setY($pdf->GetY() + 10); - - $pdf->SetFont('ComicSans', '', 10); - $pdf->MultiCell(0, 5, FileExportHelpers::FormatTextForExport("Cette attestation est remise pour faire valoir ce que de droit. - Fait à ".$defaultConfig[0]->adresse.", le ".$today), '', 'J', 0); - - $pdf->setY($pdf->GetY() + 10); - - // signature - $pdf->SetFont('ComicSans', '', 11); - $pdf->Cell($pdf->GetPageWidth() - 30, 0, utf8_decode(html_entity_decode($defaultConfig[0]->nom).' '.html_entity_decode($defaultConfig[0]->prenom)), 0, 0, 'L'); - $pdf->setY($pdf->GetY() + 5); - - $signatureExist = $this->signatureImageExists('sign.png'); - if ($signatureExist) { - $pdf->Image($this->defaultImagePath."sign.png", 5, $pdf->GetY(), 60, 40); - } - - $pdf->setY($pdf->GetY() - 5); - $pdf->SetFont('ComicSans', '', 11); - $pdf->Cell($pdf->GetPageWidth() - 80, 0, "Pour :", 0, 0, 'R'); - - $pdf->SetY(-15); - $pdf->SetFont('ComicSans', '', 8); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode($defaultConfig[0]->legal_one)), 0, 'C'); - $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode($defaultConfig[0]->adresse)), 0, 'C'); - - $ff_pdf = $folderDestination.'RAPPORT_BIJOUX_'.strtoupper($nomDefunt).'.pdf'; - $this->storage->newFile($ff_pdf); - $pdfContent = $pdf->Output('', 'S'); - - $file_pdf = $this->storage->get($ff_pdf); - $file_pdf->putContent($pdfContent); - - if($ff_pdf != null && trim($email) != '') { - //send email - $this->sendAttachmentToClientByDefunt($defunt->id, $ff_pdf, $email, "Rapport des bijoux", "Vous trouverez en pièce jointe le rapport des bijoux de ", true); - } - - $res = array(); - $res['path'] = $folderDestination; - return json_encode($res); - } catch(\OCP\Files\NotFoundException $e) { - return $e; - } - } - - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param array $thanatoIdsToExport - * @param string $month - * @param string $year - * - */ - - public function exportThanatoStatistic($thanatoIdsToExport, $month, $year) - { - if(empty($thanatoIdsToExport)) { - return ""; - } - $month = $month ?? date('m'); - $year = $year ?? date('Y'); - try { - $filenames = $this->exportThanatoStatisticService->exportThanatosListStatistic($thanatoIdsToExport, $month, $year, $this->idNextcloud); - return $filenames; - } catch(\OCP\Files\NotFoundException $e) { - } - - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param array $clientIdsToExport - * - */ - - public function exportClientStatistic($clientIdsToExport) - { - if(empty($clientIdsToExport)) { - return ""; - } - $exportData = $this->myDb->getExportClientStatData($clientIdsToExport); - try { - $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); - $clean_folder = html_entity_decode($current_config[0]->path).'/'; - $_clean_folder = $clean_folder.'STATISTIQUES/CLIENTS/'; - try { - $this->storage->newFolder($_clean_folder); - } catch(\OCP\Files\NotPermittedException $e) { - - } - $fileHeader = $this->exportClientStatisticService->getExportClientFileHeader(); - $fileContent = $this->exportClientStatisticService->populateExportDataIntoFileContent($exportData, $fileHeader); - $fileName = $this->exportClientStatisticService->getFileName($clientIdsToExport); - $fileNamePath = $_clean_folder."STAT-CLIENTS-" . $fileName .'.csv'; - $this->storage->newFile($fileNamePath); - $file = $this->storage->get($fileNamePath); - $file->putContent($fileContent); - return $fileNamePath; - } catch(\OCP\Files\NotFoundException $e) { - } - - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param int $factureId - * - */ - - public function exportFactureToPdf($factureId) - { - try { - $factureGeneratedResponse = $this->invoicePdfService->generateFacturePdfByFactureId($factureId, $this->idNextcloud); - return json_encode($factureGeneratedResponse["filenames"]); - } catch(\OCP\Files\NotFoundException $e) { - } - - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $filter - * @param string $month - * @param string $year - * @param string $filterType // client|group - * - */ - - public function exportFactureByClientAndMonthYearToPdf($filter, $month, $year, $filterType = "client") - { - try { - $factureFilename = $this->invoicePdfService->generateMultipleInvoicePdfByClientAndMonthYear( - filter: $filter, - month: $month, - year: $year, - idNextCloud: $this->idNextcloud, - filterType: $filterType - ); - return $factureFilename; - } catch(\OCP\Files\NotFoundException $e) { - } - - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - - public function addDevisNumberColumn() - { - try { - $this->myDb->addNumberColumnOnDevis(); - return true; - } catch(\OCP\Files\NotFoundException $e) { - } - - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - - public function addFactureNumberColumn() - { - try { - $this->myDb->addNumberColumnOnFacture(); - return true; - } catch(\OCP\Files\NotFoundException $e) { - } - - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getClientGroupDiscounts() - { - return $this->myDb->getClientGroupDiscounts(); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function clientGroupDiscount() - { + private function calculAge($dateNaissance) { + + // Convertir la date de naissance en objet DateTime + $dateNaissance = new DateTime($dateNaissance); + // Obtenir la date actuelle + $dateActuelle = new DateTime(); + // Calculer la différence entre les deux dates + $difference = $dateActuelle->diff($dateNaissance); + // Renvoyer l'âge + return $difference->y; + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numdefunt + */ + public function saveRapportSoin($numdefunt, $email = ''){ + + $defaultConfig = json_decode($this->myDb->getConfiguration(BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD)); + $defunt = json_decode($this->myDb->getOneDefunt($numdefunt, $this->idNextcloud))[0]; + $observations = json_decode($this->myDb->getListObservations($numdefunt, $this->idNextcloud)); + $hypodermiques = json_decode($this->myDb->getListHypodermiques($numdefunt, $this->idNextcloud)); + + // print_r(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $current_config[0]->legal_one)); + + if($defunt->id_devis != NULL) { + try { + $numFacture = ($defunt->numero_facture==NULL)?'-':$defunt->numero_facture; + $nomDefunt = $defunt->nom_defunt; + $age = $this->calculAge($defunt->date_naissance); + + $date_devis_temp = date("d-m-Y", strtotime($defunt->date)); + $date_temp = date("d-m-Y", strtotime(date('Y-m-d'))); + + $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE); + $date_devis = $formatter->format(DateTime::createFromFormat('d-m-Y', $date_devis_temp)); + $today = $formatter->format(DateTime::createFromFormat('d-m-Y', $date_temp)); + + $folderDestination = FileExportHelpers::GetDefuntsFolder( + $defunt->nom, + $defunt->nom_defunt, + $defaultConfig[0]->path.'/' + ); + $folderDestination .= 'RAPPORTS/'; + try { + $this->storage->newFolder($folderDestination); + } catch(\OCP\Files\NotPermittedException $e) { } + + + // TODO: init pdf + $pdf = new FPDF(); + // $pdf->AddFont('Arial','','Comic Sans MS.php'); + // $pdf->AddFont('Arial','B','comic-sans-bold.php'); + $pdf->AddPage(); + + $pdf->SetAutoPagebreak(False); + $pdf->SetMargins(15,15,15); + + // logo : 80 de largeur et 55 de hauteur + $logo = $this->getLogo(); + if($logo != 'nothing'){ + $pdf->Image($this->defaultImagePath."logo.png", 4, 2, 50, 35); + } + $pdf->setXY(15, 15); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("N : ".$numFacture)), '', 'R'); + + + + $pdf->setXY(15, 55); $pdf->SetFont('Arial', 'B', 15); $pdf->Cell(80, 10, 'RAPPORT DE SOIN', 1, 1, 'C'); + + + + $pdf->SetY(68); + $pdf->SetFont('Arial', '', 10); + $pdf->MultiCell(0, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->adresse.", le ".$today), '', 'R'); + + $rapportInfoHeaderY = $pdf->GetY() + 15; + $rapportDefuntInfoY = $rapportInfoHeaderY; + $rapportDevisInfoY = $rapportInfoHeaderY; + $pdf->SetY(y: $rapportDefuntInfoY); + $pdf->SetFont('Arial', '', 10); + $pdf->Cell(0,5,FileExportHelpers::FormatTextForExport($nomDefunt)); + $rapportDefuntInfoY += 5; + $pdf->SetY($rapportDefuntInfoY); + $pdf->Cell(0,5,FileExportHelpers::FormatTextForExport($age. " ans")); + $rapportDefuntInfoY += 5; + $pdf->SetY($rapportDefuntInfoY); + $sexeText = strcmp($defunt->sexe, 'm')==0 ? 'Masculin' : 'Féminin'; + $pdf->Cell(0,5,FileExportHelpers::FormatTextForExport($sexeText)); + + //devis info + $rapportDevisInfoX = 115; + $maxWidth = $pdf->GetPageWidth(); + $availableWidhtForDevisInfo = $maxWidth - 10 - $rapportDevisInfoX; + $pdf->SetXY($rapportDevisInfoX,$rapportDevisInfoY); + $pdf->MultiCell(0,5,FileExportHelpers::FormatTextForExport("Éffectuées le ".$date_devis)); + $rapportDevisInfoY += 5; + $pdf->SetXY($rapportDevisInfoX,$rapportDevisInfoY); + $addressText = "à ".$defunt->adresse_lieu; + $pdf->MultiCell(0,5,FileExportHelpers::FormatTextForExport($addressText),0,'L'); + $addressLineCount = FileExportHelpers::GetLineCountForATextInAMaxWidth($pdf,$addressText,$availableWidhtForDevisInfo); + $rapportDevisInfoY += 5 * $addressLineCount; + $pdf->SetXY($rapportDevisInfoX,$rapportDevisInfoY); + $pdf->Cell(0,5,FileExportHelpers::FormatTextForExport("de ".$defunt->heure_debut." à ".$defunt->heure_fin)); + + $pdf->SetY($pdf->GetY()+10); + $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth()-15, $pdf->GetY()); + $pdf->SetY($pdf->GetY()+10); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("ÉTAT DU CORPS")), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Corpulence : ".$defunt->corpulence)), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Rigidité : ".$defunt->rigidite)), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Observations du corps : ".$defunt->observations_corps)), '', 'L'); + + + + + + $pdf->SetY($pdf->GetY()+5); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("ACCÈS")), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Arteriel : ".$defunt->acces)), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Recherche : ".$defunt->acces_recherche)), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("État : ".$defunt->acces_etat)), '', 'L'); + + + + + + $pdf->SetY($pdf->GetY()+5); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("INJECTION")), '', 'L'); + + $pdf->SetY($pdf->GetY()+3); + $col_width = round(($pdf->GetPageWidth()-30)/3); + $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth()-15, $pdf->GetY()); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("")), 'LR', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Quantité (l)")), 'LR', 'C'); + $pdf->SetXY(($col_width*2)+15, $pdf->GetY()-8); $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Diffusion")), 'LR', 'C'); + + + + + + $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth()-15, $pdf->GetY()); // --- + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Pré-injection")), 'LR', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->preinjection_qte)), 'LR', 'C'); + $pdf->SetXY(($col_width*2)+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->preinjection_diffusion)), 'LR', 'C'); + + + + + + $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth()-15, $pdf->GetY()); // --- + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Injection")), 'LR', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->injection_qte)), 'LR', 'C'); + $pdf->SetXY(($col_width*2)+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->injection_diffusion)), 'LR', 'C'); + + + + + + $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth()-15, $pdf->GetY()); // --- + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Co-injection")), 'LR', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->coinjection_qte)), 'LR', 'C'); + $pdf->SetXY(($col_width*2)+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->coinjection_diffusion)), 'LR', 'C'); + + + + + + $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth()-15, $pdf->GetY()); + + $pdf->SetY($pdf->GetY()+10); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("DRAINAGE")), '', 'L'); + + $pdf->SetY($pdf->GetY()+3); + $col_width = round(($pdf->GetPageWidth()-30)/3); + $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth()-15, $pdf->GetY()); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("")), 'LR', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Quantité (l)")), 'LR', 'C'); + $pdf->SetXY(($col_width*2)+15, $pdf->GetY()-8); $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("État")), 'LR', 'C'); + + + + + + $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth()-15, $pdf->GetY()); // --- + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->drainage)), 'LR', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->drainage_qte)), 'LR', 'C'); + $pdf->SetXY(($col_width*2)+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->drainage_etat)), 'LR', 'C'); + + + + + + $pdf->Line(15, $pdf->GetY(), $pdf->GetPageWidth()-15, $pdf->GetY()); + + $pdf->SetY(-20); $pdf->SetFont('Arial', '', 8); $pdf->MultiCell($pdf->GetPageWidth()-30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->legal_one), '', 'C'); + $pdf->SetFont('Arial', '', 8); $pdf->MultiCell($pdf->GetPageWidth()-30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->adresse), '', 'C'); + + + + + $pdf->AddPage(); + + $pdf->SetAutoPagebreak(True); + $pdf->SetMargins(15,15,15); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("PONCTION")), '', 'L'); + + $pdf->SetY($pdf->GetY()+3); + $col_width = round(($pdf->GetPageWidth()-30)/3); + $pdf->Line(15, $pdf->GetY(), ($col_width+7)*2, $pdf->GetY()); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("")), 'LR', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Quantité (l)")), 'LR', 'C'); + + + + $pdf->Line(15, $pdf->GetY(), ($col_width+7)*2, $pdf->GetY()); // --- + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->ponction)), 'LR', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->ponction_qte)), 'LR', 'C'); + + + + $pdf->Line(15, $pdf->GetY(), ($col_width+7)*2, $pdf->GetY()); + + $pdf->SetY($pdf->GetY()+15); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("CAVITÉ")), '', 'L'); + + $pdf->SetY($pdf->GetY()+3); + $col_width = round(($pdf->GetPageWidth()-30)/3); + $pdf->Line(15, $pdf->GetY(), ($col_width+7)*2, $pdf->GetY()); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("")), 'LR', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Quantité (l)")), 'LR', 'C'); + + + + $pdf->Line(15, $pdf->GetY(), ($col_width+7)*2, $pdf->GetY()); // --- + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->cavite)), 'LR', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($defunt->cavite_qte)), 'LR', 'C'); + + + + $pdf->Line(15, $pdf->GetY(), ($col_width+7)*2, $pdf->GetY()); + + $pdf->SetY($pdf->GetY()+10); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("AUTRES TRAITEMENTS")), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Hypodermiques : ")), '', 'L'); + + + foreach ($hypodermiques as $key => $hypo) { + $pdf->setX($pdf->GetX()+5); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, "- ".utf8_decode(html_entity_decode($hypo->qte." ".$hypo->designation." sur ".$hypo->endroit)), '', 'L'); + + } + + $pdf->SetY($pdf->GetY()+10); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("HYGIÈNE")), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Désinfection : ".$defunt->desinfection)), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Lavage : ".$defunt->lavage)), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Rasage : ".(($defunt->rasage==0)?'Non':'Oui'))), '', 'L'); + + + + + + $pdf->SetY($pdf->GetY()+10); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("PRÉSENTATION")), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Cosmétiques : ".$defunt->presentation_cosmetique)), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Sur : ".$defunt->presentation_sur)), '', 'L'); + + + + + $pdf->SetY($pdf->GetY()+10); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("TEMPS")), '', 'L'); + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Total : ".$this->calculHeureTotal($defunt->heure_debut, $defunt->heure_fin))), '', 'L'); + + + + $pdf->SetY($pdf->GetY()+10); + + $pdf->SetFont('Arial', 'B', 10); $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("OBSERVATIONS")), '', 'L'); + + $pdf->SetY($pdf->GetY()+3); + $col_width = round(($pdf->GetPageWidth()-30)/2); + foreach ($observations as $key => $obs) { + if($pdf->getY()>=($pdf->GetPageHeight()-45)) { + $pdf->SetY(-20); $pdf->SetFont('Arial', '', 8); $pdf->MultiCell($pdf->GetPageWidth()-30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->legal_one), '', 'C'); + $pdf->SetFont('Arial', '', 8); $pdf->MultiCell($pdf->GetPageWidth()-30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->adresse), '', 'C'); + + + + $pdf->AddPage(); + } + $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($obs->designation)), 'LTRB', 'L'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($obs->commentaire)), 'LTRB', 'L'); + + + + } + + $pdf->setY($pdf->GetY()+10); + + if($pdf->getY()>=($pdf->GetPageHeight()-45)) { + $pdf->SetY(-20); $pdf->SetFont('Arial', '', 8); $pdf->MultiCell($pdf->GetPageWidth()-30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->legal_one), '', 'C'); + $pdf->SetFont('Arial', '', 8); $pdf->MultiCell($pdf->GetPageWidth()-30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->adresse), '', 'C'); + + + + $pdf->AddPage(); + } + + // signature + $pdf->SetFont('Arial','',11); + $pdf->setY($pdf->GetY()+10); + $pdf->Cell( $pdf->GetPageWidth()-30, 0, utf8_decode(html_entity_decode($defaultConfig[0]->nom).' '.html_entity_decode($defaultConfig[0]->prenom)), 0, 0, 'L'); + $pdf->setY($pdf->GetY()+5); + + $signatureExist = $this->signatureImageExists('sign.png'); + if($signatureExist){ + $pdf->Image($this->defaultImagePath."sign.png", 15, $pdf->GetY(), 55, 30); + } + + $pdf->setY($pdf->GetY()-5); + $pdf->SetFont('Arial','',11); $pdf->Cell( $pdf->GetPageWidth()-80, 0, "Pour :", 0, 0, 'R'); + + + $pdf->SetY(-20); $pdf->SetFont('Arial', '', 8); $pdf->MultiCell($pdf->GetPageWidth()-30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->legal_one), '', 'C'); + $pdf->SetFont('Arial', '', 8); $pdf->MultiCell($pdf->GetPageWidth()-30, 5, FileExportHelpers::FormatTextForExport($defaultConfig[0]->adresse), '', 'C'); + + + + + $pdf->AddPage(); + $pdf->Image($this->src_path.(($defunt->sexe=='m'?'facehomme.jpg':'facefemme.jpg')), 0, 0, $pdf->GetPageWidth(), $pdf->GetPageHeight()); + $pdf->AddPage(); + $pdf->Image($this->src_path.(($defunt->sexe=='m'?'doshomme.jpg':'dosfemme.jpg')), 0, 0, $pdf->GetPageWidth(), $pdf->GetPageHeight()); + + $ff_pdf = $folderDestination.'RAPPORT_SOIN_'.strtoupper($nomDefunt).'.pdf'; + $this->storage->newFile($ff_pdf); + $pdfContent = $pdf->Output('','S'); + + $file_pdf = $this->storage->get($ff_pdf); + $file_pdf->putContent($pdfContent); + + if($ff_pdf != null && trim($email) != ''){ + //send email + $this->sendAttachmentToClientByDefunt($defunt->id, $ff_pdf, $email,"Rapport soins", "Vous trouverez en pièce jointe le rapport de soins de " , true); + } + + $res = array(); + $res['path'] = $folderDestination; + return json_encode($res); + } catch(\OCP\Files\NotFoundException $e) { + return $e; + } + } else { + return false; + } + } + + function calculHeureTotal($heureDebut, $heureFin) { + + // Extraction des heures et des minutes de l'heure de début + list($heureDebutHeures, $heureDebutMinutes) = explode(':', $heureDebut); + $heureDebutHeures = (int)$heureDebutHeures; + $heureDebutMinutes = (int)$heureDebutMinutes; + + // Extraction des heures et des minutes de l'heure de fin + list($heureFinHeures, $heureFinMinutes) = explode(':', $heureFin); + $heureFinHeures = (int)$heureFinHeures; + $heureFinMinutes = (int)$heureFinMinutes; + + // Calculer la différence en heures et minutes + $diffHeures = $heureFinHeures - $heureDebutHeures; + $diffMinutes = $heureFinMinutes - $heureDebutMinutes; + + // Gérer le cas où la différence des minutes est négative + if ($diffMinutes < 0) { + $diffHeures--; + $diffMinutes += 60; + } + return sprintf("%02dh%02d", $diffHeures, $diffMinutes); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $numdefunt + */ + public function saveRapportBijoux($numdefunt,$withPhotos = false, $email = ''){ + + if($withPhotos != null && $withPhotos == 1){ + $withPhotos = true; + } + else{ + $withPhotos = false; + } + $defaultConfig = json_decode($this->myDb->getConfiguration(self::DEFAULT_NEXTCLOUD_ADMIN)); + $defunt = json_decode($this->myDb->getOneDefunt($numdefunt, $this->idNextcloud))[0]; + $bijoux = json_decode($this->myDb->getListBijoux($numdefunt, $this->idNextcloud)); + try { + $nomDefunt = $defunt->nom_defunt; + $date_temp = new Datetime($defunt->date); + $date_temp = $date_temp->format('d-m-Y'); + $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE); + $today = $formatter->format(DateTime::createFromFormat('d-m-Y', $date_temp)); + + // $folderDestination = html_entity_decode($defaultConfig[0]->path).'/CLIENTS/'.strtoupper($defunt->entreprise).'/DEFUNTS/'.strtoupper($nomDefunt).'/RAPPORTS/'; + $folderDestination = FileExportHelpers::GetDefuntsFolder( + $defunt->nom, + $defunt->nom_defunt, + $defaultConfig[0]->path.'/' + ); + $folderDestination .= 'RAPPORTS/'; + try { + $this->storage->newFolder($folderDestination); + } catch(\OCP\Files\NotPermittedException $e) { } + + + // TODO: init pdf + $pdf = new FPDF(); + // $pdf->AddFont('Arial','','Comic Sans MS.php'); + // $pdf->AddFont('Arial','B','comic-sans-bold.php'); + $pdf->AddPage(); + + // on sup les 2 cm en bas + $pdf->SetAutoPagebreak(True); + + // logo : 80 de largeur et 55 de hauteur + $logo = $this->getLogo(); + if($logo != 'nothing'){ + $pdf->Image($this->defaultImagePath."logo.png", 4, 2, 50, 35); + } + $pdf->SetY(45); $pdf->SetFont('Arial', 'B', 15); $pdf->Cell(0, 10, utf8_decode(html_entity_decode("ATTESTATION BIJOU(X)")), 0, 0, 'C'); + + + + $pdf->SetMargins(15,15,15); + + $pdf->SetY(65); $pdf->SetFont('Arial', '', 10); + + $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("Je soussignée ".$defunt->prenom_thanato." ".strtoupper($defunt->nom_thanato).", Thanatopracteur, agissant pour le compte de la société ".strtoupper($defaultConfig[0]->entreprise)." titulaire de l'habilitation n° ".$defunt->reference_habilitation." atteste par la présente que : + ".(strcmp($defunt->sexe, 'm')==0 ? 'Monsieur' : 'Madame').". ".$defunt->nom_defunt." + a été pris(e) en charge par nos services pour des soins mortuaires.")), '','J',0); + + $pdf->setY($pdf->GetY()+10); + + $hasTaker = false; + foreach ($bijoux as $key => $bijou) { + $currentBijouHasTaker = $bijou->taker_name != null && $bijou->taker_name != "" && $bijou->taker_name != "-"; + if($currentBijouHasTaker){ + $hasTaker = true; + break; + } + } + $columnNumber = $hasTaker ? 3 : 2; + $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode("À la suite de notre prise en charge, une liste des bijoux appartenant au défunt a été établie comme suit :")), '','J',0); + $pdf->setY($pdf->GetY()+5); + $col_width = round(($pdf->GetPageWidth()-30)/$columnNumber); + $pdf->SetFont('Arial', 'B', 10); + $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Désignation")), 'LTRB', 'C'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); + $pdf->SetFont('Arial', 'B', 10); + $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Commentaire")), 'LTRB', 'C'); + if($hasTaker){ + $pdf->SetXY($col_width+75, $pdf->GetY()-8); + $pdf->SetFont('Arial', 'B', 10); + $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode("Prise en charge des bijoux par")), 'LTRB', 'C'); + } + foreach ($bijoux as $key => $bijou) { + $pdf->SetFont('Arial', '', 10); + $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($bijou->designation)), 'LTRB', 'L'); + $pdf->SetXY($col_width+15, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); + + $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($bijou->commentaire)), 'LTRB', 'L'); + if($hasTaker){ + $pdf->SetXY($col_width+75, $pdf->GetY()-8); $pdf->SetFont('Arial', '', 10); + + $pdf->MultiCell($col_width, 8, utf8_decode(html_entity_decode($bijou->taker_name)), 'LTRB', 'L'); + } + } + $photosCount = 0; + if($withPhotos){ + $photosCountLimitToGoToNewLine = 3; + $currentUserFolder = "/var/www/html/data/".BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD."/files/"; + $clientName = $defunt->nom; + if($clientName != null){ + $bijouxPhotosFolder = FileExportHelpers::GetBijouxOfDefuntFolder($clientName,$defunt->nom_defunt,$defaultConfig[0]->path); + $pdf->setXY($pdf->GetX(),$pdf->GetY()+5); + $pdf->Cell(0,5,"Photos :",0,1); + $pdf->setXY($pdf->GetX(),$pdf->GetY()+5); + foreach ($bijoux as $key => $bijou) { + if($bijou->photo == null){ + continue; + } + try{ + $fullPhotoPath = $currentUserFolder.$bijouxPhotosFolder.$bijou->photo; + $pdf->Image($fullPhotoPath,$pdf->GetX(),$pdf->GetY(),50,30); + $pdf->SetXY($pdf->GetX() + 60,$pdf->GetY()); + $photosCount++; + if($photosCount == $photosCountLimitToGoToNewLine){ + $pdf->SetY($pdf->GetY() + 35); + } + } + catch(Exception){ + + } + } + } + if($photosCount > 0){ + $pdf->SetY($pdf->GetY()+30); + } + } + + $pdf->setY($pdf->GetY()+10); + + $pdf->SetFont('Arial', '', 10); + $pdf->MultiCell(0, 5, FileExportHelpers::FormatTextForExport("Cette attestation est remise pour faire valoir ce que de droit. + Fait à ".$defaultConfig[0]->adresse.", le ".$today), '','J',0); + + $pdf->setY($pdf->GetY()+10); + + // signature + $pdf->SetFont('Arial','',11); + $pdf->Cell( $pdf->GetPageWidth()-30, 0, utf8_decode(html_entity_decode($defaultConfig[0]->nom).' '.html_entity_decode($defaultConfig[0]->prenom)), 0, 0, 'L'); + $pdf->setY($pdf->GetY()+5); + + $signatureExist = $this->signatureImageExists('sign.png'); + if ($signatureExist) { + $pdf->Image($this->defaultImagePath."sign.png", 5, $pdf->GetY(), 60, 40); + } + + $pdf->setY($pdf->GetY()-5); + $pdf->SetFont('Arial','',11); $pdf->Cell( $pdf->GetPageWidth()-80, 0, "Pour :", 0, 0, 'R'); + + + $pdf->SetY(-15); $pdf->SetFont('Arial', '', 8); + + $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode($defaultConfig[0]->legal_one)), 0, 'C'); + $pdf->MultiCell(0, 5, utf8_decode(html_entity_decode($defaultConfig[0]->adresse)), 0,'C'); + + $ff_pdf = $folderDestination.'RAPPORT_BIJOUX_'.strtoupper($nomDefunt).'.pdf'; + $this->storage->newFile($ff_pdf); + $pdfContent = $pdf->Output('','S'); + + $file_pdf = $this->storage->get($ff_pdf); + $file_pdf->putContent($pdfContent); + + if($ff_pdf != null && trim($email) != ''){ + //send email + $this->sendAttachmentToClientByDefunt($defunt->id, $ff_pdf, $email,"Rapport des bijoux", "Vous trouverez en pièce jointe le rapport des bijoux de " , true); + } + + $res = array(); + $res['path'] = $folderDestination; + return json_encode($res); + } catch(\OCP\Files\NotFoundException $e) { + return $e; + } + } + + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param array $thanatoIdsToExport + * @param string $month + * @param string $year + * + */ + + public function exportThanatoStatistic($thanatoIdsToExport,$month,$year){ + + if(empty($thanatoIdsToExport)){ + return ""; + } + $month = $month ?? date('m'); + $year = $year ?? date('Y'); + try{ + $filenames = $this->exportThanatoStatisticService->exportThanatosListStatistic($thanatoIdsToExport,$month,$year,$this->idNextcloud); + return $filenames; + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param array $clientIdsToExport + * + */ + + public function exportClientStatistic($clientIdsToExport){ + + if(empty($clientIdsToExport)){ + return ""; + } + $exportData = $this->myDb->getExportClientStatData($clientIdsToExport); + try{ + $current_config = json_decode($this->myDb->getConfiguration($this->idNextcloud)); + $clean_folder = html_entity_decode($current_config[0]->path).'/'; + $_clean_folder = $clean_folder.'STATISTIQUES/CLIENTS/'; + try { + $this->storage->newFolder($_clean_folder); + } + catch(\OCP\Files\NotPermittedException $e) { + + } + $fileHeader = $this->exportClientStatisticService->getExportClientFileHeader(); + $fileContent = $this->exportClientStatisticService->populateExportDataIntoFileContent($exportData,$fileHeader); + $fileName = $this->exportClientStatisticService->getFileName($clientIdsToExport); + $fileNamePath = $_clean_folder."STAT-CLIENTS-" . $fileName .'.csv'; + $this->storage->newFile($fileNamePath); + $file = $this->storage->get($fileNamePath); + $file->putContent($fileContent); + return $fileNamePath; + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param int $factureId + * + */ + + public function exportFactureToPdf($factureId){ + + try{ + $factureGeneratedResponse = $this->invoicePdfService->generateFacturePdfByFactureId($factureId,$this->idNextcloud); + return json_encode($factureGeneratedResponse["filenames"]); + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $filter + * @param string $month + * @param string $year + * @param string $filterType // client|group + * + */ + + public function exportFactureByClientAndMonthYearToPdf($filter,$month,$year,$filterType="client"){ + + try{ + $factureFilename = $this->invoicePdfService->generateMultipleInvoicePdfByClientAndMonthYear( + filter: $filter, + month: $month, + year: $year, + idNextCloud: $this->idNextcloud, + filterType: $filterType); + + return $factureFilename; + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + + public function addDevisNumberColumn(){ + + try{ + $this->myDb->addNumberColumnOnDevis(); + return true; + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + + public function addFactureNumberColumn(){ + + try{ + $this->myDb->addNumberColumnOnFacture(); + return true; + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getClientGroupDiscounts() { + + return $this->myDb->getClientGroupDiscounts(); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function clientGroupDiscount() { + return new TemplateResponse('gestion', 'clientGroupDiscount', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/thanatopracteur.php } - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function clientGroups() - { - return new TemplateResponse('gestion', 'clientGroup', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/thanatopracteur.php - } + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function clientGroups() { - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getClientGroups() - { - return $this->myDb->getClientGroups(); - } + return new TemplateResponse('gestion', 'clientGroup', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); // templates/thanatopracteur.php + } - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function createDefaultClientGroup() - { - return $this->myDb->createDefaultClientGroup(); - } + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getClientGroups() { - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function createDefaultClientGroupDiscount() - { - return $this->myDb->createDefaultClientGroupDiscount(); - } + return $this->myDb->getClientGroups(); + } - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function createDefaultClientGroup(){ - public function addClientGroupDiscountFeatureTables() - { - try { - $this->myDb->addClientGroupDiscountFeatureTables(); - return true; - } catch(\OCP\Files\NotFoundException $e) { - } + return $this->myDb->createDefaultClientGroup(); + } - } + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function createDefaultClientGroupDiscount(){ - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param int $defuntId - */ + return $this->myDb->createDefaultClientGroupDiscount(); + } - public function exportCareCertificate($defuntId, $email = '') - { - try { - $careCertificateFilename = $this->certificateService->generateCareCertificate($defuntId, $this->idNextcloud); - if($careCertificateFilename != null && trim($email) != '') { - //send email - $this->sendAttachmentToClientByDefunt($defuntId, $careCertificateFilename, $email, "Attestation de soins", " Vous trouverez en pièce jointe l'attestation de soins ", true); + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + + public function addClientGroupDiscountFeatureTables(){ + + try{ + $this->myDb->addClientGroupDiscountFeatureTables(); + return true; + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param int $defuntId + */ + + public function exportCareCertificate($defuntId, $email = ''){ + + try{ + $careCertificateFilename = $this->certificateService->generateCareCertificate($defuntId,$this->idNextcloud); + if($careCertificateFilename != null && trim($email) != '' ){ + //send email + $this->sendAttachmentToClientByDefunt($defuntId, $careCertificateFilename, $email,"Attestation de soins", " Vous trouverez en pièce jointe l'attestation de soins ", true); + } + return $careCertificateFilename; + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param int $defuntId + * @param int $productId + */ + + public function setDefuntCover($defuntId,$productId){ + + try{ + $response = $this->myDb->setDefuntCover($defuntId,$productId); + return $response; + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + + public function getUserConnectedGroups(){ + + try{ + return json_encode($this->groups); + + } + catch(\OCP\Files\NotFoundException $e) { } + } + + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + + public function testTalk(){ + + try{ + $message = $this->myDb->getDevisTalkRoomMessage(1,$this->idNextcloud); + // $message ="FROM API"; + $this->talkService->sendDevisTalkNotifications($message,$this->idNextcloud); + return true; + + } + catch(\OCP\Files\NotFoundException $e) { } + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + + public function getCoverProducts(){ + + try{ + $coverProducts = $this->myDb->getCoverProducts(); + return $coverProducts; + + } + catch(\OCP\Files\NotFoundException $e) { } + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param int $devisId + * + */ + + public function exportDevisToPdf($devisId){ + + try{ + $devisFilenames = $this->devisPdfService->generateDevisPdfByDevisId($devisId,$this->idNextcloud); + return json_encode($devisFilenames); + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param string $clientId + * @param string $month + * @param string $year + * + */ + + public function exportDevisByClientAndMonthYearToPdf($clientId,$month,$year,$type=DevisExportTypeConstant::TYPE_SINGLE){ + + try{ + $devisFilename = $this->devisPdfService->generateMultipleDevisPdfByClientAndMonthYear($clientId,$month,$year,$type,$this->idNextcloud); + return $devisFilename; + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + + public function addClientGroupFacturationFeatureTables(){ + + try{ + $this->myDb->addClientGroupFacturationFeatureTables(); + return true; + + } + catch(\OCP\Files\NotFoundException $e) { } + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function clientGroupFacturation() { + + return new TemplateResponse('gestion', 'clientGroupFacturation', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getClientGroupFacturations() { + + return $this->myDb->getClientGroupFacturations(); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function createDefaultClientGroupFacturation(){ + + return $this->myDb->createDefaultGroupFacturation(); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @param int $defuntId + */ + + public function saveAttestationPacemaker($defuntId, $email = ''){ + + try{ + $careCertificateFilename = $this->certificateService->generatePacemakerCertificate($defuntId,$this->idNextcloud); + if($careCertificateFilename != null && trim($email) != ''){ + //send email + $this->sendAttachmentToClientByDefunt($defuntId, $careCertificateFilename, $email,"Retrait de pile", "Vous trouverez en pièce jointe l'attestation de retrait de pile ", true); + + } + return $careCertificateFilename; + + } + catch(\OCP\Files\NotFoundException $e) { } + + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + + public function addProductTypeTables(){ + + try{ + $this->myDb->addProductTypeTables(); + return true; + + } + catch(\OCP\Files\NotFoundException $e) { } + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + */ + public function getProductTypes() { + + return $this->myDb->getProductTypes(); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + + public function addLocationCodesColumn(){ + + try{ + $this->myDb->addLocationCodesColumn(); + return true; + + } + catch(\OCP\Files\NotFoundException $e) { } + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function uploadFileToBijoux($bijouxId){ + + try{ + $configs = json_decode($this->myDb->getConfiguration(self::DEFAULT_NEXTCLOUD_ADMIN)); + $currentConfig = $configs[0]; + $bijoux = $this->myDb->getBijouxWithDefuntByBijouxId($bijouxId); + if($bijoux == null){ + return false; + } + if($bijoux["defunt_id"] == null){ + return false; + } + $defuntId = $bijoux["defunt_id"]; + $devisOfDefunt = $this->myDb->getDevisOfDefunt($defuntId); + if($devisOfDefunt == null){ + return false; + } + $folder = FileExportHelpers::GetBijouxOfDefuntFolder($devisOfDefunt["client_nom"],$bijoux["defunt_nom"],$currentConfig->path); + $appAdminStorage = $this->rootFolder->getUserFolder(BddConstant::DEFAULT_ADMIN_APP_ID_NEXTCLOUD); + try { + $this->storage->newFolder($folder); + $this->adminStorage->newFolder($folder); + $appAdminStorage->newFolder($folder); + } + catch(\OCP\Files\NotPermittedException $e) { } - return $careCertificateFilename; - } catch(\OCP\Files\NotFoundException $e) { - } - - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param int $defuntId - * @param int $productId - */ - - public function setDefuntCover($defuntId, $productId) - { - try { - $response = $this->myDb->setDefuntCover($defuntId, $productId); - return $response; - } catch(\OCP\Files\NotFoundException $e) { - } - - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - - public function getUserConnectedGroups() - { - try { - return json_encode($this->groups); - } catch(\OCP\Files\NotFoundException $e) { - } - } - - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - - public function testTalk() - { - try { - $message = $this->myDb->getDevisTalkRoomMessage(1, $this->idNextcloud); - // $message ="FROM API"; - $this->talkService->sendDevisTalkNotifications($message, $this->idNextcloud); - return true; - } catch(\OCP\Files\NotFoundException $e) { - } - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - - public function getCoverProducts() - { - try { - $coverProducts = $this->myDb->getCoverProducts(); - return $coverProducts; - } catch(\OCP\Files\NotFoundException $e) { - } - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param int $devisId - * - */ - - public function exportDevisToPdf($devisId) - { - try { - $devisFilenames = $this->devisPdfService->generateDevisPdfByDevisId($devisId, $this->idNextcloud); - return json_encode($devisFilenames); - } catch(\OCP\Files\NotFoundException $e) { - } - - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param string $clientId - * @param string $month - * @param string $year - * - */ - - public function exportDevisByClientAndMonthYearToPdf($clientId, $month, $year, $type = DevisExportTypeConstant::TYPE_SINGLE) - { - try { - $devisFilename = $this->devisPdfService->generateMultipleDevisPdfByClientAndMonthYear($clientId, $month, $year, $type, $this->idNextcloud); - return $devisFilename; - } catch(\OCP\Files\NotFoundException $e) { - } - - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - - public function addClientGroupFacturationFeatureTables() - { - try { - $this->myDb->addClientGroupFacturationFeatureTables(); - return true; - } catch(\OCP\Files\NotFoundException $e) { - } - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function clientGroupFacturation() - { - return new TemplateResponse('gestion', 'clientGroupFacturation', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, 'url' => $this->getNavigationLink())); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getClientGroupFacturations() - { - return $this->myDb->getClientGroupFacturations(); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function createDefaultClientGroupFacturation() - { - return $this->myDb->createDefaultGroupFacturation(); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @param int $defuntId - */ - - public function saveAttestationPacemaker($defuntId, $email = '') - { - try { - $careCertificateFilename = $this->certificateService->generatePacemakerCertificate($defuntId, $this->idNextcloud); - if($careCertificateFilename != null && trim($email) != '') { - //send email - $this->sendAttachmentToClientByDefunt($defuntId, $careCertificateFilename, $email, "Retrait de pile", "Vous trouverez en pièce jointe l'attestation de retrait de pile ", true); - + $photoName = basename($_FILES["photo"]["name"]); + $filename = uniqid() . "_" .$photoName; + $fullPath = $folder.$filename; + $fileContent = file_get_contents($_FILES["photo"]["tmp_name"]); + $this->storage->newFile($fullPath,$fileContent); + $this->adminStorage->newFile($fullPath,$fileContent); + try{ + $appAdminStorage->newFile($fullPath,$fileContent); + } + catch(\OCP\Files\NotPermittedException $e) { } - return $careCertificateFilename; - } catch(\OCP\Files\NotFoundException $e) { - } + $this->myDb->saveBijouxPhoto($bijouxId,$filename,$photoName); + return $fullPath; - } + } + catch(\OCP\Files\NotFoundException $e) { } + } - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function uploadPacemakerPhotoToDefunts($defuntId){ - public function addProductTypeTables() - { - try { - $this->myDb->addProductTypeTables(); - return true; - } catch(\OCP\Files\NotFoundException $e) { - } - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - */ - public function getProductTypes() - { - return $this->myDb->getProductTypes(); - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - - public function addLocationCodesColumn() - { - try { - $this->myDb->addLocationCodesColumn(); - return true; - } catch(\OCP\Files\NotFoundException $e) { - } - } - - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function uploadFileToBijoux($bijouxId) - { - try { - $configs = json_decode($this->myDb->getConfiguration(self::DEFAULT_NEXTCLOUD_ADMIN)); - $currentConfig = $configs[0]; - $bijoux = $this->myDb->getBijouxWithDefuntByBijouxId($bijouxId); - if($bijoux == null) { - return false; + try{ + $configs = json_decode($this->myDb->getConfiguration(self::DEFAULT_NEXTCLOUD_ADMIN)); + $currentConfig = $configs[0]; + $devisOfDefunt = $this->myDb->getDevisOfDefunt($defuntId); + if($devisOfDefunt == null){ + return null; + } + $folder = FileExportHelpers::GetPacemakerPhotoFolderOfDefunt($devisOfDefunt["client_nom"],$devisOfDefunt["defunt_nom"],$currentConfig->path); + $appAdminStorage = $this->rootFolder->getUserFolder(BddConstant::DEFAULT_ADMIN_APP_ID_NEXTCLOUD); + try { + $this->storage->newFolder($folder); + $this->adminStorage->newFolder($folder); + $appAdminStorage->newFolder($folder); + } + catch(\OCP\Files\NotPermittedException $e) { } - if($bijoux["defunt_id"] == null) { - return false; + $photoName = basename($_FILES["photo"]["name"]); + $filename = uniqid() . "_" .$photoName; + $fullPath = $folder.$filename; + $fileContent = file_get_contents($_FILES["photo"]["tmp_name"]); + $this->storage->newFile($fullPath,$fileContent); + $this->adminStorage->newFile($fullPath,$fileContent); + try{ + $appAdminStorage->newFile($fullPath,$fileContent); + } + catch(\OCP\Files\NotPermittedException $e) { } - $defuntId = $bijoux["defunt_id"]; - $devisOfDefunt = $this->myDb->getDevisOfDefunt($defuntId); - if($devisOfDefunt == null) { - return false; - } - $folder = FileExportHelpers::GetBijouxOfDefuntFolder($devisOfDefunt["client_nom"], $bijoux["defunt_nom"], $currentConfig->path); - $appAdminStorage = $this->rootFolder->getUserFolder(BddConstant::DEFAULT_ADMIN_APP_ID_NEXTCLOUD); - try { - $this->storage->newFolder($folder); - $this->adminStorage->newFolder($folder); - $appAdminStorage->newFolder($folder); - } catch(\OCP\Files\NotPermittedException $e) { - } - $photoName = basename($_FILES["photo"]["name"]); - $filename = uniqid() . "_" .$photoName; - $fullPath = $folder.$filename; - $fileContent = file_get_contents($_FILES["photo"]["tmp_name"]); - $this->storage->newFile($fullPath, $fileContent); - $this->adminStorage->newFile($fullPath, $fileContent); - try { - $appAdminStorage->newFile($fullPath, $fileContent); - } catch(\OCP\Files\NotPermittedException $e) { - } - $this->myDb->saveBijouxPhoto($bijouxId, $filename, $photoName); - return $fullPath; - } catch(\OCP\Files\NotFoundException $e) { - } - } + $this->myDb->saveDefuntPacemakerPhoto($defuntId,$filename,$photoName); + return $fullPath; + } + catch(\OCP\Files\NotFoundException $e) { + return null; + } + } - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function uploadPacemakerPhotoToDefunts($defuntId) - { - try { - $configs = json_decode($this->myDb->getConfiguration(self::DEFAULT_NEXTCLOUD_ADMIN)); - $currentConfig = $configs[0]; - $devisOfDefunt = $this->myDb->getDevisOfDefunt($defuntId); - if($devisOfDefunt == null) { - return null; - } - $folder = FileExportHelpers::GetPacemakerPhotoFolderOfDefunt($devisOfDefunt["client_nom"], $devisOfDefunt["defunt_nom"], $currentConfig->path); - $appAdminStorage = $this->rootFolder->getUserFolder(BddConstant::DEFAULT_ADMIN_APP_ID_NEXTCLOUD); - try { - $this->storage->newFolder($folder); - $this->adminStorage->newFolder($folder); - $appAdminStorage->newFolder($folder); - } catch(\OCP\Files\NotPermittedException $e) { - } - $photoName = basename($_FILES["photo"]["name"]); - $filename = uniqid() . "_" .$photoName; - $fullPath = $folder.$filename; - $fileContent = file_get_contents($_FILES["photo"]["tmp_name"]); - $this->storage->newFile($fullPath, $fileContent); - $this->adminStorage->newFile($fullPath, $fileContent); - try { - $appAdminStorage->newFile($fullPath, $fileContent); - } catch(\OCP\Files\NotPermittedException $e) { - } - $this->myDb->saveDefuntPacemakerPhoto($defuntId, $filename, $photoName); - return $fullPath; - } catch(\OCP\Files\NotFoundException $e) { - return null; - } - } + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function payInvoices($factureIds,$facturePaymentTypeId,$paymentDate){ - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function payInvoices($factureIds, $facturePaymentTypeId, $paymentDate) - { - try { - $result = $this->myDb->payInvoices($factureIds, $facturePaymentTypeId, $paymentDate); - return $result; - } catch(Exception) { - return false; - } - } + try{ + $result = $this->myDb->payInvoices($factureIds,$facturePaymentTypeId,$paymentDate); + return $result; + } + catch(Exception) { + return false; + } + } - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function getUsersNotLinkedToThanato() - { - try { - $result = $this->myDb->getUsersNotLinkedToThanato(); - return $result; - } catch(Exception $e) { - return json_encode([]); - } - } + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function getUsersNotLinkedToThanato(){ - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function exportGroupOfDevisIntoFacture($clientId, $clientType, $month, $year, $facturationDate) - { - try { - $result = $this->invoicePdfService->exportGroupOfDevisIntoFacture( - $clientId, - $clientType, - $month, - $year, - $facturationDate, - $this->idNextcloud - ); - if ($result) { + try{ + $result = $this->myDb->getUsersNotLinkedToThanato(); + return $result; + } + catch(Exception $e) { + return json_encode([]); + } + } - return json_encode($result); - } - return json_encode([]); - } catch(Exception $e) { - return json_encode([]); - } - } + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function exportGroupOfDevisIntoFacture($clientId,$clientType,$month,$year,$facturationDate){ - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function getClientTemplateTypes() - { - return $this->myDb->getClientTemplateTypes(); - } + try{ + $result = $this->invoicePdfService->exportGroupOfDevisIntoFacture( + $clientId, + $clientType, + $month, + $year, + $facturationDate, + $this->idNextcloud + ); + if ($result) { + + return json_encode($result); + } + return json_encode([]); + } + catch(Exception $e) { + return json_encode([]); + } + } - /** - * @NoAdminRequired - * @NoCSRFRequired - * - */ - public function factureGroupDetails($numfacture) - { - $this->denyIfNotAdmin(); - $facture = $this->myDb->getFactureGroupByFactureIdWithDetails($numfacture); - $facture["path_to_file"] = $this->idNextcloud.'/'.FileExportHelpers::GetFactureGroupFileFullPath( + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function getClientTemplateTypes(){ + + return $this->myDb->getClientTemplateTypes(); + } + + /** + * @NoAdminRequired + * @NoCSRFRequired + * + */ + public function factureGroupDetails($numfacture){ + + $this->denyIfNotAdmin(); + $facture = $this->myDb->getFactureGroupByFactureIdWithDetails($numfacture); + $facture["path_to_file"] = $this->idNextcloud.'/'.FileExportHelpers::GetFactureGroupFileFullPath( clientName:$facture['group_name'], factureNum: $facture['num'], facturationDate: $facture['date_paiement'] ); - return new TemplateResponse('gestion', 'factureGroupDetails', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, - 'configuration' => $this->getConfiguration(), - 'facture' => json_decode(json_encode($facture)), - 'url' => $this->getNavigationLink(), - 'logo' => $this->getLogo() - )); - } + return new TemplateResponse('gestion', 'factureGroupDetails', array('groups' => $this->groups, 'user' => $this->user, 'path' => $this->idNextcloud, + 'configuration'=> $this->getConfiguration(), + 'facture'=>json_decode(json_encode($facture)), + 'url' => $this->getNavigationLink(), + 'logo' => $this->getLogo() + )); + } } diff --git a/gestion/lib/Db/Bdd.php b/gestion/lib/Db/Bdd.php index 4f8ba57..f88cec0 100644 --- a/gestion/lib/Db/Bdd.php +++ b/gestion/lib/Db/Bdd.php @@ -2,7 +2,7 @@ namespace OCA\Gestion\Db; -use Datetime; +use \Datetime; use OCA\Gestion\Helpers\MailHelpers; use OCP\IL10N; use OCP\IDBConnection; @@ -21,8 +21,8 @@ use OCA\Gestion\Constants\VCalendarPropertyConstant; use OCA\Gestion\Constants\ClientTemplateTypeConstant; use OCA\Gestion\Constants\MultipleFactureTypeConstant; -class Bdd -{ +class Bdd { + private String $charset = 'utf8mb4'; public const DEFAULT_CALENDAR_UUID_FOR_DEVIS = "not-related"; @@ -36,22 +36,22 @@ class Bdd private $l; /** @var LoggerInterface */ - private $logger; + private $logger; - public function __construct(IDbConnection $db, IL10N $l, LoggerInterface $logger) - { - $this->whiteColumn = array("date", "num", "id_client", "id_thanato", "entreprise", "nom", "prenom", "legal_one", "telephone", "mail", "adresse", "produit_id", - "quantite", "is_tva", "date_paiement", "type_paiement", "id_devis", "reference", "description", "prix_unitaire", "legal_two", "path", "tva_default", "coefficient_ik", - "mentions_default", "version", "mentions", "comment", "status_paiement", "devise", "auto_invoice_number", "changelog", "format", "comment", "user_id", + public function __construct(IDbConnection $db, IL10N $l, LoggerInterface $logger) { + + $this->whiteColumn = array("date", "num", "id_client", "id_thanato", "entreprise", "nom", "prenom", "legal_one", "telephone", "mail", "adresse", "produit_id", + "quantite", "is_tva", "date_paiement", "type_paiement", "id_devis", "reference", "description", "prix_unitaire", "legal_two", "path", "tva_default", "coefficient_ik", + "mentions_default", "version", "mentions", "comment", "status_paiement", "devise", "auto_invoice_number", "changelog", "format", "comment", "user_id", "facture_prefixe", "arrivee", "depart", "latitude", "longitude", "id_lieu", "rang", "mois", "annee", "id_trajet", "commentaire","source", "date_habilitation", "sexe", "observations_generales", "ref_pacemaker", "id_defunt", "article_id", "corpulence", "date_naissance", "heure_debut", "heure_fin", "rigidite", "lividite", "observations_corps", "acces", "acces_recherche", "acces_etat", "injection", "injection_diffusion", "injection_qte", "preinjection", "preinjection_qte", "coinjection", "coinjection_qte", "drainage", "drainage_qte", "drainage_etat", "ponction", "ponction_qte", "cavite", "cavite_qte", "desinfection", "lavage", - "rasage", "presentation_cosmetique", "presentation_sur", "hypodermiques", "hypodermiques_sur", "local", "local_sur", "contenu", + "rasage", "presentation_cosmetique", "presentation_sur", "hypodermiques", "hypodermiques_sur", "local", "local_sur", "contenu", "commentaire", "designation", "hypodermiques_text1", "hypodermiques_text2", "qte", "endroit", "fk_client_group_id","fk_produit_id","ht_amount","client_group_name", - "fk_client_group_facturation_id","group_facturation_name", + "fk_client_group_facturation_id","group_facturation_name", "fk_product_type_id", "portal_code","alarm_code","funeral_code", "product_brand","product_reference", @@ -69,8 +69,8 @@ class Bdd $this->logger = $logger; } - public function getConfiguration($idNextcloud) - { + public function getConfiguration($idNextcloud){ + $sql = "SELECT * FROM `".$this->tableprefix."configuration` WHERE id_nextcloud = ?"; return $this->execSQL($sql, array($idNextcloud)); } @@ -101,6 +101,7 @@ class Bdd if (isset($produit->prix_unitaire) && isset($produit->quantite)) { $total += $produit->prix_unitaire * $produit->quantite; } + } } @@ -120,22 +121,24 @@ class Bdd } } - public function getClients($idNextcloud) - { + public function getClients($idNextcloud){ + $sql = "SELECT * FROM ".$this->tableprefix."client;"; - $clients = $this->execSQLNoJsonReturn($sql, []); - foreach($clients as &$client) { - if($client['fk_client_group_id'] == null) { + $clients = $this->execSQLNoJsonReturn($sql,[]); + foreach($clients as &$client){ + if($client['fk_client_group_id'] == null){ $client['client_group_name'] = ''; - } else { + } + else{ $clientGroup = $this->getClientGroupById($client['fk_client_group_id']); $client['client_group_name'] = $clientGroup != null ? $clientGroup['client_group_name'] : ''; } - if($client['fk_client_group_facturation_id'] == null) { + if($client['fk_client_group_facturation_id'] == null){ $client['client_group_facturation_name'] = ''; - } else { + } + else{ $clientGroupFacturation = $this->getClientGroupFacturationById($client['fk_client_group_facturation_id']); $client['client_group_facturation_name'] = $clientGroupFacturation != null ? $clientGroupFacturation['group_facturation_name'] : ''; } @@ -143,41 +146,41 @@ class Bdd return json_encode($clients); } - private function getClientGroupById($clientGroupId) - { + private function getClientGroupById($clientGroupId){ + $sql = "SELECT * FROM ".$this->tableprefix."client_group as client_group WHERE client_group.id = ? ;"; $clientGroup = $this->execSQLNoJsonReturn($sql, array($clientGroupId)); - if(!empty($clientGroup)) { + if(!empty($clientGroup)){ return $clientGroup[0]; } return null; } - public function getClientsName() - { + public function getClientsName(){ + $sql = "SELECT client.nom, client.prenom, client.id FROM ".$this->tableprefix."client as client ORDER BY client.id DESC"; return $this->execSQL($sql, array()); } + + public function getClient($id,$idNextcloud){ - public function getClient($id, $idNextcloud) - { $sql = "SELECT * FROM ".$this->tableprefix."client WHERE id = ?"; return $this->execSQL($sql, array($id)); } - public function getClientbyiddevis($id, $idNextcloud) - { + public function getClientbyiddevis($id, $idNextcloud){ + $sql = "SELECT * FROM ".$this->tableprefix."devis as d, ".$this->tableprefix."client as c WHERE d.id_client = c.id AND d.id = ?"; return $this->execSQL($sql, array($id)); } - public function getThanatopracteurs($idNextcloud) - { + public function getThanatopracteurs($idNextcloud){ + $sql = "SELECT thanato.*, users.uid as user_uuid, @@ -188,9 +191,9 @@ class Bdd return $this->execSQL($sql, array()); } - public function getThanatoByIds(array $thanatoIds) - { - if(empty($thanatoIds)) { + public function getThanatoByIds(array $thanatoIds){ + + if(empty($thanatoIds)){ return []; } @@ -203,21 +206,21 @@ class Bdd FROM ".$this->tableprefix."thanato as thanato WHERE thanato.id IN ($sqlConditionsPlaceholder)"; $thanatoList = $this->execSQLNoJsonReturn( - $sql, - $thanatoIds - ); + $sql, + $thanatoIds); + return $thanatoList; } - public function getBibliotheques($idNextcloud) - { + public function getBibliotheques($idNextcloud) { + $sql = "SELECT * FROM ".$this->tableprefix."bibliotheque;"; return $this->execSQL($sql, array()); } - public function getTrajets($idNextcloud) - { + public function getTrajets($idNextcloud) { + // $sql_delete = "DELETE FROM ".$this->tableprefix."ligne_trajet"; // $this->execSQL($sql_delete, array()); // $sql_delete = "DELETE FROM ".$this->tableprefix."trajet"; @@ -230,8 +233,8 @@ class Bdd return $this->execSQL($sql, array()); } - public function getTrajetById($numtrajet, $idNextcloud) - { + public function getTrajetById($numtrajet, $idNextcloud) { + $sql = "SELECT trajet.id, trajet.mois, trajet.annee, trajet.distance, trajet.id_nextcloud, trajet.user_id, thanato.id as id_thanato, thanato.nom as nom_thanato, thanato.prenom as prenom_thanato FROM ".$this->tableprefix."trajet as trajet @@ -240,8 +243,8 @@ class Bdd return $this->execSQL($sql, array($numtrajet)); } - public function getTrajetsdetails($numtrajet, $idNextcloud) - { + public function getTrajetsdetails($numtrajet, $idNextcloud) { + $sql = "SELECT ligne_trajet.id, ligne_trajet.rang, ligne_trajet.id_nextcloud, ligne_trajet.date, ligne_trajet.user_id, ligne_trajet.commentaire, ligne_trajet.source, lieu.id as lid, lieu.nom as lieu, lieu.latitude as latitude, lieu.longitude as longitude, devis.id as did, devis.num as dnum, client_devis.nom as dnom, client_devis.prenom as dprenoms, devis.id_nextcloud as didnextcloud, @@ -257,8 +260,8 @@ class Bdd return $this->execSQL($sql, array($numtrajet)); } - public function getTrajetsdetails_orderByDate($numtrajet, $idNextcloud) - { + public function getTrajetsdetails_orderByDate($numtrajet, $idNextcloud) { + $sql = "SELECT ligne_trajet.id, ligne_trajet.rang, ligne_trajet.id_nextcloud, ligne_trajet.date, ligne_trajet.user_id, ligne_trajet.commentaire, ligne_trajet.source, lieu.id as lid, lieu.nom as lieu, lieu.latitude as latitude, lieu.longitude as longitude, client.nom as cnom, client.id as cid, client.prenom as cprenoms @@ -270,26 +273,26 @@ class Bdd return $this->execSQL($sql, array($numtrajet)); } - public function getOneTrajetdetails($id, $idNextcloud) - { + public function getOneTrajetdetails($id, $idNextcloud) { + $sql = "SELECT * FROM ".$this->tableprefix."ligne_trajet WHERE ".$this->tableprefix."ligne_trajet.id = ?;"; return $this->execSQL($sql, array($id)); } - public function getOneTrajetdetails_byIdDevis($id_devis, $idNextcloud) - { + public function getOneTrajetdetails_byIdDevis($id_devis, $idNextcloud) { + $sql = "SELECT * FROM ".$this->tableprefix."ligne_trajet WHERE ".$this->tableprefix."ligne_trajet.id_devis = ? AND ".$this->tableprefix."ligne_trajet.source LIKE 'devis';"; return $this->execSQL($sql, array($id_devis)); } - public function getOneTrajetdetails_byRang($id_trajet, $rang, $idNextcloud) - { + public function getOneTrajetdetails_byRang($id_trajet, $rang, $idNextcloud) { + $sql = "SELECT * FROM ".$this->tableprefix."ligne_trajet WHERE ".$this->tableprefix."ligne_trajet.id_trajet = ? AND ".$this->tableprefix."ligne_trajet.rang = ?;"; return $this->execSQL($sql, array($id_trajet, $rang)); } - public function getOneTrajet($id, $idNextcloud) - { + public function getOneTrajet($id, $idNextcloud) { + $sql = "SELECT trajet.id, trajet.mois, trajet.annee, trajet.distance, trajet.id_nextcloud, trajet.user_id, thanato.id as id_thanato, thanato.nom as nom_thanato, thanato.prenom as prenom_thanato FROM ".$this->tableprefix."trajet as trajet @@ -298,8 +301,8 @@ class Bdd return $this->execSQL($sql, array()); } - public function getLieux($idNextcloud) - { + public function getLieux($idNextcloud){ + $sql = "SELECT lieu.nom, lieu.adresse, lieu.latitude,lieu.longitude, lieu.user_id, lieu.id, lieu.portal_code,lieu.alarm_code,lieu.funeral_code FROM ".$this->tableprefix."lieu as lieu @@ -307,18 +310,18 @@ class Bdd return $this->execSQL($sql, array()); } - public function getLieu($id, $idNextcloud) - { + public function getLieu($id,$idNextcloud){ + $sql = "SELECT * FROM ".$this->tableprefix."lieu WHERE id = ?"; return $this->execSQL($sql, array($id)); } - public function getDevis($idNextcloud, $mentionFilters = []) - { + public function getDevis($idNextcloud,$mentionFilters = []){ + $sql = "SELECT ".$this->tableprefix."devis.id, ".$this->tableprefix."devis.id as devisid, ".$this->tableprefix."devis.user_id,".$this->tableprefix."devis.id_nextcloud ,".$this->tableprefix."devis.comment ," .$this->tableprefix."client.nom, ".$this->tableprefix."client.prenom, ".$this->tableprefix."client.id as cid, ".$this->tableprefix."client.id as id_client,".$this->tableprefix."client.is_tva as tva, " .$this->tableprefix."client.adresse as adresse_cli,".$this->tableprefix."client.mail as mail_cli,".$this->tableprefix."client.telephone as telephone_cli,".$this->tableprefix."client.legal_one as legalone_cli," - .$this->tableprefix."client.fk_client_group_facturation_id as fk_client_group_facturation_id," + .$this->tableprefix."client.fk_client_group_facturation_id as fk_client_group_facturation_id," .$this->tableprefix."thanato.nom as nom_thanato, ".$this->tableprefix."thanato.prenom as prenom_thanato, ".$this->tableprefix."thanato.id as tid, " .$this->tableprefix."devis.num, ".$this->tableprefix."devis.date, ".$this->tableprefix."devis.version, ".$this->tableprefix."devis.mentions, " .$this->tableprefix."devis.order_number, ".$this->tableprefix."devis.case_number, " @@ -332,7 +335,7 @@ class Bdd LEFT JOIN ".$this->tableprefix."lieu on id_lieu = ".$this->tableprefix."lieu.id"; $conditions = []; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " WHERE ". $this->tableprefix."devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); @@ -341,24 +344,24 @@ class Bdd return $this->execSQL($sql, $conditions); } - public function getDevisWithProduits($idNextcloud) - { + public function getDevisWithProduits($idNextcloud){ + $devis = $this->getDevis($idNextcloud); $devisList = json_decode($devis); - foreach($devisList as $currentDevis) { + foreach($devisList as $currentDevis){ $produits = $this->getProduitsDevisByDevisId($currentDevis->devisid); $currentDevis->produits = $produits; } return json_encode($devisList); } - public function getDevisEmmanuelle($idNextcloud) - { + public function getDevisEmmanuelle($idNextcloud){ + $sql = "SELECT ".$this->tableprefix."devis.id, ".$this->tableprefix."devis.id as devisid, ".$this->tableprefix."devis.user_id,".$this->tableprefix."devis.id_nextcloud ,".$this->tableprefix."devis.comment ," .$this->tableprefix."client.nom, ".$this->tableprefix."client.prenom, ".$this->tableprefix."client.id as cid, ".$this->tableprefix."client.id as id_client, " .$this->tableprefix."client.adresse as adresse_cli,".$this->tableprefix."client.mail as mail_cli,".$this->tableprefix."client.telephone as telephone_cli,".$this->tableprefix."client.legal_one as legalone_cli," .$this->tableprefix."thanato.nom as nom_thanato, ".$this->tableprefix."thanato.prenom as prenom_thanato, ".$this->tableprefix."thanato.id as tid, " - .$this->tableprefix."devis.num, ".$this->tableprefix."devis.date, ".$this->tableprefix."devis.version, ".$this->tableprefix."devis.mentions, " + .$this->tableprefix."devis.num, ".$this->tableprefix."devis.date, ".$this->tableprefix."devis.version, ".$this->tableprefix."devis.mentions, " .$this->tableprefix."lieu.id as lid, ".$this->tableprefix."lieu.nom as lieu,".$this->tableprefix."lieu.adresse as adresse_soin,".$this->tableprefix."devis.id_lieu, " .$this->tableprefix."defunt.id as id_defunt, ".$this->tableprefix."defunt.nom as nom_defunt FROM (".$this->tableprefix."devis @@ -370,13 +373,13 @@ class Bdd return $this->execSQL($sql, array()); } - public function getDevisDelphine($idtrajetdetails, $idNextcloud) - { + public function getDevisDelphine($idtrajetdetails, $idNextcloud) { + $ligne_trajet = json_decode($this->getOneTrajetdetails($idtrajetdetails, $idNextcloud))[0]; $sql = "SELECT ".$this->tableprefix."devis.id, ".$this->tableprefix."devis.user_id,".$this->tableprefix."devis.id_nextcloud ," .$this->tableprefix."client.nom, ".$this->tableprefix."client.prenom, ".$this->tableprefix."client.id as cid, " .$this->tableprefix."thanato.nom as nom_thanato, ".$this->tableprefix."thanato.prenom as prenom_thanato, ".$this->tableprefix."thanato.id as tid, " - .$this->tableprefix."devis.num, ".$this->tableprefix."devis.date, ".$this->tableprefix."devis.version, ".$this->tableprefix."devis.mentions, " + .$this->tableprefix."devis.num, ".$this->tableprefix."devis.date, ".$this->tableprefix."devis.version, ".$this->tableprefix."devis.mentions, " .$this->tableprefix."lieu.id as lid, ".$this->tableprefix."lieu.nom as lieu,".$this->tableprefix."devis.id_lieu FROM (".$this->tableprefix."devis LEFT JOIN ".$this->tableprefix."client on id_client = ".$this->tableprefix."client.id @@ -384,56 +387,56 @@ class Bdd LEFT JOIN ".$this->tableprefix."lieu on id_lieu = ".$this->tableprefix."lieu.id ) WHERE LOWER(".$this->tableprefix."devis.id_nextcloud) LIKE 'delphine' AND ".$this->tableprefix."devis.date LIKE '".$ligne_trajet->date."'"; + + if($ligne_trajet->id_client != NULL) $sql = $sql." AND ".$this->tableprefix."devis.id_client = ".$ligne_trajet->id_client; + if($ligne_trajet->id_lieu != NULL) $sql = $sql." AND ".$this->tableprefix."devis.id_lieu = ".$ligne_trajet->id_lieu; + + + - if($ligne_trajet->id_client != null) { - $sql = $sql." AND ".$this->tableprefix."devis.id_client = ".$ligne_trajet->id_client; - } - if($ligne_trajet->id_lieu != null) { - $sql = $sql." AND ".$this->tableprefix."devis.id_lieu = ".$ligne_trajet->id_lieu; - } $sql = $sql." ORDER BY ".$this->tableprefix."devis.id DESC, ".$this->tableprefix."devis.date DESC;"; return $this->execSQL($sql, array()); } - private function getClientsWithClientType(bool $includeClientInsideGroup = true) - { + private function getClientsWithClientType(bool $includeClientInsideGroup = true){ + $sql = "SELECT client.*,'client' as client_type FROM ".$this->tableprefix."client as client"; - if($includeClientInsideGroup == false) { + if($includeClientInsideGroup == false){ $sql .= " WHERE client.fk_client_group_facturation_id IS NULL"; } $sql .= ";"; - $clientsWithClientType = $this->execSQLNoJsonReturn($sql, []); + $clientsWithClientType = $this->execSQLNoJsonReturn($sql,[]); return $clientsWithClientType; } - public function getClientsAndClientGroupFacturations(bool $includeClientInsideGroup = true) - { + public function getClientsAndClientGroupFacturations(bool $includeClientInsideGroup = true){ + $clients = $this->getClientsWithClientType($includeClientInsideGroup); $clientGroupFacturations = $this->getClientGroupFacturationsWithType(); $result = [...$clientGroupFacturations,...$clients]; return json_encode($result); } - public function getFacturesListWithDependencies() - { - $sql = "SELECT - facture.id, - facture.user_id, - facture.num, + public function getFacturesListWithDependencies(){ + + $sql = "SELECT + facture.id, + facture.user_id, + facture.num, facture.date, - facture.fk_facture_status_key, - facture.fk_facture_payment_type_id, + facture.fk_facture_status_key, + facture.fk_facture_payment_type_id, facture.payment_date, facture_payment_type.facture_payment_type_label, facture_status.facture_status_label, facture.facture_type, facture.fk_client_id as facture_client_id, facture.fk_client_group_facturation_id as facture_client_group_facturation_id, - facture.date_paiement, - facture.type_paiement, + facture.date_paiement, + facture.type_paiement, facture.id_devis, - facture.version, + facture.version, facture.status_paiement, facture_client.nom as facture_client_name, facture_client.entreprise as facture_client_entreprise, @@ -444,20 +447,20 @@ class Bdd facture.document_sent_date as facture_document_sent_date, facture.month as facture_month, facture.year as facture_year, - devis.num as dnum, - devis.comment as dcomment, + devis.num as dnum, + devis.comment as dcomment, client.entreprise, - client.nom, + client.nom, client.prenom, - client.id as id_cli, - client.entreprise as client_entreprise, + client.id as id_cli, + client.entreprise as client_entreprise, client.fk_client_group_facturation_id as fk_client_group_facturation_id, client.adresse as adresse_cli,client.mail as mail_cli, client.telephone as telephone_cli,client.legal_one as legalone_cli, client.fk_client_group_id as fk_client_group_id, - defunt.id as id_defunt, + defunt.id as id_defunt, defunt.nom as nom_defunt, - lieu.id as lid, + lieu.id as lid, lieu.nom as lieu, lieu.adresse as adresse_soin,devis.id_lieu FROM ".$this->tableprefix."facture as facture @@ -474,8 +477,8 @@ class Bdd return $result; } - public function getFactures($idNextcloud) - { + public function getFactures($idNextcloud){ + $sql = "SELECT ".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, " .$this->tableprefix."facture.fk_facture_status_key, ".$this->tableprefix."facture.fk_facture_payment_type_id, ".$this->tableprefix."facture.payment_date, " .$this->tableprefix."facture_payment_type.facture_payment_type_label, " @@ -506,19 +509,19 @@ class Bdd return $result; } - public function getFacturesWithProduits() - { + public function getFacturesWithProduits(){ + $factures = $this->getFacturesListWithDependencies(); $facturesList = json_decode($factures); - foreach($facturesList as $currentFacture) { + foreach($facturesList as $currentFacture){ $produits = $this->getProduitsDevisByDevisId($currentFacture->id_devis); $currentFacture->produits = $produits; } return json_encode($facturesList); } - private function getClientFacturesByClientIdListAndDate($clientIdList, $date) - { + private function getClientFacturesByClientIdListAndDate($clientIdList,$date) { + $clientIdsSqlPlaceholder = implode(',', array_fill(0, count($clientIdList), '?')); $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month," .$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, " @@ -541,23 +544,23 @@ class Bdd WHERE YEAR(".$this->tableprefix."facture.date_paiement) = ".explode('-', $date)[2]." AND MONTH(".$this->tableprefix."facture.date_paiement) = ".explode('-', $date)[1]." AND ".$this->tableprefix."client.id IN($clientIdsSqlPlaceholder) ORDER BY date_soin ASC"; $result = $this->execSQL( - sql: $sql, - conditions: $clientIdList - ); + sql: $sql, + conditions: $clientIdList ); + return $result; } - public function getClientFacturesByClientGroupFacturationIdAndDate($clientGroupFacturationId, $date) - { + public function getClientFacturesByClientGroupFacturationIdAndDate($clientGroupFacturationId,$date){ + $clientIds = $this->getClientIdsByClientGroupFacturationId($clientGroupFacturationId); - if(empty($clientIds)) { + if(empty($clientIds)){ return []; } - return $this->getClientFacturesByClientIdListAndDate($clientIds, $date); + return $this->getClientFacturesByClientIdListAndDate($clientIds,$date); } - public function getClientFacturesByClientIdAndDate($clientId, $date) - { + public function getClientFacturesByClientIdAndDate($clientId,$date){ + $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month," .$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, " .$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."devis.comment as numero_commande, " @@ -588,8 +591,8 @@ class Bdd return $result; } - public function getCurrentMonthFactures_byClient($idNextcloud, $date, $idclient) - { + public function getCurrentMonthFactures_byClient($idNextcloud, $date, $idclient) { + $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month," .$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, " .$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."devis.comment as numero_commande, " @@ -606,17 +609,17 @@ class Bdd LEFT JOIN ".$this->tableprefix."defunt on ".$this->tableprefix."devis.id_defunt = ".$this->tableprefix."defunt.id WHERE YEAR(".$this->tableprefix."facture.date_paiement) = ".explode('-', $date)[2]." AND MONTH(".$this->tableprefix."facture.date_paiement) = ".explode('-', $date)[1]." AND ".$this->tableprefix."client.id = ".$idclient." ORDER BY year DESC, month DESC;"; - // $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month,".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."client.adresse as adresse_client, ".$this->tableprefix."devis.date as date_soin, ".$this->tableprefix."devis.id_client as id_client, date_paiement, type_paiement, id_devis, nom, prenom, entreprise, ".$this->tableprefix."facture.version, status_paiement FROM (".$this->tableprefix."facture LEFT JOIN ".$this->tableprefix."devis on ".$this->tableprefix."facture.id_devis = ".$this->tableprefix."devis.id) LEFT JOIN ".$this->tableprefix."client on ".$this->tableprefix."devis.id_client = ".$this->tableprefix."client.id + // $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month,".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."client.adresse as adresse_client, ".$this->tableprefix."devis.date as date_soin, ".$this->tableprefix."devis.id_client as id_client, date_paiement, type_paiement, id_devis, nom, prenom, entreprise, ".$this->tableprefix."facture.version, status_paiement FROM (".$this->tableprefix."facture LEFT JOIN ".$this->tableprefix."devis on ".$this->tableprefix."facture.id_devis = ".$this->tableprefix."devis.id) LEFT JOIN ".$this->tableprefix."client on ".$this->tableprefix."devis.id_client = ".$this->tableprefix."client.id // WHERE YEAR(".$this->tableprefix."facture.date_paiement) = YEAR(CURRENT_DATE) AND MONTH(".$this->tableprefix."facture.date_paiement) = MONTH(CURRENT_DATE) // ORDER BY year DESC, month DESC;"; - // $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month,".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."client.adresse as adresse_client, ".$this->tableprefix."devis.date as date_soin, ".$this->tableprefix."devis.id_client as id_client, date_paiement, type_paiement, id_devis, nom, prenom, entreprise, ".$this->tableprefix."facture.version, status_paiement FROM (".$this->tableprefix."facture LEFT JOIN ".$this->tableprefix."devis on ".$this->tableprefix."facture.id_devis = ".$this->tableprefix."devis.id) LEFT JOIN ".$this->tableprefix."client on ".$this->tableprefix."devis.id_client = ".$this->tableprefix."client.id + // $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month,".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."client.adresse as adresse_client, ".$this->tableprefix."devis.date as date_soin, ".$this->tableprefix."devis.id_client as id_client, date_paiement, type_paiement, id_devis, nom, prenom, entreprise, ".$this->tableprefix."facture.version, status_paiement FROM (".$this->tableprefix."facture LEFT JOIN ".$this->tableprefix."devis on ".$this->tableprefix."facture.id_devis = ".$this->tableprefix."devis.id) LEFT JOIN ".$this->tableprefix."client on ".$this->tableprefix."devis.id_client = ".$this->tableprefix."client.id // ORDER BY year DESC, month DESC;"; $result = $this->execSQL($sql, array()); return $result; } - public function getCurrentMonthFactures($idNextcloud, $date) - { + public function getCurrentMonthFactures($idNextcloud, $date) { + $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month," .$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, " .$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."devis.comment as numero_commande, " @@ -633,17 +636,17 @@ class Bdd LEFT JOIN ".$this->tableprefix."defunt on ".$this->tableprefix."devis.id_defunt = ".$this->tableprefix."defunt.id WHERE YEAR(".$this->tableprefix."facture.date_paiement) = ".explode('-', $date)[2]." AND MONTH(".$this->tableprefix."facture.date_paiement) = ".explode('-', $date)[1]." ORDER BY year DESC, month DESC;"; - // $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month,".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."client.adresse as adresse_client, ".$this->tableprefix."devis.date as date_soin, ".$this->tableprefix."devis.id_client as id_client, date_paiement, type_paiement, id_devis, nom, prenom, entreprise, ".$this->tableprefix."facture.version, status_paiement FROM (".$this->tableprefix."facture LEFT JOIN ".$this->tableprefix."devis on ".$this->tableprefix."facture.id_devis = ".$this->tableprefix."devis.id) LEFT JOIN ".$this->tableprefix."client on ".$this->tableprefix."devis.id_client = ".$this->tableprefix."client.id + // $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month,".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."client.adresse as adresse_client, ".$this->tableprefix."devis.date as date_soin, ".$this->tableprefix."devis.id_client as id_client, date_paiement, type_paiement, id_devis, nom, prenom, entreprise, ".$this->tableprefix."facture.version, status_paiement FROM (".$this->tableprefix."facture LEFT JOIN ".$this->tableprefix."devis on ".$this->tableprefix."facture.id_devis = ".$this->tableprefix."devis.id) LEFT JOIN ".$this->tableprefix."client on ".$this->tableprefix."devis.id_client = ".$this->tableprefix."client.id // WHERE YEAR(".$this->tableprefix."facture.date_paiement) = YEAR(CURRENT_DATE) AND MONTH(".$this->tableprefix."facture.date_paiement) = MONTH(CURRENT_DATE) // ORDER BY year DESC, month DESC;"; - // $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month,".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."client.adresse as adresse_client, ".$this->tableprefix."devis.date as date_soin, ".$this->tableprefix."devis.id_client as id_client, date_paiement, type_paiement, id_devis, nom, prenom, entreprise, ".$this->tableprefix."facture.version, status_paiement FROM (".$this->tableprefix."facture LEFT JOIN ".$this->tableprefix."devis on ".$this->tableprefix."facture.id_devis = ".$this->tableprefix."devis.id) LEFT JOIN ".$this->tableprefix."client on ".$this->tableprefix."devis.id_client = ".$this->tableprefix."client.id + // $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month,".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."client.adresse as adresse_client, ".$this->tableprefix."devis.date as date_soin, ".$this->tableprefix."devis.id_client as id_client, date_paiement, type_paiement, id_devis, nom, prenom, entreprise, ".$this->tableprefix."facture.version, status_paiement FROM (".$this->tableprefix."facture LEFT JOIN ".$this->tableprefix."devis on ".$this->tableprefix."facture.id_devis = ".$this->tableprefix."devis.id) LEFT JOIN ".$this->tableprefix."client on ".$this->tableprefix."devis.id_client = ".$this->tableprefix."client.id // ORDER BY year DESC, month DESC;"; $result = $this->execSQL($sql, array()); return $result; } - public function getCurrentMonthFactures_COGF($idNextcloud, $date) - { + public function getCurrentMonthFactures_COGF($idNextcloud, $date) { + $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month," .$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, " .$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."devis.comment as numero_commande, " @@ -659,17 +662,17 @@ class Bdd LEFT JOIN ".$this->tableprefix."defunt on ".$this->tableprefix."devis.id_defunt = ".$this->tableprefix."defunt.id WHERE YEAR(".$this->tableprefix."facture.date_paiement) = ".explode('-', $date)[2]." AND MONTH(".$this->tableprefix."facture.date_paiement) = ".explode('-', $date)[1]." AND LOWER(".$this->tableprefix."client.entreprise) LIKE LOWER('COGF') ORDER BY year DESC, month DESC;"; - - // $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month,".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."client.adresse as adresse_client, ".$this->tableprefix."devis.date as date_soin, ".$this->tableprefix."devis.id_client as id_client, date_paiement, type_paiement, id_devis, nom, prenom, entreprise, ".$this->tableprefix."facture.version, status_paiement FROM (".$this->tableprefix."facture LEFT JOIN ".$this->tableprefix."devis on ".$this->tableprefix."facture.id_devis = ".$this->tableprefix."devis.id) LEFT JOIN ".$this->tableprefix."client on ".$this->tableprefix."devis.id_client = ".$this->tableprefix."client.id - // WHERE LOWER(".$this->tableprefix."client.entreprise) LIKE LOWER('COGF') + + // $sql = "SELECT YEAR(".$this->tableprefix."facture.date_paiement) AS year, MONTH(".$this->tableprefix."facture.date_paiement) AS month,".$this->tableprefix."facture.id, ".$this->tableprefix."facture.user_id, ".$this->tableprefix."facture.num, ".$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum,".$this->tableprefix."devis.version as adresse_devis,".$this->tableprefix."client.adresse as adresse_client, ".$this->tableprefix."devis.date as date_soin, ".$this->tableprefix."devis.id_client as id_client, date_paiement, type_paiement, id_devis, nom, prenom, entreprise, ".$this->tableprefix."facture.version, status_paiement FROM (".$this->tableprefix."facture LEFT JOIN ".$this->tableprefix."devis on ".$this->tableprefix."facture.id_devis = ".$this->tableprefix."devis.id) LEFT JOIN ".$this->tableprefix."client on ".$this->tableprefix."devis.id_client = ".$this->tableprefix."client.id + // WHERE LOWER(".$this->tableprefix."client.entreprise) LIKE LOWER('COGF') // ORDER BY year DESC, month DESC;"; - + $result = $this->execSQL($sql, array()); return $result; } - public function getCurrentMonthTrajet($idNextcloud, $date) - { + public function getCurrentMonthTrajet($idNextcloud, $date) { + $sql = "SELECT t.id_nextcloud, t.date, t.distance, depart.nom as lieu_depart, arrivee.nom as lieu_arrivee, depart_c.nom as depart_cnom, depart_c.prenom as depart_cprenoms, arrivee_c.nom as arrivee_cnom, arrivee_c.prenom as arrivee_cprenoms, thanato.id as id_thanato, thanato.nom as nom_thanato, thanato.prenom as prenom_thanato @@ -684,8 +687,8 @@ class Bdd return $result; } - public function getOneFacture($numfacture, $idNextcloud) - { + public function getOneFacture($numfacture, $idNextcloud){ + $sql = "SELECT ".$this->tableprefix."facture.id," . $this->tableprefix . "facture.version," . $this->tableprefix . "facture.num, " . $this->tableprefix . "facture.facture_number, " .$this->tableprefix."facture.date, ".$this->tableprefix."devis.num as dnum, comment, date_paiement, type_paiement, id_devis, ".$this->tableprefix."client.nom, prenom, entreprise," .$this->tableprefix."devis.comment as dcomment,".$this->tableprefix."lieu.nom as lieu, ".$this->tableprefix."lieu.adresse as adresse_soin," @@ -709,8 +712,8 @@ class Bdd return $this->execSQL($sql, array($numfacture)); } - public function getProduits($idNextcloud, $orderDirection = 'DESC') - { + public function getProduits($idNextcloud,$orderDirection = 'DESC'){ + $sql = "SELECT produit.id, produit.reference, @@ -727,38 +730,38 @@ class Bdd return $this->execSQL($sql, array()); } - private function getThanatoByIdNextcloud($idNextcloud) - { + private function getThanatoByIdNextcloud($idNextcloud){ + $sql = "SELECT * FROM ".$this->tableprefix."thanato as thanato WHERE LOWER(thanato.nom) = LOWER(?) ORDER BY thanato.id ASC;"; $thanato = $this->execSQLNoJsonReturn($sql, array($idNextcloud)); - if(!empty($thanato)) { + if(!empty($thanato)){ return $thanato[0]; } return null; } - private function getDefuntIdsRelatedToThanato($thanatoId) - { + private function getDefuntIdsRelatedToThanato($thanatoId){ + $devis = $this->getDevisMadeByAThanato($thanatoId); $defuntIds = $this->getDefuntIdsFromDevisList($devis); return $defuntIds; } - private function getDefuntIdsFromDevisList($devisList) - { + private function getDefuntIdsFromDevisList($devisList){ + $defuntIds = []; - foreach($devisList as $devis) { + foreach($devisList as $devis){ $defuntIds[] = $devis["id_defunt"]; } return $defuntIds; } - private function getDevisMadeByAThanato($thanatoId) - { + private function getDevisMadeByAThanato($thanatoId){ + $sql = "SELECT devis.id, devis.id_thanato, @@ -770,7 +773,7 @@ class Bdd return $devisList; } - public function getDefunts($idNextcloud, $isUserThanatoOnly = false) + public function getDefunts($idNextcloud, $isUserThanatoOnly = false) { $sql = "SELECT ".$this->tableprefix."defunt.id, ".$this->tableprefix."defunt.nom, ".$this->tableprefix."defunt.date_naissance, ".$this->tableprefix."defunt.ref_pacemaker, ".$this->tableprefix."defunt.sexe, " .$this->tableprefix."client.nom as nom_client, ".$this->tableprefix."client.id as id_client, " @@ -783,14 +786,14 @@ class Bdd LEFT JOIN ".$this->tableprefix."lieu ON ".$this->tableprefix."devis.id_lieu = ".$this->tableprefix."lieu.id"; $conditions = []; - if($isUserThanatoOnly) { + if($isUserThanatoOnly){ $thanato = $this->getThanatoByIdNextcloud($idNextcloud); - if($thanato == null) { + if($thanato == null){ return json_encode([]); } $thanatoId = $thanato["id"]; $defuntsIdRelatedToThanato = $this->getDefuntIdsRelatedToThanato($thanatoId); - if(empty($defuntsIdRelatedToThanato)) { + if(empty($defuntsIdRelatedToThanato)){ return json_encode([]); } $defuntListConditionPlaceholder = implode(',', array_fill(0, count($defuntsIdRelatedToThanato), '?')); @@ -799,13 +802,13 @@ class Bdd } $sql .= " ORDER BY ".$this->tableprefix."defunt.id DESC;"; - $defuntsList = $this->execSQLNoJsonReturn($sql, $conditions); - foreach($defuntsList as &$defunt) { + $defuntsList = $this->execSQLNoJsonReturn($sql,$conditions); + foreach($defuntsList as &$defunt){ $defunt["product_cover_description"] = null; $defuntHasDevis = $defunt["id_devis"] != null; - if($defuntHasDevis) { + if($defuntHasDevis){ $productCover = $this->getProductCoverByDevisId($defunt["id_devis"]); - if($productCover != null) { + if($productCover != null){ $defunt["product_cover_description"] = $productCover["description"]; } } @@ -813,8 +816,8 @@ class Bdd return json_encode($defuntsList); } - public function getUnusedDefunts($idNextcloud) - { + public function getUnusedDefunts($idNextcloud) { + $sql = "SELECT ".$this->tableprefix."defunt.id, ".$this->tableprefix."defunt.nom, ".$this->tableprefix."defunt.date_naissance, ".$this->tableprefix."defunt.ref_pacemaker, ".$this->tableprefix."defunt.sexe," .$this->tableprefix."devis.user_id as user_id FROM ".$this->tableprefix."defunt @@ -824,8 +827,8 @@ class Bdd return $this->execSQL($sql, array()); } - public function getOneDevis($numdevis, $idNextcloud) - { + public function getOneDevis($numdevis,$idNextcloud){ + $sql = "SELECT ".$this->tableprefix."devis.id as devisid, ".$this->tableprefix."devis.version, ".$this->tableprefix."devis.comment, ".$this->tableprefix."devis.date, num," .$this->tableprefix."devis.id_nextcloud as didnextcloud,".$this->tableprefix."devis.id_client, id_lieu, id_thanato,case_number,order_number," .$this->tableprefix."defunt.id as id_defunt, ".$this->tableprefix."defunt.nom as nom_defunt," @@ -845,8 +848,8 @@ class Bdd return $this->execSQL($sql, array($numdevis)); } - public function getOneDefunt($numdefunt, $idNextcloud, $includeDefuntProductCover = false) - { + public function getOneDefunt($numdefunt,$idNextcloud,$includeDefuntProductCover = false){ + $sql = "SELECT ".$this->tableprefix."defunt.id, ".$this->tableprefix."devis.version, ".$this->tableprefix."devis.comment, ".$this->tableprefix."devis.date, num," .$this->tableprefix."devis.id as id_devis,".$this->tableprefix."devis.id_client, id_lieu, id_thanato,".$this->tableprefix."devis.user_id as user_id, " .$this->tableprefix."defunt.id as id_defunt, ".$this->tableprefix."defunt.nom as nom_defunt,".$this->tableprefix."defunt.date_naissance,".$this->tableprefix."defunt.sexe,".$this->tableprefix."defunt.ref_pacemaker," @@ -900,14 +903,14 @@ class Bdd LEFT JOIN ".$this->tableprefix."thanato on ".$this->tableprefix."devis.id_thanato = ".$this->tableprefix."thanato.id WHERE ".$this->tableprefix."defunt.id = ?"; - $defunts = $this->execSQLNoJsonReturn($sql, [$numdefunt]); - if($includeDefuntProductCover) { - foreach($defunts as &$defunt) { + $defunts = $this->execSQLNoJsonReturn($sql,[$numdefunt]); + if($includeDefuntProductCover){ + foreach($defunts as &$defunt){ $defunt["product_cover_id"] = null; $defuntHasDevis = $defunt["id_devis"] != null; - if($defuntHasDevis) { + if($defuntHasDevis){ $productCover = $this->getProductCoverByDevisId($defunt["id_devis"]); - if($productCover != null) { + if($productCover != null){ $defunt["product_cover_id"] = $productCover["produit_id"]; } } @@ -916,8 +919,8 @@ class Bdd return json_encode($defunts); } - public function getListProduit($numdevis, $idNextcloud) - { + public function getListProduit($numdevis, $idNextcloud){ + $sql = "SELECT ". $this->tableprefix."produit.id as pid," .$this->tableprefix."produit_devis.id as pdid, reference, description," @@ -926,25 +929,25 @@ class Bdd FROM ".$this->tableprefix."produit, ".$this->tableprefix."devis, ".$this->tableprefix."produit_devis WHERE ".$this->tableprefix."produit.id = produit_id AND ".$this->tableprefix."devis.id = devis_id AND ".$this->tableprefix."devis.id = ?"; - $produits = $this->execSQLNoJsonReturn($sql, [$numdevis]); + $produits = $this->execSQLNoJsonReturn($sql,[$numdevis]); - if(!empty($produits)) { + if(!empty($produits)){ $clientId = $produits[0]["id_client"]; $client = $this->getClientById($clientId); - foreach($produits as &$produit) { - $productPrice = $this->getProductPriceByClientGroupId($client['fk_client_group_id'], $produit['pid']); + foreach($produits as &$produit){ + $productPrice = $this->getProductPriceByClientGroupId($client['fk_client_group_id'],$produit['pid']); $produit['prix_unitaire'] = $productPrice ?? $produit['prix_unitaire']; } } return json_encode($produits); } - public function getListArticle($numdevis, $idNextcloud) - { + public function getListArticle($numdevis, $idNextcloud) { + $sql = "SELECT ".$this->tableprefix."article.id as aid,".$this->tableprefix."article_devis.id as adid, reference, description,".$this->tableprefix."article_devis.comment, quantite, prix_unitaire FROM ".$this->tableprefix."article, ".$this->tableprefix."devis, ".$this->tableprefix."article_devis WHERE ".$this->tableprefix."article.id = article_id AND ".$this->tableprefix."devis.id = devis_id AND ".$this->tableprefix."devis.id = ?"; return $this->execSQL($sql, array($numdevis)); } - + /** * Récupère le statut TVA du client associé au devis * @param int $numdevis ID du devis @@ -964,36 +967,36 @@ class Bdd return isset($clientData[0]->is_tva) ? (int)$clientData[0]->is_tva : 1; // Par défaut TVA = 1 si non trouvé } - public function getArticles($idNextcloud) - { + public function getArticles($idNextcloud){ + $sql = "SELECT * FROM ".$this->tableprefix."article"; return $this->execSQL($sql, array()); } - private function getFunctionCall() - { + private function getFunctionCall(){ + $trace = debug_backtrace(); return $trace[2]['function']; } - public function getListObservations($numdefunt, $idNextcloud) - { + public function getListObservations($numdefunt, $idNextcloud) { + $sql = "SELECT ".$this->tableprefix."obs_defunt.id as odid, designation, commentaire FROM " .$this->tableprefix."obs_defunt, ".$this->tableprefix."defunt WHERE ".$this->tableprefix."defunt.id = defunt_id AND ".$this->tableprefix."defunt.id = ?"; return $this->execSQL($sql, array($numdefunt)); } - public function getListBijoux($numdefunt, $idNextcloud) - { + public function getListBijoux($numdefunt, $idNextcloud) { + $sql = "SELECT ".$this->tableprefix."bijou_defunt.id as bdid, designation, commentaire,photo,photo_name,taker_name FROM " .$this->tableprefix."bijou_defunt, ".$this->tableprefix."defunt WHERE ".$this->tableprefix."defunt.id = defunt_id AND ".$this->tableprefix."defunt.id = ?"; return $this->execSQL($sql, array($numdefunt)); } - public function getListHypodermiques($numdefunt, $idNextcloud) - { + public function getListHypodermiques($numdefunt, $idNextcloud) { + $sql = "SELECT ".$this->tableprefix."hypo_defunt.id as hdid, designation, qte, endroit FROM " .$this->tableprefix."hypo_defunt, ".$this->tableprefix."defunt WHERE ".$this->tableprefix."defunt.id = defunt_id AND ".$this->tableprefix."defunt.id = ?"; @@ -1004,12 +1007,12 @@ class Bdd * INSERT client * @$idnextcloud */ - public function insertClient($idNextcloud) - { + public function insertClient($idNextcloud){ + $sql = "INSERT INTO `".$this->tableprefix."client` (`id_nextcloud`,`nom`,`prenom`,`legal_one`,`entreprise`,`telephone`,`mail`,`adresse`) VALUES (?,?,?,?,?,?,?,?)"; - $this->execSQLNoData( - $sql, - array($idNextcloud, + $this->execSQLNoData($sql,array($idNextcloud, + + $this->l->t('Last name'), $this->l->t('First name'), $this->l->t('Limited company'), @@ -1018,33 +1021,33 @@ class Bdd $this->l->t('Email'), $this->l->t('Address') ) - ); + ); return true; } /** - * + * */ - public function insertThanatopracteur($idNextcloud) - { + public function insertThanatopracteur($idNextcloud) { + $sql = "INSERT INTO `".$this->tableprefix."thanato` (`id_nextcloud`,`nom`,`prenom`,`reference`,`date_habilitation`) VALUES (?,?,?,?,NOW())"; - $this->execSQLNoData( - $sql, - array($idNextcloud, + $this->execSQLNoData($sql,array($idNextcloud, + + $this->l->t('Last name'), $this->l->t('First name'), 'reference', ) - ); + ); return true; } /** * Insert lieu */ - public function insertTrajet($id_thanato, $mois, $annee, $idNextcloud) - { - $last = 0; + public function insertTrajet($id_thanato, $mois, $annee, $idNextcloud){ + + $last=0; $last = $this->lastinsertid("trajet", $idNextcloud) + 1; // $sql = "INSERT INTO `".$this->tableprefix."trajet` ( `id_nextcloud`, @@ -1056,7 +1059,7 @@ class Bdd // `id_lieu_arrivee`, // `distance`, // `user_id` - // ) + // ) // VALUES (?,NOW(),?,?,0,0,0,0,?);"; $sql = "INSERT INTO `".$this->tableprefix."trajet` ( `id_nextcloud`, `date`, @@ -1074,9 +1077,9 @@ class Bdd /** * Insert lieu */ - public function insertTrajetdetails($numtrajet, $idNextcloud) - { - $last = 0; + public function insertTrajetdetails($numtrajet, $idNextcloud){ + + $last=0; $last = $this->lastinsertid("ligne_trajet", $idNextcloud) + 1; $rang = $this->get_last_rang_trajetdetails($numtrajet, $idNextcloud); @@ -1096,14 +1099,14 @@ class Bdd `user_id` ) VALUES (?,?,0,0,?,?,'','lieu',?);"; - $this->execSQLNoData($sql, array($idNextcloud,$trajetdetails[sizeof($trajetdetails) - 1]->date,$numtrajet,$rang + 1,$last)); + $this->execSQLNoData($sql, array($idNextcloud,$trajetdetails[sizeof($trajetdetails)-1]->date,$numtrajet,$rang+1,$last)); return true; } - public function insertTrajetdetails_h2f($numtrajet, $date, $idNextcloud, $lieuSiege = "siege", $devisId = 0) - { + public function insertTrajetdetails_h2f($numtrajet, $date, $idNextcloud,$lieuSiege = "siege",$devisId = 0){ + $lieuSiege = strtolower($lieuSiege); - $last = 0; + $last=0; $last = $this->lastinsertid("ligne_trajet", $idNextcloud) + 1; $rang = $this->get_last_rang_trajetdetails($numtrajet, $idNextcloud); @@ -1116,7 +1119,7 @@ class Bdd $response_h2f = $this->execSQL($sql_h2f, array($lieuSiege)); $h2f = json_decode($response_h2f)[0]; - $id_h2f = ($h2f != null) ? $h2f->id : 0; + $id_h2f = ($h2f!=NULL)?$h2f->id:0; $sql = "INSERT INTO `".$this->tableprefix."ligne_trajet` ( `id_nextcloud`, `date`, @@ -1129,16 +1132,16 @@ class Bdd `user_id` ) VALUES (?,?,?,?,?,?,'','siege',?);"; - $this->execSQLNoData($sql, array($idNextcloud,$date,$devisId,$id_h2f,$numtrajet,$rang + 1,$last)); + $this->execSQLNoData($sql, array($idNextcloud,$date,$devisId,$id_h2f,$numtrajet,$rang+1,$last)); return true; } /** * Insert lieu */ - public function insertTrajetdetails_byDevis($numtrajet, $devis, $idNextcloud) - { - $last = 0; + public function insertTrajetdetails_byDevis($numtrajet, $devis, $idNextcloud){ + + $last=0; $last = $this->lastinsertid("ligne_trajet", $idNextcloud) + 1; $rang = $this->get_last_rang_trajetdetails($numtrajet, $idNextcloud); @@ -1147,8 +1150,8 @@ class Bdd $trajetdetails = json_decode($this->getTrajetsdetails_orderByDate($numtrajet, $idNextcloud)); - $id_client = ($devis->id_client != null) ? $devis->id_client : 0; - $id_lieu = ($devis->id_lieu != null) ? $devis->id_lieu : 0; + $id_client = ($devis->id_client != NULL)?$devis->id_client:0; + $id_lieu = ($devis->id_lieu != NULL)?$devis->id_lieu:0; $sql = "INSERT INTO `".$this->tableprefix."ligne_trajet` ( `id_nextcloud`, `date`, @@ -1162,27 +1165,27 @@ class Bdd `user_id` ) VALUES (?,?,?,?,?,?,?,'','devis',?);"; - $this->execSQLNoData($sql, array($idNextcloud,$devis->date,$devis->devisid,$id_client,$id_lieu,$numtrajet,$rang + 1,$last)); + $this->execSQLNoData($sql, array($idNextcloud,$devis->date,$devis->devisid,$id_client,$id_lieu,$numtrajet,$rang+1,$last)); return true; } - public function get_last_rang_trajetdetails($numtrajet, $idNextcloud) - { + public function get_last_rang_trajetdetails($numtrajet, $idNextcloud) { + $trajetdetails = json_decode($this->getTrajetsdetails($numtrajet, $idNextcloud)); $rang_max = 0; foreach ($trajetdetails as $key => $details) { - if($rang_max <= $details->rang) { - $rang_max = $details->rang; - } + if($rang_max<=$details->rang) $rang_max = $details->rang; + } + return $rang_max; } /** * Insert Defunt */ - public function insertDefunt($idNextcloud) - { + public function insertDefunt($idNextcloud) { + $sql = "INSERT INTO `".$this->tableprefix."defunt` ( `id_nextcloud`, `nom`, `sexe`, `date_naissance`, `ref_pacemaker`, `date`, `corpulence`, `observations_corps`, `observations_generales` @@ -1194,8 +1197,8 @@ class Bdd /** * Insert Defunt */ - public function insertDefuntByName($name) - { + public function insertDefuntByName($name) { + $sql = "INSERT INTO `".$this->tableprefix."defunt` ( `id_nextcloud`, `nom`, `sexe`, `date_naissance`, `ref_pacemaker`, `date`, `corpulence`, `observations_corps`, `observations_generales` @@ -1204,104 +1207,104 @@ class Bdd return true; } - public function insertDefuntByNameAndReturnId($name) - { + public function insertDefuntByNameAndReturnId($name) { + $this->insertDefuntByName($name); return $this->getLastDefuntIdByName($name); } - public function getLastDefuntIdByName($name) - { + public function getLastDefuntIdByName( $name ) { + $sql = "SELECT max(id) as LAST_INSERT_ID FROM ".$this->tableprefix."defunt WHERE nom = ?"; - $res = $this->execSQLNoJsonReturn($sql, array($name)); - if($res) { + $res = $this->execSQLNoJsonReturn($sql,array($name)); + if($res){ return $res[0]['LAST_INSERT_ID']; } return null; } - public function getLastClientIdByName($name) - { + public function getLastClientIdByName($name) { + $sql = "SELECT max(id) as LAST_INSERT_ID FROM ".$this->tableprefix."client WHERE nom = ?"; - $res = $this->execSQLNoJsonReturn($sql, array($name)); - if($res) { + $res = $this->execSQLNoJsonReturn($sql,array($name)); + if($res){ return $res[0]['LAST_INSERT_ID']; } return null; } - public function getLastLocationIdByName($name) - { + public function getLastLocationIdByName($name) { + $sql = "SELECT max(id) as LAST_INSERT_ID FROM ".$this->tableprefix."lieu WHERE nom = ?"; - $res = $this->execSQLNoJsonReturn($sql, array($name)); - if($res) { + $res = $this->execSQLNoJsonReturn($sql,array($name)); + if($res){ return $res[0]['LAST_INSERT_ID']; } return null; } - public function getOrCreateThanatoIdByLastName($name) - { + public function getOrCreateThanatoIdByLastName($name){ + $thanatoId = $this->getLastThanatoIdByName($name); - if($thanatoId == null) { + if($thanatoId == null){ $this->createThanatoByLastName($name); $thanatoId = $this->getLastThanatoIdByName($name); } return $thanatoId; } - private function createThanatoByLastName($name) - { + private function createThanatoByLastName($name){ + $idNextcloud = "admin"; $sql = "INSERT INTO `".$this->tableprefix."thanato` (`id_nextcloud`,`nom`,`prenom`,`reference`,`date_habilitation`) VALUES (?,?,?,?,NOW())"; - $this->execSQLNoData( - $sql, - array($idNextcloud, + $this->execSQLNoData($sql,array($idNextcloud, + + $name, $this->l->t('First name'), 'reference', ) - ); + ); return true; } - public function getLastThanatoIdByName($name) - { + public function getLastThanatoIdByName($name) { + $sql = "SELECT max(id) as LAST_INSERT_ID FROM ".$this->tableprefix."thanato WHERE nom = ?"; - $res = $this->execSQLNoJsonReturn($sql, array($name)); - if($res) { + $res = $this->execSQLNoJsonReturn($sql,array($name)); + if($res){ return $res[0]['LAST_INSERT_ID']; } return null; } - public function getFirstThanatoIdByName($name) - { + public function getFirstThanatoIdByName($name) { + $sql = "SELECT min(id) as FIRST_INSERT_ID FROM ".$this->tableprefix."thanato WHERE nom = ?"; - $res = $this->execSQLNoJsonReturn($sql, array($name)); - if($res) { + $res = $this->execSQLNoJsonReturn($sql,array($name)); + if($res){ return $res[0]['FIRST_INSERT_ID']; } return null; } - public function getThanatoIdByUserUuid($userUuid) - { + public function getThanatoIdByUserUuid($userUuid){ + $sql = "SELECT min(id) as FIRST_INSERT_ID FROM ".$this->tableprefix."thanato WHERE fk_user_uuid = ?"; - $res = $this->execSQLNoJsonReturn($sql, array($userUuid)); - if($res) { + $res = $this->execSQLNoJsonReturn($sql,array($userUuid)); + if($res){ return $res[0]['FIRST_INSERT_ID']; } return null; @@ -1310,9 +1313,9 @@ class Bdd /** * Insert lieu */ - public function insertLieu($idNextcloud) - { - $last = 0; + public function insertLieu($idNextcloud){ + + $last=0; $last = $this->lastinsertid("lieu", $idNextcloud) + 1; // $sql = "INSERT INTO `".$this->tableprefix."lieu` ( `id_nextcloud`, @@ -1326,7 +1329,7 @@ class Bdd // `depart`, // `arrivee`, // `user_id` - // ) + // ) // VALUES (?,?,NOW(),0,'',?,?,0,'','',?);"; $sql = "INSERT INTO `".$this->tableprefix."lieu` ( `id_nextcloud`, @@ -1343,9 +1346,9 @@ class Bdd /** * Insert quote */ - public function insertDevis($idNextcloud) - { - $last = 0; + public function insertDevis($idNextcloud){ + + $last=0; $last = $this->lastinsertid("devis", $idNextcloud) + 1; $sql = "INSERT INTO `".$this->tableprefix."devis` ( `date`, @@ -1372,40 +1375,41 @@ class Bdd return true; } - private function getLastDevisNumberByMonthAndYear($month, $year) - { + private function getLastDevisNumberByMonthAndYear($month,$year){ + $sql = "SELECT - max(devis.devis_number) as LAST_DEVIS_NUMBER, devis.date FROM " + max(devis.devis_number) as LAST_DEVIS_NUMBER, devis.date FROM " . $this->tableprefix."devis as devis WHERE YEAR(devis.date) = ? AND MONTH(devis.date) = ?;"; - $res = $this->execSQLNoJsonReturn($sql, array($year,$month)); + $res = $this->execSQLNoJsonReturn($sql,array($year,$month)); $lastNumber = 0; - if(!empty($res)) { + if(!empty($res)){ $lastNumber = $res[0]['LAST_DEVIS_NUMBER']; } return $lastNumber; } - public function insertDevisFromVCalendarAndReturnId($thanatoId, $clientId, $locationId, $defuntId, $calendarUuid = self::DEFAULT_CALENDAR_UUID_FOR_DEVIS, $date = null, $devisComment = "Commentaire") - { + public function insertDevisFromVCalendarAndReturnId($thanatoId,$clientId,$locationId,$defuntId,$calendarUuid = self::DEFAULT_CALENDAR_UUID_FOR_DEVIS,$date = null,$devisComment = "Commentaire"){ - if($date == null) { + + if($date == null){ $dateTime = new Datetime(); $date = $dateTime->format('Y-m-d'); - } else { + } + else{ $dateTime = new DateTime($date); } $idNextcloud = "admin"; - $last = 0; + $last=0; $last = $this->lastinsertid("devis", "admin") + 1; $dateMonth = $dateTime->format('m'); $dateYear = $dateTime->format('Y'); - $devisLastNumber = $this->getLastDevisNumberByMonthAndYear($dateMonth, $dateYear); + $devisLastNumber = $this->getLastDevisNumberByMonthAndYear($dateMonth,$dateYear); $devisNumber = $devisLastNumber + 1; - $devisFullNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($dateTime, $devisNumber, 'DEV'); + $devisFullNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($dateTime,$devisNumber,'DEV'); $sql = "INSERT INTO `".$this->tableprefix."devis` ( `date`, `id_nextcloud`, @@ -1422,9 +1426,9 @@ class Bdd `devis_full_number` ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?);"; - $this->execSQLNoData( - $sql, - array( + $this->execSQLNoData($sql, array( + + $date, $idNextcloud, $calendarUuid, @@ -1440,30 +1444,30 @@ class Bdd $devisFullNumber ) ); - - return $this->getLastDevisIdFromVCalendarProperty($thanatoId, $clientId, $locationId, $defuntId, $calendarUuid); + + return $this->getLastDevisIdFromVCalendarProperty($thanatoId,$clientId,$locationId,$defuntId,$calendarUuid); } - public function getLastDevisIdFromVCalendarProperty($thanatoId, $clientId, $locationId, $defuntId, $calendarUuid = self::DEFAULT_CALENDAR_UUID_FOR_DEVIS) - { + public function getLastDevisIdFromVCalendarProperty($thanatoId,$clientId,$locationId,$defuntId,$calendarUuid=self::DEFAULT_CALENDAR_UUID_FOR_DEVIS){ + $sql = "SELECT max(id) as LAST_INSERT_ID FROM ".$this->tableprefix."devis WHERE id_defunt = ? AND id_lieu = ? AND id_client = ? AND id_thanato = ? AND num = ?"; - $res = $this->execSQLNoJsonReturn($sql, array( + $res = $this->execSQLNoJsonReturn($sql,array( $defuntId, $locationId, $clientId, $thanatoId, $calendarUuid )); - if($res) { + if($res){ return $res[0]['LAST_INSERT_ID']; } - return null; + return null; } - public function getArticlesIdFromArticlesNameArray(array $articles): array - { + public function getArticlesIdFromArticlesNameArray(array $articles): array { + $articleIds = []; foreach ($articles as $article) { $sql = "SELECT id FROM ".$this->tableprefix."produit WHERE description = ?"; @@ -1475,19 +1479,19 @@ class Bdd return $articleIds; } - public function insertDevisArticleFromDevisIdAndArticlesIdArray($devisId, $articleIds) - { + public function insertDevisArticleFromDevisIdAndArticlesIdArray($devisId, $articleIds) { + if (!empty($articleIds)) { $idNextcloud = "admin"; foreach ($articleIds as $articleId) { - $this->insertDevisArticle(devisId: $devisId, articleId: $articleId, idNextcloud: $idNextcloud); + $this->insertDevisArticle(devisId: $devisId, articleId: $articleId,idNextcloud: $idNextcloud); } } return true; } - private function insertDevisArticle($devisId, $articleId, $idNextcloud) - { + private function insertDevisArticle($devisId,$articleId,$idNextcloud){ + $sql = "INSERT INTO ".$this->tableprefix."produit_devis (devis_id, produit_id, quantite, discount, comment,id_nextcloud) VALUES (?, ?, 1, 0, '-',?)"; $this->execSQLNoData($sql, array($devisId, $articleId,$idNextcloud)); return true; @@ -1496,29 +1500,29 @@ class Bdd /** * Insert invoice */ - public function insertFacture($idNextcloud) - { + public function insertFacture($idNextcloud){ + $last = 0; $last = $this->lastNumFacture($idNextcloud); - $pref = $this->execSQLNoJsonReturn("SELECT * FROM ".$this->tableprefix."configuration WHERE id_nextcloud LIKE ?", array($idNextcloud)); + $pref = $this->execSQLNoJsonReturn("SELECT * FROM ".$this->tableprefix."configuration WHERE id_nextcloud LIKE ?",array($idNextcloud)); $sql = "INSERT INTO `".$this->tableprefix."facture` (`date`,`id_nextcloud`,`num`,`date_paiement`,`type_paiement`,`id_devis`,`user_id`, `version`,`facture_number`) VALUES (?,?,?,NOW(),?,0,?,?,?);"; $date_temp = new DateTime(); $date = $date_temp->format('Y-m-d'); $dateMonth = $date_temp->format('m'); $dateYear = $date_temp->format('Y'); - $factureLastNumber = $this->getLastFactureNumberByMonthAndYear($dateMonth, $dateYear); + $factureLastNumber = $this->getLastFactureNumberByMonthAndYear($dateMonth,$dateYear); $factureNumber = $factureLastNumber + 1; - $factureFullNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($date_temp, $factureNumber, 'FAC'); - + $factureFullNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($date_temp,$factureNumber,'FAC'); + $datesplit = explode('-', $date); - $this->execSQLNoData($sql, array($date , $idNextcloud, $factureFullNumber,"Comptant",$last + 1,"Ajouter un lieu",$factureNumber)); + $this->execSQLNoData($sql, array($date , $idNextcloud, $factureFullNumber,"Comptant",$last+1,"Ajouter un lieu",$factureNumber)); return $last; } - private function getDevisIdListFilteredByMentionAndDevisListId($mentionsFilter, $devisListId) - { + private function getDevisIdListFilteredByMentionAndDevisListId($mentionsFilter,$devisListId){ + if (empty($devisListId)) { return []; } @@ -1529,23 +1533,23 @@ class Bdd WHERE devis.id IN ($placeholders) AND mentions IN ($mentionsFilterPlaceholders)"; - $result = $this->execSQLNoJsonReturn($sql, array_merge( - $devisListId, - $mentionsFilter - )); + $result = $this->execSQLNoJsonReturn($sql,array_merge( + $devisListId, + $mentionsFilter)); + return $result; } - public function insertFactureForeEachDevisId($idNextCloud, $devisIdArray, $facturationDate = null) - { + public function insertFactureForeEachDevisId($idNextCloud,$devisIdArray,$facturationDate = null){ + $mentionsFilter = [ DevisMentionConstant::NEW, DevisMentionConstant::MENTION ]; - $devisIdListFiltered = $this->getDevisIdListFilteredByMentionAndDevisListId($mentionsFilter, $devisIdArray); + $devisIdListFiltered = $this->getDevisIdListFilteredByMentionAndDevisListId($mentionsFilter,$devisIdArray); $factureIdsGenerated = []; - foreach($devisIdListFiltered as $devis) { - $factureId = $this->insertFactureByDevisId($idNextCloud, $devis['id'], $devis['devis_date'], $facturationDate); + foreach($devisIdListFiltered as $devis){ + $factureId = $this->insertFactureByDevisId($idNextCloud,$devis['id'],$devis['devis_date'],$facturationDate); $factureIdsGenerated[] = $factureId; } return $factureIdsGenerated; @@ -1554,156 +1558,157 @@ class Bdd /** * Insert invoice with a devis */ - public function insertFactureByDevisId($idNextcloud, $devisId, $devisDate = null, $facturationDate = null) - { - if($facturationDate == null || $facturationDate == "") { + public function insertFactureByDevisId($idNextcloud,$devisId,$devisDate = null,$facturationDate = null){ + + if($facturationDate == null || $facturationDate == ""){ $datetimeNow = new Datetime(); $facturationDate = DateHelpers::GetLastDayOfTheMonthOfADate($datetimeNow); - $facturationDate = $facturationDate->format('Y-m-d'); - } else { - $facturationDate = Datetime::createFromFormat('Y-m-d', $facturationDate); - $facturationDate = $facturationDate->format('Y-m-d'); + $facturationDate = $facturationDate->format('Y-m-d'); + } + else{ + $facturationDate = Datetime::createFromFormat('Y-m-d',$facturationDate); + $facturationDate = $facturationDate->format('Y-m-d'); } $devisDatetime = new Datetime(); - if($devisDate != null) { + if($devisDate != null){ $devisDatetime = new Datetime($devisDate); } $factureDate = $devisDatetime->format('Y-m-d'); $factureNumber = $this->getFactureNumberByDate($devisDatetime); $facturePrefix = "FAC"; $devis = json_decode($this->getOneDevis($devisId, $idNextcloud))[0]; - $isDevisNegative = $this->isDevisNegative($devisId, clientId: $devis->clientid); - if($isDevisNegative) { + $isDevisNegative = $this->isDevisNegative($devisId,clientId: $devis->clientid); + if($isDevisNegative){ $facturePrefix = "AVO"; } - - $fullFactureNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($devisDatetime, $factureNumber, $facturePrefix); + + $fullFactureNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($devisDatetime,$factureNumber,$facturePrefix); $last = 0; $last = $this->lastNumFacture($idNextcloud); $sql = "INSERT INTO `".$this->tableprefix."facture` (`date`,`id_nextcloud`,`num`,`date_paiement`,`type_paiement`,`id_devis`,`user_id`, `version`,`facture_number`) VALUES (?,?,?,?,?,?,?,?,?);"; - $this->execSQLNoData( - $sql, - array( - $factureDate , - $idNextcloud, + $this->execSQLNoData($sql, array( + + + $factureDate , + $idNextcloud, $fullFactureNumber, $facturationDate, "Comptant", $devisId, - $last + 1, + $last+1, "Ajouter un lieu", $factureNumber) ); $factureId = $this->getFactureIdByDevisId($devisId); //update devis status - $this->gestion_update('devis', 'mentions', DevisMentionConstant::FACTURED_FORMATTED, $devisId, $idNextcloud); + $this->gestion_update('devis','mentions',DevisMentionConstant::FACTURED_FORMATTED,$devisId,$idNextcloud); return $factureId; } - private function getFactureIdByDevisId($devisId) - { + private function getFactureIdByDevisId($devisId){ + $sql = "SELECT facture.id FROM ".$this->tableprefix."facture as facture WHERE facture.id_devis = ? ORDER BY facture.id DESC;"; $facture = $this->execSQLNoJsonReturn( - $sql, - [$devisId] - ); - if(!empty($facture)) { + $sql, + [$devisId]); + + if(!empty($facture)){ return $facture[0]['id']; } return null; } + + public function insertProduit($idNextcloud){ - public function insertProduit($idNextcloud) - { $sql = "INSERT INTO `".$this->tableprefix."produit` (`id_nextcloud`,`reference`,`description`,`prix_unitaire`) VALUES (?,?,?,0);"; $this->execSQLNoData($sql, array($idNextcloud,$this->l->t('Reference'),$this->l->t('Designation'))); return true; } - public function insertProduitDevis($id, $idNextcloud) - { + public function insertProduitDevis($id,$idNextcloud){ + $res = $this->searchMaxIdProduit($idNextcloud); $sql = "INSERT INTO `".$this->tableprefix."produit_devis` (`devis_id`, `id_nextcloud`,`produit_id`,`quantite`,`discount`) VALUES (?,?,?,1,0);"; - $this->execSQLNoData($sql, array($id,$idNextcloud,($res[0]['id'] == null) ? 0 : $res[0]['id'])); + $this->execSQLNoData($sql, array($id,$idNextcloud,($res[0]['id']==NULL)?0:$res[0]['id'])); return true; } - public function insertArticle($idNextcloud) - { + public function insertArticle($idNextcloud){ + $sql = "INSERT INTO `".$this->tableprefix."article` (`id_nextcloud`,`reference`,`description`,`prix_unitaire`) VALUES (?,?,?,0);"; $this->execSQLNoData($sql, array($idNextcloud,$this->l->t('Reference'),$this->l->t('Designation'))); return true; } - public function insertArticleDevis($id, $idNextcloud) - { + public function insertArticleDevis($id,$idNextcloud){ + $res = $this->searchMaxIdArticle($idNextcloud); $sql = "INSERT INTO `".$this->tableprefix."article_devis` (`devis_id`, `id_nextcloud`,`article_id`,`quantite`,`discount`, `comment`) VALUES (?,?,?,1,0,'-');"; - $this->execSQLNoData($sql, array($id,$idNextcloud,($res[0]['id'] == null) ? 0 : $res[0]['id'])); + $this->execSQLNoData($sql, array($id,$idNextcloud,($res[0]['id']==NULL)?0:$res[0]['id'])); return true; } - public function insertObservationDefunt($id, $idNextcloud) - { + public function insertObservationDefunt($id,$idNextcloud){ + $sql = "INSERT INTO `".$this->tableprefix."obs_defunt` (`defunt_id`, `id_nextcloud`,`designation`,`commentaire`) VALUES (?,?,?,?);"; $this->execSQLNoData($sql, array($id,$idNextcloud,'inserer une observation', 'inserer un commentaire')); return true; } - public function insertBijouDefunt($id, $idNextcloud) - { + public function insertBijouDefunt($id,$idNextcloud){ + $sql = "INSERT INTO `".$this->tableprefix."bijou_defunt` (`defunt_id`, `id_nextcloud`,`designation`,`commentaire`) VALUES (?,?,?,?);"; $this->execSQLNoData($sql, array($id,$idNextcloud,'', '')); return true; } - public function insertHypoDefunt($id, $idNextcloud) - { + public function insertHypoDefunt($id,$idNextcloud){ + $sql = "INSERT INTO `".$this->tableprefix."hypo_defunt` (`defunt_id`, `id_nextcloud`,`designation`,`qte`, `endroit`) VALUES (?,?,?,?,?);"; $this->execSQLNoData($sql, array($id,$idNextcloud,'', 0, '')); return true; } - public function searchMaxIdProduit($idNextcloud) - { + public function searchMaxIdProduit($idNextcloud){ + // $sqlSearchMax = "SELECT MIN(id) as id FROM `".$this->tableprefix."produit` WHERE id_nextcloud = ?"; $sqlSearchMax = "SELECT MIN(id) as id FROM `".$this->tableprefix."produit`"; // return $this->execSQLNoJsonReturn($sqlSearchMax, array($idNextcloud)); return $this->execSQLNoJsonReturn($sqlSearchMax, array()); } - public function searchMaxIdArticle($idNextcloud) - { + public function searchMaxIdArticle($idNextcloud){ + $sqlSearchMax = "SELECT MIN(id) as id FROM `".$this->tableprefix."article`"; return $this->execSQLNoJsonReturn($sqlSearchMax, array()); } - public function insertBibliotheque($idNextcloud) - { + public function insertBibliotheque($idNextcloud){ + $sql = "INSERT INTO `".$this->tableprefix."bibliotheque` (`id_nextcloud`,`contenu`) VALUES (?,?);"; $this->execSQLNoData($sql, array($idNextcloud,'inserer un texte ici')); return true; } - private function isDevisNegative($devisId, $clientId) - { + private function isDevisNegative($devisId,$clientId){ + $sql = "SELECT produit_devis.quantite,produit.prix_unitaire,produit.id FROM ".$this->tableprefix."produit_devis as produit_devis LEFT JOIN ".$this->tableprefix."produit as produit ON produit_devis.produit_id = produit.id WHERE produit_devis.devis_id = ?;"; - $devisProduits = $this->execSQLNoJsonReturn($sql, array($devisId)); + $devisProduits = $this->execSQLNoJsonReturn($sql,array($devisId)); $total = 0; - if(!empty($devisProduits)) { - foreach($devisProduits as $currentProduit) { - if($currentProduit['id'] != null) { - $produitPrice = $this->getProductPriceByClient($currentProduit['id'], $clientId, $currentProduit['prix_unitaire']); + if(!empty($devisProduits)){ + foreach($devisProduits as $currentProduit){ + if($currentProduit['id'] != null){ + $produitPrice = $this->getProductPriceByClient($currentProduit['id'],$clientId,$currentProduit['prix_unitaire']); $total += $produitPrice * $currentProduit['quantite']; } } @@ -1711,120 +1716,122 @@ class Bdd return $total < 0; } - private function getProduitDevisById($produitDevisId) - { + private function getProduitDevisById($produitDevisId){ + $sql = "SELECT * FROM ".$this->tableprefix."produit_devis as produit_devis WHERE produit_devis.id = ?;"; - $result = $this->execSQLNoJsonReturn($sql, [$produitDevisId]); - ; + $result = $this->execSQLNoJsonReturn($sql,[$produitDevisId]);; - if(!empty($result)) { + + if(!empty($result)){ return $result[0]; } return null; } - private function getFactureByDevisId($devisId) - { + private function getFactureByDevisId($devisId){ + $sql = "SELECT * FROM ".$this->tableprefix."facture as facture WHERE facture.id_devis = ?"; - $result = $this->execSQLNoJsonReturn($sql, [$devisId]); - if(!empty($result)) { + $result = $this->execSQLNoJsonReturn($sql,[$devisId]); + if(!empty($result)){ return $result[0]; } return null; } - + /** * UPDATE */ - public function gestion_update($table, $column, $data, $id, $idNextcloud) - { - if(in_array($table, $this->whiteTable) && in_array($column, $this->whiteColumn)) { - if(strcmp($table, "facture") == 0 && strcmp($column, "date_paiement") == 0) { + public function gestion_update($table, $column, $data, $id, $idNextcloud){ + + if(in_array($table, $this->whiteTable) && in_array($column, $this->whiteColumn)){ + if(strcmp($table, "facture")==0 && strcmp($column, "date_paiement")==0) { $facture = $this->getFactureByFactureId($id); - if($facture['date_paiement'] != $data) { - $facturationDatetime = Datetime::createFromFormat('Y-m-d', $data); + if($facture['date_paiement'] != $data){ + $facturationDatetime = Datetime::createFromFormat('Y-m-d',$data); $factureNumber = $this->getFactureNumberByDate($facturationDatetime); $facturePrefix = "FAC"; - if($facture['id_devis']) { + if($facture['id_devis']){ $devis = json_decode($this->getOneDevis($facture['id_devis'], $idNextcloud))[0]; - $isDevisNegative = $this->isDevisNegative($facture['id_devis'], $devis->clientid); - if($isDevisNegative) { + $isDevisNegative = $this->isDevisNegative($facture['id_devis'],$devis->clientid); + if($isDevisNegative){ $facturePrefix = "AVO"; } } - $fullFactureNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($facturationDatetime, $factureNumber, $facturePrefix); + $fullFactureNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($facturationDatetime,$factureNumber,$facturePrefix); $sql = "UPDATE ".$this->tableprefix.$table." SET `facture_number`= ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($factureNumber, $id)); $sql = "UPDATE ".$this->tableprefix.$table." SET $column = ?, `num`= ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($data, $fullFactureNumber, $id)); } - - } elseif(strcmp($table, "facture") == 0 && strcmp($column, "id_devis") == 0) { - + + } else if(strcmp($table, "facture")==0 && strcmp($column, "id_devis")==0) { + $facture = json_decode($this->getOneFacture($id, $idNextcloud))[0]; $devis = json_decode($this->getOneDevis(htmlentities(rtrim($data)), $idNextcloud))[0]; $sql = "UPDATE ".$this->tableprefix.$table." SET $column = ?, `date`= ?, `version`= ? WHERE `id` = ?"; $this->execSQLNoData($sql, array(htmlentities(rtrim($data)), $devis->date, html_entity_decode($devis->version),$id)); $facturePrefix = "FAC"; $factureNumber = $facture->facture_number; - $isDevisNegative = $this->isDevisNegative($devis->devisid, $devis->clientid); - if($isDevisNegative) { + $isDevisNegative = $this->isDevisNegative($devis->devisid,$devis->clientid); + if($isDevisNegative){ $facturePrefix = "AVO"; } $facturationDatetime = new Datetime($facture->date); - $fullFactureNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($facturationDatetime, $factureNumber, $facturePrefix); + $fullFactureNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($facturationDatetime,$factureNumber,$facturePrefix); $sql = "UPDATE ".$this->tableprefix.$table." SET `num`= ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($fullFactureNumber, $id)); - } elseif(strcmp($table, "lieu") == 0 && (strcmp($column, "latitude") == 0 || strcmp($column, "longitude") == 0)) { - + } else if(strcmp($table, "lieu")==0 && (strcmp($column, "latitude")==0 || strcmp($column, "longitude")==0)) { + $lieu = json_decode($this->getLieu($id, $idNextcloud))[0]; - if(floatval($data) != 0) { + if(floatval($data)!=0) { $sql = "UPDATE ".$this->tableprefix.$table." SET $column = ? WHERE `id` = ?"; - $this->execSQLNoData($sql, array(htmlentities(rtrim(floatval($data))), $id)); + $this->execSQLNoData($sql, array(htmlentities(rtrim(floatval($data))), $id)); $lieu = json_decode($this->getLieu($id, $idNextcloud))[0]; - if(floatval($lieu->latitude) != 0 && floatval($lieu->longitude) != 0) { + if(floatval($lieu->latitude)!=0 && floatval($lieu->longitude)!=0) { $adresse = $this->recuperer_adresse(floatval($lieu->latitude), floatval($lieu->longitude)); $sql = "UPDATE ".$this->tableprefix.$table." SET adresse = ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($adresse, $id)); } } - - } elseif(strcmp($table, "devis") == 0 && (strcmp($column, "id_lieu") == 0 || strcmp($column, "date") == 0 || strcmp($column, "id_client") == 0 || strcmp($column, "id_thanato") == 0)) { + + } else if(strcmp($table, "devis")==0 && (strcmp($column, "id_lieu")==0 || strcmp($column, "date")==0 || strcmp($column, "id_client")==0 || strcmp($column, "id_thanato")==0)) { $devis = json_decode($this->getOneDevis($id, $idNextcloud))[0]; $this->update_lieu_date_devis($devis, $column, htmlentities(rtrim($data)), $idNextcloud); - - } elseif(strcmp($table, "ligne_trajet") == 0 && (strcmp($column, "id_devis") == 0 || strcmp($column, "date") == 0 || strcmp($column, "id_lieu") == 0 || strcmp($column, "rang") == 0)) { + + } else if(strcmp($table, "ligne_trajet")==0 && (strcmp($column, "id_devis")==0 || strcmp($column, "date")==0 || strcmp($column, "id_lieu")==0 || strcmp($column, "rang")==0)) { $ligne_trajet = json_decode($this->getOneTrajetdetails($id, $idNextcloud))[0]; $this->update_lieu_date_devis_rang_ligneTrajet($ligne_trajet, $column, htmlentities(rtrim($data)), $idNextcloud); - } elseif(strcmp($table, "produit_devis") == 0 && (strcmp($column, "quantite") == 0)) { + } + else if(strcmp($table,"produit_devis") == 0 && (strcmp($column,"quantite") == 0)){ $sql = "UPDATE ".$this->tableprefix.$table." SET $column = ? WHERE `id` = ?"; $this->execSQLNoData($sql, array(trim(string: $data), $id)); $produitDevis = $this->getProduitDevisById($id); - if($produitDevis) { + if($produitDevis){ $devisId = $produitDevis['devis_id']; $devis = json_decode($this->getOneDevis($devisId, $idNextcloud))[0]; - if($devis) { + if($devis){ $facture = $this->getFactureByDevisId($devisId); - $isDevisNegative = $this->isDevisNegative($devisId, $devis->clientid); - if($isDevisNegative) { + $isDevisNegative = $this->isDevisNegative($devisId,$devis->clientid); + if($isDevisNegative){ $factureNumber = $facture["facture_number"]; $facturePrefix = "AVO"; $facturationDatetime = new Datetime($facture["date"]); - $fullFactureNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($facturationDatetime, $factureNumber, $facturePrefix); + $fullFactureNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($facturationDatetime,$factureNumber,$facturePrefix); $sql = "UPDATE ".$this->tableprefix."facture SET `num`= ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($fullFactureNumber, $facture['id'])); } } } - } else { + } + else { $sql = "UPDATE ".$this->tableprefix.$table." SET $column = ? WHERE `id` = ?"; $this->execSQLNoData($sql, array(trim($data), $id)); } @@ -1833,8 +1840,8 @@ class Bdd return false; } - public function init_trajets_data($idNextcloud) - { + public function init_trajets_data($idNextcloud) { + // supprimer d'abord les lignes de trajet ainsi que les trajets existants $sqldeletelignetrajet = "DELETE FROM ".$this->tableprefix."ligne_trajet;"; $this->execSQLNoData($sqldeletelignetrajet, array()); @@ -1845,26 +1852,26 @@ class Bdd // $all_devis = json_decode($this->getDevisEmmanuelle($idNextcloud)); $all_devis = json_decode($this->getDevis($idNextcloud)); foreach ($all_devis as $key => $devis) { - if($devis->id_lieu != null) { + if($devis->id_lieu != NULL) { $this->update_lieu_date_devis($devis, 'id_lieu', $devis->id_lieu, $idNextcloud); } } } - public function createDevisTrajetFromVCalendar($devisId, $idNextcloud = "admin") - { + public function createDevisTrajetFromVCalendar($devisId,$idNextcloud = "admin"){ + $devis = json_decode($this->getOneDevis($devisId, $idNextcloud))[0]; $this->generate_ligneTrajet($devis, $idNextcloud); $ligne_trajet = json_decode(json: $this->getOneTrajetdetails_byIdDevis($devis->devisid, $idNextcloud))[0]; - $this->range_ligneTrajet($ligne_trajet->id_trajet, $idNextcloud, $devis->devisid); + $this->range_ligneTrajet($ligne_trajet->id_trajet, $idNextcloud,$devis->devisid); $this->calculer_distance_trajet($ligne_trajet->id_trajet, $idNextcloud); } /** * update lieu et date devis */ - public function update_lieu_date_devis($devis, $column, $data, $idNextcloud) - { + public function update_lieu_date_devis($devis, $column, $data, $idNextcloud) { + $ligne_trajet = json_decode($this->getOneTrajetdetails_byIdDevis($devis->devisid, $idNextcloud))[0]; switch ($column) { case 'id_client': @@ -1872,13 +1879,13 @@ class Bdd $this->execSQLNoData($sql, array($data, $devis->devisid)); $updated_devis = json_decode($this->getOneDevis($devis->devisid, $idNextcloud))[0]; - if($ligne_trajet != null) { // si il existe déja une ligne trajet + if($ligne_trajet != NULL) { // si il existe déja une ligne trajet $sql = "UPDATE ".$this->tableprefix."ligne_trajet SET $column = ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($data, $ligne_trajet->id)); $this->range_ligneTrajet($ligne_trajet->id_trajet, $idNextcloud); $this->calculer_distance_trajet($ligne_trajet->id_trajet, $idNextcloud); } else { - if($updated_devis->id_lieu != 0) { + if($updated_devis->id_lieu!=0) { // ajouter le devis dans trajet s'il n'existe pas encore $this->generate_ligneTrajet($updated_devis, $idNextcloud); $ligne_trajet = json_decode($this->getOneTrajetdetails_byIdDevis($updated_devis->devisid, $idNextcloud))[0]; @@ -1893,19 +1900,19 @@ class Bdd $this->execSQLNoData($sql, array($data, $devis->devisid)); $updated_devis = json_decode($this->getOneDevis($devis->devisid, $idNextcloud))[0]; - if($devis->id_lieu != null) { + if($devis->id_lieu!=NULL) { if(strcmp(explode('-', $devis->date)[1], explode('-', $updated_devis->date)[1]) != 0) { // si le mois a changé // deplacer la ligne de trajet - if($ligne_trajet != null) { - $this->gestion_delete('ligne_trajet', $ligne_trajet->id, $idNextcloud); - } + if($ligne_trajet != NULL) $this->gestion_delete('ligne_trajet', $ligne_trajet->id, $idNextcloud); + + $this->generate_ligneTrajet($updated_devis, $idNextcloud); $ligne_trajet = json_decode($this->getOneTrajetdetails_byIdDevis($updated_devis->devisid, $idNextcloud))[0]; $this->range_ligneTrajet($ligne_trajet->id_trajet, $idNextcloud); $this->calculer_distance_trajet($ligne_trajet->id_trajet, $idNextcloud); } else { // mettre a jour ligne_trajet - if($ligne_trajet != null) { + if($ligne_trajet != NULL) { $sql = "UPDATE ".$this->tableprefix."ligne_trajet SET $column = ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($data, $ligne_trajet->id)); $this->range_ligneTrajet($ligne_trajet->id_trajet, $idNextcloud); @@ -1914,20 +1921,20 @@ class Bdd } } break; - + case 'id_lieu': // mettre a jour devis et ligne_trajet $sql = "UPDATE ".$this->tableprefix."devis SET $column = ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($data, $devis->devisid)); $updated_devis = json_decode($this->getOneDevis($devis->devisid, $idNextcloud))[0]; - if($ligne_trajet != null) { + if($ligne_trajet != NULL) { $sql = "UPDATE ".$this->tableprefix."ligne_trajet SET $column = ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($data, $ligne_trajet->id)); $this->range_ligneTrajet($ligne_trajet->id_trajet, $idNextcloud); $this->calculer_distance_trajet($ligne_trajet->id_trajet, $idNextcloud); } else { - if($updated_devis->id_lieu != 0 && $updated_devis->id_thanato != 0) { + if($updated_devis->id_lieu!=0 && $updated_devis->id_thanato!=0) { // ajouter le devis dans trajet s'il n'existe pas encore $this->generate_ligneTrajet($updated_devis, $idNextcloud); $ligne_trajet = json_decode($this->getOneTrajetdetails_byIdDevis($updated_devis->devisid, $idNextcloud))[0]; @@ -1936,14 +1943,14 @@ class Bdd } } break; - + case 'id_thanato': // mettre a jour devis et ligne_trajet $sql = "UPDATE ".$this->tableprefix."devis SET $column = ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($data, $devis->devisid)); $updated_devis = json_decode($this->getOneDevis($devis->devisid, $idNextcloud))[0]; - - if($ligne_trajet != null) { + + if($ligne_trajet != NULL) { $this->gestion_delete('ligne_trajet', $ligne_trajet->id, $idNextcloud); } $this->generate_ligneTrajet($updated_devis, $idNextcloud); @@ -1954,8 +1961,8 @@ class Bdd } } - public function update_lieu_date_devis_rang_ligneTrajet($ligne_trajet, $column, $data, $idNextcloud) - { + public function update_lieu_date_devis_rang_ligneTrajet($ligne_trajet, $column, $data, $idNextcloud) { + switch ($column) { case 'id_devis': $current_devis = json_decode($this->getOneDevis($data, $idNextcloud))[0]; @@ -1979,9 +1986,9 @@ class Bdd break; case 'rang': $ligneTrajet_surLeRang = json_decode($this->getOneTrajetdetails_byRang($ligne_trajet->id_trajet, $data, $idNextcloud))[0]; - if($ligneTrajet_surLeRang != null) { + if($ligneTrajet_surLeRang != NULL) { $this->update_ligneTrajet('ligne_trajet', 'rang', intval($data), $ligne_trajet->id, $idNextcloud); - $this->update_ligneTrajet('ligne_trajet', 'rang', intval($data) + 1, $ligneTrajet_surLeRang->id, $idNextcloud); + $this->update_ligneTrajet('ligne_trajet', 'rang', intval($data)+1, $ligneTrajet_surLeRang->id, $idNextcloud); $this->range_ligneTrajet($ligne_trajet->id_trajet, $idNextcloud); $this->calculer_distance_trajet($ligne_trajet->id_trajet, $idNextcloud); } else { @@ -1996,13 +2003,13 @@ class Bdd /** * generer une ligne de trajet par un devis */ - public function generate_ligneTrajet($devis, $idNextcloud) - { + public function generate_ligneTrajet($devis, $idNextcloud) { + $date_devis_split = explode('-', $devis->date); // creer le trajet s'il n'existe pas $trajet = json_decode($this->getOneTrajet_byThanatoMonthYear($devis->id_thanato, $date_devis_split[1], $date_devis_split[0]))[0]; - if($trajet == null) { + if($trajet == NULL) { $this->insertTrajet($devis->id_thanato, $date_devis_split[1], $date_devis_split[0], $idNextcloud); $trajet = json_decode($this->getOneTrajet_byThanatoMonthYear($devis->id_thanato, $date_devis_split[1], $date_devis_split[0]))[0]; } @@ -2014,16 +2021,16 @@ class Bdd * ranger les lignes de trajet dans un trajet par date et par rang * inserer ligne siege au debut et fin de chaque journee s'il n'existe pas */ - public function range_ligneTrajet($id_trajet, $idNextcloud, $devisId = 0) - { + public function range_ligneTrajet($id_trajet, $idNextcloud,$devisId = 0) { + $lignes = json_decode($this->getTrajetsdetails_orderByDate($id_trajet, $idNextcloud)); $nb_jour = 0; - if(sizeof($lignes) > 0) { + if(sizeof($lignes)>0) { $nb_jour = 1; - $dates = array(0 => $lignes[0]->date); + $dates = array(0=>$lignes[0]->date); $date_temp = $lignes[0]->date; foreach ($lignes as $key => $ligne) { - if(strcmp($date_temp, string2: $ligne->date) != 0) { + if(strcmp($date_temp, string2: $ligne->date)!=0) { $date_temp = $ligne->date; array_push($dates, $date_temp); $nb_jour++; @@ -2031,9 +2038,9 @@ class Bdd } // on verifie si le nombre de ligne ets correspond à 2*nb_jour (debut et fin de journee) - $reste = (2 * $nb_jour) - (sizeof(array_filter($lignes, function ($ligne) {return strcmp($ligne->source, 'siege') == 0;}))); - while ($reste > 0) { - $this->insertTrajetdetails_h2f($id_trajet, $lignes[0]->date, $idNextcloud, $idNextcloud, $devisId); + $reste = (2*$nb_jour) - (sizeof(array_filter($lignes, function($ligne) {return strcmp($ligne->source,'siege')==0;}))); + while ($reste>0) { + $this->insertTrajetdetails_h2f($id_trajet, $lignes[0]->date, $idNextcloud,$idNextcloud,$devisId); $reste--; } @@ -2042,60 +2049,60 @@ class Bdd // ici le nombre de ligne h2f est egale au nb_jour*2 $array_siege = array(); foreach ($current_lines as $key => $ligne) { - if(strcmp($ligne->source, 'siege') == 0) { - array_push($array_siege, $ligne); - } + if(strcmp($ligne->source,'siege')==0) array_push($array_siege, $ligne); + } - $j = 0; - for ($i = 0; $i < sizeof($dates); $i++) { + + $j=0; + for ($i=0; $i < sizeof($dates); $i++) { $this->update_ligneTrajet('ligne_trajet', 'rang', 0, $array_siege[$j]->id, $idNextcloud); $this->update_ligneTrajet('ligne_trajet', 'date', $dates[$i], $array_siege[$j]->id, $idNextcloud); - $this->update_ligneTrajet('ligne_trajet', 'rang', sizeof($current_lines) + 1, $array_siege[$j + 1]->id, $idNextcloud); - $this->update_ligneTrajet('ligne_trajet', 'date', $dates[$i], $array_siege[$j + 1]->id, $idNextcloud); - $j += 2; + $this->update_ligneTrajet('ligne_trajet', 'rang', sizeof($current_lines)+1, $array_siege[$j+1]->id, $idNextcloud); + $this->update_ligneTrajet('ligne_trajet', 'date', $dates[$i], $array_siege[$j+1]->id, $idNextcloud); + $j+=2; } $ordered_lines = json_decode($this->getTrajetsdetails_orderByDate($id_trajet, $idNextcloud)); foreach ($ordered_lines as $key => $line) { - $this->update_ligneTrajet('ligne_trajet', 'rang', $key + 1, $line->id, $idNextcloud); + $this->update_ligneTrajet('ligne_trajet', 'rang', $key+1, $line->id, $idNextcloud); } } } - public function update_ligneTrajet($table, $column, $data, $id, $idNextcloud) - { + public function update_ligneTrajet($table, $column, $data, $id, $idNextcloud){ - if(in_array($table, $this->whiteTable) && in_array($column, $this->whiteColumn)) { + + if(in_array($table, $this->whiteTable) && in_array($column, $this->whiteColumn)){ $sql = "UPDATE ".$this->tableprefix.$table." SET $column = ? WHERE `id` = ?"; $this->execSQLNoData($sql, array($data, $id)); } } - public function calculer_distance_trajet($numtrajet, $idNextcloud) - { + public function calculer_distance_trajet($numtrajet, $idNextcloud) { + $trajetdetails = json_decode($this->getTrajetsdetails_orderByDate($numtrajet, $idNextcloud)); $distance_temp = 0; $distances = array(); - $last_point = null; - for ($i = 0; $i < sizeof($trajetdetails); $i++) { - if(strcmp(explode('-', $trajetdetails[$i]->date)[2], explode('-', $trajetdetails[$i + 1]->date)[2]) != 0) { + $last_point = NULL; + for ($i=0; $i < sizeof($trajetdetails); $i++) { + if(strcmp(explode('-', $trajetdetails[$i]->date)[2], explode('-', $trajetdetails[$i+1]->date)[2])!=0) { array_push($distances, $distance_temp); $distance_temp = 0; - $last_point = null; + $last_point = NULL; } else { - if($trajetdetails[$i]->lid != null) { - $last_point = $trajetdetails[$i]; - } - if($last_point->lid != null && $trajetdetails[$i + 1]->lid != null) { - $distance_temp += $this->calcul_distance(floatval($last_point->latitude), floatval($last_point->longitude), floatval($trajetdetails[$i + 1]->latitude), floatval($trajetdetails[$i + 1]->longitude)); - } + if($trajetdetails[$i]->lid != NULL) $last_point = $trajetdetails[$i]; + if($last_point->lid != NULL && $trajetdetails[$i+1]->lid != NULL) $distance_temp += $this->calcul_distance(floatval($last_point->latitude), floatval($last_point->longitude), floatval($trajetdetails[$i+1]->latitude), floatval($trajetdetails[$i+1]->longitude)); } + + } - if(sizeof($trajetdetails) > 1 && sizeof($distances) == 0) { - array_push($distances, $distance_temp); - } + if(sizeof($trajetdetails)>1 && sizeof($distances)==0) array_push($distances, $distance_temp); + + + + $distance_final = 0; foreach ($distances as $key => $valdistance) { $distance_final += $valdistance; @@ -2104,16 +2111,16 @@ class Bdd $this->execSQLNoData($sql, array($distance_final, $numtrajet)); } - public function getOneTrajet_byThanatoMonthYear($id_thanato, $mois, $annee) - { + public function getOneTrajet_byThanatoMonthYear($id_thanato, $mois, $annee) { + $sql = "SELECT " . $this->tableprefix . "trajet.id, " . $this->tableprefix . "trajet.distance, " . $this->tableprefix . "trajet.date, " . $this->tableprefix . "trajet.mois, " . $this->tableprefix . "trajet.annee FROM " . $this->tableprefix . "trajet WHERE " . $this->tableprefix . "trajet.annee = " . $annee . " AND " . $this->tableprefix . "trajet.mois = " . $mois . " AND " . $this->tableprefix . "trajet.id_thanato = " . $id_thanato . ";"; return $this->execSQL($sql, array()); } - public function recuperer_adresse($latitude, $longitude) - { + public function recuperer_adresse($latitude, $longitude) { + $curl = curl_init(); @@ -2143,13 +2150,13 @@ class Bdd /** * Calcul la distance entre les deux points à vol d'oiseau */ - public function calcul_distance($lat1, $lon1, $lat2, $lon2) - { + public function calcul_distance($lat1, $lon1, $lat2, $lon2) { + $R = 6371; // Rayon moyen de la Terre en kilomètres $dLat = deg2rad($lat2 - $lat1); $dLon = deg2rad($lon2 - $lon1); - $a = sin($dLat / 2) * sin($dLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon / 2) * sin($dLon / 2); - $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); + $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2); + $c = 2 * atan2(sqrt($a), sqrt(1-$a)); $d = $R * $c; return round($d, 2); } @@ -2157,8 +2164,8 @@ class Bdd /** * Verification si la valeur d'un coordonnees est valide */ - private function is_valid_gps($latitude, $longitude) - { + private function is_valid_gps($latitude, $longitude) { + // Vérifie si les valeurs sont des nombres décimaux valides entre -90 et 90 pour la latitude et -180 et 180 pour la longitude if (is_numeric($latitude) && is_numeric($longitude) && $latitude >= -90 && $latitude <= 90 && $longitude >= -180 && $longitude <= 180) { return true; @@ -2170,10 +2177,10 @@ class Bdd /** * DELETE */ - public function gestion_delete($table, $id, $idNextcloud) - { - if(in_array($table, $this->whiteTable)) { - if(strcmp($table, "ligne_trajet") == 0) { + public function gestion_delete($table, $id, $idNextcloud){ + + if(in_array($table, $this->whiteTable)){ + if(strcmp($table, "ligne_trajet")==0) { $distance = 0; $ligne_trajet = json_decode($this->getOneTrajetdetails($id, $idNextcloud))[0]; @@ -2197,15 +2204,15 @@ class Bdd * Check * TODO Translation */ - public function checkConfig($idNextcloud) - { + public function checkConfig($idNextcloud){ + $sql = "SELECT count(*) as res FROM `".$this->tableprefix."configuration` WHERE `id_nextcloud` = ?"; $res = json_decode($this->execSQL($sql, array($idNextcloud)))[0]->res; - if ($res < 1) { + if ( $res < 1 ){ $sql = "INSERT INTO `".$this->tableprefix."configuration` (`entreprise`, `nom`, `prenom`, `legal_one`, `legal_two`, `mail`, `telephone`, `adresse`, `path`, `id_nextcloud`,`mentions_default`,`tva_default`,`devise`,`facture_prefixe`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '', ?, ?, '0',?,?);"; - $this->execSQLNoData( - $sql, - array($this->l->t('Your company name'), + $this->execSQLNoData($sql, array($this->l->t('Your company name'), + + $this->l->t('Your company contact last name'), $this->l->t('Your company contact first name'), $this->l->t('Company legal information line one'), @@ -2218,29 +2225,29 @@ class Bdd $this->l->t('EUR'), $this->l->t('INVOICE') ) - ); + ); } return $res; } - public function isConfig($idNextcloud) - { + public function isConfig($idNextcloud){ + $changelog = 9; //+1 if you want changelog appear for everybody one time ! $sql = "SELECT count(*) as res FROM `".$this->tableprefix."configuration` WHERE `id_nextcloud` = ?"; $res = json_decode($this->execSQL($sql, array($idNextcloud)))[0]->res; // Utilisateur jamais utilisé l'application - if ($res < 1) { + if ( $res < 1 ){ return false; - } else { + }else{ $sql = "SELECT id as id, changelog as res FROM `".$this->tableprefix."configuration` WHERE `id_nextcloud` = ?"; $res = json_decode($this->execSQL($sql, array($idNextcloud)))[0]->res; $id = json_decode($this->execSQL($sql, array($idNextcloud)))[0]->id; - if($res < $changelog) { - $this->gestion_update("configuration", "changelog", $changelog, $id, $idNextcloud); + if($res < $changelog){ + $this->gestion_update("configuration","changelog",$changelog,$id,$idNextcloud); return false; - } else { + }else{ return true; } } @@ -2249,8 +2256,8 @@ class Bdd /** * Number client */ - public function numberClient($idNextcloud) - { + public function numberClient($idNextcloud){ + // $sql = "SELECT count(*) as c from ".$this->tableprefix."client WHERE `id_nextcloud` = ?;"; $sql = "SELECT count(*) as c from ".$this->tableprefix."client;"; return $this->execSQL($sql, array()); @@ -2260,8 +2267,8 @@ class Bdd /** * Number thanatopracteur */ - public function numberThanato($idNextcloud) - { + public function numberThanato($idNextcloud){ + // $sql = "SELECT count(*) as c from ".$this->tableprefix."thanato WHERE `id_nextcloud` = ?;"; $sql = "SELECT count(*) as c from ".$this->tableprefix."thanato;"; return $this->execSQL($sql, array()); @@ -2271,8 +2278,8 @@ class Bdd /** * Number devis */ - public function numberDevis($idNextcloud) - { + public function numberDevis($idNextcloud){ + // $sql = "SELECT count(*) as c from ".$this->tableprefix."devis WHERE `id_nextcloud` = ? AND `mentions` NOT LIKE 'facturé';"; // $sql = "SELECT count(*) as c from ".$this->tableprefix."devis WHERE `mentions` NOT LIKE 'facturé';"; $sql = "SELECT count(*) as c from ".$this->tableprefix."devis;"; @@ -2280,12 +2287,12 @@ class Bdd // return $this->execSQL($sql, array($idNextcloud)); return $this->execSQL($sql, array()); } - + /** * Number facture */ - public function numberFacture($idNextcloud) - { + public function numberFacture($idNextcloud){ + // $sql = "SELECT count(*) as c from ".$this->tableprefix."facture WHERE `id_nextcloud` = ?;"; $sql = "SELECT count(*) as c from ".$this->tableprefix."facture;"; // return $this->execSQL($sql, array($idNextcloud)); @@ -2295,8 +2302,8 @@ class Bdd /** * Number lieu */ - public function numberLieu($idNextcloud) - { + public function numberLieu($idNextcloud){ + $sql = "SELECT count(*) as c from ".$this->tableprefix."lieu;"; return $this->execSQL($sql, array()); } @@ -2304,8 +2311,8 @@ class Bdd /** * Number trajet */ - public function numberTrajet($idNextcloud) - { + public function numberTrajet($idNextcloud){ + $sql = "SELECT count(*) as c from ".$this->tableprefix."trajet;"; return $this->execSQL($sql, array()); } @@ -2313,8 +2320,8 @@ class Bdd /** * Number produit */ - public function numberProduit($idNextcloud) - { + public function numberProduit($idNextcloud){ + // $sql = "SELECT count(*) as c from ".$this->tableprefix."produit WHERE `id_nextcloud` = ?;"; $sql = "SELECT count(*) as c from ".$this->tableprefix."produit;"; // return $this->execSQL($sql, array($idNextcloud)); @@ -2324,8 +2331,8 @@ class Bdd /** * Number article */ - public function numberArticle($idNextcloud) - { + public function numberArticle($idNextcloud){ + $sql = "SELECT count(*) as c from ".$this->tableprefix."article;"; return $this->execSQL($sql, array()); } @@ -2333,18 +2340,19 @@ class Bdd /** * Number défunt */ - public function numberDefunt($idNextcloud, $isUserThanatoOnly = false) - { + public function numberDefunt($idNextcloud, $isUserThanatoOnly = false){ + $defuntCount = 0; - if($isUserThanatoOnly == false) { + if($isUserThanatoOnly == false){ $sql = "SELECT count(*) as c from ".$this->tableprefix."defunt;"; $defuntCountBythanato = $this->execSQLNoJsonReturn($sql, array()); - if(!empty($defuntCountBythanato)) { + if(!empty($defuntCountBythanato)){ $defuntCount = $defuntCountBythanato[0]['c']; } - } else { + } + else{ $thanato = $this->getThanatoByIdNextcloud($idNextcloud); - if($thanato != null) { + if($thanato != null){ $thanatoId = $thanato["id"]; $defuntsIdRelatedToThanato = $this->getDefuntIdsRelatedToThanato($thanatoId); $defuntCount = count($defuntsIdRelatedToThanato); @@ -2356,14 +2364,14 @@ class Bdd /** * Number bibliotheque */ - public function numberBibliotheque($idNextcloud) - { + public function numberBibliotheque($idNextcloud){ + $sql = "SELECT count(*) as c from ".$this->tableprefix."bibliotheque;"; return $this->execSQL($sql, array()); } - public function retrieveTotalInvoicesForTheYear() - { + public function retrieveTotalInvoicesForTheYear(){ + $sql = "SELECT EXTRACT(YEAR FROM devis.date) AS y, EXTRACT(MONTH FROM devis.date) AS m, @@ -2390,9 +2398,9 @@ class Bdd EXTRACT(MONTH FROM devis.`date`) ORDER BY EXTRACT(YEAR FROM devis.`date`) DESC, - EXTRACT(MONTH FROM devis.`date`);"; + EXTRACT(MONTH FROM devis.`date`);"; - return $this->execSQL($sql, [ + return $this->execSQL($sql, [ DevisMentionConstant::FACTURED, DevisMentionConstant::FACTURED_FORMATTED ]); @@ -2401,8 +2409,8 @@ class Bdd /** * Annual turnover per month without VAT */ - public function getAnnualTurnoverPerMonthNoVat($idNextcloud) - { + public function getAnnualTurnoverPerMonthNoVat($idNextcloud){ + $sql = "SELECT EXTRACT(YEAR FROM facture.date_paiement) AS y, EXTRACT(MONTH FROM facture.date_paiement) AS m, @@ -2433,8 +2441,8 @@ class Bdd return $this->execSQLNoJsonReturn($sql, array()); } - public function getStatArticleAnnuel($idNextcloud, $annee) - { + public function getStatArticleAnnuel($idNextcloud, $annee) { + $sql = "SELECT p.id, p.reference, COALESCE(SUM(CASE WHEN MONTH(d.date) = 1 THEN pd.quantite ELSE 0 END), 0) AS janvier, COALESCE(SUM(CASE WHEN MONTH(d.date) = 2 THEN pd.quantite ELSE 0 END), 0) AS fevrier, @@ -2460,8 +2468,8 @@ class Bdd ]); } - public function getStatSoinsThanatoAnnuel($idNextcloud, $annee) - { + public function getStatSoinsThanatoAnnuel($idNextcloud, $annee) { + $sql = "SELECT thanato.nom AS nom_thanato, thanato.prenom AS prenom_thanato, @@ -2490,8 +2498,8 @@ class Bdd ]); } - public function getStatSoinsThanatoWeekend($idNextcloud, $annee, $mois) - { + public function getStatSoinsThanatoWeekend($idNextcloud, $annee, $mois) { + /** * stat nombre de soins samedis et dimanches * */ @@ -2535,60 +2543,60 @@ class Bdd /** * Get last insert id */ - public function lastinsertid($table, $idNextcloud) - { + public function lastinsertid($table,$idNextcloud){ + // $sql = "SELECT max(user_id) as LAST_INSERT_ID FROM `" . $this->tableprefix . $table . "` WHERE " . $this->tableprefix . $table .".id_nextcloud = ?;"; // $res = $this->execSQLNoJsonReturn($sql,array($idNextcloud)); $sql = "SELECT max(user_id) as LAST_INSERT_ID FROM `" . $this->tableprefix . $table. "`;"; - $res = $this->execSQLNoJsonReturn($sql, array()); + $res = $this->execSQLNoJsonReturn($sql,array()); return $res[0]['LAST_INSERT_ID']; } - public function lastNumFacture($idNextcloud) - { + public function lastNumFacture($idNextcloud) { + $lastFactureId = $this->getLastFactureId(); return $lastFactureId; } - private function getLastFactureId() - { + private function getLastFactureId(){ + $sql = "SELECT - max(facture.id) as LAST_FACTURE_ID FROM " + max(facture.id) as LAST_FACTURE_ID FROM " . $this->tableprefix."facture as facture;"; - $res = $this->execSQLNoJsonReturn($sql, []); + $res = $this->execSQLNoJsonReturn($sql,[]); $lastId = 0; - if(!empty($res)) { + if(!empty($res)){ $lastId = $res[0]['LAST_FACTURE_ID']; } return $lastId; } - public function backup() - { + public function backup(){ + $res = array(); $res[] = array("===client==="); $sql = "SELECT * FROM ".$this->tableprefix."client"; $res = array_merge($res, $this->execSQLNoJsonReturn($sql, array())); - + $res[] = array("===devis==="); $sql = "SELECT * FROM ".$this->tableprefix."devis"; - $res = array_merge($res, $this->execSQLNoJsonReturn($sql, array())); + $res = array_merge($res,$this->execSQLNoJsonReturn($sql, array())); $res[] = array("===facture==="); $sql = "SELECT * FROM ".$this->tableprefix."facture"; - $res = array_merge($res, $this->execSQLNoJsonReturn($sql, array())); + $res = array_merge($res,$this->execSQLNoJsonReturn($sql, array())); $res[] = array("===produit==="); $sql = "SELECT * FROM ".$this->tableprefix."produit"; - $res = array_merge($res, $this->execSQLNoJsonReturn($sql, array())); + $res = array_merge($res,$this->execSQLNoJsonReturn($sql, array())); $res[] = array("===produit_devis==="); $sql = "SELECT * FROM ".$this->tableprefix."produit_devis"; - $res = array_merge($res, $this->execSQLNoJsonReturn($sql, array())); + $res = array_merge($res,$this->execSQLNoJsonReturn($sql, array())); $res[] = array("===configuration==="); $sql = "SELECT * FROM ".$this->tableprefix."configuration"; - $res = array_merge($res, $this->execSQLNoJsonReturn($sql, array())); + $res = array_merge($res,$this->execSQLNoJsonReturn($sql, array())); return $res; } @@ -2597,8 +2605,8 @@ class Bdd * @sql * @array() //prepare statement */ - private function execSQL($sql, $conditions) - { + private function execSQL($sql, $conditions){ + $stmt = $this->pdo->prepare($sql); $stmt->execute($conditions); $data = $stmt->fetchAll(\PDO::FETCH_ASSOC); @@ -2606,15 +2614,15 @@ class Bdd return json_encode($data); } - private function execSQLNoData($sql, $conditions) - { + private function execSQLNoData($sql, $conditions){ + $stmt = $this->pdo->prepare($sql); $stmt->execute($conditions); $stmt->closeCursor(); } - private function execSQLNoJsonReturn($sql, $conditions) - { + private function execSQLNoJsonReturn($sql, $conditions){ + $stmt = $this->pdo->prepare($sql); $stmt->execute($conditions); $data = $stmt->fetchAll(\PDO::FETCH_ASSOC); @@ -2622,8 +2630,8 @@ class Bdd return $data; } - private function getThanatoDevisListByDate($thanatoId, $date) - { + private function getThanatoDevisListByDate($thanatoId,$date){ + $dateFormatted = $date->format('Y-m-d'); $sql = "SELECT devis.id, @@ -2657,38 +2665,38 @@ class Bdd (devis.mentions = ? OR devis.mentions = ?) ORDER BY devis.date ASC;"; $devisList = $this->execSQLNoJsonReturn( - $sql, - [$dateFormatted,$thanatoId,DevisMentionConstant::FACTURED,DevisMentionConstant::FACTURED_FORMATTED] - ); + $sql, + [$dateFormatted,$thanatoId,DevisMentionConstant::FACTURED,DevisMentionConstant::FACTURED_FORMATTED]); + return $devisList; } - public function getThanatoById($thanatoId) - { + public function getThanatoById($thanatoId){ + $sql = "SELECT id, nom, prenom,fk_user_uuid FROM ".$this->tableprefix."thanato WHERE id = ? LIMIT 1;"; - $thanato = $this->execSQLNoJsonReturn($sql, [$thanatoId]); - if(!empty($thanato)) { + $thanato = $this->execSQLNoJsonReturn($sql,[$thanatoId]); + if(!empty($thanato)){ return $thanato[0]; } return null; } - private function getCalendarByThanatoIdNextcloud($idNextCloud) - { + private function getCalendarByThanatoIdNextcloud($idNextCloud){ + $searchString = "%principals/users/$idNextCloud%"; $sql = "SELECT * FROM ".self::DEFAULT_TABLE_PREFIX."calendars as calendar WHERE calendar.principaluri LIKE ? LIMIT 1;"; - $calendar = $this->execSQLNoJsonReturn($sql, [$searchString]); - if(!empty($calendar)) { + $calendar = $this->execSQLNoJsonReturn($sql,[$searchString]); + if(!empty($calendar)){ return $calendar[0]; } return null; } + + private function getThanatoLeaveByCalendarAndDate($calendarId,$date){ - private function getThanatoLeaveByCalendarAndDate($calendarId, $date) - { $isLeaveConditionAsString = "ABSENCETYPE:"; - + $datetimeFormatted = $date->format('Ymd'); $dateCondition = "%DTSTART%".$datetimeFormatted."%"; $conditions = []; @@ -2708,75 +2716,76 @@ class Bdd calendarobject.calendardata LIKE ? AND calendarobject.deleted_at IS NULL AND (" . implode(" OR ", $conditions) . ");"; - $leaves = $this->execSQLNoJsonReturn($sql, $params); + $leaves = $this->execSQLNoJsonReturn($sql,$params); return $leaves; } + + public function getThanatoDevisPerDateInAMonthYear($thanatoId,$month,$year){ - public function getThanatoDevisPerDateInAMonthYear($thanatoId, $month, $year) - { - $dateOfMonths = DateHelpers::getDatesOfMonth($year, $month); + $dateOfMonths = DateHelpers::getDatesOfMonth($year,$month); $devisListPerThanatoPerDate = []; $thanato = $this->getThanatoById($thanatoId); $thanatoName = $thanato["nom"]; $thanatoCalendar = $this->getCalendarByThanatoIdNextcloud($thanato["fk_user_uuid"] ?? $thanato["nom"]); - if($thanatoCalendar == null) { + if($thanatoCalendar == null){ return []; } $thanatoCalendarId = $thanatoCalendar["id"]; - foreach($dateOfMonths as $currentDate) { + foreach($dateOfMonths as $currentDate){ $currentDateFormatted = $currentDate->format('Y-m-d'); $isPublicHoliday = DateHelpers::isPublicHoliday($currentDateFormatted); - $devisList = $this->getThanatoDevisListByDate($thanatoId, $currentDate); + $devisList = $this->getThanatoDevisListByDate($thanatoId,$currentDate); $thereIsNoDevisForCurrentDate = empty($devisList); - if($thereIsNoDevisForCurrentDate) { + if($thereIsNoDevisForCurrentDate){ $devisListPerThanatoPerDate[$currentDateFormatted]["hasDevis"] = false; - $thanatoLeavesThisDay = $this->getThanatoLeaveByCalendarAndDate($thanatoCalendarId, $currentDate); - if(empty($thanatoLeavesThisDay)) { + $thanatoLeavesThisDay = $this->getThanatoLeaveByCalendarAndDate($thanatoCalendarId,$currentDate); + if(empty($thanatoLeavesThisDay)){ $devisListPerThanatoPerDate[$currentDateFormatted]["leaves"][] = [ "onLeave" => false, "startTime" => null, "endTime" => null, - "thanatoName" => $thanatoName, + "thanatoName"=>$thanatoName, "date" => $currentDateFormatted, "totalHours" => 0, "totalWorkedHours" => 8, "isPublicHoliday" => $isPublicHoliday ]; - } else { - foreach($thanatoLeavesThisDay as $currentLeave) { + } + else{ + foreach($thanatoLeavesThisDay as $currentLeave){ $leaveTime = VCalendarHelpers::GetStartAndEndTimeFromVCalendarString($currentLeave['calendardata']); - $absenceType = VCalendarHelpers::GetValueFromKeyInVCalendarString(VCalendarPropertyConstant::ABSENCE_TYPE, $currentLeave['calendardata']); + $absenceType = VCalendarHelpers::GetValueFromKeyInVCalendarString(VCalendarPropertyConstant::ABSENCE_TYPE,$currentLeave['calendardata']); $absenceTypeKey = null; $absenceTypeLabel = null; - if($absenceType) { + if($absenceType){ $absenceTypeKey = $absenceType; $absenceTypeLabel = FileExportHelpers::GetAbsenceTypeLabelFromKey($absenceType); - } else { + }else{ //get is leave - $isLeave = VCalendarHelpers::GetValueFromKeyInVCalendarString(BddConstant::ISLEAVEPROPERTYONVCALENDAR, $currentLeave['calendardata']); - if ($isLeave) { + $isLeave = VCalendarHelpers::GetValueFromKeyInVCalendarString(BddConstant::ISLEAVEPROPERTYONVCALENDAR,$currentLeave['calendardata']); + if ( $isLeave ) { $absenceTypeKey = AbsenceTypeConstant::LEAVE; - $absenceTypeLabel = VCalendarPropertyConstant::ABSENCE_TYPES_KEYS_VALUES[$absenceTypeKey]; - ; + $absenceTypeLabel = VCalendarPropertyConstant::ABSENCE_TYPES_KEYS_VALUES[$absenceTypeKey]; ; + } } $startTimeValueWithMinutes = ""; $endTimeValueWithMinutes = ""; - if($leaveTime["datetimeStart"]) { + if($leaveTime["datetimeStart"]){ $startTimeValueWithMinutes = $leaveTime["datetimeStart"]->format('H\hi'); } - if($leaveTime["datetimeEnd"]) { + if($leaveTime["datetimeEnd"]){ $endTimeValueWithMinutes = $leaveTime["datetimeEnd"]->format('H\hi'); } - + $devisListPerThanatoPerDate[$currentDateFormatted]["leaves"][] = [ "onLeave" => true, "startTime" => $startTimeValueWithMinutes, "endTime" => $endTimeValueWithMinutes, - "thanatoName" => $thanatoName, + "thanatoName"=>$thanatoName, "date" => $currentDateFormatted, "totalHours" => $leaveTime["totalHours"], "totalWorkedHours" => $leaveTime["totalWorkedHours"], @@ -2786,8 +2795,9 @@ class Bdd ]; } } - } else { - foreach($devisList as $devis) { + } + else{ + foreach($devisList as $devis){ $devis = $this->setDevisStartAndEndTime($devis); $devis = $this->setDevisIsPublicHolidayOrNotText($devis); $devis = $this->setDevisProduitsList($devis); @@ -2804,37 +2814,37 @@ class Bdd $devisListPerThanatoPerDate[$currentDateFormatted]["devisId"][] = $devis['id']; } $devisListPerThanatoPerDate[$currentDateFormatted]["leaves"] = []; - $thanatoLeavesThisDay = $this->getThanatoLeaveByCalendarAndDate($thanatoCalendarId, $currentDate); - foreach($thanatoLeavesThisDay as $currentLeave) { + $thanatoLeavesThisDay = $this->getThanatoLeaveByCalendarAndDate($thanatoCalendarId,$currentDate); + foreach($thanatoLeavesThisDay as $currentLeave){ $leaveTime = VCalendarHelpers::GetStartAndEndTimeFromVCalendarString($currentLeave['calendardata']); $startTimeValueWithMinutes = ""; $endTimeValueWithMinutes = ""; - if($leaveTime["datetimeStart"]) { + if($leaveTime["datetimeStart"]){ $startTimeValueWithMinutes = $leaveTime["datetimeStart"]->format('H\hi'); } - if($leaveTime["datetimeEnd"]) { + if($leaveTime["datetimeEnd"]){ $endTimeValueWithMinutes = $leaveTime["datetimeEnd"]->format('H\hi'); } - $absenceType = VCalendarHelpers::GetValueFromKeyInVCalendarString(VCalendarPropertyConstant::ABSENCE_TYPE, $currentLeave['calendardata']); + $absenceType = VCalendarHelpers::GetValueFromKeyInVCalendarString(VCalendarPropertyConstant::ABSENCE_TYPE,$currentLeave['calendardata']); $absenceTypeKey = null; $absenceTypeLabel = null; - if($absenceType) { + if($absenceType){ $absenceTypeKey = $absenceType; $absenceTypeLabel = FileExportHelpers::GetAbsenceTypeLabelFromKey($absenceType); - } else { + }else{ //get is leave - $isLeave = VCalendarHelpers::GetValueFromKeyInVCalendarString(BddConstant::ISLEAVEPROPERTYONVCALENDAR, $currentLeave['calendardata']); - if ($isLeave) { + $isLeave = VCalendarHelpers::GetValueFromKeyInVCalendarString(BddConstant::ISLEAVEPROPERTYONVCALENDAR,$currentLeave['calendardata']); + if ( $isLeave ) { $absenceTypeKey = AbsenceTypeConstant::LEAVE; - $absenceTypeLabel = VCalendarPropertyConstant::ABSENCE_TYPES_KEYS_VALUES[$absenceTypeKey]; - ; + $absenceTypeLabel = VCalendarPropertyConstant::ABSENCE_TYPES_KEYS_VALUES[$absenceTypeKey]; ; + } } $devisListPerThanatoPerDate[$currentDateFormatted]["leaves"][] = [ "onLeave" => true, "startTime" => $startTimeValueWithMinutes, "endTime" => $endTimeValueWithMinutes, - "thanatoName" => $thanatoName, + "thanatoName"=>$thanatoName, "date" => $currentDateFormatted, "totalHours" => $leaveTime["totalHours"], "totalWorkedHours" => $leaveTime["totalWorkedHours"], @@ -2846,41 +2856,41 @@ class Bdd return $devisListPerThanatoPerDate; } - public function getExportThanatoStatisticData($thanatoId, $month, $year) - { - $devisList = $this->getThanatoDevisPerDateInAMonthYear($thanatoId, $month, $year); + public function getExportThanatoStatisticData($thanatoId,$month,$year){ + + $devisList = $this->getThanatoDevisPerDateInAMonthYear($thanatoId,$month,$year); return $devisList; } - public function getProduitsDevisByDevisId($devisId) - { - $sql = "SELECT + public function getProduitsDevisByDevisId($devisId){ + + $sql = "SELECT produit_devis.id as produit_devis_id, - produit.id as produit_id, - produit.reference as produit_reference, + produit.id as produit_id, + produit.reference as produit_reference, produit.description as produit_description FROM ".$this->tableprefix."produit_devis as produit_devis LEFT JOIN ".$this->tableprefix."produit as produit on produit_devis.produit_id = produit.id WHERE produit_devis.devis_id = ?;"; $produitsList = $this->execSQLNoJsonReturn( - $sql, - [$devisId] - ); + $sql, + [$devisId]); + $finalProduitList = []; - foreach($produitsList as $produit) { - if($produit['produit_id'] != null) { + foreach($produitsList as $produit){ + if($produit['produit_id'] != null){ $finalProduitList[] = $produit; } } return $finalProduitList; } - private function getDevisListGroupedByDateAndThenByThanato(array $devisListPerDate) - { + private function getDevisListGroupedByDateAndThenByThanato(array $devisListPerDate){ + $devisListGroupedByThanatoAndThenByDate = []; - foreach($devisListPerDate as $date => $devisList) { - foreach($devisList as $devis) { + foreach($devisListPerDate as $date => $devisList){ + foreach($devisList as $devis){ $devisDate = $devis["date"]; $devisThanatoId = $devis["id_thanato"]; $devis = $this->setDevisStartAndEndTime($devis); @@ -2904,10 +2914,10 @@ class Bdd return $devisListGroupedByThanatoAndThenByDate; } - private function setDevisProduitsList($devis) - { + private function setDevisProduitsList($devis){ + $produitsList = $this->getProduitsDevisByDevisId($devis['id']); - foreach($produitsList as $produit) { + foreach($produitsList as $produit){ if (!isset($devis['produits'])) { $devis['produits'] = []; } @@ -2916,23 +2926,23 @@ class Bdd return $devis; } - private function setDevisIsPublicHolidayOrNotText($devis) - { + private function setDevisIsPublicHolidayOrNotText($devis){ + $isPublicHoliday = DateHelpers::isPublicHoliday($devis['date']); $devis["dayType"] = DateHelpers::getPublicHolidayText($isPublicHoliday); return $devis; } - public function setDevisStartAndEndTime($devis) - { + public function setDevisStartAndEndTime($devis){ + $calendarData = $this->getCalendarDataByCalendarObjectUuid($devis["calendar_uuid"]); $devisTimeValue = VCalendarHelpers::GetStartAndEndTimeFromVCalendarString($calendarData); $startTimeValueWithMinutes = ""; $endTimeValueWithMinutes = ""; - if($devisTimeValue["datetimeStart"]) { + if($devisTimeValue["datetimeStart"]){ $startTimeValueWithMinutes = $devisTimeValue["datetimeStart"]->format('H\hi'); } - if($devisTimeValue["datetimeEnd"]) { + if($devisTimeValue["datetimeEnd"]){ $endTimeValueWithMinutes = $devisTimeValue["datetimeEnd"]->format('H\hi'); } $devis["startTime"] = $startTimeValueWithMinutes; @@ -2942,9 +2952,9 @@ class Bdd return $devis; } - public function getRouteLinesByDevisIdList(array $devisIdList) - { - if(empty($devisIdList)) { + public function getRouteLinesByDevisIdList(array $devisIdList){ + + if(empty($devisIdList)){ return []; } $sqlConditionsPlaceholder = implode(',', array_fill(0, count($devisIdList), '?')); @@ -2958,12 +2968,12 @@ class Bdd return $this->execSQLNoJsonReturn($sql, $devisIdList); } - private function getDevisListByThanatoIds(array $thanatoIds) - { - if(empty($thanatoIds)) { + private function getDevisListByThanatoIds(array $thanatoIds){ + + if(empty($thanatoIds)){ return []; } - $currentYear = date('Y'); + $currentYear = date('Y'); $currentMonth = date('m'); $sqlConditionsPlaceholder = implode(',', array_fill(0, count($thanatoIds), '?')); @@ -2998,17 +3008,17 @@ class Bdd (devis.mentions = ? OR devis.mentions = ?) ORDER BY devis.date ASC;"; $devisList = $this->execSQLNoJsonReturn( - $sql, - array_merge([$currentYear, $currentMonth], $thanatoIds, [DevisMentionConstant::FACTURED,DevisMentionConstant::FACTURED_FORMATTED]) - ); + $sql, + array_merge([$currentYear, $currentMonth],$thanatoIds,[DevisMentionConstant::FACTURED,DevisMentionConstant::FACTURED_FORMATTED])); + return $devisList; } - public function getCalendarDataByCalendarObjectUuid(string $calendarObjectUuid) - { + public function getCalendarDataByCalendarObjectUuid(string $calendarObjectUuid){ + $sql = "SELECT * FROM ".self::DEFAULT_TABLE_PREFIX."calendarobjects WHERE uid = ?;"; $calendarObjectList = $this->execSQLNoJsonReturn($sql, [$calendarObjectUuid]); - if(!empty($calendarObjectList)) { + if(!empty($calendarObjectList)){ $calendarDataBlob = $calendarObjectList[0]['calendardata']; $calendarDataString = VCalendarHelpers::ReadVCalendarDataBlob($calendarDataBlob); return $calendarDataString; @@ -3016,66 +3026,66 @@ class Bdd return ""; } - public function getCalendarPrincipalNameByCalendarId($calendarId) - { + public function getCalendarPrincipalNameByCalendarId($calendarId){ + $calendar = $this->getCalendarById($calendarId); - if($calendar != null) { + if($calendar != null){ $principalUri = $calendar["principaluri"]; - $organizerName = str_replace('principals/users/', '', $principalUri); + $organizerName = str_replace('principals/users/','',$principalUri); $organizerName = trim($organizerName); return $organizerName; } return null; } - public function getCalendarOrganizerNameByCalendarObjectUuid(string $calendarObjectUuid) - { + public function getCalendarOrganizerNameByCalendarObjectUuid(string $calendarObjectUuid){ + $calendarObject = $this->getCalendarObjectByUuid($calendarObjectUuid); - if($calendarObject != null) { + if($calendarObject != null){ return $this->getCalendarPrincipalNameByCalendarId($calendarObject['calendarid']); } return null; } - public function getCalendarObjectByUuid(string $calendarObjectUuid) - { + public function getCalendarObjectByUuid(string $calendarObjectUuid){ + $sql = "SELECT * FROM ".self::DEFAULT_TABLE_PREFIX."calendarobjects WHERE uid = ?;"; $calendarObjectList = $this->execSQLNoJsonReturn($sql, [$calendarObjectUuid]); - if(!empty($calendarObjectList)) { + if(!empty($calendarObjectList)){ $calendarData = $calendarObjectList[0]; return $calendarData; } return null; } - public function getCalendarById(int $calendarId) - { + public function getCalendarById(int $calendarId){ + $sql = "SELECT * FROM ".self::DEFAULT_TABLE_PREFIX."calendars WHERE id = ?;"; $calendarList = $this->execSQLNoJsonReturn($sql, [$calendarId]); - if(!empty($calendarList)) { + if(!empty($calendarList)){ $calendarData = $calendarList[0]; return $calendarData; } return null; } - public function getProduitDevisByDevisId($devisId) - { + public function getProduitDevisByDevisId($devisId){ + $sql = "SELECT * FROM ".$this->tableprefix ."produit_devis as produit_devis WHERE produit_devis.devis_id = ?;"; $produitDevisList = $this->execSQLNoJsonReturn( - $sql, - [$devisId] - ); + $sql, + [$devisId]); + return $produitDevisList; } - public function getDevisProduits($devisId) - { + public function getDevisProduits($devisId){ + $sql = "SELECT produit_devis.id, produit_devis.produit_id, @@ -3094,15 +3104,15 @@ class Bdd WHERE produit_devis.devis_id = ?;"; $produitList = $this->execSQLNoJsonReturn( - $sql, - [$devisId] - ); + $sql, + [$devisId]); - if(!empty($produitList)) { + + if(!empty($produitList)){ $clientId = $produitList[0]["devis_client_id"]; $client = $this->getClientById($clientId); - foreach($produitList as &$produit) { - $productPrice = $this->getProductPriceByClientGroupId($client['fk_client_group_id'], $produit['produit_id']); + foreach($produitList as &$produit){ + $productPrice = $this->getProductPriceByClientGroupId($client['fk_client_group_id'],$produit['produit_id']); $produit['produit_price'] = $productPrice ?? $produit['produit_price']; } } @@ -3110,36 +3120,36 @@ class Bdd return $produitList; } - public function getProductPriceByClientGroupId($clientGroupId, $productId) - { + public function getProductPriceByClientGroupId($clientGroupId,$productId){ + $sql = "SELECT * FROM ".$this->tableprefix ."client_group_discount as client_group_discount WHERE client_group_discount.fk_client_group_id = ? AND client_group_discount.fk_produit_id = ?; "; $clientGroupDiscount = $this->execSQLNoJsonReturn( - $sql, - [$clientGroupId,$productId] - ); - if(!empty($clientGroupDiscount)) { + $sql, + [$clientGroupId,$productId]); + + if(!empty($clientGroupDiscount)){ return $clientGroupDiscount[0]['ht_amount']; } return null; } - private function getProductPriceByClient($productId, $clientId, $productInitialPrice) - { + private function getProductPriceByClient($productId,$clientId,$productInitialPrice){ + $client = $this->getClientById($clientId); - if($client != null) { - $productDiscountPrice = $this->getProductPriceByClientGroupId($client['fk_client_group_id'], $productId); + if($client != null){ + $productDiscountPrice = $this->getProductPriceByClientGroupId($client['fk_client_group_id'],$productId); $productInitialPrice = $productDiscountPrice ?? $productInitialPrice; } return $productInitialPrice; } - private function getDevisProductsQuantityByDevisListAndProductId($devisList, $productId) - { - if(empty($devisList)) { + private function getDevisProductsQuantityByDevisListAndProductId($devisList,$productId){ + + if(empty($devisList)){ return 0; } $sqlConditionsPlaceholder = implode(',', array_fill(0, count($devisList), '?')); @@ -3150,23 +3160,23 @@ class Bdd produit_devis.produit_id = ?;"; $produitList = $this->execSQLNoJsonReturn( - $sql, - array_merge($devisList, array($productId)) - ); + $sql, + array_merge($devisList,array($productId))); - if(!empty($produitList)) { + + if(!empty($produitList)){ return $produitList[0]['total_quantity']; } return 0; } - private function getClientFactureStatisticPerMonth($clientId, array $produitList) - { - $currentYear = date('Y'); - $monthLists = range(1, 12); + private function getClientFactureStatisticPerMonth($clientId,array $produitList){ + + $currentYear = date('Y'); + $monthLists = range(1,12); $data = [] ; - foreach($monthLists as $monthValue) { - if(!isset($data[$monthValue])) { + foreach($monthLists as $monthValue){ + if(!isset($data[$monthValue])){ $data[$monthValue] = []; } $sql = "SELECT @@ -3185,23 +3195,23 @@ class Bdd (devis.mentions = ? OR devis.mentions = ?) ORDER BY facture.date_paiement ASC;"; $factureList = $this->execSQLNoJsonReturn( - $sql, - [$currentYear,$monthValue,$clientId,DevisMentionConstant::FACTURED,DevisMentionConstant::FACTURED_FORMATTED] - ); + $sql, + [$currentYear,$monthValue,$clientId,DevisMentionConstant::FACTURED,DevisMentionConstant::FACTURED_FORMATTED]); + $factureDevisIds = []; - foreach($factureList as $facture) { + foreach($factureList as $facture){ $factureDevisIds[] = $facture['devis_id']; } $defuntCount = count($factureList); $produitsPrice = 0; $statisticForeachProductPerMonth = []; - foreach($produitList as $produit) { - if(!isset($statisticForeachProductPerMonth[$produit['id']])) { + foreach($produitList as $produit){ + if(!isset($statisticForeachProductPerMonth[$produit['id']])){ $statisticForeachProductPerMonth[$produit['id']] = 0; } - $productTotalCount = $this->getDevisProductsQuantityByDevisListAndProductId($factureDevisIds, $produit['id']); + $productTotalCount = $this->getDevisProductsQuantityByDevisListAndProductId($factureDevisIds,$produit['id']); $totalWithoutVat = $productTotalCount * $produit["prix_unitaire"]; $statisticForeachProductPerMonth[$produit['id']] += $productTotalCount; $produitsPrice += $totalWithoutVat; @@ -3216,29 +3226,29 @@ class Bdd return $data; } - public function getExportClientStatData(array $clientIds) - { + public function getExportClientStatData(array $clientIds){ + $data = []; $produitList = $this->getProduitsListAsArray(); - foreach($clientIds as $clientId) { - if(!isset($data[$clientId])) { + foreach($clientIds as $clientId){ + if(!isset($data[$clientId])){ $data[$clientId] = []; } //get client name $clientName = "Default client name"; $client = $this->getClientById($clientId); - if($client != null) { + if($client != null){ $clientName = trim($client["client_nom"]) . '-' .trim($client['client_entreprise']); } $data[$clientId]["client_name"] = $clientName; - $data[$clientId]["client_data"] = $this->getClientFactureStatisticPerMonth($clientId, $produitList); + $data[$clientId]["client_data"] = $this->getClientFactureStatisticPerMonth($clientId,$produitList); } return $data; } - public function getClientById($clientId) - { - $sql = "SELECT + private function getClientById($clientId){ + + $sql = "SELECT client.id, client.nom as client_nom, client.prenom as client_prenom, @@ -3246,25 +3256,25 @@ class Bdd client.legal_one as client_legal_one, client.adresse as client_address, client.mail as client_mail, - client.is_tva as tva, + client.fk_client_group_id as fk_client_group_id FROM ".$this->tableprefix."client as client WHERE client.id = ?;"; $clientList = $this->execSQLNoJsonReturn( - $sql, - [$clientId] - ); + $sql, + [$clientId]); - if(!empty($clientList)) { + + if(!empty($clientList)){ return $clientList[0]; } return null; } - public function getClientsByClientsID(array $clientIds) - { - if(empty($clientIds)) { + public function getClientsByClientsID(array $clientIds){ + + if(empty($clientIds)){ return []; } @@ -3277,15 +3287,15 @@ class Bdd FROM ".$this->tableprefix."client as client WHERE client.id IN ($sqlConditionsPlaceholder);"; $clientList = $this->execSQLNoJsonReturn( - $sql, - $clientIds - ); + $sql, + $clientIds); + return $clientList; } - private function getInvoiceGroupDevisDatasByFactureId($factureId) - { + private function getInvoiceGroupDevisDatasByFactureId($factureId){ + $sql = "SELECT devis_facture.id as devis_facture_id, devis.id as devis_id, @@ -3326,46 +3336,47 @@ class Bdd WHERE devis_facture.fk_facture_id = ? ;"; $devis = $this->execSQLNoJsonReturn( - $sql, - [$factureId] - ); + $sql, + [$factureId]); + return $devis; } - public function getFactureByFactureId($factureId) - { + public function getFactureByFactureId($factureId){ + $sql = "SELECT * FROM ".$this->tableprefix."facture as facture WHERE facture.id = ? LIMIT 1; "; - $result = $this->execSQLNoJsonReturn($sql, [$factureId]); - if(!empty($result)) { + $result = $this->execSQLNoJsonReturn($sql,[$factureId]); + if(!empty($result)){ return $result[0]; } return null; } - public function getInvoicePdfData($factureId, $configuration) - { + + public function getInvoicePdfData($factureId,$configuration){ $factureData = $this->getFactureByIdWithDevis($factureId); - if($factureData == null) { + if($factureData == null){ return null; } $products = $this->getDevisProduits($factureData["devis_id"]); - $isDevisNegative = $this->isDevisNegative($factureData['devis_id'], $factureData['client_id']); + $isDevisNegative = $this->isDevisNegative($factureData['devis_id'],$factureData['client_id']); $factureData = $this->setDevisStartAndEndTime($factureData); $factureData["products"] = $products; $factureData["configuration"] = $configuration; - + $isClientInsideGroup = $factureData["group_id"] != null; - if($isClientInsideGroup) { + if($isClientInsideGroup){ $factureData["client_real_adress"] = $factureData["group_address"]; $factureData["client_adress_city"] = $factureData["group_postal_code"]." ".$factureData["group_city"]; $factureData["client_mail"] = $factureData["group_email"]; $factureData["siret"] = $factureData["group_siret_number"]; - } else { + } + else{ $factureData["siret"] = $factureData["client_legal_one"]; $clientAdresses = FileExportHelpers::GetAddressAndCityFromAddress($factureData["client_adresse"]); $factureData["client_real_adress"] = $clientAdresses["address"]; @@ -3379,13 +3390,13 @@ class Bdd return $factureData; } - private function getDevisByClientIdsListAndMonthYear($clientIds, $month, $year) - { - if(empty($clientIds)) { + private function getDevisByClientIdsListAndMonthYear($clientIds,$month,$year){ + + if(empty($clientIds)){ return []; } $clientSqlPlaceholders = implode(',', array_fill(0, count($clientIds), '?')); - $sql = "SELECT + $sql = "SELECT devis.id as devis_id, devis.date as devis_date, devis.num as calendar_uuid, @@ -3418,26 +3429,26 @@ class Bdd LEFT JOIN ".$this->tableprefix."thanato as thanato on devis.id_thanato = thanato.id WHERE devis.id_client IN ($clientSqlPlaceholders) AND YEAR(devis.date) = ?"; - + $conditions = array_merge( $clientIds, [$year] ); - if($month != 0) { + if($month != 0){ $conditions[] = $month; $sql .= " AND MONTH(devis.date) = ?"; } $sql .= ";"; $devisList = $this->execSQLNoJsonReturn( - $sql, - $conditions - ); + $sql, + $conditions); + return $devisList; } - private function getDevisByClientAndMonthYear($clientId, $month, $year) - { + private function getDevisByClientAndMonthYear($clientId,$month,$year){ + $sql = "SELECT devis.id as devis_id, devis.date as devis_date, @@ -3448,7 +3459,7 @@ class Bdd client.nom as client_nom, client.entreprise as client_entreprise, client.adresse as client_adresse, - client.is_tva as tva, + defunt.nom as defunt_nom, defunt.sexe as defunt_sexe, lieu.nom as lieu_nom, @@ -3471,54 +3482,56 @@ class Bdd LEFT JOIN ".$this->tableprefix."thanato as thanato on devis.id_thanato = thanato.id WHERE devis.id_client = ?"; + $conditions = [$clientId]; if($year != -1) { $conditions[] = $year; $sql .= " AND YEAR(devis.date) = ?"; } - if($month != 0) { + if($month != 0){ $conditions[] = $month; $sql .= " AND MONTH(devis.date) = ?"; } $sql .= ";"; $devisList = $this->execSQLNoJsonReturn( - $sql, - $conditions - ); + $sql, + $conditions); + return $devisList; } - public function getDevisPdfDataByClientGroupFacturationAndMonthYear($clientGroupFacturationId, $month, $year, $configuration) - { + public function getDevisPdfDataByClientGroupFacturationAndMonthYear($clientGroupFacturationId,$month,$year,$configuration){ + $clientIds = $this->getClientIdsByClientGroupFacturationId($clientGroupFacturationId); - $devisList = $this->getDevisByClientIdsListAndMonthYear($clientIds, $month, $year); + $devisList = $this->getDevisByClientIdsListAndMonthYear($clientIds,$month,$year); return $devisList; } - public function getDevisPdfDataByClientAndMonthYear($clientId, $month, $year, $configuration) - { - $devisList = $this->getDevisByClientAndMonthYear($clientId, $month, $year); + public function getDevisPdfDataByClientAndMonthYear($clientId,$month,$year,$configuration){ + + $devisList = $this->getDevisByClientAndMonthYear($clientId,$month,$year); return $devisList; } - public function getInvoicePdfDataByClientAndMonthYear($filter, $month, $year, $configuration, $filterType) - { + public function getInvoicePdfDataByClientAndMonthYear($filter,$month,$year,$configuration,$filterType){ + $isFilterByClient = $filterType === MultipleFactureTypeConstant::CLIENT_FILTER_TYPE; - if($isFilterByClient) { + if($isFilterByClient){ $invoices = $this->getInvoiceByClientAndMonthYear( clientId: $filter, month: $month, year: $year ); - } else { + } + else{ $invoices = $this->getInvoiceByClientGroupFacturationAndMonthYear( clientGroupFacturationId: $filter, month: $month, year: $year ); } - foreach($invoices as &$invoice) { + foreach($invoices as &$invoice){ $products = $this->getDevisProduits($invoice["devis_id"]); $invoice["products"] = $products; $invoice["configuration"] = $configuration; @@ -3531,12 +3544,13 @@ class Bdd $invoice["is_tva"] = $hasTva; $isClientInsideGroup = $invoice["group_id"] != null; - if($isClientInsideGroup) { + if($isClientInsideGroup){ $invoice["client_real_adress"] = $invoice["group_address"]; $invoice["client_adress_city"] = $invoice["group_postal_code"]." ".$invoice["group_city"]; $invoice["client_mail"] = $invoice["group_email"]; $invoice["siret"] = $invoice["group_siret_number"]; - } else { + } + else{ $invoice["siret"] = $invoice["client_legal_one"]; $clientAdresses = FileExportHelpers::GetAddressAndCityFromAddress($invoice["client_adresse"]); $invoice["client_real_adress"] = $clientAdresses["address"]; @@ -3550,31 +3564,31 @@ class Bdd return $invoices; } - private function getClientIdsByClientGroupFacturationId($clientGroupFacturationId) - { + private function getClientIdsByClientGroupFacturationId($clientGroupFacturationId){ + $sql = "SELECT client.id FROM ".$this->tableprefix."client as client WHERE client.fk_client_group_facturation_id = ? ;"; $clientIds = []; $clients = $this->execSQLNoJsonReturn( - $sql, - [$clientGroupFacturationId] - ); + $sql, + [$clientGroupFacturationId]); - if(!empty($clients)) { - foreach($clients as $client) { + + if(!empty($clients)){ + foreach($clients as $client){ $clientIds[] = $client["id"]; } } return $clientIds; } - private function getInvoiceByClientIdsListAndMonthYear($clientIds, $month, $year) - { + private function getInvoiceByClientIdsListAndMonthYear($clientIds,$month,$year){ + $clientIdsSqlPlaceholder = implode(',', array_fill(0, count($clientIds), '?')); - $sql = "SELECT + $sql = "SELECT facture.id, facture.date, facture.date_paiement, @@ -3590,7 +3604,7 @@ class Bdd client.prenom as client_prenom, client.entreprise as client_entreprise, client.adresse as client_adresse, - client.is_tva as tva, + client.mail as client_mail, client.legal_one as client_legal_one, defunt.nom as defunt_nom, @@ -3618,33 +3632,33 @@ class Bdd LEFT JOIN ".$this->tableprefix."client_group_facturation as client_group_facturation on client.fk_client_group_facturation_id = client_group_facturation.id WHERE client.id IN ($clientIdsSqlPlaceholder) AND YEAR(facture.date_paiement) = ?"; - - $conditions = array_merge($clientIds, [$year]); - if($month != 0) { + + $conditions = array_merge($clientIds,[$year]); + if($month != 0){ $conditions[] = $month; $sql .= " AND MONTH(facture.date_paiement) = ?"; } $sql .= ";"; $factures = $this->execSQLNoJsonReturn( - $sql, - $conditions - ); + $sql, + $conditions); + return $factures; } - private function getInvoiceByClientGroupFacturationAndMonthYear($clientGroupFacturationId, $month, $year) - { + private function getInvoiceByClientGroupFacturationAndMonthYear($clientGroupFacturationId,$month, $year){ + $clientIdsInsideClientFacturationGroup = $this->getClientIdsByClientGroupFacturationId($clientGroupFacturationId); - if(empty($clientIdsInsideClientFacturationGroup)) { + if(empty($clientIdsInsideClientFacturationGroup)){ return []; } - return $this->getInvoiceByClientIdsListAndMonthYear($clientIdsInsideClientFacturationGroup, $month, $year); + return $this->getInvoiceByClientIdsListAndMonthYear($clientIdsInsideClientFacturationGroup,$month,$year); } - private function getInvoiceByClientAndMonthYear($clientId, $month, $year) - { - $sql = "SELECT + private function getInvoiceByClientAndMonthYear($clientId,$month,$year){ + + $sql = "SELECT facture.id, facture.date, facture.date_paiement, @@ -3688,6 +3702,7 @@ class Bdd LEFT JOIN ".$this->tableprefix."client_group_facturation as client_group_facturation on client.fk_client_group_facturation_id = client_group_facturation.id WHERE client.id = ?"; + $conditions = [$clientId]; if ($year != -1) { @@ -3695,23 +3710,23 @@ class Bdd $conditions[] = $year; $sql .= " AND YEAR(facture.date_paiement) = ?"; } - if($month != 0) { + if($month != 0){ $conditions[] = $month; $sql .= " AND MONTH(facture.date_paiement) = ?"; } $sql .= ";"; $factures = $this->execSQLNoJsonReturn( - $sql, - $conditions - ); + $sql, + $conditions); + return $factures; } - public function getDevisPdfDataByDevisId($devisId) - { - $sql = "SELECT + public function getDevisPdfDataByDevisId($devisId){ + + $sql = "SELECT devis.id as devis_id, devis.date as devis_date, devis.num as calendar_uuid, @@ -3735,18 +3750,18 @@ class Bdd WHERE devis.id = ? ;"; $devis = $this->execSQLNoJsonReturn( - $sql, - [$devisId] - ); - if(!empty($devis)) { + $sql, + [$devisId]); + + if(!empty($devis)){ return $devis[0]; } return null; } - private function getFactureByIdWithDevis($factureId) - { - $sql = "SELECT + private function getFactureByIdWithDevis($factureId){ + + $sql = "SELECT facture.id, facture.date, facture.date_paiement, @@ -3789,29 +3804,29 @@ class Bdd WHERE facture.id = ? ;"; $facture = $this->execSQLNoJsonReturn( - $sql, - [$factureId] - ); - if(!empty($facture)) { + $sql, + [$factureId]); + + if(!empty($facture)){ return $facture[0]; } return null; } - public function getProduitsListAsArray() - { + public function getProduitsListAsArray(){ + $sql = "SELECT * FROM ".$this->tableprefix."produit as produit;"; $produitList = $this->execSQLNoJsonReturn( - $sql, - [] - ); + $sql, + []); + return $produitList; } - public function getArticleIdsByArticleReferences(array $articleReferences) - { + public function getArticleIdsByArticleReferences(array $articleReferences){ + $articleIds = []; foreach ($articleReferences as $reference) { $reference = trim($reference); @@ -3824,115 +3839,115 @@ class Bdd return $articleIds; } - public function addNumberColumnOnDevis() - { + public function addNumberColumnOnDevis(){ + $sql = "ALTER TABLE ". $this->tableprefix."devis ADD devis_number INT DEFAULT 1;" ; $this->execSQLNoJsonReturn( - $sql, - [] - ); + $sql, + []); + $sql = "ALTER TABLE ". $this->tableprefix."devis ADD devis_full_number VARCHAR(255);" ; $this->execSQLNoJsonReturn( - $sql, - [] - ); + $sql, + []); + $sql = "UPDATE ".$this->tableprefix."devis as devis SET devis.devis_full_number = CONCAT('DEV', YEAR(devis.date) % 100, LPAD(MONTH(devis.date), 2, '0'), LPAD(devis.devis_number, 2, '0'));"; $this->execSQLNoJsonReturn( - $sql, - [] - ); + $sql, + []); + return true; } - public function addNumberColumnOnFacture() - { + public function addNumberColumnOnFacture(){ + $sql = "ALTER TABLE ". $this->tableprefix."facture ADD facture_number INT DEFAULT 1;" ; $this->execSQLNoJsonReturn( - $sql, - [] - ); + $sql, + []); + $sql = "UPDATE ".$this->tableprefix."facture as facture SET facture.num = CONCAT('FAC', YEAR(facture.date) % 100, LPAD(MONTH(facture.date), 2, '0'), LPAD(facture.facture_number, 2, '0'));"; $this->execSQLNoJsonReturn( - $sql, - [] - ); + $sql, + []); + return true; } - private function getLastFactureNumberByMonthAndYear($month, $year) - { + private function getLastFactureNumberByMonthAndYear($month,$year){ + $sql = "SELECT - max(facture.facture_number) as LAST_FACTURE_NUMBER, facture.date FROM " + max(facture.facture_number) as LAST_FACTURE_NUMBER, facture.date FROM " . $this->tableprefix."facture as facture WHERE YEAR(facture.date) = ? AND MONTH(facture.date) = ?;"; - $res = $this->execSQLNoJsonReturn($sql, array($year,$month)); + $res = $this->execSQLNoJsonReturn($sql,array($year,$month)); $lastNumber = 0; - if(!empty($res)) { + if(!empty($res)){ $lastNumber = $res[0]['LAST_FACTURE_NUMBER']; } return $lastNumber; } - public function getFactureNumberByDate($datetime) - { + public function getFactureNumberByDate($datetime){ + $month = $datetime->format('m'); $year = $datetime->format('Y'); - $lastFactureNumber = $this->getLastFactureNumberByMonthAndYear($month, $year); + $lastFactureNumber = $this->getLastFactureNumberByMonthAndYear($month,$year); $factureNumber = $lastFactureNumber + 1; return $factureNumber; } - public function getFactureFullNumberByDate($datetime) - { + public function getFactureFullNumberByDate($datetime){ + $factureNumber = $this->getFactureNumberByDate($datetime); - $factureFullNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($datetime, $factureNumber, 'FAC'); + $factureFullNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($datetime,$factureNumber,'FAC'); return $factureFullNumber; } - public function getDevisNumberByDate($datetime) - { + public function getDevisNumberByDate($datetime){ + $month = $datetime->format('m'); $year = $datetime->format('Y'); - $lastDevisNumber = $this->getLastDevisNumberByMonthAndYear($month, $year); + $lastDevisNumber = $this->getLastDevisNumberByMonthAndYear($month,$year); $devisNumber = $lastDevisNumber + 1; return $devisNumber; } - public function getDevisFullNumberByDate($datetime) - { + public function getDevisFullNumberByDate($datetime){ + $devisNumber = $this->getDevisNumberByDate($datetime); - $devisFullNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($datetime, $devisNumber, 'DEV'); + $devisFullNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($datetime,$devisNumber,'DEV'); return $devisFullNumber; } - public function getFirstClient() - { + public function getFirstClient(){ + $sql = "SELECT * FROM ".$this->tableprefix."client as client LIMIT 1;"; $client = $this->execSQLNoJsonReturn( - $sql, - [] - ); + $sql, + []); - if(!empty($client)) { + + if(!empty($client)){ return $client[0]; } - + return null; } - public function getClientGroupDiscounts() - { + public function getClientGroupDiscounts(){ + $sql = "SELECT client_group_discount.id as id, @@ -3948,61 +3963,61 @@ class Bdd LEFT JOIN ".$this->tableprefix."produit as produit on client_group_discount.fk_produit_id = produit.id ORDER BY client_group_discount.id DESC "; - + $clientGroupDiscounts = $this->execSQL( - $sql, - [] - ); + $sql, + []); + return $clientGroupDiscounts; } - public function getClientGroups() - { + public function getClientGroups(){ + $sql = "SELECT * FROM ".$this->tableprefix."client_group as client_group ORDER BY client_group.id DESC;"; - $clientGroups = $this->execSQL($sql, []); + $clientGroups = $this->execSQL($sql,[]); return $clientGroups; } - public function createDefaultClientGroup() - { + public function createDefaultClientGroup(){ + $sql = "INSERT INTO `".$this->tableprefix."client_group` (`client_group_name`) VALUES (?);"; $this->execSQLNoData($sql, array(self::DEFAULT_CLIENT_GROUP_NAME)); return true; } - public function createDefaultClientGroupDiscount() - { + public function createDefaultClientGroupDiscount(){ + $sql = "INSERT INTO `".$this->tableprefix."client_group_discount` (`fk_client_group_id`,`fk_produit_id`,`ht_amount`) VALUES (0,0,0);"; $this->execSQLNoData($sql, array()); return true; } - public function getClientGroupCount() - { + public function getClientGroupCount(){ + $sql = "SELECT count(*) as c from ".$this->tableprefix."client_group;"; return $this->execSQL($sql, array()); } - public function getClientGroupDiscountCount() - { + public function getClientGroupDiscountCount(){ + $sql = "SELECT count(*) as c from ".$this->tableprefix."client_group_discount;"; return $this->execSQL($sql, array()); } - public function addClientGroupDiscountFeatureTables() - { + public function addClientGroupDiscountFeatureTables(){ + $createTableClientGroupSQL = "CREATE TABLE oc_gestion_client_group ( id INT PRIMARY KEY AUTO_INCREMENT, client_group_name VARCHAR(255) DEFAULT '' );"; - $this->execSQLNoData($createTableClientGroupSQL, []); + $this->execSQLNoData($createTableClientGroupSQL,[]); - $addColumnFkClientGroupIdIntoClientTableSQL = "ALTER TABLE oc_gestion_client + $addColumnFkClientGroupIdIntoClientTableSQL= "ALTER TABLE oc_gestion_client ADD fk_client_group_id INT NULL;"; - $this->execSQLNoData($addColumnFkClientGroupIdIntoClientTableSQL, []); + $this->execSQLNoData($addColumnFkClientGroupIdIntoClientTableSQL,[]); $createTableClientGroupDiscountSQL = "CREATE TABLE oc_gestion_client_group_discount ( id INT PRIMARY KEY AUTO_INCREMENT, @@ -4011,13 +4026,13 @@ class Bdd ht_amount FLOAT NOT NULL );"; - $this->execSQLNoData($createTableClientGroupDiscountSQL, []); + $this->execSQLNoData($createTableClientGroupDiscountSQL,[]); return true; } - public function getDevisOfDefunt($defuntId) - { + public function getDevisOfDefunt($defuntId){ + $sql = "SELECT devis.id as id, devis.date as devis_date, @@ -4047,18 +4062,18 @@ class Bdd LEFT JOIN ".$this->tableprefix."client_group_facturation as client_group_facturation on client.fk_client_group_facturation_id = client_group_facturation.id LEFT JOIN ".$this->tableprefix."thanato as thanato on devis.id_thanato = thanato.id WHERE devis.id_defunt = ? ;"; + + $devisOfDefunt = $this->execSQLNoJsonReturn($sql, [$defuntId]); - $devisOfDefunt = $this->execSQLNoJsonReturn($sql, [$defuntId]); - - if(!empty($devisOfDefunt)) { + if(!empty( $devisOfDefunt)){ return $devisOfDefunt[0]; } return null; } + + private function getDefuntById($defuntId){ - private function getDefuntById($defuntId) - { $sql = "SELECT defunt.id as id, defunt.nom as defunt_nom, @@ -4068,28 +4083,28 @@ class Bdd WHERE defunt.id = ? LIMIT 1;"; - $defunt = $this->execSQLNoJsonReturn($sql, [$defuntId]); - if(!empty($defunt)) { + $defunt = $this->execSQLNoJsonReturn($sql,[$defuntId]); + if(!empty($defunt)){ return $defunt[0]; } return null; } - private function getProductAsDefuntCoverProduct($productCoverId) - { + private function getProductAsDefuntCoverProduct($productCoverId){ + $product = $this->getProductByProductId($productCoverId); - if($product == null) { + if($product == null){ return null; } $productCoverType = $this->getProductTypeByKey(ProductConstant::PRODUCT_COVER_TYPE_KEY); - if($product["fk_product_type_id"] == $productCoverType["id"]) { + if($product["fk_product_type_id"] == $productCoverType["id"]){ return $product; } return null; } - private function isProductAlreadyExistInDevis($productId, $devisId) - { + private function isProductAlreadyExistInDevis($productId,$devisId){ + $sql = "SELECT produit_devis.id FROM ".$this->tableprefix."produit_devis as produit_devis @@ -4097,25 +4112,25 @@ class Bdd produit_devis.devis_id = ? LIMIT 1;"; - $product = $this->execSQLNoJsonReturn($sql, [$productId,$devisId]); - if(!empty($product)) { + $product = $this->execSQLNoJsonReturn($sql,[$productId,$devisId]); + if(!empty($product)){ return true; } return false; } - private function removeProductFromDevis($productId, $devisId) - { + private function removeProductFromDevis($productId,$devisId){ + $sql = "DELETE FROM ". $this->tableprefix."produit_devis WHERE devis_id = ? AND produit_id = ? "; - $this->execSQLNoData($sql, [$devisId,$productId]); + $this->execSQLNoData($sql,[$devisId,$productId]); } - private function getProductByReference($productReference) - { + private function getProductByReference($productReference){ + $sql = "SELECT produit.id, produit.reference @@ -4123,32 +4138,32 @@ class Bdd WHERE produit.reference = ? LIMIT 1;"; - $product = $this->execSQLNoJsonReturn($sql, [$productReference]); - if(!empty($product)) { + $product = $this->execSQLNoJsonReturn($sql,[$productReference]); + if(!empty($product)){ return $product[0]; } return null; } - private function removeProductFromDevisByProductReference($productReference, $devisId) - { + private function removeProductFromDevisByProductReference($productReference,$devisId){ + $product = $this->getProductByReference($productReference); - if($product != null) { - $this->removeProductFromDevis($product["id"], $devisId); + if($product != null){ + $this->removeProductFromDevis($product["id"],$devisId); } } - private function createProductDevisIfNotExist($productId, $devisId) - { - $isProductDevisAlreadyExist = $this->isProductAlreadyExistInDevis($productId, $devisId); - if(!$isProductDevisAlreadyExist) { + private function createProductDevisIfNotExist($productId,$devisId){ + + $isProductDevisAlreadyExist = $this->isProductAlreadyExistInDevis($productId,$devisId); + if(!$isProductDevisAlreadyExist){ $idNextcloud = "admin"; - $this->insertDevisArticle(devisId: $devisId, articleId: $productId, idNextcloud: $idNextcloud); + $this->insertDevisArticle(devisId: $devisId, articleId: $productId,idNextcloud: $idNextcloud); } } - private function getProductByProductId($productId) - { + private function getProductByProductId($productId){ + $sql = "SELECT produit.id, produit.reference, @@ -4156,59 +4171,60 @@ class Bdd FROM ".$this->tableprefix."produit as produit WHERE produit.id = ? LIMIT 1;"; - - $result = $this->execSQLNoJsonReturn($sql, [$productId]); - if(!empty($result)) { + + $result = $this->execSQLNoJsonReturn($sql,[$productId]); + if(!empty($result)){ return $result[0]; } return null; } - private function deleteProductsInDevisByProductType($devisId, $productTypeId) - { + private function deleteProductsInDevisByProductType($devisId,$productTypeId){ + $sql = "DELETE produit_devis FROM ".$this->tableprefix."produit_devis as produit_devis LEFT JOIN ".$this->tableprefix."produit as produit ON produit_devis.produit_id = produit.id WHERE produit_devis.devis_id = ? AND produit.fk_product_type_id = ?;"; - $this->execSQLNoData($sql, [$devisId,$productTypeId]); + $this->execSQLNoData($sql,[$devisId,$productTypeId]); } - public function setDefuntCover($defuntId, $productCoverId) - { + public function setDefuntCover($defuntId, $productCoverId){ + $defunt = $this->getDefuntById($defuntId); - if($defunt == null) { + if($defunt == null){ return null; } - if($defunt["devis_id"] == null) { + if($defunt["devis_id"] == null){ return null; } - if($productCoverId == null) { + if($productCoverId == null){ $productTypeCover = $this->getProductTypeByKey(ProductConstant::PRODUCT_COVER_TYPE_KEY); - $this->deleteProductsInDevisByProductType($defunt["devis_id"], $productTypeCover['id']); + $this->deleteProductsInDevisByProductType($defunt["devis_id"],$productTypeCover['id']); return true; } $product = $this->getProductAsDefuntCoverProduct($productCoverId); - if($product == null) { + if($product == null){ return null; } - + $coverProductList = $this->getProductsByProductTypeKey(ProductConstant::PRODUCT_COVER_TYPE_KEY); $coverProductList = json_decode($coverProductList); - foreach($coverProductList as $currentCoverProduct) { - if($currentCoverProduct->id == $product["id"]) { - $this->createProductDevisIfNotExist($product["id"], $defunt["devis_id"]); - } else { - $this->removeProductFromDevis($currentCoverProduct->id, $defunt["devis_id"]); + foreach($coverProductList as $currentCoverProduct){ + if($currentCoverProduct->id == $product["id"]){ + $this->createProductDevisIfNotExist($product["id"],$defunt["devis_id"]); + } + else{ + $this->removeProductFromDevis($currentCoverProduct->id,$defunt["devis_id"]); } } return true; } - private function getProductsByProductTypeKey(string $productTypeKey) - { + private function getProductsByProductTypeKey(string $productTypeKey){ + $sql = "SELECT produit.id, produit.reference, @@ -4217,17 +4233,17 @@ class Bdd LEFT JOIN ".$this->tableprefix."product_type as product_type on produit.fk_product_type_id = product_type.id WHERE product_type.product_type_key = ?;"; - $products = $this->execSQL($sql, [$productTypeKey]); + $products = $this->execSQL($sql,[$productTypeKey]); return $products; } - public function getCoverProducts() - { + public function getCoverProducts(){ + return $this->getProductsByProductTypeKey(ProductConstant::PRODUCT_COVER_TYPE_KEY); } - private function getProductTypeByKey(string $key) - { + private function getProductTypeByKey(string $key){ + $sql = "SELECT product_type.id, product_type.product_type_name, @@ -4235,15 +4251,15 @@ class Bdd FROM ".$this->tableprefix."product_type as product_type WHERE product_type.product_type_key = ?;"; - $productType = $this->execSQLNoJsonReturn($sql, [$key]); - if(!empty($productType)) { + $productType = $this->execSQLNoJsonReturn($sql,[$key]); + if(!empty($productType)){ return $productType[0]; } return null; } - private function getProductCoverByDevisId($devisId) - { + private function getProductCoverByDevisId($devisId){ + $coverProductType = $this->getProductTypeByKey(ProductConstant::PRODUCT_COVER_TYPE_KEY); $sql = "SELECT @@ -4256,33 +4272,33 @@ class Bdd LEFT JOIN ".$this->tableprefix."produit as produit on produit_devis.produit_id = produit.id WHERE produit_devis.devis_id = ? AND produit.fk_product_type_id = ? LIMIT 1"; - - $productCover = $this->execSQLNoJsonReturn($sql, [$devisId,$coverProductType["id"]]); - if($productCover) { + + $productCover = $this->execSQLNoJsonReturn($sql,[$devisId,$coverProductType["id"]]); + if($productCover){ return $productCover[0]; } return null; } - private function getDevisByIdWithCalendarDataAndProducts($devisId, $idNextcloud) - { - $devis = $this->getOneDevis($devisId, $idNextcloud); - $devis = json_decode($devis); - if(empty($devis)) { + private function getDevisByIdWithCalendarDataAndProducts($devisId,$idNextcloud){ + + $devis = $this->getOneDevis($devisId,$idNextcloud); + $devis= json_decode($devis); + if(empty($devis)){ return null; } $devis = $devis[0]; - if(isset($devis->numm) && $devis->num == null) { + if(isset($devis->numm) && $devis->num == null){ return null; } $calendarData = $this->getCalendarDataByCalendarObjectUuid($devis->num); $devisTimeValue = VCalendarHelpers::GetStartAndEndTimeFromVCalendarString($calendarData); $startTimeValueWithMinutes = ""; $endTimeValueWithMinutes = ""; - if($devisTimeValue["datetimeStart"]) { + if($devisTimeValue["datetimeStart"]){ $startTimeValueWithMinutes = $devisTimeValue["datetimeStart"]->format('H\hi'); } - if($devisTimeValue["datetimeEnd"]) { + if($devisTimeValue["datetimeEnd"]){ $endTimeValueWithMinutes = $devisTimeValue["datetimeEnd"]->format('H\hi'); } $devis->startTime = $startTimeValueWithMinutes; @@ -4294,37 +4310,37 @@ class Bdd return $devis; } - private function getDevisTalkRoomProductSectionMessage($devisProducts) - { - if(empty($devisProducts)) { + private function getDevisTalkRoomProductSectionMessage($devisProducts){ + + if(empty($devisProducts)){ return ""; } $productMessage = "ACTE A FAIRE : "; - foreach($devisProducts as $product) { - $productMessage .= html_entity_decode($product->produit_reference).", "; + foreach($devisProducts as $product){ + $productMessage.= html_entity_decode($product->produit_reference).", "; } - $productMessage = trim($productMessage); - $productMessage = rtrim($productMessage, ","); + $productMessage = trim( $productMessage ); + $productMessage = rtrim($productMessage,","); return $productMessage; } - private function getDevisTalkRoomClientContent($clientPrenom) - { + private function getDevisTalkRoomClientContent($clientPrenom){ + $message = "Pour PF: "; $clientNameContent = "aucun"; $clientPrenomIsSet = $clientPrenom != null && $clientPrenom != "" && $clientPrenom != "-"; - if($clientPrenomIsSet) { + if($clientPrenomIsSet){ $clientNameContent = html_entity_decode($clientPrenom); } $message .= $clientNameContent; return $message; } + + public function getDevisTalkRoomMessage($devisId,$idNextcloud){ - public function getDevisTalkRoomMessage($devisId, $idNextcloud) - { - $devis = $this->getDevisByIdWithCalendarDataAndProducts($devisId, $idNextcloud); - if($devis == null) { + $devis = $this->getDevisByIdWithCalendarDataAndProducts($devisId,$idNextcloud); + if($devis == null){ return null; } $devisDate = new Datetime($devis->date); @@ -4344,7 +4360,7 @@ le '.$devisDate; $message .= ' '.$productMessage; $comment = "aucun"; - if(strtolower($devis->comment) != "commentaire" && $devis->comment != "") { + if(strtolower($devis->comment) != "commentaire" && $devis->comment != ""){ $comment = html_entity_decode($devis->comment); } $message .= " @@ -4355,9 +4371,9 @@ COMMENTAIRES: ".$comment; "Code funéraire" => $devis->funeral_code ]; $locationCodeMessageContent = ""; - foreach($locationCodes as $label => $code) { + foreach($locationCodes as $label => $code){ $value = "Aucun"; - if($code != null && trim($code) != "") { + if($code != null && trim($code) != ""){ $value = $code; } $locationCodeMessageContent .= $label. ": ".$value.". "; @@ -4368,9 +4384,9 @@ COMMENTAIRES: ".$comment; return $message; } - public function getDevisByCalendarUuid($calendarUuid) - { - if($calendarUuid === self::DEFAULT_CALENDAR_UUID_FOR_DEVIS) { + public function getDevisByCalendarUuid($calendarUuid){ + + if($calendarUuid === self::DEFAULT_CALENDAR_UUID_FOR_DEVIS){ return null; } $sql = "SELECT @@ -4389,37 +4405,38 @@ COMMENTAIRES: ".$comment; WHERE devis.num = ? ;"; $devis = $this->execSQLNoJsonReturn($sql, array($calendarUuid)); - if(empty($devis)) { + if(empty($devis)){ return null; } return $devis[0]; } + + public function updateDevisMentionToCanceled($devisId){ - public function updateDevisMentionToCanceled($devisId) - { - $sql = "UPDATE ".$this->tableprefix."devis as devis + $sql= "UPDATE ".$this->tableprefix."devis as devis SET devis.mentions = ? WHERE devis.id = ?"; - $this->execSQLNoData($sql, [DevisMentionConstant::CANCELED,$devisId]); + $this->execSQLNoData($sql,[DevisMentionConstant::CANCELED,$devisId]); } - private function updateDefuntByName($defuntId, $requestedDefuntName) - { - $sql = "UPDATE ".$this->tableprefix."defunt as defunt + private function updateDefuntByName($defuntId,$requestedDefuntName){ + + $sql= "UPDATE ".$this->tableprefix."defunt as defunt SET defunt.nom = ? WHERE defunt.id = ?"; - $this->execSQLNoData($sql, [$requestedDefuntName,$defuntId]); + $this->execSQLNoData($sql,[$requestedDefuntName,$defuntId]); } - public function createOrUpdateDefuntByNameAndReturnDefuntId($defuntId, $currentDefuntName, $requestedDefuntName) - { - if($defuntId != null) { + public function createOrUpdateDefuntByNameAndReturnDefuntId($defuntId,$currentDefuntName,$requestedDefuntName){ + + if($defuntId != null){ $defuntNameIsUpdated = $currentDefuntName != $requestedDefuntName; - if($defuntNameIsUpdated) { - $this->updateDefuntByName($defuntId, $requestedDefuntName); + if($defuntNameIsUpdated){ + $this->updateDefuntByName($defuntId,$requestedDefuntName); } - } else { + } + else{ $this->insertDefuntByName($requestedDefuntName); $defunt = $this->getLastDefuntIdByName($requestedDefuntName); $defuntId = $defunt['id']; @@ -4427,207 +4444,207 @@ COMMENTAIRES: ".$comment; return $defuntId; } - public function updateDevisDefunt($devisId, $requestedDefuntId, $currentDefuntId = null) - { + public function updateDevisDefunt($devisId,$requestedDefuntId,$currentDefuntId = null){ + $defuntIsUpdated = $currentDefuntId != $requestedDefuntId; - if($defuntIsUpdated) { - $sql = "UPDATE ".$this->tableprefix."devis as devis + if($defuntIsUpdated){ + $sql= "UPDATE ".$this->tableprefix."devis as devis SET devis.id_defunt = ? WHERE devis.id = ?"; - $this->execSQLNoData($sql, [$requestedDefuntId,$devisId]); + $this->execSQLNoData($sql,[$requestedDefuntId,$devisId]); } } - public function updateDevisThanato($devisId, $requestedThanatoId) - { - $sql = "UPDATE ".$this->tableprefix."devis as devis + public function updateDevisThanato($devisId,$requestedThanatoId){ + + $sql= "UPDATE ".$this->tableprefix."devis as devis SET devis.id_thanato = ? WHERE devis.id = ?"; - $this->execSQLNoData($sql, [$requestedThanatoId,$devisId]); + $this->execSQLNoData($sql,[$requestedThanatoId,$devisId]); } - public function updateDevisClient($devisId, $requestedClientId, $currentClientId = null) - { + public function updateDevisClient($devisId,$requestedClientId,$currentClientId = null){ + $clientIsUpdated = $currentClientId != $requestedClientId; - if($clientIsUpdated) { - $sql = "UPDATE ".$this->tableprefix."devis as devis + if($clientIsUpdated){ + $sql= "UPDATE ".$this->tableprefix."devis as devis SET devis.id_client = ? WHERE devis.id = ?"; - $this->execSQLNoData($sql, [$requestedClientId,$devisId]); + $this->execSQLNoData($sql,[$requestedClientId,$devisId]); } } - public function updateDevisLieu($devisId, $requestedLieuId, $currentLieuId = null) - { + public function updateDevisLieu($devisId,$requestedLieuId,$currentLieuId = null){ + $lieuIsUpdated = $currentLieuId != $requestedLieuId; - if($lieuIsUpdated) { - $sql = "UPDATE ".$this->tableprefix."devis as devis + if($lieuIsUpdated){ + $sql= "UPDATE ".$this->tableprefix."devis as devis SET devis.id_lieu = ? WHERE devis.id = ?"; - $this->execSQLNoData($sql, [$requestedLieuId,$devisId]); + $this->execSQLNoData($sql,[$requestedLieuId,$devisId]); } } - public function updateDevisComment($devisId, $requestedComment, $currentComment = null) - { + public function updateDevisComment($devisId,$requestedComment,$currentComment = null){ + $commentIsUpdated = $currentComment != $requestedComment; - if($commentIsUpdated) { - $sql = "UPDATE ".$this->tableprefix."devis as devis + if($commentIsUpdated){ + $sql= "UPDATE ".$this->tableprefix."devis as devis SET devis.comment = ? WHERE devis.id = ?"; - $this->execSQLNoData($sql, [$requestedComment,$devisId]); + $this->execSQLNoData($sql,[$requestedComment,$devisId]); } } - public function updateDevisDate($devisId, $requestedDate) - { - $sql = "UPDATE ".$this->tableprefix."devis as devis + public function updateDevisDate($devisId,$requestedDate){ + + $sql= "UPDATE ".$this->tableprefix."devis as devis SET devis.date = ? WHERE devis.id = ?"; - $this->execSQLNoData($sql, [$requestedDate,$devisId]); + $this->execSQLNoData($sql,[$requestedDate,$devisId]); } - public function deleteDevisProduit($devisProductId) - { + public function deleteDevisProduit($devisProductId){ + $sql = "DELETE FROM ".$this->tableprefix."produit_devis WHERE id = ?;"; $this->execSQLNoData($sql, array($devisProductId)); } - public function updateDevisArticles($devisId, $requestedArticlesIds) - { + public function updateDevisArticles($devisId,$requestedArticlesIds){ + $currentDevisProducts = $this->getDevisProduits($devisId); $currentDevisProduitIds = []; //delete old product - foreach($currentDevisProducts as $devisProduct) { + foreach($currentDevisProducts as $devisProduct){ $currentDevisProduitIds[] = $devisProduct['produit_id']; - $currentProductIsNotPartOfRequestedDevisProduct = !in_array($devisProduct['produit_id'], $requestedArticlesIds); - if($currentProductIsNotPartOfRequestedDevisProduct) { + $currentProductIsNotPartOfRequestedDevisProduct = !in_array($devisProduct['produit_id'],$requestedArticlesIds); + if($currentProductIsNotPartOfRequestedDevisProduct){ $this->deleteDevisProduit($devisProduct['id']); } } - + //add new requested product - foreach($requestedArticlesIds as $requestedArticleId) { - $currentRequestedArticleIsNewArticleForDevis = !in_array($requestedArticleId, $currentDevisProduitIds); - if($currentRequestedArticleIsNewArticleForDevis) { - $this->insertDevisArticle(devisId: $devisId, articleId: $requestedArticleId, idNextcloud: BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD); + foreach($requestedArticlesIds as $requestedArticleId){ + $currentRequestedArticleIsNewArticleForDevis = !in_array($requestedArticleId,$currentDevisProduitIds); + if($currentRequestedArticleIsNewArticleForDevis){ + $this->insertDevisArticle(devisId: $devisId, articleId: $requestedArticleId,idNextcloud: BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD); } } } - public function addClientGroupFacturationFeatureTables() - { + public function addClientGroupFacturationFeatureTables(){ + $createTableClientGroupSQL = "CREATE TABLE oc_gestion_client_group_facturation ( id INT PRIMARY KEY AUTO_INCREMENT, group_facturation_name VARCHAR(255) DEFAULT '' );"; - $this->execSQLNoData($createTableClientGroupSQL, []); + $this->execSQLNoData($createTableClientGroupSQL,[]); - $addColumnFkClientGroupFacturationIdIntoClientTableSQL = "ALTER TABLE oc_gestion_client + $addColumnFkClientGroupFacturationIdIntoClientTableSQL= "ALTER TABLE oc_gestion_client ADD fk_client_group_facturation_id INT NULL;"; - $this->execSQLNoData($addColumnFkClientGroupFacturationIdIntoClientTableSQL, []); + $this->execSQLNoData($addColumnFkClientGroupFacturationIdIntoClientTableSQL,[]); return true; } - private function getClientGroupFacturationsWithType() - { + private function getClientGroupFacturationsWithType(){ + $sql = "SELECT client_group_facturation.id as id, client_group_facturation.group_facturation_name as nom, 'group' as client_type FROM ".$this->tableprefix."client_group_facturation as client_group_facturation ORDER BY client_group_facturation.id DESC;"; - $clientGroupFacturations = $this->execSQLNoJsonReturn($sql, []); + $clientGroupFacturations = $this->execSQLNoJsonReturn($sql,[]); return $clientGroupFacturations; } - public function getClientGroupFacturations() - { + public function getClientGroupFacturations(){ + $sql = "SELECT * FROM ".$this->tableprefix."client_group_facturation as client_group_facturation ORDER BY client_group_facturation.id DESC;"; - $clientGroupFacturations = $this->execSQL($sql, []); + $clientGroupFacturations = $this->execSQL($sql,[]); return $clientGroupFacturations; } - public function createDefaultGroupFacturation() - { + public function createDefaultGroupFacturation(){ + $sql = "INSERT INTO `".$this->tableprefix."client_group_facturation` (`group_facturation_name`) VALUES (?);"; $this->execSQLNoData($sql, array(self::DEFAULT_CLIENT_GROUP_FACTURATION_NAME)); return true; } - public function getClientGroupFacturationById($clientGroupFacturationId) - { + public function getClientGroupFacturationById($clientGroupFacturationId){ + $sql = "SELECT * FROM ".$this->tableprefix."client_group_facturation as client_group_facturation WHERE client_group_facturation.id = ? ;"; $clientGroupFacturation = $this->execSQLNoJsonReturn($sql, array($clientGroupFacturationId)); - if(!empty($clientGroupFacturation)) { + if(!empty($clientGroupFacturation)){ return $clientGroupFacturation[0]; } return null; } - public function getClientGroupFacturationCount() - { + public function getClientGroupFacturationCount(){ + $sql = "SELECT count(*) as c from ".$this->tableprefix."client_group_facturation;"; return $this->execSQL($sql, array()); } + + public function addProductTypeTables(){ - public function addProductTypeTables() - { $sql = "CREATE TABLE oc_gestion_product_type ( id INT PRIMARY KEY AUTO_INCREMENT, product_type_key VARCHAR(255) DEFAULT '', product_type_name VARCHAR(255) DEFAULT '' );"; - $this->execSQLNoData($sql, []); + $this->execSQLNoData($sql,[]); $sql = "ALTER TABLE oc_gestion_produit ADD fk_product_type_id INT NULL;"; - - $this->execSQLNoData($sql, []); + + $this->execSQLNoData($sql,[]); $sql = "INSERT INTO oc_gestion_product_type (product_type_key,product_type_name) VALUES (?,?);"; - $this->execSQLNoData($sql, [ProductConstant::PRODUCT_COVER_TYPE_KEY,ProductConstant::PRODUCT_COVER_TYPE_NAME]); + $this->execSQLNoData($sql,[ProductConstant::PRODUCT_COVER_TYPE_KEY,ProductConstant::PRODUCT_COVER_TYPE_NAME]); } - public function getProductTypes() - { + public function getProductTypes(){ + $sql = "SELECT * FROM ".$this->tableprefix."product_type;"; - $productTypes = $this->execSQL($sql, []); + $productTypes = $this->execSQL($sql,[]); return $productTypes; } - public function addLocationCodesColumn() - { + public function addLocationCodesColumn(){ + $sql = "ALTER TABLE oc_gestion_lieu ADD portal_code VARCHAR(255) DEFAULT NULL;"; - $this->execSQLNoData($sql, []); + $this->execSQLNoData($sql,[]); $sql = "ALTER TABLE oc_gestion_lieu ADD alarm_code VARCHAR(255) DEFAULT NULL;"; - $this->execSQLNoData($sql, []); + $this->execSQLNoData($sql,[]); $sql = "ALTER TABLE oc_gestion_lieu ADD funeral_code VARCHAR(255) DEFAULT NULL;"; - $this->execSQLNoData($sql, []); + $this->execSQLNoData($sql,[]); } - public function updateDevisMention(int $devisId, string $mention) - { + public function updateDevisMention(int $devisId,string $mention){ + $sql = "UPDATE ".$this->tableprefix."devis as devis SET devis.mentions = ? WHERE devis.id = ?;"; - $this->execSQLNoData($sql, [$mention,$devisId]); + $this->execSQLNoData($sql,[$mention,$devisId]); } - public function getBijouxWithDefuntByBijouxId($bijouxId) - { + public function getBijouxWithDefuntByBijouxId($bijouxId){ + $sql = "SELECT bijou.id, bijou.defunt_id, @@ -4639,80 +4656,80 @@ COMMENTAIRES: ".$comment; LEFT JOIN ".$this->tableprefix."defunt as defunt on bijou.defunt_id = defunt.id WHERE bijou.id = ? ;"; - $bijoux = $this->execSQLNoJsonReturn($sql, [$bijouxId,]); - if(!empty($bijoux)) { + $bijoux = $this->execSQLNoJsonReturn($sql,[$bijouxId,]); + if(!empty($bijoux)){ return $bijoux[0]; } return null; } - public function saveBijouxPhoto($bijouxId, $photo, $photoRealName) - { + public function saveBijouxPhoto($bijouxId,$photo,$photoRealName){ + $sql = "UPDATE ".$this->tableprefix."bijou_defunt as bijou_defunt SET bijou_defunt.photo = ?,bijou_defunt.photo_name = ? WHERE bijou_defunt.id = ? ;"; $this->execSQLNoData( - $sql, - [$photo,$photoRealName,$bijouxId] - ); + $sql, + [$photo,$photoRealName,$bijouxId]); + return true; } - public function saveDefuntPacemakerPhoto($defuntId, $photo, $photoRealName) - { + public function saveDefuntPacemakerPhoto($defuntId,$photo,$photoRealName){ + $sql = "UPDATE ".$this->tableprefix."defunt as defunt SET defunt.product_photo = ?,defunt.product_photo_name = ? WHERE defunt.id = ? ;"; $this->execSQLNoData( - $sql, - [$photo,$photoRealName,$defuntId] - ); + $sql, + [$photo,$photoRealName,$defuntId]); + return true; } - private function getFacturePaymentTypeById($facturePaymentTypeId) - { + private function getFacturePaymentTypeById($facturePaymentTypeId){ + $sql = "SELECT * FROM ".$this->tableprefix."facture_payment_type as facture_payment_type WHERE facture_payment_type.id = ? LIMIT 1 "; - $facturePaymentType = $this->execSQLNoJsonReturn($sql, [$facturePaymentTypeId]); - if(!empty($facturePaymentType)) { + $facturePaymentType = $this->execSQLNoJsonReturn($sql,[$facturePaymentTypeId]); + if(!empty($facturePaymentType)){ return $facturePaymentType[0]; } return null; } - public function getFacturePaymentList() - { + public function getFacturePaymentList(){ + $sql = "SELECT * FROM ".$this->tableprefix."facture_payment_type"; - return $this->execSQL($sql, []); + return $this->execSQL($sql,[]); } - public function payInvoices($factureIds, $facturePaymentTypeId, $paymentDate) - { + public function payInvoices($factureIds,$facturePaymentTypeId,$paymentDate){ + $facturePaymentType = $this->getFacturePaymentTypeById($facturePaymentTypeId); - if($facturePaymentType == null) { + if($facturePaymentType == null){ return null; } - $paymentDate = Datetime::createFromFormat('Y-m-d', $paymentDate); - $paymentDate = $paymentDate->format('Y-m-d'); - foreach($factureIds as $factureId) { - $this->payAnInvoice($factureId, $facturePaymentTypeId, $paymentDate); + $paymentDate = Datetime::createFromFormat('Y-m-d',$paymentDate); + $paymentDate = $paymentDate->format('Y-m-d'); + foreach($factureIds as $factureId){ + $this->payAnInvoice($factureId,$facturePaymentTypeId,$paymentDate); } return true; } - private function payAnInvoice($factureId, $facturePaymentTypeId, $paymentDate) - { + private function payAnInvoice($factureId,$facturePaymentTypeId,$paymentDate){ + $sql = "UPDATE ".$this->tableprefix."facture as facture SET facture.fk_facture_status_key = ?, facture.payment_date = ?, facture.fk_facture_payment_type_id = ? WHERE facture.id = ? "; - $this->execSQLNoData($sql, [ + $this->execSQLNoData($sql,[ FactureStatusConstant::PAID_KEY, $paymentDate, $facturePaymentTypeId, @@ -4721,8 +4738,8 @@ COMMENTAIRES: ".$comment; return true; } - public function getUsersNotLinkedToThanato() - { + public function getUsersNotLinkedToThanato(){ + $sql = "SELECT users.uid, users.uid_lower, @@ -4734,12 +4751,12 @@ COMMENTAIRES: ".$comment; thanato.fk_user_uuid IS NULL; "; - return $this->execSQL($sql, [BddConstant::DEFAULT_THANATOS_GROUP_NAME]); + return $this->execSQL($sql,[BddConstant::DEFAULT_THANATOS_GROUP_NAME]); } - public function doDevisIdsListIdsBelongsToTheSameClientFacturationGroup(array $devisIds) - { - if(empty($devisIds)) { + public function doDevisIdsListIdsBelongsToTheSameClientFacturationGroup(array $devisIds){ + + if(empty($devisIds)){ return []; } $sqlPlacholders = implode(',', array_fill(0, count($devisIds), '?')); @@ -4752,89 +4769,90 @@ COMMENTAIRES: ".$comment; devis.id_client IS NOT NULL AND devis.id IN($sqlPlacholders);"; - $results = $this->execSQLNoJsonReturn($sql, $devisIds); + $results = $this->execSQLNoJsonReturn($sql,$devisIds); $clientGroupFacturationsIds = []; - foreach($results as $currentResult) { - if($currentResult['fk_client_group_facturation_id'] == null) { + foreach($results as $currentResult){ + if($currentResult['fk_client_group_facturation_id'] == null){ return false; } $clientGroupFacturationsIds[] = $currentResult['fk_client_group_facturation_id']; } $uniqueClientGroupFacturation = array_unique($clientGroupFacturationsIds); - return $uniqueClientGroupFacturation > 1; - + return $uniqueClientGroupFacturation > 1; + } - private function doesDevisFactureGroupAlreadyExist($factureId, $devisId) - { + private function doesDevisFactureGroupAlreadyExist($factureId,$devisId){ + $sql = "SELECT count(*) as DEVIS_FACTURE_COUNT FROM ".$this->tableprefix."devis_facture as devis_facture WHERE devis_facture.fk_devis_id = ? AND devis_facture.fk_facture_id = ?"; - $result = $this->execSQLNoJsonReturn($sql, [$devisId,$factureId]); - if(!empty($result)) { + $result = $this->execSQLNoJsonReturn($sql,[$devisId,$factureId]); + if(!empty($result)){ return $result[0]["DEVIS_FACTURE_COUNT"] > 0; } return false; } - private function createFactureGroupDevis($factureId, $devisId) - { - $doesDevisFactureGroupAlreadyExist = $this->doesDevisFactureGroupAlreadyExist($factureId, $devisId); - if(!$doesDevisFactureGroupAlreadyExist) { + private function createFactureGroupDevis($factureId,$devisId){ + + $doesDevisFactureGroupAlreadyExist = $this->doesDevisFactureGroupAlreadyExist($factureId,$devisId); + if(!$doesDevisFactureGroupAlreadyExist){ $sql = "INSERT INTO `".$this->tableprefix."devis_facture` (`fk_devis_id`,`fk_facture_id`) VALUES (?,?);"; $this->execSQLNoData($sql, [$devisId,$factureId]); - $this->gestion_update('devis', 'mentions', DevisMentionConstant::FACTURED_FORMATTED, $devisId, BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD); + $this->gestion_update('devis','mentions',DevisMentionConstant::FACTURED_FORMATTED,$devisId,BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD); } } - public function createFactureGroupForDevisList($factureId, $devisIds) - { - foreach($devisIds as $devis) { - $this->createFactureGroupDevis($factureId, $devis['id']); + public function createFactureGroupForDevisList($factureId,$devisIds){ + + foreach($devisIds as $devis){ + $this->createFactureGroupDevis($factureId,$devis['id']); } } - private function getFactureIdByFactureNumber($factureNumber) - { + private function getFactureIdByFactureNumber($factureNumber){ + $sql = "SELECT max(facture.id) AS FACTURE_ID FROM ".$this->tableprefix."facture as facture WHERE facture.num = ? ;"; - $result = $this->execSQLNoJsonReturn($sql, [$factureNumber]); - if(!empty($result)) { + $result = $this->execSQLNoJsonReturn($sql,[$factureNumber]); + if(!empty($result)){ return $result[0]['FACTURE_ID']; } return null; } - public function createFactureAndReturnFactureId($facturationDate, $type, $month = null, $year = null, $fkClientId = null, $fkClientGroupFacturationId = null) - { + public function createFactureAndReturnFactureId($facturationDate,$type,$month = null,$year = null,$fkClientId = null,$fkClientGroupFacturationId = null){ + $datetimeNow = new Datetime(); $month = $month ?? $datetimeNow->format('m'); $year = $year ?? $datetimeNow->format('Y'); - if($facturationDate == null || $facturationDate == "") { + if($facturationDate == null || $facturationDate == ""){ $facturationDatetime = DateHelpers::GetLastDayOfTheMonthOfADate($datetimeNow); - } else { - $facturationDatetime = Datetime::createFromFormat('Y-m-d', $facturationDate); } - $facturationDate = $facturationDatetime->format('Y-m-d'); + else{ + $facturationDatetime = Datetime::createFromFormat('Y-m-d',$facturationDate); + } + $facturationDate = $facturationDatetime->format('Y-m-d'); $factureDate = $facturationDate; $factureNumber = $this->getFactureNumberByDate($facturationDatetime); - $fullFactureNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($facturationDatetime, $factureNumber, "FAC"); + $fullFactureNumber = DateHelpers::GetFullFactureOrDevisNumberByDate($facturationDatetime,$factureNumber,"FAC"); $last = 0; $last = $this->lastNumFacture(BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD); $sql = "INSERT INTO `".$this->tableprefix."facture` (`date`,`id_nextcloud`,`num`,`date_paiement`,`type_paiement`,`id_devis`,`user_id`, `version`,`facture_number`,`facture_type`,`month`,`year`,`fk_client_id`,`fk_client_group_facturation_id`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; - $this->execSQLNoData( - $sql, - array( - $factureDate, - BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD, + $this->execSQLNoData($sql, array( + + + $factureDate, + BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD, $fullFactureNumber, $facturationDate, "", 0, - $last + 1, + $last+1, "", $factureNumber, $type, @@ -4848,34 +4866,34 @@ COMMENTAIRES: ".$comment; } - public function generateGroupFactureForMultipleDevis($devisToFacture, $paymentDate) - { + public function generateGroupFactureForMultipleDevis($devisToFacture,$paymentDate){ + $mentionsFilter = [ DevisMentionConstant::NEW, DevisMentionConstant::MENTION ]; - $devisIdListFiltered = $this->getDevisIdListFilteredByMentionAndDevisListId($mentionsFilter, $devisToFacture); - $factureId = $this->createFactureAndReturnFactureId($paymentDate, FactureTypeConstant::TYPE_GROUP); - $this->createFactureGroupForDevisList($factureId, $devisIdListFiltered); + $devisIdListFiltered = $this->getDevisIdListFilteredByMentionAndDevisListId($mentionsFilter,$devisToFacture); + $factureId = $this->createFactureAndReturnFactureId($paymentDate,FactureTypeConstant::TYPE_GROUP); + $this->createFactureGroupForDevisList($factureId,$devisIdListFiltered); return [$factureId]; } - public function getFactureTypeByFactureId($factureId): mixed - { + public function getFactureTypeByFactureId($factureId): mixed{ + $sql = "SELECT facture.facture_type FROM ".$this->tableprefix."facture as facture WHERE facture.id = ? LIMIT 1;"; - $result = $this->execSQLNoJsonReturn($sql, [$factureId]); - if(!empty($result)) { + $result = $this->execSQLNoJsonReturn($sql,[$factureId]); + if(!empty($result)){ return $result[0]['facture_type']; } return FactureTypeConstant::TYPE_SINGLE; } - public function getDevisByClientGroupFacturationIdAndMonthYear($clientGroupFacturationId, $month, $year, $mentionsFilters = []) - { + public function getDevisByClientGroupFacturationIdAndMonthYear($clientGroupFacturationId,$month,$year,$mentionsFilters = []){ + $sql = "SELECT devis.id ,devis.id_client,client.fk_client_group_id FROM ".$this->tableprefix."devis as devis LEFT JOIN ".$this->tableprefix."client as client on devis.id_client = client.id @@ -4886,21 +4904,21 @@ COMMENTAIRES: ".$comment; "; $conditions = [$clientGroupFacturationId,$year,$month]; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " AND ". $this->tableprefix."devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); } - $sql .= ";"; - $result = $this->execSQLNoJsonReturn($sql, $conditions); + $sql.= ";"; + $result = $this->execSQLNoJsonReturn($sql,$conditions); return $result; } - public function getDevisIdsByClientGroupFacturationIdAnDate($clientGroupFacturationId, $facturationDate, $mentionFilters = []) - { + public function getDevisIdsByClientGroupFacturationIdAnDate($clientGroupFacturationId,$facturationDate , $mentionFilters = []){ - $dateTime = Datetime::createFromFormat('Y-m-d', $facturationDate); + + $dateTime = Datetime::createFromFormat('Y-m-d',$facturationDate); $month = $dateTime->format('m'); $year = $dateTime->format('Y'); @@ -4915,23 +4933,23 @@ COMMENTAIRES: ".$comment; $conditions = [$clientGroupFacturationId,$year,$month ,$facturationDate]; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " AND devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); } - $sql .= ";"; - $result = $this->execSQLNoJsonReturn($sql, $conditions); + $sql.= ";"; + $result = $this->execSQLNoJsonReturn($sql,$conditions); $devisIds = []; - foreach($result as $currentResult) { + foreach($result as $currentResult){ $devisIds[] = $currentResult['id']; } return $devisIds; } //OLD concept - public function getDevisIdsByClientGroupFacturationIdAndMonthYear($clientGroupFacturationId, $month, $year, $mentionFilters = []) - { + public function getDevisIdsByClientGroupFacturationIdAndMonthYear($clientGroupFacturationId,$month,$year,$mentionFilters = []){ + $sql = "SELECT devis.id FROM ".$this->tableprefix."devis as devis LEFT JOIN ".$this->tableprefix."client as client on devis.id_client = client.id @@ -4942,23 +4960,23 @@ COMMENTAIRES: ".$comment; "; $conditions = [$clientGroupFacturationId,$year,$month]; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " AND ". $this->tableprefix."devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); } - $sql .= ";"; - $result = $this->execSQLNoJsonReturn($sql, $conditions); + $sql.= ";"; + $result = $this->execSQLNoJsonReturn($sql,$conditions); $devisIds = []; - foreach($result as $currentResult) { + foreach($result as $currentResult){ $devisIds[] = $currentResult['id']; } return $devisIds; } - public function getDevisByClientIdAndMonthYear($clientId, $month, $year, $mentionFilters = []) - { + public function getDevisByClientIdAndMonthYear($clientId,$month,$year,$mentionFilters = []){ + $sql = "SELECT devis.id,devis.id_client,client.fk_client_group_id FROM ".$this->tableprefix."devis as devis LEFT JOIN ".$this->tableprefix."client as client on devis.id_client = client.id @@ -4968,41 +4986,41 @@ COMMENTAIRES: ".$comment; MONTH(devis.date) = ?"; $conditions = [$clientId,$year,$month]; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " AND devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); } - $sql .= ";"; - $result = $this->execSQLNoJsonReturn($sql, $conditions); + $sql.= ";"; + $result = $this->execSQLNoJsonReturn($sql,$conditions); return $result; } - public function getDevisByClientIdByFactureId($factureId, $mentionFilters = []) - { + public function getDevisByClientIdByFactureId($factureId , $mentionFilters = []){ + $sql = "SELECT devis.id,devis.id_client,client.fk_client_group_id FROM ".$this->tableprefix."devis as devis LEFT JOIN ".$this->tableprefix."client as client on devis.id_client = client.id WHERE devis.fk_facture_id = ? "; $conditions = [$factureId]; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " AND devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); } - $sql .= ";"; - $result = $this->execSQLNoJsonReturn($sql, $conditions); + $sql.= ";"; + $result = $this->execSQLNoJsonReturn($sql,$conditions); return $result; } - public function getDevisIdsByClientIdAndDate($clientId, $date, $mentionFilters = []) - { - $dateTime = Datetime::createFromFormat('Y-m-d', $date); + public function getDevisIdsByClientIdAndDate($clientId,$date,$mentionFilters = [] ){ + + $dateTime = Datetime::createFromFormat('Y-m-d',$date); $month = $dateTime->format('m'); $year = $dateTime->format('Y'); - + $sql = "SELECT devis.id,devis.id_client,client.fk_client_group_id FROM ".$this->tableprefix."devis as devis LEFT JOIN ".$this->tableprefix."client as client on devis.id_client = client.id @@ -5013,23 +5031,23 @@ COMMENTAIRES: ".$comment; devis.date <= ? "; $conditions = [$clientId,$year,$month ,$date]; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " AND devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); } - $sql .= ";"; - $result = $this->execSQLNoJsonReturn($sql, $conditions); + $sql.= ";"; + $result = $this->execSQLNoJsonReturn($sql,$conditions); $devisIds = []; - foreach($result as $currentResult) { + foreach($result as $currentResult){ $devisIds[] = $currentResult['id']; } return $devisIds; - + } - public function getDevisIdsByClientIdAndMonthYear($clientId, $month, $year, $mentionFilters = []) - { + public function getDevisIdsByClientIdAndMonthYear($clientId,$month,$year,$mentionFilters = []){ + $sql = "SELECT devis.id,devis.id_client,client.fk_client_group_id FROM ".$this->tableprefix."devis as devis LEFT JOIN ".$this->tableprefix."client as client on devis.id_client = client.id @@ -5039,24 +5057,24 @@ COMMENTAIRES: ".$comment; MONTH(devis.date) = ?"; $conditions = [$clientId,$year,$month]; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " AND devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); } - $sql .= ";"; - $result = $this->execSQLNoJsonReturn($sql, $conditions); + $sql.= ";"; + $result = $this->execSQLNoJsonReturn($sql,$conditions); $devisIds = []; - foreach($result as $currentResult) { + foreach($result as $currentResult){ $devisIds[] = $currentResult['id']; } return $devisIds; - + } - public function getFactureIdByClientIdAndDate($clientId, $facturationDate) - { + public function getFactureIdByClientIdAndDate($clientId,$facturationDate){ + $sql = "SELECT facture.id as facture_id @@ -5066,20 +5084,20 @@ COMMENTAIRES: ".$comment; facture.facture_type = ? AND facture.date_paiement = ? "; - $result = $this->execSQLNoJsonReturn($sql, [ + $result = $this->execSQLNoJsonReturn($sql,[ $clientId, FactureTypeConstant::TYPE_GROUP, $facturationDate, ]); - - if(!empty($result)) { + + if(!empty($result)){ return $result[0]['facture_id']; } return null; } - public function getFactureIdByClientGroupFacturationIdAndDate($clientId, $facturationDate) - { + public function getFactureIdByClientGroupFacturationIdAndDate($clientId,$facturationDate){ + $sql = "SELECT facture.id as facture_id FROM ".$this->tableprefix."facture as facture @@ -5087,22 +5105,22 @@ COMMENTAIRES: ".$comment; facture.fk_client_group_facturation_id = ? AND facture.facture_type = ? AND facture.date_paiement = ? "; + - - $result = $this->execSQLNoJsonReturn($sql, [ + $result = $this->execSQLNoJsonReturn($sql,[ $clientId, FactureTypeConstant::TYPE_GROUP, $facturationDate ]); - - if(!empty($result)) { + + if(!empty($result)){ return $result[0]['facture_id']; } return null; } - public function invoiceListOfDevisIds($devisIds, $factureId) - { + public function invoiceListOfDevisIds($devisIds ,$factureId){ + $sqlConditionsPlaceholder = implode(',', array_fill(0, count($devisIds), '?')); $sql = "UPDATE ".$this->tableprefix."devis as devis SET devis.mentions = ? , devis.fk_facture_id = ? @@ -5113,11 +5131,11 @@ COMMENTAIRES: ".$comment; $devisIds ); - $this->execSQLNoData($sql, $conditions); + $this->execSQLNoData($sql,$conditions); } - private function getDevisDataByClientGroupFacturationIdAndMonthYear($clientGroupFacturationId, $month, $year, $mentionFilters = []) - { + private function getDevisDataByClientGroupFacturationIdAndMonthYear($clientGroupFacturationId,$month,$year,$mentionFilters = []){ + $sql = "SELECT devis.id as devis_id, devis.date as devis_date, @@ -5161,19 +5179,19 @@ COMMENTAIRES: ".$comment; MONTH(devis.date) = ?"; $conditions = [$clientGroupFacturationId,$year,$month]; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " AND devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); } - $sql .= " ORDER BY devis.date ASC;"; - $devisList = $this->execSQLNoJsonReturn($sql, $conditions); + $sql.= " ORDER BY devis.date ASC;"; + $devisList = $this->execSQLNoJsonReturn($sql,$conditions); return $devisList; } - public function getDevisDataGroupByFactureId($factureId, $mentionFilters = []) - { + public function getDevisDataGroupByFactureId($factureId ,$mentionFilters = []){ + $sql = "SELECT devis.id as devis_id, devis.date as devis_date, @@ -5214,18 +5232,18 @@ COMMENTAIRES: ".$comment; WHERE devis.fk_facture_id = ? "; $conditions = [$factureId]; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " AND devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); } - $sql .= " ORDER BY devis.date ASC;"; - $devisList = $this->execSQLNoJsonReturn($sql, $conditions); + $sql.= " ORDER BY devis.date ASC;"; + $devisList = $this->execSQLNoJsonReturn($sql,$conditions); return $devisList; } - private function getDevisDataByClientIdAndMonthYear($clientId, $month, $year, $mentionFilters = []) - { + private function getDevisDataByClientIdAndMonthYear($clientId,$month,$year,$mentionFilters = []){ + $sql = "SELECT devis.id as devis_id, devis.date as devis_date, @@ -5268,34 +5286,34 @@ COMMENTAIRES: ".$comment; MONTH(devis.date) = ?"; $conditions = [$clientId,$year,$month]; - if(!empty($mentionFilters)) { + if(!empty($mentionFilters)){ $mentionsFilterPlaceholders = implode(',', array_fill(0, count($mentionFilters), '?')); $sql .= " AND devis.mentions IN ($mentionsFilterPlaceholders)"; $conditions = array_merge($conditions, $mentionFilters); } - $sql .= " ORDER BY devis.date ASC;"; - $devisList = $this->execSQLNoJsonReturn($sql, $conditions); + $sql.= " ORDER BY devis.date ASC;"; + $devisList = $this->execSQLNoJsonReturn($sql,$conditions); return $devisList; } - public function getClientTemplateTypes() - { + public function getClientTemplateTypes(){ + $sql = "SELECT * FROM ".$this->tableprefix."client_template_type as client_template_type"; - return $this->execSQL($sql, []); + return $this->execSQL($sql,[]); } - public function getDevisByFkFactureId($factureId) - { + public function getDevisByFkFactureId($factureId){ + $sql = "SELECT * FROM ".$this->tableprefix."devis as devis WHERE devis.fk_facture_id = ? LIMIT 1;"; - $result = $this->execSQLNoJsonReturn($sql, [$factureId]); - if(!empty($result)) { + $result = $this->execSQLNoJsonReturn($sql,[$factureId]); + if(!empty($result)){ return $result[0]; } return null; } - public function getFactureGroupById($factureId) - { + public function getFactureGroupById($factureId){ + $sql = "SELECT facture.id, facture.date, @@ -5312,21 +5330,21 @@ COMMENTAIRES: ".$comment; facture.facture_type = ? ;"; - $result = $this->execSQLNoJsonReturn($sql, [$factureId,FactureTypeConstant::TYPE_GROUP]); - if(!empty($result)) { + $result = $this->execSQLNoJsonReturn($sql,[$factureId,FactureTypeConstant::TYPE_GROUP]); + if(!empty($result)){ return $result[0]; } return null; } - public function getFactureGroupByFactureIdWithDetails($factureId) - { + public function getFactureGroupByFactureIdWithDetails($factureId){ + $facture = $this->getFactureGroupById($factureId); $configuration = $this->getConfiguration(BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD); $configuration = json_decode($configuration); $currentConfig = $configuration[0]; - $isFactureSingleClient = $facture['fk_client_id'] != null + $isFactureSingleClient = $facture['fk_client_id'] != null && $facture['fk_client_id'] != 0; $devisMentionFilters = [ @@ -5356,8 +5374,9 @@ COMMENTAIRES: ".$comment; $tvaValue = 0; } } + - if($isFactureSingleClient) { + if($isFactureSingleClient){ $client = $this->getClientById($facture['fk_client_id']); $facture['group_name'] = $client["client_nom"]; $facture['client_name'] = $client["client_prenom"]; @@ -5372,14 +5391,16 @@ COMMENTAIRES: ".$comment; $facture['year'], $devisMentionFilters ); - } else { - $devisList = $this->getDevisDataGroupByFactureId($factureId, $devisMentionFilters); + + }else{ + $devisList = $this->getDevisDataGroupByFactureId( $factureId,$devisMentionFilters); } - } else { + } + else{ $clientGroupFacturation = $this->getClientGroupFacturationById($facture['fk_client_group_facturation_id']); $facture['group_name'] = $clientGroupFacturation["group_facturation_name"]; $facture['client_name'] = $clientGroupFacturation["group_facturation_name"]; - $facture['client_address'] = $clientGroupFacturation["address"] . ' - ' .$clientGroupFacturation["postal_code"] . ' ' . $clientGroupFacturation['city']; + $facture['client_address'] = $clientGroupFacturation["address"] . ' - ' .$clientGroupFacturation["postal_code"] . ' ' . $clientGroupFacturation['city']; $facture['siret'] = $clientGroupFacturation["siret_number"]; $facture['mail'] = $clientGroupFacturation["email"]; @@ -5390,22 +5411,22 @@ COMMENTAIRES: ".$comment; $facture['year'], $devisMentionFilters ); - } else { - $devisList = $this->getDevisDataGroupByFactureId($factureId, $devisMentionFilters); + }else{ + $devisList = $this->getDevisDataGroupByFactureId( $factureId,$devisMentionFilters); } } - $factureTotalHt = 0; + $factureTotalHt= 0; $factureTotalTva = 0; $factureTotalTtc = 0; - foreach($devisList as &$currentDevis) { + foreach($devisList as &$currentDevis){ $totalHt = 0; $totalTva = 0; $totalTtc = 0; $devisProducts = $this->getDevisProduits($currentDevis['devis_id']); - foreach($devisProducts as $currentProduct) { + foreach($devisProducts as $currentProduct){ $valueHt = $currentProduct['produit_price'] * $currentProduct['quantite']; // CALCUL SIMPLE : TVA OU PAS TVA @@ -5613,31 +5634,31 @@ COMMENTAIRES: ".$comment; $factureData["client_tva_intracommu"] = $groupClient["tva_intracommu"]; return $factureData; } + + public function setFactureGeneratedDate($factureId){ - public function setFactureGeneratedDate($factureId) - { $datetimeNow = new Datetime(); $dateNow = $datetimeNow->format("Y-m-d"); $sql = "UPDATE ".$this->tableprefix."facture set document_generated_date = ? WHERE id = ?"; - $this->execSQLNoData($sql, [ + $this->execSQLNoData($sql,[ $dateNow, $factureId ]); } - public function setFactureSentDate($factureId) - { + public function setFactureSentDate($factureId){ + $datetimeNow = new Datetime(); $dateNow = $datetimeNow->format("Y-m-d"); $sql = "UPDATE ".$this->tableprefix."facture set document_sent_date = ? WHERE id = ?"; - $this->execSQLNoData($sql, [ + $this->execSQLNoData($sql,[ $dateNow, $factureId ]); } - public function getFactureClientMailByFactureId($factureId) - { + public function getFactureClientMailByFactureId($factureId){ + $sql = "SELECT facture.id, facture.facture_type, @@ -5664,17 +5685,18 @@ COMMENTAIRES: ".$comment; LIMIT 1;"; $mail = null; - $result = $this->execSQLNoJsonReturn($sql, [$factureId]); - if(!empty($result)) { + $result = $this->execSQLNoJsonReturn($sql,[$factureId]); + if(!empty($result)){ $facture = $result[0]; $factureIsSingle = $facture["facture_type"] == FactureTypeConstant::TYPE_SINGLE; - if($factureIsSingle) { - $mail = $facture["fk_client_group_facturation_id"] != null ? + if($factureIsSingle){ + $mail = $facture["fk_client_group_facturation_id"] != null ? $facture["devis_client_group_mail"] : $facture["devis_client_mail"]; - } else { + } + else{ $factureIsClientWithoutGroup = $facture["facture_client_id"] != null && $facture["facture_client_id"] != 0; - $mail = $factureIsClientWithoutGroup ? + $mail = $factureIsClientWithoutGroup ? $facture["facture_client_mail"] : $facture["facture_client_group_mail"]; } @@ -5702,7 +5724,7 @@ COMMENTAIRES: ".$comment; } return null; } - + public function getTvaItracomuIdClient($clientId) { $sql = "SELECT diff --git a/gestion/lib/Service/InvoicePdfHandler.php b/gestion/lib/Service/InvoicePdfHandler.php index 3139766..3da1b4f 100644 --- a/gestion/lib/Service/InvoicePdfHandler.php +++ b/gestion/lib/Service/InvoicePdfHandler.php @@ -35,6 +35,7 @@ use OCA\Gestion\Helpers\PriceHelpers; class InvoicePdfHandler extends FPDF { + private $multipleFactureData = []; private $factureData = []; private $logo = null; @@ -42,8 +43,11 @@ class InvoicePdfHandler extends FPDF protected $extgstates = []; private $thereIsOrderOrCaseNumber = false; private $startingYOfArticlesTable = 100; + private $endingYOfArticlesTable = 230; + private $articleTablesHeight = 130; + public $interLigneHeader = 5; public $hasTva = true; @@ -89,6 +93,10 @@ class InvoicePdfHandler extends FPDF // Ajouter l'image en filigrane $this->Image($imagePath, $x, $y, $width, $height); // Chemin, position x, position y, largeur, hauteur $this->SetAlpha(0.1); // Définir l'opacité + + + + } public function SetAlpha($alpha) @@ -346,6 +354,7 @@ class InvoicePdfHandler extends FPDF $yValue = $this->startingYOfArticlesTable + 13; $maxDescriptionWidth = 102; + foreach ($products as $product) { $valueHt = $product['produit_price'] * $product['quantite']; @@ -365,8 +374,17 @@ class InvoicePdfHandler extends FPDF if ($product === end($products)) { $dateValue = $devisDate; $productDescription .= " de " . FileExportHelpers::GetSexeLabel($this->factureData['defunt_sexe']) . ' ' . $this->factureData["defunt_nom"]; + + } + + + + + + + $this->SetXY(5, $yValue); $this->Cell(5, 6, $dateValue, 0, 0);