///////////////////////////////////////////////// // LOGGING ///////////////////////////////////////////////// const logger = require("../public/js/app/logger_adhesion"); ///////////////////////////////////////////////// // APPELS DES MODULES ///////////////////////////////////////////////// const moment = require('moment'); const ejs = require('ejs'); const nodemailer = require('nodemailer'); const path = require("path"); const stripe = require('stripe')(process.env.STRIPE_PRIVATE_KEY); const pdf = require("pdf-creator-node"); const fs = require("fs"); const mysql = require('mysql2'); const mysql_promise = require('mysql2/promise'); // ADOBE PDF const PDFServicesSdk = require('@adobe/pdfservices-node-sdk'); ///////////////////////////////////////////////// // APPELS DES FONCTIONS ///////////////////////////////////////////////// // Déterminer les profils de l'adhésion const carte_adherent = require("./../modules/adhesion/carte_adherent"); // FAIRE UNE PAUSE const sleep = require("./../modules/sleep"); //////////////////////////////////////////////////// // FILE NAME //////////////////////////////////////////////////// const filename = path.parse(__filename).base; ///////////////////////////////////////////////// // GOOGLE SHEET PARAMETERS ///////////////////////////////////////////////// const { GoogleSpreadsheet } = require('google-spreadsheet'); const GS_creds = require('../inscriptionsafps-53b60452f63d.json'); const { error } = require("console"); // Initialize the sheet - doc ID is the long id in the sheets URL const GS_adhesion = new GoogleSpreadsheet(process.env.gsheet_adhesion); ///////////////////////////////////////////////// // VARIABLES GLOBALES ///////////////////////////////////////////////// let adherent_type, profil1, profil2, profil3; ///////////////////////////////////////////////// // ASSOCIATIONS LOCACLES // IMPORTS ADHÉRENTS DANS DB // CLIC SUR LE BOUTON "Valider" de la page /maj_googlesheet ///////////////////////////////////////////////// const import_ass_locales_v2 = async function(req, res) { logger.info("======================================", { label: filename }); logger.info("======== FUNCTION import_ass_locales_v2 (adhesion maj_googlesheet) ==========", { label: filename }); logger.info("======================================", { label: filename }); ///////////////////////////////////////////////// // DATE let now = moment().format("YYYY-MM-DD HH:mm:ss"); let now_pdf = moment().format("YYYY-MM-DDTHH-mm-ss"); ///////////////////////////////////////////////// // VARIABLE let nb_import = 0; ///////////////////////////////////////////////// // CONNEXION GSHEET try { await GS_adhesion.useServiceAccountAuth(GS_creds); } catch (error) { // Echec de connection à GS logger.error("Il y a un problème avec la connection à Google Sheet. : " + error, { numsession: req.session.id }); req.session.message4 = "Il y a un problème système, veuillez recommencer."; res.redirect('/adhesion/maj_googlesheet'); }; await GS_adhesion.loadInfo(); const GS_asso_locales = GS_adhesion.sheetsByTitle['adhesion_ass_locales']; const GS_asso_locales_rows = await GS_asso_locales.getRows(); console.log("GS_asso_locales.rowCount = ", GS_asso_locales.rowCount); //console.log("GS_asso_locales_rows[0].identifiant = ", GS_asso_locales_rows[0].identifiant); //console.log("GS_asso_locales_rows[1].identifiant = ", GS_asso_locales_rows[1].identifiant); // NOMBRE DE LIGNE DANS L'ONGLET adhesion_ass_locales let compteur = GS_asso_locales.rowCount - 1; // POUR DÉCOMPTER LA LIGNE D'EN-TÊTE console.log("compteur = ", compteur); //////////////////////////////////////////////////// // CONNECTION ADOBE API //////////////////////////////////////////////////// const credentials = PDFServicesSdk.Credentials .servicePrincipalCredentialsBuilder() .withClientId(process.env.PDF_SERVICES_CLIENT_ID) .withClientSecret(process.env.PDF_SERVICES_CLIENT_SECRET) .build(); //timeout Default: 10000 const clientConfig = PDFServicesSdk.ClientConfig .clientConfigBuilder() .withConnectTimeout(40000) .withReadTimeout(80000) .build(); // Create an ExecutionContext using credentials const executionContext = PDFServicesSdk.ExecutionContext.create(credentials); ///////////////////////////////////////////////// // CONNECTION DB try { const pool = mysql.createPool({ host: process.env.db_connection_host, port: process.env.db_connection_port, user: process.env.db_connection_user, password: process.env.db_connection_password, database: process.env.db_connection_database, rowsAsArray: true }); const promisePool = pool.promise(); ///////////////////////////////////////////////// // ON LIT TOUTES LES LIGNES DU GOOGLE SHEET LES UNES APRÈS LES AUTRES for (i=0; i 0) { OUTPUT = path.resolve(__dirname, "../pdf/adhesion/2526/paye/")+"/"+GS_asso_locales_rows[i].identifiant+"_adhesion_2526_paye_don_"+now_pdf+".pdf"; INPUT = path.resolve(__dirname, "../pdf/template/carte_adherent_don.docx"); } else { // S'il n'y a pas de don OUTPUT = path.resolve(__dirname, "../pdf/adhesion/2526/paye/")+"/"+GS_asso_locales_rows[i].identifiant+"_adhesion_2526_paye_"+now_pdf+".pdf"; INPUT = path.resolve(__dirname, "../pdf/template/carte_adherent.docx"); } moment.locale('fr'); var date_formattee = moment().format('L') var today = date_formattee; var adresse = GS_asso_locales_rows[i].adherent_adresse_rue; adresse += " "; adresse += GS_asso_locales_rows[i].adherent_adresse_codepostal; adresse += " "; adresse += GS_asso_locales_rows[i].adherent_adresse_ville; if (profil2 == undefined) {profil2 = " "}; if (profil3 == undefined) {profil3 = ""}; JSON_INPUT = { "date": today, "identifiant": GS_asso_locales_rows[i].identifiant, "profil1": profil1, "profil2": profil2, "profil3": profil3, "mode_paiement": GS_asso_locales_rows[i].adherent_paiement_mode, "nom": GS_asso_locales_rows[i].adherent_nom, "prenom": GS_asso_locales_rows[i].adherent_prenom, "adresse": adresse, "montant_don": GS_asso_locales_rows[i].adherent_paiement_montant_don }; const documentMerge = PDFServicesSdk.DocumentMerge, documentMergeOptions = documentMerge.options, adobe_options = new documentMergeOptions.DocumentMergeOptions(JSON_INPUT, documentMergeOptions.OutputFormat.PDF); // Create a new operation instance using the options instance. const documentMergeOperation = documentMerge.Operation.createNew(adobe_options); // Set operation input document template from a source file. const input = PDFServicesSdk.FileRef.createFromLocalFile(INPUT); documentMergeOperation.setInput(input); // Execute the operation and Save the result to the specified location. await documentMergeOperation .execute(executionContext) .then(result => result.saveAsFile(OUTPUT).then( ) ) .catch(err => { if(err instanceof PDFServicesSdk.Error.ServiceApiError || err instanceof PDFServicesSdk.Error.ServiceUsageError) { console.log('Exception encountered while executing ADOBE PDF', err); } else { console.log('Exception encountered while executing ADOBE PDF', err); } }); ////////////////////////////////////////////////////////////////////////////// // ENVOIE CARTE ADHERENT + JUSTIFICATIF DE DON PAR MAIL console.log("MAIL ENVOI AVANT"); var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: process.env.nodemailer_user, pass: process.env.nodemailer_pass } }); var attachment_name = GS_asso_locales_rows[i].identifiant; attachment_name += "_adhesion_2526_carteadherent.pdf"; var attachment_don_name = GS_asso_locales_rows[i].identifiant; attachment_don_name += "_don.pdf"; var mail_objet = "ASSOCIATION FRANÇAISE POUR LA PÉDAGOGIE SUZUKI - ADHÉSION 2025/2026 - "; mail_objet += GS_asso_locales_rows[i].identifiant; mail_html = "

Cher adhérent,

Félicitations ! Vous êtes désormais membre de l’Association Française pour la Pédagogie Suzuki (http://www.afpedagogiesuzuki.fr) et de l’European Suzuki Association (https://europeansuzuki.org) pour l'année 2025/2026. Vous pouvez à ce titre participer à tous les événements Suzuki en France et dans le monde.

Vous trouverez en pièce jointe votre carte d'adhésion annuelle (valable du 1er septembre 2025 au 31 août 2026).

Votre identifiant (valable pour toute la famille) est "; mail_html += GS_asso_locales_rows[i].identifiant; mail_html += ".

"; if (GS_asso_locales_rows[i].adherent_paiement_montant_don > 0) { mail_html += "

Nous vous remercions chaleureusement pour votre don. Votre justificatif est également joint à ce mail

"; } mail_html += "


Nous vous remercions pour votre intérêt et vous souhaitons une très belle année en musique !

Association Française pour la pédagogie Suzuki
Chez Anne PAGES
30 rue des Tattes
74500 PUBLIER

"; var mailOptions = { from: 'afps.inscription@gmail.com', to: GS_asso_locales_rows[i].adherent_mail, subject: mail_objet, html: mail_html, attachments: [{ filename: attachment_name, path: OUTPUT } ] }; transporter.sendMail(mailOptions, function(error, info){ if (error) { logger.info("error : " + error, { numsession: req.session.id }); } else { console.log('Email sent: ' + info.response); } }); console.log("MAIL ENVOI APRES"); // METTRE À JOUR LE STATUS D'ENVOI DE LA CARTE let sql10 = 'UPDATE '; sql10 += 'adherent'; sql10 += ' SET '; sql10 += 'carte_envoi = "definitive"'; sql10 += ' WHERE identifiant = "' + GS_asso_locales_rows[i].identifiant + '"'; const [results10, fields10] = await promisePool.query(sql10); // Execution SQL logger.info("adherent carte envoi Row ID changed : " + results10.changedRows, { numsession: req.session.id, label: filename}); ///////////////////////////////////////////////// // GS - Taguer l'adhérent comme importé dans le tableau Google Sheet GS_asso_locales_rows[i].date_export = now; await GS_asso_locales_rows[i].save(); await sleep.wait(2000); nb_import++; } } ///////////////////////////////////////////////// // ON AFFICHE LE NOMBRE DE LIGNES IMPORTÉES req.session.message4 = 'Adhérents associations locales importées : ' + nb_import; res.redirect('/adhesion/maj_googlesheet'); } catch (error) { // Echec de connection à la BD logger.error("Il y a un problème avec la connection à la base de données : " + error, { numsession: req.session.id }); req.session.message4 = "Il y a un problème système, veuillez recommencer. " + error; //pool.end(); res.redirect('/adhesion/maj_googlesheet'); }; } ///////////////////////////////////////////////// // EXPORT DE MODULE POUR QU'IL SOIT LU DANS LES AUTRES FICHIERS JS ///////////////////////////////////////////////// module.exports = { import_ass_locales_v2 }