/
poweremail_template.py
285 lines (267 loc) · 17.4 KB
/
poweremail_template.py
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
#########################################################################
#Power Email is a module for Open ERP which enables it to send mails #
#Core settings are stored here #
#########################################################################
# ##### # # # #### ### ### # # ## ### # #
# # # # # # # # # # # # # # # # # # #
# #### # # # # ### ### ### # # # # # # #
# # # # # # # # # # # # # #### # # #
# # # # # #### # # ### # # # # ### #### #
# Copyright (C) 2009 Sharoon Thomas #
# #
#This program is free software: you can redistribute it and/or modify #
#it under the terms of the GNU General Public License as published by #
#the Free Software Foundation, either version 3 of the License, or #
# any later version. #
# #
#This program is distributed in the hope that it will be useful, #
#but WITHOUT ANY WARRANTY; without even the implied warranty of #
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
#GNU General Public License for more details. #
# #
#You should have received a copy of the GNU General Public License #
#along with this program. If not, see <http://www.gnu.org/licenses/>. #
#########################################################################
from osv import osv, fields
import netsvc
import poweremail_engines
class poweremail_templates(osv.osv):
_name="poweremail.templates"
_description = 'Power Email Templates for Models'
_columns = {
'name' : fields.char('Name of Template',size=100,required=True),
'object_name':fields.many2one('ir.model','Model'),
'def_to':fields.char('Recepient (To)',size=64,help="The default recepient of email. Placeholders can be used here."),
'def_cc':fields.char('Default CC',size=64,help="The default CC for the email. Placeholders can be used here."),
'def_bcc':fields.char('Default BCC',size=64,help="The default BCC for the email. Placeholders can be used here."),
'def_subject':fields.char('Default Subject',size=200, help="The default subject of email. Placeholders can be used here."),
'def_body_text':fields.text('Standard Body (Text)',help="The text version of the mail"),
'def_body_html':fields.text('Body (Text-Web Client Only)',help="The text version of the mail"),
'use_sign':fields.boolean('Use Signature',help="the signature from the User details will be appened to the mail"),
'file_name':fields.char('File Name Pattern',size=200,help="File name pattern can be specified with placeholders. eg. 2009_SO003.pdf"),
'report_template':fields.many2one('ir.actions.report.xml','Report to send'),
#'report_template':fields.reference('Report to send',[('ir.actions.report.xml','Reports')],size=128),
'allowed_groups':fields.many2many('res.groups','template_group_rel','templ_id','group_id',string="Allowed User Groups", help="Only users from these groups will be allowed to send mails from this ID"),
'enforce_from_account':fields.many2one('poweremail.core_accounts',string="Enforce From Account",help="Emails will be sent only from this account.",domain="[('company','=','yes')]"),
'auto_email':fields.boolean('Auto Email', help="Selecting Auto Email will create a server action for you which automatically sends mail after a new record is created."),
#Referred Stuff - Dont delete even if template is deleted
'attached_wkf':fields.many2one('workflow','Workflow'),
'attached_activity':fields.many2one('workflow.activity','Activity'),
#Referred Stuff - Delete these if template are deleted or they will crash the system
'server_action':fields.many2one('ir.actions.server','Related Server Action',help="Corresponding server action is here.",ondelete="cascade"),
'ref_ir_act_window':fields.many2one('ir.actions.act_window','Window Action',readonly=True,ondelete="cascade"),
'ref_ir_value':fields.many2one('ir.values','Wizard Button',readonly=True,ondelete="cascade"),
#Expression Builder fields
'model_object_field':fields.many2one('ir.model.fields',string="Field",help="Select the field from the model you want to use.\nIf it is a relationship field you will be able to choose the nested values in the box below\n(Note:If there are no values make sure you have selected the correct model)"),
'sub_object':fields.many2one('ir.model','Sub-model',help='When a relation field is used this field will show you the type of field you have selected'),
'sub_model_object_field':fields.many2one('ir.model.fields','Sub Field',help='When you choose relationship fields this field will specify the sub value you can use.'),
'null_value':fields.char('Null Value',help="This Value is used if the field is empty",size=50),
'copyvalue':fields.char('Expression',size=100,help="Copy and paste the value in the location you want to use a system value.")
}
_defaults = {
}
_sql_constraints = [
('name', 'unique (name)', 'The template name must be unique !')
]
def create(self, cr, uid, vals, *args, **kwargs):
src_obj = self.pool.get('ir.model').read(cr,uid,vals['object_name'],['model'])['model']
win_val={
'name': vals['name'] + " Mail Form",
'type':'ir.actions.act_window',
'res_model':'poweremail.send.wizard',
'src_model': src_obj,
'view_type': 'form',
'context': "{'src_model':'" + src_obj + "','template':'" + vals['name'] + "'}",
'view_mode':'form,tree',
'view_id':self.pool.get('ir.ui.view').search(cr,uid,[('name','=','poweremail.send.wizard.form')])[0],
'target': 'new',
'auto_refresh':1
}
vals['ref_ir_act_window']= self.pool.get('ir.actions.act_window').create(cr, uid, win_val)
value_vals={
'name': 'Send Mail(' + vals['name'] + ")",
'model': src_obj,
'key2': 'client_action_multi',
'value': "ir.actions.act_window,"+ str(vals['ref_ir_act_window']),
'object':True,
}
vals['ref_ir_value'] = self.pool.get('ir.values').create(cr, uid, value_vals)
return super(poweremail_templates,self).create(cr, uid, vals, *args, **kwargs)
def unlink(self, cr, uid, ids, ctx={}):
for id in ids:
try:
ref_ir_act_window = self.read(cr, uid, id, ['ref_ir_act_window'])['ref_ir_act_window']
ref_ir_value = self.read(cr, uid, id, ['ref_ir_value'])['ref_ir_value']
print ref_ir_act_window,ref_ir_value
if ref_ir_act_window:
self.pool.get('ir.actions.act_window').unlink(cr,uid,ref_ir_act_window[0])
if ref_ir_value:
self.pool.get('ir.values').unlink(cr,uid,ref_ir_value[0])
super(poweremail_templates,self).unlink(cr,uid,id)
except:
raise osv.except_osv(_("Warning"),_("Deletion of Record failed"))
return False
return True
def _field_changed(self,cr,uid,ids,parent_field):
#print "Parent:",parent_field
if parent_field:
field_obj = self.pool.get('ir.model.fields').browse(cr,uid,parent_field)
#print field_obj.ttype
if field_obj.ttype in ['many2one','one2many','many2many']:
res_ids=self.pool.get('ir.model').search(cr,uid,[('model','=',field_obj.relation)])
#print res_ids[0]
if res_ids:
self.write(cr,uid,ids,{'model_object_field':parent_field,'sub_object':res_ids[0],'sub_model_object_field':False})
expr_val = self._add_field(cr,uid,ids)
return {'value':{'sub_object':res_ids[0],'copyvalue':expr_val['value']['copyvalue']}}
else:
self.write(cr,uid,ids,{'model_object_field':parent_field,'sub_object':False,'sub_model_object_field':False})
expr_val = self._add_field(cr,uid,ids)
return {'value':{'sub_object':False,'sub_model_object_field':False,'copyvalue':expr_val['value']['copyvalue']}}
else:
self.write(cr,uid,ids,{'model_object_field':parent_field,'sub_object':False,'sub_model_object_field':False,})
expr_val = self._add_field(cr,uid,ids)
return {'value':{'sub_object':False,'sub_model_object_field':False,'copyvalue':expr_val['value']['copyvalue']}}
else:
expr_val = self._add_field(cr,uid,ids)
self.write(cr,uid,ids,{'sub_object':False,'sub_model_object_field':False})
return {'value':{'sub_object':False,'sub_model_object_field':False,'copyvalue':expr_val['value']['copyvalue']}}
def _add_field(self,cr,uid,ids,ctx={}):
try:
if self.read(cr,uid,ids,['model_object_field'])[0]['model_object_field']:
#print "Computing Field"
obj_id = self.read(cr,uid,ids,['model_object_field'])[0]['model_object_field'][0]
obj_br = self.pool.get('ir.model.fields').browse(cr,uid,obj_id)
obj_not = obj_br.name
if self.read(cr,uid,ids,['sub_model_object_field'])[0]['sub_model_object_field']:
obj_id = self.read(cr,uid,ids,['sub_model_object_field'])[0]['sub_model_object_field'][0]
obj_br = self.pool.get('ir.model.fields').browse(cr,uid,obj_id)
obj_not = obj_not + "." + obj_br.name
if self.read(cr,uid,ids,['null_value'])[0]['null_value']:
obj_not = obj_not + "/" + self.read(cr,uid,ids,['null_value'])[0]['null_value']
obj_not = "[[object." + obj_not + "]]"
#print "Object Value (_add_field):",obj_not
self.write(cr,uid,ids,{'copyvalue':obj_not})
return {'value':{'copyvalue':obj_not}}
except:
raise osv.except_osv(_("Warning"),_("You need to save the template before expressions can be computed"))
def _auto_compute(self,cr,uid,ids,model_object_field,sub_model_object_field,null_value,ctx={}):
if model_object_field:
obj_id = model_object_field
obj_br = self.pool.get('ir.model.fields').browse(cr,uid,obj_id)
obj_not = obj_br.name
if sub_model_object_field:
obj_br = self.pool.get('ir.model.fields').browse(cr,uid,sub_model_object_field)
obj_not = obj_not + "." + obj_br.name
if null_value:
obj_not = obj_not + "/" + null_value
obj_not = "[[object." + obj_not + "]]"
#print "Object Value (_suto_compute):",obj_not
#self.write(cr,uid,ids,{'copyvalue':obj_not})
return {'value':{'copyvalue':obj_not}}
def get_value(self,cr,uid,recid,message={},template=None):
if message:
return self.engine.parsevalue(cr,uid,recid,message,template,{})
else:
return ""
def generate_mail(self,cr,uid,id,recid,context={}):
#Generates an email an saves to outbox given the template id & record ID of a record in template's model
#id: ID of template to be used
#recid: record id for the mail
#Context: not currently used
logger = netsvc.Logger()
try:
self.engine = self.pool.get("poweremail.engines")
template = self.browse(cr,uid,id)
vals = {
'pem_from': template.object_name.model,
'pem_to':self.get_value(cr,uid,recid,template.def_to,template.id),
'pem_cc':self.get_value(cr,uid,recid,template.def_cc,template.id),
'pem_bcc':self.get_value(cr,uid,recid,template.def_bcc,template.id),
'pem_subject':self.get_value(cr,uid,recid,template.def_subject,template.id),
'pem_body_text':self.get_value(cr,uid,recid,template.def_body_text,template.id),
'pem_body_html':self.get_value(cr,uid,recid,template.def_body_html,template.id),
'pem_account_id' :template.enforce_from_account,#This is a mandatory field when automatic emails are sent
'state':'na',
'mail_type':'multipart/alternative' #Options:'multipart/mixed','multipart/alternative','text/plain','text/html'
}
if template.use_sign:
sign = self.pool.get('res.users').read(cr,uid,uid,['signature'])['signature']
if vals['pem_body_text']:
vals['pem_body_text']+=sign
if vals['pem_body_html']:
vals['pem_body_html']+=sign
#Create partly the mail and later update attachments
mail_id = self.pool.get('poweremail.mailbox').create(cr,uid,vals)
if template.report_template:
reportname = 'report.' + self.pool.get('ir.actions.report.xml').read(cr,uid,template.report_template.id,['report_name'])['report_name']
service = netsvc.LocalService(reportname)
(result, format) = service.create(cr, uid, [id], {}, {})
att_obj = self.pool.get('ir.attachment')
new_att_vals={
'name':vals['pem_subject'] + ' (Email Attachment)',
'datas':base64.b64encode(result),
'datas_fname':str(self.get_value(template.file_name) or 'Report') + "." + format,
'description':vals['pem_body_text'] or "No Description",
'res_model':'poweremail.mailbox',
'res_id':mail_id
}
attid = att_obj.create(cr,uid,new_att_vals)
if attid:
self.pool.get('poweremail.mailbox').write(cr,uid,mail_id,{'pem_attachments_ids':[[6, 0, [attid]]],'mail_type':'multipart/mixed','folder':'outbox'})
return mail_id
except Exception,error:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Email Generation failed, Reason:%s")% (error))
return False
poweremail_templates()
class poweremail_preview(osv.osv_memory):
_name = "poweremail.preview"
_description = "Power Email Template Preview"
def _get_model_recs(self,cr,uid,ctx={}):
#Fills up the selection box which allows records from the selected object to be displayed
self.context = ctx
if 'active_id' in ctx.keys():
ref_obj_id = self.pool.get('poweremail.templates').read(cr,uid,ctx['active_id'],['object_name'])['object_name']
ref_obj_name = self.pool.get('ir.model').read(cr,uid,ref_obj_id[0],['model'])['model']
ref_obj_ids = self.pool.get(ref_obj_name).search(cr,uid,[])
ref_obj_recs = self.pool.get(ref_obj_name).name_get(cr,uid,ref_obj_ids)
#print ref_obj_recs
return ref_obj_recs
_columns = {
'ref_template':fields.many2one('poweremail.templates','Template',readonly=True),
'rel_model':fields.many2one('ir.model','Model',readonly=True),
'rel_model_ref':fields.selection(_get_model_recs,'Referred Document'),
'to':fields.char('To',size=100,readonly=True),
'cc':fields.char('CC',size=100,readonly=True),
'bcc':fields.char('BCC',size=100,readonly=True),
'subject':fields.char('Subject',size=200,readonly=True),
'body_text':fields.text('Body',readonly=True),
'body_html':fields.text('Body',readonly=True),
'report':fields.char('Report Name',size=100,readonly=True),
}
_defaults = {
'ref_template': lambda self,cr,uid,ctx:ctx['active_id'],
'rel_model': lambda self,cr,uid,ctx:self.pool.get('poweremail.templates').read(cr,uid,ctx['active_id'],['object_name'])['object_name']
}
def _on_change_ref(self,cr,uid,ids,rel_model_ref,ctx={}):
engine = self.pool.get("poweremail.engines")
if rel_model_ref:
vals={}
if ctx == {}:
ctx = self.context
template = self.pool.get('poweremail.templates').browse(cr,uid,ctx['active_id'],ctx)
vals['to']= engine.parsevalue(cr,uid,rel_model_ref,template.def_to,template.id,ctx)
vals['cc']= engine.parsevalue(cr,uid,rel_model_ref,template.def_cc,template.id,ctx)
vals['bcc']= engine.parsevalue(cr,uid,rel_model_ref,template.def_bcc,template.id,ctx)
vals['subject']= engine.parsevalue(cr,uid,rel_model_ref,template.def_subject,template.id,ctx)
vals['body_text']=engine.parsevalue(cr,uid,rel_model_ref,engine.strip_html(template.def_body_text),template.id,ctx)
vals['body_html']=engine.parsevalue(cr,uid,rel_model_ref,template.def_body_html,template.id,ctx)
vals['report']= engine.parsevalue(cr,uid,rel_model_ref,template.file_name,template.id,ctx)
#print "Vals>>>>>",vals
return {'value':vals}
poweremail_preview()
class res_groups(osv.osv):
_inherit = "res.groups"
_description = "User Groups"
_columns = {}
res_groups()