cfg = $this->config->item('google') ?: []; $this->load->database(); $this->load->helper('url'); // pour base_url() } /* ========= AUTH SERVICE ACCOUNT (JWT) ========= */ private function getClient(array $scopes): Google_Client { $credsPath = $this->cfg['credentials_path'] ?? null; if (!$credsPath || !is_file($credsPath)) { throw new Exception("google.credentials_path introuvable : ".($credsPath ?? '(null)')); } $client = new Google_Client(); $client->setAuthConfig($credsPath); $client->setScopes($scopes); $client->setAccessType('offline'); if (!empty($this->cfg['subject'])) { $client->setSubject($this->cfg['subject']); // DWD si configuré } return $client; } private function drive(): Google_Service_Drive { if ($this->driveService instanceof Google_Service_Drive) { return $this->driveService; } $client = $this->getClient(['https://www.googleapis.com/auth/drive']); $this->driveService = new Google_Service_Drive($client); return $this->driveService; } /* ========= Utilitaires ========= */ private function sanitizeDriveName(string $s): string { // Retire caractères non valides pour un nom Drive $s = preg_replace('/[\\\\\/:*?"<>|]/u', ' ', $s); $s = preg_replace('/\s+/u', ' ', trim($s)); return mb_substr($s, 0, 240, 'UTF-8'); } /* ========= PUBLIC: Créer / Actualiser “InfoCourse {NomProjet}” ========= */ public function creer_document($proj_id) { // Données projet $this->load->model('Projets_model'); $mem_proj = $this->Projets_model->mod_getRecord((int)$proj_id); if (empty($mem_proj) || empty($mem_proj->proj_google_rep_id)) { return; // rien à faire sans dossier cible } $this->load->model('Clients_model'); $contacts = $this->Clients_model->mod_getRecords_contacts($mem_proj->proj_client_id); $parentId = $mem_proj->proj_google_rep_id; $dateHeure = date('Y-m-d H:i'); $mem_link = base_url('index.php/projets/form/'.$mem_proj->proj_id); $nomProject = $this->sanitizeDriveName((string)$mem_proj->proj_nom); $nomFichier = 'InfoCourse ' . $nomProject; // ← comme demandé $drive = $this->drive(); try { // DriveId du dossier (Shared drive) $folderInfo = $drive->files->get($parentId, [ 'fields' => 'driveId', 'supportsAllDrives' => true ]); $driveId = $folderInfo->getDriveId(); // ===== Construire le tableau (même rendu que ton exemple) $rows = [ ['Nom du projet', (string)$mem_proj->proj_nom], ['Date', (string)($mem_proj->proj_date_debut ?? '')], ['Client', (string)($mem_proj->compagnie ?? '')], ['Notes', (string)($mem_proj->proj_notes ?? '')], ['Lien', "".$mem_link.""], ['Représentant', (string)($mem_proj->rep_prenom ?? '')], ['Date de création', $dateHeure], ]; // Contacts + tickets Jira ouverts if (is_array($contacts)) { foreach ($contacts as $c) { $nomComplet = trim(($c['con_prenom'] ?? '').' '.($c['con_nom'] ?? '')); $email = $c['con_courriel'] ?? ''; $tel = $c['con_telephone2'] ?? ''; $role = $c['rol_nom'] ?? ''; $ligne = $nomComplet; if ($email) $ligne .= $email; if ($tel) $ligne .= ' - '.$tel; if ($role) $ligne .= ' - '.$role; $rows[] = [$nomComplet, $ligne]; if (function_exists('jira_get_tickets_by_email') && $email) { $tickets = jira_get_tickets_by_email($email); if (!empty($tickets['ouverts'])) { $li = ''; foreach ($tickets['ouverts'] as $t) { $sum = isset($t['summary']) ? htmlspecialchars($t['summary']) : ''; $key = $t['key'] ?? ''; $url = $t['url'] ?? '#'; $st = $t['status'] ?? ''; $li .= '
  • '.$key.' — '.$sum.' ('.$st.')
  • '; } $rows[] = ['Tickets ouvert', '']; } } } } // ===== Supprimer l’existant (même nom, même dossier) $nameEsc = addcslashes($nomFichier, "'"); $existing = $drive->files->listFiles([ 'q' => "name = '{$nameEsc}' and mimeType='application/vnd.google-apps.document' and '{$parentId}' in parents and trashed = false", 'spaces' => 'drive', 'driveId' => $driveId, 'corpora' => 'drive', 'includeItemsFromAllDrives' => true, 'supportsAllDrives' => true, 'fields' => 'files(id)' ]); if (count($existing->getFiles()) > 0) { $drive->files->delete($existing->getFiles()[0]->getId(), ['supportsAllDrives' => true]); } // ===== HTML (table) $html = ''; $html .= ''; foreach ($rows as $row) { $label = htmlspecialchars($row[0]); $value = $row[1]; // peut contenir du HTML (lien/ul) $html .= ""; $html .= ""; $html .= ""; $html .= ""; } $html .= '
    {$label}{$value}
    '; $html .= ''; // ===== Import HTML -> Google Docs $tmp = tempnam(sys_get_temp_dir(), 'gdoc_').'.html'; file_put_contents($tmp, $html); $content = file_get_contents($tmp); $fileMeta = new Google_Service_Drive_DriveFile([ 'name' => $nomFichier, 'mimeType' => 'application/vnd.google-apps.document', 'parents' => [$parentId] ]); $file = $drive->files->create($fileMeta, [ 'data' => $content, 'mimeType' => 'text/html', 'uploadType' => 'multipart', 'fields' => 'id', 'supportsAllDrives' => true ]); @unlink($tmp); // (optionnel) log_message('info', 'InfoCourse généré: '.$file->id); } catch (Exception $e) { log_message('error', 'creer_document: '.$e->getMessage()); echo "Erreur : ".$e->getMessage(); } } }