-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.gs
More file actions
314 lines (271 loc) · 10.9 KB
/
Code.gs
File metadata and controls
314 lines (271 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/**
* Sanadidari MailFlow AI 📧
* Phase 2 - Dashboard de Communication Intelligente
*/
function onOpen(e) {
// Pour un Add-on Gmail, le menu est géré par le Manifest,
// mais on garde onOpen pour la compatibilité si testé hors Gmail.
}
function onHomepage(e) {
return buildMainCard(e, null);
}
/**
* Point d'entrée principal pour Gmail
* Affiche la Sidebar/Card lors de l'ouverture d'un message
*/
function getContextualAddOn(e) {
if (!e.messageMetadata) {
return onHomepage(e);
}
const messageId = e.messageMetadata.messageId;
const accessToken = e.messageMetadata.accessToken;
GmailApp.setCurrentMessageAccessToken(accessToken);
return buildMainCard(e, messageId);
}
/**
* Construction de la carte principale
*/
function buildMainCard(e, messageId) {
let section = CardService.newCardSection();
if (messageId) {
const message = GmailApp.getMessageById(messageId);
const subject = message.getSubject();
const sender = message.getFrom();
section.addWidget(CardService.newDecoratedText()
.setText("✉️ " + sender)
.setBottomLabel("Sujet : " + subject)
.setWrapText(true))
.addWidget(CardService.newDivider())
.addWidget(CardService.newTextParagraph().setText("<b>Sélectionnez une action :</b>"))
.addWidget(CardService.newButtonSet()
.addButton(CardService.newTextButton()
.setText("💼 Réponse Pro")
.setOnClickAction(CardService.newAction().setFunctionName('handleReplyPro').setParameters({msgId: messageId})))
.addButton(CardService.newTextButton()
.setText("😊 Réponse Amicale")
.setOnClickAction(CardService.newAction().setFunctionName('handleReplyFriendly').setParameters({msgId: messageId}))))
.addWidget(CardService.newButtonSet()
.addButton(CardService.newTextButton()
.setText("⚡ Résumé Flash")
.setOnClickAction(CardService.newAction().setFunctionName('handleSummary').setParameters({msgId: messageId}))));
} else {
const credits = getUserCredits();
section.addWidget(CardService.newDecoratedText()
.setText("✨ Bienvenue dans MailFlow !")
.setBottomLabel("Ouvrez un email pour générer des réponses.")
.setWrapText(true))
.addWidget(CardService.newDivider())
.addWidget(CardService.newDecoratedText()
.setTopLabel("Votre solde")
.setText("💎 " + credits + " Crédits MF_")
.setBottomLabel("Packs de rechargement disponibles bientôt.")
.setWrapText(true));
}
return CardService.newCardBuilder()
.setHeader(CardService.newCardHeader().setTitle("MailFlow AI 📧").setSubtitle("Expert en communication AI"))
.addSection(section)
.build();
}
/**
* Inclut des fichiers HTML (CSS/JS)
*/
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
/**
* Ouvre l'interface HTML Premium
*/
function showPremiumUI(e) {
const msgId = e.parameters.msgId;
const html = HtmlService.createTemplateFromFile('Sidebar');
html.msgId = msgId;
return CardService.newActionResponseBuilder()
.setNavigation(CardService.newNavigation().pushCard(
CardService.newCardBuilder()
.setHeader(CardService.newCardHeader().setTitle("MailFlow Premium"))
.addSection(CardService.newCardSection()
.addWidget(CardService.newTextParagraph().setText("Chargement de l'interface haute performance...")))
.build()
))
.setOpenLink(CardService.newOpenLink()
.setUrl(ScriptApp.getService().getUrl() + "?msgId=" + msgId)
.setOpenAs(CardService.OpenAs.FULL_SIZE)
.setOnClose(CardService.OnClose.RELOAD_ADD_ON))
.build();
}
/**
* Point d'entrée pour l'accès direct via Web URL (si nécessaire)
*/
function doGet(e) {
const msgId = e.parameter.msgId;
const template = HtmlService.createTemplateFromFile('Sidebar');
template.msgId = msgId;
return template.evaluate().setTitle("Sanadidari MailFlow").setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
/**
* Génère une réponse via l'interface HTML
*/
function generateWithTone(prompt, tone, msgId) {
try {
const message = GmailApp.getMessageById(msgId);
const context = message.getPlainBody();
const credits = getUserCredits();
if (credits <= 0) return { status: 'error', message: '🚫 Crédits épuisés.' };
const systemPrompt = "Tu es un expert en communication. Ton but est de générer une réponse à cet email.\n" +
"Ton : " + tone + "\n" +
"Instructions utilisateur : " + prompt + "\n\n" +
"Email reçu : " + context;
const aiText = callGemini(systemPrompt, "Réponds UNIQUEMENT avec le corps de l'email de réponse. Pas de salutations d'intro IA.");
return { status: 'success', text: aiText };
} catch (e) {
return { status: 'error', message: e.toString() };
}
}
/**
* Crée un brouillon à partir du texte validé dans l'UI HTML
*/
function createDraftFromHtml(text, msgId) {
try {
const message = GmailApp.getMessageById(msgId);
message.createDraftReply(text);
return { status: 'success' };
} catch (e) {
return { status: 'error', message: e.toString() };
}
}
/**
* Handlers pour les boutons
*/
function handleReplyPro(e) { return generateAIResponse(e, "Professionnelle, courtoise et structurée."); }
function handleReplyFriendly(e) { return generateAIResponse(e, "Amicale, chaleureuse et décontractée."); }
function handleReplyDirect(e) { return generateAIResponse(e, "Directe, concise et efficace. Va droit au but."); }
function handleSummary(e) {
const msgId = e.parameters.msgId;
const message = GmailApp.getMessageById(msgId);
const context = message.getPlainBody();
const prompt = "Résume cet email en 3 points clés (bullet points). Sois très précis. \nEmail : " + context;
const summary = callGemini(prompt, "Tu es un assistant de synthèse haute performance.");
// Déduction crédit
deductCredit();
const card = CardService.newCardBuilder()
.setHeader(CardService.newCardHeader().setTitle("Résumé Flash"))
.addSection(CardService.newCardSection().addWidget(CardService.newTextParagraph().setText(summary)))
.addSection(CardService.newCardSection().addWidget(CardService.newTextButton().setText("⬅️ Retour").setOnClickAction(CardService.newAction().setFunctionName('getContextualAddOn'))))
.build();
return CardService.newNavigation().pushCard(card);
}
/**
* Moteur de génération de réponse
*/
function generateAIResponse(e, tone) {
const msgId = e.parameters.msgId;
const message = GmailApp.getMessageById(msgId);
const context = message.getPlainBody();
const credits = getUserCredits();
if (credits <= 0) {
return CardService.newActionResponseBuilder()
.setNotification(CardService.newNotification().setText("🚫 Crédits insuffisants."))
.build();
}
const prompt = "Génère une réponse à cet email avec le ton : " + tone + ". \nEmail reçu : " + context;
const aiDraft = callGemini(prompt, "Tu es un expert en communication. Réponds uniquement avec le texte de l'email.");
// Créer le brouillon dans Gmail
message.createDraftReply(aiDraft);
// Déduction crédit
deductCredit();
return CardService.newActionResponseBuilder()
.setNotification(CardService.newNotification().setText("✅ Brouillon créé avec succès !"))
.build();
}
/**
* Appel API Gemini (Multi-modèles Fallback)
*/
function callGemini(prompt, systemRole) {
// 🔑 Utilisation de la clé prouvée fonctionnelle (FlashBoard)
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
if (!apiKey) throw new Error('GEMINI_API_KEY not configured. Run setupApiKey() first.');
// 🌪️ MODÈLES DE DERNIÈRE GÉNÉRATION (DÉTECTÉS PAR DIAGNOSTIC)
const models = [
'gemini-2.5-flash',
'gemini-2.5-pro',
'gemini-2.0-flash'
];
const payload = {
contents: [{
parts: [{ text: systemRole + "\n\nDemande : " + prompt }]
}]
};
let lastError = "";
for (let model of models) {
try {
const url = `https://generativelanguage.googleapis.com/v1/models/${model}:generateContent?key=${apiKey}`;
const response = UrlFetchApp.fetch(url, {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload),
muteHttpExceptions: true
});
const code = response.getResponseCode();
const text = response.getContentText();
if (code === 200) {
const resJson = JSON.parse(text);
if (resJson.candidates && resJson.candidates[0].content) {
return resJson.candidates[0].content.parts[0].text;
}
} else {
lastError = `[Modèle: ${model}] Code: ${code} - ${text}`;
}
} catch (e) {
lastError = e.toString();
continue;
}
}
throw new Error("Impossible d'activer l'IA après test des modèles 2.5/2.0. Erreur : " + lastError);
}
// --- GESTION CRÉDITS (Préfixe MF_) ---
function getUserEmail() { return Session.getActiveUser().getEmail(); }
function getUserCredits() {
const email = getUserEmail();
const props = PropertiesService.getScriptProperties();
const db = JSON.parse(props.getProperty('CREDITS_DB') || "{}");
return db[email] === undefined ? 10 : db[email];
}
function deductCredit() {
const email = getUserEmail();
const props = PropertiesService.getScriptProperties();
const db = JSON.parse(props.getProperty('CREDITS_DB') || "{}");
const current = db[email] === undefined ? 10 : db[email];
db[email] = Math.max(0, current - 1);
props.setProperty('CREDITS_DB', JSON.stringify(db));
return db[email];
}
function doPost(e) {
// Webhook standardisé (Préfixe MF_)
try {
const params = e.parameter;
const paymentStatus = params.payment_status;
const payerEmail = params.payer_email;
const itemNumber = params.item_number || "";
if (paymentStatus === "Completed" && itemNumber.indexOf("MF_") === 0) {
let toAdd = 0;
if (itemNumber.includes("10")) toAdd = 10;
if (itemNumber.includes("50")) toAdd = 50;
if (itemNumber.includes("100")) toAdd = 100;
const props = PropertiesService.getScriptProperties();
const db = JSON.parse(props.getProperty('CREDITS_DB') || "{}");
db[payerEmail] = (db[payerEmail] || 10) + toAdd;
props.setProperty('CREDITS_DB', JSON.stringify(db));
return ContentService.createTextOutput("SUCCESS");
}
} catch (err) { return ContentService.createTextOutput("ERROR"); }
return ContentService.createTextOutput("IGNORED");
}
/**
* Run once from Apps Script editor (Run > setupApiKey) to store your Gemini API key.
* Alternatively: Apps Script > Project Settings > Script Properties > Add GEMINI_API_KEY.
*/
function setupApiKey() {
// Replace with your key, run once, then remove the hardcoded value
PropertiesService.getScriptProperties().setProperty('GEMINI_API_KEY', 'PASTE_YOUR_KEY_HERE');
Logger.log('✅ GEMINI_API_KEY saved. Remove the hardcoded value from setupApiKey() now.');
}