<?php
/**
* Created by PhpStorm.
* User: rostandnj
* Date: 13/3/19
* Time: 2:02 PM
*/
namespace App\Service;
use App\Entity\ActeurExterne;
use App\Entity\ArchiveLocation;
use App\Entity\Article;
use App\Entity\Boite;
use App\Entity\Bordereau;
use App\Entity\CadreClassement;
use App\Entity\Comment;
use App\Entity\Courrier;
use App\Entity\CourrierCollaborateur;
use App\Entity\Courtier;
use App\Entity\DemandeArchive;
use App\Entity\Document;
use App\Entity\DocumentPartage;
use App\Entity\Dossier;
use App\Entity\DossierDemande;
use App\Entity\DossierWorkgroup;
use App\Entity\DureeDossier;
use App\Entity\Elimination;
use App\Entity\EmpruntArchive;
use App\Entity\Etagere;
use App\Entity\Fichier;
use App\Entity\Log;
use App\Entity\Message;
use App\Entity\News;
use App\Entity\Notification;
use App\Entity\Operation;
use App\Entity\PieceJointe;
use App\Entity\PieceJointeAjoutee;
use App\Entity\Priorite;
use App\Entity\Rayon;
use App\Entity\RegisterItem;
use App\Entity\RegleConservation;
use App\Entity\Relance;
use App\Entity\Repertoire;
use App\Entity\RepertoirePartage;
use App\Entity\Salle;
use App\Entity\Save;
use App\Entity\Service;
use App\Entity\Statut;
use App\Entity\System;
use App\Entity\Tache;
use App\Entity\TypeActeur;
use App\Entity\TypeConfidentialite;
use App\Entity\TypeCourrier;
use App\Entity\TypeDossier;
use App\Entity\TypeTache;
use App\Entity\UserWorkgroup;
use App\Entity\Workgroup;
use BackupManager\Filesystems\Destination;
use BackupManager\Manager;
use Doctrine\DBAL\ConnectionException;
use Doctrine\ORM\EntityManagerInterface;
use Firebase\JWT\JWT;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Security;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;
use FOS\ElasticaBundle\Persister\ObjectPersister;
use App\Entity\User;
use App\Entity\Role;
use App\Entity\File;
use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Folder;
use App\Service\OpenProjectService;
class UserService
{
private $em;
private $container;
private $encoder;
private $jwt;
private $currenUser;
private $currentUser;
private $hash;
private $backupManager;
private $indexer;
private Security $security;
private UrlGeneratorInterface $urlGenerator;
private RequestStack $requestStack;
private OpenProjectService $openProjectService;
private UserPasswordHasherInterface $passwordHasher;
public function __construct(EntityManagerInterface $em,ContainerInterface $c,Manager $backupManager,
UserPasswordHasherInterface $passwordEncoder,JWTTokenManagerInterface $jwt, Security $security,RequestStack $requestStack,
OpenProjectService $openProjectService, UserPasswordHasherInterface $passwordHasher)
{
$this->hash = new HashService($c);
$this->backupManager = $backupManager;
$this->em = $em;
$this->container = $c;
$this->encoder = $passwordEncoder;
$this->jwt = $jwt;
$this->security = $security;
$this->currenUser = $this->security->getUser();
$this->currentUser = $this->security->getUser();
if(is_string($this->currenUser)) $this->currenUser = null;
$this->indexer = $this->container->get("fos_elastica.object_persister.app.dossiers");
$this->urlGenerator = $this->container->get('router');
$this->requestStack = $requestStack;
$this->openProjectService = $openProjectService;
$this->passwordHasher = $passwordHasher;
}
public function getRandom(int $n)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$numbers='0123456789';
$maj='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $n; $i++) {
if($i ==$n-1)
{
$index = rand(0, strlen($numbers) - 1);
$randomString .= $numbers[$index];
}
else if($i==$n)
{
$index = rand(0, strlen($maj) - 1);
$randomString .= $maj[$index];
}
else
{
$index = rand(0, strlen($characters) - 1);
$randomString .= $characters[$index];
}
}
return $randomString;
}
private function passwordStrength(string $password) {
$returnVal = true;
if ( strlen($password) < 8 ) {
$returnVal = false;
}
if ( !preg_match("#[0-9]+#", $password) ) {
$returnVal = false;
}
/* if ( !preg_match("#[a-z]+#", $password) ) {
$returnVal = False;
}*/
if ( !preg_match("#[A-Z]+#", $password) ) {
$returnVal = false;
}
/*if ( !preg_match("/[\'^£$%&*()}{@#~?><>,|=_+!-]/", $password) ) {
$returnVal = False;
}*/
return $returnVal;
}
private function verifyBasicInfo(array $data)
{
$requireField =["nom","prenom","fonction","telephone","email","gender","service_id","role","level"];
foreach ($requireField as $el)
{
if(!array_key_exists($el,$data))
{
return ["message"=>$el." field is required","statut"=>false,"code"=>"FIELD_REQUIRED"];
}
}
if(!filter_var($data["email"], FILTER_VALIDATE_EMAIL))
{
return ["message"=>"invalid_email","statut"=>false,"code"=>"EMAIL_INVALID"];
}
/* if($this->passwordStrength($data["password"])==false)
{
return ["message"=>"invalid_password","statut"=>false,"code"=>"PASSWORD_PATTERN"];
}*/
if(strlen($data["nom"])<1)
{
return ["message"=>"name field empty","statut"=>false,"code"=>"NAME_SHORT"];
}
if(strlen($data["fonction"])<1)
{
return ["message"=>"fonction field empty","statut"=>false,"code"=>"FONCTION_SHORT"];
}
if(strlen($data["telephone"])<1)
{
return ["message"=>"invalid_phone","statut"=>false,"code"=>"PHONE_LENGTH"];
}
/* if (!preg_match('/^[0-9]+$/', $data["telephone"]))
{
return ["message"=>"invalid_phone","statut"=>false,"code"=>"PHONE_NUMBER"];
}*/
if(!in_array($data["gender"],[0,1]))
{
return ["message"=>"invalid_gender","statut"=>false,"code"=>"GENDER_INVALID"];
}
if(!in_array($data["role"],[0,1,2,3,4]))
{
return ["message"=>"invalid_role","statut"=>false,"code"=>"ROLE_INVALID"];
}
$user = $this->em->getRepository(User::class)->findOneBy(array("email"=>$data["email"]));
if(!is_null($user)) return ["message"=>$this->container->get('translator')->trans("email_already_used"),"statut"=>false,"code"=>"EMAIL_USED"];
$user = $this->em->getRepository(User::class)->findOneBy(array("telephone"=>$data["telephone"]));
if(!is_null($user)) return ["message"=>$this->container->get('translator')->trans("phone_already_used"),"statut"=>false,"code"=>"PHONE_USED"];
$service = $this->em->getRepository(Service::class)->findOneBy(array("id"=>$data["service_id"]));
if(is_null($service)) return ["message"=>"service not found","statut"=>false,"code"=>"SERVICE_NOT_FOUND"];
else{
$data["service"] = $service;
}
return ["message"=>"","statut"=>true,"data"=>$data];
}
private function verifyBasicInfo2(array $data)
{
$requireField =["id","nom","prenom","fonction","telephone","email","gender","service_id","role","level"];
foreach ($requireField as $el)
{
if(!array_key_exists($el,$data))
{
return ["message"=>$el." field is required","statut"=>false,"code"=>"FIELD_REQUIRED"];
}
}
if(!filter_var($data["email"], FILTER_VALIDATE_EMAIL))
{
return ["message"=>"invalid_email","statut"=>false,"code"=>"EMAIL_INVALID"];
}
/* if($this->passwordStrength($data["password"])==false)
{
return ["message"=>"invalid_password","statut"=>false,"code"=>"PASSWORD_PATTERN"];
}*/
if(strlen($data["nom"])<1)
{
return ["message"=>"name field empty","statut"=>false,"code"=>"NAME_SHORT"];
}
if(strlen($data["fonction"])<1)
{
return ["message"=>"fonction field empty","statut"=>false,"code"=>"FONCTION_SHORT"];
}
if(strlen($data["telephone"])==0)
{
return ["message"=>"invalid_phone","statut"=>false,"code"=>"PHONE_LENGTH"];
}
/*if (!preg_match('/^[0-9]+$/', $data["telephone"]))
{
return ["message"=>"invalid_phone","statut"=>false,"code"=>"PHONE_NUMBER"];
}*/
if(!in_array($data["gender"],[0,1]))
{
return ["message"=>"invalid_gender","statut"=>false,"code"=>"GENDER_INVALID"];
}
if(!in_array($data["role"],[0,1,2,3,4]))
{
return ["message"=>"invalid_role","statut"=>false,"code"=>"ROLE_INVALID"];
}
$user = $this->em->getRepository(User::class)->findOneBy(array("email"=>$data["email"]));
if(!is_null($user) && $user->getEmail()!=$data["email"]) return ["message"=>"email_already_used","statut"=>false,"code"=>"EMAIL_USED"];
$user = $this->em->getRepository(User::class)->findOneBy(array("telephone"=>$data["telephone"]));
if(!is_null($user) && $user->getTelephone()!=$data["telephone"]) return ["message"=>"phone_already_used","statut"=>false,"code"=>"PHONE_USED"];
$service = $this->em->getRepository(Service::class)->findOneBy(array("id"=>$data["service_id"]));
if(is_null($service)) return ["message"=>"service not found","statut"=>false,"code"=>"SERVICE_NOT_FOUND"];
else{
$data["service"] = $service;
}
$user = $this->em->getRepository(User::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($user)) return ["message"=>"user_not_found","statut"=>false,"code"=>"USER_NOT_FOUND"];
return ["message"=>"","statut"=>true,"data"=>$data,"user"=>$user];
}
private function hydrateBasicInfo(array $data)
{
$user = new User();
$user->setNom($data["nom"]);
$user->setPrenom($data["prenom"]);
$user->setEmail($data["email"]);
$user->setTelephone($data["telephone"]);
$user->setFonction($data["fonction"]);
$user->setGender($data["gender"]);
$user->setLevel($data["level"]);
switch ((int)$data["role"])
{
case User::ROLE_ADMIN:
$user->setType(User::ROLE_ADMIN);
break;
case User::ROLE_USER:
$user->setType(User::ROLE_USER);
break;
case User::ROLE_MANAGER:
$user->setType(User::ROLE_MANAGER);
break;
case User::ROLE_TRAINEE:
$user->setType(User::ROLE_TRAINEE);
break;
default:
$user->setType(User::USER);
break;
}
$user->setIsClose(false);
$user->setIsActive(true);
$p = $this->getRandom(8);
$user->setPassword($this->passwordHasher->hashPassword($user,$p));
$user->setNewPassword($p);
$user->setService($data["service"]);
$user->setGender((boolean)$data["gender"]);
$user->setNewPassword($p);
return $user;
}
private function hydrateBasicInfo2(array $data,User $user)
{
$user->setNom($data["nom"]);
$user->setPrenom($data["prenom"]);
$user->setEmail($data["email"]);
$user->setTelephone($data["telephone"]);
$user->setFonction($data["fonction"]);
$user->setGender($data["gender"]);
$user->setLevel($data["level"]);
switch ((int)$data["role"])
{
case User::ROLE_ADMIN:
$user->setType(User::ROLE_ADMIN);
break;
case User::ROLE_USER:
$user->setType(User::ROLE_USER);
break;
case User::ROLE_MANAGER:
$user->setType(User::ROLE_MANAGER);
break;
case User::ROLE_TRAINEE:
$user->setType(User::ROLE_TRAINEE);
break;
default:
$user->setType(User::USER);
break;
}
$user->setIsClose(false);
$user->setIsActive(true);
//$p = $this->getRandom(8);
//$user->setPassword($this->passwordHasher->hashPassword($user,$p));
//$user->setNewPassword($p);
$user->setService($data["service"]);
$user->setGender((boolean)$data["gender"]);
//$user->setNewPassword($p);
return $user;
}
public function createUser(array $data)
{
$result = $this->verifyBasicInfo($data);
if($result["statut"]==false)
{
return $result;
}
else
{
$user = $this->hydrateBasicInfo($result["data"]);
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT12'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
$filesystem = new Filesystem();
if(!$filesystem->exists(__DIR__.'/../../public/USER/user'.$user->getId())){
try {
$filesystem->mkdir(__DIR__.'/../../public/USER/user'.$user->getId(),0777);
} catch (IOExceptionInterface $exception) {
return ["message"=>"An error occurred while creating your directory at ".$exception->getPath(),"statut"=>false,"code"=>401,"data"=>""];
}
}
// Create user in OpenProject if integration is enabled
// The plain password is stored in newPassword during hydrateBasicInfo
if ($user->getNewPassword()) {
$this->syncUserToOpenProject($user, $user->getNewPassword());
}
return ["message"=>"","statut"=>true,"data"=>$user->toArray()];
}
}
public function getUserByEmail(string $email)
{
$user = $this->em->getRepository(User::class)->findOneBy(array("email"=>$email));
return $user;
}
public function getUserById(int $id)
{
$user = $this->em->getRepository(User::class)->findOneBy(array("id"=>$id));
return $user;
}
public function updateProfile(User $user,string $type,array $data)
{
switch ($type)
{
case "picture":
if(!array_key_exists("file",$data)) return ["message"=>"file field is required","statut"=>false,"data"=>"","code"=>401];
$required =["name","size","extension","type","path"];
foreach ($required as $key=>$el)
{
if(!array_key_exists($el,$data["file"]))
{
return ["message"=>$el." field is required","statut"=>false,"data"=>"","code"=>401];
}
}
$file = $user->getPicture();
if(is_null($file)) $file = new File();
$file->setIsActive(true);
$file->setName($data["file"]["name"]);
$file->setPath($data["file"]["path"]);
$file->setSize($data["file"]["size"]);
$file->setType($data["file"]["type"]);
$file->setExtension($data["file"]["extension"]);
$file->setIsProfile(true);
$file->setDate(new \DateTime());
$user->setPicture($file);
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT05'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"picture updated","statut"=>true,"data"=>$user,"code"=>201];
break;
case "password":
if(!array_key_exists("c-password",$data)) return ["message"=>"c-password field is required","statut"=>false,"data"=>$user,"code"=>401];
if(!array_key_exists("n-password",$data)) return ["message"=>"n-password field is required","statut"=>false,"data"=>$user,"code"=>401];
$res=$this->encoder->isPasswordValid($user,$data["c-password"]);
if($res ==false) return ["message"=>"current_password_invalid","statut"=>false,"data"=>$user,"code"=>401];
$res = $this->passwordStrength($data["n-password"]);
if($res ==false) return ["message"=>"new_password_invalid","statut"=>false,"data"=>$user,"code"=>401];
$user->setPassword($this->passwordHasher->hashPassword($user,$data["n-password"] ));
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT04'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($user);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"profile_updated","statut"=>true,"data"=>$user,"code"=>201];
break;
default:
return ["message"=>"no type added","statut"=>false,"data"=>"","code"=>401];
break;
}
}
public function getSimpleProfile(int $id)
{
$user = $this->em->getRepository(User::class)->findOneBy(array("id"=>$id));
if(is_null($user)) return["message"=>"user not found","statut"=>false,"code"=>404,"data"=>""];
return ["message"=>"","statut"=>true,"code"=>201,"data"=>["user"=>$user->toArray()]];
}
public function lockAccount(User $user,int $id)
{
$cr = $user->getRole();
$u = $this->em->getRepository(User::class)->findOneBy(array("id"=>$id));
if(is_null($u)) return ["message"=>"user not found","statut"=>false,"code"=>404,"data"=>""];
$role = $u->getRole();
if($role->getCode() =="ROLE_ADMIN") return ["message"=>"operation_denied","statut"=>false,"code"=>401,"data"=>""];
if($user->getId()==$u->getId())
{
$user->setIsClose(true);
$this->em->persist($user);
$this->em->flush();
$this->container->get("mail_manager")->accountLocked($user->getUsername(),$user->getEmail());
return ["message"=>"account locked","statut"=>true,"code"=>201,"data"=>$user->toArray()];
}
else
{
if($cr->getCode()!="ROLE_ADMIN") {
return ["message" => "operation_denied", "statut" => false, "code" => 401, "data" => ""];
}
else
{
$u->setIsClose(true);
$this->em->persist($u);
$this->em->flush();
$this->container->get("mail_manager")->accountLocked($u->getUsername(),$u->getEmail());
return ["message"=>"account_locked","statut"=>true,"code"=>201,"data"=>$u->toArray()];
}
}
}
public function login(string $email,string $password)
{
$user = $this->em->getRepository(User::class)->findOneBy(array('email' =>$email));
if($user === null) return ['message' =>"user_not_found","statut"=>false,"code"=>401,"data"=>""];
if($user->getIsClose()==true) return ["message"=>"account_locked","statut"=>false,"code"=>401,"data"=>""];
$res=$this->encoder->isPasswordValid($user,$password);
if($res == false)
{
if($user->getAttemptLogin()<3)
{
$user->setAttemptLogin($user->getAttemptLogin()+1);
if($user->getAttemptLogin()>=3) $user->setIsClose(true);
$this->em->persist($user);
$this->em->flush();
}
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT01'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($user);
$log->setObservation("echec de connexion");
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"login_incorrect","statut"=>false,"code"=>401,"data"=>""];
}
else{
if($user->getIsActive()==0)
{
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT01'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($user);
$log->setObservation("echec de connexion");
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"account_not_activated","statut"=>false,"code"=>401,"data"=>""];
}
$token = $this->jwt->create($user);
$user->setAttemptLogin(0);
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT01'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($user);
$log->setObservation("connexion ok");
$this->em->persist($log);
$this->em->flush();
}
$filesystem = new Filesystem();
if(!$filesystem->exists(__DIR__.'/../../public/USER/user'.$user->getId())){
try {
$filesystem->mkdir(__DIR__.'/../../public/USER/user'.$user->getId(),0777);
} catch (IOExceptionInterface $exception) {
return ["message"=>"An error occurred while creating your directory at ".$exception->getPath(),"statut"=>false,"code"=>401,"data"=>""];
}
}
// Create user in OpenProject if integration is enabled
$this->syncUserToOpenProject($user, $password);
return ["message"=>"","statut"=>true,"code"=>201,"data"=>["user"=>$user,"token"=>$token]];
}
}
/**
* Sync user to OpenProject (create if not exists)
*
* @param User $user The Symfony user
* @param string $password Plain text password
* @return void
*/
private function syncUserToOpenProject(User $user, string $password): void
{
if (!$this->openProjectService->isEnabled()) {
return;
}
// Check if user already exists in OpenProject by email
$existingUser = $this->openProjectService->findUserByEmail($user->getEmail());
if ($existingUser !== null) {
return; // User already exists
}
// Create user in OpenProject
// nom = lastName, prenom = firstName
$this->openProjectService->createUserFromSymfony(
$user->getPrenom() ?? '',
$user->getNom() ?? '',
$user->getEmail(),
$password,
$user->getType() === User::ROLE_ADMIN
);
}
public function resetPassword1(string $email)
{
$user = $this->em->getRepository(User::class)->findOneBy(array("email"=>$email));
if(is_null($user)) return ["message"=>"user not found","statut"=>false,"code"=>404,"data"=>""];
$pass = $this->getRandom(10);
$user2 =new User();
$user2->setPassword($this->passwordHasher->hashPassword($user2,$pass ));
$user->setRpassword($user2->getPassword());
$this->em->persist($user);
$this->em->flush();
$this->container->get("mail_manager")->resetPassword($user->getUsername(),$user->getEmail(),$pass);
return ["message"=>"","statut"=>true,"code"=>201,"data"=>$user];
}
public function usersList(int $limit,int $offset)
{
$users = $this->em->getRepository(User::class)->loadUsers($limit,$offset);
return $users;
}
public function createService(array $data)
{
$req=["code","nom_fr","nom_en","parent","cadre"];
$reqObli=["code","nom_fr","nom_en"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$old = $this->em->getRepository(Service::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1));
if(!is_null($old)) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
$service = new Service();
$service->setCode($data["code"]);
$service->setNomEn($data["nom_en"]);
$service->setNomFr($data["nom_fr"]);
if(strlen($data["parent"])>0)
{
$p = $this->em->getRepository(Service::class)->findOneBy(array("id"=>$data["parent"]));
if(is_null($p)) return ["message"=>"parent service not found","statut"=>false,"code"=>""];
$service->setService($p);
}
$cadres = $this->em->getRepository(CadreClassement::class)->findMultiple($data["cadre"]);
foreach ($cadres as $c){
$service->addCadre($c);
}
$this->em->persist($service);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT09'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($service->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$service->toArray()];
}
public function createNews(array $data)
{
$req=["titre_fr","titre_en","type","desc_fr","desc_en"];
$reqObli=["titre_fr","titre_en","type"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$news = new News();
$news->setTitreEn($data["titre_en"]);
$news->setTitreFr($data["titre_fr"]);
$news->setType(boolval($data["type"]));
$news->setDescFr($data["desc_fr"]);
$news->setDescEn($data["desc_en"]);
$this->em->persist($news);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT63'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($news->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$news->toArray()];
}
public function editNews(array $data)
{
$req=["titre_fr","titre_en","type","desc_fr","desc_en","id"];
$reqObli=["titre_fr","titre_en","type","id"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$news = $this->em->getRepository(News::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($news)) return ["message"=>"news not found","statut"=>false,"code"=>""];
$news->setTitreEn($data["titre_en"]);
$news->setTitreFr($data["titre_fr"]);
$news->setType(boolval($data["type"]));
$news->setDescFr($data["desc_fr"]);
$news->setDescEn($data["desc_en"]);
$this->em->persist($news);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT64'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($news->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$news->toArray()];
}
public function editNewsContent(array $data)
{
$req=["contenu_fr","contenu_en","id"];
$reqObli=["id"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$news = $this->em->getRepository(News::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($news)) return ["message"=>"news not found","statut"=>false,"code"=>""];
$news->setContenuEn($data["contenu_en"]);
$news->setContenuFr($data["contenu_fr"]);
$this->em->persist($news);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT64'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($news->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$news->toArray()];
}
public function createRayon(array $data)
{
$req=["code","salle","nb"];
$reqObli=["code","salle","nb"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$salle = $this->em->getRepository(Salle::class)->findOneBy(['id'=>$data['salle']]);
if($salle === null) return ["message"=>$this->container->get('translator')->trans('room_not_found'),"statut"=>false,"code"=>401];
$old = $this->em->getRepository(Rayon::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1,'salle'=>$salle));
if($old !== null) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
$rayon = new Rayon();
$rayon->setCode($data["code"]);
$rayon->setSalle($salle);
$rayon->setNbFace((int)$data["nb"]);
$this->em->persist($rayon);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT65'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($rayon->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$rayon->toArray()];
}
public function createWorkgroup(array $data)
{
$req=["code","type","title","start_date","end_date","reason"];
$reqObli=["code","type","title"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$old = $this->em->getRepository(Workgroup::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1));
if(!is_null($old)) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
$wkg = new Workgroup();
$wkg->setCode($data["code"]);
$wkg->setTitle($data["title"]);
$wkg->setMotif($data["reason"]);
if($data["type"]==1)
{
$wkg->setType(true);
}
else
{
$wkg->setType(false);
$wkg->setDateDebut(\DateTime::createFromFormat('d/m/Y',$data["start_date"]));
$wkg->setDateFin(\DateTime::createFromFormat('d/m/Y',$data["end_date"]));
}
$this->em->persist($wkg);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT66'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($wkg->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$wkg->toArray()];
}
public function editRayon(array $data)
{
$req=["code","salle","nb","id"];
$reqObli=["code","salle","nb","id"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$rayon = $this->em->getRepository(Rayon::class)->findOneBy(array("id"=>$data["id"]));
if($rayon === null) return ["message"=>"rayon not found","statut"=>false,"code"=>""];
$salle = $this->em->getRepository(Salle::class)->findOneBy(['id'=>$data['salle']]);
if($salle === null) return ["message"=>$this->container->get('translator')->trans('room_not_found'),"statut"=>false,"code"=>401];
$old = $this->em->getRepository(Rayon::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1,'salle'=>$salle));
if($old !== null) {
if($old->getId()!=$rayon->getId())return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
}
$rayon->setCode($data["code"]);
$rayon->setSalle($salle);
$rayon->setNbFace((int)$data["nb"]);
$this->em->persist($rayon);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT67'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($rayon->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$rayon->toArray()];
}
public function createRole(array $data)
{
$req=["code","nom_fr","nom_en"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
$r = new Role();
$r->setCode($data["code"]);
$r->setNomEn($data["nom_en"]);
$r->setNomFr($data["nom_fr"]);
$this->em->persist($r);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$r->toArray()];
}
public function createActorType(array $data)
{
$req=["nom_fr","nom_en"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
$t = new TypeActeur();
$t->setNomEn($data["nom_en"]);
$t->setNomFr($data["nom_fr"]);
$this->em->persist($t);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$t->toArray()];
}
public function createConfidentialityType(array $data)
{
$req=["nom_fr","nom_en","niveau"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
$t = new TypeConfidentialite();
$t->setNomEn($data["nom_en"]);
$t->setNomFr($data["nom_fr"]);
$t->setNiveau($data["niveau"]);
$this->em->persist($t);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$t->toArray()];
}
public function createFolderType(array $data)
{
$req=["code","nom_fr","nom_en"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
$old = $this->em->getRepository(TypeDossier::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1));
if(!is_null($old)) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
$d = new TypeDossier();
$d->setCode($data["code"]);
$d->setNomEn($data["nom_en"]);
$d->setNomFr($data["nom_fr"]);
$this->em->persist($d);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT17'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($d->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$d->toArray()];
}
public function createExternalActor(array $data)
{
$req=["nom","phone","type","email","category"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
if(strlen($data["nom"])<1) return ["message"=>"nom field is empty","statut"=>false,"code"=>""];
if(strlen($data["phone"])===0) return ["message"=>"phone field is empty","statut"=>false,"code"=>""];
$ty = $data["type"];
$actor = new ActeurExterne();
$actor->setNom($data["nom"]);
$actor->setType($ty);
$actor->setTelephone($data["phone"]);
$actor->setCategory($data["category"]);
/*if($data["email"]!='')
{
if(!filter_var($data["email"], FILTER_VALIDATE_EMAIL))
{
return ["message"=>"invalid_email","statut"=>false,"code"=>"EMAIL_INVALID"];
}
}*/
$actor->setEmail($data["email"]);
$this->em->persist($actor);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$actor->toArray()];
}
public function createDureeDossier(array $data)
{
$req=["dua","type_dua","conservation","type_conservation","communication","type_communication"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
foreach ($req as $el)
{
if(empty($data[$el])) return ["message"=>$el." field is empty","statut"=>false,"code"=>""];
}
$d = new DureeDossier();
$d->setDua($data["dua"]);
$d->setTypeDua($data["type_dua"]);
$d->setConservation($data["conservation"]);
$d->setTypeConsevation($data["type_conservation"]);
$d->setCommunication($data["communication"]);
$d->setTypeCommunication($data["type_communication"]);
$this->em->persist($d);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$d->toArray()];
}
public function createCadreClassement(array $data)
{
$req=["niveau","ordre","code","nom_en","nom_fr","desc_fr","desc_en","url_sys","parent"];
$reqObli=["niveau","ordre","code","nom_en","nom_fr","parent"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
foreach ($reqObli as $el)
{
if(empty($el)) return ["message"=>$el." field is empty","statut"=>false,"code"=>""];
}
$c = new CadreClassement();
$old = $this->em->getRepository(CadreClassement::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1));
if(!is_null($old)) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
$c->setNiveau($data["niveau"]);
$c->setOrdre($data["ordre"]);
$c->setCode($data["code"]);
$c->setNomEn($data["nom_en"]);
$c->setNomFr($data["nom_fr"]);
$c->setDescEn($data["desc_en"]);
$c->setDescFr($data["desc_fr"]);
$c->setUrlSys($data["url_sys"]);
$c->setLocalisation("");
if($data["parent"]!='')
{
$p = $this->em->getRepository(CadreClassement::class)->findOneBy(array("id"=>$data["parent"]));
if(is_null($p)) return ["message"=>"parent not found","statut"=>false,"code"=>""];
else
{
$c->setCardreClassement($p);
}
}
$this->em->persist($c);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT23'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($c->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$c->toArray()];
}
public function createBordereau(array $data)
{
$req=["numero","du","file","boite","cote","cadre"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
if(strlen($data["numero"])===0) return ["message"=>"numero field is empty","statut"=>false,"code"=>""];
if(strlen($data["du"])===0) return ["message"=>"du field is empty","statut"=>false,"code"=>""];
if(strlen($data["boite"])===0) return ["message"=>"boite field is empty","statut"=>false,"code"=>""];
if(strlen($data["cote"])===0) return ["message"=>"cote field is empty","statut"=>false,"code"=>""];
if(strlen($data["cadre"])===0) return ["message"=>"cadre field is empty","statut"=>false,"code"=>""];
if(count($data["file"])==0) return ["message"=>"file is empty","statut"=>false,"code"=>""];
$old = $this->em->getRepository(Bordereau::class)->findOneBy(['numero'=>$data['numero'],"isActive"=>1]);
if($old !== null) return ["message"=>$this->container->get('translator')->trans('error_slip_number'),"statut"=>false,"code"=>""];
$cadre = $this->em->getRepository(CadreClassement::class)->findOneBy(['id'=>$data['cadre']]);
if($cadre === null) return ["message"=>$this->container->get('translator')->trans('cadre_not_found'),"statut"=>false,"code"=>""];
$boite = $this->em->getRepository(Boite::class)->findOneBy(['id'=>$data['boite']]);
if($boite === null) return ["message"=>$this->container->get('translator')->trans('box_not_found'),"statut"=>false,"code"=>""];
$b= new Bordereau();
$b->setNumero($data["numero"]);
$b->setDu(\DateTime::createFromFormat('d/m/Y',$data["du"]));
$b->setFichier($data["file"]["name"]);
$b->setBoite($boite);
$b->setCadreClassement($cadre);
$b->setCote($cadre->getCode());
$this->em->persist($b);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$b->toArray()];
}
public function listObject(string $object,$limit=10,$offset=0)
{
$req =["role","service","type-acteur","type-confidentialite","type-dossier","duree-dossier","utilisateur","bordereau","dossier","acteur","salle"];
if(!in_array($object,$req)) return ["message"=>"bad object for looking list","statut"=>false,"code"=>""];
switch ($object)
{
case 'role':
$res = $this->em->getRepository(Role::class)->findBy(array(),array("nomFr"=>"ASC"),100,$offset);
break;
case 'service':
$res = $this->em->getRepository(Service::class)->findBy(array("isActive"=>true),array("nomFr"=>"ASC"),$limit,$offset);
break;
case 'salle':
$res = $this->em->getRepository(Salle::class)->findBy(array("isActive"=>true),array("code"=>"ASC"),$limit,$offset);
break;
case 'archive_location':
$res = $this->em->getRepository(ArchiveLocation::class)->findBy(array("isActive"=>true),array("code"=>"ASC"),$limit,$offset);
break;
case 'type-acteur':
$res = $this->em->getRepository(TypeActeur::class)->findBy(array("isActive"=>true),array("nomFr"=>"ASC"),$limit,$offset);
break;
case 'type-confidentialite':
$res = $this->em->getRepository(TypeConfidentialite::class)->findBy(array("isActive"=>true),array("niveau"=>"ASC"),$limit,$offset);
break;
case 'type-dossier':
$res = $this->em->getRepository(TypeDossier::class)->findBy(array("isActive"=>true),array("nomFr"=>"ASC"),$limit,$offset);
break;
case 'duree-dossier':
$res = $this->em->getRepository(DureeDossier::class)->findBy(array("isActive"=>true),array("dua"=>"ASC"),$limit,$offset);
break;
case 'utilisateur':
$res = $this->em->getRepository(User::class)->listUsers($limit,$offset);
break;
case 'bordereau':
$res = $this->em->getRepository(Bordereau::class)->findBy(array("isActive"=>true),array("numero"=>"ASC"),$limit,$offset);
break;
case 'dossier':
$res = $this->em->getRepository(Dossier::class)->findBy(array("isActive"=>true),array("id"=>"ASC"),$limit,$offset);
break;
case 'acteur':
$res = $this->em->getRepository(ActeurExterne::class)->findBy(array("isActive"=>true),array("id"=>"ASC"),$limit,$offset);
break;
default:
$res=[];
break;
}
$data=[];
foreach ($res as $el)
{
$data[]=$el->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$data];
}
public function generateCode(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""];
$u = $this->em->getRepository(User::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($u)) return ["message"=>"user not found","statut"=>false,"code"=>""];
$u->setPasswordCode($this->getRandom(5));
$this->em->persist($u);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$u->getPasswordCode()];
}
public function resetPassword(array $data)
{
if(!array_key_exists("email",$data)) return ["message"=>"email field is required","statut"=>false,"code"=>""];
if(!array_key_exists("code",$data)) return ["message"=>"code field is required","statut"=>false,"code"=>""];
if(!array_key_exists("password",$data)) return ["message"=>"password field is required","statut"=>false,"code"=>""];
if(strlen($data["password"])<6) return ["message"=>"password is shot min 6 characters","statut"=>false,"code"=>""];
if(strlen($data["code"])!=5) return ["message"=>"incorrect email/code","statut"=>false,"code"=>""];
$user = $this->em->getRepository(User::class)->findOneBy(array("email"=>$data["email"]));
if(is_null($user)) return ["message"=>"incorrect email/code","statut"=>false,"code"=>""];
if($user->getPasswordCode()!=$data["code"]) return ["message"=>"incorrect email/code","statut"=>false,"code"=>""];
$user->setPassword($this->passwordHasher->hashPassword($user,$data["password"]));
$user->setPasswordCode(null);
$user->setIsClose(0);
$user->setAttemptLogin(0);
$this->em->persist($user);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$user->toArray()];
}
public function addRole(array $data)
{
if(!array_key_exists("role_id",$data)) return ["message"=>"role_id field is required","statut"=>false,"code"=>""];
if(!array_key_exists("user_id",$data)) return ["message"=>"user_id field is required","statut"=>false,"code"=>""];
$r = $this->em->getRepository(Role::class)->findOneBy(array("id"=>$data["role_id"]));
if(is_null($r)) return ["message"=>"role not found","statut"=>false,"code"=>""];
$u = $this->em->getRepository(User::class)->findOneBy(array("id"=>$data["user_id"]));
if(is_null($u)) return ["message"=>"user not found","statut"=>false,"code"=>""];
if($data["current_user"]->getId()==$u->getId()) return ["message"=>"operation denied because same user","statut"=>false,"code"=>""];
if($u->getUserRoles()->contains($r)) return ["message"=>"role already added","statut"=>true,"data"=>$u->toArray()];
$u->addRole($r);
$this->em->persist($u);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$u->toArray()];
}
public function removeRole(array $data)
{
if(!array_key_exists("role_id",$data)) return ["message"=>"role_id field is required","statut"=>false,"code"=>""];
if(!array_key_exists("user_id",$data)) return ["message"=>"user_id field is required","statut"=>false,"code"=>""];
$r = $this->em->getRepository(Role::class)->findOneBy(array("id"=>$data["role_id"]));
if(is_null($r)) return ["message"=>"role not found","statut"=>false,"code"=>""];
$u = $this->em->getRepository(User::class)->findOneBy(array("id"=>$data["user_id"]));
if(is_null($u)) return ["message"=>"user not found","statut"=>false,"code"=>""];
if($data["current_user"]->getId()==$u->getId()) return ["message"=>"operation denied because same user","statut"=>false,"code"=>""];
if(!$u->getUserRoles()->contains($r)) return ["message"=>"user not having this role","statut"=>false,"data"=>$u->toArray()];
$u->removeRole($r);
$this->em->persist($u);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$u->toArray()];
}
public function validCode(array $data)
{
if(!array_key_exists("email",$data)) return ["message"=>"email field is required","statut"=>false,"code"=>""];
if(!array_key_exists("code",$data)) return ["message"=>"code field is required","statut"=>false,"code"=>""];
if(strlen($data["code"])!=5) return ["message"=>"incorrect_email_code","statut"=>false,"code"=>""];
$user = $this->em->getRepository(User::class)->findOneBy(array("email"=>$data["email"]));
if(is_null($user)) return ["message"=>"incorrect_email_code","statut"=>false,"code"=>""];
if($user->getPasswordCode()!=$data["code"]) return ["message"=>"incorrect_email_code","statut"=>false,"code"=>""];
return ["message"=>"","statut"=>true,"data"=>$user->toArray()];
}
public function editUserSatus(array $data)
{
if(!array_key_exists("user_id",$data)) return ["message"=>"user_id field is required","statut"=>false,"code"=>""];
if(!array_key_exists("status",$data)) return ["message"=>"status field is required","statut"=>false,"code"=>""];
$user = $this->em->getRepository(User::class)->findOneBy(array("id"=>$data["user_id"]));
if(is_null($user)) return ["message"=>"user not found","statut"=>false,"code"=>""];
if($user->getEmail()=="admin@admin.cm") return ["message"=>"operation denied","statut"=>false,"code"=>""];
$user->setIsClose((bool)$data["status"]);
if($user->getIsClose()==0)
{
$user->setAttemptLogin(0);
}
$this->em->persist($user);
$this->em->flush();
$log = new Log();
if((bool)$data["status"]==true)$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT03'));
else $operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT15'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"code"=>"","data"=>$user->toArray()];
}
public function updateUserRole(array $data)
{
if(!array_key_exists("user_id",$data)) return ["message"=>"user_id field is required","statut"=>false,"code"=>""];
if(!array_key_exists("roles",$data)) return ["message"=>"roles field is required","statut"=>false,"code"=>""];
$user = $this->em->getRepository(User::class)->findOneBy(array("id"=>$data["user_id"]));
if(is_null($user)) return ["message"=>"user not found","statut"=>false,"code"=>""];
if($user->getEmail()=="admin@admin.cm") return ["message"=>"operation denied","statut"=>false,"code"=>""];
$roles = $user->getUserRoles();
if(count($data["roles"])==0)
{
foreach ($roles as $el)
{
$user->removeRole($el);
}
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT14'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"code"=>"","data"=>$user->toArray()];
}
else
{ $alreadyHere=[];
foreach ($roles as $el)
{
if(!in_array($el->getId(),$data["roles"]))
{
$user->removeRole($el);
}
else{
$alreadyHere[]=$el->getId();
}
}
foreach ($data["roles"] as $el)
{
if(!in_array($el,$alreadyHere))
{
$r = $this->em->getRepository(Role::class)->findOneBy(array("id"=>$el));
if(!is_null($r))
{
$user->addRole($r);
}
}
}
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT14'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"code"=>"","data"=>$user->toArray()];
}
}
public function editService(array $data)
{
$req=["code","nom_fr","nom_en","parent","id","cadres"];
$reqObli=["code","nom_fr","nom_en"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$service = $this->em->getRepository(Service::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"service not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(Service::class)->findOneBy(array("code"=>$data["code"]));
if(!is_null($old)) {
if($old->getId()!=$service->getId())return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
}
$service->setCode($data["code"]);
$service->setNomEn($data["nom_en"]);
$service->setNomFr($data["nom_fr"]);
if(strlen($data["parent"])>0)
{
$p = $this->em->getRepository(Service::class)->findOneBy(array("id"=>$data["parent"]));
if(is_null($p)) return ["message"=>"parent service not found","statut"=>false,"code"=>""];
if($p->getCode()!=$service->getCode())
{
$service->setService($p);
}
}
else{
$service->setService(null);
}
$oldCa = $service->getCadres();
foreach ($oldCa as $ca){
$service->removeCadre($ca);
}
$cadres = $this->em->getRepository(CadreClassement::class)->findMultiple($data["cadres"]);
foreach ($cadres as $c){
$service->addCadre($c);
}
$this->em->persist($service);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT10'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($service->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$service->toArray()];
}
public function updateServiceRole(array $data)
{
if(!array_key_exists("service_id",$data)) return ["message"=>"service_id field is required","statut"=>false,"code"=>""];
if(!array_key_exists("roles",$data)) return ["message"=>"roles field is required","statut"=>false,"code"=>""];
$service = $this->em->getRepository(Service::class)->findOneBy(array("id"=>$data["service_id"]));
if(is_null($service)) return ["message"=>"service not found","statut"=>false,"code"=>""];
$roles = $service->getRoles();
if(count($data["roles"])==0)
{
foreach ($roles as $el)
{
$service->removeRole($el);
}
$this->em->persist($service);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT11'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($service->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"code"=>"","data"=>$service->toArray()];
}
else
{ $alreadyHere=[];
foreach ($roles as $el)
{
if(!in_array($el->getId(),$data["roles"]))
{
$service->removeRole($el);
}
else{
$alreadyHere[]=$el->getId();
}
}
foreach ($data["roles"] as $el)
{
if(!in_array($el,$alreadyHere))
{
$r = $this->em->getRepository(Role::class)->findOneBy(array("id"=>$el));
if(!is_null($r))
{
$service->addRole($r);
}
}
}
$this->em->persist($service);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT11'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($service->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"code"=>"","data"=>$service->toArray()];
}
}
public function editFolderType(array $data)
{
$req=["code","nom_fr","nom_en","id"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
$type = $this->em->getRepository(TypeDossier::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($type)) return ["message"=>"type dossier not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(TypeDossier::class)->findOneBy(array("code"=>$data["code"]));
if(!is_null($old)) {
if($old->getId()!=$type->getId())return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
}
$type->setCode($data["code"]);
$type->setNomEn($data["nom_en"]);
$type->setNomFr($data["nom_fr"]);
$this->em->persist($type);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT18'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($type->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$type->toArray()];
}
public function editActorType(array $data)
{
$req=["nom_fr","nom_en","id"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
$t = $this->em->getRepository(TypeActeur::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($t)) return ["message"=>"type acteur not found","statut"=>false,"code"=>""];
$t->setNomEn($data["nom_en"]);
$t->setNomFr($data["nom_fr"]);
$this->em->persist($t);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$t->toArray()];
}
public function editDureeDossier(array $data)
{
$req=["dua","type_dua","conservation","type_conservation","communication","type_communication","id"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
foreach ($req as $el)
{
if(empty($data[$el])) return ["message"=>$el." field is empty","statut"=>false,"code"=>""];
}
$d = $this->em->getRepository(DureeDossier::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($d)) return ["message"=>"duree dossier not found","statut"=>false,"code"=>""];
$d->setDua($data["dua"]);
$d->setTypeDua($data["type_dua"]);
$d->setConservation($data["conservation"]);
$d->setTypeConsevation($data["type_conservation"]);
$d->setCommunication($data["communication"]);
$d->setTypeCommunication($data["type_communication"]);
$this->em->persist($d);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$d->toArray()];
}
public function createSystemParam(array $data)
{
$req =["ftp_user", "ftp_password","ftp_directory","database_folder","awiating_folder","orgainsation_name",
"orgainsation_logo","orgainsation_sigle"
];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$sys = new System();
$sys->setFtpUser($data["ftp_user"]);
$sys->setFtpPassword($data["ftp_password"]);
$sys->setFtpDirectory($data["ftp_directory"]);
$sys->setDatabaseFolder($data["database_folder"]);
$sys->setAwaitingFolder($data["awiating_folder"]);
$sys->setOraganisationName($data["orgainsation_name"]);
$sys->setOrganisationLogo($data["orgainsation_logo"]);
$sys->setOrganisationSigle($data["orgainsation_sigle"]);
$this->em->persist($sys);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$sys->toArray()];
}
public function editPasswordAndPicture(array $data)
{
$user = $data["current_user"];
switch ($data["type"])
{
case "picture":
if(!array_key_exists("file",$data)) return ["message"=>"file field is required","statut"=>false,"data"=>"","code"=>401];
$user->setPhoto($data["file"]["path"]);
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT05'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"picture updated","statut"=>true,"data"=>$user->toArray(),"code"=>201];
break;
case "password":
if(!array_key_exists("c-password",$data)) return ["message"=>"c-password field is required","statut"=>false,"data"=>"","code"=>401];
if(!array_key_exists("n-password",$data)) return ["message"=>"n-password field is required","statut"=>false,"data"=>"","code"=>401];
$res=$this->encoder->isPasswordValid($user,$data["c-password"]);
if($res ==false) return ["message"=>"current_password_invalid","statut"=>false,"data"=>"","code"=>401];
if(strlen($data["n-password"])<6) return ["message"=>"new_password_invalid","statut"=>false,"data"=>"","code"=>401];
$user->setPassword($this->passwordHasher->hashPassword($user,$data["n-password"] ));
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT04'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"profile_updated","statut"=>true,"data"=>$user,"code"=>201];
break;
default:
return ["message"=>"no type added","statut"=>false,"data"=>"","code"=>401];
break;
}
}
public function searchUser(array $data,int $limit,int $offset)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>""];
$res = $this->em->getRepository(User::class)->search($data["keywords"],$limit,$offset);
$datas=[];
foreach ($res as $el)
{
$e=$el->getMiniArray();
$f = $this->container->get("upload_service")->getFile($e["picture"]);
$e["picture"] = "data:".$f["data"]["mime"].";base64, ".$f["data"]["file"];
$datas[]=$e;
}
/*$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT06'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($data["keywords"]);
$this->em->persist($log);
$this->em->flush();
}
*/
return ["message"=>"","statut"=>true,"data"=>$datas];
}
public function searchUser2(array $data,int $limit,int $offset)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>""];
$res = $this->em->getRepository(User::class)->search2($data["keywords"],$limit,$offset);
$datas=[];
foreach ($res as $el)
{
$e=$el->getMiniArray();
$f = $this->container->get("upload_service")->getFile($e["picture"]);
$e["picture"] = "data:".$f["data"]["mime"].";base64, ".$f["data"]["file"];
$datas[]=$e;
}
/*$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT06'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($data["keywords"]);
$this->em->persist($log);
$this->em->flush();
}
*/
return ["message"=>"","statut"=>true,"data"=>$datas];
}
public function deleteItem(array $data,string $type)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""];
if($type=="service")
{
$service = $this->em->getRepository(Service::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"service not found","statut"=>false,"code"=>""];
}
if($type=="article")
{
$service = $this->em->getRepository(Article::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"subject not found","statut"=>false,"code"=>""];
}
if($type=="type_acteur")
{
$service = $this->em->getRepository(TypeActeur::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"type acteur not found","statut"=>false,"code"=>""];
}
if($type=="type_dossier")
{
$service = $this->em->getRepository(TypeDossier::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"type dossier not found","statut"=>false,"code"=>""];
}
if($type=="regle")
{
$service = $this->em->getRepository(RegleConservation::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"regle not found","statut"=>false,"code"=>""];
}
if($type=="cadre")
{
$service = $this->em->getRepository(CadreClassement::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"cadre not found","statut"=>false,"code"=>""];
}
if($type=="rayon")
{
$service = $this->em->getRepository(Rayon::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"rayon not found","statut"=>false,"code"=>""];
}
if($type=="salle")
{
$service = $this->em->getRepository(Salle::class)->findOneBy(array("id"=>$data["id"]));
if($service === null) return ["message"=>"salle not found","statut"=>false,"code"=>""];
}
if($type=="archive_location")
{
$service = $this->em->getRepository(ArchiveLocation::class)->findOneBy(array("id"=>$data["id"]));
if($service === null) return ["message"=>"Archive location not found","statut"=>false,"code"=>""];
}
if($type=="etagere")
{
$service = $this->em->getRepository(Etagere::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"rack not found","statut"=>false,"code"=>""];
}
if($type=="boite")
{
$service = $this->em->getRepository(Boite::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"box not found","statut"=>false,"code"=>""];
}
if($type=="redgister_item")
{
$service = $this->em->getRepository(RegisterItem::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($service)) return ["message"=>"Register item not found","statut"=>false,"code"=>""];
}
$service->setIsActive(false);
$this->em->persist($service);
$this->em->flush();
$operation=null;
if($type=="type_dossier")
{
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT19'));
}
if($type=="regle")
{
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT22'));
}
if($type=="cadre")
{
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT25'));
}
$log = new Log();
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($service->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"operation done","statut"=>true,"data"=>""];
}
public function createRegle(array $data)
{
$req=["dua","type_dua","conservation","type_conservation","observation_fr","observation_en",
"sort_final","code","reference_fr","reference_en","type_dossier"];
$reqObli=["dua","type_dua","conservation","type_conservation",
"sort_final","code","type_dossier"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
foreach ($reqObli as $el)
{
if(trim($data[$el])=="") return ["message"=>$el." field is empty","statut"=>false,"code"=>""];
}
$type =$this->em->getRepository(TypeDossier::class)->findOneBy(array("id"=>$data["type_dossier"]));
if(is_null($type)) return ["message"=>"typeDossier not found","statut"=>false,"code"=>401];
$d = new DureeDossier();
$d->setDua($data["dua"]);
$d->setTypeDua($data["type_dua"]);
$d->setConservation($data["conservation"]);
$d->setTypeConsevation($data["type_conservation"]);
$regle = new RegleConservation();
$regle->setTypeDossier($type);
$regle->setDureeDossier($d);
$regle->setCode($data["code"]);
$regle->setObservationFr($data["observation_fr"]);
$regle->setObservationEn($data["observation_en"]);
$regle->setSortFinal($data["sort_final"]);
$regle->setTexteReferenceFr($data["reference_fr"]);
$regle->setTexteReferenceEn($data["reference_en"]);
$this->em->persist($regle);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT20'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($regle->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$regle->toArray()];
}
public function editRegle(array $data)
{
$req=["id", "dua","type_dua","conservation","type_conservation","observation_fr","observation_en",
"sort_final","code","reference_fr","reference_en"];
$reqObli=["dua","type_dua","conservation","type_conservation",
"sort_final","code","id"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
foreach ($reqObli as $el)
{
if(trim($data[$el])=="") return ["message"=>$el." field is empty","statut"=>false,"code"=>""];
}
$regle = $this->em->getRepository(RegleConservation::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($regle)) return ["message"=>"regle not found","statut"=>false,"code"=>""];
$d = $regle->getDureeDossier();
$d->setDua($data["dua"]);
$d->setTypeDua($data["type_dua"]);
$d->setConservation($data["conservation"]);
$d->setTypeConsevation($data["type_conservation"]);
$regle->setDureeDossier($d);
$regle->setCode($data["code"]);
$regle->setObservationFr($data["observation_fr"]);
$regle->setObservationEn($data["observation_en"]);
$regle->setSortFinal($data["sort_final"]);
$regle->setTexteReferenceFr($data["reference_fr"]);
$regle->setTexteReferenceEN($data["reference_en"]);
$this->em->persist($regle);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT21'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($regle->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$regle->toArray()];
}
public function editCadreClassement(array $data)
{
$req=["niveau","ordre","code","nom_en","nom_fr","desc_fr","desc_en","url_sys","parent","id"];
$reqObli=["niveau","ordre","code","nom_en","nom_fr","parent","id"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
foreach ($reqObli as $el)
{
if(empty($el)) return ["message"=>$el." field is empty","statut"=>false,"code"=>""];
}
$c = $this->em->getRepository(CadreClassement::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($c)) return ["message"=>"cadre not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(CadreClassement::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1));
if(!is_null($old)) {
if($old->getId()!=$c->getId())return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
}
$c->setOrdre($data["ordre"]);
$c->setCode($data["code"]);
$c->setNomEn($data["nom_en"]);
$c->setNomFr($data["nom_fr"]);
$c->setDescEn($data["desc_en"]);
$c->setDescFr($data["desc_fr"]);
$c->setUrlSys($data["url_sys"]);
$c->setLocalisation("");
if($data["parent"]!='')
{
$p = $this->em->getRepository(CadreClassement::class)->findOneBy(array("id"=>$data["parent"]));
if(is_null($p)) return ["message"=>"parent not found","statut"=>false,"code"=>""];
else
{
if($p->getId() != $c->getId()) {
$c->setCardreClassement($p);
$c->setNiveau($data["niveau"]);
}
}
}
else
{
$c->setNiveau($data["niveau"]);
}
$this->em->persist($c);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT24'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($c->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$c->toArray()];
}
public function editBordereau(array $data)
{
$req=["numero","du","id","boite","cote","cadre"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
if(strlen($data["numero"])===0) return ["message"=>"numero field is empty","statut"=>false,"code"=>""];
if(strlen($data["du"])===0) return ["message"=>"du field is empty","statut"=>false,"code"=>""];
if(strlen($data["boite"])===0) return ["message"=>"boite field is empty","statut"=>false,"code"=>""];
if(strlen($data["cote"])===0) return ["message"=>"cote field is empty","statut"=>false,"code"=>""];
if(strlen($data["cadre"])===0) return ["message"=>"cadre field is empty","statut"=>false,"code"=>""];
$b= $this->em->getRepository(Bordereau::class)->findOneBy(array("id"=>$data["id"]));
if($b === null) return ["message"=>"bordereau not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(Bordereau::class)->findBy(['numero'=>$data['numero'],"isActive"=>1]);
if(count($old)>=2 ) return ["message"=>$this->container->get('translator')->trans('error_slip_number'),"statut"=>false,"code"=>""];
$cadre = $this->em->getRepository(CadreClassement::class)->findOneBy(['id'=>$data['cadre']]);
if($cadre === null) return ["message"=>$this->container->get('translator')->trans('cadre_not_found'),"statut"=>false,"code"=>""];
$boite = $this->em->getRepository(Boite::class)->findOneBy(['id'=>$data['boite']]);
if($boite === null) return ["message"=>$this->container->get('translator')->trans('box_not_found'),"statut"=>false,"code"=>""];
$b->setNumero($data["numero"]);
$b->setDu(\DateTime::createFromFormat('d/m/Y',$data["du"]));
$b->setBoite($boite);
$b->setCadreClassement($cadre);
$b->setCote($cadre->getCode());
if(array_key_exists("file",$data)&&array_key_exists("name",$data["file"]))
{
$b->setFichier($data["file"]["name"]);
}
$this->em->persist($b);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT35'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($b->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$b->toArray()];
}
public function searchBordereau(array $data,int $limit,int $offset)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>""];
$res = $this->em->getRepository(Bordereau::class)->search($data["keywords"],$limit,$offset);
$datas=[];
foreach ($res as $el)
{
$datas[]=$el->toArray();
}
/*$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT06'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($data["keywords"]);
$this->em->persist($log);
$this->em->flush();
}
*/
return ["message"=>"","statut"=>true,"data"=>$datas];
}
public function searchService(array $data,int $limit,int $offset)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>""];
$res = $this->em->getRepository(Service::class)->search($data["keywords"],$limit,$offset);
$datas=[];
foreach ($res as $el)
{
$datas[]=$el->toArray();
}
/*
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT06'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($data["keywords"]);
$this->em->persist($log);
$this->em->flush();
}
*/
return ["message"=>"","statut"=>true,"data"=>$datas];
}
public function searchTypeActeur(array $data,int $limit,int $offset)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>""];
$res = $this->em->getRepository(TypeActeur::class)->search($data["keywords"],$limit,$offset);
$datas=[];
foreach ($res as $el)
{
$datas[]=$el->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$datas];
}
public function searchTypeDossier(array $data,int $limit,int $offset)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>""];
$res = $this->em->getRepository(TypeDossier::class)->search($data["keywords"],$limit,$offset);
$datas=[];
foreach ($res as $el)
{
$datas[]=$el->toArray();
}
/*$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT06'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($data["keywords"]);
$this->em->persist($log);
$this->em->flush();
}
*/
return ["message"=>"","statut"=>true,"data"=>$datas];
}
public function createFolder(array $data)
{
$req=["type_confidentialite",
"bordereau","type","description",
"titre","reference",
"cote_dossier","observation","date_cloture","date_type",
"date_creation","langue","files","location","boite","ref_int"];
/* $reqObli=["service_verseur","service_producteur",
"bordereau","type",
"titre","reference",
"cote_dossier","date_cloture",
"date_creation","langue","date_depot","date_versement"];*/
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
/* foreach ($reqObli as $el)
{
if(empty($data[$el])) return ["message"=>$el." field is empty","statut"=>false,"code"=>""];
}*/
$data['reference']= $this->generateReference()["data"];
$type = $this->em->getRepository(TypeDossier::class)->findOneBy(array("id"=>$data["type"]));
if(is_null($type)) return ["message"=>"type dossier not found","statut"=>false,"code"=>""];
$b = $this->em->getRepository(Bordereau::class)->findOneBy(array("id"=>$data["bordereau"]));
if(is_null($b)) return ["message"=>"bordereau not found","statut"=>false,"code"=>""];
$conf = $this->em->getRepository(TypeConfidentialite::class)->findOneBy(array("id"=>$data["type_confidentialite"]));
if(is_null($conf)) return ["message"=>"type confidentialite not found","statut"=>false,"code"=>""];
$cadre = $this->em->getRepository(CadreClassement::class)->findOneBy(array("id"=>$data["cote_dossier"]));
if(is_null($cadre)) return ["message"=>"cadre de classement not found","statut"=>false,"code"=>""];
$boite = $this->em->getRepository(Boite::class)->findOneBy(array("id"=>$data["boite"]));
if(is_null($boite)) return ["message"=>"box not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(Dossier::class)->findOneBy(["reference"=>$data["reference"]]);
if($old !== null) return ["message"=>$this->container->get('translator')->trans("reference already used"),"statut"=>false,"code"=>""];
$dossier = new Dossier();
if(array_key_exists("parent_folder",$data) && strlen($data["parent_folder"])>0){
$parentFolder = $this->em->getRepository(Dossier::class)->findOneBy(["reference"=>$data["parent_folder"]]);
if($parentFolder===null){
return ["message"=>$this->container->get('translator')->trans("parent_folder_not_found"),"statut"=>false,"code"=>""];
}
$dossier->setDossierParent($parentFolder);
}
$dossier->setType($type);
$dossier->setBordereau($b);
$dossier->setTitre($data["titre"]);
$dossier->setObservation($data["observation"]);
$dossier->setLocalisation($data["location"]);
$dossier->setLangue($data["langue"]);
$dossier->setCadreClassement($cadre);
$dossier->setBoite($boite);
$dossier->setCoteDossier($cadre->getCode());
$dossier->setDescription($data["description"]);
$dossier->setReference($data["reference"]);
$dossier->setRefInterne($data["ref_int"]);
$dossier->setTypeConfidentialite($conf);
$df = $data["date_cloture"];
$dc = $data["date_creation"];
switch ($data["date_type"])
{
case 0:
$df = $data["date_cloture"];
$dc = $data["date_creation"];
break;
case 1:
if($data["date_cloture"] != ""){
$df = "01/".$data["date_cloture"];
}
if($data["date_creationloture"] != ""){
$dc = "01/".$data["date_creation"];
}
break;
case 2:
if($data["date_cloture"] != ""){
$df = "01/01/".$data["date_cloture"];
}
if($data["date_creation"] != ""){
$dc = "01/01/".$data["date_creation"];
}
break;
}
$dossier->setDateCreation(\DateTime::createFromFormat('d/m/Y',$dc));
if($df != ""){
$dossier->setDateCloture(\DateTime::createFromFormat('d/m/Y',$df));
}
else{
$dossier->setDateCloture(null);
}
if(array_key_exists('category',$data)){
$dossier->setCategory((int)$data['category']);
}
$dossier->setDateType($data["date_type"]);
$nb=count($data["files"]);
$dossier->setNbPiece($nb);
if($nb>0)
{
foreach ($data["files"] as $f)
{
$file = new Fichier();
$file->setNom($f["name"]);
$file->setFolderNameAndName($dossier->getTitre()." | ". $f["name"]);
$file->setExtension($f["extension"]);
$file->setType($f["type"]);
$file->setTaille($f["size"]);
$file->setPath($f["path"]);
$file->setAuteur($data["user"]->getNom()." ".$data["user"]->getPrenom());
$file->setDossier($dossier);
$dossier->addFichier($file);
}
}
$this->em->persist($dossier);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT36'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($dossier->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$dossier->toArray()];
}
public function generateReference()
{
$ref="B";
$date = new \DateTime();
$ref = strtoupper(uniqid('B'.$date->format("Y"), false));
return ["message"=>"","statut"=>true,"data"=>$ref];
}
public function updatePassword(array $data)
{
$user = $data["user"];
if(!array_key_exists("c-password",$data)) return ["message"=>"c-password field is required","statut"=>false,"data"=>$user,"code"=>401];
if(!array_key_exists("n-password",$data)) return ["message"=>"n-password field is required","statut"=>false,"data"=>$user,"code"=>401];
$res=$this->encoder->isPasswordValid($user,$data["c-password"]);
if($res ==false) return ["message"=>"current_password_invalid","statut"=>false,"data"=>$user,"code"=>401];
$res = strlen($data["n-password"])>=6;
if($res ==false) return ["message"=>"new_password_invalid","statut"=>false,"data"=>$user,"code"=>401];
$user->setPassword($this->passwordHasher->hashPassword($user,$data["n-password"] ));
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT04'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"profile_updated","statut"=>true,"data"=>$user,"code"=>201];
}
public function updatePicture(array $data)
{
$user = $data["user"];
$user->setPhoto($data["file"]);
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT05'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"profile_updated","statut"=>true,"data"=>$user,"code"=>201];
}
public function updateSystemInfo(array $data)
{
$req=["name","country","slogan","phone","fax","bp","ftp_user","ftp_password","ftp_dir","ftp_port","ftp_protocol","ftp_folder"];
if(!in_array($data["field"],$req))
{
return ["message"=>"field_not_available","statut"=>false,"data"=>[],"code"=>401];
}
else
{
$sys = $this->em->getRepository(System::class)->findOneBy(array('statut'=>1));
if(is_null($sys)) return ["message"=>"system info not available on database","statut"=>false,"data"=>[],"code"=>401];
if(strlen($data["value"])==0) return ["message"=>"empty_field","statut"=>false,"data"=>[],"code"=>401];
switch ($data["field"])
{
case 'name':
$sys->setOrganisationName($data["value"]);
break;
case 'country':
$sys->setCountry($data["value"]);
break;
case 'slogan':
$sys->setSlogan($data["value"]);
break;
case 'phone':
$sys->setPhone($data["value"]);
break;
case 'fax':
$sys->setFax($data["value"]);
break;
case 'bp':
$sys->setBp($data["value"]);
break;
case 'ftp_user':
$sys->setFtpUser($data["value"]);
break;
case 'ftp_password':
$hashed = $this->encoder->hashPassword($sys, $data["value"]);
$sys->setFtpPassword($hashed);
break;
case 'ftp_dir':
$sys->setFtpDirectory($data["value"]);
break;
case 'ftp_port':
$sys->setFtpPort($data["value"]);
break;
case 'ftp_protocol':
$sys->setFtpProtocole($data["value"]);
break;
case 'ftp_folder':
$sys->setFtpFolder($data["value"]);
break;
default:
return ["message"=>"field_not_available","statut"=>false,"data"=>[],"code"=>401];
break;
}
$this->em->persist($sys);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT08'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($data["field"]);
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
}
}
public function getSystemInfo()
{
$sys = $this->em->getRepository(System::class)->findOneBy(array('statut'=>1));
if($sys!= null){
if($sys->getFtpPassword()!==""){
$sys->setFtpPassword("xxxxxxx");
}
}
return ["message"=>"","statut"=>true,"data"=>$sys,"code"=>201];
}
public function getOneObject(array $data)
{
if(!array_key_exists("type",$data)&&!array_key_exists("id",$data))
{
return ["message"=>"type or id is missing","statut"=>false,"data"=>[],"code"=>401];
}
switch ($data["type"])
{
case 'service':
$e = $this->em->getRepository(Service::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'article':
$e = $this->em->getRepository(Article::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'news':
$e = $this->em->getRepository(News::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'rayon':
$e = $this->em->getRepository(Rayon::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'etagere':
$e = $this->em->getRepository(Etagere::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'boite':
$e = $this->em->getRepository(Boite::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'salle':
$e = $this->em->getRepository(Salle::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'archive_location':
$e = $this->em->getRepository(ArchiveLocation::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'user':
$e = $this->em->getRepository(User::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'regle':
$e = $this->em->getRepository(RegleConservation::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'cadre':
$e = $this->em->getRepository(CadreClassement::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'bordereau':
$e = $this->em->getRepository(Bordereau::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'dossier':
$e = $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$data["id"]));
if(!is_null($e))
{
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT42'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($e->getId());
$this->em->persist($log);
$this->em->flush();
}
}
break;
case 'workgroup':
$e = $this->em->getRepository(Workgroup::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'type-courrier':
$e = $this->em->getRepository(TypeCourrier::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'piece-jointe':
$e = $this->em->getRepository(PieceJointe::class)->findOneBy(array("id"=>$data["id"]));
if($e !== null)
{
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT60'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($e->getId());
$this->em->persist($log);
$this->em->flush();
}
}
break;
case 'type-tache':
$e = $this->em->getRepository(TypeTache::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'courtier':
$e = $this->em->getRepository(Courtier::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'acteur':
$e = $this->em->getRepository(ActeurExterne::class)->findOneBy(array("id"=>$data["id"]));
break;
case 'register_item':
$e = $this->em->getRepository(RegisterItem::class)->findOneBy(array("id"=>$data["id"]));
break;
default:
return ["message"=>"type not available","statut"=>false,"data"=>[],"code"=>401];
break;
}
if($e === null) return ["message"=>$data["type"]." not found","statut"=>false,"data"=>[],"code"=>401];
$el = $e->toArray();
if($data['type'] === 'user')
{
$f = $this->container->get("upload_service")->getFile($el["picture"]);
$el["picture"] = "data:".$f["data"]["mime"].";base64, ".$f["data"]["file"];
}
return ["message"=>"","statut"=>true,"data"=>$el,"code"=>201];
}
public function getServiceRole(array $data)
{
if(!array_key_exists("id",$data))
{
return ["message"=>"type or id is missing","statut"=>false,"data"=>[],"code"=>401];
}
else
{
$ser = $this->em->getRepository(Service::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($ser)) return ["message"=>"service not found","statut"=>false,"data"=>[],"code"=>401];
else
{
$roles = $ser->getRoles();
$res=[];
foreach ($roles as $r)
{
if($r->getIsActive())$res[]=$r->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$res,"code"=>201];
}
}
}
public function editUser(array $data)
{
$result = $this->verifyBasicInfo2($data);
if($result["statut"]==false)
{
return $result;
}
else
{
$user = $this->hydrateBasicInfo2($result["data"],$result["user"]);
$this->em->persist($user);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT13'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($user->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$user->toArray()];
}
}
public function editLogo(array $data)
{
if(!array_key_exists("file",$data)) return ["message"=>"file field is required","statut"=>false,"data"=>"","code"=>401];
$required =["name","size","extension","type","path"];
foreach ($required as $key=>$el)
{
if(!array_key_exists($el,$data["file"]))
{
return ["message"=>$el." field is required","statut"=>false,"data"=>"","code"=>401];
}
}
$sys = $this->em->getRepository(System::class)->findOneBy(array("statut"=>1));
if(is_null($sys)) return ["message"=>"system info not found","statut"=>false,"data"=>"","code"=>401];
$sys->setOrganisationLogo($data["file"]["path"]);
$this->em->persist($sys);
$this->em->flush();
return ["message"=>"picture updated","statut"=>true,"data"=>$sys->toArray(),"code"=>201];
}
public function activateMultipleNews(array $data)
{
if(!array_key_exists("ids",$data)) return ["message"=>"ids field is required","statut"=>false,"data"=>"","code"=>401];
$elements = $this->em->getRepository(News::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setStatus(true);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
}
public function desactivateMultipleNews(array $data)
{
if(!array_key_exists("ids",$data)) return ["message"=>"ids field is required","statut"=>false,"data"=>"","code"=>401];
$elements = $this->em->getRepository(News::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setStatus(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
}
public function deleteMultiple(array $data)
{
switch ($data["option"])
{
case 'delete':
switch ($data["type"])
{
case 'service':
$elements = $this->em->getRepository(Service::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'workgroup':
$elements = $this->em->getRepository(Workgroup::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'news':
$elements = $this->em->getRepository(News::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'rayon':
$elements = $this->em->getRepository(Rayon::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'etagere':
$elements = $this->em->getRepository(Etagere::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'boite':
$elements = $this->em->getRepository(Boite::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'salle':
$elements = $this->em->getRepository(Salle::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'archive_location':
$elements = $this->em->getRepository(ArchiveLocation::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'user':
$elements = $this->em->getRepository(User::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'type-dossier':
$elements = $this->em->getRepository(TypeDossier::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT19'));
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
if(!is_null($operation))
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getId());
$this->em->persist($log);
}
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'regle':
$elements = $this->em->getRepository(RegleConservation::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT80'));
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
if(!is_null($operation))
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getId());
$this->em->persist($log);
}
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'cadre':
$elements = $this->em->getRepository(CadreClassement::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT25'));
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
if(!is_null($operation))
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getId());
$this->em->persist($log);
}
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'type-courrier':
$elements = $this->em->getRepository(TypeCourrier::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT81'));
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
if($operation !== null)
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getId());
$this->em->persist($log);
}
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'piece-jointe':
$elements = $this->em->getRepository(PieceJointe::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT69'));
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
/* if($operation !== null)
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getId());
$this->em->persist($log);
}*/
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
case 'type-tache':
$elements = $this->em->getRepository(TypeTache::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT82'));
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
if($operation !== null)
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getId());
$this->em->persist($log);
}
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'acteur':
$elements = $this->em->getRepository(ActeurExterne::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT83'));
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
if($operation !== null)
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getId());
$this->em->persist($log);
}
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'courtier':
$elements = $this->em->getRepository(Courtier::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT84'));
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
if($operation !== null)
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getId());
$this->em->persist($log);
}
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'register_item':
$elements = $this->em->getRepository(RegisterItem::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT19'));
foreach ($elements as $el)
{
$el->setIsActive(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
}
break;
case 'activate':
$elements = $this->em->getRepository(User::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT15'));
foreach ($elements as $el)
{
$el->setIsClose(false);
$this->em->persist($el);
if(!is_null($operation))
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getId());
$this->em->persist($log);
}
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
case 'desactivate':
$elements = $this->em->getRepository(User::class)->findMultiple($data["ids"]);
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT03'));
foreach ($elements as $el)
{
$el->setIsClose(true);
$this->em->persist($el);
if(!is_null($operation))
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getId());
$this->em->persist($log);
}
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
break;
}
return ["message"=>"bad type","statut"=>false,"data"=>[],"code"=>401];
}
public function getHistory(array $data)
{
$req=["user","start_date","end_date","operation_type"];
foreach ($req as $r)
{
if(!array_key_exists($r,$data)) return ["message"=>$r." field is required","statut"=>false,"data"=>"","code"=>401];
}
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$op_type = "";
$operations = [
'authentication' => [
'MVT01', // Log in
'MVT02', // Sign Out
'MVT03', // Blocked account
'MVT04', // Change password
'MVT16', // Forgotten password code generation
'MVT05', // Update profile picture
'MVT12', // Register a user
'MVT13', // Edit a user
'MVT14', // User empowerment management
'MVT15', // User unlocking
],
'system_administration' => [
'MVT08', // System parameter change
'MVT26', // System log lookup
'MVT27', // Printing the system log
'MVT28', // Database backup
'MVT29', // Backup system folder
'MVT30', // Backup FTP Transfer
'MVT31', // Backup history print
],
'settings' => [
'MVT32', // Consultation chart
'MVT17', // Save a file type
'MVT18', // Edit a folder type
'MVT19', // Delete folder type
'MVT20', // Save a conservation rule
'MVT21', // Modify a conservation rule
'MVT22', // Delete conservation rule
'MVT80', // Delete a folder conservation rule
'MVT23', // Save a level to the ranking frame
'MVT24', // Modify a ranking frame level
'MVT25', // Delete rank frame
'MVT07', // Download Guide
'MVT33', // OCR Scan
'MVT65', // Create a shelving
'MVT67', // Update a shelving
'MVT73', // Create a shelf
'MVT74', // Update a shelf
'MVT75', // Create an archive box
'MVT76', // Update an archive box
'MVT66', // Create a workgroup
'MVT72', // Update workgroup
'MVT78', // Update a mail type
'MVT81', // Delete a mail type
'MVT79', // Update a task type
'MVT82', // Delete a task type
'MVT83', // Delete an external actor
'MVT84', // Delete a courier
'MVT09', // Register a service
'MVT10', // Edit a service
'MVT11', // Service Enablement Management
],
'operation_type_file' => [
'MVT34', // Add an installment slip
'MVT35', // Edit an installment slip
'MVT36', // Register a folder
'MVT37', // treatment file paid
'MVT38', // Folder batch recording
'MVT85', // Mail batch recording
'MVT39', // Consultation of folder registration history
'MVT40', // Historical deposit printing
'MVT58', // Moving and reclassifying records
'MVT70', // Update a folder
// 'MVT06', // Rapid search
'MVT41', // advanced search
'MVT42', // Folder Consultation
'MVT43', // File Download
'MVT44', // Print search results
'MVT45', // Statistics Consultation
'MVT71', // Consultation of archive statistics,
'MVT46', // Write a request
'MVT47', // See a request
'MVT48', // To treat a request
'MVT49', // Send an answer
'MVT50', // Exit file validation
'MVT51', // Back file validation
'MVT52', // Consultation of files to eliminate
'MVT53', // Print list of files to eliminate
'MVT54', // Validation elimination of records
'MVT55', // History of eliminations
'MVT56', // Historical impression of eliminations
'MVT57', // Control interface
'MVT59', // Create attached file
'MVT60', // Folder Attached file Consultation
'MVT61', // Edit mail attached file
'MVT69', // Delete a mail attached file
'MVT62', // Update status to ended
'MVT86', // Mail registering
],
'blog' => [
'MVT63', // Create an article
'MVT64', // Update an article
'MVT77', // Update an article (duplicate)
],
];
if(array_key_exists($data["operation_type"],$operations)) {
$op_type = $operations[$data["operation_type"]];
};
if($op_type == ""){
$total = $this->em->getRepository(Log::class)->findForUserNb($data["user"],$data["start_date"],$data["end_date"]);
$res = $this->em->getRepository(Log::class)->findForUser($data["user"],$data["start_date"],$data["end_date"],$offset,$limit);
}else{
$total = $this->em->getRepository(Log::class)->findByListCodeNb($data["user"],$op_type,$data["start_date"],$data["end_date"]);
$res = $this->em->getRepository(Log::class)->findByListCode($data["user"],$op_type,$data["start_date"],$data["end_date"],$offset,$limit);
}
$result=[];
foreach ($res as $r) {
$t = $r->toArray();
$t["date"] = $r->getDate()->format('d/m/Y H:i:s');
$result[]=$t;
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$result,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function saveDbOk()
{
$database = 'gedmindef';
$user = 'root';
$pass = '';
$host = 'localhost';
$name = 'db-'.(new \DateTime())->format('d-m-Y-H:i:s').'.sql';
$dir = $this->container->get("kernel")->getProjectDir()."/public/SAVE/".$name;
exec("/opt/lampp/bin/mysqldump --user={$user} --password={$pass} --host={$host} {$database} --result-file={$dir} 2>&1", $output);
$s = new Save();
$s->setState(0);
$s->setFile($name);
$s->setSize(filesize($dir));
$this->em->persist($s);
$this->em->flush();
return ["message"=>$output,"statut"=>true,"data"=>"","code"=>201];
}
public function saveDb()
{
$name = 'db-'.(new \DateTime())->format('d-m-Y-H-i-s').'.sql';
$dir = $this->container->get("kernel")->getProjectDir()."/public/SAVE/".$name.".gz";
$this->backupManager->makeBackup()->run('development', [new Destination('local', $name)], 'gzip');
$s = new Save();
$s->setState(0);
$s->setFile($name.".gz");
$s->setSize(filesize($dir));
$this->em->persist($s);
$this->em->flush();
return ["message"=>"ok","statut"=>true,"data"=>"","code"=>201];
}
private function zip( $zip,$source)
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true) {
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if (in_array(substr($file, strrpos($file, '/')+1), array('.', '..'))) {
continue;
}
$file = realpath($file);
if (is_dir($file) === true) {
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} elseif (is_file($file) === true) {
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
} elseif (is_file($source) === true) {
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip;
}
private function zip2($zip,$archive_folder)
{
$dir = preg_replace('/[\/]{2,}/', '/', $archive_folder."/");
$zip->addEmptyDir(basename($dir));
$dh = opendir($dir);
while($file = readdir($dh))
{
if ($file != '.' && $file != '..')
{
if (is_file($dir.$file))
{
$zip -> addFile($dir.$file, basename($dir)."/".$file);
}
elseif (is_dir($dir.$file))
{
$dir2 = $dir.$file.'/';
$dh2 = opendir($dir2);
while($file1 = readdir($dh2))
{
if ($file1 != '.' && $file1 != '..')
{
if (is_file($dir2.$file1))
{
$zip -> addFile($dir2.$file1, basename($dir).'/'.basename($dir2)."/".$file1);
}
elseif (is_dir($dir2.$file1))
{
//$dir2 = $dir.$file1.'/';
}
else
{
//var_dump(0);
}
}
}
closedir($dh2);
}
else
{
var_dump(0);
}
}
}
closedir($dh);
return $zip;
}
public function saveFolder()
{
/*$zipFileName="Archive".(new \DateTime())->format('d-m-Y-H:i:s').".zip";
$serverPath=$this->container->get("kernel")->getProjectDir()."/public/SAVE";
$zipFileSavePath=$serverPath."/".$zipFileName;
$inputZip[0]=$this->container->get("kernel")->getProjectDir()."/public/"."BORDEREAU";
$inputZip[1]=$this->container->get("kernel")->getProjectDir()."/public/"."CADRE";
$inputZip[2]=$this->container->get("kernel")->getProjectDir()."/public/"."uploads";
$inputZip[3]=$this->container->get("kernel")->getProjectDir()."/public/"."VER";
$zip = new \ZipArchive();
if(file_exists($zipFileSavePath)) {
unlink ($zipFileSavePath);
}
if ($zip->open($zipFileSavePath, \ZIPARCHIVE::CREATE) != TRUE){
return ["message"=>"Could not open archive","statut"=>false,"data"=>"","code"=>401];
}
else
{
foreach ($inputZip as $el)
{
$zip = $this->zip2($zip,$el);
}
$zip->close();
$s = new Save();
$s->setState(0);
$s->setFile($zipFileName);
$s->setSize(filesize($zipFileSavePath));
$this->em->persist($s);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>"","code"=>201];
}*/
return ["message"=>"operation disable / opération desactivée","statut"=>false,"data"=>"","code"=>401];
}
public function listBordereauFolder(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"field id is required","statut"=>false,"data"=>"","code"=>401];
if(!array_key_exists("type",$data)) return ["message"=>"field type is required","statut"=>false,"data"=>"","code"=>401];
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$bordereau = $this->em->getRepository(Bordereau::class)->findOneBy(["id"=>$data["id"]]);
if(is_null($bordereau)) return ["message"=>"bordereau not found","statut"=>false,"data"=>"","code"=>404];
$total = $this->em->getRepository(Dossier::class)->findForBordereauNb($data['search']['value'],$data["id"],$data["type"], $this->currenUser->getLevel());
$folders = $this->em->getRepository(Dossier::class)->findForBordereau($data['search']['value'],$data["id"],$data["type"],$this->currenUser->getLevel(),$offset,$limit);
$res =[];
foreach ($folders as $f)
{
$res[] = $f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function editFolder(array $data)
{
$req=["type_confidentialite",
"type","description","titre",
"cote_dossier","observation","date_cloture","date_type",
"date_creation","langue","added_files","remove_files","id","location","boite","ref_int"];
/*$reqObli=["service_verseur","service_producteur","type",
"titre","cote_dossier","date_cloture",
"date_creation","langue","date_depot","date_versement","date_type","id"];*/
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>401];
}
/* foreach ($reqObli as $el)
{
if(empty($data[$el])) return ["message"=>$el." field is empty","statut"=>false,"code"=>""];
}*/
$dossier = $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($dossier)) return ["message"=>"folder not found","statut"=>false,"code"=>401];
$type = $this->em->getRepository(TypeDossier::class)->findOneBy(array("id"=>$data["type"]));
if(is_null($type)) return ["message"=>"type dossier not found","statut"=>false,"code"=>401];
$conf = $this->em->getRepository(TypeConfidentialite::class)->findOneBy(array("id"=>$data["type_confidentialite"]));
if(is_null($conf)) return ["message"=>"type confidentialite not found","statut"=>false,"code"=>401];
$cadre = $this->em->getRepository(CadreClassement::class)->findOneBy(array("id"=>$data["cote_dossier"]));
if(is_null($cadre)) return ["message"=>"cadre de classement not found","statut"=>false,"code"=>401];
$boite = $this->em->getRepository(Boite::class)->findOneBy(array("id"=>$data["boite"]));
if(is_null($boite)) return ["message"=>"box not found","statut"=>false,"code"=>401];
if(array_key_exists("parent_folder",$data) ){
if(strlen($data["parent_folder"])>0){
$parentFolder = $this->em->getRepository(Dossier::class)->findOneBy(["reference"=>$data["parent_folder"]]);
if($parentFolder===null){
return ["message"=>$this->container->get('translator')->trans("parent_folder_not_found"),"statut"=>false,"code"=>""];
}
$dossier->setDossierParent($parentFolder);
}else{
$dossier->setDossierParent(null);
}
}
$dossier->setType($type);
$dossier->setTitre($data["titre"]);
$dossier->setObservation($data["observation"]);
$dossier->setLocalisation($data["location"]);
$dossier->setLangue($data["langue"]);
$dossier->setCadreClassement($cadre);
$dossier->setBoite($boite);
$dossier->setRefInterne($data["ref_int"]);
$dossier->setCoteDossier($cadre->getCode());
$dossier->setDescription($data["description"]);
$dossier->setTypeConfidentialite($conf);
$df = $data["date_cloture"];
$dc = $data["date_creation"];
switch ($data["date_type"])
{
case 0:
$df = $data["date_cloture"];
$dc = $data["date_creation"];
break;
case 1:
if($data["date_cloture"] != ""){
$df = "01/".$data["date_cloture"];
}
$dc = "01/".$data["date_creation"];
break;
case 2:
if($data["date_cloture"] != ""){
$df = "01/01/".$data["date_cloture"];
}
$dc = "01/01/".$data["date_creation"];
break;
}
$dossier->setDateCreation(\DateTime::createFromFormat('d/m/Y',$dc));
if($df != ""){
$dossier->setDateCloture(\DateTime::createFromFormat('d/m/Y',$df));
}
else{
$dossier->setDateCloture(null);
}
if(array_key_exists('category',$data)){
$dossier->setCategory((int)$data['category']);
}
$dossier->setDateType($data["date_type"]);
$totalFile= $dossier->getNbPiece();
foreach ($data["remove_files"] as $id)
{
$file = $this->em->getRepository(Fichier::class)->findOneBy(array("id"=>$id));
if(!is_null($file))
{
$dossier->removeFichier($file);
$totalFile--;
}
}
foreach ($data["added_files"] as $f)
{
$file = new Fichier();
$file->setNom($f["name"]);
$file->setFolderNameAndName($dossier->getTitre()." | ". $f["name"]);
$file->setExtension($f["extension"]);
$file->setType($f["type"]);
$file->setTaille($f["size"]);
$file->setPath($f["path"]);
$file->setAuteur($data["user"]->getNom()." ".$data["user"]->getPrenom());
$file->setDossier($dossier);
$dossier->addFichier($file);
$totalFile++;
}
if(array_key_exists("updated_files",$data)){
foreach ($data["updated_files"] as $file)
{
foreach ($dossier->getFichiers() as $f){
if($f->getId() === (int)$file['id'] ){
$f->setNom($file['name']);
$f->setFolderNameAndName($dossier->getTitre()." | ". $file["name"]);
}
}
}
}
foreach ($dossier->getFichiers() as $f){
$f->setFolderNameAndName($dossier->getTitre()." | ". $f->getNom());
}
$dossier->setNbPiece($totalFile);
$dossier->setIsActive(1);
$this->em->persist($dossier);
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT70'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($dossier->getId());
$this->em->persist($log);
}
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$dossier->toArray()];
}
public function saveMultipleFolder(array $data)
{
if(!array_key_exists("file",$data)) return ["message"=>"file field is required","statut"=>false,"code"=>401];
if(!array_key_exists("bordereau",$data)) return ["message"=>"bordereau field is required","statut"=>false,"code"=>401];
$bordereau = $this->em->getRepository(Bordereau::class)->findOneBy(['numero'=>$data['bordereau']]);
if($bordereau ===null ) return ["message"=>"bordereau not found","statut"=>false,"code"=>""];
$file =$this->container->get('upload_service')->uploadBase64($data["file"]);
if($file["statut"]==false) return ["message"=>"error_file_upload","statut"=>false,"code"=>401];
if(!in_array(strtolower($file["file"]["encoding"]),["utf-8","iso-8859-1"]))
{
$f = $this->container->get('upload_service')->getTargetDirectory()."/FOLDER/".$file["file"]["path"];
unlink($f);
return ["message"=>$this->container->get('translator')->trans("bad_encoding")." ".$file["file"]["encoding"],"statut"=>false,"code"=>401];
}
$f = $this->container->get('upload_service')->getTargetDirectory()."/FOLDER/".$file["file"]["path"];
$fileError = fopen($this->container->get('upload_service')->getImportDirectory()."file_error.txt", "a");
file_put_contents($this->container->get('upload_service')->getImportDirectory()."file_error.txt",'');
$fp = fopen($f, "r");
$firstLine = fgets($fp);
rewind($fp);
// BOM cleanup si nécessaire
$bom = "\xEF\xBB\xBF";
if (strncmp($firstLine, $bom, 3) === 0) {
$firstLine = substr($firstLine, 3);
}
$delimiter = ','; // défaut
$semicolonCount = substr_count($firstLine, ';');
$commaCount = substr_count($firstLine, ',');
if ($semicolonCount > $commaCount) {
$delimiter = ';';
}
$i=0;
$tab=[];
while (($datai = fgetcsv($fp, 10000, $delimiter)) !== FALSE) {
$tab[] = $datai;
}
$j=0;
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT38'));
$this->em->getConnection()->beginTransaction();
foreach ($tab as $index=> $r) {
if($index>0){
$j++;
if(count($r)==12) {
$type = $this->em->getRepository(TypeDossier::class)->findOneBy(array("code"=>trim($r[1])));
if(is_null($type)) return ["message"=>"type dossier not found","statut"=>false,"code"=>""];
$b = $bordereau;
$conf = $this->em->getRepository(TypeConfidentialite::class)->findOneBy(array("niveau"=>1));
if(is_null($conf)) return ["message"=>"type confidentialite not found","statut"=>false,"code"=>""];
$cadre = $this->em->getRepository(CadreClassement::class)->findOneBy(array("code"=>trim($r[9])));
if(is_null($cadre)) return ["message"=>"cadre de classement not found","statut"=>false,"code"=>""];
$boite = $this->em->getRepository(Boite::class)->findOneBy(array("code"=>trim($r[8])));
if(is_null($boite)) return ["message"=>"box not found","statut"=>false,"code"=>""];
$parentFolder = null;
if(trim($r[11])!==""){
$parentFolders = $this->em->getRepository(Dossier::class)->findBy(array("refInterne"=>trim($r[11])));
if(count($parentFolders)==0){
return ["message"=>$this->container->get('translator')->trans('parent_folder_not_found')." ".trim($r[11]),"statut"=>false,"code"=>""];
}elseif (count($parentFolders)==1){
$parentFolder = $parentFolders[0];
}else{
return ["message"=>$this->container->get('translator')->trans('multiple_folder_with_same_ref')." ".trim($r[11]),"statut"=>false,"code"=>""];
}
}
$dossier = new Dossier();
$dossier->setType($type);
$dossier->setDossierParent($parentFolder);
$dossier->setBordereau($b);
$dossier->setTitre(trim($r[2]));
$dossier->setObservation("");
$dossier->setLangue(strtolower(trim($r[4])));
$dossier->setCadreClassement($cadre);
$dossier->setBoite($boite);
$dossier->setOrdreRangement(0);
$dossier->setCoteDossier($cadre->getCode());
$dossier->setDescription(trim($r[3]));
$dossier->setReference($this->generateReference()["data"]);
$dossier->setRefInterne(trim($r[0]));
//$dossier->setCategory((int)trim($r[10]));
$dossier->setTypeConfidentialite($conf);
$dossier->setStatut(0);
try{
$df = $r[7];
$dc = $r[6];
switch ($r[5])
{
case 0:
$df = $r[7];
$dc = $r[6];
break;
case 1:
if($r[7] != ""){
$df = "01/".$r[7];
}
$dc = "01/".$r[6];
break;
case 2:
if($r[7] != ""){
$df = "01/01/".$r[7];
}
$dc = "01/01/".$r[6];
break;
}
$dossier->setCategory((int)$r[10]);
switch ($dossier->getCategory()){
case 1:
if($r[7] != ""){
$dossier->setDateCloture(\DateTime::createFromFormat('d/m/Y',$df));
}
else{
$dossier->setDateCloture(null);
}
$dossier->setDateCreation(\DateTime::createFromFormat('d/m/Y',$dc));
break;
default:
$dossier->setDateCloture(\DateTime::createFromFormat('d/m/Y',$df));
$dossier->setDateCreation(\DateTime::createFromFormat('d/m/Y',$dc));
break;
}
$dossier->setDateType((int)trim($r[5]));
$this->em->persist($dossier);
if(!is_null($operation))
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($dossier->getId());
$this->em->persist($log);
}
}
catch (\Exception $e)
{
//return ["message"=>$e->getMessage()." ".$e->getFile()."line ".$e->getLine() ,"statut"=>false,"code"=>401];
return ["message"=>$e->getMessage().$e->getLine() ,"statut"=>false,"code"=>401];
}
catch (\Error $e)
{
//return ["message"=>$e->getMessage()." ".$e->getFile()."line ".$e->getLine() ,"statut"=>false,"code"=>401];
return ["message"=>$e->getMessage() ,"statut"=>false,"code"=>401];
}
}else{
return ["message"=>$this->container->get('translator')->trans('file_incorrect'),"statut"=>false,"code"=>401];
}
}
}
try{
$this->em->flush();
$this->em->getConnection()->commit();
}
catch (\Exception $e)
{
$this->em->getConnection()->rollBack();
return ["message"=>$e->getMessage()." ".$e->getFile()."line ".$e->getLine(),"statut"=>false,"code"=>401];
}
fclose($fp);
unlink($f);
return ["message"=>$this->container->get('translator')->trans("folder_saved")." : ".$j,"statut"=>true, "code"=>201,"data"=>[]];
}
public function markFolderAsEnded(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>401];
$dossier = $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($dossier)) return ["message"=>"folder not found","statut"=>false,"code"=>401];
$dossier->setStatut(true);
$this->em->persist($dossier);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT62'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($dossier->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"operation_done","data"=>$dossier->toArray(), "statut"=>true,"code"=>201];
}
public function depositHistory(array $data)
{
if(!array_key_exists("start_date",$data)) return ["message"=>"start_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("end_date",$data)) return ["message"=>"end_date field is required","statut"=>false,"code"=>401];
$s = \DateTime::createFromFormat('d/m/Y',$data["start_date"]);
$e = \DateTime::createFromFormat('d/m/Y',$data["end_date"]);
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$level = $this->currenUser->getLevel();
$total = $this->em->getRepository(Dossier::class)->findHistoryNb($level,$data["bordereau"],$s->format("Y-m-d"),$e->format("Y-m-d"));
$dossiers = $this->em->getRepository(Dossier::class)->findHistory($level,$data["bordereau"],$s->format("Y-m-d"),$e->format("Y-m-d"),$offset,$limit);
$res=[];
foreach ($dossiers as $d)
{
$res[]=$d->toArray();
}
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT39'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function folderToDelete()
{
$regles = $this->em->getRepository(RegleConservation::class)->findBy(array("isActive"=>true,"sortFinal"=>"1"));
$ty=[];
$types=[];
$final=[];
foreach ($regles as $r)
{
$types[]=$r->getTypeDossier()->getId();
switch ($r->getDureeDossier()->getTypeConsevation())
{
case DureeDossier::ANNEE:
$nb=$r->getDureeDossier()->getConservation();
$add = 365*$nb;
$ty["type_".$r->getTypeDossier()->getId()]=$add;
break;
case DureeDossier::MOIS:
$nb=$r->getDureeDossier()->getConservation();
$ty["type_".$r->getTypeDossier()->getId()]=30*$nb;
break;
case DureeDossier::SEMAINE:
$nb=$r->getDureeDossier()->getConservation();
$add = 7*$nb;
$ty["type_".$r->getTypeDossier()->getId()]=$add;
break;
case DureeDossier::JOUR:
$nb=$r->getDureeDossier()->getConservation();
$ty["type_".$r->getTypeDossier()->getId()]=$nb;
break;
default:
$ty["type_".$r->getTypeDossier()->getId()]=365*4;
break;
}
}
$level = $this->currenUser->getLevel();
$all = $this->em->getRepository(Dossier::class)->findForDelete($level,$types);
foreach ($all as $d)
{
$date = new \DateTime();
$tocompare = $d->getDateCreation();
$diff = $date->diff($tocompare)->days;
if($diff>$ty["type_".$d->getType()->getId()])
{
$final[]=$d;
}
}
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT52'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$this->em->persist($log);
$this->em->flush();
}
return $final;
}
public function generateReference2()
{
$ref="BDEL";
$date = new \DateTime();
$ref = $ref.strtoupper($date->format("Y")).strtoupper(uniqid('', false));
return ["message"=>"","statut"=>true,"data"=>$ref];
}
public function generateReference3()
{
$ref="DEM";
$date = new \DateTime();
$ref = $ref.strtoupper($date->format("Y")).strtoupper(uniqid('', false));
return ["message"=>"","statut"=>true,"data"=>$ref];
}
public function deleteFolder(array $data)
{
$req =["reference","numero","date_decision","dossiers"];
foreach ($req as $r)
{
if(!array_key_exists($r,$data)) return ["message"=>$r." field is required","statut"=>false,"code"=>401];
}
$nb=0;
$el = new Elimination();
foreach ($data["dossiers"] as $i)
{
$d= $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$i,"isActive"=>true));
if(!is_null($d)){
$d->setIsActive(false);
$nb++;
$el->addDossier($d);
}
}
$el->setReference($data["reference"]);
$el->setNumero($data["numero"]);
$el->setDateDecision(\DateTime::createFromFormat('d/m/Y',$data["date_decision"]));
if($nb==0)
{
return ["message"=>"no folder selected, please try again","statut"=>false,"code"=>401];
}
else
{
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT54'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($el->getReference());
$this->em->persist($log);
$this->em->flush();
}
$this->em->persist($el);
$this->em->flush();
return ["message"=>"operation_done","statut"=>true,"code"=>201,"data"=>[]];
}
}
public function deleteFolderHistory(array $data)
{
if(!array_key_exists("start_date",$data)) return ["message"=>"start_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("end_date",$data)) return ["message"=>"end_date field is required","statut"=>false,"code"=>401];
$s = \DateTime::createFromFormat('d/m/Y',$data["start_date"]);
$e = \DateTime::createFromFormat('d/m/Y',$data["end_date"]);
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$total = $this->em->getRepository(Elimination::class)->findHistoryNb( $s->format("Y-m-d h:i:s"),$e->format("Y-m-d"));
$eli = $this->em->getRepository(Elimination::class)->findHistory( $s->format("Y-m-d h:i:s"),$e->format("Y-m-d"),$offset,$limit);
$res=[];
foreach ($eli as $e)
{
$ds= $e->getDossiers();
foreach ($ds as $d)
{
$t=$d->toArray();
$t["ref_eli"]=$e->getReference();
$res[]=$t;
}
}
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT55'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function advancedSearch(array $data)
{
$req=["bordereau","cote","titre","localisation","type_dossier","reference","langue","date_type","start_date","end_date"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>401];
}
if($data["start_date"]!="")
{
if(preg_match("/^[a-zA-Z]+$/", $data["start_date"])==false){
switch ($data["date_type"])
{
case 0:
$d = \DateTime::createFromFormat('d/m/Y',$data["start_date"]);
$data["start_date"] =$d->format("Y-m-d")." 00:00:01";
$data["start_date_1"] =$d->format("Y-m-d");
$data["start_date_2"] =$d->format("Y-m-d")." 23:59:59";
break;
case 1:
$d = \DateTime::createFromFormat('d/m/Y',"01/".$data["start_date"]);
$da = clone $d;
$d2 = $da->add(new \DateInterval('P31D'));
$data["start_date"] =$d->format("Y-m-d")." 00:00:01";
$data["start_date_1"] =$d->format("Y-m-d");
$data["start_date_2"] =$d2->format("Y-m-d")." 23:59:59";
break;
case 2:
$d = \DateTime::createFromFormat('d/m/Y',"01/01/".$data["start_date"]);
$d2 = \DateTime::createFromFormat('d/m/Y',"31/12/".$data["start_date"]);
$data["start_date"] =$d->format("Y-m-d")." 00:00:01";
$data["start_date_1"] =$d->format("Y-m-d");
$data["start_date_2"] =$d2->format("Y-m-d")." 23:59:59";
break;
}
}
}
if($data["end_date"]!="")
{
if(preg_match("/^[a-zA-Z]+$/", $data["end_date"])==false){
switch ($data["date_type"])
{
case 0:
$d = \DateTime::createFromFormat('d/m/Y',$data["end_date"]);
$data["end_date"] =$d->format("Y-m-d")." 00:00:01";
$data["end_date_1"] =$d->format("Y-m-d");
$data["end_date_2"] =$d->format("Y-m-d")." 23:59:59";
break;
case 1:
$d = \DateTime::createFromFormat('d/m/Y',"01/".$data["end_date"]);
$da = clone $d;
$d2 = $da->add(new \DateInterval('P31D'));
$data["end_date"] =$d->format("Y-m-d")." 00:00:01";
$data["end_date_1"] =$d->format("Y-m-d");
$data["end_date_2"] =$d2->format("Y-m-d")." 23:59:59";
break;
case 2:
$d = \DateTime::createFromFormat('d/m/Y',"01/01/".$data["end_date"]);
$d2 = \DateTime::createFromFormat('d/m/Y',"31/12/".$data["end_date"]);
$data["end_date"] =$d->format("Y-m-d")." 00:00:01";
$data["end_date_1"] =$d->format("Y-m-d");
$data["end_date_2"] =$d2->format("Y-m-d")." 23:59:59";
break;
}
}
}
//$da = $this->em->getRepository(Dossier::class)->findAdvanced($level,$data);
$level = $this->currenUser->getLevel();
try {
$da = $this->container->get(FOSElasticSearchService::class)->searchAdvanced($data,$level);
}
catch (\Exception $e){
return ["message"=>$e->getMessage(),"data"=>[], "statut"=>false,"code"=>401];
}
$res=[];
foreach ($da as $d)
{
$res[]=$d->toArray();
}
return ["message"=>"operation_done","data"=>$res, "statut"=>true,"code"=>201];
}
public function showCadreFolder(array $data)
{
if(!array_key_exists('id',$data)) return ["message"=>"id field is required","statut"=>false,"code"=>401];
$level = $this->currenUser->getLevel();
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$total = $this->em->getRepository(Dossier::class)->findForCadreNb($data["id"],$level);
$folders = $this->em->getRepository(Dossier::class)->findForCadre($data["id"],$level,$offset,$limit);
$res=[];
foreach ($folders as $f)
{
$res[]=$f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function makeRequest(array $data)
{
$req=["motif","start_date","end_date","folders"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>401];
}
$folders=[];
foreach ($data["folders"] as $id)
{
$f = $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$id));
if(!is_null($f)) $folders[]=$f;
}
//if(count($folders)==0) return ["message"=>"no folder founded","statut"=>false,"code"=>401];
try{
$s = \DateTime::createFromFormat('d/m/Y',$data["start_date"]);
$e = \DateTime::createFromFormat('d/m/Y',$data["end_date"]);
$demande= new DemandeArchive();
$demande->setReference($this->generateReference3()["data"]);
$demande->setStatut(false);
$demande->setStartDate($s);
$demande->setEndDate($e);
if(array_key_exists("type",$data))
{
if(!array_key_exists("acteur",$data)) return ["message"=>"acteur field is required","statut"=>false,"code"=>401];
$ac = $this->em->getRepository(ActeurExterne::class)->findOneBy(array("id"=>$data["acteur"]["id"]));
if(is_null($ac)) return ["message"=>"actor not found","statut"=>false,"code"=>401];
$demande->setUserType(DemandeArchive::USEREXTERNE);
$demande->setActeurExterne($ac);
}
else {
$demande->setUserType(DemandeArchive::USERINTERNE);
$demande->setUser($this->currenUser);
}
$demande->setMotif($data["motif"]);
foreach ($folders as $f)
{
$do = new DossierDemande();
$do->setStatut(false);
$do->setDossier($f);
$do->setDemande($demande);
$this->em->persist($do);
}
$notif = new Notification();
$notif->setUser($this->currenUser);
$notif->setDemandeArchive($demande);
$notif->setCode(Notification::NEW_DEMANDE);
$admins = $this->em->getRepository(User::class)->loadUserManageArchive();
$userNotif = [];
if(count($admins)>0){
foreach ($admins as $a){
$status = new Statut();
$status->setNotification($notif);
$status->setUser($a);
$notif->addStatut($status);
$userNotif[]=$a->getId();
}
}
else{
$ad = $this->em->getRepository(User::class)->findOneBy(array("type"=>1));
if(!is_null($ad))
{
$status = new Statut();
$status->setNotification($notif);
$status->setUser($ad);
$notif->addStatut($status);
$userNotif[]=$ad->getId();
}
}
$this->em->persist($notif);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT46'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($demande->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"operation_done","data"=>$demande->toArray(), "statut"=>true,"code"=>201,'notif_user'=>$userNotif];
}
catch (\Exception $e)
{
return ["message"=>$e->getMessage(),"statut"=>false,"code"=>401];
}
}
public function showRequest(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>401];
$demande =$this->em->getRepository(DemandeArchive::class)->findOneBy(array("isActive"=>true,"id"=>$data["id"]));
if(is_null($demande)) return ["message"=>"demande not found","statut"=>false,"code"=>401];
$answer = $this->em->getRepository(EmpruntArchive::class)->findOneBy(array("isActive"=>true,"demande"=>$demande));
$res=["demande"=>$demande->toArray(),"answer"=>null,"folders"=>[]];
if(!is_null($answer)) $res["answer"] = $answer->toArray();
$dossiers= $this->em->getRepository(DossierDemande::class)->findBy(array("isActive"=>true,"demande"=>$demande));
foreach ($dossiers as $d)
{
$res["folders"][]=$d->toArray();
}
if($demande->getStatut()==0)
{
if($this->currenUser->getType()==1)
{
$demande->setStatut(1);
$this->em->persist($demande);
$this->em->flush();
}
}
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT47'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($demande->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"operation_done","data"=>$res, "statut"=>true,"code"=>201];
}
public function answerRequest(array $data)
{
$req=["motif","answer","id"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>401];
}
$demande =$this->em->getRepository(DemandeArchive::class)->findOneBy(array("isActive"=>true,"id"=>$data["id"]));
if(is_null($demande)) return ["message"=>"demande not found","statut"=>false,"code"=>401];
if($demande->getStatut() ==2 || $demande->getStatut() ==3) return ["message"=>"operation denied","statut"=>false,"code"=>401];
$code=DemandeArchive::DEMANDE_ACCEPTED;
switch ($data["answer"])
{
case 2:
$code= DemandeArchive::DEMANDE_ACCEPTED;
break;
case 3:
$code= DemandeArchive::DEMANDE_REFUSED;
break;
}
$demande->setStatut($code);
$em = new EmpruntArchive();
$em->setDemande($demande);
$em->setObservation($data["motif"]);
$em->setStatus(0);
$notif = new Notification();
$notif->setUser($this->currenUser);
$notif->setEmpruntArchive($em);
$notif->setCode($code);
$ad = $demande->getUser();
if(!is_null($ad))
{
$status = new Statut();
$status->setNotification($notif);
$status->setUser($ad);
$notif->addStatut($status);
}
$this->em->persist($em);
$this->em->persist($notif);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT49'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($demande->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"operation_done","data"=>$demande->toArray(), "statut"=>true,"code"=>201];
}
public function updateRequest(array $data)
{
$req=["date_type","date","id"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>401];
}
$demande =$this->em->getRepository(DemandeArchive::class)->findOneBy(array("isActive"=>true,"id"=>$data["id"]));
if(is_null($demande)) return ["message"=>"demande not found","statut"=>false,"code"=>401];
//if($demande->getStatut() <2) return ["message"=>"operation denied","statut"=>false,"code"=>401];
$em=$this->em->getRepository(EmpruntArchive::class)->findOneBy(array("isActive"=>true,"demande"=>$demande));
if(is_null($em)) return ["message"=>"demande answer not found","statut"=>false,"code"=>401];
try{
switch ($data["date_type"])
{
case 'out':
$em->setOutDate(\DateTime::createFromFormat('d/m/Y',$data["date"]));
break;
case 'back':
$em->setBackDate(\DateTime::createFromFormat('d/m/Y',$data["date"]));
break;
}
$this->em->persist($em);
$this->em->flush();
}
catch (\Exception $e)
{
return ["message"=>$e->getMessage(),"statut"=>false,"code"=>401];
}
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT48'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($demande->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"operation_done","data"=>[], "statut"=>true,"code"=>201];
}
public function moveFolder(array $data)
{
if(!array_key_exists("ref",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>401];
if(!array_key_exists("cadre",$data)) return ["message"=>"cadre field is required","statut"=>false,"code"=>401];
$dossier = $this->em->getRepository(Dossier::class)->findOneBy(array("reference"=>$data["ref"]));
if(is_null($dossier)) return ["message"=>"dossier not found","statut"=>false,"code"=>401];
$cadre = $this->em->getRepository(CadreClassement::class)->findOneBy(array("code"=>$data["cadre"]));
if(is_null($cadre)) return ["message"=>"cadre not found","statut"=>false,"code"=>401];
$dossier->setCadreClassement($cadre);
$dossier->setCoteDossier($cadre->getCode());
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT58'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($dossier->getId());
$this->em->persist($log);
}
$this->em->persist($dossier);
$this->em->flush();
return ["message"=>"","data"=>$dossier->toArray(),"statut"=>true,"code"=>201];
}
public function requestFolderHistory(array $data)
{
if(!array_key_exists("start_date",$data)) return ["message"=>"start_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("end_date",$data)) return ["message"=>"end_date field is required","statut"=>false,"code"=>401];
$s = \DateTime::createFromFormat('d/m/Y',$data["start_date"]);
$e = \DateTime::createFromFormat('d/m/Y',$data["end_date"]);
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$total = $this->em->getRepository(DemandeArchive::class)->findHistoryNb($s->format("Y-m-d"),$e->format("Y-m-d"));
$eli = $this->em->getRepository(DemandeArchive::class)->findHistory($s->format("Y-m-d"),$e->format("Y-m-d"),$offset,$limit);
$res=[];
foreach ($eli as $e)
{
$t=["demande"=>$e->toArray(),"answer"=>null];
if($e->getStatut()>1)
{
$r = $this->em->getRepository(EmpruntArchive::class)->findOneBy(array("demande"=>$e));
if(!is_null($r)) $t["answer"] = $r->toArray();
}
$res[]=$t;
}
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT55'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
private function getDatesFromRange($start, $end, $format = 'Y-m-d') {
// Declare an empty array
$array = array();
// Variable that store the date interval
// of period 1 day
$interval = new \DateInterval('P1D');
$realEnd = new \DateTime($end);
$realEnd->add($interval);
$period = new \DatePeriod(new \DateTime($start), $interval, $realEnd);
// Use loop to store date into array
foreach($period as $date) {
$array[] = $date->format($format);
}
// Return the array elements
return $array;
}
public function getStatistic(array $data)
{
if(!array_key_exists("start_date",$data)) return ["message"=>"start_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("end_date",$data)) return ["message"=>"end_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("type_filter",$data)) return ["message"=>"type_filter field is required","statut"=>false,"code"=>401];
if(!array_key_exists("type",$data)) return ["message"=>"type field is required","statut"=>false,"code"=>401];
$s = \DateTime::createFromFormat('d.m.Y',$data["start_date"])->format("Y-m-d");
$e = \DateTime::createFromFormat('d.m.Y',$data["end_date"])->format("Y-m-d");
$res=[];
switch ($data["type"])
{
case 1:
//pyramide des dossiers
if($data["type_filter"]==1)
{
$folders= $this->em->getRepository(Dossier::class)->findStatSimple($s,$e);
$total = 0;
$ls = $this->em->getRepository(CadreClassement::class)->findBy(array("isActive"=>true,"niveau"=>1));
$levels =[];
foreach ($ls as $l)
{
$levels["cadre_".$l->getId()] = 0;
}
foreach ($folders as $f)
{
$code = "cadre_".$f->getCadreClassement()->getId();
if(array_key_exists($code,$levels))
{
$levels[$code]++;
$total++;
}
}
if($total==0) $total=1;
foreach ($ls as $l)
{
$res[]=["name"=>$l->getCode()." : ".$l->getNomFr(),"value"=>round($levels["cadre_".$l->getId()]/$total,2)*100];
}
}
elseif ($data["type_filter"]==3)
{
$folders= $this->em->getRepository(Dossier::class)->findStatSimple($s,$e);
$total = count($folders);
$total2=0;
$delete=0;
$save=0;
$none=0;
foreach ($folders as $f)
{
$re = $this->em->getRepository(RegleConservation::class)->findOneBy(array("typeDossier"=>$f->getType()));
if(!is_null($re))
{
$total2++;
if($re->getSortFinal()==0)$save++;
else $delete++;
}
else $none++;
}
if($total==0){
$res=[
["name"=>$this->container->get('translator')->trans("regle_delete"),"value"=>0],
["name"=>$this->container->get('translator')->trans("regle_save"),"value"=>0],
["name"=>$this->container->get('translator')->trans("regle_none"),"value"=>0]
];
}
else{
$res=[
["name"=>$this->container->get('translator')->trans("regle_delete"),"value"=>round($delete/$total,2)*100],
["name"=>$this->container->get('translator')->trans("regle_save"),"value"=>round($save/$total,2)*100],
["name"=>$this->container->get('translator')->trans("regle_none"),"value"=>round($none/$total,2)*100]
];
}
}
elseif ($data["type_filter"]==2)
{
$folders= $this->em->getRepository(Dossier::class)->findStatSimple($s,$e);
$total = count($folders);
$types=[];
$already=[];
$all=[];
foreach ($folders as $f)
{
if(!in_array($f->getType()->getId(),$already))
{
$already[]=$f->getType()->getId();
$types[]=$f->getType();
$all["type_".$f->getType()->getId()]=1;
}
else
{
$all["type_".$f->getType()->getId()]++;
}
}
if($total==0){
$tys = $this->em->getRepository(TypeDossier::class)->findBy(array("isActive"=>true));
$res=[];
$in=[];
$a=[];
$b=[];
foreach ($tys as $t)
{
if(!in_array($t->getId(),$in))
{
$in[]=$t->getId();
$a[$t->getCode()]=1;
$b[$t->getCode()]=$t->getCode()." : ".$t->getNomFr();
}
else{
$a[$t->getCode()]++;
}
}
if(count($tys)>0)
{
foreach ($a as $key=>$val)
{
$res[]=["name"=>$b[$key],"value"=>$val];
}
}
}
else{
$n = count($types);
for($i=0;$i<$n;$i++)
{
$res[]=["name"=>$types[$i]->getCode()." : ".$types[$i]->getNomFr(),"value"=>$all["type_".$types[$i]->getId()]];
}
}
}
else{
$folders= $this->em->getRepository(Dossier::class)->findStatSimple($s,$e);
$total = count($folders);
$done=0;
$await=0;
foreach ($folders as $f)
{
if($f->getStatut()==0)$await++;
else $done++;
}
if($total==0){
$res=[
["name"=>$this->container->get('translator')->trans("vers_treated"),"value"=>0],
["name"=>$this->container->get('translator')->trans("vers_not_treated"),"value"=>0]];
}
else{
$res=[
["name"=>$this->container->get('translator')->trans("vers_treated"),"value"=>round($done/$total,2)*100],
["name"=>$this->container->get('translator')->trans("vers_not_treated"),"value"=>round($await/$total,2)*100]];
}
}
break;
case 2:
//courbe de versement
$dossiers = $this->em->getRepository(Dossier::class)->findStatSimple($s,$e);
$res=[];
$res["dates"]=$this->getDatesFromRange($s, $e);
$res["x"][]='Dates';
foreach ($res["dates"] as $t)
{
$res["x"][]=$t;
}
$dates=$this->getDatesFromRange($s, $e);
if($data["type_filter"]==1)
{
$ls = $this->em->getRepository(CadreClassement::class)->findBy(array("isActive"=>true,"niveau"=>1));
$types =[];
$typesName=[];
$codes=[];
foreach ($ls as $l)
{
$codes[$l->getCode()]=$l->getId();
$types["cadre_".$l->getId()] = [];
$typesName["cadre_".$l->getId()]=$l;
foreach ($dates as $t)
{
$types["cadre_".$l->getId()][$t]=0;
}
}
foreach ($dossiers as $d)
{
foreach ($codes as $k=>$v){
if(strpos($d->getCoteDossier(), $k) !== false){
$types["cadre_".$v][$d->getDate()->format("Y-m-d")]++;
}
}
/*if(array_key_exists($d->getCoteDossier(),$codes)){
$types["cadre_".$codes['']][$d->getDate()->format("Y-m-d")]++;
}
if($d->getCadreClassement()->getNiveau()==1)
{
$types["cadre_".$d->getCadreClassement()->getId()][$d->getDate()->format("Y-m-d")]++;
}*/
}
$res["type"]=1;
$res["data"] =[];
foreach ($types as $key=>$val)
{
$tab=[];
$tab[]=$key;
foreach ($val as $v)
{
$tab[]=$v;
}
$res["data"][]=$tab;
}
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
$ta[]=$typesName[$t[0]]->getNomFr();
for($j=1;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
$res["data"]=$main;
}
elseif ($data["type_filter"]==2)
{
$types=[];
$in=[];
//$aty=[];
$res["type"]=2;
$res["data"] =[];
foreach ($dossiers as $d)
{
if(!in_array($d->getType()->getId(),$in))
{
$in[]=$d->getType()->getId();
$types[$d->getType()->getNomFr()]=[];
$dates=$this->getDatesFromRange($s, $e);
foreach ($dates as $t)
{
$types[$d->getType()->getNomFr()][$t]=0;
}
// $aty[]=$d->getType()->getNomFr();
}
}
foreach ($dossiers as $d)
{
$types[$d->getType()->getNomFr()][$d->getDate()->format("Y-m-d")]++;
}
foreach ($types as $key=>$val)
{
$tab=[];
$tab[]=$key;
foreach ($val as $v)
{
$tab[]=$v;
}
$res["data"][]=$tab;
}
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
for($j=0;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
$res["data"]=$main;
//var_dump($res);
}
elseif ($data["type_filter"]==3)
{
$res["type"]=3;
$res["data"] =[];
$types=["sort0"=>[],"sort1"=>[],"sort2"=>[]];
$dates=$this->getDatesFromRange($s, $e);
foreach ($dates as $t)
{
$types["sort0"][$t]=0;
$types["sort1"][$t]=0;
$types["sort2"][$t]=0;
}
foreach ($dossiers as $d)
{
$r = $this->em->getRepository(RegleConservation::class)->findOneBy(array("typeDossier"=>$d->getType()));
if(!is_null($r) && $r->getSortFinal()!="2")
{
$types["sort".$r->getSortFinal()][$d->getDate()->format("Y-m-d")]++;
}
else
{
$types["sort2".$r->getSortFinal()][$d->getDate()->format("Y-m-d")]++;
}
}
foreach ($types as $key=>$val)
{
$tab=[];
if($key =="sort0") $tab[]=$this->container->get("translator")->trans("regle_save");
elseif ($key == "sort1") $tab[]=$this->container->get("translator")->trans("regle_delete");
else $tab[]=$this->container->get("translator")->trans("regle_none");
foreach ($val as $v)
{
$tab[]=$v;
}
$res["data"][]=$tab;
}
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
for($j=0;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
$res["data"]=$main;
}
else{
$res["data"]=[];
$res["type"]=0;
$types=[];
$dates=$this->getDatesFromRange($s, $e);
foreach ($dates as $t)
{
$types[$t]=0;
}
foreach ($dossiers as $d)
{
$types[$d->getDate()->format("Y-m-d")]++;
}
$tab=[];
$tab[]="general";
foreach ($types as $key=>$val)
{
$tab[]=$val;
}
$res["data"][]=$tab;
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
for($j=0;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
$res["data"]=$main;
}
break;
case 3:
//disque des dossiers
$folders= $this->em->getRepository(Dossier::class)->findStatSimple($s,$e);
if($data["type_filter"]==1)
{
$ls = $this->em->getRepository(CadreClassement::class)->findBy(array("isActive"=>true,"niveau"=>1));
$types =[];
$typesName=[];
foreach ($ls as $l)
{
$types["cadre_".$l->getId()] = 0;
$typesName["cadre_".$l->getId()]=$l;
}
$total=0;
foreach ($folders as $f)
{
if($f->getCadreClassement()->getNiveau()==1)
{
$code = "cadre_".$f->getCadreClassement()->getId();
$types[$code]++;
$total++;
}
}
if($total==0)$total=1;
$res=[];
foreach ($types as $key =>$val)
{
$res[]=[$typesName[$key]->getNomFr(),round($val/$total,2)*100];
}
}
elseif ($data["type_filter"]==2)
{
$types=[];
$in=[];
$aty=[];
foreach ($folders as $d)
{
if(!in_array($d->getType()->getId(),$in))
{
$in[]=$d->getType()->getId();
$types[$d->getType()->getCode()]=1;
$aty[$d->getType()->getCode()]=$d->getType()->getNomFr();
}
else
{
$types[$d->getType()->getCode()]++;
}
}
$res=[];
foreach ($aty as $k => $v)
{
$res[]=[$v,$types[$k]];
}
}
elseif ($data["type_filter"]==3)
{
$ok=0;
$no=0;
$none=0;
foreach ($folders as $f)
{
$r = $this->em->getRepository(RegleConservation::class)->findOneBy(array("typeDossier"=>$f->getType()));
if(!is_null($r))
{
if($r->getSortFinal()==0) $ok++;
else $no++;
}
else $none++;
}
$total = count($folders);
$res=[];
if($total>0)
{
$res[]=[$this->container->get('translator')->trans("regle_save"),$ok];
$res[]=[$this->container->get('translator')->trans("regle_delete"),$no];
$res[]=[$this->container->get('translator')->trans("regle_none"),$none];
}
else
{
$res[]=[$this->container->get('translator')->trans("regle_save"),0];
$res[]=[$this->container->get('translator')->trans("regle_delete"),0];
$res[]=[$this->container->get('translator')->trans("regle_none"),0];
}
}
else
{
$ok=0;
$no=0;
foreach ($folders as $f)
{
if($f->getStatut()==0) $no++;
else $ok++;
}
$total = count($folders);
$res=[];
if($total>0)
{
$res[]=[$this->container->get('translator')->trans("vers_treated"),$ok];
$res[]=[$this->container->get('translator')->trans("vers_not_treated"),$no];
}
else
{
$res[]=[$this->container->get('translator')->trans("vers_treated"),0];
$res[]=[$this->container->get('translator')->trans("vers_not_treated"),0];
}
}
break;
case 4:
//Courbe des recherches
if($data["type_filter"]==1)
{
$dossiers = $this->em->getRepository(Dossier::class)->findBy(array("isActive"=>true));
$months=[];
$label=[];
$value1=[];
$value2=[];
$value3=[];
$level1=[];
$level2=[];
$level3=[];
for ($i = 0; $i <= 11; $i++)
{
$months[date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))] =0 ;
$level1[date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))] =0 ;
$level2[date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))] =0 ;
$level3[date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))] =0 ;
}
foreach ($dossiers as $d)
{
//var_dump($d->getDate()->format("Y-m"));
if(array_key_exists($d->getDate()->format("Y-m"),$months))
{
$months[$d->getDate()->format("Y-m")]++;
if($d->getCadreClassement()->getNiveau()==1)
{
if(array_key_exists($d->getDate()->format("Y-m"),$level1))
{
$level1[$d->getDate()->format("Y-m")]++;
}
}
elseif ($d->getCadreClassement()->getNiveau()==2)
{
if(array_key_exists($d->getDate()->format("Y-m"),$level2))
{
$level2[$d->getDate()->format("Y-m")]++;
}
}
else{
if(array_key_exists($d->getDate()->format("Y-m"),$level3))
{
$level3[$d->getDate()->format("Y-m")]++;
}
}
}
}
foreach ($months as $key=>$val)
{
$label[]=$key;
$value1[]=$level1[$key];
$value2[]=$level2[$key];
$value3[]=$level3[$key];
}
$res=["label"=>$label,"value"=>[$value1,$value2,$value3]];
$res["type"]=1;
}
elseif ($data["type_filter"]==2)
{
$dossiers = $this->em->getRepository(Dossier::class)->findBy(array("isActive"=>true));
$months=[];
$label=[];
$types=[];
$in=[];
$aty=[];
foreach ($dossiers as $d)
{
if(!in_array($d->getType()->getId(),$in))
{
$in[]=$d->getType()->getId();
$types[$d->getType()->getCode()]=[];
$aty[]=$d->getType()->getNomFr();
}
}
for ($i = 0; $i <= 11; $i++)
{
$months[date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))] =0 ;
foreach ($types as $k => $a)
{
$types[$k][date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))]=0;
}
}
foreach ($dossiers as $d)
{
//var_dump($d->getDate()->format("Y-m"));
if(array_key_exists($d->getDate()->format("Y-m"),$months))
{
$months[$d->getDate()->format("Y-m")]++;
$types[$d->getType()->getCode()][$d->getDate()->format("Y-m")]++;
}
}
$values=[];
foreach ($types as $k=>$v)
{
$values[]=array_values($v);
}
foreach ($months as $key=>$val)
{
$label[]=$key;
}
$res=["label"=>$label,"value"=>$values,"types"=>$aty];
$res["type"]=2;
}
elseif ($data["type_filter"]==3)
{
$dossiers = $this->em->getRepository(Dossier::class)->findBy(array("isActive"=>true));
$months=[];
$label=[];
$value1=[];
$value2=[];
$value3=[];
$delete=[];
$save=[];
$none=[];
for ($i = 0; $i <= 11; $i++)
{
$months[date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))] =0 ;
$save[date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))] =0 ;
$delete[date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))] =0 ;
$none[date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))] =0 ;
}
foreach ($dossiers as $d)
{
//var_dump($d->getDate()->format("Y-m"));
if(array_key_exists($d->getDate()->format("Y-m"),$months))
{
$months[$d->getDate()->format("Y-m")]++;
$r = $this->em->getRepository(RegleConservation::class)->findOneBy(array("typeDossier"=>$d));
if(!is_null($r))
{
if($r->getSortFinal()==0) $save[$d->getDate()->format("Y-m")]++;
else $delete[$d->getDate()->format("Y-m")]++;
}
else $none[$d->getDate()->format("Y-m")]++;
}
}
foreach ($months as $key=>$val)
{
$label[]=$key;
$value1[]=$save[$key];
$value2[]=$delete[$key];
$value3[]=$none[$key];
}
$res=["label"=>$label,"value"=>[$value1,$value2,$value3]];
$res["type"]=3;
}
else{
$dossiers = $this->em->getRepository(Dossier::class)->findBy(array("isActive"=>true));
$months=[];
$label=[];
$value=[];
for ($i = 0; $i <= 11; $i++)
{
$months[date("Y-m", strtotime( date( 'Y-m-01' )." -$i months"))] =0 ;
}
foreach ($dossiers as $d)
{
//var_dump($d->getDate()->format("Y-m"));
if(array_key_exists($d->getDate()->format("Y-m"),$months))
{
$months[$d->getDate()->format("Y-m")]++;
}
}
foreach ($months as $key=>$val)
{
$label[]=$key;
$value[]=$val;
}
$res=["label"=>$label,"value"=>$value];
$res["type"]=0;
}
break;
case 5:
//Courbe des consultations
$dossiers = [];
$res=[];
$res["dates"]=$this->getDatesFromRange($s, $e);
$res["x"][]='Dates';
foreach ($res["dates"] as $t)
{
$res["x"][]=$t;
}
$logs= $this->em->getRepository(Log::class)->findStatSimple("MVT42",$s,$e);
$dates=$this->getDatesFromRange($s, $e);
$res["data"] = [];
if($data["type_filter"]==1)
{
$dates=$this->getDatesFromRange($s, $e);
$ls = $this->em->getRepository(CadreClassement::class)->findBy(array("isActive"=>true,"niveau"=>1));
$types =[];
$typesName=[];
foreach ($ls as $l)
{
$types["cadre_".$l->getId()] = [];
$typesName["cadre_".$l->getId()]=$l;
foreach ($dates as $t)
{
$types["cadre_".$l->getId()][$t]=0;
}
}
foreach ($logs as $l)
{
$d = $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$l->getObservation()));
if(!is_null($d))
{
if($d->getCadreClassement()->getNiveau()==1)
{
$types["cadre_".$d->getCadreClassement()->getId()][$l->getDate()->format("Y-m-d")]++;
}
}
};
$res["type"]=1;
foreach ($types as $key=>$val)
{
$tab=[];
$tab[]=$key;
foreach ($val as $v)
{
$tab[]=$v;
}
$res["data"][]=$tab;
}
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
$ta[]=$typesName[$t[0]]->getNomFr();
for($j=1;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
$res["data"]=$main;
}
elseif ($data["type_filter"]==2)
{
$types=[];
$in=[];
$aty=[];
$res["type"]=2;
$res["data"] = [];
$dossiers=[];
foreach ($logs as $l)
{
$d = $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$l->getObservation()));
if(!is_null($d))
{
if(!in_array($d->getType()->getId(),$in))
{
$in[]=$d->getType()->getId();
$types[$d->getType()->getNomFr()]=[];
$dates=$this->getDatesFromRange($s, $e);
foreach ($dates as $t)
{
$types[$d->getType()->getNomFr()][$t]=0;
}
$aty[]=$d->getType()->getNomFr();
}
}
};
foreach ($logs as $l)
{
$d = $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$l->getObservation()));
if(!is_null($d))
{
$types[$d->getType()->getNomFr()][$l->getDate()->format("Y-m-d")]++;
}
};
foreach ($types as $key=>$val)
{
$tab=[];
$tab[]=$key;
foreach ($val as $v)
{
$tab[]=$v;
}
$res["data"][]=$tab;
}
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
for($j=0;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
$res["data"]=$main;
//var_dump($res);
}
elseif ($data["type_filter"]==3)
{
$res["type"]=3;
$res["data"] = [];
$types=["sort0"=>[],"sort1"=>[],"sort2"=>[]];
$dates=$this->getDatesFromRange($s, $e);
foreach ($dates as $t)
{
$types["sort0"][$t]=0;
$types["sort1"][$t]=0;
$types["sort2"][$t]=0;
}
foreach ($logs as $l)
{
$d = $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$l->getObservation()));
if(!is_null($d))
{
$r = $this->em->getRepository(RegleConservation::class)->findOneBy(array("typeDossier"=>$d->getType()));
if(!is_null($r) && $r->getSortFinal()!="2")
{
$types["sort".$r->getSortFinal()][$l->getDate()->format("Y-m-d")]++;
}
else
{
$types["sort2".$r->getSortFinal()][$l->getDate()->format("Y-m-d")]++;
}
}
};
foreach ($types as $key=>$val)
{
$tab=[];
if($key =="sort0") $tab[]=$this->container->get("translator")->trans("regle_save");
elseif ($key == "sort1") $tab[]=$this->container->get("translator")->trans("regle_delete");
else $tab[]=$this->container->get("translator")->trans("regle_none");
foreach ($val as $v)
{
$tab[]=$v;
}
$res["data"][]=$tab;
}
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
for($j=0;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
$res["data"]=$main;
}
else{
$res["type"]=0;
$types=[];
$dates=$this->getDatesFromRange($s, $e);
foreach ($dates as $t)
{
$types[$t]=0;
}
foreach ($logs as $l)
{
$d = $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$l->getObservation()));
if(!is_null($d))
{
$types[$l->getDate()->format("Y-m-d")]++;
}
};
$tab=[];
$tab[]="general";
foreach ($types as $key=>$val)
{
$tab[]=$val;
}
$res["data"][]=$tab;
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
for($j=0;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
$res["data"]=$main;
}
//old
break;
default:
break;
}
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT71'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation("");
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"operation_done","data"=>$res, "statut"=>true,"code"=>201];
}
public function getNotifications(array $data)
{
$lastId1 =0;
if(array_key_exists('last_id',$data)){
$lastId1 = $data['last_id'];
$lastId = $data['last_id'];
}
/*if((int)$lastId1 !== 0){
$status = $this->em->getRepository(Statut::class)->findNew($this->currenUser->getId(), $lastId1);
}else{
$status = $this->em->getRepository(Statut::class)->findLast($this->currenUser->getId(),8,$lastId1);
}*/
$status = $this->em->getRepository(Statut::class)->findLast($this->currenUser->getId(),8,0, $lastId1);
$status2 = $this->em->getRepository(Statut::class)->findByNotRead($this->currenUser->getId());
if($lastId1 == 0){
if(count($status)>0){
$lastId = $status[0]->getId();
}
}
else{
$lastId = $lastId1;
if(count($status)>0){
$lastId = $status[0]->getId();
}
}
$res=[];
$nb=$status2[0]['nb'];
foreach ($status as $s)
{
$res[] = $s->toArray();
// var_dump($s->getId());
}
return ["message"=>"operation_done","data"=>["notifs"=>$res,"nb"=>$nb,'last_id'=>$lastId], "statut"=>true,"code"=>201];
}
public function getNotificationsMore(array $data)
{
//if(!array_key_exists("limit",$data)) ["message"=>"limit field is required","data"=>[], "statut"=>false,"code"=>401];
if(!array_key_exists("offset",$data)) ["message"=>"offset field is required","data"=>[], "statut"=>false,"code"=>401];
$status = $this->em->getRepository(Statut::class)->findLast($this->currenUser->getId(),8,$data["offset"],0);
$res=[];
foreach ($status as $s)
{
$res[] = $s->toArray();
}
return ["message"=>"operation_done","data"=>["notifs"=>$res], "statut"=>true,"code"=>201];
}
public function getCadreLevel(array $data)
{
if(!array_key_exists("level",$data)) ["message"=>"level field is required","data"=>[], "statut"=>false,"code"=>401];
$cadre = $this->em->getRepository(CadreClassement::class)->findOneBy(["id"=>$data["level"]]);
if(is_null($cadre)) return ["message"=>"operation_done","data"=>[], "statut"=>true,"code"=>201];
$cadres = $cadre->getCadreClassements();
$res=[];
foreach ($cadres as $c)
{
$ca =$c->toArray();
$ca["sons"]=[];
$sons = $c->getCadreClassements();
foreach ($sons as $s)
{
$ca["sons"][]=$s->toArray();
}
$res[]=$ca;
}
return ["message"=>"operation_done","data"=>$res, "statut"=>true,"code"=>201];
}
private function ftp_file( $ftpservername,$ftp_port, $ftpusername, $ftppassword, $ftpsourcefile, $ftpdirectory, $ftpdestinationfile )
{
$conn_id = \ftp_connect($ftpservername,$ftp_port );
if ( $conn_id == false )
{
return "FTP open connection failed to ".$ftpservername;
}
$login_result = \ftp_login($conn_id, $ftpusername, $ftppassword);
if ((!$login_result)) {
return "FTP connection has failed";
}
if ( strlen( $ftpdirectory ) > 0 )
{
if (!\ftp_chdir($conn_id, $ftpdirectory )) {
return "Couldn't change directory on ".$ftpservername;
}
}
\ftp_pasv ( $conn_id, true ) ;
$upload = \ftp_put( $conn_id, $ftpdestinationfile, $ftpsourcefile, \FTP_ASCII );
if (!$upload) {
return " FTP upload has failed!";
}
\ftp_close($conn_id);
return $this->container->get('translator')->trans("operation_done");
}
public function sendFtp($data)
{
if(!array_key_exists("password_ftp",$data)) ["message"=>$this->container->get('translator')->trans("no_ftp_password_set"),"data"=>[], "statut"=>false,"code"=>401];
$todaydb = $this->em->getRepository(Save::class)->findForTodayDb();
//$todayar = $this->em->getRepository(Save::class)->findForTodayArchive();
//if(count($todayar)==0 && count($todaydb)==0) return ["message"=>$this->container->get('translator')->trans("no_file_to_send"),"data"=>[], "statut"=>true,"code"=>201];
$sys = $this->em->getRepository(System::class)->findOneBy(array("statut"=>1));
if(is_null($sys)) return ["message"=>$this->container->get('translator')->trans("system_error"),"data"=>[], "statut"=>false,"code"=>401];
if (!$this->encoder->isPasswordValid($sys, $data["password_ftp"])) {
return [
"message" =>$this->container->get('translator')->trans("password_error"),
"statut" => false,
"code" => 401
];
}
$ftp_server = $sys->getFtpDirectory();
$ftp_user_name = $sys->getFtpUser();
$ftp_user_pass = $data["password_ftp"];
$ftp_port = $sys->getFtpPort();
$ftp_protocol = $sys->getFtpProtocole();
$ftp_directory = $sys->getFtpFolder(); // leave blank
$ftp_source_file_name = "";
$ftp_dest_file_name = $ftp_source_file_name;
if(strlen($ftp_server)===0 || strlen($ftp_user_name) === 0 || strlen($ftp_user_pass)===0 || strlen($ftp_port)===0 || strlen($ftp_protocol)===0 || strlen($ftp_directory)===0){
return ["message"=>$this->container->get('translator')->trans("system_param_not_ok"),"data"=>[], "statut"=>false,"code"=>401];
}
/*if(count($todayar)>0)
{
$el = $todayar[0]->getFile();
$ftp_source_file_name = $this->container->get("kernel")->getProjectDir()."/public/SAVE/".$el;
$ftp_dest_file_name=$el;
$mesg=$this->ftp_file( $ftp_server, $ftp_user_name, $ftp_user_pass, $ftp_source_file_name, $ftp_directory, $ftp_dest_file_name);
if ($mesg != $this->container->get('translator')->trans("operation_done")) return ["message"=>$mesg,"statut"=>false,"code"=>401];
}*/
if(count($todaydb)>0)
{
$el = $todaydb[0]->getFile();
$ftp_source_file_name = $this->container->get("kernel")->getProjectDir()."/public/SAVE/".$el;
$ftp_dest_file_name=$ftp_directory."/".$el;
if($ftp_protocol === "ftp"){
$mesg=$this->ftp_file( $ftp_server,$ftp_port, $ftp_user_name, $ftp_user_pass, $ftp_source_file_name, $ftp_directory, $ftp_dest_file_name);
if ($mesg != $this->container->get('translator')->trans("operation_done")) return ["message"=>$mesg,"statut"=>false,"code"=>401];
}else{
try{
$sftp = new SFTPConnection($ftp_server, $ftp_port);
$sftp->login($ftp_user_name, $ftp_user_pass);
$sftp->uploadFile($ftp_source_file_name, $ftp_dest_file_name);
}
catch (\Exception $e)
{
return ["message"=>$e->getMessage(),"statut"=>false,"code"=>401];
}
}
}
return ["message"=>$this->container->get('translator')->trans("operation_done"),"data"=>[], "statut"=>true,"code"=>201];
}
public function getCopyRight()
{
$news = $this->em->getRepository(News::class)->findOneBy(["type"=>0,"isActive"=>true,"status"=>true],["id"=>"desc"]);
$data =null;
if($news !== null) $data=$news->toArray();
return ["message"=>"operation_done","data"=>$data, "statut"=>true,"code"=>201];
}
public function resetRegle(array $data)
{
if(!array_key_exists("file",$data)) return ["message"=>"file field is required","statut"=>false,"code"=>401];
$file =$this->container->get('upload_service')->uploadBase64($data["file"]);
if($file["statut"]==false) return ["message"=>"error_file_upload","statut"=>false,"code"=>401];
$f = $this->container->get('upload_service')->getTargetDirectory()."/FOLDER/".$file["file"]["path"];
$fp = fopen($f, "r");
// Détecter le séparateur sur la première ligne
$firstLine = fgets($fp);
rewind($fp);
// BOM cleanup si nécessaire
$bom = "\xEF\xBB\xBF";
if (strncmp($firstLine, $bom, 3) === 0) {
$firstLine = substr($firstLine, 3);
}
$delimiter = ','; // défaut
$semicolonCount = substr_count($firstLine, ';');
$commaCount = substr_count($firstLine, ',');
if ($semicolonCount > $commaCount) {
$delimiter = ';';
}
$i=0;
$tab=[];
$all=[];
// lecture ligne par ligne tant qu'on ne rencontre pas le code: fin de fichier(feof)
while (($datai = fgetcsv($fp, 10000, $delimiter)) !== FALSE) {
$tab[$i] = $datai;
$i++;
}
$j=0;
foreach ($tab as $r) {
if(count($r)==11) {
$j++;
$type = $this->em->getRepository(TypeDossier::class)->findOneBy(array("code"=>trim($r[1])));
if(is_null($type)) return ["message"=>$r[1]." type dossier not found","statut"=>false,"code"=>""];
$regle = new RegleConservation();
$regle->setId($r[0]);
$regle->setTypeDossier($type);
$regle->setCode($type->getCode()."-000".$j);
$regle->setObservationFr($r[9]);
$regle->setObservationEn($r[10]);
$regle->setSortFinal($r[8]);
$regle->setTexteReferenceFr($r[6]);
$regle->setTexteReferenceEn($r[7]);
$duree = new DureeDossier();
$duree->setTypeConsevation(intval($r[5]));
$duree->setConservation(intval($r[4]));
$duree->setTypeDua(intval($r[3]));
$duree->setDua(intval($r[2]));
$regle->setDureeDossier($duree);
$regle->setIsActive(true);
$this->em->persist($regle);
}
}
try{
$this->em->flush();
}
catch (\Exception $e)
{
return ["message"=>$e->getMessage(),"statut"=>false,"code"=>""];
}
fclose($fp);
return ["message"=>"operation_done","statut"=>true, "code"=>201,"data"=>[]];
}
public function simpleSearch(array $data)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>401];
$q = $data["keywords"];
$level = $this->currenUser->getLevel();
$res = $this->container->get(FOSElasticSearchService::class)->search($q,$level);
// $res = $this->em->getRepository(Dossier::class)->findSimple($level, $data['keywords']);
$all=[];
foreach ($res as $d)
{
$all[]=$d->getMiniArray();
}
return ["message"=>"","data"=>$all, "statut"=>true,"code"=>201];
}
public function editWorkgroup(array $data)
{
$req=["id", "code","type","title","start_date","end_date","reason"];
$reqObli=["code","type","title","id"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$old = $this->em->getRepository(Workgroup::class)->findOneBy(array("id"=>$data["id"],"isActive"=>1));
if(is_null($old)) return ["message"=>"workgroup not found","statut"=>false,"code"=>401];
// $old2 = $this->em->getRepository(Workgroup::class)->findOneBy(array("code"=>$data["code"]));
//if(!is_null($old2)) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
if($data["code"]!=$old->getCode()) return ["message"=>$this->container->get('translator')->trans("operation_denied"),"statut"=>false,"code"=>401];
$wkg = $old;
$wkg->setCode($data["code"]);
$wkg->setTitle($data["title"]);
$wkg->setMotif($data["reason"]);
if($data["type"]==1)
{
$wkg->setType(true);
}
else
{
$wkg->setType(false);
$wkg->setDateDebut(\DateTime::createFromFormat('d/m/Y',$data["start_date"]));
$wkg->setDateFin(\DateTime::createFromFormat('d/m/Y',$data["end_date"]));
}
$this->em->persist($wkg);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT72'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($wkg->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$wkg->toArray()];
}
public function usersWorkgroup(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""];
$wkg= $this->em->getRepository(Workgroup::class)->findOneBy(array("id"=>$data["id"],"isActive"=>true));
if(is_null($wkg)) return ["message"=>"workgroup not found","statut"=>false,"code"=>401];
$users = $wkg->getUserWorkgroups();
$res=[];
foreach ($users as $u)
{
if($u->getIsActive()==true) $res[]=$u->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$res];
}
public function foldersWorkgroup(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""];
$wkg= $this->em->getRepository(Workgroup::class)->findOneBy(array("id"=>$data["id"],"isActive"=>true));
if(is_null($wkg)) return ["message"=>"workgroup not found","statut"=>false,"code"=>401];
$folders = $wkg->getDossierWorkgroups();
$res=[];
foreach ($folders as $u)
{
if($u->getIsActive()==true) $res[]=$u->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$res];
}
public function addUserToWorkgroup(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""];
if(!array_key_exists("user_id",$data)) return ["message"=>"user_id field is required","statut"=>false,"code"=>""];
$wkg= $this->em->getRepository(Workgroup::class)->findOneBy(array("id"=>$data["id"],"isActive"=>true));
if(is_null($wkg)) return ["message"=>"workgroup not found","statut"=>false,"code"=>401];
$user = $this->em->getRepository(User::class)->findOneBy(array("id"=>$data["user_id"]));
if(is_null($user)) return ["message"=>"user not found","statut"=>false,"code"=>401];
$users = $wkg->getUserWorkgroups();
foreach ($users as $u)
{
if($u->getUser()->getId() == $user->getId()) return ["message"=>$this->container->get('translator')->trans("user_already_added"),"statut"=>false,"code"=>401];
}
$userW = new UserWorkgroup();
$userW->setStatus(false);
$userW->setUser($user);
$userW->setWorkgroup($wkg);
$this->em->persist($userW);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$userW->toArray()];
}
public function addFolderToWorkgroup(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""];
if(!array_key_exists("folder_id",$data)) return ["message"=>"folder_id field is required","statut"=>false,"code"=>""];
$wkg= $this->em->getRepository(Workgroup::class)->findOneBy(array("id"=>$data["id"],"isActive"=>true));
if(is_null($wkg)) return ["message"=>"workgroup not found","statut"=>false,"code"=>401];
$folder = $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$data["folder_id"]));
if(is_null($folder)) return ["message"=>"Dossier not found","statut"=>false,"code"=>401];
$folders = $wkg->getDossierWorkgroups();
foreach ($folders as $f)
{
if($f->getDossier()->getId() == $folder->getId()) return ["message"=>$this->container->get('translator')->trans("folder_already_added"),"statut"=>false,"code"=>401];
}
$folderW = new DossierWorkgroup();
$folderW->setWorkgroup($wkg);
$folderW->setDossier($folder);
$this->em->persist($folderW);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$folderW->toArray()];
}
public function removeUserToWorkgroup(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""];
if(!array_key_exists("user_id",$data)) return ["message"=>"user_id field is required","statut"=>false,"code"=>""];
$user = $this->em->getRepository(UserWorkgroup::class)->findOneBy(array("id"=>$data["user_id"],"workgroup"=>$data["id"]));
if(is_null($user)) return ["message"=>"user not found","statut"=>false,"code"=>401];
$this->em->remove($user);
$this->em->flush();
return ["message"=>"operation_done","statut"=>true,"data"=>[]];
}
public function removeFolderToWorkgroup(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""];
if(!array_key_exists("folder_id",$data)) return ["message"=>"folder_id field is required","statut"=>false,"code"=>""];
$folder = $this->em->getRepository(DossierWorkgroup::class)->findOneBy(array("id"=>$data["folder_id"],"workgroup"=>$data["id"]));
if(is_null($folder)) return ["message"=>"Dossier not found","statut"=>false,"code"=>401];
$this->em->remove($folder);
$this->em->flush();
return ["message"=>"operation_done","statut"=>true,"data"=>[]];
}
public function setWorkGroupMaster(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""];
if(!array_key_exists("user_id",$data)) return ["message"=>"user_id field is required","statut"=>false,"code"=>""];
$user = $this->em->getRepository(UserWorkgroup::class)->findOneBy(array("id"=>$data["user_id"],"workgroup"=>$data["id"]));
if(is_null($user)) return ["message"=>"user not found","statut"=>false,"code"=>401];
$usersW = $this->em->getRepository(UserWorkgroup::class)->findBy(array("workgroup"=>$user->getWorkgroup()));
$send=[];
foreach ($usersW as $wu)
{
if($wu->getStatus()==true) {
$wu->setStatus(false);
$this->em->persist($wu);
}else{
if($wu->getId()==$user->getId())
{
$user->setStatus(true);
$this->em->persist($user);
}
}
$send[]=$wu->toArray();
}
$this->em->flush();
return ["message"=>"operation_done","statut"=>true,"data"=>$send];
}
public function activateMultipleWorkgroup(array $data)
{
if(!array_key_exists("ids",$data)) return ["message"=>"ids field is required","statut"=>false,"data"=>"","code"=>401];
$elements = $this->em->getRepository(Workgroup::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setStatus(true);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
}
public function desactivateMultipleWorkgroup(array $data)
{
if(!array_key_exists("ids",$data)) return ["message"=>"ids field is required","statut"=>false,"data"=>"","code"=>401];
$elements = $this->em->getRepository(Workgroup::class)->findMultiple($data["ids"]);
foreach ($elements as $el)
{
$el->setStatus(false);
$this->em->persist($el);
}
if(count($elements)>0)
{
$this->em->flush();
}
return ["message"=>"operation_done","statut"=>true,"data"=>[],"code"=>201];
}
public function userWorkgroups()
{
$user = $this->currenUser;
$wkgs = $this->em->getRepository(UserWorkgroup::class)->userGroups($user->getId());
return $wkgs;
}
public function createSalle(array $data)
{
$req=["code","location"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
if(strlen($data['code'])<2) return ["message"=>$this->container->get('translator')->trans("room_min_length"),"statut"=>false,"code"=>""];
if(strlen($data['code'])>10) return ["message"=>$this->container->get('translator')->trans("room_max_length"),"statut"=>false,"code"=>""];
$location = $this->em->getRepository(ArchiveLocation::class)->findOneBy(['id'=>$data['location']]);
if($location === null) return ["message"=>$this->container->get('translator')->trans("archive_depot_not_found"),"statut"=>false,"code"=>401];
$old = $this->em->getRepository(Salle::class)->findOneBy(['isActive'=>true,'code'=>$data['code'],'archiveLocation'=>$location]);;
if($old !== null) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
$r = new Salle();
$r->setCode($data["code"]);
$r->setArchiveLocation($location);
$this->em->persist($r);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$r->toArray()];
}
public function editSalle(array $data)
{
$req=["id","code","location"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
if(strlen($data['code'])<2) return ["message"=>$this->container->get('translator')->trans("room_min_length"),"statut"=>false,"code"=>""];
if(strlen($data['code'])>10) return ["message"=>$this->container->get('translator')->trans("room_max_length"),"statut"=>false,"code"=>""];
$salle = $this->em->getRepository(Salle::class)->findOneBy(array("id"=>$data["id"]));
if($salle === null) return ["message"=>"salle not found","statut"=>false,"code"=>""];
$location = $this->em->getRepository(ArchiveLocation::class)->findOneBy(['id'=>$data['location']]);
if($location === null) return ["message"=>$this->container->get('translator')->trans("archive_depot_not_found"),"statut"=>false,"code"=>401];
$old = $this->em->getRepository(Salle::class)->findBy(['isActive'=>true,'code'=>$data['code'],'archiveLocation'=>$location]);
foreach ($old as $el ){
if($el->getId() !== $salle->getId()) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
}
$salle->setCode($data["code"]);
$salle->setArchiveLocation($location);
$this->em->persist($salle);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$salle->toArray()];
}
public function getSalleRayons(array $data)
{
if(!array_key_exists("id",$data))
{
return ["message"=>"type or id is missing","statut"=>false,"data"=>[],"code"=>401];
}
$rayons = $this->em->getRepository(Rayon::class)->findBy(array("salle"=>$data["id"]));
$res=[];
foreach ($rayons as $r)
{
if($r->getIsActive())$res[]=$r->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$res,"code"=>201];
}
public function driveStat()
{
$user = $this->currenUser;
$doc = $this->em->getRepository(Document::class)->countDocument($user->getId())[0]['nb'];
$rep = $this->em->getRepository(Repertoire::class)->countRepertoire($user->getId())[0]['nb'];
return ['statut'=>true,'data'=>['doc'=>$doc,'rep'=>$rep]];
}
public function driveSharedStat()
{
$user = $this->currenUser;
$doc = $this->em->getRepository(DocumentPartage::class)->countShared($user->getId())[0]['nb'];
$rep = $this->em->getRepository(RepertoirePartage::class)->countShared($user->getId())[0]['nb'];
return ['statut'=>true,'data'=>['doc'=>$doc,'rep'=>$rep]];
}
// not forget to add log
public function createDocument(array $data){
$user = $this->currenUser;
$req=['name','file','folder'];
$reqFile = ['name','extension','type','size','path'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
foreach ($reqFile as $val)
{
if(!array_key_exists($val,$data['file'])) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$r = $data['folder'] === ''?null:(int)$data['folder'];
$same = $this->em->getRepository(Document::class)->searchLike($user->getId(),$r,$data['name']);
if(count($same)>0) return ["message"=>$this->container->get('translator')->trans("name_already_exist"),"statut"=>false,"code"=>""];
$doc = new Document();
if($data['folder']!==''){
$rep = $this->em->getRepository(Repertoire::class)->findOneBy(['user'=>$user,'id'=>$data['folder']]);
if($rep === null) return ["message"=>"folder not found","statut"=>false,"code"=>""];
$doc->setRepertoire($rep);
}
$doc->setUser($user);
$doc->setNom($data['name']);
$file = new Fichier();
$file->setNom($data['file']['name']);
$file->setFolderNameAndName($data['file']['name']);
$file->setExtension($data['file']['extension']);
$file->setType($data['file']['type']);
$file->setTaille($data['file']['size']);
$file->setPath($data['file']['path']);
$file->setAuteur($user->getNom()." ".$user->getPrenom());
$doc->setFichier($file);
$this->em->persist($doc);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$doc->toArray()];
}
public function createRepertoire(array $data){
$user = $this->currenUser;
$req=['name','folder'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$r = $data['folder'] === ''?null:(int)$data['folder'];
$same = $this->em->getRepository(Repertoire::class)->searchLike($user->getId(),$r,$data['name']);
if(count($same)>0) return ["message"=>$this->container->get('translator')->trans("name_already_exist"),"statut"=>false,"code"=>""];
$r = new Repertoire();
if($data['folder']!==''){
$rep = $this->em->getRepository(Repertoire::class)->findOneBy(['user'=>$user,'id'=>$data['folder']]);
if($rep === null) return ["message"=>"folder not found","statut"=>false,"code"=>""];
$r->setParent($rep);
}
$r->setUser($user);
$r->setNom($data['name']);
$this->em->persist($r);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$r->toArray()];
}
public function checkDocumentExist(array $data){
$user = $this->currenUser;
if(!array_key_exists('name',$data)) return ["message"=>"name field is required","statut"=>false,"code"=>""];
if(!array_key_exists('folder',$data)) return ["message"=>"folder field is required","statut"=>false,"code"=>""];
$r = $data['folder'] === ''?null:(int)$data['folder'];
$same = $this->em->getRepository(Document::class)->searchLike($user->getId(),$r,$data['name']);
if(count($same)>0) return ["message"=>$this->container->get('translator')->trans("name_already_exist"),"statut"=>false,"code"=>""];
return ["message"=>"ok","statut"=>true,"code"=>""];
}
public function checkFolderExist(array $data){
$user = $this->currenUser;
if(!array_key_exists('name',$data)) return ["message"=>"name field is required","statut"=>false,"code"=>""];
if(!array_key_exists('folder',$data)) return ["message"=>"folder field is required","statut"=>false,"code"=>""];
$r = $data['folder'] === ''?null:(int)$data['folder'];
$same = $this->em->getRepository(Repertoire::class)->searchLike($user->getId(),$r,$data['name']);
if(count($same)>0) return ["message"=>$this->container->get('translator')->trans("name_already_exist"),"statut"=>false,"code"=>""];
return ["message"=>"ok","statut"=>true,"code"=>""];
}
public function getMainFolderAndMainFile(array $data){
$user = $this->currenUser;
$req=['limit','offset'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$orderBy = 'date_desc';//date_desc name_asc name_desc
if(array_key_exists('orderBy',$data)){
$orderBy = $data['orderBy'];
}
$folders = $this->em->getRepository(Repertoire::class)->getMainFolder($user->getId(),$data['limit'],$data['offset'],$orderBy);
$docs = $this->em->getRepository(Document::class)->getMainDocument($user->getId(),$data['limit'],$data['offset'],$orderBy);
$f=[];
$d=[];
foreach ($folders as $e)
{
$t = $e->toArray();
$t['type']=1;
$f[] = $t;
}
foreach ($docs as $e)
{
$t = $e->toArray();
$t['type']=0;
$d[] = $t;
}
return ["message"=>"","statut"=>true,"data"=>['docs'=>$d,'folders'=>$f]];
}
public function getMainFolderMore(array $data){
$user = $this->currenUser;
$req=['limit','offset'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$folders = $this->em->getRepository(Repertoire::class)->getMainFolder($user->getId(),$data['limit'],$data['offset']);
$d=[];
foreach ($folders as $e)
{
$d[] = $e->toArray();
}
return ["message"=>"","statut"=>true,"data"=>['folders'=>$d]];
}
public function getMainFolderMoreExcept(array $data){
$user = $this->currenUser;
$req=['limit','offset','folder'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$folders = $this->em->getRepository(Repertoire::class)->getMainFolderExcept($user->getId(),$data['folder'],$data['limit'],$data['offset']);
$d=[];
foreach ($folders as $e)
{
$d[] = $e->toArray();
}
return ["message"=>"","statut"=>true,"data"=>['folders'=>$d]];
}
public function getSubFolderMoreExcept(array $data){
$user = $this->currenUser;
$req=['limit','offset','id','folder'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$main = null;
if($data['folder'] !==0){
$mainFolder = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$data['folder']]);
if($mainFolder === null) return ["message"=>$this->container->get('translator')->trans("folder_not_found"),"statut"=>false,"code"=>""];
$main = $mainFolder->toArray();
$folders = $this->em->getRepository(Repertoire::class)->getSubFolderExcept($user->getId(),$data['folder'],$data['id'],$data['limit'],$data['offset']);
}
else{
$folders = $this->em->getRepository(Repertoire::class)->getMainFolderExcept($user->getId(),$data['id'],$data['limit'],$data['offset']);
}
$d=[];
foreach ($folders as $e)
{
$d[] = $e->toArray();
}
return ["message"=>"","statut"=>true,"data"=>['folders'=>$d,'main'=>$main]];
}
public function getMainFileMore(array $data){
$user = $this->currenUser;
$req=['limit','offset'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$docs = $this->em->getRepository(Document::class)->getMainDocument($user->getId(),$data['limit'],$data['offset']);
$d = [];
foreach ($docs as $e)
{
$d[] = $e->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$d];
}
public function getFolderDocument(array $data){
$user = $this->currenUser;
$req=['id','limit','offset'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$docs = $this->em->getRepository(Document::class)->getFolderDocument($user->getId(),$data['id'],$data['limit'],$data['offset']);
$d = [];
foreach ($docs as $doc) {
$d[] = $doc->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$d];
}
public function deleteDocument(array $data){
$user = $this->currenUser;
$req=['id'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$doc = $this->em->getRepository(Document::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($doc === null) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if($doc->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
$doc->setIsActive(false);
$this->em->persist($doc);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$doc->toArray()];
}
public function deleteRepertoire(array $data){
$user = $this->currenUser;
$req=['id'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$rep = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($rep === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
if($rep->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
$rep->setIsActive(false);
$docs = $this->em->getRepository(Document::class)->findBy(['repertoire'=>$rep,'isActive'=>0]);
$reps = $this->em->getRepository(Repertoire::class)->findBy(['parent'=>$rep,'isActive'=>0]);
foreach ($docs as $el ){
$el->setIsActive(false);
$this->em->persist($el);
}
foreach ($reps as $el){
$el->setIsActive(false);
$this->em->persist($el);
}
$this->em->persist($rep);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$rep->toArray()];
}
public function renameDocument(array $data){
$user = $this->currenUser;
$req=['id','name'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data) || strlen($data[$val])===0) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$doc = $this->em->getRepository(Document::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($doc === null) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if($doc->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
$r = $doc->getRepertoire() === null?null: $doc->getRepertoire()->getId();
$same = $this->em->getRepository(Document::class)->searchLike($user->getId(),$r, $data['name']);
if(count($same)>0) return ["message"=>$this->container->get('translator')->trans("name_already_exist"),"statut"=>false,"code"=>""];
$doc->setNom($data['name']);
$this->em->persist($doc);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$doc->toArray()];
}
public function renameRepertoire(array $data){
$user = $this->currenUser;
$req=['id','name'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data) || strlen($data[$val])===0) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$rep = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($rep === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
if($rep->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
$r = $rep->getParent() === null?null: $rep->getParent()->getId();
$same = $this->em->getRepository(Repertoire::class)->searchLike($user->getId(),$r, $data['name']);
if(count($same)>0) return ["message"=>$this->container->get('translator')->trans("name_already_exist"),"statut"=>false,"code"=>""];
$rep->setNom($data['name']);
$this->em->persist($rep);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$rep->toArray()];
}
public function moveDocument(array $data){
$user = $this->currenUser;
$req=['id','folder'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data) || strlen($data[$val])===0) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$doc = $this->em->getRepository(Document::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($doc === null) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if($doc->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
$r = (int)$data['folder'];
if($r>0){
/*$same = $this->em->getRepository(Document::class)->searchLike($user->getId(),$r, $data['name']);
if(count($same)>0) return ["message"=>$this->container->get('translator')->trans("name_already_exist"),"statut"=>false,"code"=>""];*/
$rep = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$r,'user'=>$user]);
if($rep === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
if($rep->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
$doc->setRepertoire($rep);
}
else{
/*$same = $this->em->getRepository(Document::class)->searchLike($user->getId(),null, $data['name']);
if(count($same)>0) return ["message"=>$this->container->get('translator')->trans("name_already_exist"),"statut"=>false,"code"=>""];*/
$doc->setRepertoire(null);
}
//$doc->setNom($data['name']);
$this->em->persist($doc);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$doc->toArray()];
}
public function moveRepertoire(array $data){
$user = $this->currenUser;
$req=['id','folder'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data) || strlen($data[$val])===0) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$rep = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($rep === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
if($rep->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
$r = (int)$data['folder'];
if($r>0){
/*$same = $this->em->getRepository(Repertoire::class)->searchLike($user->getId(),$r, $data['name']);
if(count($same)>0) return ["message"=>$this->container->get('translator')->trans("name_already_exist"),"statut"=>false,"code"=>""];*/
$p = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$r,'user'=>$user]);
if($p === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
if($p->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
if($p->getId() === $rep->getId()) return ['message' =>$this->container->get('translator')->trans('operation_denied'),"statut"=>false,"code"=>401];
$rep->setParent($p);
}
else{
/*$same = $this->em->getRepository(Repertoire::class)->searchLike($user->getId(),null, $data['name']);
if(count($same)>0) return ["message"=>$this->container->get('translator')->trans("name_already_exist"),"statut"=>false,"code"=>""];*/
$rep->setParent(null);
}
//$rep->setNom($data['name']);
$this->em->persist($rep);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$rep->toArray()];
}
public function shareDocumentUsers(array $data){
$user = $this->currenUser;
$req=['id','users'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$doc = $this->em->getRepository(Document::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($doc === null) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if($doc->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if(count($data['users'])===0) return ['message' =>$this->container->get('translator')->trans('no_user_found'),"statut"=>false,"code"=>401];
if($doc->getIsShared()){
$docShare = $this->em->getRepository(DocumentPartage::class)->findOneBy(['document'=>$doc,'isActive'=>1]);
if($docShare === null){
$docShare = new DocumentPartage();
$docShare->setDocument($doc);
}
}
else{
$docShare = new DocumentPartage();
$docShare->setDocument($doc);
$doc->setIsShared(true);
$this->em->persist($doc);
}
$users = $this->em->getRepository(User::class)->findMultiple($data['users']);
$nbUser =0;
$notifUser=[];
foreach ($users as $u){
if($u->getId() !== $user->getId()){
if(!$docShare->getUsers()->contains($u)){
$notifUser[]=$u;
$nbUser++;
$docShare->addUser($u);
}
}
}
$docShare->setNbUser($nbUser);
// dont forget notification
$notif = new Notification();
$notif->setUser($this->currenUser);
$notif->setDocumentPartage($docShare);
$notif->setCode(Notification::SHARE_DOCUMENT_USER);
foreach ($notifUser as $u){
$status = new Statut();
$status->setNotification($notif);
$status->setUser($u);
$notif->addStatut($status);
}
$this->em->persist($notif);
$this->em->persist($docShare);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$docShare->toArray()];
}
public function shareRepertoireUsers(array $data){
$user = $this->currenUser;
$req=['id','users'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$rep = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($rep === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
if($rep->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
if(count($data['users'])===0) return ['message' =>$this->container->get('translator')->trans('no_user_found'),"statut"=>false,"code"=>401];
if($rep->getIsShared()){
$repShare = $this->em->getRepository(RepertoirePartage::class)->findOneBy(['repertoire'=>$rep,'isActive'=>1]);
if($repShare === null){
$repShare = new RepertoirePartage();
$repShare->setRepertoire($rep);
}
}
else{
$repShare = new RepertoirePartage();
$repShare->setRepertoire($rep);
$rep->setIsShared(true);
$this->em->persist($rep);
}
$users = $this->em->getRepository(User::class)->findMultiple($data['users']);
$nbUser =0;
$notifUser = [];
/* $files = $this->em->getRepository(Document::class)->findBy(['repertoire'=>$rep,'isActive'=>true]);
$parentFiles = [];
foreach ($files as $f){
$p = $this->em->getRepository(DocumentPartage::class)->findOneBy(['document'=>$f]);
if($p !== null){
$p->setIsActive(true);
$parentFiles[] = $p;
}
else{
$docShare = new DocumentPartage();
$docShare->setDocument($f);
if($f->getIsShared()===false){
$f->setIsShared(true);
$this->em->persist($f);
}
$parentFiles[] = $docShare;
}
}
$len = count($parentFiles);*/
foreach ($users as $u){
if(!$repShare->getUsers()->contains($u)){
$notifUser[]=$u;
$nbUser++;
$repShare->addUser($u);
}
/*for($i=0;$i<$len;$i++){
if(!$parentFiles[$i]->getUsers()->contains($u)){
$parentFiles[$i]->setNbUser($parentFiles[$i]->getNbUser()+1);
$parentFiles[$i]->addUser($u);
}
}*/
}
$repShare->setNbUser($nbUser);
$notif = new Notification();
$notif->setUser($this->currenUser);
$notif->setRepertoirePartage($repShare);
$notif->setCode(Notification::SHARE_FOLDER_USER);
foreach ($notifUser as $u){
$status = new Statut();
$status->setNotification($notif);
$status->setUser($u);
$notif->addStatut($status);
}
$this->em->persist($notif);
/*foreach ($parentFiles as $f){
$this->em->persist($f);
}*/
$this->em->persist($repShare);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$repShare->toArray()];
}
public function shareDocumentGroup(array $data){
$user = $this->currenUser;
$req=['id','groups'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$doc = $this->em->getRepository(Document::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($doc === null) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if($doc->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if(count($data['groups'])==0) return ['message' =>$this->container->get('translator')->trans('no_group_found'),"statut"=>false,"code"=>401];
if($doc->getIsShared()){
$docShare = $this->em->getRepository(DocumentPartage::class)->findOneBy(['document'=>$doc,'isActive'=>1]);
if($docShare === null){
$docShare = new DocumentPartage();
$docShare->setDocument($doc);
}
}
else{
$docShare = new DocumentPartage();
$docShare->setDocument($doc);
$doc->setIsShared(true);
$this->em->persist($doc);
}
$groups = $this->em->getRepository(Workgroup::class)->findMultiple($data['groups']);
foreach ($groups as $group){
if(!$docShare->getWorkgroups()->contains($group)){
$docShare->addWorkgroup($group);
$docShare->setNbGroup($docShare->getNbGroup()+1);
$notif = new Notification();
$notif->setUser($this->currenUser);
$notif->setWorkgroup($group);
$notif->setDocumentPartage($docShare);
$notif->setCode(Notification::SHARE_DOCUMENT_GROUP);
$userWorks = $group->getUserWorkgroups();
foreach ($userWorks as $uw){
$status = new Statut();
$status->setNotification($notif);
$status->setUser($uw->getUser());
$notif->addStatut($status);
}
$this->em->persist($notif);
}
}
$this->em->persist($docShare);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$docShare->toArray()];
}
public function removeGroupFromSharedDocument(array $data){
$user = $this->currenUser;
$req=['id','groups'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$doc = $this->em->getRepository(Document::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($doc === null) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if($doc->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if(count($data['groups'])===0) return ['message' =>$this->container->get('translator')->trans('no_group_found'),"statut"=>false,"code"=>401];
if(!$doc->getIsShared()){
return ["message"=>"operation_denied","statut"=>false,"code"=>401,"data"=>""];
}
$docShare = $this->em->getRepository(DocumentPartage::class)->findOneBy(['document'=>$doc,'isActive'=>1]);
if($docShare === null){
return ["message"=>"operation_denied","statut"=>false,"code"=>401,"data"=>""];
}
$groups = $this->em->getRepository(Workgroup::class)->findMultiple($data['groups']);
if(count($groups)===0) return ['message' =>$this->container->get('translator')->trans('no_group_found'),"statut"=>false,"code"=>401];
$nb = $docShare->getNbGroup();
foreach($groups as $g){
if($docShare->getWorkgroups()->contains($g)){
$docShare->removeWorkgroup($g);
$nb--;
}
}
$docShare->setNbGroup($nb);
$this->em->persist($docShare);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$docShare->toArray()];
}
public function removeUserFromSharedDocument(array $data){
$user = $this->currenUser;
$req=['id','users'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$doc = $this->em->getRepository(Document::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($doc === null) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if($doc->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
if(count($data['users'])===0) return ['message' =>$this->container->get('translator')->trans('no_user_found'),"statut"=>false,"code"=>401];
if(!$doc->getIsShared()){
return ["message"=>"operation_denied","statut"=>false,"code"=>401,"data"=>""];
}
$docShare = $this->em->getRepository(DocumentPartage::class)->findOneBy(['document'=>$doc,'isActive'=>1]);
if($docShare === null){
return ["message"=>"operation_denied","statut"=>false,"code"=>401,"data"=>""];
}
$users = $this->em->getRepository(User::class)->findMultiple($data['users']);
if(count($users)===0) return ['message' =>$this->container->get('translator')->trans('no_user_found'),"statut"=>false,"code"=>401];
$nb = $docShare->getNbUser();
foreach($users as $u){
if($docShare->getUsers()->contains($u)){
$docShare->removeUser($u);
$nb--;
}
}
$docShare->setNbUser($nb);
$this->em->persist($docShare);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$docShare->toArray()];
}
public function removeUserFromSharedRepertoire(array $data){
$user = $this->currenUser;
$req=['id','users'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$rep = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$data['id'],'user'=>$user]);
if($rep === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
if($rep->getIsActive() === false) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
if(count($data['users'])===0) return ['message' =>$this->container->get('translator')->trans('no_user_found'),"statut"=>false,"code"=>401];
if(!$rep->getIsShared()){
return ["message"=>"operation_denied","statut"=>false,"code"=>401,"data"=>""];
}
$repShare = $this->em->getRepository(RepertoirePartage::class)->findOneBy(['repertoire'=>$rep,'isActive'=>1]);
if($repShare === null){
return ["message"=>"operation_denied","statut"=>false,"code"=>401,"data"=>""];
}
$users = $this->em->getRepository(User::class)->findMultiple($data['users']);
if(count($users)===0) return ['message' =>$this->container->get('translator')->trans('no_user_found'),"statut"=>false,"code"=>401];
$nb = $repShare->getNbUser();
foreach($users as $u){
if($repShare->getUsers()->contains($u)){
$repShare->removeUser($u);
$nb--;
}
}
$repShare->setNbUser($nb);
$this->em->persist($repShare);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$repShare->toArray()];
}
/**
* Return OnlyOffice fileType (extension) from MIME type
* or null if not editable.
*/
function getOnlyOfficeFileTypeFromMime(string $mimeType): ?string
{
$map = [
// ===== WORD =====
'application/msword' =>
'doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' =>
'docx',
'application/vnd.oasis.opendocument.text' =>
'odt',
'application/rtf' =>
'rtf',
'text/plain' =>
'txt',
// ===== EXCEL =====
'application/vnd.ms-excel' =>
'xls',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' =>
'xlsx',
'application/vnd.oasis.opendocument.spreadsheet' =>
'ods',
'text/csv' =>
'csv',
// ===== POWERPOINT =====
'application/vnd.ms-powerpoint' =>
'ppt',
'application/vnd.openxmlformats-officedocument.presentationml.presentation' =>
'pptx',
'application/vnd.oasis.opendocument.presentation' =>
'odp',
];
return isset($map[$mimeType]) ? $map[$mimeType] : null;
}
/**
* Return OnlyOffice documentType from fileType
*/
function getOnlyOfficeDocumentType(string $fileType): string
{
if (in_array($fileType, ['doc', 'docx', 'odt', 'rtf', 'txt'], true)) {
return 'word';
}
if (in_array($fileType, ['xls', 'xlsx', 'ods', 'csv'], true)) {
return 'cell';
}
if (in_array($fileType, ['ppt', 'pptx', 'odp'], true)) {
return 'slide';
}
throw new \RuntimeException('Unsupported OnlyOffice fileType: ' . $fileType);
}
public function getOneDocument(array $data){
$user = $this->currenUser;
$req=['id'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$doc = $this->em->getRepository(Document::class)->findOneBy(['id'=>$data['id'],'isActive'=>true]);
if($doc === null) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>401];
$test = false;
if($doc->getUser()->getId() === $user->getId()) { $test = true;}
else{
$t = true;
$docShare = $this->em->getRepository(DocumentPartage::class)->findOneBy(['document'=>$doc]);
if($docShare !== null){
if($docShare->getUsers()->contains($user)){
$t = false;
$test = true;
}
}
else{
$rep = $doc->getRepertoire();
while($rep !== null && $t === true){
if($rep->getIsShared()){
$sh = $this->em->getRepository(RepertoirePartage::class)->findOneBy(['repertoire'=>$rep]);
if($sh !== null){
if($sh->getUsers()->contains($user)){
$test = true;
$t = false;
}
else
{
$rep = $rep->getParent();
}
}
else
{
$rep->setIsShared(false);
$this->em->persist($rep);
$this->em->flush();
$rep = $rep->getParent();
}
}else{
$rep = $rep->getParent();
}
}
}
}
if($test === false){
return ['message' =>$this->container->get('translator')->trans('operation_denied'),"statut"=>false,"code"=>401];
}
$dr = $doc->toArray();
$onlyOffice = [];
$mimeType = $doc->getFichier()->getType();
// Get file extension from the actual filename
$fileName = $doc->getFichier()->getNom();
$extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
// Prioritize file extension over MIME type for accuracy
// MIME type can be wrong (e.g., xlsx detected as xls)
$fileType = null;
// CRITICAL: OnlyOffice cannot save in old XLS format (exit code 88)
// Always treat XLS files as XLSX to avoid converter errors
if ($extension === 'xls') {
$fileType = 'xlsx'; // Force modern format
} elseif ($extension === 'doc') {
$fileType = 'docx'; // Same for old Word format
} elseif ($extension === 'ppt') {
$fileType = 'pptx'; // Same for old PowerPoint format
} elseif (in_array($extension, ['docx', 'odt', 'rtf', 'txt', 'xlsx', 'ods', 'csv', 'pptx', 'odp'])) {
$fileType = $extension;
} else {
// Fallback to MIME type detection if extension is not recognized
$fileType = $this->getOnlyOfficeFileTypeFromMime($mimeType);
}
if ($fileType !== null) {
$documentType = $this->getOnlyOfficeDocumentType($fileType);
if($documentType!==''){
/**
* Préparation ONLYOFFICE
*/
$encryptedPath = $this->container
->get('upload_service')
->getTargetDirectory() . '/' . $doc->getFichier()->getPath();
// 1️⃣ Decrypt file to unique temp file per user/session
$tmpFileName = sprintf(
'ged_%d_%d_%s.%s',
$doc->getId(),
$this->currentUser->getId(),
bin2hex(random_bytes(4)), // unique per session
$fileType
);
$tmpPath = sys_get_temp_dir() . '/' . $tmpFileName;
if (!file_exists($tmpPath)) {
$encryptedContent = file_get_contents($encryptedPath);
$clearContent = $this->container->get('hash_service')->decrypt($encryptedContent);
file_put_contents($tmpPath, $clearContent);
}
$fileUrl = $this->urlGenerator->generate(
'web_tmp_file',
['name' => $tmpFileName],
UrlGeneratorInterface::ABSOLUTE_URL
);
$fileUrl = str_replace('localhost', $this->container->getParameter('app.symfony_domain'), $fileUrl);
$callbackUrl = $this->urlGenerator->generate(
'web_onlyoffice_callback',
['id' => $doc->getId(), 'tmp_file' => $tmpFileName],
UrlGeneratorInterface::ABSOLUTE_URL
);
$callbackUrl = str_replace('localhost', $this->container->getParameter('app.symfony_domain'), $callbackUrl);
$callbackUrl = str_replace('http:', 'https:', $callbackUrl);
// 🔑 Document key identifies a specific version of the document
// Include fileType and dateCreation timestamp so key changes when content changes
// This tells OnlyOffice it's a new version after save
$lastModified = $doc->getFichier()->getDateCreation()->getTimestamp();
$documentKey = hash('sha256', 'doc_' . $doc->getId() . '_' . $fileType . '_' . $lastModified);
$config = [
'documentType' => $documentType,
'document' => [
'fileType' => $fileType,
'key' => $documentKey,
'title' => $doc->getNom(),
'url' => $fileUrl,
'permissions' => [
'edit' => true,
'download' => true,
'print' => true,
'comment' => true,
'fillForms' => true
],
],
'editorConfig' => [
'mode' => 'edit',
'user' => [
'id' => (string) $this->currentUser->getId(),
'name' => $this->currentUser->getEmail(),
],
'callbackUrl' => $callbackUrl,
'coEditing' => [
'mode' => 'strict', // or 'fast' for real-time collaboration
'change' => true
],
'customization' => [
'autosave' => true,
'forcesave' => true,
'assemblyFormatAsOrigin'=> true,
'goback' => false
],
],
'file' => [
'tmp_name' => $tmpFileName,
],
'exp' => time() + (($this->container->getParameter('app.session_time_out')/60000)*60 - 120),
];
$token = JWT::encode(
$config,
$this->container->getParameter('app.only_office_jwt_secret'),
'HS256'
);
$onlyOffice = [
'onlyofficeUrl' => $this->container->getParameter('app.only_office_url'),
'config' => $config,
'token' => $token,
];
$dr['onlyOffice'] = $onlyOffice;
}
}
return ["message"=>"","statut"=>true,"data"=>$dr];
}
public function getFolderItem(array $data){
$user = $this->currenUser;
$req=['limit','offset','id'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$main = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$data['id'],'isActive'=>true]);
if($main === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
$test = false;
if($main->getUser()->getId() === $user->getId()) {
$test = true;
}
else{
$t = true;
$rep = $main;
while($rep !== null && $t === true){
if($rep->getIsShared()){
$sh = $this->em->getRepository(RepertoirePartage::class)->findOneBy(['repertoire'=>$rep]);
if($sh !== null){
if($sh->getUsers()->contains($user)){
$test = true;
$t = false;
}
else
{
$rep = $rep->getParent();
}
}
else
{
$rep->setIsShared(false);
$this->em->persist($rep);
$this->em->flush();
$rep = $rep->getParent();
}
}else{
$rep = $rep->getParent();
}
}
}
if($test === false){
return ['message' =>$this->container->get('translator')->trans('operation_denied'),"statut"=>false,"code"=>401];
}
$orderBy = 'date_desc';//date_desc name_asc name_desc
if(array_key_exists('orderBy',$data)){
$orderBy = $data['orderBy'];
}
$folders = $this->em->getRepository(Repertoire::class)->getSubFolder($main->getUser()->getId(),$main->getId(), $data['limit'],$data['offset'],$orderBy);
$docs = $this->em->getRepository(Document::class)->getFolderDocument($main->getUser()->getId(),$main->getId(),$data['limit'],$data['offset'],$orderBy);
$f=[];
$d=[];
foreach ($folders as $e)
{
$t = $e->toArray();
$t['type']=1;
$f[] = $t;
}
foreach ($docs as $e)
{
$t = $e->toArray();
$t['type']=0;
$d[] = $t;
}
return ["message"=>"","statut"=>true,"data"=>['docs'=>$d,'folders'=>$f,'main'=>$main->toArray()]];
}
public function getFile(array $data){
if(!array_key_exists('name',$data)) return ["message"=>"name field is required","statut"=>false,"code"=>""];
$file = $this->em->getRepository(Fichier::class)->findByNameLike($data['name']);
if($file === null) return null;
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT60'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($file->getId());
$this->em->persist($log);
$this->em->flush();
}
return $file->toArray();
}
public function getOneRepertoire(array $data){
$user = $this->currenUser;
$req=['id'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$doc = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$data['id'],'isActive'=>true]);
if($doc === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
$test = false;
if($doc->getUser()->getId() === $user->getId()) $test = true;
if($test === false){
if($doc->getIsShared()){
$docShare = $this->em->getRepository(RepertoirePartage::class)->findOneBy(['repertoire'=>$doc]);
if($docShare === null) {
$doc->setIsShared(false);
$this->em->persist($doc);
$this->em->flush();
return ['message' =>$this->container->get('translator')->trans('operation_denied'),"statut"=>false,"code"=>401];
}
if(!$docShare->getUsers()->contains($user)){
return ['message' =>$this->container->get('translator')->trans('operation_denied'),"statut"=>false,"code"=>401];
}
}
else{
return ['message' =>$this->container->get('translator')->trans('operation_denied'),"statut"=>false,"code"=>401];
}
}
return ["message"=>"","statut"=>true,"data"=>$doc->toArray()];
}
public function getDocumentSharedUsersAndGroup(array $data){
$u = $this->currenUser;
if(!array_key_exists('id',$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""
];
$doc = $this->em->getRepository(Document::class)->findOneBy(['id'=>$data['id']]);
if($doc === null) return ['message' =>$this->container->get('translator')->trans('document_not_found'),"statut"=>false,"code"=>""];
//$users = $this->em->getRepository(User::class)->findBy(['isActive'=>true,'isClose'=>false,'type'=>User::USER]);
$users = $this->em->getRepository(User::class)->loadAllUsersExecptAdmin();
$uW = $this->em->getRepository(UserWorkgroup::class)->findBy(['user'=>$u,'isActive'=>true,'status'=>true]);
$docShare = $this->em->getRepository(DocumentPartage::class)->findOneBy(['document'=>$doc]);
$shUser = [];
$shGroup = [];
$sendUsers= [];
$sendGroups= [];
if($docShare !== null){
$allU = $docShare->getUsers();
$allG = $docShare->getWorkgroups();
foreach ($allU as $el){
$shUser[]=$el->getId();
}
foreach ($allG as $el){
$shGroup[]=$el->getId();
}
}
foreach ($users as $el){
if($el->getId() !== $u->getId()){
if(in_array($el->getId(),$shUser)){
$sendUsers[]=['user'=>$el->toArray(),'status'=>1];
}
else{
$sendUsers[]=['user'=>$el->toArray(),'status'=>0];
}
}
}
foreach ($uW as $el){
if(in_array($el->getWorkgroup()->getId(),$shGroup)){
$sendGroups[]=['group'=>$el->getWorkgroup()->toArray(),'status'=>1];
}
else{
$sendGroups[]=['group'=>$el->getWorkgroup()->toArray(),'status'=>0];
}
}
return ["message"=>"","statut"=>true,"data"=>['users'=>$sendUsers,'groups'=>$sendGroups]];
}
public function getRepertoireSharedUsers(array $data){
$u = $this->currenUser;
if(!array_key_exists('id',$data)) return ["message"=>"id field is required","statut"=>false,"code"=>""
];
$rep = $this->em->getRepository(Repertoire::class)->findOneBy(['id'=>$data['id']]);
if($rep === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>""];
//$users = $this->em->getRepository(User::class)->findBy(['isActive'=>true,'isClose'=>false,'type'=>User::USER]);
$users = $this->em->getRepository(User::class)->loadAllUsersExecptAdmin();
$repShare = $this->em->getRepository(RepertoirePartage::class)->findOneBy(['repertoire'=>$rep]);
$shUser = [];
$sendUsers= [];
if($repShare !== null){
$allU = $repShare->getUsers();
foreach ($allU as $el){
$shUser[]=$el->getId();
}
}
foreach ($users as $el){
if($el->getId() !== $u->getId()){
if(in_array($el->getId(),$shUser)){
$sendUsers[]=['user'=>$el->toArray(),'status'=>1];
}
else{
$sendUsers[]=['user'=>$el->toArray(),'status'=>0];
}
}
}
return ["message"=>"","statut"=>true,"data"=>['users'=>$sendUsers]];
}
public function getMySharedFileAndFolder(array $data){
$user = $this->currenUser;
$req=['limit','offset'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$folders = $this->em->getRepository(RepertoirePartage::class)->getSharedWithUser($user->getId(),$data['limit'],$data['offset']);
$docs = $this->em->getRepository(DocumentPartage::class)->getSharedWithUser($user->getId(),$data['limit'],$data['offset']);
$f=[];
$d=[];
foreach ($folders as $e)
{
$t = $e->getRepertoire()->toArray();
$t['type']=1;
$f[] = $t;
}
foreach ($docs as $e)
{
$t = $e->getDocument()->toArray();
$t['type']=0;
$d[] = $t;
}
return ["message"=>"","statut"=>true,"data"=>['docs'=>$d,'folders'=>$f]];
}
public function testChat(array $data){
$user = $this->currenUser;
return ["message"=>"","statut"=>true,"data"=>['user'=>$user->toArray()]];
}
public function getMercureToken($user){
$token = (new Builder())
->withClaim('mercure', ['subscribe' => [
sprintf("/%s",$this->hash->encrypt($user->getEmail()) ),
sprintf("/%s",'chat' ),
sprintf("/%s",'TYPE_'.$user->getType() )
]
])
->getToken(
new Sha256(),
new Key('digitrav')
)
;
return $token;
}
public function getCurrentUser(){
$u = $this->currenUser;
if($u === null) {
return ['message' =>"", 'statut' =>false, 'data' =>null];
}
else {
return ['message' =>"", 'statut' =>true, 'data' =>$u->toArray()];
}
}
public function getAllUser()
{
$user = $this->currenUser;
$wkgs = $this->em->getRepository(UserWorkgroup::class)->userGroups($user->getId());
$users = $this->em->getRepository(User::class)->loadAllUsersExceptCurrent($this->currenUser->getId(),1000,0);
$notReadUsers = $this->em->getRepository(Statut::class)->findNotReadChatUser($user->getId());
$notReadGroup = $this->em->getRepository(Statut::class)->findNotReadChatGroup($user->getId());
$uno =[];
$unosid =[];
$wno = [];
$wnosid = [];
foreach ($notReadUsers as $n){
if(!array_key_exists($n['id'],$uno)){
$uno[$n['id']]=1;
$unosid[$n['id']]=[];
$unosid[$n['id']][]=$n['sid'];
}else{
$uno[$n['id']]++;
$unosid[$n['id']][]=$n['sid'];
}
}
foreach ($notReadGroup as $n){
if(!array_key_exists($n['id'],$wno)){
$wno[$n['id']]=1;
$wnosid[$n['id']]=[];
$wnosid[$n['id']][]=$n['sid'];
}else{
$wno[$n['id']]++;
$wnosid[$n['id']][]=$n['sid'];
}
}
$tab = [];
$tab2 = [];
foreach ($users as $u){
$e = $u->toArray();
if(array_key_exists($u->getId(),$uno)){
$e['not_read'] =$uno[$u->getId()];
$e['not_read_sid'] =$unosid[$u->getId()];
}
else{
$e['not_read'] =0;
}
$tab[] =$e ;
}
foreach ($wkgs as $w){
$e = $w->getWorkgroup()->toArray();
if(array_key_exists($w->getWorkgroup()->getId(),$wno)){
$e['not_read'] =$wno[$w->getWorkgroup()->getId()];
$e['not_read_sid'] =$wnosid[$w->getWorkgroup()->getId()];
}
else{
$e['not_read'] =0;
}
$tab2[] = $e;
}
return ['message' =>"", 'statut' =>true, 'data' =>['users'=>$tab,'groups'=>$tab2
]];
}
public function sendMessageToAll(array $data){
$user = $this->currenUser;
$req=['message'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
if(strlen($data['message']) === 0) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
$msg = new Message();
$msg->setSender($user);
$msg->setContent($data['message']);
if(array_key_exists('file',$data)){
$msg->setFile($data['file']);
}
$msg->setType(Message::MESSAGE_ALL);
$this->em->persist($msg);
$notif = new Notification();
$notif->setUser($user);
$notif->setMessage($msg);
$notif->setCode(Notification::NEW_MESSAGE);
/*$users = $this->em->getRepository(User::class)->loadAllUsersExceptCurrent($user->getId(),1000,0);
$uids =[];
foreach ($users as $u){
$statut = new Statut();
$statut->setUser($u);
$statut->setNotification($notif);
$notif->addStatut($statut);
$uids[] = $u->getId();
}*/
$this->em->persist($notif);
$this->em->flush();
return ['message' =>"", 'statut' =>true, 'data' =>['message'=>$msg->toArray(),'users'=>[],'except'=>$user->getId()]];
}
public function sendMessageToUser(array $data){
$user = $this->currenUser;
$req=['message','user'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
if(strlen($data['message']) === 0) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
$r = $this->em->getRepository(User::class)->findOneBy(['id'=>$data['user']]);
if($r === null) return ["message"=>$this->container->get('translator')->trans('operation_denied'),"statut"=>false,"code"=>""];
$msg = new Message();
$msg->setSender($user);
$msg->setReceiver($r);
$msg->setContent($data['message']);
if(array_key_exists('file',$data)){
$msg->setFile($data['file']);
}
$msg->setType(Message::MESSAGE_USER);
$this->em->persist($msg);
$notif = new Notification();
$notif->setUser($user);
$notif->setMessage($msg);
$notif->setCode(Notification::NEW_MESSAGE);
$uids =[];
$uids[] = $r->getId();
$statut = new Statut();
$statut->setUser($r);
$statut->setNotification($notif);
$notif->addStatut($statut);
$this->em->persist($notif);
$this->em->flush();
return ['message' =>"", 'statut' =>true, 'data' =>['message'=>$msg->toArray(),'users'=>$uids]];
}
public function sendMessageToGroup(array $data){
$user = $this->currenUser;
$req=['message','group'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
if(strlen($data['message']) === 0) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
$group = $this->em->getRepository(Workgroup::class)->findOneBy(['id'=>$data['group']]);
if($group === null) return ["message"=>$this->container->get('translator')->trans('group_not_found'),"statut"=>false,"code"=>""];
$msg = new Message();
$msg->setSender($user);
$msg->setWorkgroup($group);
$msg->setContent($data['message']);
if(array_key_exists('file',$data)){
$msg->setFile($data['file']);
}
$msg->setType(Message::MESSAGE_GROUP);
$this->em->persist($msg);
$notif = new Notification();
$notif->setUser($user);
$notif->setMessage($msg);
$notif->setCode(Notification::NEW_MESSAGE);
$wkgs = $this->em->getRepository(UserWorkgroup::class)->findBy(['workgroup'=>$group]);
$uids =[];
foreach ($wkgs as $wk){
$u = $wk->getUser();
if($u->getId() !== $user->getId()){
$statut = new Statut();
$statut->setUser($u);
$statut->setNotification($notif);
$notif->addStatut($statut);
$uids[] = $u->getId();
}
}
$this->em->persist($notif);
$this->em->flush();
return ['message' =>"", 'statut' =>true, 'data' =>['message'=>$msg->toArray(),'users'=>$uids]];
}
public function getUserChatMessage(array $data){
$user = $this->currenUser;
$req=['limit','offset','id'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
if((int)$data['id'] === $user->getId()) return ["message"=>$this->container->get('translator')->trans('operation_denied'),"statut"=>false,"code"=>""];
$messages = $this->em->getRepository(Message::class)->findForUser($user->getId(),$data['id'], $data['limit'],$data['offset']);
$tab = [];
if(array_key_exists('status',$data)&& (count($data['status'])>0)){
$status = $this->em->getRepository(Statut::class)->findList($user->getId(),$data['status']);
foreach ($status as $s){
$s->setStatut(1);
$this->em->persist($s);
}
if(count($status)>0){
$this->em->flush();
}
}
foreach ($messages as $m){
$tab[]=$m->toArray();
}
return ['message' =>"", 'statut' =>true, 'data' =>$tab];
}
public function getGroupChatMessage(array $data){
$user = $this->currenUser;
$req=['limit','offset','id'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$group = $this->em->getRepository(UserWorkgroup::class)->findOneBy(['user'=>$user->getId(),'workgroup'=>$data['id']]);
if($group === null) return ["message"=>$this->container->get('translator')->trans('operation_denied'),"statut"=>false,"code"=>""];
$messages = $this->em->getRepository(Message::class)->findForGroup($data['id'], $data['limit'],$data['offset']);
$tab = [];
if(array_key_exists('status',$data)&& (count($data['status'])>0)){
$status = $this->em->getRepository(Statut::class)->findList($user->getId(),$data['status']);
foreach ($status as $s){
$s->setStatut(1);
$this->em->persist($s);
}
if(count($status)>0){
$this->em->flush();
}
}
foreach ($messages as $m){
$tab[]=$m->toArray();
}
return ['message' =>"", 'statut' =>true, 'data' =>$tab];
}
public function getAllChatMessage(array $data){
$user = $this->currenUser;
$req=['limit','offset'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$messages = $this->em->getRepository(Message::class)->findForAll( $data['limit'],$data['offset']);
$tab = [];
foreach ($messages as $m){
$tab[]=$m->toArray();
}
return ['message' =>"", 'statut' =>true, 'data' =>$tab];
}
public function updateStatus(array $data){
$user = $this->currenUser;
$req=['list'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$status = $this->em->getRepository(Statut::class)->findList($user->getId(),$data['list']);
foreach ($status as $s){
$s->setStatut(1);
$this->em->persist($s);
}
if(count($status)>0){
$this->em->flush();
}
return ['message' =>"", 'statut' =>true, 'data' => []];
}
public function registerIncomingMail(array $data){
$user = $this->currenUser;
$req=['confi','priorite','receiver','actor','courtier','type','contenu','titre','reference','date_enreg','files','ref_int','selected_attached_file'];
$reqObli=['confi','priorite','receiver','actor','courtier','type','titre','reference','date_enreg'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) {
return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
else{
if(in_array($val,$reqObli) && strlen($data[$val]) ===0){
return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$confi = $this->em->getRepository(TypeConfidentialite::class)->findOneBy(array('id' =>$data['confi']));
if($confi === null) return ["message"=>" Type confidentialite not found","statut"=>false,"code"=>""];
$priorite = $this->em->getRepository(Priorite::class)->findOneBy(array('id' =>$data['priorite']));
if($priorite === null) return ["message"=>" Priorite not found","statut"=>false,"code"=>""];
$type = $this->em->getRepository(TypeCourrier::class)->findOneBy(array('id' =>$data['type']));
if($type === null) return ["message"=>" Type courrier not found","statut"=>false,"code"=>""];
$receiver = $this->em->getRepository(User::class)->findOneBy(array('id' =>$data['receiver']));
if($receiver === null) return ["message"=>" Destinataire not found","statut"=>false,"code"=>""];
$actor = $this->em->getRepository(ActeurExterne::class)->findOneBy(array('id' =>$data['actor']));
if($actor === null) return ["message"=>" Expéditeur not found","statut"=>false,"code"=>""];
$broker = $this->em->getRepository(Courtier::class)->findOneBy(array('id' =>$data['courtier']));
if($broker === null) return ["message"=>" Courtier not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(Courrier::class)->findOneBy(['reference'=>$data['reference']]);
if($old !== null) return ["message"=>$this->container->get('translator')->trans("reference already used"),"statut"=>false,"code"=>""];
$courrier = new Courrier();
$courrier->setType(Courrier::COURRIER_ENTRANT);
$courrier->setConfidentialite($confi);
$courrier->setPriorite($priorite);
$courrier->setDestinataire($receiver);
$courrier->setUser($user);
$courrier->setTypeCourrier($type);
$courrier->setActeur($actor);
$courrier->setCourtier($broker);
$courrier->setReference($data['reference']);
$courrier->setInternalReference($data['ref_int']);
$courrier->setContenu($data['contenu']);
$courrier->setObjet($data['titre']);
$courrier->setDateEnreg(\DateTime::createFromFormat('d/m/Y',$data['date_enreg']));
$attachedFiles = $type->getPieceJointes();
$nb = 0;
foreach($attachedFiles as $item){
if($item->getIsActive()){
$p = new PieceJointeAjoutee();
$p->setCourrier($courrier);
$p->setPieceJointe($item);
if(in_array($item->getId(),$data['selected_attached_file'])){
$p->setStatus(1);
}
else{
$p->setStatus(0);
}
$courrier->addPieceJointeAjoutee($p);
$nb++;
}
}
$courrier->setNbPieceJointe($nb);
foreach ($data["files"] as $f)
{
$file = new Fichier();
$file->setNom($f["name"]);
$file->setFolderNameAndName($courrier->getObjet()." | ". $f["name"]);
$file->setExtension($f["extension"]);
$file->setType($f["type"]);
$file->setTaille($f["size"]);
$file->setPath($f["path"]);
$file->setAuteur($user->getNom()." ".$user->getPrenom());
$file->setCourrier($courrier);
$courrier->addFichier($file);
}
if($user->getId() !== $receiver->getId()){
$notif = new Notification();
$notif->setCourrier($courrier);
$notif->setCode(Notification::NEW_INCOMING_MAIL);
$notif->setUser($user);
$statut = new Statut();
$statut->setUser($receiver);
$statut->setNotification($notif);
$notif->addStatut($statut);
$this->em->persist($notif);
}
$this->em->persist($courrier);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT86'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($user);
$log->setObservation($courrier->getId());
$this->em->persist($log);
$this->em->flush();
}
$res = $courrier->toArray();
$res['new_ref']= strtoupper(uniqid("CE".(new \DateTime())->format("Y"), false));
return ["message"=>"","statut"=>true,"data"=>$res];
}
public function registerOutGoingMail(array $data){
$user = $this->currenUser;
$req=['confi','priorite','receiver','actor','courtier','type','contenu','titre','reference','date_enreg','files','ref_int'];
$reqObli=['confi','priorite','receiver','actor','courtier','type','titre','reference','date_enreg'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) {
return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
else{
if(in_array($val,$reqObli) && strlen($data[$val]) ===0){
return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$confi = $this->em->getRepository(TypeConfidentialite::class)->findOneBy(array('id' =>$data['confi']));
if($confi === null) return ["message"=>" Type confidentialite not found","statut"=>false,"code"=>""];
$priorite = $this->em->getRepository(Priorite::class)->findOneBy(array('id' =>$data['priorite']));
if($priorite === null) return ["message"=>" Priorite not found","statut"=>false,"code"=>""];
$type = $this->em->getRepository(TypeCourrier::class)->findOneBy(array('id' =>$data['type']));
if($type === null) return ["message"=>" Type courrier not found","statut"=>false,"code"=>""];
$receiver = $this->em->getRepository(User::class)->findOneBy(array('id' =>$data['receiver']));
if($receiver === null) return ["message"=>" Destinataire not found","statut"=>false,"code"=>""];
$actor = $this->em->getRepository(ActeurExterne::class)->findOneBy(array('id' =>$data['actor']));
if($actor === null) return ["message"=>" Expéditeur not found","statut"=>false,"code"=>""];
$broker = $this->em->getRepository(Courtier::class)->findOneBy(array('id' =>$data['courtier']));
if($broker === null) return ["message"=>" Courtier not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(Courrier::class)->findOneBy(['reference'=>$data['reference']]);
if($old !== null) return ["message"=>$this->container->get('translator')->trans("reference already used"),"statut"=>false,"code"=>""];
$courrier = new Courrier();
$courrier->setType(Courrier::COURRIER_SORTANT);
$courrier->setConfidentialite($confi);
$courrier->setPriorite($priorite);
$courrier->setDestinataire($receiver);
$courrier->setUser($user);
$courrier->setTypeCourrier($type);
$courrier->setActeur($actor);
$courrier->setCourtier($broker);
$courrier->setReference($data['reference']);
$courrier->setInternalReference($data['ref_int']);
$courrier->setContenu($data['contenu']);
$courrier->setObjet($data['titre']);
$courrier->setStatut(Courrier::STATUT_RANGE);
$courrier->setDateCloture(new \DateTime());
$courrier->setDateEnreg(\DateTime::createFromFormat('d/m/Y',$data['date_enreg']));
foreach ($data["files"] as $f)
{
$file = new Fichier();
$file->setNom($f["name"]);
$file->setFolderNameAndName($courrier->getObjet()." | ". $f["name"]);
$file->setExtension($f["extension"]);
$file->setType($f["type"]);
$file->setTaille($f["size"]);
$file->setPath($f["path"]);
$file->setAuteur($user->getNom()." ".$user->getPrenom());
$file->setCourrier($courrier);
$courrier->addFichier($file);
}
if($user->getId() !== $receiver->getId()){
$notif = new Notification();
$notif->setCourrier($courrier);
$notif->setCode(Notification::NEW_OUTGOING_MAIL);
$notif->setUser($user);
$statut = new Statut();
$statut->setUser($receiver);
$statut->setNotification($notif);
$notif->addStatut($statut);
$this->em->persist($notif);
}
$this->em->persist($courrier);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT86'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($user);
$log->setObservation($courrier->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$courrier->toArray()];
}
public function getOneMail(array $data)
{
if(!array_key_exists("id",$data))
{
return ["message"=>"type or id is missing","statut"=>false,"data"=>[],"code"=>401];
}
else
{
$mail = $this->em->getRepository(Courrier::class)->findOneBy(array("id"=>$data["id"]));
if($mail === null) return ["message"=>"courrier not found","statut"=>false,"data"=>[],"code"=>401];
else
{
$files = $this->em->getRepository(Fichier::class)->findBy(array("courrier"=>$mail,"isActive"=>true));
$res=[];
foreach ($files as $f)
{
$res[]=$f->toArray();
}
$collabo = $this->em->getRepository(CourrierCollaborateur::class)->findBy(['courrier'=>$mail,'isActive'=>1]);
$co = [];
foreach ($collabo as $c)
{
$co[]=$c->toArray();
}
if($mail->getStatut()=== Courrier::STATUT_NOUVEAU){
if($this->currenUser->getId() === $mail->getDestinataire()->getId()){
$mail->setStatut(Courrier::STATUT_EN_COURS);
$this->em->persist($mail);
$this->em->flush();
}
}
$attachedFile = $mail->getPieceJointeAjoutees();
$attachedFileTab = [];
foreach ($attachedFile as $item){
$attachedFileTab[]=$item->toArray();
}
return ["message"=>"","statut"=>true,"data"=>['mail'=>$mail->toArray(),'files'=>$res,'collabo'=>$co,'attached_files'=>$attachedFileTab],"code"=>201];
}
}
}
public function editIncomingMail(array $data){
$user = $this->currenUser;
$req=['id','confi','priorite','receiver','actor','courtier','type','contenu','titre','date_enreg','added_files','remove_files','ref_int','attached_files'];
$reqObli=['confi','priorite','receiver','actor','courtier','type','titre','date_enreg'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) {
return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
else{
if(in_array($val,$reqObli) && strlen($data[$val]) ===0){
return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$courrier = $this->em->getRepository(Courrier::class)->findOneBy(array("id"=>$data["id"]));
if($courrier === null) return ["message"=>"courrier not found","statut"=>false,"code"=>401];
$confi = $this->em->getRepository(TypeConfidentialite::class)->findOneBy(array('id' =>$data['confi']));
if($confi === null) return ["message"=>" Type confidentialite not found","statut"=>false,"code"=>""];
$priorite = $this->em->getRepository(Priorite::class)->findOneBy(array('id' =>$data['priorite']));
if($priorite === null) return ["message"=>" Priorite not found","statut"=>false,"code"=>""];
$type = $this->em->getRepository(TypeCourrier::class)->findOneBy(array('id' =>$data['type']));
if($type === null) return ["message"=>" Type courrier not found","statut"=>false,"code"=>""];
$receiver = $this->em->getRepository(User::class)->findOneBy(array('id' =>$data['receiver']));
if($receiver === null) return ["message"=>" Destinataire not found","statut"=>false,"code"=>""];
$actor = $this->em->getRepository(ActeurExterne::class)->findOneBy(array('id' =>$data['actor']));
if($actor === null) return ["message"=>" Expéditeur not found","statut"=>false,"code"=>""];
$broker = $this->em->getRepository(Courtier::class)->findOneBy(array('id' =>$data['courtier']));
if($broker === null) return ["message"=>" Coursier not found","statut"=>false,"code"=>""];
$courrier->setConfidentialite($confi);
$courrier->setPriorite($priorite);
$courrier->setDestinataire($receiver);
$courrier->setUser($user);
$courrier->setTypeCourrier($type);
$courrier->setActeur($actor);
$courrier->setInternalReference($data['ref_int']);
$courrier->setCourtier($broker);
$courrier->setContenu($data['contenu']);
$courrier->setObjet($data['titre']);
$courrier->setDateEnreg(\DateTime::createFromFormat('d/m/Y',$data['date_enreg']));
foreach ($data["remove_files"] as $id)
{
$file = $this->em->getRepository(Fichier::class)->findOneBy(array("id"=>$id));
if($file !== null)
{
$courrier->removeFichier($file);
}
}
foreach ($data["added_files"] as $f)
{
$file = new Fichier();
$file->setNom($f["name"]);
$file->setFolderNameAndName($courrier->getObjet()." | ". $f["name"]);
$file->setExtension($f["extension"]);
$file->setType($f["type"]);
$file->setTaille($f["size"]);
$file->setPath($f["path"]);
$file->setAuteur($user->getNom()." ".$user->getPrenom());
$file->setCourrier($courrier);
$courrier->addFichier($file);
}
if(count($data['attached_files'])>0){
foreach($courrier->getPieceJointeAjoutees() as $i){
if(in_array($i->getId(),$data['attached_files'])){
$i->setStatus(1);
}else{
$i->setStatus(0) ;
}
$courrier->addPieceJointeAjoutee($i);
}
}else{
foreach($courrier->getPieceJointeAjoutees() as $i){
$i->setStatus(0) ;
$courrier->addPieceJointeAjoutee($i);
}
}
$this->em->persist($courrier);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'1021'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($user);
$log->setObservation($courrier->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$courrier->toArray()];
}
public function getMailTask(array $data)
{
if(!array_key_exists("id",$data))
{
return ["message"=>"type or id is missing","statut"=>false,"data"=>[],"code"=>401];
}
else
{
$mail = $this->em->getRepository(Courrier::class)->findOneBy(array("id"=>$data["id"]));
if($mail === null) return ["message"=>"courrier not found","statut"=>false,"data"=>[],"code"=>401];
else
{
$tasks = $this->em->getRepository(Tache::class)->findBy(array("courrier"=>$mail,"isActive"=>true));
$res=[];
foreach ($tasks as $f)
{
$res[]=$f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$res,"code"=>201];
}
}
}
/**
* Internal method to create a single task
* Extracted from createTask() to support batch creation
* Does not auto-flush - caller is responsible for transaction management
*
* @param array $data Task data
* @return array Result with task data or error
*/
private function createTaskInternal(array $data)
{
$user = $this->currenUser;
$req=['instruction','user','priority','type','files','mail_id','date','cotation','cotation_file'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$mail = $this->em->getRepository(Courrier::class)->findOneBy(['id'=>$data['mail_id']]);
if($mail === null) return ["message"=>'related mail not found',"statut"=>false,"code"=>""];
if(!in_array($mail->getStatut(),[Courrier::STATUT_EN_COURS,Courrier::STATUT_NOUVEAU]) ) return ["message"=>$this->container->get('translator')->trans("operation_denied"),"statut"=>false,"code"=>""];
$u = $this->em->getRepository(User::class)->findOneBy(['id'=>$data['user']]);
if($u === null) return ["message"=>$this->container->get('translator')->trans("user_not_found"),"statut"=>false,"code"=>""];
$pri = $this->em->getRepository(Priorite::class)->findOneBy(['id'=>$data['priority']]);
if($pri === null) return ["message"=>'priority not found',"statut"=>false,"code"=>""];
$type = $this->em->getRepository(TypeTache::class)->findOneBy(['id'=>$data['type']]);
if($type === null) return ["message"=>'Task type not found',"statut"=>false,"code"=>""];
$task = new Tache();
$task->setUser($u);
$task->setCourrier($mail);
$task->setEmetteur($user);
$task->setInstruction($data['instruction']);
try {
$task->setDateButtoir(\DateTime::createFromFormat('d/m/Y',$data["date"]));
} catch (\Exception $e) {
return ["message"=>$e->getMessage(),"statut"=>false,"code"=>""];
}
$task->setPriorite($pri);
$task->setTypeTache($type);
$task->setCode(uniqid('TA-', true));
if($user->getId()===$u->getId()){
$task->setStatut(Tache::STATUT_EN_COURS);
}
foreach ($data['files'] as $f){
$file = new Fichier();
$file->setNom($f['name']);
$file->setFolderNameAndName($task->getInstruction()." | ". $f["name"]);
$file->setExtension($f['extension']);
$file->setType($f['type']);
$file->setTaille($f['size']);
$file->setPath($f['path']);
$file->setAuteur($user->getNom()." ".$user->getPrenom());
$file->setTache($task);
$task->addFichier($file);
}
if($data['cotation']==1){
$task->setHasMailFile(true);
}else{
if($data['cotation_file']==1){
$task->setHasMailFile(true);
}
}
$courCol = null;
$alreadyCourCol = false;
if($user->getId()!==$u->getId()){
$courColAll = $this->em->getRepository(CourrierCollaborateur::class)->findBy(['courrier'=>$mail]);
if(count($courColAll)===0){
$courCol = new CourrierCollaborateur();
$courCol->setCourrier($mail);
$courCol->setUser($u);
if($data['cotation'] == 1){
$courCol->setCotation(true);
$courCol->setStatut(true);
}
$this->em->persist($courCol);
}
else{
$courCol= $this->em->getRepository(CourrierCollaborateur::class)->findOneBy(['courrier'=>$mail,'user'=>$u]);
if($courCol === null){
$courCol = new CourrierCollaborateur();
$courCol->setCourrier($mail);
$courCol->setUser($u);
if($data['cotation'] == 1){
$courCol->setCotation(true);
$courCol->setStatut(true);
}
$this->em->persist($courCol);
}
else{
$alreadyCourCol = true;
}
}
$notif = new Notification();
$notif->setUser($user);
$notif->setTache($task);
$notif->setCode(Notification::NEW_TASK);
if($data['cotation'] == 1){
$notif->setCode(Notification::MAIL_COTATION);
}
$status = new Statut();
$status->setNotification($notif);
$status->setUser($u);
$notif->addStatut($status);
$this->em->persist($notif);
}
$this->em->persist($task);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'1002'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($task->getId());
$this->em->persist($log);
$this->em->flush();
}
if($alreadyCourCol == false){
if($courCol !== null){
$sta = $courCol->getStatut();
$id = $courCol->getId();
$courCol = $courCol->getUser()->getMiniArray();
$courCol['collabo_status'] = $sta;
$courCol['collabo_id'] = $id;
}
}
else{
$courCol = null;
}
return ["message"=>"","statut"=>true,"data"=>['tache'=>$task->toArray(),'collabo'=>$courCol]];
}
/**
* Create a single task (public interface)
* Delegates to createTaskInternal()
*
* @param array $data Task data
* @return array Result with task data or error
*/
public function createTask(array $data){
return $this->createTaskInternal($data);
}
/**
* Create multiple tasks in a single atomic transaction
* All tasks succeed together or fail together (no partial creation)
*
* @param array $tasksData Array of task data objects
* @return array Result with created tasks or error
*/
public function createMultipleTasks(array $tasksData)
{
$createdTasks = [];
// Start transaction for atomicity
$this->em->getConnection()->beginTransaction();
try {
foreach ($tasksData as $index => $taskData) {
// Create task using internal method
$result = $this->createTaskInternal($taskData);
if ($result["statut"] == false) {
throw new \Exception("Task " . ($index + 1) . ": " . $result["message"]);
}
$createdTasks[] = $result;
}
// Commit transaction if all tasks created successfully
$this->em->getConnection()->commit();
return [
"message" => $this->container->get('translator')->trans("operation_done"),
"statut" => true,
"data" => [
"created_tasks" => $createdTasks,
"count" => count($createdTasks)
]
];
} catch (\Exception $e) {
// Rollback transaction on any error
$this->em->getConnection()->rollBack();
return [
"message" => $e->getMessage(),
"statut" => false,
"code" => ""
];
}
}
public function updateMailManager(array $data){
$user = $this->currenUser;
$req=['collabo_id'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$collabo = $this->em->getRepository(CourrierCollaborateur::class)->findOneBy(['id'=>$data['collabo_id']]);
if($collabo === null) return ["message"=>$this->container->get('translator')->trans("user_not_found"),"statut"=>false,"code"=>""];
$mail = $collabo->getCourrier();
if($mail->getStatut()!== Courrier::STATUT_EN_COURS) return ["message"=>$this->container->get('translator')->trans("operation_denied"),"statut"=>false,"code"=>""];
if($user->getId() !== $mail->getDestinataire()->getId()){
return ["message"=>$this->container->get('translator')->trans("operation_denied"),"statut"=>false,"code"=>""];
}
$allCollabo = $this->em->getRepository(CourrierCollaborateur::class)->findBy(['courrier'=>$mail]);
$all=[];
foreach ($allCollabo as $c){
if($c->getId() === $collabo->getId()){
$collabo->setStatut(true);
$c->setStatut(true);
$this->em->persist($collabo);
}
else{
if($c->getStatut()===true){
$c->setStatut(false);
$this->em->persist($c);
}
}
$all[]=$c->toArray();
}
$this->em->flush();
return ["message"=>'',"data"=>$all, "statut"=>true,"code"=>201];
}
public function mailAction(array $data){
$user = $this->currenUser;
$req=['id','action'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
if(!in_array($data['action'],['end','order','archive','open'])){
return ["message"=>"bad action","statut"=>false,"code"=>""];
}
if ($data['action'] === 'archive'){
if(!array_key_exists('place',$data)) return ["message"=>"place field is required","statut"=>false,"code"=>""];
}
$mail = $this->em->getRepository(Courrier::class)->findOneBy(['id'=>$data['id']]);
if($mail === null) return ["message"=>"mail not found","statut"=>false,"code"=>""];
if($mail->getDestinataire()->getId() !== $user->getId())
{
return ["message"=>$this->container->get('translator')->trans("operation_denied"),"statut"=>false,"code"=>""];
}
if($data['action'] === 'end'){
$mail->setStatut(Courrier::STATUT_EN_TERMINE);
$mail->setDateCloture(new \DateTime());
$this->em->persist($mail);
$tasks = $this->em->getRepository(Tache::class)->findBy(['courrier'=>$mail]);
foreach ($tasks as $t){
if(in_array($t->getStatut(),[ Tache::STATUT_EN_COURS,Tache::STATUT_NOUVEAU])){
$t->setStatut(Tache::STATUT_EN_TERMINE);
$t->setDateFin(new \DateTime());
$this->em->persist($t);
}
}
$allCollabo = $this->em->getRepository(CourrierCollaborateur::class)->findBy(['courrier'=>$mail]);
$notif = new Notification();
$notif->setUser($user);
$notif->setCourrier($mail);
$notif->setCode(Notification::MAIL_ENDED);
foreach ($allCollabo as $co){
$status = new Statut();
$status->setNotification($notif);
$status->setUser($co->getUser());
$notif->addStatut($status);
}
$this->em->persist($notif);
}
else if($data['action'] === 'open'){
$mail->setStatut(Courrier::STATUT_EN_COURS);
$mail->setDateCloture(null);
$this->em->persist($mail);
$allCollabo = $this->em->getRepository(CourrierCollaborateur::class)->findBy(['courrier'=>$mail]);
$notif = new Notification();
$notif->setUser($user);
$notif->setCourrier($mail);
$notif->setCode(Notification::MAIL_REOPEN);
foreach ($allCollabo as $co){
$status = new Statut();
$status->setNotification($notif);
$status->setUser($co->getUser());
$notif->addStatut($status);
}
$this->em->persist($notif);
}
else if($data['action'] === 'order'){
$mail->setStatut(Courrier::STATUT_RANGE);
$this->em->persist($mail);
}
else{
$mail->setStatut(Courrier::STATUT_ARCHIVE);
$mail->setArchive($data['place']);
$this->em->persist($mail);
}
$this->em->flush();
return ['message'=>'','data'=>$mail->toArray(),'statut'=>true,'code'=>201];
}
public function getOneTask(array $data)
{
if(!array_key_exists("id",$data))
{
return ["message"=>"id is missing","statut"=>false,"data"=>[],"code"=>401];
}
else
{
$task = $this->em->getRepository(Tache::class)->findOneBy(array("id"=>$data["id"]));
if($task === null) return ["message"=>"Tache not found","statut"=>false,"data"=>[],"code"=>401];
else
{
$files = $this->em->getRepository(Fichier::class)->findBy(array("tache"=>$task,"isActive"=>true));
$res=[];
foreach ($files as $f)
{
$res[]=$f->toArray();
}
$mail = $task->getCourrier();
$mailFiles = [];
if($this->currentUser->getId() == $task->getEmetteur()->getId() || $task->isHasMailFile()){
$mailFiles = $this->em->getRepository(Fichier::class)->findBy(array("courrier"=>$mail,"isActive"=>true));
}else{
$collabo = $this->em->getRepository(CourrierCollaborateur::class)->findOneBy(["courrier"=>$mail,"user"=>$this->currentUser]);
if($collabo != null && $collabo->getCotation()){
$mailFiles = $this->em->getRepository(Fichier::class)->findBy(array("courrier"=>$mail,"isActive"=>true));
}
}
$resMain=[];
foreach ($mailFiles as $f)
{
$resMain[]=$f->toArray();
}
$attachedFile = $mail->getPieceJointeAjoutees();
$attachedFileTab = [];
foreach ($attachedFile as $item){
$attachedFileTab[]=$item->toArray();
}
if($task->getStatut()=== Tache::STATUT_NOUVEAU){
if($this->currenUser->getId() === $task->getUser()->getId()){
$task->setStatut(Courrier::STATUT_EN_COURS);
$this->em->persist($task);
$this->em->flush();
}
}
return ["message"=>"","statut"=>true,"data"=>['task'=>$task->toArray(),'files'=>$res,'main_files'=>$resMain,"attached_files"=>$attachedFileTab],"code"=>201];
}
}
}
public function endTask(array $data)
{
$user = $this->currenUser;
if(!array_key_exists("id",$data))
{
return ["message"=>"id is missing","statut"=>false,"data"=>[],"code"=>401];
}
if(!array_key_exists("observation",$data))
{
return ["message"=>"observation is missing","statut"=>false,"data"=>[],"code"=>401];
}
$task = $this->em->getRepository(Tache::class)->findOneBy(array("id"=>$data["id"]));
if($task === null) return ["message"=>"Tache not found","statut"=>false,"data"=>[],"code"=>401];
if($task->getUser()->getId() !== $user->getId() ) {
return ["message"=>$this->container->get('translator')->trans("operation_denied"),"statut"=>false,"code"=>""];
}
$task->setStatut(Tache::STATUT_EN_TERMINE);
$task->setObservation($data['observation']);
$task->setDateFin(new \DateTime());
$notif = new Notification();
$notif->setUser($user);
$notif->setTache($task);
$notif->setCode(Notification::TASK_END);
$status = new Statut();
$status->setNotification($notif);
$status->setUser($task->getEmetteur());
$notif->addStatut($status);
$this->em->persist($notif);
$this->em->persist($task);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'1004'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($task->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$task->toArray(),"code"=>201];
}
public function addTaskFile(array $data)
{
$user = $this->currenUser;
if(!array_key_exists("file",$data))
{
return ["message"=>"file is missing","statut"=>false,"data"=>[],"code"=>401];
}
if(!array_key_exists("id",$data))
{
return ["message"=>"id is missing","statut"=>false,"data"=>[],"code"=>401];
}
$task = $this->em->getRepository(Tache::class)->findOneBy(array("id"=>$data["id"]));
if($task === null) return ["message"=>"Tache not found","statut"=>false,"data"=>[],"code"=>401];
if($task->getUser()->getId() !== $user->getId() ) {
return ["message"=>$this->container->get('translator')->trans("operation_denied"),"statut"=>false,"code"=>""];
}
if($task->getStatut() === Tache::STATUT_EN_TERMINE)
{
return ["message"=>$this->container->get('translator')->trans("operation_denied"),"statut"=>false,"code"=>""];
}
$file = new Fichier();
$file->setNom($data['file']['name']);
$file->setFolderNameAndName($task->getInstruction()." | ". $data['file']["name"]);
$file->setExtension($data['file']['extension']);
$file->setType($data['file']['type']);
$file->setTaille($data['file']['size']);
$file->setPath($data['file']['path']);
$file->setAuteur($user->getNom()." ".$user->getPrenom());
$file->setTache($task);
$task->addFichier($file);
$this->em->persist($task);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'1006'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($task->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$file->toArray(),"code"=>201];
}
public function getStatisticMail(array $data)
{
if(!array_key_exists("start_date",$data)) return ["message"=>"start_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("end_date",$data)) return ["message"=>"end_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("type_filter",$data)) return ["message"=>"type_filter field is required","statut"=>false,"code"=>401];
if(!array_key_exists("type",$data)) return ["message"=>"type field is required","statut"=>false,"code"=>401];
$s = \DateTime::createFromFormat('d.m.Y',$data["start_date"])->format("Y-m-d");
$e = \DateTime::createFromFormat('d.m.Y',$data["end_date"])->format("Y-m-d");
$res=[];
switch ($data["type"])
{
case 1:
//pyramide des états
$mailIn = $this->em->getRepository(Courrier::class)->findStatSimple($s,$e, Courrier::COURRIER_ENTRANT);
$totalIn = count($mailIn);
$doneIn=0;
$awaitIn=0;
foreach ($mailIn as $m)
{
if($m->getStatut()>=2){
$doneIn ++;
}
else{
$awaitIn ++;
}
}
if($totalIn==0){
$res=[
["name"=>$this->container->get('translator')->trans("mail_incoming_treated"),"value"=>0],
["name"=>$this->container->get('translator')->trans("mail_incoming_untreated"),"value"=>0]];
}
else{
$res=[
["name"=>$this->container->get('translator')->trans("mail_incoming_treated"),"value"=>round($doneIn/$totalIn,4)*100],
["name"=>$this->container->get('translator')->trans("mail_incoming_untreated"),"value"=>round($awaitIn/$totalIn,4)*100]];
}
break;
case 2:
//courbe de versement
$mailIn = $this->em->getRepository(Courrier::class)->findStatSimple($s,$e, Courrier::COURRIER_ENTRANT);
$mailOut = $this->em->getRepository(Courrier::class)->findStatSimple($s,$e, Courrier::COURRIER_SORTANT);
$res=[];
$typesIn=[];
$typesOut=[];
$dates=$this->getDatesFromRange($s, $e);
foreach ($dates as $t)
{
$typesIn[$t]=0;
$typesOut[$t]=0;
}
foreach ($mailIn as $d)
{
$typesIn[$d->getDate()->format("Y-m-d")]++;
}
foreach ($mailOut as $d)
{
$typesOut[$d->getDate()->format("Y-m-d")]++;
}
$tabIn[]=$this->container->get('translator')->trans('mail_incoming');
$tabOut[]=$this->container->get('translator')->trans('mail_outgoing');
foreach ($dates as $t)
{
$tabIn[] = $typesIn[$t];
$tabOut[] = $typesOut[$t];
}
$tabInFinal[]=$this->container->get('translator')->trans('mail_incoming');
$tabOutFinal[]=$this->container->get('translator')->trans('mail_outgoing');
$tabDateFinal[]='Dates';
foreach ($dates as $t)
{
if($typesIn[$t] !=0 || $typesOut[$t]!=0 ){
$tabDateFinal[]=$t;
$tabInFinal[]=$typesIn[$t];
$tabOutFinal[]=$typesOut[$t];
}
}
$res["data_in"]=$tabInFinal;
$res["data_out"]=$tabOutFinal;
$res["dates"]=$tabDateFinal;
break;
case 3:
//disque des courriers
$folders= $this->em->getRepository(Courrier::class)->findStatSimple($s,$e, Courrier::COURRIER_ENTRANT);
$types=[];
$in=[];
$aty=[];
foreach ($folders as $d)
{
if(!in_array($d->getTypeCourrier()->getId(),$in))
{
$in[]=$d->getTypeCourrier()->getId();
$types[$d->getTypeCourrier()->getCode()]=1;
$aty[$d->getTypeCourrier()->getCode()]=$d->getTypeCourrier()->getNomFr();
}
else
{
$types[$d->getTypeCourrier()->getCode()]++;
}
}
$res=[];
foreach ($aty as $k => $v)
{
$res[]=[$v,$types[$k]];
}
break;
case 4:
//Courbe des recherches
break;
case 5:
//courriers traité dans les délais
$folders= $this->em->getRepository(Courrier::class)->findStatSimpleTreated($s,$e, Courrier::COURRIER_ENTRANT);
$types[$this->container->get('translator')->trans("in_time")]=0;
$types[$this->container->get('translator')->trans("out_time")]=0;
foreach ($folders as $d)
{
$ext = $d->getDate();
$end = $d->getDateCloture();
$pri = $d->getPriorite();
switch ($pri->getType()){
case Priorite::PRI_DAY:
$p ='P'.$pri->getDelais().'D';
$ext->add(new \DateInterval($p));
break;
case Priorite::PRI_WEEK:
$p ='P'.($pri->getDelais()*7).'D';
$ext->add(new \DateInterval($p));
break;
case Priorite::PRI_MONTH:
$p ='P'.$pri->getDelais().'M';
$ext->add(new \DateInterval($p));
break;
}
if($end>=$ext){
$types[$this->container->get('translator')->trans("out_time")]++;
}else{
$types[$this->container->get('translator')->trans("in_time")]++;
}
}
$res[]=[$this->container->get('translator')->trans("in_time"),$types[$this->container->get('translator')->trans("in_time")]];
$res[]=[$this->container->get('translator')->trans("out_time"),$types[$this->container->get('translator')->trans("out_time")]];
break;
case 6:
//pyramide des tâches
$mailIn = $this->em->getRepository(Tache::class)->findStatSimple($s,$e);
$totalIn = count($mailIn);
$doneIn=0;
$awaitIn=0;
foreach ($mailIn as $m)
{
if($m->getStatut()>1){
$doneIn ++;
}
else{
$awaitIn ++;
}
}
if($totalIn==0){
$res=[
["name"=>$this->container->get('translator')->trans("task_treated"),"value"=>0],
["name"=>$this->container->get('translator')->trans("task_in_progress"),"value"=>0]];
}
else{
$res=[
["name"=>$this->container->get('translator')->trans("task_treated"),"value"=>round($doneIn/$totalIn,4)*100],
["name"=>$this->container->get('translator')->trans("task_in_progress"),"value"=>round($awaitIn/$totalIn,4)*100]];
}
break;
case 7:
// tâches effectuées dans les délais
$folders= $this->em->getRepository(Tache::class)->findStatSimpleTreated($s,$e);
$types[$this->container->get('translator')->trans("in_time")]=0;
$types[$this->container->get('translator')->trans("out_time")]=0;
foreach ($folders as $d)
{
$ext = $d->getDateButtoir();
$end = $d->getDateFin();
if($end>$ext){
$types[$this->container->get('translator')->trans("out_time")]++;
}else{
$types[$this->container->get('translator')->trans("in_time")]++;
}
}
$res[]=[$this->container->get('translator')->trans("in_time"),$types[$this->container->get('translator')->trans("in_time")]];
$res[]=[$this->container->get('translator')->trans("out_time"),$types[$this->container->get('translator')->trans("out_time")]];
break;
default:
break;
}
/* if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$this->em->persist($log);
$this->em->flush();
}*/
return ["message"=>"operation_done","data"=>$res, "statut"=>true,"code"=>201];
}
public function getMonitoring(array $data){
if(!array_key_exists("start_date",$data)) return ["message"=>"start_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("end_date",$data)) return ["message"=>"end_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("type",$data)) return ["message"=>"type field is required","statut"=>false,"code"=>401];
$s = \DateTime::createFromFormat('d.m.Y',$data["start_date"])->format("Y-m-d");
$e = \DateTime::createFromFormat('d.m.Y',$data["end_date"])->format("Y-m-d");
$res=[];
switch ($data['type']){
case 1:
$mail = $this->em->getRepository(Courrier::class)->findStatSimpleNonRead($s,$e);
foreach ($mail as $m){
$res[]=$m->toArray();
}
break;
case 2:
$mail = $this->em->getRepository(Courrier::class)->findStatSimpleOutTime($s,$e);
$end = new \DateTime();
foreach ($mail as $m){
$ext = clone $m->getDate();
$pri = $m->getPriorite();
switch ($pri->getType()){
case Priorite::PRI_DAY:
$p ='P'.$pri->getDelais().'D';
$ext->add(new \DateInterval($p));
break;
case Priorite::PRI_WEEK:
$p ='P'.($pri->getDelais()*7).'D';
$ext->add(new \DateInterval($p));
break;
case Priorite::PRI_MONTH:
$p ='P'.$pri->getDelais().'M';
$ext->add(new \DateInterval($p));
break;
}
if($end>$ext){
$el = $m->toArray();
//$dif = $end->diff($ext);
$dif = $end->diff($ext,true);
if($dif->days>0){
$el['exceed'] = $dif->days;
$res[]=$el;
}
}
}
break;
case 3:
$tasks = $this->em->getRepository(Tache::class)->findStatSimpleNotRead($s,$e);
foreach ($tasks as $t){
$res[] = $t->toArray();
}
break;
case 5:
$tasks = $this->em->getRepository(Tache::class)->findStatSimpleOutTime($s,$e);
$end = new \DateTime();
foreach ($tasks as $m){
/*var_dump($m->getInstruction());
var_dump($m->getDateButtoir()->format('Y-m-d'));
var_dump($end->format('Y-m-d'));*/
$ext = $m->getDateButtoir();
if($end>$ext){
$el = $m->toArray();
//$dif = $end->diff($ext);
$dif = $end->diff($ext,true);
if($dif->days>0){
$el['exceed'] = $dif->days;
$res[]=$el;
}
}
}
break;
}
return ["message"=>"operation_done","data"=>$res, "statut"=>true,"code"=>201];
}
public function notifiedRelaunch(array $data){
if(!array_key_exists("type",$data)) return ["message"=>"type field is required","statut"=>false,"code"=>401];
if(!array_key_exists("motif",$data)) return ["message"=>"motif field is required","statut"=>false,"code"=>401];
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>401];
if(!in_array($data['type'],[0,1])) return ["message"=>"bad type field ","statut"=>false,"code"=>401];
if(!in_array($data['motif'],[0,1])) return ["message"=>"bad motif field ","statut"=>false,"code"=>401];
if($data['type'] == 0){
$elt = $this->em->getRepository(Courrier::class)->findOneBy(['id'=>$data['id']]);
}
else{
$elt = $this->em->getRepository(Tache::class)->findOneBy(['id'=>$data['id']]);
}
if($elt === null) return ["message"=>"item not found","statut"=>false,"code"=>401];
$relance = $elt->getRelance();
if($relance !== null){
$relance->setDate(new \DateTime());
if($data['motif'] == 0){
$relance->setNonLu($relance->getNonLu()+1);
}
else{
$relance->setNonTraite($relance->getNonTraite()+1);
}
$elt->setRelance($relance);
}
else{
$relance = new Relance();
$relance->setUser($this->currenUser);
if($data['motif'] == 0){
$relance->setNonLu(1);
}
else{
$relance->setNonTraite(1);
}
if($data['type'] == 0){
$relance->setCourrier($elt);
$relance->setType(Relance::RELANCE_COURRIER);
}
else{
$relance->setTache($elt);
$relance->setType(Relance::RELANCE_TACHE);
}
$elt->setRelance($relance);
}
$notif = new Notification();
$notif->setRelance($relance);
$notif->setUser($this->currenUser);
$notif->setCode(Notification::RELAUNCH);
$statut = new Statut();
$statut->setNotification($notif);
if($data['type'] == 0){
$notif->setCourrier($elt);
$statut->setUser($elt->getDestinataire());
}
else{
$notif->setTache($elt);
$statut->setUser($elt->getUser());
}
$notif->addStatut($statut);
$this->em->persist($notif);
$this->em->persist($elt);
$this->em->flush();
return ["message"=>"operation_done","data"=>$elt->toArray(), "statut"=>true,"code"=>201];
}
public function generateReferenceMail($data)
{
if(!array_key_exists('key',$data)) return ["message"=>"key field is required","statut"=>false,"code"=>""];
$ref=$data['key'];
$date = new \DateTime();
$ref = strtoupper(uniqid($ref.$date->format("Y"), false));
return ["message"=>"","statut"=>true,"data"=>$ref];
}
public function allUserExecptAdmin(array $data)
{
$users = $this->em->getRepository(User::class)->loadAllUsersExecptAdmin();
$tab = [];
foreach ($users as $u){
$tab[]=$u->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$tab];
}
public function createTypeCourrier(array $data)
{
$req=["nom_fr","nom_en","code","attached_file"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
$t = new TypeCourrier();
$t->setNomEn($data["nom_en"]);
$t->setNomFr($data["nom_fr"]);
$t->setCode($data["code"]);
$t->setPossedePieceJointe($data["attached_file"]);
$this->em->persist($t);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$t->toArray()];
}
public function createPieceJointe(array $data)
{
$req=["nom_fr","nom_en","mail_type_id"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
$mailType = $this->em->getRepository(TypeCourrier::class)->findOneBy(['id'=>$data['mail_type_id']]);
if($mailType === null){
return ["message"=>"mail type not found","statut"=>false,"data"=>[]];
}
$t = new PieceJointe();
$t->setNomEn($data["nom_en"]);
$t->setNomFr($data["nom_fr"]);
$t->setTypeCourrier($mailType);
$this->em->persist($t);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$t->toArray()];
}
public function createTypeTache(array $data)
{
$req=["nom_fr","nom_en","code"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
$t = new TypeTache();
$t->setNomEn($data["nom_en"]);
$t->setNomFr($data["nom_fr"]);
$t->setCode($data["code"]);
$this->em->persist($t);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$t->toArray()];
}
public function editTypeCourrier(array $data)
{
$req=["code","nom_fr","nom_en","id","user","attached_file"];
$reqObli=["code","nom_fr","nom_en","id","attached_file"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$typeCourrier = $this->em->getRepository(TypeCourrier::class)->findOneBy(array("id"=>$data["id"]));
if($typeCourrier === null) return ["message"=>"type courrier not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(TypeCourrier::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1));
if($old !== null) {
if($old->getId()!=$typeCourrier->getId())return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
}
$typeCourrier->setCode($data["code"]);
$typeCourrier->setNomEn($data["nom_en"]);
$typeCourrier->setNomFr($data["nom_fr"]);
$typeCourrier->setPossedePieceJointe($data["attached_file"]);
if($data['user'] == ''){
$typeCourrier->setUser(null);
}
else{
$n = $this->em->getRepository(User::class)->findOneBy(['id'=>$data['user']]);
if($n === null) return ["message"=>"user_not_found","statut"=>false,"code"=>"USER_NOT_FOUND"];
$typeCourrier->setUser($n);
}
$this->em->persist($typeCourrier);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT78'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($typeCourrier->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$typeCourrier->toArray()];
}
public function editPiecejointe(array $data)
{
$req=["nom_fr","nom_en","id"];
$reqObli=["nom_fr","nom_en","id"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$piece = $this->em->getRepository(PieceJointe::class)->findOneBy(array("id"=>$data["id"]));
if($piece === null) return ["message"=>"attached file not found","statut"=>false,"code"=>""];
$piece->setNomEn($data["nom_en"]);
$piece->setNomFr($data["nom_fr"]);
$this->em->persist($piece);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT61'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($piece->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$piece->toArray()];
}
public function editTypeTache(array $data)
{
$req=["code","nom_fr","nom_en","id"];
$reqObli=["code","nom_fr","nom_en","id"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$typeTache = $this->em->getRepository(TypeTache::class)->findOneBy(array("id"=>$data["id"]));
if($typeTache === null) return ["message"=>"type tache not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(TypeTache::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1));
if($old !== null) {
if($old->getId()!=$typeTache->getId())return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
}
$typeTache->setCode($data["code"]);
$typeTache->setNomEn($data["nom_en"]);
$typeTache->setNomFr($data["nom_fr"]);
$this->em->persist($typeTache);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT79'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($typeTache->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$typeTache->toArray()];
}
public function editPriorite(array $data)
{
$req=["type","delais","niveau","nom_en","nom_fr","code","id"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
foreach ($req as $el)
{
if(strlen($data[$el])===0) return ["message"=>$el." field is empty","statut"=>false,"code"=>""];
}
$d = $this->em->getRepository(Priorite::class)->findOneBy(array("id"=>$data["id"]));
if($d === null) return ["message"=>"Priorite not found","statut"=>false,"code"=>""];
$d->setType($data["type"]);
$d->setCode($data["code"]);
$d->setNiveau($data["niveau"]);
$d->setDelais($data["delais"]);
$d->setNomFr($data["nom_fr"]);
$d->setNomEn($data["nom_en"]);
$this->em->persist($d);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$d->toArray()];
}
public function createCourtier(array $data)
{
$req=["nom","phone","cni"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
if(strlen($data["nom"])<1) return ["message"=>"nom field is empty","statut"=>false,"code"=>""];
if(strlen($data["cni"])<1) return ["message"=>"cni field is empty","statut"=>false,"code"=>""];
//if(strlen($data["phone"])<9) return ["message"=>"phone field is empty (min 9 characters)","statut"=>false,"code"=>""];
$actor = new Courtier();
$actor->setNom($data["nom"]);
$actor->setCni($data["cni"]);
$actor->setTelephone($data["phone"]);
$this->em->persist($actor);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$actor->toArray()];
}
public function editExternalActor(array $data)
{
$req=["nom","phone","type","email","id","category"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
if(strlen($data["nom"])<1) return ["message"=>"nom field is empty","statut"=>false,"code"=>""];
if(strlen($data["phone"])===0) return ["message"=>"phone field is empty","statut"=>false,"code"=>""];
$actor = $this->em->getRepository(ActeurExterne::class)->findOneBy(['id'=>$data['id']]);
if($actor === null) return ["message"=>"Actor not found","statut"=>false,"code"=>""];
$actor->setNom($data["nom"]);
$actor->setType((int)$data["type"]);
$actor->setTelephone($data["phone"]);
$actor->setCategory($data["category"]);
/*if($data["email"]!='')
{
if(!filter_var($data["email"], FILTER_VALIDATE_EMAIL))
{
return ["message"=>"invalid_email","statut"=>false,"code"=>"EMAIL_INVALID"];
}
}*/
$actor->setEmail($data["email"]);
$this->em->persist($actor);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$actor->toArray()];
}
public function uploadCadre($data){
$maxlevel = 7;
$tabALL = [];
$tabALL[0] = [];
foreach ($data as $t){
for ($i=1;$i<=$maxlevel;$i++){
$test = $i+1;
if(count($t)== $test){
$c = new CadreClassement();
$c->setCode($t[1]);
$c->setIsActive(1);
if($test>2){
$c->setDescEn($t[2]);
}
$c->setDescFr("");
$c->setNomEn($t[0]);
$c->setNomFr($t[0]);
$c->setNiveau($i);
$c->setOrdre(0);
if(!array_key_exists($i,$tabALL)){
$tabALL[$i]=[];
$tabALL[$i][]=$c;
}
else{
$tabALL[$i][]=$c;
}
}
}
}
$tl = count($tabALL);
for ($i=2;$i<=$tl;$i++){
$parents = $tabALL[$i-1];
if(array_key_exists($i,$tabALL)){
$sons = $tabALL[$i];
foreach ($sons as $key=>$val){
foreach ($parents as $p){
if($p->getCode()===$val->getDescEn()){
$p->addCadreClassement($val);
$val->setCardreClassement($p);
$val->setDescEn("");
}
}
}
}
}
foreach ($tabALL[1] as $p){
$this->em->persist($p);
}
$this->em->flush();
return [];
}
public function importNewCategories($data){
$okVal = [];
foreach ($data as $d){
$old = $this->em->getRepository(TypeDossier::class)->findOneBy(["code"=>$d]);
if($old === null){
$okVal[]=$d;
$d = new TypeDossier();
$d->setCode($d);
$d->setNomEn($d);
$d->setNomFr($d);
$this->em->persist($d);
}
}
$this->em->flush();
return $d;
}
public function saveMultiple(string $fi)
{
$fp = fopen($fi, "r");
$i=0;
$tab=[];
// lecture ligne par ligne tant qu'on ne rencontre pas le code: fin de fichier(feof)
while(!feof($fp))
{
$tab[$i]=fgetcsv($fp, 100000, ",");
$i++;
}
$j=-1;
//$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT38'));
foreach ($tab as $r) {
$j++;
if(count($r)==16 && $j>=1) {
//var_dump(trim($r[5]));
$type = $this->em->getRepository(TypeDossier::class)->findOneBy(array("code"=>trim($r[1])));
if(is_null($type)){
$type = new TypeDossier();
$type->setNomFr($r[1]);
$type->setNomEn($r[1]);
$type->setCode($r[1]);
$this->em->persist($type);
$this->em->flush();
}
$b = $this->em->getRepository(Bordereau::class)->findOneBy(array("numero"=>"000001"));
//if(is_null($b)) return ["message"=>"bordereau not found","statut"=>false,"code"=>""];
$conf = $this->em->getRepository(TypeConfidentialite::class)->findOneBy(array("niveau"=>1));
//if(is_null($conf)) return ["message"=>"type confidentialite not found","statut"=>false,"code"=>""];
$cadre = $this->em->getRepository(CadreClassement::class)->findOneBy(array("code"=>trim($r[13])));
//if(is_null($cadre)) return ["message"=>"cadre de classement not found","statut"=>false,"code"=>""];
if(is_null($cadre)) return "cadre de classement not found ".$r[0];
$rayon = $this->em->getRepository(Rayon::class)->findOneBy(array("code"=>trim($r[9])));
//if(is_null($rayon)) return ["message"=>"rayonnage not found","statut"=>false,"code"=>""];
$dossier = new Dossier();
$dossier->setType($type);
$dossier->setBordereau($b);
$dossier->setTitre(trim($r[2]));
$dossier->setObservation("");
$dossier->setLangue(strtolower(trim($r[5])));
$dossier->setCadreClassement($cadre);
$dossier->setRayon($rayon);
$dossier->setEtagere(trim($r[10]));
$dossier->setBoite(trim($r[11]));
$dossier->setOrdreRangement(trim($r[14]));
$dossier->setNbPiece(1);
$dossier->setCoteDossier($cadre->getCode());
$dossier->setDescription("");
$dossier->setReference($this->generateReference()["data"]);
$dossier->setTypeConfidentialite($conf);
$dossier->setContent(trim($r[12]));
$dossier->setStatut(1);
$dossier->setDateCloture(\DateTime::createFromFormat('d/m/Y',trim($r[15])));
$dossier->setDateCreation(\DateTime::createFromFormat('d/m/Y',trim($r[4])));
$dossier->setDateType(Dossier::DATE_NORMAL);
$file_a = new Fichier();
$file_a->setNom(trim($r[0]));
$file_a->setFolderNameAndName(trim($r[2])." | ". trim($r[0]));
$file_a->setExtension(".");
$file_a->setType("application/pdf");
$file_a->setTaille(120000);
$file_a->setPath(trim($r[0]));
$file_a->setAuteur("admin admin");
$file_a->setDossier($dossier);
$dossier->addFichier($file_a);
$this->em->persist($dossier);
}
}
try{
$this->em->flush();
}
catch (\Exception $e)
{
return $e->getMessage()." ".$e->getFile()."line ".$e->getLine();
}
fclose($fp);
return "operation_done ".$j;
}
public function createEtagere(array $data)
{
$req=["code","rayon","face"];
$reqObli=["code","rayon","face"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$old = $this->em->getRepository(Etagere::class)->findOneBy(array("code"=>$data["code"],"rayon"=>$data["rayon"], "isActive"=>1));
if($old !== null) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
$rayon = $this->em->getRepository(Rayon::class)->findOneBy(['id'=>$data['rayon']]);
if($rayon === null) return ["message"=>$this->container->get('translator')->trans('shelving_not_found'),"statut"=>false,"code"=>401];
$eta = new Etagere();
$eta->setCode($data["code"]);
$eta->setFace($data["face"]);
$eta->setRayon($rayon);
$this->em->persist($eta);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT73'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($eta->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$eta->toArray()];
}
public function createBoite(array $data)
{
$req=["code","etagere","type"];
$reqObli=["code","etagere","type"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$old = $this->em->getRepository(Boite::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1));
if($old !== null) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
$eta = $this->em->getRepository(Etagere::class)->findOneBy(['id'=>$data['etagere']]);
if($eta === null) return ["message"=>$this->container->get('translator')->trans('rack_not_found'),"statut"=>false,"code"=>401];
$box = new Boite();
$box->setCode($data["code"]);
$box->setType((int)$data["type"]);
$box->setEtagere($eta);
$this->em->persist($box);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT74'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($box->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$eta->toArray()];
}
public function editEtagere(array $data)
{
$req=["code","rayon","id","face"];
$reqObli=["code","rayon","id","face"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$eta = $this->em->getRepository(Etagere::class)->findOneBy(array("id"=>$data["id"]));
if($eta === null) return ["message"=>"shelf not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(Etagere::class)->findOneBy(array("code"=>$data["code"],"rayon"=>$data["rayon"],"isActive"=>1));
if($old !== null) {
if($old->getId()!=$eta->getId())return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
}
$rayon = $this->em->getRepository(Rayon::class)->findOneBy(['id'=>$data['rayon']]);
if($rayon === null) return ["message"=>$this->container->get('translator')->trans('shelving_not_found'),"statut"=>false,"code"=>401];
$eta->setCode($data["code"]);
$eta->setFace($data["face"]);
$eta->setRayon($rayon);
$this->em->persist($eta);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT75'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($eta->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$eta->toArray()];
}
public function editBoite(array $data)
{
$req=["code","etagere","id","type"];
$reqObli=["code","etagere","id","type"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$box = $this->em->getRepository(Boite::class)->findOneBy(array("id"=>$data["id"]));
if($box === null) return ["message"=>"box not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(Boite::class)->findOneBy(array("code"=>$data["code"],"isActive"=>1));
if($old !== null) {
if($old->getId()!=$box->getId())return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
}
$eta = $this->em->getRepository(Etagere::class)->findOneBy(['id'=>$data['etagere']]);
if($eta === null) return ["message"=>$this->container->get('translator')->trans('rack_not_found'),"statut"=>false,"code"=>401];
$box->setCode($data["code"]);
$box->setType((int)$data["type"]);
$box->setEtagere($eta);
$this->em->persist($box);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT76'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($box->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$box->toArray()];
}
public function simpleSearchBordereau(array $data)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>""];
$res = $this->em->getRepository(Bordereau::class)->searchSimple($data["keywords"]);
$datas=[];
foreach ($res as $el)
{
$datas[]=$el->toArray();
}
/*
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT06'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($data["keywords"]);
$this->em->persist($log);
$this->em->flush();
}
*/
return ["message"=>"","statut"=>true,"data"=>$datas];
}
public function listOfFolderAwaiting(array $data)
{
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
if(!array_key_exists('category',$data)){
return ["message"=>"field category is required","statut"=>false,"code"=>401];
}
$total = $this->em->getRepository(Dossier::class)->findForTreatNb($data['search']['value'],$this->currenUser->getLevel(),$data['category']);
$folders = $this->em->getRepository(Dossier::class)->findForTreat($data['search']['value'],$this->currenUser->getLevel(),$data['category'],$offset,$limit);
//var_dump(count($total));
//var_dump(count($folders));
$res =[];
foreach ($folders as $f)
{
$res[] = $f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function listOfFolderToDelete(array $data)
{
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$regles = $this->em->getRepository(RegleConservation::class)->findBy(array("isActive"=>true,"sortFinal"=>"1"));
$ty=[];
$types=[];
$final=[];
foreach ($regles as $r)
{
$types[]=$r->getTypeDossier()->getId();
switch ($r->getDureeDossier()->getTypeConsevation())
{
case DureeDossier::ANNEE:
$nb=$r->getDureeDossier()->getConservation();
$add = 365*$nb;
$ty["type_".$r->getTypeDossier()->getId()]=$add;
break;
case DureeDossier::MOIS:
$nb=$r->getDureeDossier()->getConservation();
$ty["type_".$r->getTypeDossier()->getId()]=30*$nb;
break;
case DureeDossier::SEMAINE:
$nb=$r->getDureeDossier()->getConservation();
$add = 7*$nb;
$ty["type_".$r->getTypeDossier()->getId()]=$add;
break;
case DureeDossier::JOUR:
$nb=$r->getDureeDossier()->getConservation();
$ty["type_".$r->getTypeDossier()->getId()]=$nb;
break;
default:
$ty["type_".$r->getTypeDossier()->getId()]=365*4;
break;
}
}
$level = $this->currenUser->getLevel();
//$total = $this->em->getRepository(Dossier::class)->findForDeleteNb($level,$types);
$folders = $this->em->getRepository(Dossier::class)->findForDelete($level,$types);
$empty = $this->em->getRepository(Dossier::class)->findEmptyFolder();
if(count($empty)>0){
foreach ($empty as $e){
$e->setIsActive(false);
$e->setDossierParent(null);
$subFolders = $e->getSousDossiers();
foreach ($subFolders as $s){
$s->setDossierParent(null);
$this->em->persist($s);
}
$demandes= $this->em->getRepository(DossierDemande::class)->findBy(['dossier'=>$e,'isActive'=>1]);
$wkg= $this->em->getRepository(DossierWorkgroup::class)->findBy(['dossier'=>$e,'isActive'=>1]);
foreach ($demandes as $d){
$d->setIsActive(false);
$this->em->persist($d);
}
foreach ($wkg as $w){
$w->setIsActive(false);
$this->em->persist($w);
}
$this->em->persist($e);
}
$this->em->flush();
}
foreach ($folders as $d)
{
$date = new \DateTime();
$tocompare = $d->getDateCreation();
$diff = $date->diff($tocompare)->days;
if($diff>$ty["type_".$d->getType()->getId()])
{
$final[]=$d->toArray();
}
}
$total = count($final);
$send = [];
$i = -1;
$max = $offset + $limit - 1;
if($max <= 0){
$max = 0;
}
foreach ($final as $f){
$i=$i+1;
if($i>=$offset and $i<= $max){
$send[]=$f;
}
}
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT52'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>["empty_folder"=>count($empty), "folders"=>$send,"total_item"=>$total,"current_page"=>1 + $offset/$limit,"code"=>201]];
}
private function manageDatatable(array $data){
}
public function listOfUserNewRequest(array $data)
{
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$total = $this->em->getRepository(DemandeArchive::class)->findForUserNewNb($this->currenUser->getId());
$folders = $this->em->getRepository(DemandeArchive::class)->findForUserNew($this->currenUser->getId(),$offset,$limit);
$res =[];
foreach ($folders as $f)
{
$res[] = $f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function listOfUserTreatedRequest(array $data)
{
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$total = $this->em->getRepository(DemandeArchive::class)->findForUserTreatedNb($this->currenUser->getId());
$folders = $this->em->getRepository(DemandeArchive::class)->findForUserTreated($this->currenUser->getId(),$offset,$limit);
$res =[];
foreach ($folders as $f)
{
$res[] = $f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
private function testRole($role): bool
{
if ($this->currentUser === "anon.") {
return false;
}
if ($this->currentUser->getType() == 1) {
return true;
}
$userRoles = $this->currentUser->getUserRoles();
$serviceRoles = $this->currentUser->getService()->getRoles();
$roles = array_merge(
is_array($userRoles) ? $userRoles : $userRoles->toArray(),
is_array($serviceRoles) ? $serviceRoles : $serviceRoles->toArray()
);
foreach ($roles as $r) {
if ($r->getCode() === $role) {
return true;
}
}
return false;
}
public function listOfAllNewRequest(array $data)
{
if(!$this->testRole('M_DAT')){
return ["message"=>"operation denied","statut"=>false,"code"=>401,"data"=>""];
}
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$total = $this->em->getRepository(DemandeArchive::class)->findForAllUserNewNb();
$folders = $this->em->getRepository(DemandeArchive::class)->findForAllUserNew($offset,$limit);
$res =[];
foreach ($folders as $f)
{
$res[] = $f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function listOfAllTreatedRequest(array $data)
{
if(!$this->testRole('M_DAT')){
return ["message"=>"operation denied","statut"=>false,"code"=>401,"data"=>""];
}
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$total = $this->em->getRepository(DemandeArchive::class)->findForAllUserTreatedNb();
$folders = $this->em->getRepository(DemandeArchive::class)->findForAllUserTreated($offset,$limit);
$res =[];
foreach ($folders as $f)
{
$res[] = $f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function simpleSearchBoite(array $data)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>""];
$res = $this->em->getRepository(Boite::class)->searchSimple($data["keywords"]);
$datas=[];
foreach ($res as $el)
{
$datas[]=$el->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$datas];
}
public function uploadMultipleCadre(array $data)
{
if(!array_key_exists("file",$data)) return ["message"=>"file field is required","statut"=>false,"code"=>401];
$file =$this->container->get('upload_service')->uploadBase64($data["file"]);
if($file["statut"]==false) return ["message"=>"error_file_upload","statut"=>false,"code"=>401];
$f = $this->container->get('upload_service')->getTargetDirectory()."/FOLDER/".$file["file"]["path"];
$tab = [];
$allCodeFull = $this->em->getRepository(CadreClassement::class)->findAllCode();
$allCode =[];
foreach ($allCodeFull as $el){
$allCode[]=$el["code"];
}
if (($handle = fopen($f, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//$num = count($data);
$t = [];
foreach ($data as $index=>$val){
if($val!==""){
$t[] =$val;
}
}
/*for ($c=0; $c < $num; $c++) {
$t[] = $data[$c];
}*/
$tab[]=$t;
}
fclose($handle);
$maxlevel = 7;
$tabALL = [];
$tabALL[0] = [];
foreach ($tab as $index=> $t){
for ($i=1;$i<=$maxlevel;$i++){
$test = $i+1;
if(count($t) === $test){
if(in_array($t[1],$allCode)){
$c = $this->em->getRepository(CadreClassement::class)->findOneBy(['code'=>$t[1]]);
if($c === null){
return ["message"=>"oops cadre not founded","statut"=>false, "code"=>401,"data"=>[]];
}
}
else{
$c = new CadreClassement();
$c->setCode($t[1]);
$c->setIsActive(1);
if($test>2){
$c->setDescEn($t[2]);
}
$c->setDescFr("");
$c->setNomEn($t[0]);
$c->setNomFr($t[0]);
$c->setNiveau($i);
$c->setOrdre(0);
}
if(!array_key_exists($i,$tabALL)){
$tabALL[$i]=[];
$tabALL[$i][]=$c;
}
else{
$tabALL[$i][]=$c;
}
}
}
}
$tl = count($tabALL);
for ($i=2;$i<=$tl;$i++){
if(array_key_exists($i-1,$tabALL)){
$parents = $tabALL[$i-1];
if(array_key_exists($i,$tabALL)){
$sons = $tabALL[$i];
foreach ($sons as $key=>$val){
foreach ($parents as $p){
if($p->getCode()===$val->getDescEn()){
$p->addCadreClassement($val);
$val->setCardreClassement($p);
$val->setDescEn("");
}
}
}
}
}
}
$added = 0;
foreach ($tabALL[1] as $p){
$this->em->persist($p);
$added++;
}
$this->em->flush();
unlink($f);
return ["message"=>$this->container->get('translator')->trans('item_added')." ".$added,"statut"=>true, "code"=>201,"data"=>[]];
}else{
return ["message"=>$this->container->get('translator')->trans('file_incorrect'),"statut"=>false, "code"=>401,"data"=>[]];
}
}
public function uploadAllRoomInfo(array $data)
{
if(!array_key_exists("file",$data)) return ["message"=>"file field is required","statut"=>false,"code"=>401];
$file =$this->container->get('upload_service')->uploadBase64($data["file"]);
if($file["statut"]==false) return ["message"=>"error_file_upload","statut"=>false,"code"=>401];
$f = $this->container->get('upload_service')->getTargetDirectory()."/FOLDER/".$file["file"]["path"];
$tab = [];
$allCodeFullBoite = $this->em->getRepository(Boite::class)->findAllCode();
$allCodeBoite =[];
foreach ($allCodeFullBoite as $el){
$allCodeBoite[]=$el["code"];
}
$allCodeFullSalle = $this->em->getRepository(Salle::class)->findAllCode();
$allCodeSalle =[];
foreach ($allCodeFullSalle as $el){
$allCodeSalle[]=$el["code"];
}
$tabArchiveLocation = [];
if (($handle = fopen($f, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$t = [];
foreach ($data as $index=>$val){
if($val!==""){
$t[] =$val;
}
}
if(count($t)===6){
$tab[]=$t;
}
}
fclose($handle);
foreach ($tab as $t){
if(!in_array($t[0],$allCodeBoite)){
$archiveLocationCode = $t[5];
$roomCode = $t[4];
if(!array_key_exists($archiveLocationCode,$tabArchiveLocation)){
$tabArchiveLocation[$archiveLocationCode]=[];
$tabArchiveLocation[$archiveLocationCode]["rooms"]=[];
}
if(!array_key_exists($roomCode,$tabArchiveLocation[$archiveLocationCode]["rooms"])){
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]=[];
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"]=[];
}
if(!array_key_exists($t[2],$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"])){
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]=[];
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['etagere']=[];
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['face']=[];
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['face'][]=$t[3];
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['etagere'][$t[1]]=['code'=>$t[1],'face'=>$t[3],'box'=>[]];
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['etagere'][$t[1]]['box'][]=$t[0];
}else{
if(!in_array($t[3],$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['face'])){
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['face'][]=$t[3];
}
if(!array_key_exists($t[1],$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['etagere'])){
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['etagere'][$t[1]]=['code'=>$t[1],'face'=>$t[3],'box'=>[]];
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['etagere'][$t[1]]['box'][]=$t[0];
}
else{
$tabArchiveLocation[$archiveLocationCode]["rooms"][$roomCode]["rayon"][$t[2]]['etagere'][$t[1]]['box'][]=$t[0];
}
}
}
}
$nb=0;
foreach ($tabArchiveLocation as $archiveLocationKey=>$archiveLocationData){
$archiveLocation = $this->em->getRepository(ArchiveLocation::class)->findOneBy(['code'=>$archiveLocationKey]);
if($archiveLocation === null){
$archiveLocation = new ArchiveLocation();
$archiveLocation->setCode($archiveLocationKey);
}
foreach ($archiveLocationData['rooms'] as $roomKey=>$room){
if(in_array($roomKey,$allCodeSalle)){
$salle = $this->em->getRepository(Salle::class)->findOneBy(['code'=>$roomKey]);
if($salle === null){
return ["message"=>"oops room not founded","statut"=>false, "code"=>401,"data"=>[]];
}
}
else{
$salle = new Salle();
$salle->setCode($roomKey);
}
$allRayon = $this->em->getRepository(Rayon::class)->findAllByRoomCode($roomKey);
$allRayonCode = [];
foreach ($allRayon as $el){
$allRayonCode[]=$el["code"];
}
foreach ($room['rayon'] as $rayonKey=>$r){
if(in_array($rayonKey,$allRayonCode)){
$rayon = $this->em->getRepository(Rayon::class)->findOneBy(['code'=>$rayonKey]);
if($rayon === null){
return ["message"=>"oops rayon not founded","statut"=>false, "code"=>401,"data"=>[]];
}
}
else{
$rayon = new Rayon();
$rayon->setCode($rayonKey);
$rayon->setSalle($salle);
$rayon->setNbFace(count($r['face']));
}
$allEtagere = $this->em->getRepository(Etagere::class)->findAllByRayonCode($rayonKey);
$allEtagereCode = [];
foreach ($allEtagere as $el){
$allEtagereCode[]=$el["code"];
}
foreach ($r['etagere'] as $etKey=>$eta){
if(in_array($etKey,$allEtagereCode)){
$etagere = $this->em->getRepository(Etagere::class)->findOneBy(['code'=>$etKey]);
if($etagere === null){
return ["message"=>"oops etagere not founded","statut"=>false, "code"=>401,"data"=>[]];
}
}
else{
$etagere = new Etagere();
$etagere->setCode($etKey);
$etagere->setRayon($rayon);
$etagere->setFace($eta['face']);
}
foreach ($eta['box'] as $b){
if(!in_array($b,$allCodeBoite)){
$boite = new Boite();
$boite->setCode($b);
$boite->setEtagere($etagere);
$etagere->addBoite($boite);
$nb++;
}
}
$rayon->addEtagere($etagere);
}
$salle->addRayon($rayon);
}
$archiveLocation->addSalle($salle);
}
$this->em->persist($archiveLocation);
}
$this->em->flush();
unlink($f);
return ["message"=>$this->container->get('translator')->trans('item_added'),"statut"=>true, "code"=>201,"data"=>[]];
}else{
return ["message"=>$this->container->get('translator')->trans('file_incorrect'),"statut"=>false, "code"=>401,"data"=>[]];
}
}
public function sendSms(array $data){
$req =['phones','message'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
$phones = [];
foreach ($data['phones'] as $p){
$phones[]='237'.$p;
}
$headers=['token' => $this->container->getParameter('app.sms_api_token'),
'Content-Type' => 'application/json',];
$body = \Unirest\Request\Body::json([
'from'=>$this->container->getParameter('app.name'),
'to'=>$phones,
'type'=>'Text',
'content'=>$data['message'],
'sendDateTime'=>''
]);
$response = \Unirest\Request::post($this->container->getParameter('app.sms_api_url'), $headers, $body);
$result= json_decode($response->raw_body,true);
if($response->code==200)
{
return ["message"=>"","statut"=>true,"data"=>$result];
}
return ["message"=>"error","statut"=>false,"data"=>$result];
}
public function listOfFolderAwaitingPersonnel(array $data)
{
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
if(!array_key_exists('category',$data)){
return ["message"=>"field category is required","statut"=>false,"code"=>401];
}
$total1 = $this->em->getRepository(Dossier::class)->findForTreatNbPersonnelOfficer($this->currenUser->getLevel());
$total2 = $this->em->getRepository(Dossier::class)->findForTreatNbPersonnelSOfficer($this->currenUser->getLevel());
$folders1 = $this->em->getRepository(Dossier::class)->findForTreatPersonnelOfficer($this->currenUser->getLevel(),$offset,$limit);
$folders2 = $this->em->getRepository(Dossier::class)->findForTreatPersonnelSOfficer($this->currenUser->getLevel(),$offset,$limit);
$res =[];
foreach ($folders1 as $f)
{
$res[] = $f->toArray();
}
foreach ($folders2 as $f)
{
$res[] = $f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>count($total1) + count($total2),"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function createRegisterItem(array $data)
{
$req=["reference","date", "matricule","name","motif","taux",'type',"unit","mention","grade","folder","departure_date","come_back_date","hospital_enter_date","file"];
$reqObli=["reference","type","grade","name","date"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$item = new RegisterItem();
$item->setReference($data["reference"]);
$item->setMatricule($data["matricule"]);
$item->setName($data["name"]);
$item->setMotif($data["motif"]);
$item->setTaux($data["taux"]);
$item->setType($data["type"]);
$item->setUnit($data["unit"]);
$item->setMention($data["mention"]);
$item->setGrade($data["grade"]);
$haveAfolder = false;
if(strlen($data["folder"])>0){
$folder = $this->em->getRepository(Dossier::class)->findOneBy(['refInterne'=>$data["folder"]]);
if($folder === null){
return ["message"=>"folder not found","statut"=>false,"code"=>401];
}
$item->setFolder($folder);
$haveAfolder = true;
}
try {
if(strlen($data["departure_date"])>0){
$s = \DateTime::createFromFormat('d/m/Y',$data["departure_date"]);
$item->setDepartureDate($s);
}
if(strlen($data["come_back_date"])>0){
$s = \DateTime::createFromFormat('d/m/Y',$data["come_back_date"]);
$item->setComeBackDate($s);
}
if(strlen($data["date"])>0){
$s = \DateTime::createFromFormat('d/m/Y',$data["date"]);
$item->setDateOperation($s);
}
if(strlen($data["hospital_enter_date"])>0){
$s = \DateTime::createFromFormat('d/m/Y',$data["hospital_enter_date"]);
$item->setHospitalEnterDate($s);
}
}
catch (\Exception $e){
return ["message"=>$e->getMessage(),"statut"=>false,"code"=>401];
}
if(is_array($data['file'])&&count($data['file'])>0){
$f = $data['file'];
$file = new Fichier();
$file->setFolderNameAndName($item->getMatricule()." | ". $data['file']["name"]);
$file->setNom($f["name"]);
$file->setExtension($f["extension"]);
$file->setType($f["type"]);
$file->setTaille($f["size"]);
$file->setPath($f["path"]);
$userU = $this->getCurrentUser();
$file->setAuteur($userU["data"]["nom"]." ".$userU["data"]["prenom"]);
if($haveAfolder){
$file->setDossier($folder);
$folder->addFichier($file);
$this->em->persist($folder);
}
$item->setFile($file);
}
$this->em->persist($item);
$this->em->flush();
/* $log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT09'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($service->getId());
$this->em->persist($log);
$this->em->flush();
}*/
return ["message"=>"","statut"=>true,"data"=>$item->toArray()];
}
public function editRegisterItem(array $data)
{
$req=["id","date", "reference","matricule","name","motif","taux",'type',"unit","mention","grade","folder","departure_date","come_back_date","hospital_enter_date","file"];
$reqObli=["id", "reference","type","date"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else{
if(in_array($val,$reqObli))
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$item = $this->em->getRepository(RegisterItem::class)->findOneBy(['id'=>$data['id']]);
if($item === null){
return ["message"=>"register item not found","statut"=>false,"code"=>401];
}
$item->setReference($data["reference"]);
$item->setMatricule($data["matricule"]);
$item->setName($data["name"]);
$item->setMotif($data["motif"]);
$item->setTaux($data["taux"]);
$item->setType($data["type"]);
$item->setUnit($data["unit"]);
$item->setMention($data["mention"]);
$item->setGrade($data["grade"]);
$haveAfolder = false;
if(strlen($data["folder"])>0){
$folder = $this->em->getRepository(Dossier::class)->findOneBy(['refInterne'=>$data["folder"]]);
if($folder === null){
return ["message"=>"folder not found","statut"=>false,"code"=>401];
}
$item->setFolder($folder);
$haveAfolder = true;
}
try {
if(strlen($data["departure_date"])>0){
$s = \DateTime::createFromFormat('d/m/Y',$data["departure_date"]);
$item->setDepartureDate($s);
}
if(strlen($data["come_back_date"])>0){
$s = \DateTime::createFromFormat('d/m/Y',$data["come_back_date"]);
$item->setComeBackDate($s);
}
if(strlen($data["date"])>0){
$s = \DateTime::createFromFormat('d/m/Y',$data["date"]);
$item->setDateOperation($s);
}
if(strlen($data["hospital_enter_date"])>0){
$s = \DateTime::createFromFormat('d/m/Y',$data["hospital_enter_date"]);
$item->setHospitalEnterDate($s);
}
}
catch (\Exception $e){
return ["message"=>$e->getMessage(),"statut"=>false,"code"=>401];
}
if(is_array($data['file'])&&count($data['file'])>0){
$f = $data['file'];
$file = new Fichier();
$file->setNom($f["name"]);
$file->setFolderNameAndName($item->getMatricule()." | ". $data['file']["name"]);
$file->setExtension($f["extension"]);
$file->setType($f["type"]);
$file->setTaille($f["size"]);
$file->setPath($f["path"]);
$userU = $this->getCurrentUser();
$file->setAuteur($userU["data"]["nom"]." ".$userU["data"]["prenom"]);
if($haveAfolder){
$file->setDossier($folder);
$folder->addFichier($file);
$this->em->persist($folder);
}
$item->setFile($file);
}
if($item->getFolder()!== null){
$fol = $item->getFolder();
if($item->getFile() !== null){
$fileE = $item->getFile();
if(!$fol->getFichiers()->contains($fileE)){
$fileE->setDossier($fol);
$fol->addFichier($fileE);
$this->em->persist($fol);
}
}
}
$this->em->persist($item);
$this->em->flush();
/* $log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT09'));
if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($service->getId());
$this->em->persist($log);
$this->em->flush();
}*/
return ["message"=>"","statut"=>true,"data"=>$item->toArray()];
}
public function getRegisterItems(array $data)
{
if(!array_key_exists("type",$data)) return ["message"=>"field type is required","statut"=>false,"data"=>"","code"=>401];
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$total = $this->em->getRepository(RegisterItem::class)->findItemsNb($data['search']['value'],$data["type"]);
$folders = $this->em->getRepository(RegisterItem::class)->findItems($data['search']['value'],$data["type"],$offset,$limit);
$res =[];
foreach ($folders as $f)
{
$res[] = $f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function getStatisticRegister(array $data)
{
if(!array_key_exists("start_date",$data)) return ["message"=>"start_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("end_date",$data)) return ["message"=>"end_date field is required","statut"=>false,"code"=>401];
if(!array_key_exists("type",$data)) return ["message"=>"type field is required","statut"=>false,"code"=>401];
$s = \DateTime::createFromFormat('d.m.Y',$data["start_date"])->format("Y-m-d");
$e = \DateTime::createFromFormat('d.m.Y',$data["end_date"])->format("Y-m-d");
$res=[];
switch ($data["type"])
{
case 1:
$dossiers = $this->em->getRepository(RegisterItem::class)->findStatSimple($s,$e, 1);
$res=[];
$res["dates"]=$this->getDatesFromRange($s, $e);
$res["x"][]='Dates';
foreach ($res["dates"] as $t)
{
$res["x"][]=$t;
}
$types=[];
$dates=$res["dates"];
foreach ($dates as $t)
{
$types[$t]=0;
}
foreach ($dossiers as $d)
{
$types[$d->getDateOperation()->format("Y-m-d")]++;
}
$tab=[];
$tab[]=$this->container->get('translator')->trans("punition");
foreach ($types as $key=>$val)
{
$tab[]=$val;
}
$res["data"][]=$tab;
$res["type"]=$types;
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
for($j=0;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
//$res["data2"]=$main;
$res["data"]=[$tab];
$res["total"]=count($dossiers);
break;
case 2:
$dossiers = $this->em->getRepository(RegisterItem::class)->findStatSimple($s,$e, 2);
$res=[];
$res["dates"]=$this->getDatesFromRange($s, $e);
$res["x"][]='Dates';
foreach ($res["dates"] as $t)
{
$res["x"][]=$t;
}
$types=[];
$dates=$res["dates"];
foreach ($dates as $t)
{
$types[$t]=0;
}
foreach ($dossiers as $d)
{
$types[$d->getDateOperation()->format("Y-m-d")]++;
}
$tab=[];
$tab[]=$this->container->get('translator')->trans("evasant");
foreach ($types as $key=>$val)
{
$tab[]=$val;
}
$res["data"][]=$tab;
$res["type"]=$types;
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
for($j=0;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
//$res["data2"]=$main;
$res["data"]=[$tab];
$res["total"]=count($dossiers);
break;
case 3:
$dossiers = $this->em->getRepository(RegisterItem::class)->findStatSimple($s,$e, 3);
$res=[];
$res["dates"]=$this->getDatesFromRange($s, $e);
$res["x"][]='Dates';
foreach ($res["dates"] as $t)
{
$res["x"][]=$t;
}
$types=[];
$dates=$res["dates"];
foreach ($dates as $t)
{
$types[$t]=0;
}
foreach ($dossiers as $d)
{
$types[$d->getDateOperation()->format("Y-m-d")]++;
}
$tab=[];
$tab[]=$this->container->get('translator')->trans("desertion");
foreach ($types as $key=>$val)
{
$tab[]=$val;
}
$res["data"][]=$tab;
$res["type"]=$types;
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
for($j=0;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
//$res["data2"]=$main;
$res["data"]=[$tab];
$res["total"]=count($dossiers);
break;
case 4:
$dossiers = $this->em->getRepository(RegisterItem::class)->findStatSimple($s,$e, 4);
$res=[];
$res["dates"]=$this->getDatesFromRange($s, $e);
$res["x"][]='Dates';
foreach ($res["dates"] as $t)
{
$res["x"][]=$t;
}
$types=[];
$dates=$res["dates"];
foreach ($dates as $t)
{
$types[$t]=0;
}
foreach ($dossiers as $d)
{
$types[$d->getDateOperation()->format("Y-m-d")]++;
}
$tab=[];
$tab[]=$this->container->get('translator')->trans("all");
foreach ($types as $key=>$val)
{
$tab[]=$val;
}
$res["data"][]=$tab;
$res["type"]=$types;
$length = count($res["data"]);
$totald= count($dates)+1;
$removeindex=[];
for($j=1;$j<$totald;$j++)
{
$som=0;
for($i=0;$i<$length;$i++)
{
$som=$som+$res["data"][$i][$j];
}
if($som==0)
{
$removeindex[]=$j;
}
}
$main=[];
foreach ($res["data"] as $t)
{
$ta=[];
for($j=0;$j<$totald;$j++)
{
if(!in_array($j,$removeindex))
{
$ta[]=$t[$j];
}
}
$main[]=$ta;
}
//$res["data2"]=$main;
$res["data"]=[$tab];
$res["total"]=count($dossiers);
break;
default:
break;
}
/* if(!is_null($operation))
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$this->em->persist($log);
$this->em->flush();
}*/
return ["message"=>"operation_done","data"=>$res, "statut"=>true,"code"=>201];
}
public function deleteSingleFolder(array $data)
{
$req =["id"];
foreach ($req as $r)
{
if(!array_key_exists($r,$data)) return ["message"=>$r." field is required","statut"=>false,"code"=>401];
}
$d= $this->em->getRepository(Dossier::class)->findOneBy(array("id"=>$data['id'],"isActive"=>true));
if(!is_null($d)){
$d->setIsActive(false);
}
$this->em->persist($d);
$this->em->flush();
return ["message"=>"operation_done","statut"=>true,"code"=>201,"data"=>[]];
}
public function advancedSearchMail(array $data)
{
$req=["titre","type_courrier","reference","start_date","end_date"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>401];
}
if($data["start_date"]!="")
{
if(preg_match("/^[a-zA-Z]+$/", $data["start_date"])==false){
$d = \DateTime::createFromFormat('d/m/Y',$data["start_date"]);
$data["start_date"] =$d->format("Y-m-d")." 00:00:01";
$data["start_date_1"] =$d->format("Y-m-d");
$data["start_date_2"] =$d->format("Y-m-d")." 23:59:59";
}
}
if($data["end_date"]!="")
{
if(preg_match("/^[a-zA-Z]+$/", $data["end_date"])==false){
$d = \DateTime::createFromFormat('d/m/Y',$data["end_date"]);
$data["end_date"] =$d->format("Y-m-d")." 00:00:01";
$data["end_date_1"] =$d->format("Y-m-d");
$data["end_date_2"] =$d->format("Y-m-d")." 23:59:59";
}
}
//$da = $this->em->getRepository(Dossier::class)->findAdvanced($level,$data);
$level = $this->currenUser->getLevel();
try {
$da = $this->container->get(FOSElasticSearchServiceMail::class)->searchAdvancedMail($data,$level);
}
catch (\Exception $e){
return ["message"=>$e->getMessage()." ".$e->getLine(),"data"=>[], "statut"=>false,"code"=>401];
}
$res=[];
foreach ($da as $d)
{
$res[]=$d->toArray();
}
return ["message"=>"operation_done","data"=>$res, "statut"=>true,"code"=>201];
}
public function advancedSearchAttachment(array $data)
{
$req=["titre","reference","bordereau"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>401];
}
$level = $this->currenUser->getLevel();
try {
$da = $this->container->get(FOSElasticSearchAttachmentService::class)->advancedSearchAttachment($data,$level);
}
catch (\Exception $e){
return ["message"=>$e->getMessage()." ".$e->getLine(),"data"=>[], "statut"=>false,"code"=>401];
}
$res=[];
foreach ($da as $d)
{
$res[]=$d->toArrayForSearch();
}
return ["message"=>"operation_done","data"=>$res, "statut"=>true,"code"=>201];
}
public function listWaitingMail(array $data)
{
$offset = 0;
$limit = 100;
if(array_key_exists("offset",$data)){
$offset = intval($data["offset"]);
}
if(array_key_exists("limit",$data)){
$limit = intval($data["limit"]);
}
$total = $this->em->getRepository(Courrier::class)->findWaitingNb($this->currenUser->getLevel());
$folders = $this->em->getRepository(Courrier::class)->findWaiting($this->currenUser->getLevel(),$offset,$limit);
$res =[];
foreach ($folders as $f)
{
$res[] = $f->toArray();
}
return ["message"=>"","statut"=>true,"data"=>["folders"=>$res,"total_item"=>$total[0]["nb"],"current_page"=>1 + $offset/$limit,"code"=>201]];
}
public function saveMultipleMail(array $data)
{
if(!array_key_exists("file",$data)) return ["message"=>"file field is required","statut"=>false,"code"=>401];
if(!array_key_exists("type",$data)) return ["message"=>"type field is required","statut"=>false,"code"=>401];
$file =$this->container->get('upload_service')->uploadBase64($data["file"]);
if($file["statut"]==false) return ["message"=>"error_file_upload","statut"=>false,"code"=>401];
if(!in_array(strtolower($file["file"]["encoding"]),["utf-8","iso-8859-1"]))
{
$f = $this->container->get('upload_service')->getTargetDirectory()."/FOLDER/".$file["file"]["path"];
unlink($f);
return ["message"=>$this->container->get('translator')->trans("bad_encoding")." ".$file["file"]["encoding"],"statut"=>false,"code"=>401];
}
$f = $this->container->get('upload_service')->getTargetDirectory()."/FOLDER/".$file["file"]["path"];
//mb_internal_encoding('UTF-8');
$fileError = fopen($this->container->get('upload_service')->getImportDirectory()."file_error.txt", "a");
file_put_contents($this->container->get('upload_service')->getImportDirectory()."file_error.txt",'');
// Remplacer l'ouverture du fichier et la lecture
$fp = fopen($f, "r");
// Détecter le séparateur sur la première ligne
$firstLine = fgets($fp);
rewind($fp);
// BOM cleanup si nécessaire
$bom = "\xEF\xBB\xBF";
if (strncmp($firstLine, $bom, 3) === 0) {
$firstLine = substr($firstLine, 3);
}
$delimiter = ','; // défaut
$semicolonCount = substr_count($firstLine, ';');
$commaCount = substr_count($firstLine, ',');
if ($semicolonCount > $commaCount) {
$delimiter = ';';
}
// Puis dans la boucle :
while (($datai = fgetcsv($fp, 10000, $delimiter)) !== FALSE) {
$tab[] = $datai;
}
//fclose($fp);
$j=0;
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT86'));
$this->em->getConnection()->beginTransaction();
foreach ($tab as $r) {
$j++;
if($j>1){
if(count($r)==7 ) {
$type = $this->em->getRepository(TypeCourrier::class)->findOneBy(array("code"=>trim($r[1])));
if(is_null($type)) return ["message"=>"type courrier not found","statut"=>false,"code"=>""];
$conf = $this->em->getRepository(TypeConfidentialite::class)->findOneBy(array("niveau"=>1));
if(is_null($conf)) return ["message"=>"type confidentialite not found","statut"=>false,"code"=>""];
$actor = $this->em->getRepository(ActeurExterne::class)->findOneBy(array("telephone"=>trim($r[3])));
$receiver = $this->em->getRepository(User::class)->findOneBy(array("email"=>trim($r[4])));
//if(is_null($receiver) && is_null($actor)) return ["message"=>"receiver not found","statut"=>false,"code"=>""];
if(is_null($receiver)) return ["message"=> "receiver : ".trim($r[4]) ." not found","statut"=>false,"code"=>""];
if(is_null($actor)) return ["message"=>"actor : ".trim($r[3])." not found","statut"=>false,"code"=>""];
// $sender= $this->em->getRepository(User::class)->findOneBy(array("email"=>trim($r[5])));
// if(is_null($sender)) return ["message"=>"receiver not found","statut"=>false,"code"=>""];
$coursier = $this->em->getRepository(Courtier::class)->findOneBy(['id'=>1]);
if(is_null($coursier)) {
$coursier = $this->em->getRepository(Courtier::class)->findOneBy(['nom'=>"internal"]);
}
if(is_null($coursier)){
return ["message"=>"Default system Courier not in database / courtier par defaut non disponible dans la base de donnée","statut"=>false,"code"=>""];
}
$priorite = $this->em->getRepository(Priorite::class)->findOneBy(['id'=>1]);
$dossier = new Courrier();
$dossier->setTypeCourrier($type);
$dossier->setObjet(trim($r[5]));
$dossier->setContenu(trim($r[6]));
$dossier->setInternalReference(trim($r[0]));
$dossier->setReference($this->generateReference()["data"]);
$dossier->setConfidentialite($conf);
$dossier->setUser($this->currenUser );
$dossier->setDestinataire($receiver);
$dossier->setActeur($actor);
$dossier->setCourtier($coursier);
$dossier->setPriorite($priorite);
if(intval(strtolower(trim($data["type"])))==0){
$dossier->setType(0);
}else{
$dossier->setType(1);
}
$dossier->setIsWaiting(1);
try{
$df = $r[2];
$dossier->setDateEnreg(\DateTime::createFromFormat('d/m/Y',$df));
$this->em->persist($dossier);
if(!is_null($operation))
{
$log = new Log();
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($dossier->getId());
$this->em->persist($log);
}
}
catch (\Exception $e)
{
//return ["message"=>$e->getMessage()." ".$e->getFile()."line ".$e->getLine() ,"statut"=>false,"code"=>401];
return ["message"=>$e->getMessage().$e->getLine() ,"statut"=>false,"code"=>401];
}
catch (\Error $e)
{
//return ["message"=>$e->getMessage()." ".$e->getFile()."line ".$e->getLine() ,"statut"=>false,"code"=>401];
return ["message"=>$e->getMessage() ,"statut"=>false,"code"=>401];
}
}else{
return ["message"=>$this->container->get('translator')->trans('file_incorrect'),"statut"=>false,"code"=>401];
}
}
}
try{
$this->em->flush();
$this->em->getConnection()->commit();
}
catch (\Exception $e)
{
$this->em->getConnection()->rollBack();
return ["message"=>$e->getMessage()." ".$e->getFile()."line ".$e->getLine(),"statut"=>false,"code"=>401];
}
fclose($fp);
unlink($f);
$j--;
return ["message"=>$this->container->get('translator')->trans("folder_saved")." : ".$j,"statut"=>true, "code"=>201,"data"=>[]];
}
public function simpleSearchMail(array $data)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>401];
$q = $data["keywords"];
$level = $this->currenUser->getLevel();
$res = $this->container->get(FOSElasticSearchServiceMail::class)->search($q,$level);
// $res = $this->em->getRepository(Dossier::class)->findSimple($level, $data['keywords']);
$all=[];
foreach ($res as $d)
{
$all[]=$d->getMiniArray();
}
return ["message"=>"","data"=>$all, "statut"=>true,"code"=>201];
}
public function simpleSearchAttachment(array $data)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>401];
$q = $data["keywords"];
$level = $this->currenUser->getLevel();
$res = $this->container->get(FOSElasticSearchAttachmentService::class)->search($q,$level);
// $res = $this->em->getRepository(Dossier::class)->findSimple($level, $data['keywords']);
$all=[];
foreach ($res as $d)
{
$all[]=$d->toArrayForSearch();
}
return ["message"=>"","data"=>$all, "statut"=>true,"code"=>201];
}
public function markMailAsOk(array $data)
{
if(!array_key_exists("id",$data)) return ["message"=>"id field is required","statut"=>false,"code"=>401];
$dossier = $this->em->getRepository(Courrier::class)->findOneBy(array("id"=>$data["id"]));
if(is_null($dossier)) return ["message"=>"Mail not found","statut"=>false,"code"=>401];
$dossier->setIsWaiting(false);
$this->em->persist($dossier);
$this->em->flush();
return ["message"=>"operation_done","data"=>$dossier->toArray(), "statut"=>true,"code"=>201];
}
public function allUserExecptAdminAndCurrent(array $data)
{
$users = $this->em->getRepository(User::class)->loadAllUsersExecptAdminAndCurrent($this->currentUser->getId());
$tab = [];
foreach ($users as $u){
$tab[]=$u->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$tab];
}
public function registerInternalMail(array $data){
$user = $this->currenUser;
$req=['confi','priorite','receiver','type','contenu','titre','reference','date_enreg','files','ref_int'];
$reqObli=['confi','priorite','receiver','type','titre','reference','date_enreg'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) {
return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
else{
if(in_array($val,$reqObli) && strlen($data[$val]) ===0){
return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$confi = $this->em->getRepository(TypeConfidentialite::class)->findOneBy(array('id' =>$data['confi']));
if($confi === null) return ["message"=>" Type confidentialite not found","statut"=>false,"code"=>""];
$priorite = $this->em->getRepository(Priorite::class)->findOneBy(array('id' =>$data['priorite']));
if($priorite === null) return ["message"=>" Priorite not found","statut"=>false,"code"=>""];
$type = $this->em->getRepository(TypeCourrier::class)->findOneBy(array('id' =>$data['type']));
if($type === null) return ["message"=>" Type courrier not found","statut"=>false,"code"=>""];
$receiver = $this->em->getRepository(User::class)->findOneBy(array('id' =>$data['receiver']));
if($receiver === null) return ["message"=>" Destinataire not found","statut"=>false,"code"=>""];
$broker = $this->em->getRepository(Courtier::class)->findOneBy(array('nom' =>"internal"));
if($broker === null) {
$broker = new Courtier();
$broker->setNom('internal');
$broker->setCni('00000000000');
$broker->setTelephone('00000000000');
$broker->setIsActive(false);
$this->em->persist($broker);
$this->em->flush();
}
$old = $this->em->getRepository(Courrier::class)->findOneBy(['reference'=>$data['reference']]);
if($old !== null) return ["message"=>$this->container->get('translator')->trans("reference already used"),"statut"=>false,"code"=>""];
$courrier = new Courrier();
$courrier->setType(Courrier::COURRIER_INTERNE);
$courrier->setConfidentialite($confi);
$courrier->setPriorite($priorite);
$courrier->setDestinataire($receiver);
$courrier->setUser($user);
$courrier->setEmetteur($user);
$courrier->setTypeCourrier($type);
$courrier->setCourtier($broker);
$courrier->setReference($data['reference']);
$courrier->setInternalReference($data['ref_int']);
$courrier->setContenu($data['contenu']);
$courrier->setObjet($data['titre']);
$courrier->setStatut(Courrier::STATUT_NOUVEAU);
$courrier->setDateCloture(new \DateTime());
$courrier->setDateEnreg(\DateTime::createFromFormat('d/m/Y',$data['date_enreg']));
foreach ($data["files"] as $f)
{
$file = new Fichier();
$file->setNom($f["name"]);
$file->setFolderNameAndName($courrier->getObjet()." | ". $f["name"]);
$file->setExtension($f["extension"]);
$file->setType($f["type"]);
$file->setTaille($f["size"]);
$file->setPath($f["path"]);
$file->setAuteur($user->getNom()." ".$user->getPrenom());
$file->setCourrier($courrier);
$courrier->addFichier($file);
}
if($user->getId() !== $receiver->getId()){
$notif = new Notification();
$notif->setCourrier($courrier);
$notif->setCode(Notification::NEW_INTERNAL_MAIL);
$notif->setUser($user);
$statut = new Statut();
$statut->setUser($receiver);
$statut->setNotification($notif);
$notif->addStatut($statut);
$this->em->persist($notif);
}
$this->em->persist($courrier);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'1003'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($user);
$log->setObservation($courrier->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$courrier->toArray()];
}
public function editInternalMail(array $data){
$user = $this->currenUser;
$req=['id','confi','priorite','type','contenu','titre','date_enreg','added_files','remove_files','ref_int'];
$reqObli=['confi','priorite','type','titre','date_enreg'];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) {
return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
else{
if(in_array($val,$reqObli) && strlen($data[$val]) ===0){
return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
}
$courrier = $this->em->getRepository(Courrier::class)->findOneBy(array("id"=>$data["id"]));
if($courrier === null) return ["message"=>"courrier not found","statut"=>false,"code"=>401];
$confi = $this->em->getRepository(TypeConfidentialite::class)->findOneBy(array('id' =>$data['confi']));
if($confi === null) return ["message"=>" Type confidentialite not found","statut"=>false,"code"=>""];
$priorite = $this->em->getRepository(Priorite::class)->findOneBy(array('id' =>$data['priorite']));
if($priorite === null) return ["message"=>" Priorite not found","statut"=>false,"code"=>""];
$type = $this->em->getRepository(TypeCourrier::class)->findOneBy(array('id' =>$data['type']));
if($type === null) return ["message"=>" Type courrier not found","statut"=>false,"code"=>""];
$courrier->setConfidentialite($confi);
$courrier->setPriorite($priorite);
$courrier->setTypeCourrier($type);
$courrier->setInternalReference($data['ref_int']);
$courrier->setContenu($data['contenu']);
$courrier->setObjet($data['titre']);
$courrier->setDateEnreg(\DateTime::createFromFormat('d/m/Y',$data['date_enreg']));
foreach ($data["remove_files"] as $id)
{
$file = $this->em->getRepository(Fichier::class)->findOneBy(array("id"=>$id));
if($file !== null)
{
$courrier->removeFichier($file);
}
}
foreach ($data["added_files"] as $f)
{
$file = new Fichier();
$file->setNom($f["name"]);
$file->setFolderNameAndName($courrier->getObjet()." | ". $f["name"]);
$file->setExtension($f["extension"]);
$file->setType($f["type"]);
$file->setTaille($f["size"]);
$file->setPath($f["path"]);
$file->setAuteur($user->getNom()." ".$user->getPrenom());
$file->setCourrier($courrier);
$courrier->addFichier($file);
}
/*if(count($data['attached_files'])>0){
foreach($courrier->getPieceJointeAjoutees() as $i){
if(in_array($i->getId(),$data['attached_files'])){
$i->setStatus(1);
}else{
$i->setStatus(0) ;
}
$courrier->addPieceJointeAjoutee($i);
}
}else{
foreach($courrier->getPieceJointeAjoutees() as $i){
$i->setStatus(0) ;
$courrier->addPieceJointeAjoutee($i);
}
}*/
$this->em->persist($courrier);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'1021'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($user);
$log->setObservation($courrier->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$courrier->toArray()];
}
public function mailHistory(array $data)
{
if(!array_key_exists("id",$data))
{
return ["message"=>"id is missing","statut"=>false,"data"=>[],"code"=>401];
}
else
{
$mail = $this->em->getRepository(Courrier::class)->findOneBy(array("id"=>$data["id"]));
if($mail === null) return ["message"=>"courrier not found","statut"=>false,"data"=>[],"code"=>401];
else
{
$collabo = $this->em->getRepository(CourrierCollaborateur::class)->findBy(['courrier'=>$mail,'isActive'=>1],['date'=>'DESC']);
$co = [];
foreach ($collabo as $c)
{
$co[]=$c->toArray();
}
if($mail->getStatut()=== Courrier::STATUT_NOUVEAU){
if($this->currenUser->getId() === $mail->getDestinataire()->getId()){
$mail->setStatut(Courrier::STATUT_EN_COURS);
$this->em->persist($mail);
$this->em->flush();
}
}
$tasks = $this->em->getRepository(Tache::class)->findBy(['courrier'=>$mail,'isActive'=>1],['date'=>'DESC']);
$ts = [];
foreach ($tasks as $c)
{
$ts[]=$c->toArray();
}
return ["message"=>"","statut"=>true,"data"=>['mail'=>$mail->toArray(),'taches'=>$ts,'collabo'=>$co],"code"=>201];
}
}
}
public function createArticle(array $data){
$req=["title","content"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
if(strlen($data["title"])===0) return ["message"=>"title field is empty","statut"=>false,"code"=>""];
$b= new Article();
$b->setTitle($data["title"]);
$b->setContent($data["content"]);
$b->setUser($this->currenUser);
$b->addRelatedUser($this->currenUser);
if(array_key_exists("file",$data)&&array_key_exists("name",$data["file"]))
{
$b->setImageCover($data["file"]["name"]);
}
$this->em->persist($b);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$b->toArray()];
}
public function editArticle(array $data)
{
$req=["id","title","content"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
if(strlen($data["title"])===0) return ["message"=>"title field is empty","statut"=>false,"code"=>""];
$b= $this->em->getRepository(Article::class)->findOneBy(array("id"=>$data["id"]));
if($b === null) return ["message"=>"subject not found","statut"=>false,"code"=>""];
$b->setTitle($data["title"]);
$b->setContent($data["content"]);
$b->setUser($this->currenUser);
if(array_key_exists("file",$data)&&array_key_exists("name",$data["file"]))
{
$b->setImageCover($data["file"]["name"]);
}
$this->em->persist($b);
$this->em->flush();
$log = new Log();
$operation = $this->em->getRepository(Operation::class)->findOneBy(array("code"=>'MVT77'));
if($operation !== null)
{
$log->setOperation($operation);
$log->setUser($this->currenUser);
$log->setObservation($b->getId());
$this->em->persist($log);
$this->em->flush();
}
return ["message"=>"","statut"=>true,"data"=>$b->toArray()];
}
public function commentArticle(array $data): array
{
$req=["id","content"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
if(strlen($data["content"])===0) return ["message"=>"content field is empty","statut"=>false,"code"=>""];
$b= $this->em->getRepository(Article::class)->findOneBy(array("id"=>$data["id"]));
if($b === null) return ["message"=>"subject not found","statut"=>false,"code"=>""];
$comment = new Comment();
$comment->setArticle($b);
$comment->setContent($data['content']);
$comment->setUser($this->currenUser);
$b->setNbComment($b->getNbComment()+1);
$b->addComment($comment);
$relatedUsers = $b->getRelatedUsers();
if(!$relatedUsers->contains($this->currenUser)){
$b->addRelatedUser($this->currenUser);
}
$this->em->persist($b);
$this->em->flush();
$relatedUsers = $b->getRelatedUsers();
$notif = new Notification();
$notif->setUser($this->currenUser);
$notif->setArticle($b);
$notif->setCode(Notification::NEW_COMMENT);
foreach ($relatedUsers as $uw){
if($uw->getId() != $this->currenUser->getId())
{
$status = new Statut();
$status->setNotification($notif);
$status->setUser($uw);
$notif->addStatut($status);
}
}
$this->em->persist($notif);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$comment->toArray()];
}
public function commentComment(array $data): array
{
$req=["id","content"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
if(strlen($data["content"])===0) return ["message"=>"content field is empty","statut"=>false,"code"=>""];
$com= $this->em->getRepository(Comment::class)->findOneBy(array("id"=>$data["id"]));
if($com === null) return ["message"=>"comment not found","statut"=>false,"code"=>""];
$b = $com->getArticle();
$comment = new Comment();
$comment->setParent($com);
$comment->setContent($data['content']);
$comment->setUser($this->currenUser);
$b->setNbComment($b->getNbComment()+1);
$com->setNbComment($com->getNbComment()+1);
$com->addComment($comment);
$relatedUsers = $b->getRelatedUsers();
if(!$relatedUsers->contains($this->currenUser)){
$b->addRelatedUser($this->currenUser);
}
$this->em->persist($b);
$this->em->persist($com);
$this->em->flush();
$notif = new Notification();
$notif->setUser($this->currenUser);
$notif->setArticle($b);
$notif->setCode(Notification::NEW_COMMENT);
$relatedUsers = $b->getRelatedUsers();
foreach ($relatedUsers as $uw){
if($uw->getId() != $this->currenUser->getId()){
$status = new Statut();
$status->setNotification($notif);
$status->setUser($uw);
$notif->addStatut($status);
}
}
$this->em->persist($notif);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$comment->toArray()];
}
public function getComments(array $data): array
{
$req=["id","limit","offset"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>""];
}
$article= $this->em->getRepository(Article::class)->findOneBy(array("id"=>$data["id"]));
if($article === null) return ["message"=>"Subject not found","statut"=>false,"code"=>""];
$comments = $this->em->getRepository( Comment::class )->findBy( [ 'article' => $article ], [
'isActive' => 'DESC',
'date' => 'DESC'
], $data['limit'], $data['offset'] );
$result = [];
foreach ($comments as $com){
$result[]=$com->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$result];
}
public function simpleSearchArticle(array $data)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>401];
$q = $data["keywords"];
$res = $this->container->get(FOSElasticSearchServiceArticle::class)->search($q);
// $res = $this->em->getRepository(Dossier::class)->findSimple($level, $data['keywords']);
return ["message"=>"","data"=>$res, "statut"=>true,"code"=>201];
}
public function getExternalMail(array $data){
$cm = new ClientManager([]);
}
public function moveFiles(array $data): array
{
$user = $this->currenUser;
$req=['ids','folder',"type"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
}
if(!in_array($data["type"],["file","folder"])){
return ["message"=>"bad move type","statut"=>false,"code"=>""];
}
if($data["type"] === "file"){
$files = [];
foreach ($data['ids'] as $item){
$file = $this->em->getRepository(Fichier::class)->findOneBy(['id'=>$item]);
if($file === null) return ['message' =>$this->container->get('translator')->trans('file_not_found')." ".$item,"statut"=>false,"code"=>401];
$files[] = $file;
}
$folder= $this->em->getRepository(Dossier::class)->findOneBy(['reference'=>$data['folder']]);
if($folder === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
$folderToIndex = [];
foreach ($files as $file){
$mainFolder = $file->getDossier();
if($mainFolder!==null){
$mainFolder->removeFichier($file);
$folderToIndex[] = $mainFolder;
$this->em->persist($mainFolder);
}
if(!$folder->getFichiers()->contains($file)){
$folder->addFichier($file);
$file->setDossier($folder);
}
}
$this->em->persist($folder);
$this->em->flush();
$this->indexer->replaceMany($folderToIndex);
$this->indexer->replaceOne($folder);
}else{
$folders = [];
foreach ($data['ids'] as $item){
$f = $this->em->getRepository(Dossier::class)->findOneBy(['id'=>$item]);
if($f === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found')." ".$item,"statut"=>false,"code"=>401];
$folders[] = $f;
}
$folder= $this->em->getRepository(Dossier::class)->findOneBy(['reference'=>$data['folder']]);
if($folder === null) return ['message' =>$this->container->get('translator')->trans('folder_not_found'),"statut"=>false,"code"=>401];
$folderToIndex = [];
foreach ($folders as $f){
$mainFolder = $f->getDossierParent();
if($mainFolder!==null){
$mainFolder->removeSousDossier($f);
$folderToIndex[] = $mainFolder;
$this->em->persist($mainFolder);
}
if(!$folder->getSousDossiers()->contains($f)){
$folder->addSousDossier($f);
$f->setDossierParent($folder);
}
}
$this->em->persist($folder);
$this->em->flush();
if(count($folderToIndex)>0){
$this->indexer->replaceMany($folderToIndex);
}
$this->indexer->replaceOne($folder);
}
return ["message"=>"","statut"=>true,"data"=>[]];
}
public function advancedSearchMailExt(array $data)
{
$req=["titre","type_courrier","reference","start_date","end_date"];
foreach ($req as $el)
{
if(!array_key_exists($el,$data)) return ["message"=>$el." field is required","statut"=>false,"code"=>401];
}
if($data["start_date"]!="")
{
if(preg_match("/^[a-zA-Z]+$/", $data["start_date"])==false){
$d = \DateTime::createFromFormat('d/m/Y',$data["start_date"]);
$data["start_date"] =$d->format("Y-m-d")." 00:00:01";
$data["start_date_1"] =$d->format("Y-m-d");
$data["start_date_2"] =$d->format("Y-m-d")." 23:59:59";
}
}
if($data["end_date"]!="")
{
if(preg_match("/^[a-zA-Z]+$/", $data["end_date"])==false){
$d = \DateTime::createFromFormat('d/m/Y',$data["end_date"]);
$data["end_date"] =$d->format("Y-m-d")." 00:00:01";
$data["end_date_1"] =$d->format("Y-m-d");
$data["end_date_2"] =$d->format("Y-m-d")." 23:59:59";
}
}
//$da = $this->em->getRepository(Dossier::class)->findAdvanced($level,$data);
$level = $this->currenUser->getLevel();
try {
$da = $this->container->get(FOSElasticSearchServiceMail::class)->searchAdvancedMailExt($data,$level);
}
catch (\Exception $e){
return ["message"=>$e->getMessage()." ".$e->getLine(),"data"=>[], "statut"=>false,"code"=>401];
}
$res=[];
foreach ($da as $d)
{
$res[]=$d->toArray();
}
return ["message"=>"operation_done","data"=>$res, "statut"=>true,"code"=>201];
}
public function simpleSearchMailExt(array $data)
{
if(!array_key_exists("keywords",$data)) return ["message"=>"keywords field is required","statut"=>false,"code"=>401];
$q = $data["keywords"];
$level = $this->currenUser->getLevel();
$res = $this->container->get(FOSElasticSearchServiceMail::class)->searchExt($q,$level);
// $res = $this->em->getRepository(Dossier::class)->findSimple($level, $data['keywords']);
$all=[];
foreach ($res as $d)
{
$all[]=$d->getMiniArray();
}
return ["message"=>"","data"=>$all, "statut"=>true,"code"=>201];
}
public function uploadMultiplePdfs($file,$bordereau)
{
if (!$file) {
return ["message" => $this->container->get('translator')->trans("empty_file"), "statut" => false];
}
// Validate file type
if ($file->getMimeType() !== 'application/pdf') {
return ["message" => $this->container->get('translator')->trans("file_must_be_pdf"), "statut" => false];
}
// Validate file size (50 MB max)
$SIZE = $this->container->getParameter('app.upload.size')!==null?$this->container->getParameter('app.upload.size'):10; // 10 MB default
$maxSize = $SIZE * 1024 * 1024;
if ($file->getSize() > $maxSize) {
return ["message" => $this->container->get('translator')->trans("file_exceeds_size_limit").$SIZE." MB", "statut" => false];
}
// Parse folder reference and file name from filename
// Format: FOLDER_REFERENCE__FILE_NAME.pdf
$originalFilename = $file->getClientOriginalName();
$parts = explode('__', $originalFilename);
if (count($parts) < 2) {
return [
"message" => $this->container->get('translator')->trans("invalid_file_name_upload"),
"statut" => false
];
}
$folderReference = $parts[0];
$dossier = $this->em->getRepository(Dossier::class)->findOneBy(['refInterne' => $folderReference]);
if($dossier === null) return ["message" => $this->container->get('translator')->trans("folder_not_found"), "statut" => false];
$fileName = implode('__', array_slice($parts, 1)); // In case there are multiple '__' in the filename
$fileName = str_replace('_', ' ', $fileName);
try {
// Upload the file
$fu = $this->container->get("upload_service");
$uploadResult = $fu->upload($file);
if (!$uploadResult["statut"]) {
return $uploadResult;
}
// Convert and save the file
$fu->convertAndSave($uploadResult["file"]);
$fi = $uploadResult["file"];
$cu = $this->currenUser;
$file = new Fichier();
$file->setNom($fileName);
$file->setFolderNameAndName($dossier->getTitre()." | ". $fileName);
$file->setExtension($fi["extension"]);
$file->setType($fi["type"]);
$file->setTaille($fi["size"]);
$file->setPath($fi["path"]);
$file->setAuteur($cu->getNom()." ".$cu->getPrenom());
$file->setDossier($dossier);
$dossier->addFichier($file);
$this->em->persist($dossier);
$this->em->flush();
return [
"message" => $this->container->get('translator')->trans('upload_success'),
"statut" => true,
"data" => [
"file" => $uploadResult["file"],
"folderReference" => $folderReference,
"fileName" => $fileName,
"bordereau" => $bordereau
]
];
} catch (\Exception $e) {
return [
"message" => $this->container->get('translator')->trans('upload_failed'). $e->getMessage(),
"statut" => false
];
}
}
public function createArchiveLocation(array $data)
{
$req=["code"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
if(strlen($data['code'])<2) return ["message"=>$this->container->get('translator')->trans("archive_depot_min_length"),"statut"=>false,"code"=>""];
if(strlen($data['code'])>30) return ["message"=>$this->container->get('translator')->trans("archive_depot_max_length"),"statut"=>false,"code"=>""];
$old = $this->em->getRepository(ArchiveLocation::class)->findOneBy(['isActive'=>true,'code'=>$data['code']]);
if($old !== null) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
$r = new ArchiveLocation();
$r->setCode($data["code"]);
$this->em->persist($r);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$r->toArray()];
}
public function editArchiveLocation(array $data)
{
$req=["id","code"];
foreach ($req as $val)
{
if(!array_key_exists($val,$data)) return ["message"=>$val." field is required","statut"=>false,"code"=>""];
else
{
if(strlen($data[$val])<1) return ["message"=>$val." field is empty","statut"=>false,"code"=>""];
}
}
if(strlen($data['code'])<2) return ["message"=>$this->container->get('translator')->trans("archive_depot_min_length"),"statut"=>false,"code"=>""];
if(strlen($data['code'])>30) return ["message"=>$this->container->get('translator')->trans("archive_depot_max_length"),"statut"=>false,"code"=>""];
$salle = $this->em->getRepository(ArchiveLocation::class)->findOneBy(array("id"=>$data["id"]));
if($salle === null) return ["message"=>"Archive location not found","statut"=>false,"code"=>""];
$old = $this->em->getRepository(ArchiveLocation::class)->findBy(['isActive'=>true,'code'=>$data['code']]);
foreach ($old as $el ){
if($el->getId() !== $salle->getId()) return ["message"=>$data["code"]." ".$this->container->get('translator')->trans("already_exist"),"statut"=>false,"code"=>401];
}
$salle->setCode($data["code"]);
$this->em->persist($salle);
$this->em->flush();
return ["message"=>"","statut"=>true,"data"=>$salle->toArray()];
}
public function getSalleArchiveLocation(array $data)
{
if(!array_key_exists("id",$data))
{
return ["message"=>"type or id is missing","statut"=>false,"data"=>[],"code"=>401];
}
$salles = $this->em->getRepository(Salle::class)->findBy(array("archiveLocation"=>$data["id"]));
$res=[];
foreach ($salles as $r)
{
if($r->getIsActive())$res[]=$r->toArray();
}
return ["message"=>"","statut"=>true,"data"=>$res,"code"=>201];
}
}