294 lines
11 KiB
JavaScript
294 lines
11 KiB
JavaScript
/////////////////////////////////////////////////
|
||
// 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 adhesion_envoi_carte = async function(req, res) {
|
||
|
||
logger.info("======================================", { label: filename });
|
||
logger.info("======== FUNCTION adhesion_envoi_carte (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
|
||
const identifiant_afps = req.params.identifiant_afps;
|
||
console.log('identifiant_afps reçu :', identifiant_afps);
|
||
|
||
////////////////////////////////////////////////////
|
||
// 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: false
|
||
});
|
||
const promisePool = pool.promise();
|
||
|
||
// Récupération des données nécessaires à la création du la carte adhérent, éventuellement au dispositif de don
|
||
// Récupération des données nécessaires à l'envoi par mail
|
||
|
||
|
||
const sql = `
|
||
SELECT adherent_nom, adherent_prenom, adherent_mail,
|
||
adherent_type, adherent_adresse_rue,
|
||
adherent_adresse_codepostal, adherent_adresse_ville
|
||
FROM adherent
|
||
WHERE identifiant = ?`;
|
||
|
||
const [results_adherent] = await promisePool.query(sql, [identifiant_afps]);
|
||
logger.info("SELECT ADHERENT adherent_nom : " + results_adherent[0].adherent_nom, { numsession: req.session.id, label: filename});
|
||
|
||
const sql2 = `SELECT montant_don, paiement_mode FROM adherent_finance WHERE identifiant = ?`;
|
||
const [results_adherent_finance] = await promisePool.query(sql2, [identifiant_afps]);
|
||
|
||
if (results_adherent[0].adherent_nom) {
|
||
|
||
/////////////////////////////////////////////////
|
||
// ENVOIE CARTE ADHÉRENT
|
||
//////////////////////////////////////////////////////////////////////////////
|
||
// ADOBE PDF : CRÉATION DE LA CARTE D'ADHÉSION EN PDF
|
||
// + JUSTIFICATIF DE DON
|
||
|
||
//////////////////////////////////////////////////////////////////////////////
|
||
// DÉFINIR LE PROFIL À AJOUTER DANS LA CARTE ADHÉRENT
|
||
// La fonction est dans le fichier /modules/adherent_type.js
|
||
profils = carte_adherent.profil(results_adherent[0].adherent_type);
|
||
profil1 = profils[0];
|
||
profil2 = profils[1];
|
||
profil3 = profils[2];
|
||
|
||
let OUTPUT;
|
||
let INPUT
|
||
|
||
// S'il y a un don
|
||
if (results_adherent_finance[0].montant_don > 0) {
|
||
|
||
OUTPUT = path.resolve(__dirname, "../pdf/adhesion/2526/paye/")+"/"+identifiant_afps+"_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/")+"/"+identifiant_afps+"_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 = results_adherent[0].adherent_adresse_rue;
|
||
adresse += " ";
|
||
adresse += results_adherent[0].adherent_adresse_codepostal;
|
||
adresse += " ";
|
||
adresse += results_adherent[0].adherent_adresse_ville;
|
||
|
||
if (profil2 == undefined) {profil2 = " "};
|
||
if (profil3 == undefined) {profil3 = ""};
|
||
|
||
|
||
JSON_INPUT =
|
||
{
|
||
"date": today,
|
||
"identifiant": identifiant_afps,
|
||
"profil1": profil1,
|
||
"profil2": profil2,
|
||
"profil3": profil3,
|
||
"mode_paiement": results_adherent_finance[0].paiement_mode,
|
||
"nom": results_adherent[0].adherent_nom,
|
||
"prenom": results_adherent[0].adherent_prenom,
|
||
"adresse": adresse,
|
||
"montant_don": results_adherent_finance[0].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 = identifiant_afps;
|
||
attachment_name += "_adhesion_2526_carteadherent.pdf";
|
||
var attachment_don_name = identifiant_afps;
|
||
attachment_don_name += "_don.pdf";
|
||
|
||
var mail_objet = "ASSOCIATION FRANÇAISE POUR LA PÉDAGOGIE SUZUKI - ADHÉSION 2025/2026 - ";
|
||
mail_objet += identifiant_afps;
|
||
mail_html = "<p>Cher adhérent,</p><p>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.</p><p>Vous trouverez en pièce jointe votre carte d'adhésion annuelle (valable du 1er septembre 2025 au 31 août 2026).</p><p>Votre identifiant (valable pour toute la famille) est ";
|
||
mail_html += identifiant_afps;
|
||
mail_html += ".</p>";
|
||
if (results_adherent_finance[0].montant_don > 0) {
|
||
mail_html += "<br><p>Nous vous remercions chaleureusement pour votre don. Votre justificatif est également joint à ce mail</p>";
|
||
}
|
||
mail_html += "<p><br>Nous vous remercions pour votre intérêt et vous souhaitons une très belle année en musique !</p><p>Association Française pour la pédagogie Suzuki<br>Chez Anne PAGES<br>30 rue des Tattes<br>74500 PUBLIER</p>";
|
||
|
||
|
||
var mailOptions = {
|
||
from: 'afps.inscription@gmail.com',
|
||
to: results_adherent[0].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 = "' + identifiant_afps + '"';
|
||
|
||
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});
|
||
|
||
res.json({
|
||
success: true,
|
||
message: `Email avec carte adhésion envoyé à : ${identifiant_afps}`,
|
||
});
|
||
} else {
|
||
res.status(404).json({
|
||
success: false,
|
||
message: `Aucun adhérent trouvé pour l'identifiant ${identifiant_afps}`,
|
||
});
|
||
}
|
||
|
||
} 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 });
|
||
res.json({ error });
|
||
};
|
||
|
||
}
|
||
|
||
|
||
/////////////////////////////////////////////////
|
||
// EXPORT DE MODULE POUR QU'IL SOIT LU DANS LES AUTRES FICHIERS JS
|
||
/////////////////////////////////////////////////
|
||
module.exports = {
|
||
adhesion_envoi_carte
|
||
} |