how to set a different message for an email template in odoo? - odoo

I created a custom module and had used the calendar object to create an event and the code is as follows
def create_calender_event(self,cr,uid,ids,context=None):
calendar_obj = self.pool.get('calendar.event')
for rec in self.browse(cr,uid,ids,context=context):
if rec.action:
for rec_res in rec.action:
calendar_obj.create(cr,uid,{'name' : rec_res.act_ion,
'user_id' : rec_res.asgnd_to.id,
'start_date' : rec_res.due_date,
'stop_date' : rec_res.due_date,
'allday' : True,
'partner_ids' : [(6,0, [rec_res.asgnd_to.partner_id.id])]
},context=context)
This will create a event in respective user's calendar, but it uses default template message.
How can i replace the calendar invitation template message by custom message ?

you can do like this from py file
1) get the template_id and browse the object
2) the template body will be stored in 'body_html' field
3) store the body_html field in one variable, lets say: old_body
4) then add your customized code to template's 'body_html' field and write the values into template using the above temlate_id
5) send the mail, using send method
6) then write back the old_body value back to the template.
just for idea, refer this....
template_id = template_pool.search(cr,uid,[('name','=ilike',template_name)])
if template_id:
template_obj = template_pool.browse(cr, uid, template_id)
body = template_obj.body_html
body_old = body
count = 0
body += " For %s Study Notes PDF Click here "%(url['subject'],url['url'])
template_pool.write(cr, uid, template_id, {'body_html':body})
template_pool.send_mail(cr, uid, template_id[0], record.id)
template_pool.write(cr, uid, template_id, {'body_html':
body_old})

It's email template with xml id "calendar_template_meeting_invitation" is used to send invitation. So find this template and change to whatever you want. Under template its called "Meeting Invitation" email template.
OLD===================
UPDATES================================
on calendar.event object create and write method calls the method create_attendees which create all attendee and send email invitation by calling method _send_mail_to_attendees code ref, so you need to overload that function and remvoe that statement so it doesn't send email when attendee is created rather send invitation when you want.
Bests

Related

How to send a variable to a text file that calling to karate feature file...?

Step 01#: I am calling 'Request Date' from json file and saving as "RequestDate"
Background:
json req = read('classpath:XXX/XXX/API/02_Dataset/DataSet.json')
* def RequestDate = get req.GameEnq.RequestDate
Step 02#: I am also calling 'GameDetailsRequest' from json file which has the field called "RequestDate", I would like pass "RequestDate" into "GameDetailsRequest".
Scenario: GameEnq
Given request
"""
GameDetailsRequest
"""
* def GameDetailsRequest = read('classpath:XXX/XXX/API/02_Dataset/ServiceRequestData_GameEnq');
Note: I can able to print the "RequestDate" value correctly ,however i don't know how to call into "GameDetailsRequest"... Please assist me. Your suggestion highly appreciated
Kind Regards
Sudheer Bonam
I think you need to try replace for a text place holder replacement
Add a placeholder <PLACEHOLDER_NAME> in your text data in GameDetailsRequest where you want to insert RequestDate
eg:
* string GameDetailsRequest = "Game release data : <RequestDate>"
* replace GameDetailsRequest.RequestDate = "12-12-2020"
Now GameDetailsRequest will be "Game release data : 12-12-2020"
refer: karate doc for replace

function with loop for urls won't return all of them

I am working on a project to pull details from state reports on restaurant inspections. Each inspection has its own url. I am able to gather the values into a dictionary, but only return one at a time. In the call to the function, if I don't specify a specific library entry, I get an error: ''list' object has no attribute 'timeout'' If it ask for a specific entry, I get a good return. How can I get them all?
# loop through the url list to gather inspection details
detailsLib = {}
def get_inspect_detail(urlList):
html = urlopen(urlList)
soup = bs4.BeautifulSoup(html.read(), 'lxml')
details = soup.find_all('font', {'face': 'verdana'})[10:]
result = []
for detail in details:
siteName = details[0].text
licNum = details[2].text
siteRank = details[4].text
detailsLib = {
'Restaurant': siteName,
'License': licNum,
'Rank': siteRank,
}
result.append(detailsLib)
return result
get_inspect_detail(urlList[21])
So I can get the 21st restaurant on the list, repeating 36 times, but not all of them.
Another question for another day is where to do the clean-up. The details will need some regex work but I'm unsure whether to do that inside the function (one at a time), or outside the function by calling all values from a specific key in the library.
Call get_inspect_detail() once per item in urlList, and save all the results.
all_results = []
for url in urlList:
details = get_inspect_detail(url)
all_results.extend(details)

Attachment is blank when sent first time but has data when sent second time through Apex contoller - SFDC NPSP

I am working on a requirement where I have to send pdf as an attachment through Apex class in SFDC NPSP. So following is my program structure –
VisualForcePage1 has two inputs – input1 and input2. The page also has
3 buttons – Preview, Send Email and Cancel. Depending on values of
input1 and input2, ApexClass1 computes values for say output1,
output2, output3, output4 and output5 using method getOutputMethod().
Values of these output1...5 variables are stored in a custom object
say Custom_Object__c.
public void getOutputMethod() {
// calculate values of output1...5
// store these values in Custom_Object__c
}
When user clicks on Preview button, method previewPDF() is called, which in turn calls getOutputMethod(). Output variables (output1...5) are stored in Custom_Object__c and then control is redirected to VisualForcePage2 which has attribute renderAs = ‘pdf’. The generated pdf has accurate data.
When user clicks on Send Email button, method emailPDF() is called, which in turn calls getOutputMethod(). Output variables (output1...5) are stored in Custom_Object__c. However attachment pdf sent in the mail has no data first time. For the same input values, attachment pdf has data when Send Email button is hit second and subsequent trials. Following is the code snippet for sending pdf as email –
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
// Reference the attachment page and pass in the account ID
PageReference pdf = Page.VisualForcePage2;
pdf.getParameters().put('paramater1',input1);
pdf.getParameters().put('paramater2',input2);
pdf.setRedirect(true);
// Take the PDF content
Blob b = pdf.getContentAsPDF();
// Create the email attachment
String filename = 'myPage.pdf';
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(filename);
efa.setBody(b);
// Sets the paramaters of the email
String subject = 'Subject';
body = 'Hello';
email.setSubject(subject);
email.setToAddresses('example#email.com');
email.setPlainTextBody(body);
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
// Sends the email
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
ApexClass2 of VisualForcePage2 queries Custom_Object__c with input1
and input2 as parameters as below –
public ApexClass2() { // constructor
var1 = ApexPages.currentPage().getParameters().get('paramater1');
var2 = ApexPages.currentPage().getParameters().get('paramater2'); getCustomObject();
}
public List<Custom_Object__c> getCustomObject() {
List<Custom_Object__c> coList = new List<Custom_Object__c>([
SELECT field1, field2, field3, field4, field5
FROM Custom_Object__c
WHERE field1 =: var1
AND field2 =: var2 ]);
return coList;
}
Please suggest.
Issue resolved. The code which was sending the attachment was picking up the records from database before they were updated. Hence, it was picking either blank or old data.
I added #future(callout=true) at the start of the method responsible for send attachment mail.

Using Google Apps script, how to check if an email has a pdf attached to it, then forward it to another email address?

I managed to create a function that converts an email to a pdf and then it forwards it to another email address ( I used this great library made by Mike Greiling :https://github.com/pixelcog/gmail-to-pdf).
but now I want to create another function that checks if the email already has an attachment, and then forward it right away.
here's my working function:
function saveExpenses() {
GmailUtils.processStarred( 'label: test', 5, function(message) {
// create a pdf of the message
var pdf = GmailUtils.messageToPdf(message);
// prefix the pdf filename with a date string
pdf.setName(GmailUtils.formatDate(message, 'yyyy/MM/dd - ') + pdf.getName());
// send confirmation email to the original sender
var confirmationEmail = message.getFrom();
// Get the name of the document to use as an email subject line.
var subject = pdf.getName();
var body = "This is a confirmation that this receipt has been sent";
// Send a confirmation email to the sender
GmailApp.sendEmail(confirmationEmail, subject, body, {attachments: [pdf]});
return true;
});
}
}
Ok, I found the solution, actually it was pretty easy.
I guess I didn't think enough, so basically I just get all the attachments from the message with the function getAttachmentswhich returns an array of attachments, I then just check if the length of the array is greater than 0 ( which means there are attachments in the email )
and if the result is 0, it means there are no attachments.
Here is what I did :
var attachment = message.getAttachments();
if (attachment.length > 0 ) {
// I add the code to deal with the attachment
} else if (attachment.length == 0 ) {
// I add the code that I posted in the question above
}

Undefined merge field in google apps script

I have a Google Apps Script for a Google Spreadsheet based on a Google Form that clients fill out online. The script is triggered by OnFormSubmit and generates a pdf based on a Google Doc template and sends the pdf to me by email using MailApp.sendEmail.
This script has been working fine until recently. The script runs successfully but the pdf output is incorrect. It seems like fields that are left blank are now being ignored in the script and so my pdf output shows the value for the next non-blank field. Ugh!
Anybody know what's going on here?
Below is an example of my script:
var docTemplate = "1FZL4rVe0LLpvMtIsq_3-pwv5POllIsyYThjfemkbkfg";
var docName = "Travel Details";
function onFormSubmit(e) {
var last = e.values[1];
var first = e.values[2];
var order = e.values[3];
var date = e.values[4];
var gender = e.values[5];
var email = "example#gmail.com";
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+last + ', ' + first)
.getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('keyLast', last);
copyBody.replaceText('keyFirst', first);
copyBody.replaceText('keyOrder', order);
copyBody.replaceText('keyDate', date);
copyBody.replaceText('keyGender', gender);
copyDoc.saveAndClose();
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
MailApp.sendEmail(email, subject, "", {htmlBody: office_message, attachments: pdf,
noReply:true});
DocsList.getFileById(copyId).setTrashed(true);
}
Example of the problem: If client leaves date field blank on the form, the gender value in the resulting pdf is put where the date value should be and the value for gender on the pdf shows "undefined".
Any ideas out there?
You should validate the values of all your variables.
if (last === undefined) {
last = 'No Data!'; //re-assign a different value
};
So, you are changing the value of the variable last if it somehow got set to undefined. That way, hopefully the pdf would still show the field.
If there is some bug that just showed up recently, you should report it as a bug. If everything was working fine, and now it's broken, Google may have changed something.
There might be something wrong with your code. I don't know. Have you looked under the "View" menu and the "Execution Transcript" to see if there are any errors? You should also use Logger.log statements: Logger.log('The value of last is: ' + last); to print output to the log. Then you can check what is actually going on.
I am no great coder but I use this script all the time to send pdf's I have never received an undefined if a field was missing. Typically if something is missing, the keygender is replaced with a blank spot and there is no error. In a spreadsheet, typically this means the columns were changed. It used to be timestamp(0), last(1), first(2), order(3), date(4), gender(5) and now their in a different order.
Try the below code it works
//commons errors -
//Triggers are not set
//spaces after Form questions
//e.values dont work when fields are not mandatory and left blank
//e.namedValues dont work for sending emails use e.values[#]
//place holder keys in template dont match
//spelling errors
//Note expect undefined error when de-bugging as values are not defined until form completed and submitted - run first with a small test form as per below
// Get Template
//from Google Docs and name it
var docTemplate = " "; // *** replace with new templae ID if new Template created***
var docName = "Test Script"; //replace with document name
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from the form and set as variables
//var variablename = "static entry or form value"
//Note: var Variablename = e.namedValues["X"]; is taking the value from the spreadsheet by column name so update if spreadsheet or form questions change
//Additions to the form will be added to the end of the spreadsheet regardless of their position in the form
var Timestamp = e.namedValues["Timestamp"];
var full_name = e.namedValues["Name"];
var position = e.namedValues["Position"]
var contact_email = e.namedValues["Contact Email"];
var phone_number = e.namedValues["Telephone Number"];
// Get document template, copy it as a new doc with Name and email, and save the id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(full_name+' '+docName+' for ' +contact_email+' '+Timestamp)//Update or remove Variablename to create full doc Name
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the documents body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys <<namedValues>> in template
//copyBody.replaceText('<<X>>', Variablename); Variables from above
//***Update if template is changed***
copyBody.replaceText('<<Timestamp>>', Timestamp);
copyBody.replaceText('<<Name>>', full_name);
copyBody.replaceText('<<Position>>', position);
copyBody.replaceText('<<Contact Email>>', contact_email);
copyBody.replaceText('<<Telephone Number>>', phone_number);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
{
// Add the data fields to the message
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = " ";
// Only include form fields that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] && (e.namedValues[key] != "") ) {
message += key+ ' : '+ e.namedValues[key] + "<br>";
}
}}
// Attach PDF and send the email
//***Change the "To" email address when to form goes live***
var to = "youremail#gmail.com";
var senders_name = e.values[1]
var contact_email = e.values[3]
var subject = "Test";
var htmlbody = "text goes here"+
"<br> <br>"+message+
"<br> <br>Submitted By:"+
"<br> <br>"+full_name+
"<br>"+position+
"<br>"+contact_email+
"<br>"+phone_number+
"<br> <br>Generated by Hansmoleman for Compu-Global-Hyper-Mega-Net";
MailApp.sendEmail({
name: senders_name,
to: to,
cc: contact_email,
replyTo: contact_email,
subject: subject,
htmlBody: htmlbody,
attachments: pdf,
});
}