src/Service/AppService.php line 110

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\AchBonCommande;
  4. use App\Entity\AchDetails;
  5. use App\Entity\AchHistoPaiement;
  6. use App\Entity\AchMarchandise;
  7. use App\Entity\AchStatut;
  8. use App\Entity\AchStatutBon;
  9. use App\Entity\AchType;
  10. use App\Entity\AgdAcompte;
  11. use App\Entity\AgdCategorie;
  12. use App\Entity\AgdEcheance;
  13. use App\Entity\AgdLivraison;
  14. use App\Entity\Agence;
  15. use App\Entity\Agenda;
  16. use App\Entity\BtpElement;
  17. use App\Entity\BtpEnoncee;
  18. use App\Entity\CaisseCommande;
  19. use App\Entity\CaissePanier;
  20. use App\Entity\ChkCheque;
  21. use App\Entity\CltHistoClient;
  22. use App\Entity\CmdBonCommande;
  23. use App\Entity\CmpBanque;
  24. use App\Entity\CmpCategorie;
  25. use App\Entity\CmpCompte;
  26. use App\Entity\CmpOperation;
  27. use App\Entity\CrdDetails;
  28. use App\Entity\CrdFinance;
  29. use App\Entity\CrdStatut;
  30. use App\Entity\Depense;
  31. use App\Entity\Devise;
  32. use App\Entity\FactDetails;
  33. use App\Entity\FactPaiement;
  34. use App\Entity\FactType;
  35. use App\Entity\Facture;
  36. use App\Entity\IntLibelle;
  37. use App\Entity\IntMateriel;
  38. use App\Entity\IntMouvement;
  39. use App\Entity\LctBail;
  40. use App\Entity\LctBailleur;
  41. use App\Entity\LctContrat;
  42. use App\Entity\LctLocataire;
  43. use App\Entity\LctPaiement;
  44. use App\Entity\LctRepartition;
  45. use App\Entity\LctStatutLoyer;
  46. use App\Entity\LvrDetails;
  47. use App\Entity\LvrLivraison;
  48. use App\Entity\Menu;
  49. use App\Entity\MenuUser;
  50. use App\Entity\ModModelePdf;
  51. use App\Entity\PrdApprovisionnement;
  52. use App\Entity\PrdCategories;
  53. use App\Entity\PrdDeduction;
  54. use App\Entity\PrdEntrepot;
  55. use App\Entity\PrdEntrpAffectation;
  56. use App\Entity\PrdFournisseur;
  57. use App\Entity\PrdHistoEntrepot;
  58. use App\Entity\PrdMargeType;
  59. use App\Entity\PrdPreferences;
  60. use App\Entity\PrdSolde;
  61. use App\Entity\PrdType;
  62. use App\Entity\PrdVariationPrix;
  63. use App\Entity\Produit;
  64. use App\Entity\SavAnnulation;
  65. use App\Entity\SavAvoirUse;
  66. use App\Entity\SavDetails;
  67. use App\Entity\SavMotif;
  68. use App\Entity\Service;
  69. use App\Entity\User;
  70. use App\Entity\LocFacture;
  71. use App\Entity\LocContrat;
  72. use Doctrine\ORM\EntityManagerInterface;
  73. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  74. use Symfony\Component\HttpFoundation\RequestStack;
  75. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  76. use Symfony\Component\Routing\RouterInterface;
  77. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  78. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  79. use Nexmo\Client\Exception\Exception;
  80. use Symfony\Component\HttpFoundation\Response;
  81. use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
  82. use Vonage\Client\Credentials\Basic;
  83. use Vonage\Client;
  84. use Vonage\SMS\Message\SMS ;
  85. class AppService extends AbstractController
  86. {
  87. private $router ;
  88. private $requestStack ;
  89. private $entityManager ;
  90. private $session ;
  91. private $encoder ;
  92. private $urlGenerator ;
  93. private $user ;
  94. private $agence ;
  95. private $nameAgence ;
  96. private $passwordEncoder ;
  97. private $userObj ;
  98. public function __construct(UserPasswordEncoderInterface $passwordEncoder, SessionInterface $session,RouterInterface $router,RequestStack $requestStack, EntityManagerInterface $entityManager,UserPasswordEncoderInterface $encoder, UrlGeneratorInterface $urlGenerator)
  99. {
  100. $this->router = $router ;
  101. $this->requestStack = $requestStack ;
  102. $this->entityManager = $entityManager;
  103. $this->session = $session ;
  104. $this->encoder = $encoder ;
  105. $this->urlGenerator = $urlGenerator ;
  106. $this->user = $this->session->get("user") ;
  107. if(!is_null($this->user))
  108. {
  109. $this->agence = $this->entityManager->getRepository(Agence::class)->find($this->user["agence"]) ;
  110. $this->nameAgence = strtolower($this->agence->getNom())."-".$this->agence->getId().".json" ;
  111. $this->userObj = $this->entityManager->getRepository(User::class)->findOneBy([
  112. "username" => $this->user["username"],
  113. "agence" => $this->agence
  114. ]) ;
  115. }
  116. $this->passwordEncoder = $passwordEncoder ;
  117. }
  118. public function getnameAgence()
  119. {
  120. return $this->nameAgence ;
  121. }
  122. public function getAgence()
  123. {
  124. return $this->agence ;
  125. }
  126. public function getHappyMessage(): string
  127. {
  128. $messages = [
  129. 'You did it! You updated the system! Amazing!',
  130. 'That was one of the coolest updates I\'ve seen all day!',
  131. 'Great work! Keep going!',
  132. ];
  133. $index = array_rand($messages);
  134. return $messages[$index];
  135. }
  136. public function currentRoute()
  137. {
  138. $currentRoute = $this->router->match($this->requestStack->getCurrentRequest()->getPathInfo())['_route'];
  139. return $currentRoute ;
  140. }
  141. public function checkUrl()
  142. {
  143. ini_set('memory_limit', '512M');
  144. ini_set('max_execution_time', '3200');
  145. $allowUrl = true ;
  146. $user = $this->session->get("user") ;
  147. if(!isset($user))
  148. {
  149. $allowUrl = false ;
  150. }
  151. else
  152. {
  153. $currentRoute = $this->router->match($this->requestStack->getCurrentRequest()->getPathInfo())['_route'];
  154. $blockedRoute =
  155. [
  156. "admin_add_societe",
  157. "admin_saveSociete",
  158. "getRandomPass",
  159. "admin_listSociete",
  160. "menu_attribution",
  161. "admin_save_attribution",
  162. "admin_menu_creation",
  163. "disp_edit_menu",
  164. "admin_validCreation",
  165. "menu_corbeille",
  166. "restore_menu_corbeille",
  167. "manager_agence",
  168. "app_admin"
  169. ] ;
  170. if($user["role"] != "ADMIN")
  171. {
  172. for ($i=0; $i < count($blockedRoute); $i++) {
  173. if($currentRoute == $blockedRoute[$i])
  174. {
  175. $allowUrl = false ;
  176. break ;
  177. }
  178. }
  179. }
  180. }
  181. if(!$allowUrl)
  182. {
  183. $url = $this->urlGenerator->generate('app_logout');
  184. header('location:'.$url) ;
  185. exit();
  186. }
  187. }
  188. public function requestMenu($role,User $user,$parent)
  189. {
  190. if($role == "AGENT")
  191. {
  192. $infoMenu = $this->entityManager
  193. ->getRepository(MenuUser::class)
  194. ->allMenuUserAgent($parent, $user->getAgence()->getId(),$user->getId()) ;
  195. }
  196. else if($role == "MANAGER")
  197. {
  198. $infoMenu = $this->entityManager
  199. ->getRepository(MenuUser::class)
  200. ->allMenuAgence($parent, $user->getAgence()->getId()) ;
  201. }
  202. else
  203. {
  204. $infoMenu = $this->entityManager
  205. ->getRepository(MenuUser::class)
  206. ->allMenu($parent,$user->getId()) ;
  207. }
  208. return $infoMenu ;
  209. }
  210. public function getMenu(&$menuUsers,&$id,&$menus,$inUser = null)
  211. {
  212. array_push($menus,$menuUsers[$id]) ;
  213. if(!is_null($inUser))
  214. $user = $inUser ;
  215. else
  216. $user = $this->session->get("user") ;
  217. $userClass = $this->entityManager
  218. ->getRepository(User::class)
  219. ->findOneBy(array("email" => $user['email'])) ;
  220. $roleUser = $userClass->getRoles()[0] ;
  221. $subMenus = $this->requestMenu($roleUser,$userClass,$menuUsers[$id]['id']) ;
  222. if(!empty($subMenus))
  223. {
  224. $endItem = end($menus) ;
  225. $endItem["submenu"] = $subMenus ;
  226. $menus[$id] = $endItem ;
  227. $childMenus = $menus[$id]["submenu"] ;
  228. for ($i=0; $i < count($childMenus); $i++) {
  229. $childMenu = $this->requestMenu($roleUser,$userClass,$childMenus[$i]["id"]) ;
  230. if(!empty($childMenu))
  231. {
  232. $menus[$id]["submenu"][$i]["submenu"] = $childMenu ;
  233. for($j = 0; $j < count($childMenu) ; $j++)
  234. {
  235. $subMenuChild = $this->requestMenu($roleUser,$userClass,$childMenu[$j]['id']) ;
  236. if(!empty($subMenuChild))
  237. {
  238. $menus[$id]["submenu"][$i]["submenu"][$j]["submenu"] = $subMenuChild ;
  239. }
  240. }
  241. }
  242. }
  243. }
  244. $id++ ;
  245. if(isset($menuUsers[$id]) && !empty($menuUsers[$id]))
  246. $this->getMenu($menuUsers, $id,$menus,$user) ;
  247. }
  248. public function getMenuUser(&$menuUsers,&$id,&$menus)
  249. {
  250. array_push($menus,$menuUsers[$id]) ;
  251. $subMenus = $this->entityManager
  252. ->getRepository(MenuUser::class)
  253. ->allMenuUser($menuUsers[$id]['id']) ;
  254. if(!empty($subMenus))
  255. {
  256. $endItem = end($menus) ;
  257. $endItem["submenu"] = $subMenus ;
  258. $menus[$id] = $endItem ;
  259. $childMenus = $menus[$id]["submenu"] ;
  260. for ($i=0; $i < count($childMenus); $i++) {
  261. $childMenu = $this->entityManager
  262. ->getRepository(MenuUser::class)
  263. ->allMenuUser($childMenus[$i]["id"]) ;
  264. if(!empty($childMenu))
  265. {
  266. $menus[$id]["submenu"][$i]["submenu"] = $childMenu ;
  267. for($j = 0; $j < count($childMenu) ; $j++)
  268. {
  269. $subMenuChild = $this->entityManager
  270. ->getRepository(MenuUser::class)
  271. ->allMenuUser($childMenu[$j]['id']) ;
  272. if(!empty($subMenuChild))
  273. {
  274. $menus[$id]["submenu"][$i]["submenu"][$j]["submenu"] = $subMenuChild ;
  275. }
  276. }
  277. }
  278. }
  279. }
  280. $id++ ;
  281. if(isset($menuUsers[$id]) && !empty($menuUsers[$id]))
  282. $this->getMenuUser($menuUsers, $id,$menus) ;
  283. }
  284. public function chiffrementCesar($texte_clair, $decalage) {
  285. $texte_chiffre = '';
  286. // Assurez-vous que le décalage est un entier
  287. $decalage = intval($decalage);
  288. // Convertir le décalage en une valeur positive dans l'intervalle [0, 25]
  289. $decalage = $decalage % 26;
  290. for ($i = 0; $i < strlen($texte_clair); $i++) {
  291. $char = $texte_clair[$i];
  292. if (ctype_alpha($char)) { // Vérifier si le caractère est une lettre
  293. $asciiOffset = ord(ctype_upper($char) ? 'A' : 'a');
  294. $chiffre_ascii = (($char - $asciiOffset + $decalage) % 26) + $asciiOffset;
  295. $texte_chiffre .= chr($chiffre_ascii);
  296. } else {
  297. // Conserver les caractères qui ne sont pas des lettres inchangés
  298. $texte_chiffre .= $char;
  299. }
  300. }
  301. return $texte_chiffre;
  302. }
  303. public function dechiffrementCesar($texte_chiffre, $decalage) {
  304. // Utilisez le décalage négatif pour déchiffrer le texte
  305. return $this->chiffrementCesar($texte_chiffre, -$decalage);
  306. }
  307. public function encodeChiffre($chiffre) {
  308. $result = dechex($chiffre) ;
  309. return base64_encode($result) ;
  310. // return $this->chiffrementCesar($result,7) ;
  311. }
  312. public function decoderChiffre($chiffrement) {
  313. // $result = $this->dechiffrementCesar(strval($chiffrement),7) ;
  314. $result = base64_decode($chiffrement) ;
  315. return hexdec($result) ;
  316. }
  317. public function generatePassword()
  318. {
  319. $lowercaseChars = 'abcdefghijklmnopqrstuvwxyz';
  320. $uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  321. $specialChars = '!@#$%^&*()_+-=[]{}|;:,.<>?';
  322. $numbers = '0123456789';
  323. $password = '';
  324. // Ajouter une lettre minuscule aléatoire
  325. $password .= $lowercaseChars[rand(0, strlen($lowercaseChars) - 1)];
  326. // Ajouter une lettre majuscule aléatoire
  327. $password .= $uppercaseChars[rand(0, strlen($uppercaseChars) - 1)];
  328. // Ajouter un caractère spécial aléatoire
  329. $password .= $specialChars[rand(0, strlen($specialChars) - 1)];
  330. // Ajouter un chiffre aléatoire
  331. $password .= $numbers[rand(0, strlen($numbers) - 1)];
  332. // Ajouter des caractères aléatoires jusqu'à ce que la longueur minimale de 8 caractères soit atteinte
  333. while (strlen($password) < 8) {
  334. $randomChar = rand(0, 3); // Choisir un chiffre aléatoire entre 0 et 3
  335. if ($randomChar == 0) {
  336. $password .= $lowercaseChars[rand(0, strlen($lowercaseChars) - 1)];
  337. } else if ($randomChar == 1) {
  338. $password .= $uppercaseChars[rand(0, strlen($uppercaseChars) - 1)];
  339. } else if ($randomChar == 2) {
  340. $password .= $specialChars[rand(0, strlen($specialChars) - 1)];
  341. } else if ($randomChar == 3) {
  342. $password .= $numbers[rand(0, strlen($numbers) - 1)];
  343. }
  344. }
  345. return $password;
  346. }
  347. public function hashPassword(User $user,string $plainPassword): string
  348. {
  349. $encodedPassword = $this->encoder->encodePassword($user, $plainPassword);
  350. return $encodedPassword;
  351. }
  352. public function generateUserMenu(&$menus,$filename)
  353. {
  354. if(!file_exists($filename))
  355. {
  356. $menuUsers = $this->entityManager
  357. ->getRepository(MenuUser::class)
  358. ->allMenuUser(null) ;
  359. $id = 0;
  360. if(!empty($menuUsers))
  361. {
  362. $this->getMenuUser($menuUsers,$id,$menus) ;
  363. $json = json_encode($menus) ;
  364. file_put_contents($filename, $json);
  365. }
  366. }
  367. }
  368. function afficher_menu($menu_array,&$menu)
  369. {
  370. $menu .= "<ul class='list-unstyled content_list overflow-auto px-3 pb-3 list_item_menu' id='menuCollapse'>";
  371. // dd($menu_array) ;
  372. foreach ($menu_array as $item) {
  373. $menu .= "<li class='py-1 px-3 w-100 menu_item rounded border font-weight-bold'>
  374. <a href=".$this->router->generate($item->route).">
  375. <i class='fa ".$item->icone."'></i>&nbsp;
  376. <span class='text-uppercase'>".$item->nom. "</span>
  377. </a>";
  378. if (isset($item->submenu)) {
  379. $this->afficher_menu($item->submenu,$menu);
  380. }
  381. $menu .= '
  382. <i class="fa fa-plus float-right ml-2 mt-1 menuPlus" data-toggle="collapse" data-target="#menuCollapse{{i}}" aria-expanded="true" aria-controls="menuCollapse{{i}}"></i>
  383. <i class="far fa-check-circle float-right ml-2 mt-1 menuCheck"></i>
  384. </li>';
  385. }
  386. $menu .= "</ul>";
  387. }
  388. public function generateListeMenu()
  389. {
  390. $listes = $this->entityManager->getRepository(Menu::class)->findBy([
  391. "statut" => True,
  392. "is_admin" => NULL
  393. ]) ;
  394. $listeMenu = [] ;
  395. $pathListeMenu = "files/json/listeMenu.json" ;
  396. foreach ($listes as $liste) {
  397. $parent = !is_null( $liste->getMenuParent()) ? $liste->getMenuParent()->getNom() : "NULL" ;
  398. array_push($listeMenu,[
  399. "id" => $liste->getId(),
  400. "nom" => $liste->getNom(),
  401. "parent" => $parent
  402. ]) ;
  403. }
  404. file_put_contents($pathListeMenu, json_encode($listeMenu)) ;
  405. }
  406. public function generateAllAgence($filename)
  407. {
  408. $agences = $this->entityManager->getRepository(Agence::class)->findBy([
  409. "statut" => True
  410. ]) ;
  411. $items = [] ;
  412. foreach ($agences as $agence) {
  413. $user = $this->entityManager->getRepository(User::class)->findOneBy([
  414. "agence" => $agence,
  415. ]) ;
  416. if($user->getRoles()[0] == "ADMIN")
  417. continue ;
  418. $item = [
  419. "id" => $agence->getId(),
  420. "nom" => $agence->getNom(),
  421. ] ;
  422. array_push($items,$item) ;
  423. }
  424. file_put_contents($filename, json_encode($items)) ;
  425. }
  426. public function sendSms($numero,$entete, $contenu)
  427. {
  428. $basic = new Basic("4c66ffd6", "XCiCWpI9qBqffTNA");
  429. $client = new Client($basic);
  430. $response = $client->sms()->send(
  431. new SMS($numero, $entete, $contenu)
  432. );
  433. $message = $response->current();
  434. if ($message->getStatus() == 0)
  435. {
  436. return "The message was sent successfully";
  437. }
  438. else
  439. {
  440. return "The message failed with status: " . $message->getStatus() ;
  441. }
  442. }
  443. public function verificationElement($data= [], $dataMessage = [])
  444. {
  445. $allow = True ;
  446. $type = "green" ;
  447. $message = "Information enregistré avec succès" ;
  448. for ($i=0; $i < count($data); $i++) {
  449. if(!is_numeric($data[$i]))
  450. {
  451. if(empty($data[$i]))
  452. {
  453. $allow = False ;
  454. $type="orange" ;
  455. $message = $dataMessage[$i]." vide" ;
  456. break;
  457. }
  458. }
  459. else
  460. {
  461. if(empty($data[$i]))
  462. {
  463. $allow = False ;
  464. $type="orange" ;
  465. $message = $dataMessage[$i]." vide" ;
  466. break;
  467. }
  468. else if(intval($data[$i]) < 0)
  469. {
  470. $allow = False ;
  471. $type="red" ;
  472. $message = $dataMessage[$i]." doit Ăªtre supĂ©rieur Ă  0" ;
  473. break;
  474. }
  475. }
  476. }
  477. $result = [] ;
  478. $result["allow"] = $allow ;
  479. $result["type"] = $type ;
  480. $result["message"] = $message ;
  481. return $result ;
  482. }
  483. public function generateStockCategorie($filename,$agence)
  484. {
  485. $categories = $this->entityManager->getRepository(PrdCategories::class)->findBy([
  486. "agence" => $agence,
  487. "statut" => True
  488. ]) ;
  489. $elements = [] ;
  490. foreach ($categories as $cat) {
  491. $cat->setNom(strtoupper($cat->getNom())) ;
  492. $this->entityManager->flush() ;
  493. $element = [] ;
  494. $element["id"] = $cat->getId() ;
  495. $element["nom"] = $cat->getNom() ;
  496. $element["image"] = $cat->getImages() ;
  497. $element["stockMax"] = $cat->getStockMax() ;
  498. $element["agence"] = $cat->getAgence()->getId() ;
  499. array_push($elements,$element) ;
  500. }
  501. file_put_contents($filename,json_encode($elements)) ;
  502. }
  503. public function generateStockEntrepot($filename, $agence)
  504. {
  505. $entrepots = $this->entityManager->getRepository(PrdEntrepot::class)->findBy([
  506. "statut" => True,
  507. "agence" => $agence
  508. ]) ;
  509. $elements = [] ;
  510. foreach ($entrepots as $entrepot) {
  511. $element = [] ;
  512. $element["id"] = $entrepot->getId() ;
  513. $element["nom"] = $entrepot->getNom() ;
  514. $element["adresse"] = $entrepot->getAdresse() ;
  515. $element["telephone"] = $entrepot->getTelephone() ;
  516. $element["agence"] = $entrepot->getAgence()->getId() ;
  517. array_push($elements,$element) ;
  518. }
  519. file_put_contents($filename,json_encode($elements)) ;
  520. }
  521. public static function comparerParNom($a, $b) {
  522. return strcmp($a['nom'], $b['nom']); // Comparaison des noms
  523. }
  524. public function generateStockPreferences($filename,$user)
  525. {
  526. $preferences = $this->entityManager->getRepository(PrdPreferences::class)->findBy([
  527. "user" => $user,
  528. "statut" => True
  529. ]) ;
  530. $elements = [] ;
  531. if(!is_null($preferences))
  532. {
  533. foreach ($preferences as $preference) {
  534. // Ignorer les préférences sans catégorie
  535. if ($preference->getCategorie() === null) {
  536. continue;
  537. }
  538. $element = [] ;
  539. $element["id"] = $preference->getId() ;
  540. $element["nom"] = $preference->getCategorie()->getNom() ;
  541. $element["categorie"] = $preference->getCategorie()->getId() ;
  542. array_push($elements,$element) ;
  543. }
  544. }
  545. usort($elements, [self::class, 'comparerParNom']);
  546. file_put_contents($filename,json_encode($elements)) ;
  547. }
  548. public static function comparaisonDates($a, $b) {
  549. $dateA = \DateTime::createFromFormat('d/m/Y', $a['date']);
  550. $dateB = \DateTime::createFromFormat('d/m/Y', $b['date']);
  551. return $dateB <=> $dateA;
  552. }
  553. public function generatePrdListeApprovisionnement($filename, $agence)
  554. {
  555. $appros = $this->entityManager->getRepository(PrdApprovisionnement::class)->findBy([
  556. "agence" => $agence
  557. ],
  558. [
  559. "id" => "DESC"
  560. ]) ;
  561. $elements = [] ;
  562. foreach ($appros as $appro) {
  563. $element = [] ;
  564. $nomProduit = $appro->getVariationPrix()->getProduit()->getNom() ;
  565. $codeProduit = $appro->getVariationPrix()->getProduit()->getCodeProduit() ;
  566. $nomType = is_null($appro->getVariationPrix()->getProduit()->getType()) ? "NA" :$appro->getVariationPrix()->getProduit()->getType()->getNom() ;
  567. $prixVente = is_null($appro->getPrixVente()) ? $appro->getVariationPrix()->getPrixVente() : $appro->getPrixVente() ;
  568. $element["id"] = $appro->getId() ;
  569. $element["date"] = is_null($appro->getDateAppro()) ? $appro->getCreatedAt()->format("d/m/Y") : $appro->getDateAppro()->format("d/m/Y") ;
  570. $element["annee"] = is_null($appro->getDateAppro()) ? $appro->getCreatedAt()->format("Y") : $appro->getDateAppro()->format("Y") ;
  571. $element["entrepot"] = $appro->getHistoEntrepot()->getEntrepot()->getNom() ;
  572. $element["idEntrepot"] = $appro->getHistoEntrepot()->getId() ;
  573. $element["produit"] = $codeProduit." | ".$nomType." | ".$nomProduit ;
  574. $element["prixVente"] = $prixVente ;
  575. $element["quantite"] = $appro->getQuantite() ;
  576. $element["total"] = $appro->getQuantite() * $prixVente ;
  577. $element["dateExpiration"] = is_null($appro->getExpireeLe()) ? "-" : $appro->getExpireeLe()->format("d/m/Y") ;
  578. $element["nomProduit"] = $nomProduit ;
  579. $element["codeProduit"] = $codeProduit ;
  580. $element["nomType"] = $nomType ;
  581. $element["indice"] = is_null($appro->getVariationPrix()->getIndice()) ? "-" : $appro->getVariationPrix()->getIndice() ;
  582. $element["variation"] = $appro->getVariationPrix()->getId() ;
  583. $element["stock"] = $appro->getQuantite() ;
  584. array_push($elements,$element) ;
  585. }
  586. // usort($elements, [self::class, 'comparaisonDates']);
  587. file_put_contents($filename,json_encode($elements)) ;
  588. }
  589. public function generateStockFournisseur($filename,$agence)
  590. {
  591. $fournisseurs = $this->entityManager->getRepository(PrdFournisseur::class)->findBy([
  592. "agence" => $agence,
  593. "statut" => True,
  594. ]) ;
  595. $elements = [] ;
  596. foreach ($fournisseurs as $fournisseur) {
  597. $element = [] ;
  598. $element["id"] = $fournisseur->getId() ;
  599. $element["nom"] = $fournisseur->getNom() ;
  600. $element["nomContact"] = $fournisseur->getNomContact() ;
  601. $element["telBureau"] = $fournisseur->getTelBureau() ;
  602. $element["telMobile"] = $fournisseur->getTelMobile() ;
  603. $element["adresse"] = $fournisseur->getAdresse() ;
  604. $element["email"] = $fournisseur->getEmail() ;
  605. $element["agence"] = $fournisseur->getAgence()->getId() ;
  606. array_push($elements,$element) ;
  607. }
  608. file_put_contents($filename,json_encode($elements)) ;
  609. }
  610. public function generateProduitStockGeneral($filename,$agence)
  611. {
  612. $stockGenerales = $this->entityManager->getRepository(Produit::class)->findBy([
  613. "agence" => $agence,
  614. "statut" => True,
  615. ]) ;
  616. $elements = [] ;
  617. foreach ($stockGenerales as $stockGeneral) {
  618. $element = [] ;
  619. $element["id"] = $stockGeneral->getId() ;
  620. $element["encodedId"] = $this->encodeChiffre($stockGeneral->getId()) ;
  621. $preference = $stockGeneral->getPreference();
  622. $element["idC"] = $preference ? $preference->getId() : 0 ;
  623. try {
  624. $categorie = $preference ? $preference->getCategorie() : null;
  625. $element["idCat"] = $categorie ? $categorie->getId() : 0 ;
  626. $element["categorie"] = $categorie ? $categorie->getNom() : "SANS CATÉGORIE" ;
  627. } catch (\Exception $e) {
  628. $element["idCat"] = 0 ;
  629. $element["categorie"] = "SANS CATÉGORIE" ;
  630. }
  631. $element["codeProduit"] = $stockGeneral->getCodeProduit() ;
  632. $element["nom"] = $stockGeneral->getNom() ;
  633. $element["stock"] = $stockGeneral->getStock() ;
  634. $element["tvaType"] = is_null($stockGeneral->getTvaType()) ? "-" : $stockGeneral->getTvaType()->getId() ;
  635. $element["agence"] = $stockGeneral->getAgence()->getId() ;
  636. $element["type"] = is_null($stockGeneral->getType()) ? "NA" : $stockGeneral->getType()->getId() ;
  637. $element["nomType"] = is_null($stockGeneral->getType()) ? "NA" : $stockGeneral->getType()->getNom() ;
  638. // Normaliser NULL comme SIMPLE
  639. $element["typeProduit"] = $stockGeneral->getTypeProduit() ? $stockGeneral->getTypeProduit() : "SIMPLE" ;
  640. $element["images"] = is_null($stockGeneral->getImages()) ? "-" : $stockGeneral->getImages() ;
  641. // Charger les entrepôts associés au produit via les variations
  642. $entrepotsList = [];
  643. $variations = $this->entityManager->getRepository(PrdVariationPrix::class)->findBy([
  644. "produit" => $stockGeneral,
  645. "statut" => True
  646. ]);
  647. foreach ($variations as $variation) {
  648. $histoEntrepots = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findBy([
  649. "variationPrix" => $variation,
  650. "statut" => True
  651. ]);
  652. foreach ($histoEntrepots as $histoEntrepot) {
  653. $entrepot = $histoEntrepot->getEntrepot();
  654. $entrepotData = [
  655. "idE" => $entrepot->getId(),
  656. "entrepot" => $entrepot->getNom()
  657. ];
  658. // Éviter les doublons
  659. $isDuplicate = false;
  660. foreach ($entrepotsList as $existing) {
  661. if ($existing["idE"] == $entrepotData["idE"]) {
  662. $isDuplicate = true;
  663. break;
  664. }
  665. }
  666. if (!$isDuplicate) {
  667. $entrepotsList[] = $entrepotData;
  668. }
  669. }
  670. }
  671. // Ajouter le premier entrepôt comme idE principal (pour compatibilité avec les filtres simples)
  672. if (!empty($entrepotsList)) {
  673. $element["idE"] = $entrepotsList[0]["idE"];
  674. $element["entrepot"] = $entrepotsList[0]["entrepot"];
  675. $element["entrepots"] = $entrepotsList;
  676. } else {
  677. // Si aucun entrepôt trouvé, ajouter une valeur par défaut
  678. $element["idE"] = null;
  679. $element["entrepot"] = "Non assigné";
  680. $element["entrepots"] = [];
  681. }
  682. array_push($elements,$element) ;
  683. }
  684. file_put_contents($filename,json_encode($elements)) ;
  685. }
  686. public function generatePrdVariationProduit($filename,$idProduit)
  687. {
  688. $produit = $this->entityManager->getRepository(Produit::class)->find($idProduit) ;
  689. $variations = $this->entityManager->getRepository(PrdVariationPrix::class)->findBy([
  690. "produit" => $produit,
  691. "statut" => True
  692. ]) ;
  693. $elements = [] ;
  694. foreach($variations as $variation)
  695. {
  696. $histoEntrepots = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findBy([
  697. "variationPrix" => $variation,
  698. "statut" => True
  699. ]) ;
  700. if(is_null($variation->getPrixAchat()))
  701. {
  702. $this->entityManager->getRepository(PrdVariationPrix::class)->updateVariationPrix([
  703. "variationPrix" => $variation
  704. ]) ;
  705. }
  706. $item = [];
  707. $indice = is_null($variation->getIndice()) ? "-" : $variation->getIndice() ;
  708. $cle = $indice."|".$variation->getPrixVente() ;
  709. foreach($histoEntrepots as $histoEntrepot)
  710. {
  711. if (array_key_exists($cle, $item))
  712. {
  713. $item[$cle]["stock"] += $histoEntrepot->getStock() ;
  714. $item[$cle]["entrepot"] .= ", ".$histoEntrepot->getEntrepot()->getNom() ;
  715. $item[$cle]["idEntrepot"][] = $histoEntrepot->getEntrepot()->getId() ;
  716. }
  717. else
  718. {
  719. $solde = $this->entityManager->getRepository(PrdSolde::class)->findOneBy([
  720. "variationPrix" => $variation,
  721. "statut" => True,
  722. ]) ;
  723. $prixAchat = $variation->getPrixAchat() ;
  724. $charge = $variation->getCharge() ;
  725. $montantMarge = $variation->getMargeValeur() ;
  726. $margeType = $variation->getMargeType() !== null ? $variation->getMargeType()->getCalcul() : null ;
  727. if($margeType == 100)
  728. {
  729. $montantMarge = $montantMarge."%" ;
  730. }
  731. else if($margeType == -1)
  732. {
  733. $montantMarge = "(Coeff) ". $montantMarge ;
  734. }
  735. $item[$cle] = [] ;
  736. $item[$cle]["id"] = $variation->getId() ;
  737. $item[$cle]["solde"] = is_null($solde) ? "-" : $solde->getCalculee() ;
  738. $item[$cle]["marge"] = $montantMarge ;
  739. $item[$cle]["charge"] = $charge ;
  740. $item[$cle]["soldeType"] = is_null($solde) ? "-" : $solde->getType()->getCalcul() ;
  741. $item[$cle]["soldeQte"] = is_null($solde) ? "-" : $solde->getSolde() ;
  742. $item[$cle]["soldeDate"] = is_null($solde) ? "-" : $solde->getDateLimite()->format("d/m/Y") ;
  743. $item[$cle]["entrepot"] = $histoEntrepot->getEntrepot()->getNom() ;
  744. $item[$cle]["idEntrepot"] = [$histoEntrepot->getEntrepot()->getId()] ;
  745. $item[$cle]["prix"] = $variation->getPrixVente() ;
  746. $item[$cle]["prixAchat"] = $prixAchat ;
  747. $item[$cle]["prixVente"] = $variation->getPrixVente() ;
  748. $item[$cle]["stock"] = $histoEntrepot->getStock() ;
  749. $item[$cle]["code"] = $produit->getCodeProduit()."/".$indice ;
  750. $item[$cle]["codeProduit"] = $produit->getCodeProduit() ;
  751. $item[$cle]["indice"] = $indice ;
  752. }
  753. $elements[$cle] = $item[$cle] ;
  754. }
  755. }
  756. $elements = array_values($elements);
  757. file_put_contents($filename,json_encode($elements)) ;
  758. }
  759. public function generatePrdType($filename, $agence)
  760. {
  761. $types = $this->entityManager->getRepository(PrdType::class)->findBy([
  762. "agence" => $agence,
  763. "statut" => True
  764. ]) ;
  765. $elements = [] ;
  766. foreach ($types as $type) {
  767. $element = [] ;
  768. $element["id"] = $type->getId() ;
  769. $element["nom"] = $type->getNom() ;
  770. $element["agence"] = $type->getAgence()->getId() ;
  771. array_push($elements,$element) ;
  772. }
  773. file_put_contents($filename,json_encode($elements)) ;
  774. }
  775. public function generatePrdStockType($filename,$agence)
  776. {
  777. $stockGenerales = $this->entityManager->getRepository(Produit::class)->findBy([
  778. "agence" => $agence,
  779. "statut" => True,
  780. "anneeData" => date('Y'),
  781. ]) ;
  782. $types = $this->entityManager->getRepository(PrdType::class)->findBy([
  783. "agence" => $agence,
  784. "statut" => True
  785. ]) ;
  786. $stocks = [] ;
  787. $stocks["Non Assignee"]["stock"] = 0 ;
  788. $stocks["Non Assignee"]["encodedId"] = "NA" ;
  789. foreach ($types as $type) {
  790. $stocks[$type->getNom()]["stock"] = 0 ;
  791. $stocks[$type->getNom()]["encodedId"] = $this->encodeChiffre($type->getId()) ;
  792. }
  793. foreach ($stockGenerales as $stockGeneral) {
  794. $stockType = $stockGeneral->getType() ;
  795. if(is_null($stockType))
  796. {
  797. $stocks["Non Assignee"]["stock"] += $stockGeneral->getStock() ;
  798. }
  799. else
  800. {
  801. $stocks[$stockType->getNom()]["stock"] += $stockGeneral->getStock() ;
  802. }
  803. }
  804. file_put_contents($filename,json_encode($stocks)) ;
  805. }
  806. public function generateProduitParategorie($filename,$agence, $user)
  807. {
  808. // Nouvelle approche : partir des stocks réels en entrepôt (PrdHistoEntrepot)
  809. // et regrouper par catĂ©gorie (mĂªme logique que generatePrdGenEntrepot)
  810. $stockCats = [] ;
  811. // Récupérer TOUS les historiques d'entrepôt pour l'agence
  812. // Utiliser LEFT JOIN pour inclure les produits sans préférence/catégorie
  813. // IMPORTANT: Filtrer aussi sur e.statut pour exclure les entrepĂ´ts inactifs
  814. $histoEntrepots = $this->entityManager->getRepository(PrdHistoEntrepot::class)
  815. ->createQueryBuilder('phe')
  816. ->join('phe.entrepot', 'e')
  817. ->join('phe.variationPrix', 'vp')
  818. ->join('vp.produit', 'p')
  819. ->leftJoin('p.preference', 'pref')
  820. ->leftJoin('pref.categorie', 'cat')
  821. ->where('e.agence = :agence')
  822. ->andWhere('e.statut = :statut')
  823. ->andWhere('phe.statut = :statut')
  824. ->andWhere('vp.statut = :statut')
  825. ->andWhere('p.statut = :statut')
  826. ->setParameter('agence', $agence)
  827. ->setParameter('statut', true)
  828. ->getQuery()
  829. ->getResult();
  830. foreach ($histoEntrepots as $histoEntrepot) {
  831. $variationPrix = $histoEntrepot->getVariationPrix();
  832. $produit = $variationPrix->getProduit();
  833. $preference = $produit->getPreference();
  834. // Gérer les produits sans préférence/catégorie
  835. if (!$preference || !$preference->getCategorie()) {
  836. // Créer une catégorie par défaut "SANS CATÉGORIE"
  837. $keyCat = "CAT_SANS_CATEGORIE";
  838. $nomCategorie = "SANS CATÉGORIE";
  839. $encodedId = 0;
  840. } else {
  841. $categorie = $preference->getCategorie();
  842. try {
  843. $keyCat = "CAT".$categorie->getId();
  844. $nomCategorie = $categorie->getNom();
  845. $encodedId = $this->encodeChiffre($preference->getId());
  846. } catch (\Exception $e) {
  847. $keyCat = "CAT_SANS_CATEGORIE";
  848. $nomCategorie = "SANS CATÉGORIE";
  849. $encodedId = 0;
  850. }
  851. }
  852. $prixVente = $variationPrix->getPrixVente() ? (string)$variationPrix->getPrixVente() : "0";
  853. $prixAchat = $variationPrix->getPrixAchat() ? (string)$variationPrix->getPrixAchat() : "0";
  854. $stock = $histoEntrepot->getStock() ? (string)$histoEntrepot->getStock() : "0";
  855. $montantVente = bcmul($stock, $prixVente, 2);
  856. $montantAchat = bcmul($stock, $prixAchat, 2);
  857. if(!isset($stockCats[$keyCat]))
  858. {
  859. $stockCats[$keyCat] = [
  860. "stock" => (float)$stock,
  861. "montantVente" => (float)$montantVente,
  862. "montantAchat" => (float)$montantAchat,
  863. "nomCategorie" => $nomCategorie,
  864. "encodedId" => $encodedId,
  865. ];
  866. }
  867. else
  868. {
  869. $stockCats[$keyCat]["stock"] += (float)$stock;
  870. $stockCats[$keyCat]["montantVente"] = bcadd((string)$stockCats[$keyCat]["montantVente"], $montantVente, 2);
  871. $stockCats[$keyCat]["montantAchat"] = bcadd((string)$stockCats[$keyCat]["montantAchat"], $montantAchat, 2);
  872. }
  873. }
  874. file_put_contents($filename,json_encode($stockCats)) ;
  875. }
  876. public function generateProduitParamTypeTva($path,$filename,$agence)
  877. {
  878. unlink($path) ;
  879. if(!file_exists($path))
  880. $this->generateProduitStockGeneral($path, $agence) ;
  881. $stockGenerales = json_decode(file_get_contents($path)) ;
  882. $elements = [] ;
  883. foreach ($stockGenerales as $stockGenerale) {
  884. $element = [] ;
  885. $element["id"] = $stockGenerale->id ;
  886. $element["idC"] = $stockGenerale->idC ;
  887. $element["produit"] = $stockGenerale->codeProduit." | ".$stockGenerale->nom." | ".$stockGenerale->stock ;
  888. $element["categorie"] = $stockGenerale->categorie ;
  889. $element["tvaType"] = $stockGenerale->tvaType ;
  890. $element["agence"] = $stockGenerale->agence ;
  891. array_push($elements,$element) ;
  892. }
  893. file_put_contents($filename,json_encode($elements)) ;
  894. }
  895. public function generateBonCommande($filename,$agence)
  896. {
  897. $bonCommandes = $this->entityManager->getRepository(CmdBonCommande::class)->findBy([
  898. "agence" => $agence
  899. ]) ;
  900. $elements = [] ;
  901. foreach ($bonCommandes as $bonCommande) {
  902. $factureDetails = $this->entityManager->getRepository(FactDetails::class)->findBy([
  903. "statut" => True,
  904. "facture" => $bonCommande->getFacture()
  905. ]) ;
  906. foreach ($factureDetails as $factureDetail) {
  907. $element = [] ;
  908. if($bonCommande->getFacture()->getClient()->getType()->getId() == 2)
  909. $client = $bonCommande->getFacture()->getClient()->getClient()->getNom() ;
  910. else
  911. $client = $bonCommande->getFacture()->getClient()->getSociete()->getNom() ;
  912. $tva = (($factureDetail->getPrix() * $factureDetail->getTvaVal()) / 100) * $factureDetail->getQuantite() ;
  913. $total = $factureDetail->getPrix() * $factureDetail->getQuantite() ;
  914. $remiseVal = $this->getFactureRemise($factureDetail,$total) ;
  915. $total = $total - $remiseVal ;
  916. $typeRemise = is_null($factureDetail->getRemiseType()) ? "" : $factureDetail->getRemiseType()->getNotation() ;
  917. $typeRemise = ($typeRemise == "%") ? $typeRemise : "" ;
  918. $typeRemiseG = is_null($bonCommande->getFacture()->getRemiseType()) ? "" : $bonCommande->getFacture()->getRemiseType()->getNotation() ;
  919. $typeRemiseG = ($typeRemiseG == "%") ? $typeRemiseG : "" ;
  920. $element["id"] = $bonCommande->getId() ;
  921. $element["agence"] = $bonCommande->getAgence()->getId() ;
  922. $element["date"] = $bonCommande->getDate()->format('d/m/Y') ;
  923. $element["numBon"] = $bonCommande->getNumBonCmd() ;
  924. $element["client"] = $client ;
  925. $element["designation"] = $factureDetail->getDesignation() ;
  926. $element["qte"] = $factureDetail->getQuantite() ;
  927. $element["prix"] = $factureDetail->getPrix() ;
  928. $element["tva"] = ($tva == 0) ? "-" : $tva ; ;
  929. $element["remise"] = $factureDetail->getRemiseVal()." ".$typeRemise ;
  930. $element["total"] = $total ;
  931. $element["statut"] = $bonCommande->getStatut()->getNom() ;
  932. $element["refStatut"] = $bonCommande->getStatut()->getreference() ;
  933. $element["remiseG"] = $bonCommande->getFacture()->getRemiseVal()." ".$typeRemiseG ;
  934. $element["totalTva"] = $bonCommande->getFacture()->getTvaVal() ;
  935. $element["totalTtc"] = $bonCommande->getFacture()->getTotal() ;
  936. array_push($elements,$element) ;
  937. }
  938. }
  939. file_put_contents($filename,json_encode($elements)) ;
  940. }
  941. public function generateCommande($filename, $agence)
  942. {
  943. $bonCommandes = $this->entityManager->getRepository(CmdBonCommande::class)->findBy([
  944. "agence" => $agence
  945. ]) ;
  946. $elements = [] ;
  947. foreach ($bonCommandes as $bonCommande) {
  948. if($bonCommande->getFacture()->getClient()->getType()->getId() == 2)
  949. $client = $bonCommande->getFacture()->getClient()->getClient()->getNom() ;
  950. else
  951. $client = $bonCommande->getFacture()->getClient()->getSociete()->getNom() ;
  952. $element = [] ;
  953. $element["id"] = $bonCommande->getId() ;
  954. $element["numBon"] = $bonCommande->getNumBonCmd() ;
  955. $element["client"] = $client ;
  956. $element["facture"] = $bonCommande->getFacture()->getId() ;
  957. $element["statut"] = $bonCommande->getStatut()->getreference() ;
  958. $element["agence"] = $bonCommande->getAgence()->getId() ;
  959. array_push($elements,$element) ;
  960. }
  961. file_put_contents($filename,json_encode($elements)) ;
  962. }
  963. public function generateLctRelevePaiementLoyer($filename, $contratId)
  964. {
  965. $contrat = $this->entityManager->getRepository(LctContrat::class)->find($contratId) ;
  966. $pourcentage = is_null($contrat->getPourcentage()) ? 0 : $contrat->getPourcentage() ;
  967. $tabMois = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"];
  968. $statutLoyerPaye = $this->entityManager->getRepository(LctStatutLoyer::class)->findOneBy([
  969. "reference" => "PAYE"
  970. ]) ;
  971. $statutLoyerAcompte = $this->entityManager->getRepository(LctStatutLoyer::class)->findOneBy([
  972. "reference" => "ACOMPTE"
  973. ]) ;
  974. $repartitions = $this->entityManager->getRepository(LctRepartition::class)->findBy([
  975. "contrat" => $contrat,
  976. "statut" => $statutLoyerPaye
  977. ]) ;
  978. $lastRepartition = $this->entityManager->getRepository(LctRepartition::class)->findOneBy([
  979. "contrat" => $contrat,
  980. "statut" => $statutLoyerAcompte
  981. ],["id" => "DESC"]) ;
  982. $childs = [] ;
  983. $totalReleve = 0 ;
  984. foreach ($repartitions as $repartition) {
  985. $item = [] ;
  986. $statutRepart = $repartition->getStatut()->getReference() ;
  987. if($statutRepart == "CAUTION")
  988. continue ;
  989. $montant = is_null($repartition->getMontant()) ? 0 : $repartition->getMontant() ;
  990. $commission = ($pourcentage * $montant) / 100 ;
  991. $versement = '<button value="'.$repartition->getId().'" data-commission="'.($montant - $commission).'" class="btn btn-outline-success lct_check_versement btn-sm font-smaller"><i class="fa fa-hand-holding-dollar"></i></button>' ;
  992. if(is_null($repartition->getNumQuittance()))
  993. {
  994. $selection = '<button data-value="'.$repartition->getId().'" class="btn btn-outline-info lct_select_impression btn-sm font-smaller"><i class="fa fa-check"></i></button>' ;
  995. }
  996. else
  997. {
  998. $selection = '<a href="#" data-value="'.$repartition->getNumQuittance()->getId().'" class="lct_print_quittance_exist text-primary font-weight-bold text-link">'.$repartition->getNumQuittance()->getNumero().'</a>' ;
  999. }
  1000. if(!is_null($repartition->getVersement()))
  1001. {
  1002. $versement = '<b class="text-success">OK</b>' ;
  1003. }
  1004. $item["id"] = $repartition->getId() ;
  1005. $item["designation"] = "Paiement. ".$repartition->getDesignation() ;
  1006. $item["debutLimite"] = is_null($repartition->getDateDebut()) ? "" : $repartition->getDateDebut()->format("d/m/Y") ;
  1007. $item["dateLimite"] = is_null($repartition->getDateLimite()) ? "" : $repartition->getDateLimite()->format("d/m/Y") ;
  1008. $item["datePaiement"] = $repartition->getPaiement()->getDate()->format("d/m/Y") ;
  1009. $item["mois"] = is_null($repartition->getMois()) ? "" : $tabMois[$repartition->getMois() - 1] ;
  1010. $item["annee"] = $repartition->getAnnee() ;
  1011. $item["dateDebut"] = is_null($repartition->getDateDebut()) ? "NONE" : $repartition->getDateDebut()->format("d/m/Y") ;
  1012. $item["montant"] = $repartition->getMontant() ;
  1013. $item["statut"] = $repartition->getStatut()->getReference() ;
  1014. $item["commission"] = $commission." (".$pourcentage."%)";
  1015. $item["commissionVal"] = $commission;
  1016. $item["versement"] = $versement ;
  1017. $item["versementVal"] = $montant - $commission ;
  1018. $item["selection"] = $selection;
  1019. $totalReleve += $repartition->getMontant() ;
  1020. array_push($childs,$item) ;
  1021. }
  1022. if(!is_null($lastRepartition))
  1023. {
  1024. $textDesignation = "Acompte. ".$lastRepartition->getDesignation() ;
  1025. $montant = is_null($lastRepartition->getMontant()) ? 0 : $lastRepartition->getMontant();
  1026. $commission = ($pourcentage * $montant) / 100 ;
  1027. $versement = "-" ;
  1028. $selection = "-" ;
  1029. $lastItem = [
  1030. "id" => $lastRepartition->getId(),
  1031. "designation" => $textDesignation,
  1032. "debutLimite" => is_null($lastRepartition->getDateDebut()) ? "" : $lastRepartition->getDateDebut()->format("d/m/Y") ,
  1033. "dateLimite" => is_null($lastRepartition->getDateLimite()) ? "" : $lastRepartition->getDateLimite()->format("d/m/Y") ,
  1034. "datePaiement" => $lastRepartition->getPaiement()->getDate()->format("d/m/Y"),
  1035. "mois" => is_null($lastRepartition->getMois()) ? "" : $tabMois[$lastRepartition->getMois() - 1] ,
  1036. "annee" => $lastRepartition->getAnnee(),
  1037. "dateDebut" => is_null($lastRepartition->getDateDebut()) ? "NONE" : $lastRepartition->getDateDebut()->format("d/m/Y"),
  1038. "montant" => $lastRepartition->getMontant(),
  1039. "statut" => $lastRepartition->getStatut()->getReference(),
  1040. "commission" => $commission." (".$pourcentage."%)",
  1041. "commissionVal" => $commission,
  1042. "versement" => $versement,
  1043. "versementVal" => 0,
  1044. "selection" => $selection
  1045. ] ;
  1046. $totalReleve += $lastRepartition->getMontant() ;
  1047. array_push($childs,$lastItem) ;
  1048. }
  1049. $frequence = is_null($contrat->getFrequenceRenouv()) ? 1 : $contrat->getFrequenceRenouv() ;
  1050. $response = [] ;
  1051. $moisDebut = $contrat->getDateDebut()->format("m") ;
  1052. $anneeDebut = $contrat->getDateDebut()->format("Y") ;
  1053. $indexMois = intval($moisDebut) - 1 ;
  1054. if($contrat->getCycle()->getReference() == "CMOIS")
  1055. {
  1056. if($contrat->getForfait()->getReference() == "FMOIS")
  1057. {
  1058. $dateDebut = $contrat->getDateDebut()->format("d/m/Y") ;
  1059. if($contrat->getPeriode()->getReference() == "M")
  1060. $duree = $contrat->getDuree() * $frequence;
  1061. else if($contrat->getPeriode()->getReference() == "A")
  1062. $duree = $contrat->getDuree() * $frequence * 12 ;
  1063. $dateAvant = $this->calculerDateAvantNjours($dateDebut,30) ;
  1064. $dateGenere = $contrat->getModePaiement()->getReference() == "DEBUT" ? $dateAvant : $dateDebut ;
  1065. $tableauMois = $this->genererTableauMois($dateGenere,$duree, $contrat->getDateLimite(),null) ;
  1066. $count = count($tableauMois);
  1067. for ($i=0; $i < $count; $i++) {
  1068. if ($i + 1 < $count && $tableauMois[$i]["indexMois"] > $tableauMois[$i + 1]["indexMois"]) {
  1069. // dd("passe".$i) ;
  1070. $tableauMois[$i + 1]["annee"] = $tableauMois[$i]["annee"] + 1;
  1071. }
  1072. $tableauMois[$i]["id"] = "-" ;
  1073. $tableauMois[$i]["designation"] = "LOYER ".$contrat->getBail()->getNom()." | ".$contrat->getBail()->getLieux() ;
  1074. $tableauMois[$i]["datePaiement"] = "-" ;
  1075. $tableauMois[$i]["commission"] = "-" ;
  1076. $tableauMois[$i]["commissionVal"] = 0 ;
  1077. $tableauMois[$i]["versement"] = "-" ;
  1078. $tableauMois[$i]["versementVal"] = 0 ;
  1079. $tableauMois[$i]["selection"] = "-" ;
  1080. $tableauMois[$i]["mois"] = $tabMois[$indexMois] ;
  1081. $tableauMois[$i]["annee"] = $anneeDebut ;
  1082. foreach ($childs as $child) {
  1083. if($child["debutLimite"] == $tableauMois[$i]["debutLimite"])
  1084. {
  1085. $tableauMois[$i]["id"] = $child["id"] ;
  1086. $tableauMois[$i]["datePaiement"] = $child["datePaiement"] ;
  1087. $tableauMois[$i]["commission"] = $child["commission"] ;
  1088. $tableauMois[$i]["commissionVal"] = $child["commissionVal"] ;
  1089. $tableauMois[$i]["versement"] = $child["versement"] ;
  1090. $tableauMois[$i]["versementVal"] = $child["versementVal"] ;
  1091. $tableauMois[$i]["selection"] = $child["selection"] ;
  1092. $tableauMois[$i]["montant"] = $child["montant"] ;
  1093. $tableauMois[$i]["designation"] = $child["designation"] ;
  1094. break;
  1095. }
  1096. }
  1097. $indexMois++ ;
  1098. if($indexMois >= 12 )
  1099. {
  1100. $indexMois = 0 ;
  1101. $anneeDebut++ ;
  1102. }
  1103. }
  1104. $response = $tableauMois ;
  1105. }
  1106. }
  1107. else if($contrat->getCycle()->getReference() == "CJOUR")
  1108. {
  1109. if($contrat->getForfait()->getReference() == "FJOUR")
  1110. {
  1111. $dateDebut = $contrat->getDateDebut()->format("d/m/Y") ;
  1112. $dateAvant = $this->calculerDateAvantNjours($dateDebut,1) ;
  1113. $dateGenere = $dateAvant ;
  1114. $duree = $contrat->getDuree() * $frequence;
  1115. $tableauMois = $this->genererTableauJour($dateGenere,$duree) ;
  1116. for ($i=0; $i < count($tableauMois); $i++) {
  1117. $tableauMois[$i]["id"] = "-" ;
  1118. $tableauMois[$i]["designation"] = "LOYER ".$contrat->getBail()->getNom()." | ".$contrat->getBail()->getLieux() ;
  1119. $tableauMois[$i]["datePaiement"] = "-" ;
  1120. $tableauMois[$i]["commission"] = "-" ;
  1121. $tableauMois[$i]["commissionVal"] = 0 ;
  1122. $tableauMois[$i]["versement"] = "-" ;
  1123. $tableauMois[$i]["versementVal"] = 0 ;
  1124. $tableauMois[$i]["selection"] = "-" ;
  1125. $tableauMois[$i]["mois"] = $tabMois[$indexMois] ;
  1126. $tableauMois[$i]["annee"] = $anneeDebut ;
  1127. foreach ($childs as $child) {
  1128. if($child["debutLimite"] == $tableauMois[$i]["debutLimite"])
  1129. {
  1130. $tableauMois[$i]["id"] = $child["id"] ;
  1131. $tableauMois[$i]["datePaiement"] = $child["datePaiement"] ;
  1132. $tableauMois[$i]["commission"] = $child["commission"] ;
  1133. $tableauMois[$i]["commissionVal"] = $child["commissionVal"] ;
  1134. $tableauMois[$i]["versement"] = $child["versement"] ;
  1135. $tableauMois[$i]["versementVal"] = $child["versementVal"] ;
  1136. $tableauMois[$i]["selection"] = $child["selection"] ;
  1137. $tableauMois[$i]["montant"] = $child["montant"] ;
  1138. $tableauMois[$i]["designation"] = $child["designation"] ;
  1139. break;
  1140. }
  1141. }
  1142. $indexMois++ ;
  1143. if($indexMois >= 12 )
  1144. {
  1145. $indexMois = 0 ;
  1146. $anneeDebut++ ;
  1147. }
  1148. }
  1149. $response = $tableauMois ;
  1150. }
  1151. }
  1152. if($contrat->getForfait()->getReference() == "FORFAIT")
  1153. {
  1154. $response = $childs ;
  1155. }
  1156. file_put_contents($filename,json_encode($response)) ;
  1157. }
  1158. public function getAgenceDevise($agence)
  1159. {
  1160. $element = [] ;
  1161. $element["symbole"] = is_null($agence->getDevise()) ? "" : $agence->getDevise()->getSymbole() ;
  1162. $element["lettre"] = is_null($agence->getDevise()) ? "" : $agence->getDevise()->getLettre() ;
  1163. return $element ;
  1164. }
  1165. public static function comparaisonMultiple($a, $b) {
  1166. // Comparaison par entrepot
  1167. $result = strcmp($a['nomType'], $b['nomType']);
  1168. if ($result !== 0) {
  1169. return $result;
  1170. }
  1171. // Comparaison par categorie
  1172. $result = strcmp($a['categorie'], $b['categorie']);
  1173. if ($result !== 0) {
  1174. return $result;
  1175. }
  1176. // Comparaison par nomType
  1177. return strcmp($a['entrepot'], $b['entrepot']);
  1178. }
  1179. // TODO Optimiser et revoir le system de cache
  1180. public function generateStockInEntrepot($filename,$agence)
  1181. {
  1182. $stockEntrepots = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findBy([
  1183. "agence" => $agence,
  1184. "statut" => True,
  1185. // "anneeData" => 2024,
  1186. ],[
  1187. "entrepot" => "ASC"
  1188. ]) ;
  1189. $elements = [] ;
  1190. foreach ($stockEntrepots as $stockEntrepot) {
  1191. $margeType = $stockEntrepot->getVariationPrix()->getMargeType() ;
  1192. if(is_null($margeType))
  1193. {
  1194. $this->entityManager->getRepository(PrdVariationPrix::class)->updateVariationPrix([
  1195. "variationPrix" => $stockEntrepot->getVariationPrix()
  1196. ]) ;
  1197. }
  1198. $prixAchat = $stockEntrepot->getVariationPrix()->getPrixAchat() ;
  1199. $charge = $stockEntrepot->getVariationPrix()->getCharge() ;
  1200. $marge = $stockEntrepot->getVariationPrix()->getMargeValeur() ;
  1201. $margeCalcul = $stockEntrepot->getVariationPrix()->getMargeType()->getCalcul() ;
  1202. $prixRevient = $prixAchat + $charge ;
  1203. if($margeCalcul == 1)
  1204. {
  1205. $marge = $marge ;
  1206. $margeVal = $marge ;
  1207. $margeRef = "MTN" ;
  1208. }
  1209. else if($margeCalcul == 100)
  1210. {
  1211. $margeVal = ($prixRevient * $marge) / 100 ;
  1212. $marge = $margeVal." (".$marge."%)" ;
  1213. $margeRef = "PRCT" ;
  1214. }
  1215. else if($margeCalcul == -1)
  1216. {
  1217. $marge = "(Coeff) ". $marge ;
  1218. $margeVal = $marge ;
  1219. $margeRef = "COEFF" ;
  1220. }
  1221. $element = [] ;
  1222. $element["id"] = $stockEntrepot->getId() ;
  1223. $element["date"] = $stockEntrepot->getCreatedAt()->format('d/m/Y') ;
  1224. $element["idE"] = $stockEntrepot->getEntrepot()->getId() ;
  1225. $element["idC"] = $stockEntrepot->getVariationPrix()->getProduit()->getPreference()->getId() ;
  1226. $element["idP"] = $stockEntrepot->getVariationPrix()->getProduit()->getId() ;
  1227. $element["idVP"] = $stockEntrepot->getVariationPrix()->getId() ;
  1228. $element["encodedIdVar"] = $this->encodeChiffre($stockEntrepot->getVariationPrix()->getId()) ;
  1229. $element["entrepot"] = $stockEntrepot->getEntrepot()->getNom() ;
  1230. $element["code"] = $stockEntrepot->getVariationPrix()->getProduit()->getCodeProduit() ;
  1231. $element["codeProduit"] = $stockEntrepot->getVariationPrix()->getProduit()->getCodeProduit() ;
  1232. $element["indice"] = !empty($stockEntrepot->getVariationPrix()->getIndice()) ? $stockEntrepot->getVariationPrix()->getIndice() : "-" ;
  1233. $element["categorie"] = $stockEntrepot->getVariationPrix()->getProduit()->getPreference()->getCategorie()->getNom() ;
  1234. $element["nom"] = $stockEntrepot->getVariationPrix()->getProduit()->getNom() ;
  1235. $element["images"] = "-" ;
  1236. $element["nomType"] = is_null($stockEntrepot->getVariationPrix()->getProduit()->getType()) ? "NA" : $stockEntrepot->getVariationPrix()->getProduit()->getType()->getNom() ;
  1237. $element["typeProduit"] = $stockEntrepot->getVariationPrix()->getProduit()->getTypeProduit() ;
  1238. $element["stock"] = $stockEntrepot->getStock() ;
  1239. $element["prixAchat"] = $prixAchat ;
  1240. $element["charge"] = $charge ;
  1241. $element["marge"] = $marge ;
  1242. $element["margeVal"] = $margeVal ;
  1243. $element["margeRef"] = $margeRef ;
  1244. $element["prixVente"] = $stockEntrepot->getVariationPrix()->getPrixVente() ;
  1245. array_push($elements,$element) ;
  1246. }
  1247. usort($elements, [self::class,'comparaisonMultiple']);
  1248. file_put_contents($filename,json_encode($elements)) ;
  1249. }
  1250. // TODO enlever si proble de cache resolut
  1251. public function generateStockInEntrepotNew($filename,$agence)
  1252. {
  1253. $stockEntrepots = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findBy([
  1254. "agence" => $agence,
  1255. "statut" => True,
  1256. ],[
  1257. "entrepot" => "ASC"
  1258. ]) ;
  1259. $elements = [] ;
  1260. foreach ($stockEntrepots as $stockEntrepot) {
  1261. $margeType = $stockEntrepot->getVariationPrix()->getMargeType() ;
  1262. if(is_null($margeType))
  1263. {
  1264. $this->entityManager->getRepository(PrdVariationPrix::class)->updateVariationPrix([
  1265. "variationPrix" => $stockEntrepot->getVariationPrix()
  1266. ]) ;
  1267. }
  1268. $prixAchat = $stockEntrepot->getVariationPrix()->getPrixAchat() ;
  1269. $charge = $stockEntrepot->getVariationPrix()->getCharge() ;
  1270. $marge = $stockEntrepot->getVariationPrix()->getMargeValeur() ;
  1271. $margeCalcul = $stockEntrepot->getVariationPrix()->getMargeType()->getCalcul() ;
  1272. $prixRevient = $prixAchat + $charge ;
  1273. if($margeCalcul == 1)
  1274. {
  1275. $marge = $marge ;
  1276. $margeVal = $marge ;
  1277. $margeRef = "MTN" ;
  1278. }
  1279. else if($margeCalcul == 100)
  1280. {
  1281. $margeVal = ($prixRevient * $marge) / 100 ;
  1282. $marge = $margeVal." (".$marge."%)" ;
  1283. $margeRef = "PRCT" ;
  1284. }
  1285. else if($margeCalcul == -1)
  1286. {
  1287. $marge = "(Coeff) ". $marge ;
  1288. $margeVal = $marge ;
  1289. $margeRef = "COEFF" ;
  1290. }
  1291. $element = [] ;
  1292. $element["id"] = $stockEntrepot->getId() ;
  1293. $element["idE"] = $stockEntrepot->getEntrepot()->getId() ;
  1294. $element["idC"] = $stockEntrepot->getVariationPrix()->getProduit()->getPreference()->getId() ;
  1295. $element["idP"] = $stockEntrepot->getVariationPrix()->getProduit()->getId() ;
  1296. $element["idVP"] = $stockEntrepot->getVariationPrix()->getId() ;
  1297. $element["encodedIdVar"] = $this->encodeChiffre($stockEntrepot->getVariationPrix()->getId()) ;
  1298. $element["entrepot"] = $stockEntrepot->getEntrepot()->getNom() ;
  1299. $element["code"] = $stockEntrepot->getVariationPrix()->getProduit()->getCodeProduit() ;
  1300. $element["codeProduit"] = $stockEntrepot->getVariationPrix()->getProduit()->getCodeProduit() ;
  1301. $element["indice"] = !empty($stockEntrepot->getVariationPrix()->getIndice()) ? $stockEntrepot->getVariationPrix()->getIndice() : "-" ;
  1302. $element["categorie"] = $stockEntrepot->getVariationPrix()->getProduit()->getPreference()->getCategorie()->getNom() ;
  1303. $element["nom"] = $stockEntrepot->getVariationPrix()->getProduit()->getNom() ;
  1304. $element["images"] = "-" ;
  1305. $element["nomType"] = is_null($stockEntrepot->getVariationPrix()->getProduit()->getType()) ? "NA" : $stockEntrepot->getVariationPrix()->getProduit()->getType()->getNom() ;
  1306. $element["stock"] = $stockEntrepot->getStock() ;
  1307. $element["prixAchat"] = $prixAchat ;
  1308. $element["charge"] = $charge ;
  1309. $element["marge"] = $marge ;
  1310. $element["margeVal"] = $margeVal ;
  1311. $element["margeRef"] = $margeRef ;
  1312. $element["prixVente"] = $stockEntrepot->getVariationPrix()->getPrixVente() ;
  1313. array_push($elements,$element) ;
  1314. }
  1315. usort($elements, [self::class,'comparaisonMultiple']);
  1316. // file_put_contents($filename,json_encode($elements)) ;
  1317. return $elements;
  1318. }
  1319. public function generatePrdGenEntrepot($filename,$agence)
  1320. {
  1321. $entrepots = $this->entityManager->getRepository(PrdEntrepot::class)->findBy([
  1322. "agence" => $agence,
  1323. "statut" => True,
  1324. ]) ;
  1325. $elements = [] ;
  1326. foreach($entrepots as $entrepot)
  1327. {
  1328. $stockEntrepot = $this->entityManager->getRepository(PrdHistoEntrepot::class)->getTotalStockInEntrepot([
  1329. "entrepot" => $entrepot->getId(),
  1330. "statut" => True
  1331. ]) ;
  1332. // Calculer le montant total pour cet entrepĂ´t
  1333. $histoEntrepots = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findBy([
  1334. "entrepot" => $entrepot,
  1335. "statut" => True
  1336. ]) ;
  1337. $montantTotalVente = "0" ;
  1338. $montantTotalAchat = "0" ;
  1339. foreach ($histoEntrepots as $histoEntrepot) {
  1340. $variationPrix = $histoEntrepot->getVariationPrix() ;
  1341. if ($variationPrix && $variationPrix->isStatut()) {
  1342. $prixVente = $variationPrix->getPrixVente() ? (string)$variationPrix->getPrixVente() : "0" ;
  1343. $prixAchat = $variationPrix->getPrixAchat() ? (string)$variationPrix->getPrixAchat() : "0" ;
  1344. $stock = $histoEntrepot->getStock() ? (string)$histoEntrepot->getStock() : "0" ;
  1345. $montantVente = bcmul($stock, $prixVente, 2) ;
  1346. $montantAchat = bcmul($stock, $prixAchat, 2) ;
  1347. $montantTotalVente = bcadd($montantTotalVente, $montantVente, 2) ;
  1348. $montantTotalAchat = bcadd($montantTotalAchat, $montantAchat, 2) ;
  1349. }
  1350. }
  1351. $element = [] ;
  1352. $element["id"] = $entrepot->getId() ;
  1353. $element["encodedId"] = $this->encodeChiffre($entrepot->getId()) ;
  1354. $element["nom"] = $entrepot->getNom() ;
  1355. $element["stock"] = $stockEntrepot["stockTotal"] ?? 0 ;
  1356. $element["montantVente"] = (float)$montantTotalVente ;
  1357. $element["montantAchat"] = (float)$montantTotalAchat ;
  1358. // foreach ($stockEntrepots as $stockEntrepot) {
  1359. // $element["stock"] += $stockEntrepot->getStock() ;
  1360. // }
  1361. array_push($elements,$element) ;
  1362. }
  1363. file_put_contents($filename,json_encode($elements)) ;
  1364. }
  1365. public static function comparaisonCaissePanier($a, $b) {
  1366. $dateA = \DateTime::createFromFormat('d/m/Y', $a['date']);
  1367. $dateB = \DateTime::createFromFormat('d/m/Y', $b['date']);
  1368. return $dateB <=> $dateA;
  1369. }
  1370. public function generateCaissePanierCommande($filename,$agence)
  1371. {
  1372. $panierCommandes = $this->entityManager->getRepository(CaissePanier::class)->findBy([
  1373. "agence" => $agence,
  1374. "statut" => True,
  1375. ],["id" => "DESC"]) ;
  1376. $elements = [] ;
  1377. foreach ($panierCommandes as $panierCommande) {
  1378. $commande = $panierCommande->getCommande() ;
  1379. $variationPrix = $panierCommande->getVariationPrix() ;
  1380. $codeProduit = is_null($variationPrix) ? "-" : $variationPrix->getProduit()->getCodeProduit() ;
  1381. $nomProduit = is_null($variationPrix) ? "-" : $variationPrix->getProduit()->getNom() ;
  1382. $nomProduit = $nomProduit == "-" ? $panierCommande->getDesignation() : $nomProduit ;
  1383. $idProduit = is_null($variationPrix) ? "-" : $variationPrix->getProduit()->getId() ;
  1384. $indice = is_null($variationPrix) ? "-" : (is_null($variationPrix->getIndice()) ? "-" : $variationPrix->getIndice()) ;
  1385. $element = [] ;
  1386. $element["id"] = $commande->getId() ;
  1387. $element["date"] = $commande->getDate()->format('d/m/Y') ;
  1388. $element["currentDate"] = $commande->getDate()->format('d/m/Y') ;
  1389. $element["dateDeclaration"] = $commande->getDate()->format('d/m/Y') ;
  1390. $element["dateDebut"] = $commande->getDate()->format('d/m/Y') ;
  1391. $element["dateFin"] = $commande->getDate()->format('d/m/Y') ;
  1392. $element["annee"] = $commande->getDate()->format('Y') ;
  1393. $element["mois"] = $commande->getDate()->format('m') ;
  1394. $element["numCommande"] = $commande->getNumCommande() ;
  1395. $element["codeProduit"] = $codeProduit ;
  1396. $element["nom"] = $nomProduit ;
  1397. $element["quantite"] = $panierCommande->getQuantite() ;
  1398. $element["prix"] = $panierCommande->getPrix() ;
  1399. $element["indice"] = $indice ;
  1400. $element["idP"] = $idProduit ;
  1401. $element["tva"] = $panierCommande->getTva() ;
  1402. $element["totalTva"] = $commande->getTva() ;
  1403. $element["montantRecu"] = $commande->getMontantRecu() ;
  1404. $element["montantPayee"] = $commande->getMontantPayee() ;
  1405. $element["remiseVal"] = is_null($commande->getRemiseValeur()) ? 0 : $panierCommande->getCommande()->getRemiseValeur() ;
  1406. $element["remiseType"] = is_null($commande->getRemiseType()) ? "-" : $panierCommande->getCommande()->getRemiseType()->getCalcul() ;
  1407. $element["user"] = $commande->getUser()->getId() ;
  1408. array_push($elements,$element) ;
  1409. }
  1410. usort($elements, [self::class, 'comparaisonCaissePanier']);
  1411. file_put_contents($filename,json_encode($elements)) ;
  1412. }
  1413. public function generateCaisseCommande($filename, $agence)
  1414. {
  1415. $commandes = $this->entityManager->getRepository(CaisseCommande::class)->findBy([
  1416. "agence" => $agence,
  1417. "statut" => True
  1418. ],["date" => "DESC"]) ;
  1419. $elements = [] ;
  1420. foreach ($commandes as $commande) {
  1421. $element = [] ;
  1422. $element["id"] = $commande->getId() ;
  1423. $element["agence"] = $commande->getAgence()->getId() ;
  1424. $element["user"] = $commande->getUser()->getId() ;
  1425. $element["numCommande"] = $commande->getNumCommande() ;
  1426. $element["montantRecu"] = $commande->getMontantRecu() ;
  1427. $element["montantPayee"] = $commande->getMontantPayee();
  1428. $element["totalTva"] = $commande->getTva();
  1429. $element["montant"] = $commande->getMontantPayee();
  1430. $element["date"] = $commande->getDate()->format('d/m/Y') ;
  1431. array_push($elements,$element) ;
  1432. }
  1433. file_put_contents($filename,json_encode($elements)) ;
  1434. }
  1435. public function generateModModelePdf($filename,$agence)
  1436. {
  1437. $modelePdfs = $this->entityManager->getRepository(ModModelePdf::class)->findBy([
  1438. "agence" => $agence,
  1439. "statut" => True,
  1440. ],
  1441. [ "id" => "DESC" ]) ;
  1442. $elements = [] ;
  1443. foreach ($modelePdfs as $modelePdf) {
  1444. $element = [] ;
  1445. $element["id"] = $modelePdf->getId() ;
  1446. $element["encodedId"] = $this->encodeChiffre($modelePdf->getId()) ;
  1447. $element["user"] = $modelePdf->getUser()->getId() ;
  1448. $element["nom"] = $modelePdf->getNom() ;
  1449. $element["type"] = $modelePdf->getType() == "ENTETE" ? "EntĂªte de page" : "Bas de page" ;
  1450. $element["refType"] = $modelePdf->getType() ;
  1451. $element["statut"] = $modelePdf->isStatut();
  1452. array_push($elements,$element) ;
  1453. }
  1454. file_put_contents($filename,json_encode($elements)) ;
  1455. }
  1456. public function synchroModelePdf()
  1457. {
  1458. $modelePdfs = $this->entityManager->getRepository(ModModelePdf::class)->findBy([
  1459. "statut" => True,
  1460. "agence" => NULL
  1461. ]) ;
  1462. foreach ($modelePdfs as $modelePdf) {
  1463. $modelePdf->setAgence($modelePdf->getUser()->getAgence()) ;
  1464. $this->entityManager->flush() ;
  1465. }
  1466. }
  1467. public function generateFacture($filename, $agence)
  1468. {
  1469. $factures = $this->entityManager->getRepository(Facture::class)->findBy([
  1470. "agence" => $agence,
  1471. "statut" => True,
  1472. ],[
  1473. "id" => "DESC"
  1474. ]
  1475. ) ;
  1476. $elements = [] ;
  1477. // Produit
  1478. // PROD
  1479. // Prestation Standard
  1480. // PSTD
  1481. // Prestation BĂ¢timent
  1482. // PBAT
  1483. // Prestation Location
  1484. // PLOC
  1485. foreach ($factures as $facture) {
  1486. $refModele = $facture->getModele()->getReference() ;
  1487. $entrepot = "-" ;
  1488. $idEntrepot = "-" ;
  1489. if($refModele == "PROD")
  1490. {
  1491. // DEBUT VRAI
  1492. $entrepotObj = $this->entityManager->getRepository(PrdEntrepot::class)->findOneBy([
  1493. "nom" => strtoupper($facture->getLieu()),
  1494. "agence" => $agence,
  1495. "statut" => True
  1496. ]) ;
  1497. if(!is_null($entrepotObj))
  1498. {
  1499. $entrepot = $entrepotObj->getNom();
  1500. $idEntrepot = $entrepotObj->getId();
  1501. }
  1502. else
  1503. {
  1504. $affectEntrepot = $this->entityManager->getRepository(PrdEntrpAffectation::class)->findOneBy([
  1505. "agent" => $facture->getUser(),
  1506. "statut" => True
  1507. ]) ;
  1508. if(!is_null($affectEntrepot))
  1509. {
  1510. $entrepot = $affectEntrepot->getEntrepot()->getNom();
  1511. $idEntrepot = $affectEntrepot->getEntrepot()->getId();
  1512. }
  1513. else
  1514. {
  1515. $factDetail = $this->entityManager->getRepository(FactDetails::class)->findOneByEntite([
  1516. "facture" => $facture,
  1517. "activite" => "Produit",
  1518. "statut" => True
  1519. ]) ;
  1520. if(!is_null($factDetail))
  1521. {
  1522. if (!is_null($factDetail->getHistoEntrepot()))
  1523. {
  1524. $entrepot = $factDetail->getHistoEntrepot()->getEntrepot()->getNom() ;
  1525. $idEntrepot = $factDetail->getHistoEntrepot()->getEntrepot()->getId() ;
  1526. }
  1527. else
  1528. {
  1529. $entrepot = "-" ;
  1530. $idEntrepot = "-" ;
  1531. }
  1532. }
  1533. }
  1534. }
  1535. // FIN VRAI
  1536. }
  1537. if(!is_null($facture->getEntrepot()))
  1538. {
  1539. if($refModele == "PROD")
  1540. {
  1541. $entrepot = is_null($facture->getEntrepot()) ? "-" : $facture->getEntrepot()->getNom();
  1542. $idEntrepot = is_null($facture->getEntrepot()) ? "-" : $facture->getEntrepot()->getId();
  1543. }
  1544. }
  1545. $element = [] ;
  1546. $specification = "NONE" ;
  1547. $element["id"] = $facture->getId() ;
  1548. $element["idC"] = $facture->getClient()->getId() ;
  1549. $element["idT"] = $facture->getType()->getId() ;
  1550. $element["idM"] = $facture->getModele()->getId() ;
  1551. $element["refModele"] = $facture->getModele()->getReference() ;
  1552. $element["entrepot"] = $refModele == "PROD" ? $entrepot : "-" ;
  1553. $element["idEntrepot"] = $refModele == "PROD" ? $idEntrepot : "-" ;
  1554. $element["date"] = $facture->getDate()->format('d/m/Y') ;
  1555. $element["currentDate"] = $facture->getDate()->format('d/m/Y') ;
  1556. $element["dateFacture"] = $facture->getDate()->format('d/m/Y') ;
  1557. $element["dateDebut"] = $facture->getDate()->format('d/m/Y') ;
  1558. $element["dateFin"] = $facture->getDate()->format('d/m/Y') ;
  1559. $element["annee"] = $facture->getDate()->format('Y') ;
  1560. $element["mois"] = $facture->getDate()->format('m') ;
  1561. $element["agence"] = $facture->getAgence()->getId() ;
  1562. $element["user"] = $facture->getUser()->getId() ;
  1563. $element["numFact"] = $facture->getNumFact() ;
  1564. $element["modele"] = $facture->getModele()->getNom() ;
  1565. $element["type"] = $facture->getType()->getNom() ;
  1566. $element["refType"] = $facture->getType()->getReference() ;
  1567. $element["dateCreation"] = $facture->getCreatedAt()->format('d/m/Y') ;
  1568. $element["client"] = $this->getFactureClient($facture)["client"] ;
  1569. $element["total"] = $facture->getTotal() ;
  1570. $element["specification"] = $specification ;
  1571. $element["nature"] = "FACTURE";
  1572. array_push($elements,$element) ;
  1573. }
  1574. // dd($elements) ;
  1575. file_put_contents($filename,json_encode($elements)) ;
  1576. }
  1577. public function generateParamGeneral($filename, $agence)
  1578. {
  1579. $devises = $this->entityManager->getRepository(Devise::class)->findBy([
  1580. "agence" => $agence,
  1581. "statut" => True
  1582. ]) ;
  1583. $elements = [] ;
  1584. foreach ($devises as $devise) {
  1585. $element = [] ;
  1586. $element["id"] = $devise->getId() ;
  1587. $element["agence"] = $devise->getAgence()->getId() ;
  1588. $element["symbole"] = $devise->getSymbole() ;
  1589. $element["lettre"] = $devise->getLettre() ;
  1590. $element["montantBase"] = $devise->getMontantBase() ;
  1591. array_push($elements,$element) ;
  1592. }
  1593. file_put_contents($filename,json_encode($elements)) ;
  1594. }
  1595. public function objectToArray($objects)
  1596. {
  1597. $elements = [] ;
  1598. foreach($objects as $item)
  1599. {
  1600. $elements[] = (array)$item ;
  1601. }
  1602. return $elements ;
  1603. }
  1604. public function generateInterneMateriel($filename,$agence)
  1605. {
  1606. $materiels = $this->entityManager->getRepository(IntMateriel::class)->findBy([
  1607. "agence" => $agence,
  1608. "statut" => True
  1609. ]) ;
  1610. $elements = [] ;
  1611. foreach ($materiels as $materiel) {
  1612. $element = [] ;
  1613. $element["id"] = $materiel->getId() ;
  1614. $element["agence"] = $materiel->getAgence()->getId() ;
  1615. $element["nom"] = $materiel->getNom() ;
  1616. $element["libelle"] = $materiel->getLibelle()->getNom() ;
  1617. $element["quantite"] = $materiel->getQuantite() ;
  1618. $element["unite"] = $materiel->getUnite() ;
  1619. $element["stock"] = $materiel->getStock() ;
  1620. array_push($elements,$element) ;
  1621. }
  1622. file_put_contents($filename,json_encode($elements)) ;
  1623. }
  1624. public function generateInterneLibelle($filename,$agence)
  1625. {
  1626. $libelles = $this->entityManager->getRepository(IntLibelle::class)->findBy([
  1627. "agence" => $agence,
  1628. ]) ;
  1629. $elements = [] ;
  1630. foreach ($libelles as $libelle) {
  1631. $element = [] ;
  1632. $element["id"] = $libelle->getId() ;
  1633. $element["agence"] = $libelle->getAgence()->getId() ;
  1634. $element["nom"] = $libelle->getNom() ;
  1635. array_push($elements,$element) ;
  1636. }
  1637. file_put_contents($filename,json_encode($elements)) ;
  1638. }
  1639. public function generateInterneMouvement($filename,$agence)
  1640. {
  1641. $mouvements = $this->entityManager->getRepository(IntMouvement::class)->findBy([
  1642. "agence" => $agence,
  1643. ]) ;
  1644. $elements = [] ;
  1645. foreach ($mouvements as $mouvement) {
  1646. $element = [] ;
  1647. $element["id"] = $mouvement->getId() ;
  1648. $element["agence"] = $mouvement->getAgence()->getId() ;
  1649. $element["date"] = $mouvement->getDate()->format("d/m/Y") ;
  1650. $element["designation"] = $mouvement->getDesignation() ;
  1651. $element["stock"] = $mouvement->getStock() ;
  1652. $element["refType"] = $mouvement->getType()->getReference() ;
  1653. array_push($elements,$element) ;
  1654. }
  1655. file_put_contents($filename,json_encode($elements)) ;
  1656. }
  1657. public function generateBonLivraison($filename, $agence)
  1658. {
  1659. $lvrDetails = $this->entityManager->getRepository(LvrDetails::class)->findBy([
  1660. "statut" => True,
  1661. "agence" => $agence
  1662. ]) ;
  1663. $elements = [] ;
  1664. foreach ($lvrDetails as $lvrDetail) {
  1665. if($lvrDetail->getLivraison()->getTypeSource() =="Facture")
  1666. {
  1667. $facture = $this->entityManager->getRepository(Facture::class)->find($lvrDetail->getLivraison()->getSource()) ;
  1668. if($facture->getClient()->getType()->getId() == 2)
  1669. $client = $facture->getClient()->getClient()->getNom() ;
  1670. else
  1671. $client = $facture->getClient()->getSociete()->getNom() ;
  1672. }
  1673. else
  1674. {
  1675. $bonCommande = $this->entityManager->getRepository(CmdBonCommande::class)->find($lvrDetail->getLivraison()->getSource()) ;
  1676. if($bonCommande->getFacture()->getClient()->getType()->getId() == 2)
  1677. $client = $bonCommande->getFacture()->getClient()->getClient()->getNom() ;
  1678. else
  1679. $client = $bonCommande->getFacture()->getClient()->getSociete()->getNom() ;
  1680. }
  1681. $element = [] ;
  1682. $element["id"] = $lvrDetail->getLivraison()->getId() ;
  1683. $element["numBonLvr"] = $lvrDetail->getLivraison()->getNumLivraison() ;
  1684. $element["source"] = $lvrDetail->getLivraison()->getSource() ;
  1685. $element["typeSource"] = $lvrDetail->getLivraison()->getTypeSource() ;
  1686. $element["client"] = $client ;
  1687. $element["designation"] = $lvrDetail->getFactureDetail()->getDesignation() ;
  1688. $element["quantite"] = $lvrDetail->getFactureDetail()->getQuantite() ;
  1689. $element["agence"] = $lvrDetail->getAgence()->getId() ;
  1690. $element["date"] = $lvrDetail->getLivraison()->getDate()->format('d/m/Y') ;
  1691. $element["lieu"] = $lvrDetail->getLivraison()->getLieu() ;
  1692. $element["statut"] = $lvrDetail->getLivraison()->getStatut()->getNom() ;
  1693. $element["refStatut"] = $lvrDetail->getLivraison()->getStatut()->getreference() ;
  1694. array_push($elements,$element) ;
  1695. }
  1696. file_put_contents($filename,json_encode($elements)) ;
  1697. }
  1698. public function genererSavMotif($filename, $agence)
  1699. {
  1700. $motifs = $this->entityManager->getRepository(SavMotif::class)->findBy([
  1701. "statut" => True,
  1702. "agence" => $agence
  1703. ]) ;
  1704. $elements = [] ;
  1705. foreach ($motifs as $motif) {
  1706. $element = [] ;
  1707. $element["id"] = $motif->getId() ;
  1708. $element["agence"] = $motif->getAgence()->getId() ;
  1709. $element["nom"] = $motif->getNom() ;
  1710. array_push($elements,$element) ;
  1711. }
  1712. file_put_contents($filename,json_encode($elements)) ;
  1713. }
  1714. public function generateSavAnnulation($filename, $agence)
  1715. {
  1716. $annulations = $this->entityManager->getRepository(SavAnnulation::class)->findBy([
  1717. "statut" => True,
  1718. "agence" => $agence,
  1719. ]) ;
  1720. $elements = [] ;
  1721. foreach ($annulations as $annulation) {
  1722. $facture = $annulation->getFacture() ;
  1723. if(!is_null($facture))
  1724. {
  1725. $client = $this->getFactureClient($facture) ;
  1726. $nomClient = $client["client"] ;
  1727. $idClient = $facture->getClient()->getId() ;
  1728. $idFacture = $facture->getId() ;
  1729. }
  1730. else
  1731. {
  1732. $nomClient = "-" ;
  1733. $idClient = "-" ;
  1734. $idFacture = "-" ;
  1735. }
  1736. $total = $annulation->getMontant() ;
  1737. $retenu = 0 ;
  1738. if($annulation->getPourcentage() == 0)
  1739. {
  1740. $retenu = "-" ;
  1741. $signe = "" ;
  1742. $remboursee = $annulation->getMontant() ;
  1743. }
  1744. else
  1745. {
  1746. $retenu = ($annulation->getMontant() * $annulation->getPourcentage()) / 100 ;
  1747. $signe = "(".$annulation->getPourcentage()."%)" ;
  1748. $remboursee = $annulation->getMontant() - $retenu ;
  1749. }
  1750. $specification = $annulation->getSpecification() ;
  1751. $nomSpec = !is_null($specification) ? $specification->getNom() : "-" ;
  1752. $refSpec = !is_null($specification) ? $specification->getReference() : "-" ;
  1753. $element = [] ;
  1754. $element["id"] = $annulation->getId() ;
  1755. $element["agence"] = $annulation->getAgence()->getId() ;
  1756. $element["user"] = $annulation->getUser()->getId() ;
  1757. $element["date"] = $annulation->getDate()->format('d/m/Y') ;
  1758. $element["annee"] = $annulation->getDate()->format('Y') ;
  1759. $element["lieu"] = $annulation->getLieu() ;
  1760. $element["typeAffiche"] = is_null($annulation->getFacture()) ? "CAISSE" : "FACTURE" ;
  1761. $element["numero"] = $annulation->getNumFact() ;
  1762. $element["client"] = $nomClient ;
  1763. $element["idC"] = $idClient ;
  1764. $element["idF"] = $idFacture ;
  1765. $element["type"] = $annulation->getType()->getNom() ;
  1766. $element["motif"] = $annulation->getMotif()->getNom() ;
  1767. $element["spec"] = $nomSpec ;
  1768. $element["refSpec"] = $refSpec ;
  1769. $element["total"] = $total ;
  1770. $element["retenu"] = $retenu ;
  1771. $element["signe"] = $signe ;
  1772. $element["remboursee"] = $remboursee ;
  1773. array_push($elements,$element) ;
  1774. }
  1775. file_put_contents($filename,json_encode($elements)) ;
  1776. }
  1777. public function generateCredit($filename, $agence,$refPaiement)
  1778. {
  1779. $paiement = $this->entityManager->getRepository(FactPaiement::class)->findOneBy([
  1780. "reference" => $refPaiement
  1781. ]) ;
  1782. $finances = $this->entityManager->getRepository(CrdFinance::class)->findBy([
  1783. "agence" => $agence,
  1784. "paiement" => $paiement
  1785. ],["id" => "DESC"]) ;
  1786. $elements = [] ;
  1787. foreach ($finances as $finance) {
  1788. $facture = $finance->getFacture() ;
  1789. if(!$facture->isStatut() or $facture->getType()->getReference() != 'DF')
  1790. continue ;
  1791. $client = $this->getFactureClient($finance->getFacture())["client"] ;
  1792. $totalPayee = $this->entityManager->getRepository(CrdDetails::class)->getFinanceTotalPayee($finance->getId()) ;
  1793. $refModele = $facture->getModele()->getReference() ;
  1794. $entrepot = "-" ;
  1795. $idEntrepot = "-" ;
  1796. if($refModele == "PROD")
  1797. {
  1798. // DEBUT VRAI
  1799. $entrepotObj = $this->entityManager->getRepository(PrdEntrepot::class)->findOneBy([
  1800. "nom" => strtoupper($facture->getLieu()),
  1801. "agence" => $agence,
  1802. "statut" => True
  1803. ]) ;
  1804. if(!is_null($entrepotObj))
  1805. {
  1806. $entrepot = $entrepotObj->getNom();
  1807. $idEntrepot = $entrepotObj->getId();
  1808. }
  1809. else
  1810. {
  1811. $affectEntrepot = $this->entityManager->getRepository(PrdEntrpAffectation::class)->findOneBy([
  1812. "agent" => $facture->getUser(),
  1813. "statut" => True
  1814. ]) ;
  1815. if(!is_null($affectEntrepot))
  1816. {
  1817. $entrepot = $affectEntrepot->getEntrepot()->getNom();
  1818. $idEntrepot = $affectEntrepot->getEntrepot()->getId();
  1819. }
  1820. else
  1821. {
  1822. $factDetail = $this->entityManager->getRepository(FactDetails::class)->findOneByEntite([
  1823. "facture" => $facture,
  1824. "activite" => "Produit",
  1825. "statut" => True
  1826. ]) ;
  1827. if(!is_null($factDetail))
  1828. {
  1829. $idVariation = $factDetail->getEntite() ;
  1830. $variation = $this->entityManager->getRepository(PrdVariationPrix::class)->find($idVariation) ;
  1831. $histoEntrepot = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findOneBy([
  1832. "variationPrix" => $variation,
  1833. "statut" => True
  1834. ]) ;
  1835. $entrepot = $histoEntrepot->getEntrepot()->getNom();
  1836. $idEntrepot = $histoEntrepot->getEntrepot()->getId();
  1837. }
  1838. else
  1839. {
  1840. $entrepot = "-" ;
  1841. $idEntrepot = "-" ;
  1842. }
  1843. }
  1844. }
  1845. // FIN VRAI
  1846. }
  1847. if(!is_null($facture->getEntrepot()))
  1848. {
  1849. if($refModele == "PROD")
  1850. {
  1851. $entrepot = is_null($facture->getEntrepot()) ? "-" : $facture->getEntrepot()->getNom();
  1852. $idEntrepot = is_null($facture->getEntrepot()) ? "-" : $facture->getEntrepot()->getId();
  1853. }
  1854. }
  1855. $factureDetails = $this->entityManager->getRepository(FactDetails::class)->findBy([
  1856. "statut" => True,
  1857. "facture" => $finance->getFacture()
  1858. ]) ;
  1859. foreach ($factureDetails as $factureDetail) {
  1860. $element = [] ;
  1861. $tva = (($factureDetail->getPrix() * $factureDetail->getTvaVal()) / 100) * $factureDetail->getQuantite() ;
  1862. $total = $factureDetail->getPrix() * $factureDetail->getQuantite() ;
  1863. $remiseVal = $this->getFactureRemise($factureDetail,$total) ;
  1864. $total = $total - $remiseVal ;
  1865. $typeRemise = is_null($factureDetail->getRemiseType()) ? "" : $factureDetail->getRemiseType()->getNotation() ;
  1866. $typeRemise = ($typeRemise == "%") ? $typeRemise : "" ;
  1867. $typeRemiseG = is_null($finance->getFacture()->getRemiseType()) ? "" : $finance->getFacture()->getRemiseType()->getNotation() ;
  1868. $typeRemiseG = ($typeRemiseG == "%") ? $typeRemiseG : "" ;
  1869. $element["id"] = $finance->getId() ;
  1870. $element["idC"] = $facture->getClient()->getId() ;
  1871. $element["refPaiement"] = $finance->getPaiement()->getReference() ;
  1872. $element["entrepot"] = $entrepot ;
  1873. $element["idE"] = $idEntrepot ;
  1874. $element["mois"] = $facture->getDate()->format('m') ;
  1875. $element["annee"] = $facture->getDate()->format('Y') ;
  1876. $element["currentDate"] = $facture->getDate()->format('d/m/Y') ;
  1877. $element["dateDebut"] = $facture->getDate()->format('d/m/Y') ;
  1878. $element["dateFin"] = $facture->getDate()->format('d/m/Y') ;
  1879. $element["dateFacture"] = $facture->getDate()->format('d/m/Y') ;
  1880. $element["agence"] = $finance->getAgence()->getId() ;
  1881. $element["date"] = $finance->getFacture()->getDate()->format('d/m/Y') ;
  1882. $element["numFnc"] = $finance->getNumFnc() ;
  1883. $element["numFacture"] = $facture->getNumFact() ;
  1884. $element["client"] = $client ;
  1885. $element["designation"] = $factureDetail->getDesignation() ;
  1886. $element["qte"] = $factureDetail->getQuantite() ;
  1887. $element["prix"] = $factureDetail->getPrix() ;
  1888. $element["tva"] = ($tva == 0) ? "-" : $tva ; ;
  1889. $element["remise"] = $factureDetail->getRemiseVal()." ".$typeRemise ;
  1890. $element["total"] = $total ;
  1891. $element["idStatut"] = $finance->getStatut()->getId() ;
  1892. $element["statut"] = $finance->getStatut()->getNom() ;
  1893. $element["refStatut"] = $finance->getStatut()->getreference() ;
  1894. $element["remiseG"] = $finance->getFacture()->getRemiseVal()." ".$typeRemiseG ;
  1895. $element["totalTva"] = $finance->getFacture()->getTvaVal() ;
  1896. $element["totalTtc"] = $finance->getFacture()->getTotal() ;
  1897. $element["totalPayee"] = $totalPayee["total"] ;
  1898. array_push($elements,$element) ;
  1899. }
  1900. }
  1901. file_put_contents($filename,json_encode($elements)) ;
  1902. }
  1903. public function generatePrestationService($filename, $agence)
  1904. {
  1905. $services = $this->entityManager->getRepository(Service::class)->findBy([
  1906. "statut" => True,
  1907. "agence" => $agence
  1908. ],
  1909. [
  1910. "nom" => "ASC"
  1911. ]) ;
  1912. $elements = [] ;
  1913. foreach ($services as $service) {
  1914. $element = [] ;
  1915. $element["id"] = $service->getId() ;
  1916. $element["agence"] = $service->getAgence()->getId() ;
  1917. $element["nom"] = $service->getNom() ;
  1918. $element["description"] = $service->getDescription() ;
  1919. array_push($elements,$element) ;
  1920. }
  1921. file_put_contents($filename,json_encode($elements)) ;
  1922. }
  1923. public function generateAgenda($filename, $fileSearch, $agence)
  1924. {
  1925. $agendas = $this->entityManager->getRepository(Agenda::class)->findBy([
  1926. "agence" => $agence
  1927. ]) ;
  1928. $badgeColor = "";
  1929. // Statut de l'agenda sur evènement et rendez-vous
  1930. // - En cours : 1
  1931. // - Terminé : 0
  1932. $elements = [] ;
  1933. $elemAgendas = [] ;
  1934. foreach ($agendas as $agenda) {
  1935. $element = [] ;
  1936. $element["date"] = $agenda->getDate()->format('Y-m-d') ;
  1937. $refType = $agenda->getType()->getReference() ;
  1938. $element["typeAgenda"] = $refType ;
  1939. $element["mois"] = intval($agenda->getDate()->format('m')) ;
  1940. $element["annee"] = intval($agenda->getDate()->format('Y')) ;
  1941. $markup = '' ;
  1942. $statut = $agenda->isStatut() ;
  1943. $icone = $refType == "EVT" ? "fa-star" : "fa-clock" ;
  1944. // Déterminer la couleur du badge selon l'état
  1945. $badgeColor = "bg-warning"; // Couleur par défaut ou si état est null
  1946. $etat = $agenda->getEtat();
  1947. if ($etat === Agenda::ETAT_ANNULE) {
  1948. $badgeColor = "bg-danger";
  1949. } elseif ($etat === Agenda::ETAT_VALIDE) {
  1950. $badgeColor = "bg-success";
  1951. } elseif ($etat === Agenda::ETAT_REPORTE) {
  1952. $badgeColor = "bg-primary";
  1953. }
  1954. if($statut)
  1955. {
  1956. $markup = "<span class=\"badge $badgeColor m-1 font-smaller p-1 text-white\"><i class=\"fa $icone\"></i></span>" ;
  1957. }
  1958. else
  1959. {
  1960. $markup = "<span class=\"badge $badgeColor m-1 font-smaller p-1 text-white\"><i class=\"fa $icone\"></i></span>" ;
  1961. }
  1962. $element["markup"] = $markup ;
  1963. if(!isset($elemAgendas[$element["date"]][$element["typeAgenda"]]))
  1964. {
  1965. $elemAgendas[$element["date"]][$element["typeAgenda"]]["markup"] = "<span class=\"badge $badgeColor my-1 font-smaller p-1 text-white\"><i class=\"fa $icone\"></i></span>" ;
  1966. $elemAgendas[$element["date"]][$element["typeAgenda"]]["nbLigne"] = 1 ;
  1967. }
  1968. else
  1969. {
  1970. $elemAgendas[$element["date"]][$element["typeAgenda"]]["nbLigne"] += 1 ;
  1971. }
  1972. array_push($elements,$element) ;
  1973. }
  1974. // AGENDA FINANCIERE : CREDIT
  1975. $refCategorie = "CRD" ;
  1976. $categorie = $this->entityManager->getRepository(AgdCategorie::class)->findOneBy([
  1977. "reference" => $refCategorie
  1978. ]) ;
  1979. $echeances = $this->entityManager->getRepository(AgdEcheance::class)->findBy([
  1980. "agence" => $this->agence,
  1981. "categorie" => $categorie
  1982. ]) ;
  1983. foreach ($echeances as $echeance) {
  1984. $element = [] ;
  1985. $element["date"] = $echeance->getDate()->format('Y-m-d') ;
  1986. $element["typeAgenda"] = "FNC" ;
  1987. $element["mois"] = intval($echeance->getDate()->format('m')) ;
  1988. $element["annee"] = intval($echeance->getDate()->format('Y')) ;
  1989. $markup = '' ;
  1990. // Tous les statut sont :
  1991. // - En cours : 1
  1992. // - Soldé : 0
  1993. // - En souffrance : NULL
  1994. $statutEcheance = $echeance->isStatut() ;
  1995. if($statutEcheance)
  1996. {
  1997. $markup = "<span class=\"badge bg-info m-1 font-smaller p-1 text-white\"><i class=\"fa fa-percent\"></i></span>" ;
  1998. }
  1999. else if(is_null($statutEcheance))
  2000. {
  2001. $markup = "<span class=\"badge bg-danger m-1 font-smaller p-1 text-white\"><i class=\"fa fa-percent\"></i></span>" ;
  2002. }
  2003. else
  2004. {
  2005. $markup = "<span class=\"badge bg-dark m-1 font-smaller p-1 text-white\"><i class=\"fa fa-percent\"></i></span>" ;
  2006. }
  2007. $element["markup"] = $markup ;
  2008. if(!isset($elemAgendas[$element["date"]][$element["typeAgenda"]]))
  2009. {
  2010. $elemAgendas[$element["date"]][$element["typeAgenda"]]["markup"] = "<span class=\"badge $badgeColor my-1 font-smaller p-1 text-white\"><i class=\"fa fa-percent\"></i></span>" ;
  2011. $elemAgendas[$element["date"]][$element["typeAgenda"]]["nbLigne"] = 1 ;
  2012. }
  2013. else
  2014. {
  2015. $elemAgendas[$element["date"]][$element["typeAgenda"]]["nbLigne"] += 1 ;
  2016. }
  2017. array_push($elements,$element) ;
  2018. }
  2019. // GESTION DE L'ACOMPTE SUR L'AGENDA
  2020. $agendaAcomptes = $this->entityManager->getRepository(AgdAcompte::class)->findBy([
  2021. "agence" => $agence
  2022. ]) ;
  2023. foreach ($agendaAcomptes as $agendaAcompte) {
  2024. $element = [] ;
  2025. $element["date"] = $agendaAcompte->getDate()->format('Y-m-d') ;
  2026. $element["typeAgenda"] = "FNC" ;
  2027. $element["mois"] = intval($agendaAcompte->getDate()->format('m')) ;
  2028. $element["annee"] = intval($agendaAcompte->getDate()->format('Y')) ;
  2029. $markup = '' ;
  2030. // Tous les statut sont :
  2031. // - En cours : 1
  2032. // - Soldé : 0
  2033. // - En souffrance : NULL
  2034. $statutAgdAcompte = $agendaAcompte->isStatut() ;
  2035. if($statutAgdAcompte)
  2036. {
  2037. $markup = "<span class=\"badge bg-info m-1 font-smaller p-1 text-white\"><i class=\"fa fa-layer-group\"></i></span>" ;
  2038. }
  2039. else if(is_null($statutAgdAcompte))
  2040. {
  2041. $markup = "<span class=\"badge bg-danger m-1 font-smaller p-1 text-white\"><i class=\"fa fa-layer-group\"></i></span>" ;
  2042. }
  2043. else
  2044. {
  2045. $markup = "<span class=\"badge bg-dark m-1 font-smaller p-1 text-white\"><i class=\"fa fa-layer-group\"></i></span>" ;
  2046. }
  2047. $element["markup"] = $markup ;
  2048. if(!isset($elemAgendas[$element["date"]][$element["typeAgenda"]]))
  2049. {
  2050. $elemAgendas[$element["date"]][$element["typeAgenda"]]["markup"] = "<span class=\"badge $badgeColor my-1 font-smaller p-1 text-white\"><i class=\"fa fa-layer-group\"></i></span>" ;
  2051. $elemAgendas[$element["date"]][$element["typeAgenda"]]["nbLigne"] = 1 ;
  2052. }
  2053. else
  2054. {
  2055. $elemAgendas[$element["date"]][$element["typeAgenda"]]["nbLigne"] += 1 ;
  2056. }
  2057. array_push($elements,$element) ;
  2058. }
  2059. // DEBUT BON DE LIVRAISON
  2060. $agdLivraisons = $this->entityManager->getRepository(AgdLivraison::class)->findBy([
  2061. "agence" => $agence
  2062. ]) ;
  2063. foreach ($agdLivraisons as $agdLivraison) {
  2064. $element = [] ;
  2065. $element["date"] = $agdLivraison->getDate()->format('Y-m-d') ;
  2066. $element["typeAgenda"] = "LVR" ;
  2067. $element["mois"] = intval($agdLivraison->getDate()->format('m')) ;
  2068. $element["annee"] = intval($agdLivraison->getDate()->format('Y')) ;
  2069. $markup = '' ;
  2070. // Tous les statut sont :
  2071. // - En cours : 1
  2072. // - Soldé : 0
  2073. // - En souffrance : NULL
  2074. $statutAgdLvr = $agdLivraison->isStatut() ;
  2075. if($statutAgdLvr)
  2076. {
  2077. $markup = "<span class=\"badge bg-info m-1 font-smaller p-1 text-white\"><i class=\"fa fa-truck\"></i></span>" ;
  2078. }
  2079. else
  2080. {
  2081. $markup = "<span class=\"badge bg-dark m-1 font-smaller p-1 text-white\"><i class=\"fa fa-truck\"></i></span>" ;
  2082. }
  2083. $element["markup"] = $markup ;
  2084. if(!isset($elemAgendas[$element["date"]][$element["typeAgenda"]]))
  2085. {
  2086. $elemAgendas[$element["date"]][$element["typeAgenda"]]["markup"] = "<span class=\"badge $badgeColor my-1 font-smaller p-1 text-white\"><i class=\"fa fa-truck\"></i></span>" ;
  2087. $elemAgendas[$element["date"]][$element["typeAgenda"]]["nbLigne"] = 1 ;
  2088. }
  2089. else
  2090. {
  2091. $elemAgendas[$element["date"]][$element["typeAgenda"]]["nbLigne"] += 1 ;
  2092. }
  2093. array_push($elements,$element) ;
  2094. }
  2095. // FIN BON DE LIVRAISON
  2096. // DEBUT CONTRATS DE LOCATION
  2097. // Récupération des contrats de location
  2098. $locContrats = $this->entityManager->getRepository(LocContrat::class)->findBy([
  2099. "agence" => $agence,
  2100. // "statut" => LocContrat::STATUT_EN_COURS
  2101. ]);
  2102. foreach ($locContrats as $locContrat) {
  2103. $facture = $locContrat->getFacture();
  2104. // Si le contrat a une facture, utiliser la date de fin de la facture
  2105. if ($facture && $facture->getDateFin()) {
  2106. $dateFin = $facture->getDateFin();
  2107. // dd($dateFin,new \DateTime());
  2108. // Si la date est déjà passée, ignorer
  2109. // if ($dateFin < new \DateTime()) {
  2110. // continue;
  2111. // }
  2112. $element = [];
  2113. $element["date"] = $dateFin->format('Y-m-d');
  2114. $element["typeAgenda"] = "CTR"; // Type agenda pour contrat - valeur unique pour éviter les collisions
  2115. $element["mois"] = intval($dateFin->format('m'));
  2116. $element["annee"] = intval($dateFin->format('Y'));
  2117. // Définir l'apparence en fonction du statut du contrat et de la date
  2118. $icone = "fa-file-contract";
  2119. // Vérifier d'abord si la date d'échéance est passée
  2120. if ($dateFin < new \DateTime()) {
  2121. $badgeColor = "bg-dark"; // Noir pour les contrats dont la date d'échéance est passée
  2122. }
  2123. // Sinon, changer la couleur selon le statut du contrat
  2124. else if ($locContrat->getStatut() === LocContrat::STATUT_TERMINE) {
  2125. $badgeColor = "bg-success"; // Vert pour les contrats terminés
  2126. } elseif ($locContrat->getStatut() === LocContrat::STATUT_ANNULE) {
  2127. $badgeColor = "bg-danger"; // Rouge pour les contrats annulés
  2128. } else {
  2129. $badgeColor = "bg-warning"; // Orange/jaune pour les contrats en cours
  2130. }
  2131. $markup = "<span class=\"badge $badgeColor m-1 font-smaller p-1 text-white\"><i class=\"fa $icone\"></i></span>";
  2132. $element["markup"] = $markup;
  2133. // S'assurer que les contrats sont toujours visibles en leur donnant une clé distincte
  2134. // qui ne sera pas confondue avec les autres types d'événements
  2135. $typeAgendaCtr = "CTR" . count($elemAgendas[$element["date"]] ?? []); // Ajouter un suffixe unique
  2136. $elemAgendas[$element["date"]][$typeAgendaCtr] = [
  2137. "markup" => "<span class=\"badge $badgeColor my-1 font-smaller p-1 text-white\"><i class=\"fa $icone\"></i></span>",
  2138. "nbLigne" => 1,
  2139. "statut" => $locContrat->getStatut() // Stocker le statut pour référence
  2140. ];
  2141. array_push($elements, $element);
  2142. }
  2143. }
  2144. // dd($elements);
  2145. // FIN CONTRATS DE LOCATION
  2146. file_put_contents($fileSearch,json_encode($elements)) ;
  2147. $items = $elements ;
  2148. $agendaResult = [] ;
  2149. foreach($elemAgendas as $key => $value)
  2150. {
  2151. $itemAgenda = '' ;
  2152. $value = array_values($value) ;
  2153. for($i=0;$i<count($value);$i++)
  2154. {
  2155. $itemAgenda .= "<div class=\"d-flex w-100 flex-column mx-1 align-items-center justify-content-center\">
  2156. ".$value[$i]["markup"]."
  2157. (".$value[$i]["nbLigne"].")
  2158. </div>";
  2159. }
  2160. $margedMarkup = "<div class=\"d-flex w-100 flex-column align-items-center justify-content-center\">
  2161. <b>[day]</b>
  2162. <div class=\"d-flex w-100 flex-row align-items-center justify-content-center\">
  2163. ".$itemAgenda."
  2164. </div>
  2165. </div>" ;
  2166. $agendaResult[] = [
  2167. "date" => $key,
  2168. "markup" => $margedMarkup
  2169. ] ;
  2170. }
  2171. file_put_contents($filename,json_encode($agendaResult)) ;
  2172. }
  2173. public function generatePrestBatiment($filename,$agence)
  2174. {
  2175. $elements = $this->entityManager->getRepository(BtpElement::class)->findBy([
  2176. "statut" => True,
  2177. "agence" => $agence
  2178. ]) ;
  2179. $items = [] ;
  2180. foreach ($elements as $element) {
  2181. $item = [] ;
  2182. $item["id"] = $element->getId() ;
  2183. $item["agence"] = $element->getAgence()->getId() ;
  2184. $item["designation"] = $element->getNom() ;
  2185. $item["mesure"] = is_null($element->getMesure()) ? "-" : $element->getMesure()->getNotation() ;
  2186. array_push($items,$item) ;
  2187. }
  2188. file_put_contents($filename,json_encode($items)) ;
  2189. }
  2190. public function generateEnonceePrestBatiment($filename,$agence)
  2191. {
  2192. $enoncees = $this->entityManager->getRepository(BtpEnoncee::class)->findBy([
  2193. "statut" => True,
  2194. "agence" => $agence
  2195. ]) ;
  2196. $items = [] ;
  2197. foreach ($enoncees as $enoncee) {
  2198. $item = [] ;
  2199. $item["id"] = $enoncee->getId() ;
  2200. $item["agence"] = $enoncee->getAgence()->getId() ;
  2201. $item["nom"] = $enoncee->getNom() ;
  2202. array_push($items,$item) ;
  2203. }
  2204. file_put_contents($filename,json_encode($items)) ;
  2205. }
  2206. public function generateLocationBailleur($filename, $agence)
  2207. {
  2208. $bailleurs = $this->entityManager->getRepository(LctBailleur::class)->findBy([
  2209. "statut" => True,
  2210. "agence" => $agence
  2211. ]) ;
  2212. $items = [] ;
  2213. foreach ($bailleurs as $bailleur) {
  2214. $item = [] ;
  2215. $item["id"] = $bailleur->getId() ;
  2216. $item["agence"] = $bailleur->getAgence()->getId() ;
  2217. $item["nom"] = $bailleur->getNom() ;
  2218. $item["telephone"] = $bailleur->getTelephone() ;
  2219. $item["adresse"] = $bailleur->getAdresse() ;
  2220. array_push($items,$item) ;
  2221. }
  2222. file_put_contents($filename,json_encode($items)) ;
  2223. }
  2224. public function generateLocationLocataire($filename, $agence)
  2225. {
  2226. $locataires = $this->entityManager->getRepository(LctLocataire::class)->findBy([
  2227. "statut" => True,
  2228. "agence" => $agence
  2229. ]) ;
  2230. $items = [] ;
  2231. foreach ($locataires as $locataire) {
  2232. $item = [] ;
  2233. $item["id"] = $locataire->getId() ;
  2234. $item["agence"] = $locataire->getAgence()->getId() ;
  2235. $item["nom"] = $locataire->getNom() ;
  2236. $item["telephone"] = $locataire->getTelephone() ;
  2237. $item["adresse"] = $locataire->getAdresse() ;
  2238. $item["email"] = $locataire->getEmail() ;
  2239. array_push($items,$item) ;
  2240. }
  2241. file_put_contents($filename,json_encode($items)) ;
  2242. }
  2243. public function generateLocationContrat($filename, $agence)
  2244. {
  2245. $contrats = $this->entityManager->getRepository(LctContrat::class)->findBy([
  2246. "agence" => $agence,
  2247. "statutGen" => True,
  2248. ]) ;
  2249. $items = [] ;
  2250. foreach ($contrats as $contrat) {
  2251. $item = [] ;
  2252. if($contrat->getPeriode()->getReference() == "J")
  2253. {
  2254. $periode = "Jour(s)" ;
  2255. }
  2256. if($contrat->getPeriode()->getReference() == "M")
  2257. {
  2258. $periode = "Mois" ;
  2259. }
  2260. else if($contrat->getPeriode()->getReference() == "A")
  2261. {
  2262. $periode = "An(s)" ;
  2263. }
  2264. $item["id"] = $contrat->getId() ;
  2265. $item["encodedId"] = $this->encodeChiffre($contrat->getId()) ;
  2266. $item["agence"] = $contrat->getAgence()->getId() ;
  2267. $item["numContrat"] = $contrat->getNumContrat() ;
  2268. $item["dateContrat"] = $contrat->getDateContrat()->format("d/m/Y") ;
  2269. $item["bailleur"] = $contrat->getBailleur()->getNom() ;
  2270. $item["bailleurId"] = $contrat->getBailleur()->getId() ;
  2271. $item["bail"] = $contrat->getBail()->getNom() ;
  2272. $item["bailId"] = $contrat->getBail()->getId() ;
  2273. $item["locataire"] = $contrat->getLocataire()->getNom() ;
  2274. $item["locataireId"] = $contrat->getLocataire()->getId() ;
  2275. $item["cycle"] = $contrat->getCycle()->getNom() ;
  2276. $item["dateDebut"] = $contrat->getDateDebut()->format("d/m/Y") ;
  2277. $item["dateFin"] = $contrat->getDateFin()->format("d/m/Y") ;
  2278. $item["frequence"] = is_null($contrat->getFrequenceRenouv()) ? "Aucun" : $contrat->getFrequenceRenouv()-1;
  2279. $item["dureeContrat"] = $contrat->getDuree()." ".$periode ;
  2280. $item["montantContrat"] = $contrat->getMontantContrat() ;
  2281. $item["statut"] = $contrat->getStatut()->getNom() ;
  2282. $item["refStatut"] = $contrat->getStatut()->getReference() ;
  2283. array_push($items,$item) ;
  2284. }
  2285. file_put_contents($filename,json_encode($items)) ;
  2286. }
  2287. public function generateLctCommisionContrat($filename, $agence)
  2288. {
  2289. $contrats = $this->entityManager->getRepository(LctContrat::class)->findBy([
  2290. "agence" => $agence,
  2291. "statutGen" => True,
  2292. ]) ;
  2293. $tabContrats = [] ;
  2294. foreach ($contrats as $contrat) {
  2295. if((is_null($contrat->getPourcentage()) || empty($contrat->getPourcentage())) || $contrat->getStatut()->getReference() != "ENCR")
  2296. continue ;
  2297. if($contrat->getForfait()->getReference() == "FORFAIT")
  2298. {
  2299. if($contrat->getPeriode()->getReference() == "J")
  2300. {
  2301. $periode = " Jour(s)" ;
  2302. }
  2303. if($contrat->getPeriode()->getReference() == "M")
  2304. {
  2305. $periode = " Mois" ;
  2306. }
  2307. else if($contrat->getPeriode()->getReference() == "A")
  2308. {
  2309. $periode = " An(s)" ;
  2310. }
  2311. $lastRecordPaiement = $this->entityManager->getRepository(LctPaiement::class)->findOneBy(["contrat" => $contrat], ['id' => 'DESC']);
  2312. $datePaiement = !is_null($lastRecordPaiement) ? ($lastRecordPaiement->getDate()->format("d/m/Y")) : "-" ;
  2313. $elemC = [] ;
  2314. $elemC["id"] = $contrat->getId() ;
  2315. $elemC["numContrat"] = $contrat->getNumContrat() ;
  2316. $elemC["bail"] = $contrat->getBail()->getNom()." | ".$contrat->getBail()->getLieux() ;
  2317. $elemC["bailId"] = $contrat->getBail()->getId() ;
  2318. $elemC["locataire"] = $contrat->getLocataire()->getNom() ;
  2319. $elemC["locataireId"] = $contrat->getLocataire()->getId() ;
  2320. $elemC["cycle"] = $contrat->getCycle()->getNom() ;
  2321. $elemC["duree"] = $contrat->getDuree().$periode ;
  2322. $elemC["datePaiement"] = $datePaiement ;
  2323. $elemC["commission"] = ($contrat->getMontantContrat() * $contrat->getPourcentage()) / 100;
  2324. array_push($tabContrats,$elemC) ;
  2325. continue ;
  2326. }
  2327. $repartitions = $this->entityManager->getRepository(LctRepartition::class)->findBy([
  2328. "contrat" => $contrat
  2329. ]) ;
  2330. $childs = [] ;
  2331. $totalReleve = 0 ;
  2332. foreach ($repartitions as $repartition) {
  2333. $item = [] ;
  2334. $statutRepart = $repartition->getStatut()->getReference() ;
  2335. if($statutRepart == "CAUTION")
  2336. continue ;
  2337. $item["dateDebut"] = is_null($repartition->getDateDebut()) ? "NONE" : $repartition->getDateDebut()->format("d/m/Y") ;
  2338. $item["montant"] = $repartition->getMontant() ;
  2339. $item["statut"] = $repartition->getStatut()->getReference() ;
  2340. $totalReleve += $repartition->getMontant() ;
  2341. array_push($childs,$item) ;
  2342. }
  2343. $resultat = array_reduce($childs, function($carry, $contenu) {
  2344. $dateDebut = $contenu['dateDebut'];
  2345. if (!isset($carry[$dateDebut])) {
  2346. $carry[$dateDebut] = $contenu;
  2347. } else {
  2348. $carry[$dateDebut]['montant'] += $contenu['montant'];
  2349. }
  2350. return $carry;
  2351. }, []);
  2352. $childs = array_values($resultat);
  2353. $newChilds = [] ;
  2354. foreach ($childs as $child) {
  2355. $elem = [] ;
  2356. $elem["dateDebut"] = $child["dateDebut"] ;
  2357. $elem["montant"] = $child["montant"] ;
  2358. if($child["montant"] == $contrat->getMontantForfait())
  2359. {
  2360. array_push($newChilds,$elem) ;
  2361. }
  2362. }
  2363. $commission = 0 ;
  2364. foreach ($newChilds as $newChild) {
  2365. $commission += ($newChild["montant"] * $contrat->getPourcentage()) / 100 ;
  2366. }
  2367. if($contrat->getPeriode()->getReference() == "J")
  2368. {
  2369. $periode = " Jour(s)" ;
  2370. }
  2371. if($contrat->getPeriode()->getReference() == "M")
  2372. {
  2373. $periode = " Mois" ;
  2374. }
  2375. else if($contrat->getPeriode()->getReference() == "A")
  2376. {
  2377. $periode = " An(s)" ;
  2378. }
  2379. $lastRecordPaiement = $this->entityManager->getRepository(LctPaiement::class)->findOneBy(["contrat" => $contrat], ['id' => 'DESC']);
  2380. $datePaiement = !is_null($lastRecordPaiement) ? ($lastRecordPaiement->getDate()->format("d/m/Y")) : "-" ;
  2381. $elemC = [] ;
  2382. $elemC["id"] = $contrat->getId() ;
  2383. $elemC["numContrat"] = $contrat->getNumContrat() ;
  2384. $elemC["bail"] = $contrat->getBail()->getNom()." | ".$contrat->getBail()->getLieux() ;
  2385. $elemC["bailId"] = $contrat->getBail()->getId() ;
  2386. $elemC["locataire"] = $contrat->getLocataire()->getNom() ;
  2387. $elemC["locataireId"] = $contrat->getLocataire()->getId() ;
  2388. $elemC["cycle"] = $contrat->getCycle()->getNom() ;
  2389. $elemC["duree"] = $contrat->getDuree().$periode ;
  2390. $elemC["datePaiement"] = $datePaiement ;
  2391. $elemC["commission"] = $commission ;
  2392. array_push($tabContrats,$elemC) ;
  2393. }
  2394. file_put_contents($filename,json_encode($tabContrats)) ;
  2395. }
  2396. public function generateLocationBails($filename, $agence)
  2397. {
  2398. $bailleurs = $this->entityManager->getRepository(LctBailleur::class)->findBy([
  2399. "agence" => $agence,
  2400. "statut" => True,
  2401. ]) ;
  2402. $tabBails = [] ;
  2403. foreach ($bailleurs as $bailleur) {
  2404. $bails = $this->entityManager->getRepository(LctBail::class)->findBy([
  2405. "bailleur" => $bailleur,
  2406. "statut" => True,
  2407. ]) ;
  2408. if(is_null($bails))
  2409. continue ;
  2410. foreach($bails as $bail) {
  2411. $myitem = [] ;
  2412. $myitem["id"] = $bail->getId() ;
  2413. $myitem["nom"] = $bail->getNom() ;
  2414. $myitem["adresse"] = $bail->getLieux() ;
  2415. array_push($tabBails,$myitem) ;
  2416. }
  2417. }
  2418. file_put_contents($filename,json_encode($tabBails)) ;
  2419. }
  2420. public function generateCmpBanque($filename, $agence)
  2421. {
  2422. $banques = $this->entityManager->getRepository(CmpBanque::class)->findBy([
  2423. "agence" => $agence,
  2424. "statut" => True,
  2425. ]) ;
  2426. $items = [] ;
  2427. foreach ($banques as $banque) {
  2428. $item = [] ;
  2429. $item["id"] = $banque->getId() ;
  2430. $item["agence"] = $banque->getAgence()->getId() ;
  2431. $item["nom"] = $banque->getNom() ;
  2432. array_push($items,$item) ;
  2433. }
  2434. file_put_contents($filename,json_encode($items)) ;
  2435. }
  2436. public function generateCmpCompte($filename, $agence)
  2437. {
  2438. $comptes = $this->entityManager->getRepository(CmpCompte::class)->findBy([
  2439. "agence" => $agence,
  2440. "statut" => True,
  2441. ]) ;
  2442. $items = [] ;
  2443. foreach ($comptes as $compte) {
  2444. $item = [] ;
  2445. $item["id"] = $compte->getId() ;
  2446. $item["agence"] = $compte->getAgence()->getId() ;
  2447. $item["banque"] = $compte->getBanque()->getNom() ;
  2448. $item["numero"] = $compte->getNumero() ;
  2449. $item["solde"] = $compte->getSolde() ;
  2450. array_push($items,$item) ;
  2451. }
  2452. file_put_contents($filename,json_encode($items)) ;
  2453. }
  2454. public function generateCmpOperation($filename, $agence)
  2455. {
  2456. $operations = $this->entityManager->getRepository(CmpOperation::class)->findBy([
  2457. "agence" => $agence,
  2458. "statut" => True,
  2459. ],["date" => "DESC"]) ;
  2460. $items = [] ;
  2461. foreach ($operations as $operation) {
  2462. $item = [] ;
  2463. $item["id"] = $operation->getId() ;
  2464. $item["agence"] = $operation->getAgence()->getId() ;
  2465. $item["banque"] = $operation->getBanque()->getNom() ;
  2466. $item["idBanque"] = $operation->getBanque()->getId() ;
  2467. $item["compte"] = $operation->getCompte()->getNumero() ;
  2468. $item["dur-compte"] = $operation->getCompte()->getNumero() ;
  2469. $item["categorie"] = $operation->getCategorie()->getNom() ;
  2470. $item["idCategorie"] = $operation->getCategorie()->getId() ;
  2471. $item["refCategorie"] = $operation->getCategorie()->getReference() ;
  2472. $item["type"] = $operation->getType()->getNom() ;
  2473. $item["toCheque"] = is_null($operation->getCheque()) ? False : True ;
  2474. $item["numeroMode"] = is_null($operation->getNumeroMode()) ? "-" : $operation->getNumeroMode() ;
  2475. $item["editeurMode"] = is_null($operation->getEditeurMode()) ? "-" : $operation->getEditeurMode() ;
  2476. $item["numero"] = $operation->getNumero() ;
  2477. $item["montant"] = $operation->getMontant() ;
  2478. $item["personne"] = $operation->getPersonne() ;
  2479. $item["dur-personne"] = $operation->getPersonne() ;
  2480. $item["date"] = $operation->getDate()->format("d/m/Y") ;
  2481. $item["currentDate"] = $operation->getDate()->format("d/m/Y") ;
  2482. $item["dateDeclaration"] = $operation->getDate()->format("d/m/Y") ;
  2483. $item["dateDebut"] = $operation->getDate()->format("d/m/Y") ;
  2484. $item["dateFin"] = $operation->getDate()->format("d/m/Y") ;
  2485. $item["annee"] = $operation->getDate()->format("Y") ;
  2486. $item["mois"] = $operation->getDate()->format("m") ;
  2487. array_push($items,$item) ;
  2488. }
  2489. file_put_contents($filename,json_encode($items)) ;
  2490. }
  2491. public function synchroCompteBancaire(CmpCompte $compte)
  2492. {
  2493. $catDepot = $this->entityManager->getRepository(CmpCategorie::class)->findOneBy([
  2494. "reference" => "DEP"
  2495. ]) ;
  2496. $catRetrait = $this->entityManager->getRepository(CmpCategorie::class)->findOneBy([
  2497. "reference" => "RET"
  2498. ]) ;
  2499. $sommeDepot = $this->entityManager->getRepository(CmpOperation::class)->getSommeOperation($catDepot->getId(), $compte->getId()) ;
  2500. $sommeRetrait = $this->entityManager->getRepository(CmpOperation::class)->getSommeOperation($catRetrait->getId(), $compte->getId()) ;
  2501. $compte->setSolde($sommeDepot[0]["montant"] - $sommeRetrait[0]["montant"]) ;
  2502. $this->entityManager->flush() ;
  2503. }
  2504. public function generateAchMarchandise($filename, $agence)
  2505. {
  2506. $marchandises = $this->entityManager->getRepository(AchMarchandise::class)->findBy([
  2507. "agence" => $agence,
  2508. "statutGen" => True,
  2509. ]) ;
  2510. $items = [] ;
  2511. foreach ($marchandises as $marchandise) {
  2512. $item = [] ;
  2513. $item["id"] = $marchandise->getId() ;
  2514. $item["agence"] = $marchandise->getAgence()->getId() ;
  2515. $item["designation"] = $marchandise->getDesignation() ;
  2516. $item["prix"] = $marchandise->getPrix();
  2517. array_push($items,$item) ;
  2518. }
  2519. file_put_contents($filename,json_encode($items)) ;
  2520. }
  2521. public function generateCltClient($filename, $agence)
  2522. {
  2523. $histoClients = $this->entityManager->getRepository(CltHistoClient::class)->findBy([
  2524. "agence" => $agence,
  2525. "statut" => True,
  2526. ]) ;
  2527. $items = [] ;
  2528. foreach ($histoClients as $histoClient) {
  2529. $item = [] ;
  2530. $item["id"] = $histoClient->getId() ;
  2531. $item["encodedId"] = $this->encodeChiffre($histoClient->getId()) ;
  2532. $item["agence"] = $histoClient->getAgence()->getId() ;
  2533. $item["numClient"] = str_pad($histoClient->getId(), 4, "0", STR_PAD_LEFT) ;
  2534. $item["nom"] = is_null($histoClient->getClient()) ? $histoClient->getSociete()->getNom() : $histoClient->getClient()->getNom();
  2535. $item["type"] = $histoClient->getType()->getNom() ;
  2536. $item["idType"] = $histoClient->getType()->getId() ;
  2537. $item["adresse"] = is_null($histoClient->getClient()) ? $histoClient->getSociete()->getAdresse() : $histoClient->getClient()->getAdresse();
  2538. $item["telephone"] = is_null($histoClient->getClient()) ? $histoClient->getSociete()->getTelFixe() : $histoClient->getClient()->getTelephone();
  2539. array_push($items,$item) ;
  2540. }
  2541. file_put_contents($filename,json_encode($items)) ;
  2542. }
  2543. public function generateChkCheque($filename,$agence)
  2544. {
  2545. $cheques = $this->entityManager->getRepository(ChkCheque::class)->findBy([
  2546. "agence" => $agence,
  2547. "statutGen" => True,
  2548. ]) ;
  2549. $items = [] ;
  2550. foreach ($cheques as $cheque) {
  2551. $item = [] ;
  2552. $item["id"] = $cheque->getId() ;
  2553. $item["encodedId"] = $this->encodeChiffre($cheque->getId()) ;
  2554. $item["agence"] = $cheque->getAgence()->getId() ;
  2555. $item["nomChequier"] = $cheque->getNomChequier() ;
  2556. $item["banque"] = $cheque->getBanque()->getNom() ;
  2557. $item["banqueId"] = $cheque->getBanque()->getId() ;
  2558. $item["type"] = $cheque->getType()->getNom() ;
  2559. $item["idType"] = $cheque->getType()->getId() ;
  2560. $item["dateCheque"] = $cheque->getDateCheque()->format("d/m/Y") ;
  2561. $item["numCheque"] = $cheque->getNumCheque() ;
  2562. $item["date"] = $cheque->getDateDeclaration()->format("d/m/Y") ;
  2563. $item["currentDate"] = $cheque->getDateDeclaration()->format("d/m/Y") ;
  2564. $item["dateDeclaration"] = $cheque->getDateDeclaration()->format("d/m/Y") ;
  2565. $item["dateDebut"] = $cheque->getDateDeclaration()->format("d/m/Y") ;
  2566. $item["dateFin"] = $cheque->getDateDeclaration()->format("d/m/Y") ;
  2567. $item["annee"] = $cheque->getDateDeclaration()->format("Y") ;
  2568. $item["mois"] = $cheque->getDateDeclaration()->format("m") ;
  2569. $item["montant"] = $cheque->getMontant() ;
  2570. $item["statut"] = $cheque->getStatut()->getNom() ;
  2571. $item["refStatut"] = $cheque->getStatut()->getReference() ;
  2572. array_push($items,$item) ;
  2573. }
  2574. file_put_contents($filename,json_encode($items)) ;
  2575. }
  2576. public function generateDepListeDepense($filename, $agence)
  2577. {
  2578. $depenses = $this->entityManager->getRepository(Depense::class)->findBy([
  2579. "agence" => $agence,
  2580. "statutGen" => True,
  2581. ],
  2582. [
  2583. "moisFacture" => "ASC",
  2584. "anneeFacture" => "ASC",
  2585. ]) ;
  2586. $items = [] ;
  2587. foreach ($depenses as $depense) {
  2588. $item = [] ;
  2589. $item["id"] = $depense->getId() ;
  2590. $item["encodedId"] = $this->encodeChiffre($depense->getId()) ;
  2591. $item["agence"] = $depense->getAgence()->getId() ;
  2592. $item["dateDeclaration"] = $depense->getDateDeclaration()->format("d/m/Y") ;
  2593. $item["date"] = str_pad($depense->getMoisFacture(), 2, "0", STR_PAD_LEFT)."/".$depense->getAnneeFacture() ;
  2594. $item["element"] = $depense->getElement() ;
  2595. $item["dur-element"] = $depense->getElement() ;
  2596. $item["beneficiaire"] = $depense->getNomConcerne() ;
  2597. $item["dur-beneficiaire"] = $depense->getNomConcerne() ;
  2598. $item["numFacture"] = $depense->getNumFacture() ;
  2599. $item["moisFacture"] = $depense->getMoisFacture() ;
  2600. $item["anneeFacture"] = $depense->getAnneeFacture() ;
  2601. $item["currentDate"] = $depense->getDateDeclaration()->format("d/m/Y") ;
  2602. $item["dateDebut"] = $depense->getDateDeclaration()->format("d/m/Y") ;
  2603. $item["dateFin"] = $depense->getDateDeclaration()->format("d/m/Y") ;
  2604. $item["moisDepense"] = $depense->getDateDeclaration()->format("m") ;
  2605. $item["anneeDepense"] = $depense->getDateDeclaration()->format("Y") ;
  2606. $item["service"] = $depense->getService()->getNom() ;
  2607. $item["idService"] = $depense->getService()->getId() ;
  2608. $item["motif"] = $depense->getMotif()->getNom() ;
  2609. $item["refMotif"] = $depense->getMotif()->getReference() ;
  2610. $item["modePaiement"] = $depense->getModePaiement()->getNom() ;
  2611. $item["refMode"] = $depense->getModePaiement()->getReference() ;
  2612. $item["montant"] = $depense->getMontantDep();
  2613. $item["statut"] = $depense->getStatut()->getNom();
  2614. array_push($items,$item) ;
  2615. }
  2616. usort($items, [self::class, 'comparaisonDates']);
  2617. file_put_contents($filename,json_encode($items)) ;
  2618. }
  2619. public static function comparaisonCommandeAchat($a, $b) {
  2620. // Comparaison par date
  2621. $dateA = \DateTime::createFromFormat('d/m/Y', $a['date']);
  2622. $dateB = \DateTime::createFromFormat('d/m/Y', $b['date']);
  2623. $result = $dateB <=> $dateA ;
  2624. if ($result !== 0) {
  2625. return $result;
  2626. }
  2627. // Comparaison par numero
  2628. return intval($a['numero']) <=> intval($b['numero']) ;
  2629. }
  2630. public function generateAchListBonCommande($filename, $agence)
  2631. {
  2632. $bonCommandes = $this->entityManager->getRepository(AchBonCommande::class)->findBy([
  2633. "agence" => $agence,
  2634. "statutGen" => True
  2635. ]) ;
  2636. $elements = [] ;
  2637. foreach ($bonCommandes as $bonCommande) {
  2638. $achatDetails = $this->entityManager->getRepository(AchDetails::class)->findBy([
  2639. "statutGen" => True,
  2640. "bonCommande" => $bonCommande
  2641. ]) ;
  2642. $totalPaiement = $this->entityManager->getRepository(AchHistoPaiement::class)->getTotalPaiement($bonCommande->getId()) ;
  2643. foreach ($achatDetails as $achatDetail) {
  2644. $element = [] ;
  2645. $element["id"] = $bonCommande->getId() ;
  2646. $element["idDetail"] = $achatDetail->getId() ;
  2647. $element["encodedId"] = $this->encodeChiffre($bonCommande->getId()) ;
  2648. $element["agence"] = $bonCommande->getAgence()->getId() ;
  2649. $element["date"] = $bonCommande->getDate()->format('d/m/Y') ;
  2650. $element["lieu"] = $bonCommande->getLieu() ;
  2651. $element["fournisseur"] = $bonCommande->getFournisseur()->getNom() ;
  2652. $element["type"] = $bonCommande->getType()->getNom() ;
  2653. $element["refType"] = $bonCommande->getType()->getReference() ;
  2654. $element["description"] = $bonCommande->getDescription() ;
  2655. $element["numero"] = $bonCommande->getNumero() ;
  2656. $element["designation"] = $achatDetail->getDesignation() ;
  2657. $element["reference"] = is_null($achatDetail->getReference()) ? "" : $achatDetail->getReference() ;
  2658. $element["quantite"] = $achatDetail->getQuantite() ;
  2659. $element["prix"] = $achatDetail->getPrix() ;
  2660. $element["totalLigne"] = $achatDetail->getPrix() * $achatDetail->getQuantite() ;
  2661. $element["totalTtc"] = $bonCommande->getMontant() ;
  2662. $element["totalPaiement"] = is_null($totalPaiement["credit"]) ? 0 : $totalPaiement["credit"] ;
  2663. $element["statut"] = $achatDetail->getStatut()->getNom() ;
  2664. $element["refStatut"] = $achatDetail->getStatut()->getreference() ;
  2665. $element["statutBon"] = $bonCommande->getStatutBon()->getNom() ;
  2666. $element["refStatutBon"] = $bonCommande->getStatutBon()->getreference() ;
  2667. array_push($elements,$element) ;
  2668. }
  2669. }
  2670. usort($elements, [self::class, 'comparaisonCommandeAchat']);
  2671. file_put_contents($filename,json_encode($elements)) ;
  2672. }
  2673. public function generateAchCommande($filename, $agence)
  2674. {
  2675. $bonCommandes = $this->entityManager->getRepository(AchBonCommande::class)->findBy([
  2676. "agence" => $agence,
  2677. "statutGen" => True
  2678. ]) ;
  2679. $items = [] ;
  2680. foreach ($bonCommandes as $bonCommande) {
  2681. $item = [] ;
  2682. $item["id"] = $bonCommande->getId() ;
  2683. $item["agence"] = $bonCommande->getAgence()->getId() ;
  2684. $item["date"] = $bonCommande->getDate()->format("d/m/Y") ;
  2685. $item["montant"] = $bonCommande->getMontant();
  2686. $item["operation"] = "Achat";
  2687. $item["refOperation"] = "ACHAT" ;
  2688. $item["refJournal"] = "CREDIT" ;
  2689. array_push($items,$item) ;
  2690. }
  2691. file_put_contents($filename,json_encode($items)) ;
  2692. }
  2693. public function updateStatutFinance($finance)
  2694. {
  2695. $totalFacture = $finance->getFacture()->getTotal() ;
  2696. $totalPayee = $this->entityManager->getRepository(CrdDetails::class)->getFinanceTotalPayee($finance->getId()) ;
  2697. $paiement = $finance->getPaiement()->getReference() ;
  2698. if($totalFacture == $totalPayee["total"])
  2699. {
  2700. if($paiement == "CR")
  2701. $statut = "SLD" ;
  2702. else
  2703. $statut = "TRM" ;
  2704. $crdStatut = $this->entityManager->getRepository(CrdStatut::class)->findOneBy([
  2705. "reference" => $statut
  2706. ]) ;
  2707. $finance->setStatut($crdStatut) ;
  2708. $this->entityManager->flush() ;
  2709. }
  2710. else if($totalPayee["total"] < $totalFacture)
  2711. {
  2712. // Si le total payé est inférieur au total de la facture, remettre le statut à "ECR" (En cours)
  2713. $statutActuel = $finance->getStatut()->getReference() ;
  2714. // Ne changer que si le statut actuel est "SLD" (soldé) ou "TRM" (terminé)
  2715. if($statutActuel == "SLD" || $statutActuel == "TRM")
  2716. {
  2717. $crdStatut = $this->entityManager->getRepository(CrdStatut::class)->findOneBy([
  2718. "reference" => "ECR"
  2719. ]) ;
  2720. $finance->setStatut($crdStatut) ;
  2721. $this->entityManager->flush() ;
  2722. }
  2723. }
  2724. }
  2725. public function recherche($item, $search = []) {
  2726. // if (count($search) > 1) {
  2727. $condition = true ;
  2728. foreach ($search as $key => $value) {
  2729. if(!empty($value))
  2730. {
  2731. if($key == "dateDebut")
  2732. {
  2733. $dateString1 = $value;
  2734. $dateString2 = $item->$key;
  2735. // Conversion des chaînes de caractères en objets DateTime
  2736. $dateSearch = \DateTime::createFromFormat('d/m/Y', $dateString1)->setTime(0, 0, 0);
  2737. $dateValue = \DateTime::createFromFormat('d/m/Y', $dateString2)->setTime(0, 0, 0);
  2738. $condition = $condition && ($dateSearch <= $dateValue) ;
  2739. }
  2740. else if($key == "dateFin")
  2741. {
  2742. $dateString1 = $value;
  2743. $dateString2 = $item->$key;
  2744. // Conversion des chaînes de caractères en objets DateTime
  2745. $dateSearch = \DateTime::createFromFormat('d/m/Y', $dateString1)->setTime(0, 0, 0);
  2746. $dateValue = \DateTime::createFromFormat('d/m/Y', $dateString2)->setTime(0, 0, 0);
  2747. $condition = $condition && ($dateSearch >= $dateValue) ;
  2748. }
  2749. else if($key == "dateFacture" || $key == "currentDate")
  2750. {
  2751. $dateString1 = $value;
  2752. $dateString2 = $item->$key;
  2753. // Conversion des chaînes de caractères en objets DateTime
  2754. $dateSearch = \DateTime::createFromFormat('d/m/Y', $dateString1)->setTime(0, 0, 0);
  2755. $dateValue = \DateTime::createFromFormat('d/m/Y', $dateString2)->setTime(0, 0, 0);
  2756. $condition = $condition && ($dateSearch == $dateValue) ;
  2757. }
  2758. else if($key == "mois")
  2759. {
  2760. $condition = $condition && ($value == $item->$key) ;
  2761. }
  2762. else if($key == "annee")
  2763. {
  2764. $condition = $condition && ($value == $item->$key) ;
  2765. }
  2766. else if($key == "idEntrepot")
  2767. {
  2768. $findEntrepot = False ;
  2769. $arrayTab = (array)($item->$key) ;
  2770. $arrayTab = array_values($arrayTab) ;
  2771. for ($i=0; $i < count($arrayTab); $i++) {
  2772. if($value == $arrayTab[$i])
  2773. {
  2774. $findEntrepot = True ;
  2775. break ;
  2776. }
  2777. }
  2778. $condition = $condition && $findEntrepot ;
  2779. }
  2780. else if($key == "statutPaiement")
  2781. {
  2782. // Si le filtre est vide, ne pas filtrer
  2783. if (!empty($value)) {
  2784. $condition = $condition && ((string)$item->$key === (string)$value) ;
  2785. }
  2786. }
  2787. else
  2788. {
  2789. $spec = explode("-",$key) ;
  2790. if(strtolower($spec[0]) == "dur")
  2791. {
  2792. // Utilisation de la fonction substr pour obtenir une sous-chaîne du début du mot
  2793. $debutMot = substr(strtolower($item->$key), 0, strlen(strtolower($value)));
  2794. $condition = $condition && strcasecmp($debutMot, strtolower($value)) === 0 ;
  2795. }
  2796. else
  2797. {
  2798. if(is_numeric($item->$key))
  2799. {
  2800. $condition = $condition && ($item->$key == $search[$key]) ;
  2801. }
  2802. else
  2803. {
  2804. $condition = $condition && (strpos($item->$key, $search[$key]) !== false) ;
  2805. }
  2806. }
  2807. }
  2808. }
  2809. }
  2810. return $condition;
  2811. // } else {
  2812. // $key = key($item);
  2813. // return strpos($item->$key, $search[$key]) !== false;
  2814. // }
  2815. }
  2816. public function searchData($data, $search = [])
  2817. {
  2818. $resultats = array_filter($data, function($item) use($search) {
  2819. return $this->recherche($item, $search);
  2820. });
  2821. $vide = True ;
  2822. foreach ($search as $key => $value) {
  2823. if(!empty($value))
  2824. {
  2825. $vide = False ;
  2826. break ;
  2827. }
  2828. }
  2829. if(empty($resultats) && $vide)
  2830. return $data ;
  2831. return $resultats ;
  2832. }
  2833. function check_duplicates_recursive($arr) {
  2834. // Si le tableau ne contient qu'un élément, il n'y a pas de doublon
  2835. if (count($arr) <= 1) {
  2836. return false;
  2837. }
  2838. // Sélectionne le premier élément du tableau
  2839. $elem = array_shift($arr);
  2840. // Vérifie si l'élément est présent dans le reste du tableau
  2841. if (in_array($elem, $arr)) {
  2842. return true;
  2843. }
  2844. // Sinon, rĂ©pète la mĂªme opĂ©ration sur le reste du tableau
  2845. return $this->check_duplicates_recursive($arr);
  2846. }
  2847. public function detecter_doublons($tableau) {
  2848. $keys = array_keys($tableau[0]);
  2849. $enregistrements = array();
  2850. $doublons = array();
  2851. foreach ($tableau as $enregistrement) {
  2852. $enregistrement_str = '';
  2853. foreach ($keys as $key) {
  2854. $enregistrement_str .= $enregistrement[$key];
  2855. }
  2856. if (in_array($enregistrement_str, $enregistrements)) {
  2857. $doublons[] = $enregistrement;
  2858. }
  2859. else {
  2860. $enregistrements[] = $enregistrement_str;
  2861. }
  2862. }
  2863. return $doublons;
  2864. }
  2865. // U est l'unité de la partie entière
  2866. // D est l'unité de la partie décimale
  2867. public function NumberToLetter($nombre, $U = null, $D = null)
  2868. {
  2869. $toLetter = [
  2870. 0 => "zéro",
  2871. 1 => "un",
  2872. 2 => "deux",
  2873. 3 => "trois",
  2874. 4 => "quatre",
  2875. 5 => "cinq",
  2876. 6 => "six",
  2877. 7 => "sept",
  2878. 8 => "huit",
  2879. 9 => "neuf",
  2880. 10 => "dix",
  2881. 11 => "onze",
  2882. 12 => "douze",
  2883. 13 => "treize",
  2884. 14 => "quatorze",
  2885. 15 => "quinze",
  2886. 16 => "seize",
  2887. 17 => "dix-sept",
  2888. 18 => "dix-huit",
  2889. 19 => "dix-neuf",
  2890. 20 => "vingt",
  2891. 30 => "trente",
  2892. 40 => "quarante",
  2893. 50 => "cinquante",
  2894. 60 => "soixante",
  2895. 70 => "soixante-dix",
  2896. 80 => "quatre-vingt",
  2897. 90 => "quatre-vingt-dix",
  2898. ];
  2899. $numberToLetter='';
  2900. $nombre = strtr((string)$nombre, [" "=>""]);
  2901. $nb = floatval($nombre);
  2902. if( strlen($nombre) > 15 ) return "dépassement de capacité";
  2903. if( !is_numeric($nombre) ) return "Nombre non valide";
  2904. if( ceil($nb) != $nb ){
  2905. $nb = explode('.',$nombre);
  2906. return $this->NumberToLetter($nb[0]) . ($U ? " $U et " : " virgule ") . $this->NumberToLetter($nb[1]) . ($D ? " $D" : "");
  2907. }
  2908. $n = strlen($nombre);
  2909. switch( $n ){
  2910. case 1:
  2911. $numberToLetter = $toLetter[$nb];
  2912. break;
  2913. case 2:
  2914. if( $nb > 19 ){
  2915. $quotient = floor($nb / 10);
  2916. $reste = $nb % 10;
  2917. if( $nb < 71 || ($nb > 79 && $nb < 91) ){
  2918. if( $reste == 0 ) $numberToLetter = $toLetter[$quotient * 10];
  2919. if( $reste == 1 ) $numberToLetter = $toLetter[$quotient * 10] . "-et-" . $toLetter[$reste];
  2920. if( $reste > 1 ) $numberToLetter = $toLetter[$quotient * 10] . "-" . $toLetter[$reste];
  2921. }else $numberToLetter = $toLetter[($quotient - 1) * 10] . "-" . $toLetter[10 + $reste];
  2922. }else $numberToLetter = $toLetter[$nb];
  2923. break;
  2924. case 3:
  2925. $quotient = floor($nb / 100);
  2926. $reste = $nb % 100;
  2927. if( $quotient == 1 && $reste == 0 ) $numberToLetter = "cent";
  2928. if( $quotient == 1 && $reste != 0 ) $numberToLetter = "cent" . " " . $this->NumberToLetter($reste);
  2929. if( $quotient > 1 && $reste == 0 ) $numberToLetter = $toLetter[$quotient] . " cents";
  2930. if( $quotient > 1 && $reste != 0 ) $numberToLetter = $toLetter[$quotient] . " cent " . $this->NumberToLetter($reste);
  2931. break;
  2932. case 4 :
  2933. case 5 :
  2934. case 6 :
  2935. $quotient = floor($nb / 1000);
  2936. $reste = $nb - $quotient * 1000;
  2937. if( $quotient == 1 && $reste == 0 ) $numberToLetter = "mille";
  2938. if( $quotient == 1 && $reste != 0 ) $numberToLetter = "mille" . " " . $this->NumberToLetter($reste);
  2939. if( $quotient > 1 && $reste == 0 ) $numberToLetter = $this->NumberToLetter($quotient) . " mille";
  2940. if( $quotient > 1 && $reste != 0 ) $numberToLetter = $this->NumberToLetter($quotient) . " mille " . $this->NumberToLetter($reste);
  2941. break;
  2942. case 7:
  2943. case 8:
  2944. case 9:
  2945. $quotient = floor($nb / 1000000);
  2946. $reste = $nb % 1000000;
  2947. if( $quotient == 1 && $reste == 0 ) $numberToLetter = "un million";
  2948. if( $quotient == 1 && $reste != 0 ) $numberToLetter = "un million" . " " . $this->NumberToLetter($reste);
  2949. if( $quotient > 1 && $reste == 0 ) $numberToLetter = $this->NumberToLetter($quotient) . " millions";
  2950. if( $quotient > 1 && $reste != 0 ) $numberToLetter = $this->NumberToLetter($quotient) . " millions " . $this->NumberToLetter($reste);
  2951. break;
  2952. case 10:
  2953. case 11:
  2954. case 12:
  2955. $quotient = floor($nb / 1000000000);
  2956. $reste = $nb - $quotient * 1000000000;
  2957. if( $quotient == 1 && $reste == 0 ) $numberToLetter = "un milliard";
  2958. if( $quotient == 1 && $reste != 0 ) $numberToLetter = "un milliard" . " " . $this->NumberToLetter($reste);
  2959. if( $quotient > 1 && $reste == 0 ) $numberToLetter = $this->NumberToLetter($quotient) . " milliards";
  2960. if( $quotient > 1 && $reste != 0 ) $numberToLetter = $this->NumberToLetter($quotient) . " milliards " . $this->NumberToLetter($reste);
  2961. break;
  2962. case 13:
  2963. case 14:
  2964. case 15:
  2965. $quotient = floor($nb / 1000000000000);
  2966. $reste = $nb - $quotient * 1000000000000;
  2967. if( $quotient == 1 && $reste == 0 ) $numberToLetter = "un billion";
  2968. if( $quotient == 1 && $reste != 0 ) $numberToLetter = "un billion" . " " . $this->NumberToLetter($reste);
  2969. if( $quotient > 1 && $reste == 0 ) $numberToLetter = $this->NumberToLetter($quotient) . " billions";
  2970. if( $quotient > 1 && $reste != 0 ) $numberToLetter = $this->NumberToLetter($quotient) . " billions " . $this->NumberToLetter($reste);
  2971. break;
  2972. }
  2973. /*respect de l'accord de quatre-vingt*/
  2974. if( substr($numberToLetter, strlen($numberToLetter)-12, 12 ) == "quatre-vingt" ) $numberToLetter .= "s";
  2975. return $numberToLetter;
  2976. }
  2977. public function homeRefreshAllFiles($key)
  2978. {
  2979. $racine = "files/systeme/" ;
  2980. $files = [
  2981. "caisse" => [
  2982. "commande(agence)",
  2983. "panierCommande(agence)"
  2984. ],
  2985. "commande" => [
  2986. "bonCommande(agence)",
  2987. "commande(agence)"
  2988. ],
  2989. "facture" => [
  2990. "facture(agence)",
  2991. "factureParent"
  2992. ],
  2993. "livraison" => [
  2994. "bonLivraison(agence)"
  2995. ],
  2996. "parametres" => [
  2997. "general(agence)",
  2998. "produitTypeTva(agence)"
  2999. ],
  3000. "sav" => [
  3001. "annulation(agence)",
  3002. "motif(agence)"
  3003. ],
  3004. "stock" => [
  3005. "approvisionnement(agence)",
  3006. "categorie(agence)",
  3007. "entrepot(agence)",
  3008. "fournisseur(agence)",
  3009. "produit(agence)",
  3010. "stock_entrepot(agence)",
  3011. "stock_general(agence)"
  3012. ],
  3013. "credit" => [
  3014. "credit(agence)",
  3015. "acompte(agence)"
  3016. ],
  3017. "agenda" => [
  3018. "agenda(agence)"
  3019. ],
  3020. "prestations" => [
  3021. "service(agence)"
  3022. ]
  3023. ];
  3024. if($key != "all")
  3025. {
  3026. foreach ($files[$key] as $file) {
  3027. $filename = $racine.$key."/".$file."/".$this->nameAgence ;
  3028. if(file_exists($filename))
  3029. unlink($filename) ;
  3030. }
  3031. }
  3032. else
  3033. {
  3034. foreach($files as $indice => $value)
  3035. {
  3036. foreach ($files[$indice] as $file) {
  3037. $filename = $racine.$indice."/".$file."/".$this->nameAgence ;
  3038. if(file_exists($filename))
  3039. unlink($filename) ;
  3040. }
  3041. }
  3042. }
  3043. }
  3044. public function getFactureClient($facture)
  3045. {
  3046. $result = [] ;
  3047. if($facture->getClient()->getType()->getId() == 2)
  3048. $result["client"] = $facture->getClient()->getClient()->getNom() ;
  3049. else
  3050. $result["client"] = $facture->getClient()->getSociete()->getNom() ;
  3051. return $result ;
  3052. }
  3053. public function getFactureRemise($facture,$totalHt)
  3054. {
  3055. if(!is_null($facture->getRemiseType()))
  3056. {
  3057. $remiseVal = is_null($facture->getRemiseVal()) ? 0 : floatval($facture->getRemiseVal()) ;
  3058. if($facture->getRemiseType()->getCalcul() == 100)
  3059. {
  3060. $remiseG = ($totalHt * $remiseVal) / 100 ;
  3061. }
  3062. else
  3063. {
  3064. $remiseG = $remiseVal ;
  3065. }
  3066. }
  3067. else
  3068. {
  3069. $remiseG = 0 ;
  3070. }
  3071. return $remiseG ;
  3072. }
  3073. public function getCaisseRemise($caisse,$totalHt)
  3074. {
  3075. if(!is_null($caisse->getRemiseType()))
  3076. {
  3077. $remiseVal = is_null($caisse->getRemiseValeur()) ? 0 : floatval($caisse->getRemiseValeur()) ;
  3078. if($caisse->getRemiseType()->getCalcul() == 100)
  3079. {
  3080. $remiseG = ($totalHt * $remiseVal) / 100 ;
  3081. }
  3082. else
  3083. {
  3084. $remiseG = $remiseVal ;
  3085. }
  3086. }
  3087. else
  3088. {
  3089. $remiseG = 0 ;
  3090. }
  3091. return $remiseG ;
  3092. }
  3093. public function formatAnnulationToFacture($annulations)
  3094. {
  3095. $elements = [] ;
  3096. foreach ($annulations as $annulation) {
  3097. $element = [] ;
  3098. $facture = $this->entityManager->getRepository(Facture::class)->find($annulation->idF) ;
  3099. if(is_null($facture))
  3100. continue;
  3101. $refModele = $facture->getModele()->getReference() ;
  3102. $entrepot = "-" ;
  3103. $idEntrepot = "-" ;
  3104. if($refModele == "PROD")
  3105. {
  3106. // DEBUT VRAI
  3107. $entrepotObj = $this->entityManager->getRepository(PrdEntrepot::class)->findOneBy([
  3108. "nom" => strtoupper($facture->getLieu()),
  3109. "agence" => $facture->getAgence(),
  3110. "statut" => True
  3111. ]) ;
  3112. if(!is_null($entrepotObj))
  3113. {
  3114. $entrepot = $entrepotObj->getNom();
  3115. $idEntrepot = $entrepotObj->getId();
  3116. }
  3117. else
  3118. {
  3119. $affectEntrepot = $this->entityManager->getRepository(PrdEntrpAffectation::class)->findOneBy([
  3120. "agent" => $facture->getUser(),
  3121. "statut" => True
  3122. ]) ;
  3123. if(!is_null($affectEntrepot))
  3124. {
  3125. $entrepot = $affectEntrepot->getEntrepot()->getNom();
  3126. $idEntrepot = $affectEntrepot->getEntrepot()->getId();
  3127. }
  3128. else
  3129. {
  3130. $factDetail = $this->entityManager->getRepository(FactDetails::class)->findOneByEntite([
  3131. "facture" => $facture,
  3132. "activite" => "Produit",
  3133. "statut" => True
  3134. ]) ;
  3135. if(!is_null($factDetail))
  3136. {
  3137. $idVariation = $factDetail->getEntite() ;
  3138. $variation = $this->entityManager->getRepository(PrdVariationPrix::class)->find($idVariation) ;
  3139. $histoEntrepot = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findOneBy([
  3140. "variationPrix" => $variation,
  3141. "statut" => True
  3142. ]) ;
  3143. $entrepot = $histoEntrepot->getEntrepot()->getNom();
  3144. $idEntrepot = $histoEntrepot->getEntrepot()->getId();
  3145. }
  3146. else
  3147. {
  3148. $entrepot = "-" ;
  3149. $idEntrepot = "-" ;
  3150. // $histoEntrepot = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findOneBy([
  3151. // "agence" => $this->agence,
  3152. // "statut" => True
  3153. // ]) ;
  3154. // $entrepot = $histoEntrepot->getEntrepot()->getNom();
  3155. // $idEntrepot = $histoEntrepot->getEntrepot()->getId();
  3156. }
  3157. }
  3158. }
  3159. // FIN VRAI
  3160. }
  3161. if(!is_null($facture->getEntrepot()))
  3162. {
  3163. if($refModele == "PROD")
  3164. {
  3165. $entrepot = is_null($facture->getEntrepot()) ? "-" : $facture->getEntrepot()->getNom();
  3166. $idEntrepot = is_null($facture->getEntrepot()) ? "-" : $facture->getEntrepot()->getId();
  3167. }
  3168. }
  3169. $element["id"] = $facture->getId() ;
  3170. $element["idA"] = $annulation->id ;
  3171. $element["idC"] = $facture->getClient()->getId() ;
  3172. $element["idT"] = $facture->getType()->getId() ;
  3173. $element["idM"] = $facture->getModele()->getId() ;
  3174. $element["entrepot"] = $refModele == "PROD" ? $entrepot : "-" ;
  3175. $element["idEntrepot"] = $refModele == "PROD" ? $idEntrepot : "-" ;
  3176. $element["mois"] = $facture->getDate()->format('m') ;
  3177. $element["annee"] = $facture->getDate()->format('Y') ;
  3178. $element["date"] = $facture->getDate()->format('d/m/Y') ;
  3179. $element["currentDate"] = $facture->getDate()->format('d/m/Y') ;
  3180. $element["dateDebut"] = $facture->getDate()->format('d/m/Y') ;
  3181. $element["dateFin"] = $facture->getDate()->format('d/m/Y') ;
  3182. $element["agence"] = $facture->getAgence()->getId() ;
  3183. $element["user"] = $facture->getUser()->getId() ;
  3184. $element["numFact"] = $annulation->numero;
  3185. $element["modele"] = $facture->getModele()->getNom() ;
  3186. $element["type"] = $facture->getType()->getNom() ;
  3187. $element["dateCreation"] = $annulation->date ;
  3188. $element["dateFacture"] = $facture->getDate()->format('d/m/Y') ;
  3189. $element["client"] = $this->getFactureClient($facture)["client"] ;
  3190. $element["total"] = $annulation->total;
  3191. $element["specification"] = $annulation->refSpec;;
  3192. $element["nature"] = "ANL" ;
  3193. array_push($elements,$element) ;
  3194. }
  3195. return $elements ;
  3196. }
  3197. public function compareDates($date1, $date2, $condition) {
  3198. $date1Obj = \DateTime::createFromFormat('d/m/Y', $date1) ;
  3199. $date2Obj = \DateTime::createFromFormat('d/m/Y', $date2) ;
  3200. switch ($condition) {
  3201. case 'G': // cas oĂ¹ la date1 est supĂ©rieure Ă  la date2
  3202. return $date1Obj > $date2Obj;
  3203. case 'P': // cas oĂ¹ la date1 est infĂ©rieure Ă  la date2
  3204. return $date1Obj < $date2Obj;
  3205. case 'E': // cas oĂ¹ la date1 est Ă©gale Ă  la date2
  3206. return $date1Obj == $date2Obj;
  3207. default:
  3208. return false;
  3209. }
  3210. }
  3211. public function checkAllDateAgenda($filename)
  3212. {
  3213. $agendas = $this->entityManager->getRepository(Agenda::class)->findBy([
  3214. "agence" => $this->agence
  3215. ]) ;
  3216. if(!is_null($agendas))
  3217. $this->validCompareDate($agendas,$filename) ;
  3218. $echeances = $this->entityManager->getRepository(AgdEcheance::class)->findBy([
  3219. "agence" => $this->agence
  3220. ]) ;
  3221. if(!is_null($echeances))
  3222. $this->validCompareDate($echeances,$filename) ;
  3223. $agendaAcomptes = $this->entityManager->getRepository(AgdAcompte::class)->findBy([
  3224. "agence" => $this->agence
  3225. ]) ;
  3226. if(!is_null($agendaAcomptes))
  3227. $this->validCompareDate($agendaAcomptes,$filename) ;
  3228. $agdLivraisons = $this->entityManager->getRepository(AgdLivraison::class)->findBy([
  3229. "agence" => $this->agence
  3230. ]) ;
  3231. if(!is_null($agdLivraisons))
  3232. $this->validCompareDate($agdLivraisons,$filename) ;
  3233. }
  3234. public function validCompareDate($object, $filename)
  3235. {
  3236. $dateActuel = date('d/m/Y') ;
  3237. foreach ($object as $obj) {
  3238. $dateAgdAcompte = $obj->getDate()->format('d/m/Y') ;
  3239. $compareInf = $this->compareDates($dateAgdAcompte,$dateActuel,"P") ;
  3240. if($compareInf)
  3241. {
  3242. if($obj->isStatut())
  3243. {
  3244. // dd($obj) ;
  3245. $obj->setStatut(NULL) ;
  3246. $this->entityManager->flush() ;
  3247. if(file_exists($filename))
  3248. unlink($filename) ;
  3249. }
  3250. }
  3251. }
  3252. }
  3253. public function convertirFormatDate($dateString) {
  3254. // Séparer la date en jour, mois et année
  3255. $dateParts = explode('/', $dateString);
  3256. $jour = $dateParts[0];
  3257. $mois = $dateParts[1];
  3258. $annee = $dateParts[2];
  3259. // Créer un nouvel objet DateTime avec le format aaaa-mm-jj
  3260. $date = new \DateTime("$annee-$mois-$jour");
  3261. // Obtenir les composants de la date au format 'aaaa-mm-jj'
  3262. $anneeConvertie = $date->format('Y');
  3263. $moisConverti = $date->format('m');
  3264. $jourConverti = $date->format('d');
  3265. // Retourner la date convertie au format 'aaaa-mm-jj'
  3266. return $anneeConvertie . '-' . $moisConverti . '-' . $jourConverti;
  3267. }
  3268. public function calculerDateAvantNjours($dateInitiale, $nbJours) {
  3269. // Convertir la date initiale en objet DateTime
  3270. $date = new \DateTime($this->convertirFormatDate($dateInitiale));
  3271. // Calculer la date N jours avant la date initiale
  3272. $dateAvantNJours = $date->modify("-$nbJours days");
  3273. // Conversion de la date en format souhaité (jj/mm/aaaa)
  3274. $jour = $dateAvantNJours->format('d');
  3275. $mois = $dateAvantNJours->format('m');
  3276. $annee = $dateAvantNJours->format('Y');
  3277. // Formattage de la date
  3278. $dateFormatee = str_pad($jour, 2, "0", STR_PAD_LEFT) . '/' . str_pad($mois, 2, "0", STR_PAD_LEFT) . '/' . $annee;
  3279. return $dateFormatee;
  3280. }
  3281. public function calculerDateApresNjours($dateInitiale, $nbJours) {
  3282. // Convertir la date initiale en objet DateTime
  3283. $date = new \DateTime($this->convertirFormatDate($dateInitiale));
  3284. // Calculer la date après le nombre de jours spécifié
  3285. $dateApresNJours = $date->modify("+$nbJours days");
  3286. // Conversion de la date en format souhaité (jj/mm/aaaa)
  3287. $jour = $dateApresNJours->format('d');
  3288. $mois = $dateApresNJours->format('m');
  3289. $annee = $dateApresNJours->format('Y');
  3290. // Formattage de la date
  3291. $dateFormatee = str_pad($jour, 2, "0", STR_PAD_LEFT) . '/' . str_pad($mois, 2, "0", STR_PAD_LEFT) . '/' . $annee;
  3292. // return $dateApresNJours;
  3293. return $dateFormatee;
  3294. }
  3295. public function genererTableauMois($dateInitiale, $nombreMois, $dateLimite,$moisExist) {
  3296. $tableauDates = array();
  3297. $tabMois = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"];
  3298. $date = \DateTime::createFromFormat('d/m/Y', $dateInitiale);
  3299. $mois = null;
  3300. for ($i = 0; $i < $nombreMois; $i++) {
  3301. // Calculer la date après le nombre de jours spécifié
  3302. $dateApresNJours = $this->calculerDateApresNjours($dateInitiale, 30 * ($i + 1));
  3303. $annee = intval(explode("/",$dateApresNJours)[2]);
  3304. if($mois == null)
  3305. {
  3306. $mois = intval(explode("/",$dateApresNJours)[1]);
  3307. if(!is_null($moisExist))
  3308. {
  3309. if( $mois >= 12 )
  3310. {
  3311. $mois = 1 ;
  3312. }
  3313. else
  3314. {
  3315. $mois = $moisExist ;
  3316. }
  3317. }
  3318. }
  3319. else if( $mois >= 12 + 1 )
  3320. {
  3321. $mois = 1 ;
  3322. // return $tableauDates;
  3323. }
  3324. // Ajouter la date au tableau
  3325. $finLimite = $this->calculerDateApresNjours($dateApresNJours,$dateLimite) ;
  3326. $resultCompare = $this->compareDates($finLimite,date("d/m/Y"),"P") || $this->compareDates($finLimite,date("d/m/Y"),"E") ;
  3327. $statut = $resultCompare ? "En Alerte" : "-" ;
  3328. // if(!$resultCompare)
  3329. // return $tableauDates ;
  3330. $tableauDates[] = [
  3331. "debutLimite" => $dateApresNJours,
  3332. "finLimite" => $finLimite,
  3333. "mois" => $tabMois[$mois - 1],
  3334. "indexMois" => $mois,
  3335. "annee" => $annee,
  3336. "statut" =>'<span class="text-danger font-weight-bold">'.strtoupper($statut).'</span>',
  3337. ] ;
  3338. $mois++ ;
  3339. }
  3340. return $tableauDates;
  3341. }
  3342. public function genererTableauJour($dateInitiale, $nombreJour) {
  3343. $tableauDates = array();
  3344. $tabMois = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"];
  3345. $date = \DateTime::createFromFormat('d/m/Y', $dateInitiale);
  3346. for ($i = 0; $i < $nombreJour; $i++) {
  3347. // Calculer la date après le nombre de jours spécifié
  3348. $dateApresNJours = $this->calculerDateApresNjours($dateInitiale,$i + 1);
  3349. // Extraire le mois de la date
  3350. // $date->modify("+1 days");
  3351. $annee = intval(explode("/",$dateApresNJours)[2]);
  3352. $mois = intval(explode("/",$dateApresNJours)[1]);
  3353. // Ajouter la date au tableau
  3354. // $finLimite = $this->calculerDateApresNjours($dateApresNJours,$dateLimite) ;
  3355. $resultCompare = $this->compareDates($dateApresNJours,date("d/m/Y"),"P") || $this->compareDates($dateApresNJours,date("d/m/Y"),"E") ;
  3356. $statut = $resultCompare ? "En Alerte" : "-" ;
  3357. // if(!$resultCompare)
  3358. // return $tableauDates ;
  3359. $tableauDates[] = [
  3360. "debutLimite" => $dateApresNJours,
  3361. // "finLimite" => $finLimite,
  3362. "mois" => $tabMois[$mois - 1],
  3363. "indexMois" => $mois,
  3364. "annee" => $annee,
  3365. "statut" =>'<span class="text-danger font-weight-bold">'.strtoupper($statut).'</span>',
  3366. ];
  3367. }
  3368. return $tableauDates;
  3369. }
  3370. public function synchronisationGeneral()
  3371. {
  3372. /* DEBUT MISE A JOUR DEDUCTION */
  3373. // $enrDeductions = $this->entityManager->getRepository(PrdDeduction::class)->findAll() ;
  3374. // foreach($enrDeductions as $enrDeduction)
  3375. // {
  3376. // $variationPrix = $enrDeduction->getHistoEntrepot()->getVariationPrix() ;
  3377. // $agenceDeduc = $enrDeduction->getHistoEntrepot()->getAgence() ;
  3378. // $enrDeduction->setAgence($agenceDeduc) ;
  3379. // $enrDeduction->setVariationPrix($variationPrix) ;
  3380. // $this->entityManager->flush() ;
  3381. // }
  3382. /* FIN MISE A JOUR DEDUCTION */
  3383. $produitFalses = $this->entityManager->getRepository(Produit::class)->findBy([
  3384. "agence" => $this->agence,
  3385. "trulyDeleted" => NULL,
  3386. "statut" => False
  3387. ]) ;
  3388. foreach($produitFalses as $produitFalse)
  3389. {
  3390. $variationPrixTrues = $this->entityManager->getRepository(PrdVariationPrix::class)->findBy([
  3391. "produit" => $produitFalse,
  3392. ]) ;
  3393. foreach ($variationPrixTrues as $variationPrixTrue) {
  3394. // if(!$variationPrixTrue->isStatut())
  3395. // continue ;
  3396. $variationPrixTrue->setStatut(False) ;
  3397. $this->entityManager->flush() ;
  3398. $histoEntrepotTrues = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findBy([
  3399. "variationPrix" => $variationPrixTrue,
  3400. ]) ;
  3401. foreach ($histoEntrepotTrues as $histoEntrepotTrue) {
  3402. $histoEntrepotTrue->setStatut(False) ;
  3403. $this->entityManager->flush() ;
  3404. }
  3405. }
  3406. $produitFalse->setTrulyDeleted(True) ;
  3407. $this->entityManager->flush() ;
  3408. }
  3409. $produits = $this->entityManager->getRepository(Produit::class)->findBy([
  3410. "agence" => $this->agence,
  3411. "toUpdate" => True,
  3412. "statut" => True
  3413. ]) ;
  3414. foreach($produits as $produit)
  3415. {
  3416. $variationPrixs = $this->entityManager->getRepository(PrdVariationPrix::class)->findBy([
  3417. "produit" => $produit,
  3418. "statut" => True
  3419. ]) ;
  3420. $stockRemoveProduit = 0 ;
  3421. $stockAddProduit = 0 ;
  3422. foreach ($variationPrixs as $variationPrix) {
  3423. $stockAddVariation = 0 ;
  3424. $stockRemoveVariation = 0 ;
  3425. $histoEntrepots = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findBy([
  3426. "variationPrix" => $variationPrix,
  3427. "statut" => True
  3428. ]) ;
  3429. foreach ($histoEntrepots as $histoEntrepot) {
  3430. // DEBUT HISTO ENTREPOT POSITIF
  3431. $totalAddEntrepot = 0 ;
  3432. $totalRemoveEntrepot = 0 ;
  3433. $appro = $this->entityManager->getRepository(PrdApprovisionnement::class)->stockTotalHistoEntrepot([
  3434. "histoEntrepot" => $histoEntrepot->getId(),
  3435. ]) ;
  3436. $stockEntrepotInSav = $this->entityManager->getRepository(SavDetails::class)->calculSavStockEntrepot(
  3437. [
  3438. "histoEntrepot" => $histoEntrepot->getId(),
  3439. "agence" => $this->agence,
  3440. "user" => $this->userObj,
  3441. ]) ;
  3442. // Prendre en compte les ajustements directs de stock (inventaire)
  3443. $ajustementsNets = $this->entityManager->getRepository(\App\Entity\PrdHistoAjustement::class)
  3444. ->calculerAjustementNetEntrepot($histoEntrepot->getId());
  3445. $totalAddEntrepot = floatval($appro["stockTotalEntrepot"]) + $stockEntrepotInSav + $ajustementsNets ;
  3446. $stockAddVariation += $totalAddEntrepot ;
  3447. // FIN
  3448. // DEBUT HISTO ENTREPOT NEGATIF
  3449. $deductionEntrepot = $this->entityManager->getRepository(PrdDeduction::class)->getSommeDeductionEntrepot([
  3450. "histoEntrepot" => $histoEntrepot->getId(),
  3451. "variationPrix" => $variationPrix->getId(),
  3452. ]) ;
  3453. $totalRemoveEntrepot = floatval($deductionEntrepot["sommeStock"]) ;
  3454. $caisseHistoEntrepot = $this->entityManager->getRepository(CaissePanier::class)->stockTotalCaisseEntrepot([
  3455. "histoEntrepot" => $histoEntrepot->getId(),
  3456. "variationPrix" => $variationPrix->getId(),
  3457. ]) ;
  3458. $totalRemoveEntrepot += floatval($caisseHistoEntrepot["totalCaisseEntrepot"]) ;
  3459. $quantiteFactureEnt = $this->entityManager->getRepository(FactDetails::class)->stockTotalFactureInEntrepot([
  3460. "histoEntrepot" => $histoEntrepot->getId(),
  3461. ]) ;
  3462. $totalRemoveEntrepot += $quantiteFactureEnt ;
  3463. $stockRemoveVariation += $totalRemoveEntrepot ;
  3464. // FIN
  3465. $histoEntrepotToUpdate = $this->entityManager->getRepository(PrdHistoEntrepot::class)->find($histoEntrepot->getId()) ;
  3466. $histoEntrepotToUpdate->setStock($totalAddEntrepot - $totalRemoveEntrepot) ;
  3467. $this->entityManager->flush() ;
  3468. }
  3469. $variationPrixToUpdate = $this->entityManager->getRepository(PrdVariationPrix::class)->find($variationPrix->getId()) ;
  3470. $variationPrixToUpdate->setStock($stockAddVariation - $stockRemoveVariation) ;
  3471. $this->entityManager->flush() ;
  3472. $stockRemoveProduit += $stockRemoveVariation ;
  3473. $stockAddProduit += $stockAddVariation ;
  3474. }
  3475. $produit->setStock($stockAddProduit - $stockRemoveProduit) ;
  3476. $produit->setToUpdate(null) ;
  3477. $this->entityManager->flush() ;
  3478. $filename = "files/systeme/stock/variationProduit(agence)/vartPrd_".$produit->getId()."_".$this->nameAgence ;
  3479. if(file_exists($filename))
  3480. unlink($filename) ;
  3481. }
  3482. if(empty($produits))
  3483. return ;
  3484. $dataFilenames = [
  3485. "files/systeme/stock/stock_general(agence)/".$this->nameAgence,
  3486. "files/systeme/stock/stock_entrepot(agence)/".$this->nameAgence,
  3487. "files/systeme/stock/type(agence)/".$this->nameAgence,
  3488. "files/systeme/stock/stockType(agence)/".$this->nameAgence ,
  3489. "files/systeme/stock/stockGEntrepot(agence)/".$this->nameAgence ,
  3490. "files/systeme/stock/stockParCategorie(agence)/".$this->nameAgence
  3491. ] ;
  3492. foreach ($dataFilenames as $dataFilename)
  3493. {
  3494. if(file_exists($dataFilename))
  3495. unlink($dataFilename) ;
  3496. }
  3497. }
  3498. public function synchronisationServiceApresVente($params = [])
  3499. {
  3500. foreach($params as $param)
  3501. {
  3502. // SYNCRO AVEC ANNULATION CAISSE
  3503. if($param == "CAISSE")
  3504. {
  3505. $commandes = $this->entityManager->getRepository(CaisseCommande::class)->findBy([
  3506. "agence" => $this->agence,
  3507. "statut" => True,
  3508. "synchro" => null
  3509. ]) ;
  3510. foreach($commandes as $commande)
  3511. {
  3512. $annulationCaisse = $this->entityManager->getRepository(SavAnnulation::class)->findOneBy([
  3513. "caisse" => $commande
  3514. ]) ;
  3515. if(is_null($annulationCaisse))
  3516. continue;
  3517. $panierCommandes = $this->entityManager->getRepository(CaissePanier::class)->findBy([
  3518. "commande" => $commande,
  3519. "statut" => True
  3520. ]) ;
  3521. if(empty($panierCommandes))
  3522. {
  3523. $commande->setMontantPayee(0) ;
  3524. $commande->setStatut(False) ;
  3525. $this->entityManager->flush() ;
  3526. }
  3527. else
  3528. {
  3529. $totalMontantCaisse = 0 ;
  3530. foreach($panierCommandes as $panierCommande)
  3531. {
  3532. $totalMontantCaisse += ($panierCommande->getPrix() * $panierCommande->getQuantite()) ;
  3533. }
  3534. $commande->setMontantPayee($totalMontantCaisse) ;
  3535. $commande->setStatut(True) ;
  3536. $this->entityManager->flush() ;
  3537. }
  3538. $commande->setSynchro(True) ;
  3539. $this->entityManager->flush() ;
  3540. }
  3541. }
  3542. else if($param == "FACTURE") // SYNCRO AVEC ANNULATION FACTURE
  3543. {
  3544. $factures = $this->entityManager->getRepository(Facture::class)->findBy([
  3545. "agence" => $this->agence,
  3546. "statut" => True,
  3547. "synchro" => null
  3548. ]) ;
  3549. foreach($factures as $facture)
  3550. {
  3551. $annulationFacture = $this->entityManager->getRepository(SavAnnulation::class)->findOneBy([
  3552. "facture" => $facture
  3553. ]) ;
  3554. if(is_null($annulationFacture))
  3555. continue;
  3556. $factureDetails = $this->entityManager->getRepository(FactDetails::class)->findBy([
  3557. "facture" => $facture,
  3558. "statut" => True
  3559. ]) ;
  3560. // if($facture->getNumFact() == "DF-002/23")
  3561. // dd($factureDetails) ;
  3562. if(empty($factureDetails))
  3563. {
  3564. $facture->setTvaVal(0) ;
  3565. $facture->setTotal(0) ;
  3566. $facture->setStatut(False) ;
  3567. $this->entityManager->flush() ;
  3568. }
  3569. else
  3570. {
  3571. $totalHTFacture = 0 ;
  3572. $totalTvaFacture = 0 ;
  3573. foreach($factureDetails as $factureDetail)
  3574. {
  3575. $remise = 0 ;
  3576. $quantite = $factureDetail->getQuantite() ;
  3577. $prixUnitaire = $factureDetail->getPrix() ;
  3578. $totalLigne = ($quantite * $prixUnitaire) ;
  3579. $totalHTLigne = ($quantite * $prixUnitaire) ;
  3580. $totalTvaLigne = is_null($factureDetail->getTvaVal()) ? 0 : $factureDetail->getTvaVal() ;
  3581. if(!is_null($factureDetail->getRemiseType()))
  3582. {
  3583. if($factureDetail->getRemiseType()->getCalcul() == 1)
  3584. {
  3585. $remise = $factureDetail->getRemiseVal() ;
  3586. }
  3587. else if($factureDetail->getRemiseType()->getCalcul() == 100)
  3588. {
  3589. $remise = ($totalLigne * $factureDetail->getRemiseVal()) / 100 ;
  3590. }
  3591. }
  3592. $totalLigne -= $remise ;
  3593. $totalHTFacture += $totalLigne ;
  3594. $totalTvaFacture += ($totalHTLigne * $totalTvaLigne) / 100 ;
  3595. }
  3596. $remiseFacture = 0 ;
  3597. if(!is_null($facture->getRemiseType()))
  3598. {
  3599. if($facture->getRemiseType()->getCalcul() == 1)
  3600. {
  3601. $remiseFacture = $facture->getRemiseVal() ;
  3602. }
  3603. else if($facture->getRemiseType()->getCalcul() == 100)
  3604. {
  3605. $remiseFacture = ($totalLigne * $facture->getRemiseVal()) / 100 ;
  3606. }
  3607. }
  3608. $totalHTFacture -= $remiseFacture ;
  3609. $facture->setTvaVal($totalTvaFacture) ;
  3610. $facture->setTotal($totalHTFacture) ;
  3611. $facture->setStatut(True) ;
  3612. $this->entityManager->flush() ;
  3613. }
  3614. $facture->setSynchro(True) ;
  3615. $this->entityManager->flush() ;
  3616. }
  3617. }
  3618. }
  3619. $dataFilenames = [
  3620. "files/systeme/caisse/commande(agence)/".$this->nameAgence ,
  3621. "files/systeme/caisse/panierCommande(agence)/".$this->nameAgence,
  3622. "files/systeme/facture/facture(agence)/".$this->nameAgence,
  3623. "files/systeme/sav/annulation(agence)/".$this->nameAgence,
  3624. ] ;
  3625. foreach ($dataFilenames as $dataFilename) {
  3626. if(file_exists($dataFilename))
  3627. unlink($dataFilename) ;
  3628. }
  3629. }
  3630. public function synchronisationAchatBonDeCommande()
  3631. {
  3632. $statutBonEnCours = $this->entityManager->getRepository(AchStatutBon::class)->findOneBy([
  3633. "reference" => "ENCR",
  3634. ]) ;
  3635. $statutBonPayee = $this->entityManager->getRepository(AchStatutBon::class)->findOneBy([
  3636. "reference" => "PAYE",
  3637. ]) ;
  3638. $statutBonLivree = $this->entityManager->getRepository(AchStatutBon::class)->findOneBy([
  3639. "reference" => "LIVRE",
  3640. ]) ;
  3641. $typeCredit = $this->entityManager->getRepository(AchType::class)->findOneBy([
  3642. "reference" => "CREDIT",
  3643. ]) ;
  3644. $bonCommandeEnCours = $this->entityManager->getRepository(AchBonCommande::class)->findBy([
  3645. "agence" => $this->agence,
  3646. "statutBon" => $statutBonEnCours,
  3647. "type" => $typeCredit,
  3648. "statutGen" => True,
  3649. ]) ;
  3650. foreach($bonCommandeEnCours as $bonCommandeEnCour)
  3651. {
  3652. $totalCreditPayee = $this->entityManager->getRepository(AchHistoPaiement::class)->getTotalPaiement($bonCommandeEnCour->getId()) ;
  3653. if($totalCreditPayee["credit"] >= $bonCommandeEnCour->getMontant())
  3654. {
  3655. $bonCommandeEnCour->setStatutBon($statutBonPayee) ;
  3656. $this->entityManager->flush() ;
  3657. }
  3658. }
  3659. $statutNonLivree = $this->entityManager->getRepository(AchStatut::class)->findOneBy([
  3660. "reference" => "NOTLVR"
  3661. ]) ;
  3662. $bonCommandePayees = $this->entityManager->getRepository(AchBonCommande::class)->findBy([
  3663. "agence" => $this->agence,
  3664. "statutBon" => $statutBonPayee,
  3665. // "type" => $typeCredit,
  3666. "statutGen" => True,
  3667. ]) ;
  3668. foreach($bonCommandePayees as $bonCommandePayee)
  3669. {
  3670. $detailAchats = $this->entityManager->getRepository(AchDetails::class)->findBy([
  3671. "bonCommande" => $bonCommandePayee,
  3672. "statut" => $statutNonLivree,
  3673. "statutGen" => True
  3674. ]) ;
  3675. if(empty($detailAchats))
  3676. {
  3677. $bonCommandePayee->setStatutBon($statutBonLivree) ;
  3678. $this->entityManager->flush() ;
  3679. }
  3680. }
  3681. $statutLivree = $this->entityManager->getRepository(AchStatut::class)->findOneBy([
  3682. "reference" => "LVR"
  3683. ]) ;
  3684. $bonCommandeLivrees = $this->entityManager->getRepository(AchBonCommande::class)->findBy([
  3685. "agence" => $this->agence,
  3686. "statutBon" => $statutBonLivree,
  3687. // "type" => $typeCredit,
  3688. "statutGen" => True,
  3689. ]) ;
  3690. foreach($bonCommandeLivrees as $bonCommandeLivree)
  3691. {
  3692. $detailAchatNonLivres = $this->entityManager->getRepository(AchDetails::class)->findBy([
  3693. "bonCommande" => $bonCommandeLivree,
  3694. "statut" => $statutNonLivree,
  3695. "statutGen" => True
  3696. ]) ;
  3697. foreach($detailAchatNonLivres as $detailAchatNonLivre)
  3698. {
  3699. $detailAchatNonLivre->setStatut($statutLivree) ;
  3700. $this->entityManager->flush() ;
  3701. }
  3702. }
  3703. $dataFilenames = [
  3704. "files/systeme/achat/listBonCommande(agence)/".$this->nameAgence,
  3705. ] ;
  3706. foreach ($dataFilenames as $dataFilename) {
  3707. if(file_exists($dataFilename))
  3708. unlink($dataFilename) ;
  3709. }
  3710. }
  3711. public function updateAnneeData()
  3712. {
  3713. // $factures = $this->entityManager->getRepository(Facture::class)->findBy([
  3714. // "agence" => $this->agence,
  3715. // "anneeData" => NULL,
  3716. // ]) ;
  3717. // foreach ($factures as $facture) {
  3718. // $facture->setAnneeData($facture->getDate()->format('Y')) ;
  3719. // $this->entityManager->flush() ;
  3720. // }
  3721. // $annulations = $this->entityManager->getRepository(SavAnnulation::class)->findBy([
  3722. // "agence" => $this->agence,
  3723. // "anneeData" => NULL,
  3724. // ]) ;
  3725. // foreach ($annulations as $annulation) {
  3726. // $annulation->setAnneeData($annulation->getDate()->format('Y')) ;
  3727. // $this->entityManager->flush() ;
  3728. // }
  3729. // $produits = $this->entityManager->getRepository(Produit::class)->findBy([
  3730. // "agence" => $this->agence,
  3731. // "anneeData" => NULL,
  3732. // ]) ;
  3733. // foreach ($produits as $produit) {
  3734. // $produit->setAnneeData($produit->getCreatedAt()->format('Y')) ;
  3735. // $this->entityManager->flush() ;
  3736. // }
  3737. // $histoEntrepots = $this->entityManager->getRepository(PrdHistoEntrepot::class)->findBy([
  3738. // "agence" => $this->agence,
  3739. // "anneeData" => NULL,
  3740. // ]) ;
  3741. // foreach ($histoEntrepots as $histoEntrepot) {
  3742. // $histoEntrepot->setAnneeData($histoEntrepot->getCreatedAt()->format('Y')) ;
  3743. // $this->entityManager->flush() ;
  3744. // }
  3745. // $caissePaniers = $this->entityManager->getRepository(CaissePanier::class)->findBy([
  3746. // "agence" => $this->agence,
  3747. // "anneeData" => NULL,
  3748. // ]) ;
  3749. // foreach ($caissePaniers as $caissePanier) {
  3750. // $caissePanier->setAnneeData($caissePanier->getCommande()->getDate()->format('Y')) ;
  3751. // $this->entityManager->flush() ;
  3752. // }
  3753. // $finances = $this->entityManager->getRepository(CrdFinance::class)->findBy([
  3754. // "agence" => $this->agence,
  3755. // "anneeData" => NULL,
  3756. // ]) ;
  3757. // foreach ($finances as $finance) {
  3758. // $finance->setAnneeData($finance->getCreatedAt()->format('Y')) ;
  3759. // $this->entityManager->flush() ;
  3760. // }
  3761. }
  3762. public function timeToDate($timestamp)
  3763. {
  3764. if(empty($timestamp))
  3765. {
  3766. $dateTime = null;
  3767. }
  3768. else
  3769. {
  3770. $dateTime = date('Y-m-d', strtotime('1899-12-30 +' . $timestamp . ' days'));
  3771. $dateTime = \DateTime::createFromFormat('Y-m-d', $dateTime) ;
  3772. }
  3773. return $dateTime ;
  3774. }
  3775. public function synchronisationFacture($agence)
  3776. {
  3777. $factures = $this->entityManager->getRepository(Facture::class)->findBy([
  3778. "agence" => $agence,
  3779. "statut" => True,
  3780. "isUpdated" => True
  3781. ],[
  3782. "id" => "DESC"
  3783. ]) ;
  3784. foreach ($factures as $facture) {
  3785. $details = $this->entityManager->getRepository(FactDetails::class)->findBy([
  3786. "facture" => $facture,
  3787. "statut" => True ]
  3788. ) ;
  3789. $totalGHt = 0 ;
  3790. $totalTva = 0 ;
  3791. foreach ($details as $factureDetail) {
  3792. $tvaVal = (empty($factureDetail->getTvaVal()) || is_null($factureDetail->getTvaVal())) ? 0 : $factureDetail->getTvaVal() ;
  3793. $tva = (($factureDetail->getPrix() * $tvaVal) / 100) * $factureDetail->getQuantite();
  3794. $totalDHt = $factureDetail->getPrix() * $factureDetail->getQuantite() ;
  3795. $remise = $this->getFactureRemise($factureDetail,$totalDHt) ;
  3796. $totalDHt = $totalDHt - $remise ;
  3797. $totalGHt += $totalDHt ;
  3798. $totalTva += $tva ;
  3799. }
  3800. $remiseGeneral = $this->getFactureRemise($facture,$totalGHt) ;
  3801. $totalTTC = $totalGHt + $totalTva - $remiseGeneral ;
  3802. $facture->setTvaVal(floatval($totalTva)) ;
  3803. $facture->setTotal(floatval($totalTTC)) ;
  3804. $facture->setIsUpdated(null) ;
  3805. $this->entityManager->flush() ;
  3806. }
  3807. }
  3808. public function authentificationAdministrateur($idUser, $passUser)
  3809. {
  3810. $user = $this->entityManager->getRepository(User::class)->find($idUser) ;
  3811. $isPasswordValid = $this->passwordEncoder->isPasswordValid($user,$passUser);
  3812. return $isPasswordValid ;
  3813. }
  3814. public function generateListeAvoir($filename)
  3815. {
  3816. $pathAnnulation = "files/systeme/sav/annulation(agence)/".$this->nameAgence ;
  3817. if(!file_exists($pathAnnulation))
  3818. $this->generateSavAnnulation($pathAnnulation,$this->agence) ;
  3819. $annulations = json_decode(file_get_contents($pathAnnulation)) ;
  3820. $search = [
  3821. "refSpec" => "AVR"
  3822. ] ;
  3823. $avoirs = $this->searchData($annulations,$search) ;
  3824. $avoirs = $this->objectToArray($avoirs) ;
  3825. $tableauRegroupe = [];
  3826. foreach ($avoirs as $element) {
  3827. $idC = $element["idC"];
  3828. if (array_key_exists($idC, $tableauRegroupe)) {
  3829. $tableauRegroupe[$idC][] = $element;
  3830. } else {
  3831. $tableauRegroupe[$idC] = [$element];
  3832. }
  3833. }
  3834. $avoirs = [] ;
  3835. foreach ($tableauRegroupe as $key => $value) {
  3836. $item = [] ;
  3837. $item["remboursee"] = 0 ;
  3838. foreach ($tableauRegroupe[$key] as $element) {
  3839. $item["client"] = $element["client"] ;
  3840. $item["remboursee"] += floatval($element["remboursee"]) ;
  3841. }
  3842. $item["idC"] = $key ;
  3843. array_push($avoirs,$item) ;
  3844. }
  3845. $avoirs = array_values($avoirs) ;
  3846. $newAvoirs = [] ;
  3847. foreach ($avoirs as $avoir) {
  3848. $histoAvoir = $this->entityManager->getRepository(SavAvoirUse::class)->getSommeAvoirUse([
  3849. "histoClient" => $avoir["idC"],
  3850. // "isNew" => True,
  3851. ]) ;
  3852. if(is_null($histoAvoir))
  3853. {
  3854. $newAvoirs[] = $avoir ;
  3855. continue ;
  3856. }
  3857. $totalAvoir = $avoir["remboursee"] - $histoAvoir ;
  3858. $avoir["remboursee"] = $totalAvoir ;
  3859. $newAvoirs[] = $avoir ;
  3860. }
  3861. file_put_contents($filename,json_encode($newAvoirs)) ;
  3862. }
  3863. public function regrouperRecette($recettes)
  3864. {
  3865. $response = [] ;
  3866. foreach ($recettes as $recette) {
  3867. $response[$recette["date"]][$recette["numero"].'|'.$recette["entrepot"]][$recette["typePaiement"]][] = $recette ;
  3868. }
  3869. return $response ;
  3870. }
  3871. public function deleteRecette()
  3872. {
  3873. $filename = "files/systeme/comptabilite/recette(agence)/".$this->nameAgence ;
  3874. if(file_exists($filename))
  3875. unlink($filename) ;
  3876. }
  3877. public function verifyIsAgenceUpdated($params = [])
  3878. {
  3879. $params["filename"] = "files/json/data_updating_agence.json" ;
  3880. if(!file_exists($params["filename"]))
  3881. {
  3882. $dataUpdatingAgences = [
  3883. $params["category"] => [$this->agence->getId()]
  3884. ] ;
  3885. file_put_contents($params["filename"],json_encode($dataUpdatingAgences)) ;
  3886. return False ;
  3887. }
  3888. $dataUpdatingAgences = (array)json_decode(file_get_contents($params["filename"])) ;
  3889. foreach ($dataUpdatingAgences as $key => $value) {
  3890. $dataUpdatingAgences[$key] = (array)$value ;
  3891. }
  3892. if(!isset($dataUpdatingAgences[$params["category"]]))
  3893. {
  3894. $dataUpdatingAgences[$params["category"]] = [$this->agence->getId()] ;
  3895. file_put_contents($params["filename"],json_encode($dataUpdatingAgences)) ;
  3896. return False ;
  3897. }
  3898. if(!in_array($this->agence->getId(),$dataUpdatingAgences[$params["category"]]))
  3899. {
  3900. $dataUpdatingAgences[$params["category"]][] = $this->agence->getId() ;
  3901. file_put_contents($params["filename"],json_encode($dataUpdatingAgences)) ;
  3902. return False ;
  3903. }
  3904. return True ;
  3905. }
  3906. public function decodeString($input) {
  3907. $decoded = str_replace(['-', '_'], ['+', '/'], $input); // Remplacer '-' par '+' et '_' par '/'
  3908. $padding = strlen($decoded) % 4;
  3909. if ($padding) {
  3910. $decoded .= str_repeat('=', 4 - $padding); // Ajouter le padding '=' si nécessaire
  3911. }
  3912. return base64_decode($decoded);
  3913. }
  3914. public function blockerDateSup($date)
  3915. {
  3916. return $this->compareDates($date,date("d/m/Y"),"G") ;
  3917. }
  3918. }