-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.gs
116 lines (103 loc) · 3.91 KB
/
code.gs
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
/**
* Builds a search query string from a list of terms.
*
* @param {Array} terms - Array of search terms.
* @param {string} startDate - Start date in YYYY/MM/DD format.
* @param {string} endDate - End date in YYYY/MM/DD format.
* @return {string} The constructed search query.
*/
function buildSearchQuery(terms, startDate, endDate) {
// Map each term into a search query part
var queryParts = terms.map(term => `(${term})`);
// Construct the date range part of the query
var dateRangeQuery = ` after:${startDate} before:${endDate}`;
// Combine all parts into a full query string
return queryParts.join(' OR ') + dateRangeQuery;
}
/**
* Finds and returns Gmail messages that match the given query.
*
* @param {string} query - The search query.
* @return {Array} Array of Gmail messages that match the query.
*/
function findMessages(query) {
var messages = [];
var threads = GmailApp.search(query); // Search for threads that match the query
threads.forEach(thread => {
var msgs = thread.getMessages(); // Get all messages in a thread
msgs.forEach(msg => {
// Check if the message has attachments
if (msg.getAttachments().length > 0) {
messages.push(msg);
}
});
});
return messages;
}
/**
* Saves attachments from a message to a specified drive location.
*
* @param {Folder} driveLocation - The Google Drive folder to save attachments in.
* @param {GmailMessage} message - The Gmail message to process for attachments.
*/
function saveAttachments(driveLocation, message) {
var attachments = message.getAttachments();
attachments.forEach(attachment => {
// Skip if the attachment is an image
if (attachment.getContentType().indexOf("image/") === -1) {
// Check if the file already exists in the folder
var existingFiles = driveLocation.getFilesByName(attachment.getName());
if (!existingFiles.hasNext()) {
// Save the attachment to the drive location
driveLocation.createFile(attachment).setName(attachment.getName());
}
}
});
}
var folderCache = {}; // Cache for Google Drive folders to improve performance
/**
* Gets an existing folder or creates a new one if it doesn't exist.
*
* @param {string} folderPath - The path of the folder.
* @return {Folder} The Google Drive folder.
*/
function getOrCreateGdriveFolder(folderPath) {
// Return from cache if already available
if (folderCache[folderPath]) {
return folderCache[folderPath];
}
var path = folderPath.split("/");
var currentFolder = DriveApp.getRootFolder();
path.forEach(folderName => {
// Check if folder exists, else create it
var folderIterator = currentFolder.getFoldersByName(folderName);
currentFolder = folderIterator.hasNext() ? folderIterator.next() : currentFolder.createFolder(folderName);
});
folderCache[folderPath] = currentFolder; // Update cache
return currentFolder;
}
function orginizeInvoices(searchTerms, startDate,endDate) {
Logger.clear();
// Build search query using the terms and date range
var query = buildSearchQuery(searchTerms, startDate, endDate);
var messages = findMessages(query); // Find messages that match the query
Logger.log(`Found ${messages.length} messages for the query.`);
messages.forEach(message => {
var date = message.getDate();
var year = date.getFullYear();
var month = date.getMonth() + 1; // Months are 0-indexed
var monthFolderName = `Invoices/${year}/${month}`;
// Retrieve or create the folder for saving attachments
var driveLocation = getOrCreateGdriveFolder(monthFolderName);
saveAttachments(driveLocation, message); // Save attachments from the message
});
Logger.log("Processing complete.");
}
function main() {
var searchTerms = ['invoice', 'חשבונית'];
// Define date range outside the function
var startDate = '2024/01/01';
var endDate = '2024/01/04';
orginizeInvoices(searchTerms,startDate,endDate);
}
main(); // Run the main function