diff --git a/poweremail_demo.xml b/poweremail_demo.xml index a0be8b2..7c3da24 100644 --- a/poweremail_demo.xml +++ b/poweremail_demo.xml @@ -29,6 +29,43 @@ Benvolgut/da ${object.login}, Això és un email generic de prova per les poweremail_camapign. +Atentament, + +un mort de gana. + + +]]> + + + + + Plantilla poweremail test 2 + + + res.users + + ${object.number} + ${object.address_invoice_id.email} + + + + Factura ${object.number} + mako + + ${object.partner_id.lang} + ${object.partner_id.lang} + + + + + + +Benvolgut/da ${object.login}, + +Això és un email generic de prova per les poweremail_camapign. + + Atentament, un mort de gana. diff --git a/poweremail_send_wizard.py b/poweremail_send_wizard.py index 8b1280b..df8f053 100644 --- a/poweremail_send_wizard.py +++ b/poweremail_send_wizard.py @@ -266,169 +266,271 @@ def get_generated(self, cr, uid, ids=None, context=None): raise osv.except_osv(_("Power Email"),_("Email sending failed for one or more objects.")) return True - def save_to_mailbox(self, cr, uid, ids, context=None): + def get_end_value(self, cr, uid, src_rec_id, value, template, context=None): + if context is None: + context = {} + if len(context['src_rec_ids']) > 1: # Multiple Mail: Gets value from the template + return self.get_value(cr, uid, template, value, context, src_rec_id) + else: + return value + + def create_mail(self, cr, uid, screen_vals, src_rec_id, vals, context=None): + if context is None: + context = {} + + mailbox_obj = self.pool.get('poweremail.mailbox') + res_users_obj = self.pool.get('res.users') + + vals.update(context.get("extra_vals", {})) + if screen_vals['signature']: + signature = res_users_obj.read(cr, uid, uid, ['signature'], context=context)['signature'] + if signature: + vals['pem_body_text'] = tools.ustr(vals['pem_body_text'] or '') + '\n--\n' + signature + vals['pem_body_html'] = tools.ustr(vals['pem_body_html'] or '') + signature + # Create partly the mail and later update attachments + ctx = context.copy() + ctx.update({'src_rec_id': src_rec_id}) + mail_id = mailbox_obj.create(cr, uid, vals, context=ctx) + return mail_id - model_obj = self.pool.get('ir.model') - + def check_lang(self, cr, uid, template, src_rec_id, context=None): if context is None: context = {} - def get_end_value(id, value): - if len(context['src_rec_ids']) > 1: # Multiple Mail: Gets value from the template - return self.get_value(cr, uid, template, value, context, id) + + res_lang_obj = self.pool.get('res.lang') + res_users_obj = self.pool.get('res.users') + + if template.lang: + context['lang'] = self.get_value(cr, uid, template, template.lang, context, src_rec_id) + lang = self.get_value(cr, uid, template, template.lang, context, src_rec_id) + if len(res_lang_obj.search(cr, uid, [('name', '=', lang)], context=context)): + return lang + if not context.get('lang', False) or context['lang'] == 'False': + return res_users_obj.read(cr, uid, uid, ['context_lang'], context=context)['context_lang'] + + def create_report_attachment(self, cr, uid, template, vals, screen_vals, mail_id, report_record_ids, src_rec_id, context=None): + if context is None: + context = {} + + ir_act_rep_xml_obj = self.pool.get('ir.actions.report.xml') + ir_model_obj = self.pool.get('ir.model') + attach_obj = self.pool.get('ir.attachment') + + if template.report_template: + reportname_read = ir_act_rep_xml_obj.read( + cr, uid, template.report_template.id, ['report_name'], context=context + )['report_name'] + reportname = 'report.' + reportname_read + data = {} + data['model'] = ir_model_obj.browse(cr, uid, screen_vals['rel_model'], context=context).model + service = netsvc.LocalService(reportname) + if template.report_template.context: + context.update(eval(template.report_template.context)) + if screen_vals['single_email'] and len(report_record_ids) > 1: + # The optional attachment will be generated as a single file for all these records + (result, format) = service.create(cr, uid, report_record_ids, data, context=context) else: - return value + (result, format) = service.create(cr, uid, [src_rec_id], data, context=context) + attach_vals = { + 'name': _('%s (Email Attachment)') % tools.ustr(vals['pem_subject']), + 'datas': base64.b64encode(result), + 'datas_fname': tools.ustr( + self.get_end_value( + cr, uid, src_rec_id, screen_vals['report'], template, context=context + ) or _('Report') + ) + "." + format, + 'description': vals['pem_body_text'] or _("No Description"), + 'res_model': 'poweremail.mailbox', + 'res_id': mail_id + } + attachment_id = attach_obj.create(cr, uid, attach_vals, context=context) + return attachment_id + return False + + def process_extra_attachment_in_template(self, cr, uid, template, src_rec_id, mail_id, data, context=None): + if context is None: + context = {} + + attach_obj = self.pool.get('ir.attachment') + + attachment_ids = [] + # For each extra attachment in template + for tmpl_attach in template.tmpl_attachment_ids: + report = tmpl_attach.report_id + reportname = 'report.%s' % report.report_name + data['model'] = report.model + model_obj = self.pool.get(report.model) + # Parse search params + search_params = eval(self.get_value(cr, uid, template, tmpl_attach.search_params,context, src_rec_id)) + report_model_ids = model_obj.search(cr, uid, search_params, context=context) + file_name = self.get_value(cr, uid, template, tmpl_attach.file_name, context, src_rec_id) + if report_model_ids: + service = netsvc.LocalService(reportname) + (result, format) = service.create(cr, uid, report_model_ids, data, context=context) + attach_vals = { + 'name': file_name, + 'datas': base64.b64encode(result), + 'datas_fname': file_name, + 'description': _("No Description"), + 'res_model': 'poweremail.mailbox', + 'res_id': mail_id + } + attachment_id = attach_obj.create(cr, uid, attach_vals, context=context) + attachment_ids.append(attachment_id) + return attachment_ids + + def add_attachment_documents(self, cr, uid, screen_vals, mail_id, context=None): + if context is None: + context = {} + + attach_obj = self.pool.get('ir.attachment') + + attach_values = { + 'res_model': 'poweremail.mailbox', + 'res_id': mail_id, + } + + # Add document attachments + attachment_ids_doc = [] + for attachment_id in screen_vals.get('attachment_ids', []): + new_id = attach_obj.copy(cr, uid, attachment_id, attach_values, context=context) + attachment_ids_doc.append(new_id) + return attachment_ids_doc + + def add_template_attachments(self, cr, uid, template, mail_id, context=None): + if context is None: + context = {} + + attach_obj = self.pool.get('ir.attachment') + + # Add template attachments + search_params = [ + ('res_model', '=', 'poweremail.templates'), + ('res_id', '=', template.id), + ] + if context['lang']: + search_params.append(('datas_fname', 'ilike', '%%.%s.%%' % context['lang'])) + attach_ids = attach_obj.search(cr, uid, search_params, context=context) + attachment_ids_templ = [] + for attach in attach_obj.browse(cr, uid, attach_ids, context=context): + attach_values = { + 'res_model': 'poweremail.mailbox', + 'res_id': mail_id, + 'name': attach.name.replace('.%s' % context['lang'], ''), + 'datas_fname': attach.datas_fname.replace('.%s' % context['lang'], '') + } + new_id = attach_obj.copy(cr, uid, attach.id, attach_values, context=context) + attachment_ids_templ.append(new_id) + return attachment_ids_templ + + def create_partner_event(self, cr, uid, template, vals, data, src_rec_id, mail_id, attachment_ids, context=None): + if context is None: + context = {} + + rrlink_obj = self.pool.get('res.request.link') + mailgate_obj = self.pool.get('mailgate.message') + + # Create a partner event + if template.partner_event and self._get_template_value(cr, uid, 'partner_event', context=context): + name = vals['pem_subject'] + if isinstance(name, str): + name = unicode(name, 'utf-8') + if len(name) > 64: + name = name[:61] + '...' + model = res_id = False + if template.report_template and rrlink_obj.search(cr, uid, [ + ('object', '=', data['model'])], context=context): + model = data['model'] + res_id = src_rec_id + elif attachment_ids and rrlink_obj.search(cr, uid, [('object', '=', 'ir.attachment')], context=context): + model = 'ir.attachment' + res_id = attachment_ids[0] + cr.execute("SELECT state from ir_module_module where state='installed' and name = 'mail_gateway'") + mail_gateway = cr.fetchall() + if mail_gateway: + values = { + 'history': True, + 'name': name, + 'date': time.strftime('%Y-%m-%d %H:%M:%S'), + 'user_id': uid, + 'email_from': vals['pem_from'] or None, + 'email_to': vals['pem_to'] or None, + 'email_cc': vals['pem_cc'] or None, + 'email_bcc': vals['pem_bcc'] or None, + 'message_id': mail_id, + 'description': vals['pem_body_text'] and vals['pem_body_text'] or vals['pem_body_html'], + 'partner_id': self.get_value(cr, uid, template, template.partner_event, context, src_rec_id), + 'model': model, + 'res_id': res_id, + } + mailgate_obj.create(cr, uid, values, context=context) + + def save_to_mailbox(self, cr, uid, ids, context=None): + if context is None: + context = {} + + core_accounts_obj = self.pool.get('poweremail.core_accounts') + mailbox_obj = self.pool.get('poweremail.mailbox') + res_users_obj = self.pool.get('res.users') mail_ids = [] template = self._get_template(cr, uid, context) screen_vals = self.read(cr, uid, ids[0], [], context) - if isinstance(screen_vals, list): # Solves a bug in v5.0.16 + if isinstance(screen_vals, list): # Solves a bug in v5.0.16 screen_vals = screen_vals[0] report_record_ids = context['src_rec_ids'][:] if screen_vals['single_email'] and len(context['src_rec_ids']) > 1: # We send a single email for several records context['src_rec_ids'] = context['src_rec_ids'][:1] - - for id in context['src_rec_ids']: - accounts = self.pool.get('poweremail.core_accounts').read(cr, uid, screen_vals['from'], context=context) + for src_rec_id in context['src_rec_ids']: + attachment_ids = [] + accounts = core_accounts_obj.read(cr, uid, screen_vals['from'], context=context) vals = { 'pem_from': tools.ustr(accounts['name']) + "<" + tools.ustr(accounts['email_id']) + ">", - 'pem_to': get_end_value(id, screen_vals['to']), - 'pem_cc': get_end_value(id, screen_vals['cc']), - 'pem_bcc': get_end_value(id, screen_vals['bcc']), - 'pem_subject': get_end_value(id, screen_vals['subject']), - 'pem_body_text': get_end_value(id, screen_vals['body_text']), - 'pem_body_html': get_end_value(id, screen_vals['body_html']), + 'pem_to': self.get_end_value(cr, uid, src_rec_id, screen_vals['to'], template, context=context), + 'pem_cc': self.get_end_value(cr, uid, src_rec_id, screen_vals['cc'], template, context=context), + 'pem_bcc': self.get_end_value(cr, uid, src_rec_id, screen_vals['bcc'], template, context=context), + 'pem_subject': self.get_end_value(cr, uid, src_rec_id, screen_vals['subject'], template, + context=context), + 'pem_body_text': self.get_end_value(cr, uid, src_rec_id, screen_vals['body_text'], template, + context=context), + 'pem_body_html': self.get_end_value(cr, uid, src_rec_id, screen_vals['body_html'], template, + context=context), 'pem_account_id': screen_vals['from'], 'priority': screen_vals['priority'], - 'state':'na', - 'mail_type':'multipart/alternative' #Options:'multipart/mixed','multipart/alternative','text/plain','text/html' + 'state': 'na', + 'mail_type': 'multipart/alternative' + # Options:'multipart/mixed','multipart/alternative','text/plain','text/html' } - vals.update(context.get("extra_vals", {})) - if screen_vals['signature']: - signature = self.pool.get('res.users').read(cr, uid, uid, ['signature'], context)['signature'] - if signature: - vals['pem_body_text'] = tools.ustr(vals['pem_body_text'] or '') + '\n--\n' + signature - vals['pem_body_html'] = tools.ustr(vals['pem_body_html'] or '') + signature - - attachment_ids = [] - - #Create partly the mail and later update attachments ctx = context.copy() - ctx.update({'src_rec_id': id}) - mail_id = self.pool.get('poweremail.mailbox').create(cr, uid, vals, ctx) + mail_id = self.create_mail(cr, uid, screen_vals, src_rec_id, vals, context=ctx) mail_ids.append(mail_id) # Ensure report is rendered using template's language. If not found, user's launguage is used. ctx = context.copy() - if template.lang: - ctx['lang'] = self.get_value(cr, uid, template, template.lang, context, id) - lang = self.get_value(cr, uid, template, template.lang, context, id) - if len(self.pool.get('res.lang').search(cr, uid, [('name','=',lang)], context = context)): - ctx['lang'] = lang - if not ctx.get('lang', False) or ctx['lang'] == 'False': - ctx['lang'] = self.pool.get('res.users').read(cr, uid, uid, ['context_lang'], context)['context_lang'] - if template.report_template: - reportname = 'report.' + self.pool.get('ir.actions.report.xml').read(cr, uid, template.report_template.id, ['report_name'], context)['report_name'] - data = {} - data['model'] = self.pool.get('ir.model').browse(cr, uid, screen_vals['rel_model'], context).model - - service = netsvc.LocalService(reportname) - - if template.report_template.context: - ctx.update(eval(template.report_template.context)) - - if screen_vals['single_email'] and len(report_record_ids) > 1: - # The optional attachment will be generated as a single file for all these records - (result, format) = service.create(cr, uid, report_record_ids, data, ctx) - else: - (result, format) = service.create(cr, uid, [id], data, ctx) - attachment_id = self.pool.get('ir.attachment').create(cr, uid, { - 'name': _('%s (Email Attachment)') % tools.ustr(vals['pem_subject']), - 'datas': base64.b64encode(result), - 'datas_fname': tools.ustr(get_end_value(id, screen_vals['report']) or _('Report')) + "." + format, - 'description': vals['pem_body_text'] or _("No Description"), - 'res_model': 'poweremail.mailbox', - 'res_id': mail_id - }, context) - attachment_ids.append( attachment_id ) - - # For each extra attachment in template - for tmpl_attach in template.tmpl_attachment_ids: - report = tmpl_attach.report_id - reportname = 'report.%s' % report.report_name - data = {} - data['model'] = report.model - model_obj = self.pool.get(report.model) - #Parse search params - search_params = eval(self.get_value(cr, uid, template, - tmpl_attach.search_params, - context, id)) - report_model_ids = model_obj.search(cr, uid, search_params) - file_name = self.get_value(cr, uid, template, - tmpl_attach.file_name, - context, id) - if not report_model_ids: - continue - service = netsvc.LocalService(reportname) - (result, format) = service.create(cr, uid, report_model_ids, data, ctx) - attachment_id = self.pool.get('ir.attachment').create(cr, uid, { - 'name': file_name, - 'datas': base64.b64encode(result), - 'datas_fname': file_name, - 'description': _("No Description"), - 'res_model': 'poweremail.mailbox', - 'res_id': mail_id - }, context) - attachment_ids.append( attachment_id ) - + self.check_lang(cr, uid, template, src_rec_id, context=ctx) + attachment_id = self.create_report_attachment( + cr, uid, template, vals, screen_vals, mail_id, report_record_ids, src_rec_id, context=ctx + ) + if attachment_id: + attachment_ids.append(attachment_id) + data = [] + attachment_ids_extra = self.process_extra_attachment_in_template( + cr, uid, template, src_rec_id, mail_id, data, context=ctx + ) + attachment_ids.extend(attachment_ids_extra) # Add document attachments - for attachment_id in screen_vals.get('attachment_ids',[]): - new_id = self.pool.get('ir.attachment').copy(cr, uid, attachment_id, { - 'res_model': 'poweremail.mailbox', - 'res_id': mail_id, - }, context) - attachment_ids.append( new_id ) - + attachment_ids_doc = self.add_attachment_documents(cr, uid, screen_vals, mail_id, context=ctx) + attachment_ids.extend(attachment_ids_doc) + # Add template attachments + attachment_ids_templ = self.add_template_attachments(cr, uid, template, mail_id, context=ctx) + attachment_ids.extend(attachment_ids_templ) if attachment_ids: - self.pool.get('poweremail.mailbox').write(cr, uid, mail_id, { + mailbox_vals = { 'pem_attachments_ids': [[6, 0, attachment_ids]], 'mail_type': 'multipart/mixed' - }, context) - - # Create a partner event - if template.partner_event and self._get_template_value(cr, uid, 'partner_event', context): - name = vals['pem_subject'] - if isinstance(name, str): - name = unicode(name, 'utf-8') - if len(name) > 64: - name = name[:61] + '...' - - model = res_id = False - if template.report_template and self.pool.get('res.request.link').search(cr, uid, [('object','=',data['model'])], context=context): - model = data['model'] - res_id = id - elif attachment_ids and self.pool.get('res.request.link').search(cr, uid, [('object','=','ir.attachment')], context=context): - model = 'ir.attachment' - res_id = attachment_ids[0] - - cr.execute("SELECT state from ir_module_module where state='installed' and name = 'mail_gateway'") - mail_gateway = cr.fetchall() - if mail_gateway: - values = { - 'history': True, - 'name': name, - 'date': time.strftime('%Y-%m-%d %H:%M:%S'), - 'user_id': uid, - 'email_from': vals['pem_from'] or None, - 'email_to': vals['pem_to'] or None, - 'email_cc': vals['pem_cc'] or None, - 'email_bcc': vals['pem_bcc'] or None, - 'message_id': mail_id, - 'description': vals['pem_body_text'] and vals['pem_body_text'] or vals['pem_body_html'], - 'partner_id': self.get_value(cr, uid, template, template.partner_event, context, id), - 'model': model, - 'res_id': res_id, - } - self.pool.get('mailgate.message').create(cr, uid, values, context) + } + mailbox_obj.write(cr, uid, mail_id, mailbox_vals, context=context) + self.create_partner_event(cr, uid, template, vals, data, src_rec_id, mail_id, attachment_ids, context=ctx) return mail_ids poweremail_send_wizard() diff --git a/poweremail_template.py b/poweremail_template.py index 76cec50..d0da89f 100644 --- a/poweremail_template.py +++ b/poweremail_template.py @@ -238,6 +238,40 @@ def _get_model_name( res[template_id] = mod_name return res + def _fnc_ir_attachment_ids(self, cr, uid, template_ids, fieldnames, args, context=None): + res = dict.fromkeys(template_ids, []) + attach_obj = self.pool.get('ir.attachment') + for template_id in template_ids: + search_params = [ + ('res_model', '=', 'poweremail.templates'), + ('res_id', '=', template_id), + ] + res[template_id] = attach_obj.search(cr, uid, search_params, context=context) + return res + + def fnct_inv_attachment_ids(self, cursor, uid, ids, field_name, value, args, context=None): + attach_obj = self.pool.get('ir.attachment') + if context is None: + context = {} + if not value: + return False + if isinstance(ids, (int, long)): + ids = [ids] + + for attach in value: + operation = attach[0] + attach_id = attach[1] + if operation != 2: # si estamos eliminando no tendremos vals + vals = attach[2] + if operation == 0: # el volem crear + vals.update({'res_id': ids[0], 'res_model': 'poweremail.templates'}) + attach_obj.create(cursor, uid, vals, context=context) + elif operation == 1: # volem escriure sobre un registre existent + attach_obj.write(cursor, uid, attach_id, vals, context=context) + elif operation == 2: # volem eliminar-lo + attach_obj.unlink(cursor, uid, [attach_id], context=context) + return True + _columns = { 'name': fields.char('Name of Template', size=100, required=True), 'object_name': fields.many2one('ir.model', 'Model'), @@ -430,7 +464,12 @@ def _get_model_name( "Example : o.type == 'out_invoice' and o.number and o.number[:3]<>'os_' "), 'tmpl_attachment_ids': fields.one2many('poweremail.template.attachment', 'template_id', - 'Attachments') + 'Attachments'), + 'ir_attachment_ids': fields.function(_fnc_ir_attachment_ids, + fnct_inv= fnct_inv_attachment_ids, + method=True, type='one2many', + relation='ir.attachment', + string='Attachments'), } _defaults = { @@ -781,13 +820,20 @@ def _generate_partner_events(self, context) return True - def _generate_attach_reports(self, - cursor, - user, - template, - record_ids, - mail, - context=None): + def create_report(self, cursor, user, template, record_ids, context=None): + if context is None: + context = {} + report_obj = self.pool.get('ir.actions.report.xml') + report_name = report_obj.read( + cursor, user, template.report_template.id, ['report_name'], context=context + )['report_name'] + reportname = 'report.' + report_name + service = netsvc.LocalService(reportname) + data = {'model': template.model_int_name} + (result, format) = service.create(cursor, user, record_ids, data, context=context) + return (result, format) + + def _generate_attach_reports(self, cursor, user, template, record_ids, mail, context=None): """ Generate report to be attached and attach it to the email @@ -802,64 +848,58 @@ def _generate_attach_reports(self, @param mail: Browse record of email object @return: True """ - lang = get_value(cursor, - user, - record_ids[0], - template.lang, - template, - context) + if context is None: + context = {} + attachment_obj = self.pool.get('ir.attachment') + mailbox_obj = self.pool.get('poweremail.mailbox') + lang = get_value(cursor, user, record_ids[0], template.lang, template, context=context) + ctx = context.copy() if lang: - ctx = context.copy() - ctx.update({'lang':lang}) + ctx['lang'] = lang template = self.browse(cursor, user, template.id, context=ctx) - reportname = 'report.' + \ - self.pool.get('ir.actions.report.xml').read( - cursor, - user, - template.report_template.id, - ['report_name'], - context)['report_name'] - service = netsvc.LocalService(reportname) - data = {} - data['model'] = template.model_int_name - (result, format) = service.create(cursor, - user, - record_ids, - data, - context) - attachment_obj = self.pool.get('ir.attachment') - new_att_vals = { - 'name': mail.pem_subject + ' (Email Attachment)', - 'datas': base64.b64encode(result), - 'datas_fname': tools.ustr( - get_value( - cursor, - user, - record_ids[0], - template.file_name, - template, - context - ) or 'Report') + "." + format, - 'description': mail.pem_subject or "No Description", - 'res_model': 'poweremail.mailbox', - 'res_id': mail.id - } - attachment_id = attachment_obj.create(cursor, - user, - new_att_vals, - context) + elif 'lang' not in ctx: + ctx['lang'] = tools.config.get('lang', 'en_US') + attachment_id = [] + if template.report_template: + report_vals = self.create_report(cursor, user, template, record_ids, context=context) + result = report_vals[0] + format = report_vals[1] + + new_att_vals = { + 'name': mail.pem_subject + ' (Email Attachment)', + 'datas': base64.b64encode(result), + 'datas_fname': tools.ustr( + get_value(cursor, user, record_ids[0], template.file_name, template, context=context) or 'Report' + ) + "." + format, + 'description': mail.pem_subject or "No Description", + 'res_model': 'poweremail.mailbox', + 'res_id': mail.id + } + attachment_id.append( + attachment_obj.create(cursor, user, new_att_vals, context=context) + ) + search_params = [ + ('res_model', '=', 'poweremail.templates'), + ('res_id', '=', template.id), + ] + if lang: + search_params += [('datas_fname', 'ilike', '%%.%s.%%' % lang)] + attach_ids = attachment_obj.search(cursor, user, search_params, context=context) + for attach in attachment_obj.browse(cursor, user, attach_ids, context=context): + attachment_vals = { + 'res_model': 'poweremail.mailbox', + 'res_id': mail.id, + 'name': attach.name.replace('.%s' % ctx['lang'], ''), + 'datas_fname': attach.datas_fname.replace('.%s' % ctx['lang'], '') + } + new_id = attachment_obj.copy(cursor, user, attach.id, attachment_vals, context=context) + attachment_id.append(new_id) if attachment_id: - self.pool.get('poweremail.mailbox').write( - cursor, - user, - mail.id, - { - 'pem_attachments_ids':[ - [6, 0, [attachment_id]] - ], - 'mail_type':'multipart/mixed' - }, - context) + mailbox_vals = { + 'pem_attachments_ids': [[6, 0, attachment_id]], + 'mail_type': 'multipart/mixed' + } + mailbox_obj.write(cursor, user, mail.id, mailbox_vals, context=context) return True def get_from_account_id_from_template(self, cursor, uid, template_id, context=None): @@ -881,12 +921,7 @@ def get_from_account_id_from_template(self, cursor, uid, template_id, context=No } return from_account - def _generate_mailbox_item_from_template(self, - cursor, - user, - template, - record_id, - context=None): + def _generate_mailbox_item_from_template(self, cursor, user, template, record_id, context=None): """ Generates an email from the template for record record_id of target object @@ -902,93 +937,47 @@ def _generate_mailbox_item_from_template(self, """ if context is None: context = {} + mailbox_obj = self.pool.get('poweremail.mailbox') + users_obj = self.pool.get('res.users') + from_account = self.get_from_account_id_from_template(cursor, user, template.id, context=context) - lang = get_value(cursor, - user, - record_id, - template.lang, - template, - context) + lang = get_value(cursor, user, record_id, template.lang, template, context=context) if lang: ctx = context.copy() - ctx.update({'lang':lang}) + ctx.update({'lang': lang}) template = self.browse(cursor, user, template.id, context=ctx) mailbox_values = { - 'pem_from': tools.ustr(from_account['name']) + \ - "<" + tools.ustr(from_account['email_id']) + ">", - 'pem_to':get_value(cursor, - user, - record_id, - template.def_to, - template, - context), - 'pem_cc':get_value(cursor, - user, - record_id, - template.def_cc, - template, - context), - 'pem_bcc':get_value(cursor, - user, - record_id, - template.def_bcc, - template, - context), - 'pem_subject':get_value(cursor, - user, - record_id, - template.def_subject, - template, - context), - 'pem_body_text':get_value(cursor, - user, - record_id, - template.def_body_text, - template, - context), - 'pem_body_html':get_value(cursor, - user, - record_id, - template.def_body_html, - template, - context), - 'pem_account_id' :from_account['id'], + 'pem_from': tools.ustr(from_account['name']) + "<" + tools.ustr(from_account['email_id']) + ">", + 'pem_to': get_value(cursor, user, record_id, template.def_to, template, context=context), + 'pem_cc': get_value(cursor, user, record_id, template.def_cc, template, context=context), + 'pem_bcc': get_value(cursor, user, record_id, template.def_bcc, template, context=context), + 'pem_subject': get_value(cursor, user, record_id, template.def_subject, template, context=context), + 'pem_body_text': get_value(cursor, user, record_id, template.def_body_text, template, context=context), + 'pem_body_html': get_value(cursor, user, record_id, template.def_body_html, template, context=context), + 'pem_account_id': from_account['id'], #This is a mandatory field when automatic emails are sent - 'state':'na', - 'folder':'drafts', - 'mail_type':'multipart/alternative', + 'state': 'na', + 'folder': 'drafts', + 'mail_type': 'multipart/alternative', 'priority': template.def_priority } #Use signatures if allowed if template.use_sign: - sign = self.pool.get('res.users').read(cursor, - user, - user, - ['signature'], - context)['signature'] + sign = users_obj.read(cursor, user, user, ['signature'], context=context)['signature'] if sign: if mailbox_values['pem_body_text']: mailbox_values['pem_body_text'] += "\n--\n"+sign if mailbox_values['pem_body_html']: mailbox_values['pem_body_html'] += sign mailbox_values.update(context.get("extra_vals", {})) - mailbox_id = self.pool.get('poweremail.mailbox').create( - cursor, - user, - mailbox_values, - context) + mailbox_id = mailbox_obj.create(cursor, user, mailbox_values, context=context) return mailbox_id def check_outbox(self, cursor, uid, mailbox_id, context=None): return True - def generate_mail(self, - cursor, - user, - template_id, - record_ids, - context=None): + def generate_mail(self, cursor, user, template_id, record_ids, context=None): if context is None: context = {} if not isinstance(record_ids, (list, tuple)): @@ -998,11 +987,11 @@ def generate_mail(self, raise Exception("The requested template could not be loaded") if template.use_filter and template.filter: - filtered_record_ids=[] + filtered_record_ids = [] for record in self.pool.get(template.object_name.model).browse(cursor, user, record_ids, context=context): - if safe_eval(template.filter, {'o':record, 'self':self, 'cr':cursor, 'context':context, 'uid': user}): + if safe_eval(template.filter, {'o': record, 'self': self, 'cr': cursor, 'context': context, 'uid': user}): filtered_record_ids.append(record.id) - record_ids=filtered_record_ids + record_ids = filtered_record_ids report_record_ids = record_ids[:] if template.single_email and len(record_ids) > 1: @@ -1010,48 +999,18 @@ def generate_mail(self, record_ids = record_ids[:1] for record_id in record_ids: - mailbox_id = self._generate_mailbox_item_from_template( - cursor, - user, - template, - record_id, - context) - mail = self.pool.get('poweremail.mailbox').browse( - cursor, - user, - mailbox_id, - context=context - ) - if template.report_template: - if template.single_email and len(report_record_ids) > 1: - # The optional attachment will be generated as a single file for all these records - self._generate_attach_reports( - cursor, - user, - template, - report_record_ids, - mail, - context - ) - else: - self._generate_attach_reports( - cursor, - user, - template, - [record_id], - mail, - context - ) + mailbox_id = self._generate_mailbox_item_from_template(cursor, user, template, record_id, context=context) + mail = self.pool.get('poweremail.mailbox').browse(cursor, user, mailbox_id, context=context) + if template.single_email and len(report_record_ids) > 1: + # The optional attachment will be generated as a single file for all these records + self._generate_attach_reports(cursor, user, template, report_record_ids, mail, context=context) + else: + self._generate_attach_reports(cursor, user, template, [record_id], mail, context=context) # Create a partner event cursor.execute("SELECT state from ir_module_module where state='installed' and name = 'mail_gateway'") mail_gateway = cursor.fetchall() if template.partner_event and mail_gateway: - self._generate_partner_events(cursor, - user, - template, - record_id, - mail, - context) + self._generate_partner_events(cursor, user, template, record_id, mail, context=context) # This should be the last statement in this method. # This prevents attempts by the scheduler to send # Emails before all the work is complete in diff --git a/poweremail_template_view.xml b/poweremail_template_view.xml index cd3c825..9438e30 100644 --- a/poweremail_template_view.xml +++ b/poweremail_template_view.xml @@ -238,15 +238,21 @@ - - - - - - + + + + + + + + + + + + + + + diff --git a/tests/__init__.py b/tests/__init__.py index c531189..129bab0 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,238 +1,2 @@ -# coding=utf-8 -from destral import testing -from destral.transaction import Transaction - - -class TestPoweremailTemplates(testing.OOTestCaseWithCursor): - - def create_account(self, extra_vals=None): - acc_obj = self.openerp.pool.get('poweremail.core_accounts') - cursor = self.cursor - uid = self.uid - - vals = { - 'name': 'Test account', - 'user': self.uid, - 'email_id': 'test@example.com', - 'smtpserver': 'smtp.example.com', - 'smtpport': 587, - 'smtpuname': 'test', - 'smtppass': 'test', - 'company': 'yes' - } - if extra_vals: - vals.update(extra_vals) - - acc_id = acc_obj.create(cursor, uid, vals) - return acc_id - - def create_template(self, extra_vals=None): - - imd_obj = self.openerp.pool.get('ir.model.data') - tmpl_obj = self.openerp.pool.get('poweremail.templates') - cursor = self.cursor - uid = self.uid - acc_id = self.create_account() - - model_partner = imd_obj.get_object_reference( - cursor, uid, 'base', 'model_res_partner' - )[1] - - vals = { - 'name': 'Test template', - 'object_name': model_partner, - 'enforce_from_account': acc_id, - 'template_language': 'mako', - 'def_priority': '2' - } - if extra_vals: - vals.update(extra_vals) - - tmpl_id = tmpl_obj.create(cursor, uid, vals) - return tmpl_id - - def test_creating_email_gets_default_priority(self): - - tmpl_obj = self.openerp.pool.get('poweremail.templates') - mail_obj = self.openerp.pool.get('poweremail.mailbox') - imd_obj = self.openerp.pool.get('ir.model.data') - - cursor = self.cursor - uid = self.uid - partner_id = imd_obj.get_object_reference( - cursor, uid, 'base', 'res_partner_asus' - )[1] - - tmpl_id = self.create_template() - - template = tmpl_obj.browse(cursor, uid, tmpl_id) - - mailbox_id = tmpl_obj._generate_mailbox_item_from_template( - cursor, uid, template, partner_id - ) - - mail = mail_obj.browse(cursor, uid, mailbox_id) - self.assertEqual(mail.priority, '2') - - def test_send_wizards_gets_default_priority_from_template(self): - imd_obj = self.openerp.pool.get('ir.model.data') - send_obj = self.openerp.pool.get('poweremail.send.wizard') - - cursor = self.cursor - uid = self.uid - partner_id = imd_obj.get_object_reference( - cursor, uid, 'base', 'res_partner_asus' - )[1] - - tmpl_id = self.create_template() - - wiz_id = send_obj.create(cursor, uid, {}, context={ - 'active_id': partner_id, - 'active_ids': [partner_id], - 'src_rec_ids': [partner_id], - 'src_model': 'res.partner', - 'template_id': tmpl_id - }) - wiz = send_obj.browse(cursor, uid, wiz_id) - self.assertEqual(wiz.priority, '2') - - -class TestPoweremailMailbox(testing.OOTestCase): - - def create_account(self, cursor, uid, extra_vals=None): - acc_obj = self.openerp.pool.get('poweremail.core_accounts') - - vals = { - 'name': 'Test account', - 'user': uid, - 'email_id': 'test@example.com', - 'smtpserver': 'smtp.example.com', - 'smtpport': 587, - 'smtpuname': 'test', - 'smtppass': 'test', - 'company': 'yes' - } - if extra_vals: - vals.update(extra_vals) - - acc_id = acc_obj.create(cursor, uid, vals) - return acc_id - - def create_template(self, cursor, uid, extra_vals=None): - - imd_obj = self.openerp.pool.get('ir.model.data') - tmpl_obj = self.openerp.pool.get('poweremail.templates') - acc_id = False - if 'enforce_from_account' not in extra_vals: - acc_id = self.create_account(cursor, uid) - - model_partner = imd_obj.get_object_reference( - cursor, uid, 'base', 'model_res_partner' - )[1] - - vals = { - 'name': 'Test template', - 'object_name': model_partner, - 'enforce_from_account': acc_id, - 'template_language': 'mako', - 'def_priority': '2' - } - if extra_vals: - vals.update(extra_vals) - - tmpl_id = tmpl_obj.create(cursor, uid, vals) - return tmpl_id - - def test_poweremail_n_mails_per_batch(self, extra_vals=None): - self.openerp.install_module('base_extended') - - with Transaction().start(self.database) as txn: - cursor = txn.cursor - uid = txn.user - mail_o = self.openerp.pool.get('poweremail.mailbox') - varconf_o = self.openerp.pool.get('res.config') - imd_obj = self.openerp.pool.get('ir.model.data') - tmpl_id = self.create_template(cursor, uid) - tmpl_obj = self.openerp.pool.get('poweremail.templates') - - partner_id = imd_obj.get_object_reference( - cursor, uid, 'base', 'res_partner_asus' - )[1] - template = tmpl_obj.browse(cursor, uid, tmpl_id) - for i in range(3): - mail_id = tmpl_obj._generate_mailbox_item_from_template( - cursor, uid, template, partner_id - ) - mail_wv = {'folder': 'outbox', 'state': 'na'} - mail_o.write(cursor, uid, mail_id, mail_wv) - - varconf_o.set(cursor, uid, 'poweremail_n_mails_per_batch', 1) - mails_per_enviar = mail_o._get_mails_to_send(cursor, uid) - self.assertEqual(len(mails_per_enviar), 1) - mails_per_enviar = mail_o._get_mails_to_send(cursor, uid, context={'limit': 2}) - self.assertEqual(len(mails_per_enviar), 2) - - varconf_o.set(cursor, uid, 'poweremail_n_mails_per_batch', 0) - mails_per_enviar = mail_o._get_mails_to_send(cursor, uid) - self.assertEqual(len(mails_per_enviar), 3) - - def test_poweremail_n_mails_per_batch_per_account(self, extra_vals=None): - self.openerp.install_module('base_extended') - - with Transaction().start(self.database) as txn: - cursor = txn.cursor - uid = txn.user - mail_o = self.openerp.pool.get('poweremail.mailbox') - varconf_o = self.openerp.pool.get('res.config') - imd_obj = self.openerp.pool.get('ir.model.data') - tmpl_obj = self.openerp.pool.get('poweremail.templates') - - acc1_id = self.create_account(cursor, uid, extra_vals={'name': 'acc1', 'email_id': 'test1@example.com'}) - acc2_id = self.create_account(cursor, uid, extra_vals={'name': 'acc2', 'email_id': 'test2@example.com'}) - acc3_id = self.create_account(cursor, uid, extra_vals={'name': 'acc3', 'email_id': 'test3@example.com'}) - - tmpl1_id = self.create_template(cursor, uid, extra_vals={'enforce_from_account': acc1_id, 'name': 'Test template 1'}) - tmpl2_id = self.create_template(cursor, uid, extra_vals={'enforce_from_account': acc2_id, 'name': 'Test template 2'}) - tmpl3_id = self.create_template(cursor, uid, extra_vals={'enforce_from_account': acc3_id, 'name': 'Test template 3'}) - - partner_id = imd_obj.get_object_reference( - cursor, uid, 'base', 'res_partner_asus' - )[1] - mails_per_acc = {'acc1': set(), 'acc2': set(), 'acc3': set()} - for tmpl_id in (tmpl1_id, tmpl2_id, tmpl3_id): - template = tmpl_obj.browse(cursor, uid, tmpl_id) - for i in range(3): - mail_id = tmpl_obj._generate_mailbox_item_from_template( - cursor, uid, template, partner_id - ) - mail_wv = {'folder': 'outbox', 'state': 'na'} - mail_o.write(cursor, uid, mail_id, mail_wv) - mails_per_acc[template.enforce_from_account.name].add(mail_id) - - varconf_o.set( - cursor, uid, 'poweremail_n_mails_per_batch_per_account', - "{'acc1': 1, 'acc2': 2}" - ) - mails_per_enviar = mail_o._get_mails_to_send(cursor, uid) - self.assertEqual(len(mails_per_enviar), 6) # 1 + 2 + 3 - self.assertEqual(len(set(mails_per_enviar) - mails_per_acc['acc1']), 5) - self.assertEqual(len(set(mails_per_enviar) - mails_per_acc['acc2']), 4) - self.assertEqual(len(set(mails_per_enviar) - mails_per_acc['acc3']), 3) - mails_per_enviar = mail_o._get_mails_to_send(cursor, uid, context={'limit': 2}) - self.assertEqual(len(mails_per_enviar), 2) - - varconf_o.set( - cursor, uid, 'poweremail_n_mails_per_batch_per_account', - "{'acc1': 1, 'acc2': 1, 'acc3': 1}" - ) - mails_per_enviar = mail_o._get_mails_to_send(cursor, uid) - self.assertEqual(len(mails_per_enviar), 3) - for acc, mails in mails_per_acc.items(): - self.assertEqual(len(set(mails_per_enviar) - mails), 2) - - varconf_o.set( - cursor, uid, 'poweremail_n_mails_per_batch_per_account', - "{}" - ) - mails_per_enviar = mail_o._get_mails_to_send(cursor, uid) - self.assertEqual(len(mails_per_enviar), 9) +from test_poweremail_mailbox import * +from test_poweremail_templates import * \ No newline at end of file diff --git a/tests/test_poweremail_mailbox.py b/tests/test_poweremail_mailbox.py new file mode 100644 index 0000000..78b32b9 --- /dev/null +++ b/tests/test_poweremail_mailbox.py @@ -0,0 +1,553 @@ +# coding=utf-8 +import base64 +import mock +from destral import testing +from destral.transaction import Transaction + + +class TestPoweremailMailbox(testing.OOTestCase): + + def create_account(self, cursor, uid, extra_vals=None): + acc_obj = self.openerp.pool.get('poweremail.core_accounts') + + vals = { + 'name': 'Test account', + 'user': uid, + 'email_id': 'test@example.com', + 'smtpserver': 'smtp.example.com', + 'smtpport': 587, + 'smtpuname': 'test', + 'smtppass': 'test', + 'company': 'yes' + } + if extra_vals: + vals.update(extra_vals) + + acc_id = acc_obj.create(cursor, uid, vals) + return acc_id + + def create_template(self, cursor, uid, extra_vals=None): + if extra_vals is None: + extra_vals = {} + + imd_obj = self.openerp.pool.get('ir.model.data') + tmpl_obj = self.openerp.pool.get('poweremail.templates') + acc_id = False + if 'enforce_from_account' not in extra_vals: + acc_id = self.create_account(cursor, uid) + + model_partner = imd_obj.get_object_reference( + cursor, uid, 'base', 'model_res_partner' + )[1] + + vals = { + 'name': 'Test template', + 'object_name': model_partner, + 'enforce_from_account': acc_id, + 'template_language': 'mako', + 'def_priority': '2' + } + if extra_vals: + vals.update(extra_vals) + + tmpl_id = tmpl_obj.create(cursor, uid, vals) + return tmpl_id + + def test_poweremail_n_mails_per_batch(self, extra_vals=None): + self.openerp.install_module('base_extended') + + with Transaction().start(self.database) as txn: + cursor = txn.cursor + uid = txn.user + mail_o = self.openerp.pool.get('poweremail.mailbox') + varconf_o = self.openerp.pool.get('res.config') + imd_obj = self.openerp.pool.get('ir.model.data') + tmpl_id = self.create_template(cursor, uid) + tmpl_obj = self.openerp.pool.get('poweremail.templates') + + partner_id = imd_obj.get_object_reference( + cursor, uid, 'base', 'res_partner_asus' + )[1] + template = tmpl_obj.browse(cursor, uid, tmpl_id) + for i in range(3): + mail_id = tmpl_obj._generate_mailbox_item_from_template( + cursor, uid, template, partner_id + ) + mail_wv = {'folder': 'outbox', 'state': 'na'} + mail_o.write(cursor, uid, mail_id, mail_wv) + + varconf_o.set(cursor, uid, 'poweremail_n_mails_per_batch', 1) + mails_per_enviar = mail_o._get_mails_to_send(cursor, uid) + self.assertEqual(len(mails_per_enviar), 1) + mails_per_enviar = mail_o._get_mails_to_send(cursor, uid, context={'limit': 2}) + self.assertEqual(len(mails_per_enviar), 2) + + varconf_o.set(cursor, uid, 'poweremail_n_mails_per_batch', 0) + mails_per_enviar = mail_o._get_mails_to_send(cursor, uid) + self.assertEqual(len(mails_per_enviar), 3) + + def test_poweremail_n_mails_per_batch_per_account(self, extra_vals=None): + if extra_vals is None: + extra_vals = {} + self.openerp.install_module('base_extended') + + with Transaction().start(self.database) as txn: + cursor = txn.cursor + uid = txn.user + mail_o = self.openerp.pool.get('poweremail.mailbox') + varconf_o = self.openerp.pool.get('res.config') + imd_obj = self.openerp.pool.get('ir.model.data') + tmpl_obj = self.openerp.pool.get('poweremail.templates') + + acc1_id = self.create_account(cursor, uid, extra_vals={'name': 'acc1', 'email_id': 'test1@example.com'}) + acc2_id = self.create_account(cursor, uid, extra_vals={'name': 'acc2', 'email_id': 'test2@example.com'}) + acc3_id = self.create_account(cursor, uid, extra_vals={'name': 'acc3', 'email_id': 'test3@example.com'}) + + tmpl1_id = self.create_template(cursor, uid, extra_vals={'enforce_from_account': acc1_id, 'name': 'Test template 1'}) + tmpl2_id = self.create_template(cursor, uid, extra_vals={'enforce_from_account': acc2_id, 'name': 'Test template 2'}) + tmpl3_id = self.create_template(cursor, uid, extra_vals={'enforce_from_account': acc3_id, 'name': 'Test template 3'}) + + partner_id = imd_obj.get_object_reference( + cursor, uid, 'base', 'res_partner_asus' + )[1] + mails_per_acc = {'acc1': set(), 'acc2': set(), 'acc3': set()} + for tmpl_id in (tmpl1_id, tmpl2_id, tmpl3_id): + template = tmpl_obj.browse(cursor, uid, tmpl_id) + for i in range(3): + mail_id = tmpl_obj._generate_mailbox_item_from_template( + cursor, uid, template, partner_id + ) + mail_wv = {'folder': 'outbox', 'state': 'na'} + mail_o.write(cursor, uid, mail_id, mail_wv) + mails_per_acc[template.enforce_from_account.name].add(mail_id) + + varconf_o.set( + cursor, uid, 'poweremail_n_mails_per_batch_per_account', + "{'acc1': 1, 'acc2': 2}" + ) + mails_per_enviar = mail_o._get_mails_to_send(cursor, uid) + self.assertEqual(len(mails_per_enviar), 6) # 1 + 2 + 3 + self.assertEqual(len(set(mails_per_enviar) - mails_per_acc['acc1']), 5) + self.assertEqual(len(set(mails_per_enviar) - mails_per_acc['acc2']), 4) + self.assertEqual(len(set(mails_per_enviar) - mails_per_acc['acc3']), 3) + mails_per_enviar = mail_o._get_mails_to_send(cursor, uid, context={'limit': 2}) + self.assertEqual(len(mails_per_enviar), 2) + + varconf_o.set( + cursor, uid, 'poweremail_n_mails_per_batch_per_account', + "{'acc1': 1, 'acc2': 1, 'acc3': 1}" + ) + mails_per_enviar = mail_o._get_mails_to_send(cursor, uid) + self.assertEqual(len(mails_per_enviar), 3) + for acc, mails in mails_per_acc.items(): + self.assertEqual(len(set(mails_per_enviar) - mails), 2) + + varconf_o.set( + cursor, uid, 'poweremail_n_mails_per_batch_per_account', + "{}" + ) + mails_per_enviar = mail_o._get_mails_to_send(cursor, uid) + self.assertEqual(len(mails_per_enviar), 9) + + def generate_mail_with_attachments_no_report(self): + with Transaction().start(self.database) as txn: + uid = txn.user + cursor = txn.cursor + mailbox_obj = self.openerp.pool.get('poweremail.mailbox') + pm_tmp_obj = self.openerp.pool.get('poweremail.templates') + ir_attachment_obj = self.openerp.pool.get('ir.attachment') + imd_obj = self.openerp.pool.get('ir.model.data') + pw_account_obj = self.openerp.pool.get('poweremail.core_accounts') + + # Agafem un template de prova per posar a l'attachment + template_id = imd_obj.get_object_reference( + cursor, uid, 'poweremail', 'default_template_poweremail' + )[1] + + # Hem de posar 'enforce_from_account' al template perque és required + pw_account_id = pw_account_obj.create(cursor, uid, { + 'name': 'test', + 'user': 1, + 'email_id': 'test@email', + 'smtpserver': 'smtp.gmail.com', + 'smtpport': '587', + 'company': 'no', + 'state': 'approved', + }) + + # Escribim al template el que necessitem + pm_tmp_obj.write(cursor, uid, template_id, {'enforce_from_account': pw_account_id}) + + # Creem un attachment de prova + ir_vals = { + 'name': 'filename_prova', + 'datas': base64.b64encode(b'attachment test content'), + 'datas_fname': 'filename_prova.txt', + 'res_model': 'poweremail.templates', + 'res_id': template_id, + } + attachment_id = ir_attachment_obj.create(cursor, uid, ir_vals) + + # Busquem els attachments que hi ha creats i hauriem de trobar el que acabem de crear + attach_ids = ir_attachment_obj.search(cursor, uid, []) + self.assertEqual(len(attach_ids), 1) + self.assertIn(attachment_id, attach_ids) + + # Cridem el mètode per generar el mail a partir del template que té un attachment. + # Ens hauria de crear un segon attachment al crear el poweremail.mailbox + pm_tmp_obj.generate_mail(cursor, uid, template_id, [template_id]) + + attach_ids = ir_attachment_obj.search(cursor, uid, []) + self.assertEqual(len(attach_ids), 2) + + @mock.patch('poweremail.poweremail_template.poweremail_templates.create_report') + def generate_mail_with_attachments_and_report(self, mock_function): + with Transaction().start(self.database) as txn: + uid = txn.user + cursor = txn.cursor + mailbox_obj = self.openerp.pool.get('poweremail.mailbox') + pm_tmp_obj = self.openerp.pool.get('poweremail.templates') + ir_attachment_obj = self.openerp.pool.get('ir.attachment') + imd_obj = self.openerp.pool.get('ir.model.data') + pw_account_obj = self.openerp.pool.get('poweremail.core_accounts') + + mock_function.return_value = ("Result", "provapdf") + + # Agafem un template de prova per posar a l'attachment + template_id = imd_obj.get_object_reference( + cursor, uid, 'poweremail', 'default_template_poweremail' + )[1] + + # Hem de posar 'enforce_from_account' al template perque és required + pw_account_id = pw_account_obj.create(cursor, uid, { + 'name': 'test', + 'user': 1, + 'email_id': 'test@email', + 'smtpserver': 'smtp.gmail.com', + 'smtpport': '587', + 'company': 'no', + 'state': 'approved', + }) + + # Agafem un report de demo + report_id = imd_obj.get_object_reference( + cursor, uid, 'base', 'report_test' + )[1] + + # Escribim el que necessitem al template + template_vals = { + 'enforce_from_account': pw_account_id, + 'report_template': report_id + } + pm_tmp_obj.write(cursor, uid, template_id, template_vals) + + # Creem un attachment de prova + ir_vals = { + 'name': 'filename_prova', + 'datas': base64.b64encode(b'attachment test content'), + 'datas_fname': 'filename_prova.txt', + 'res_model': 'poweremail.templates', + 'res_id': template_id, + } + attachment_id = ir_attachment_obj.create(cursor, uid, ir_vals) + + # Busquem els attachments que hi ha creats i hauriem de trobar el que acabem de crear + attach_ids = ir_attachment_obj.search(cursor, uid, []) + self.assertEqual(len(attach_ids), 1) + self.assertIn(attachment_id, attach_ids) + + # Cridem el mètode per generar el mail a partir del template que té un attachment i un report. + # Ens hauria de crear un segon attachment al crear el poweremail.mailbox + # I també ens hauria de crear un tercer attachment que és el report + pm_tmp_obj.generate_mail(cursor, uid, template_id, [template_id]) + + attach_ids = ir_attachment_obj.search(cursor, uid, []) + self.assertEqual(len(attach_ids), 3) + + @mock.patch('poweremail.poweremail_template.poweremail_templates.create_report') + def generate_mail_with_report_no_attachments(self, mock_function): + with Transaction().start(self.database) as txn: + uid = txn.user + cursor = txn.cursor + mailbox_obj = self.openerp.pool.get('poweremail.mailbox') + pm_tmp_obj = self.openerp.pool.get('poweremail.templates') + ir_attachment_obj = self.openerp.pool.get('ir.attachment') + imd_obj = self.openerp.pool.get('ir.model.data') + pw_account_obj = self.openerp.pool.get('poweremail.core_accounts') + + mock_function.return_value = ("Result", "provapdf") + + # Agafem un template de prova per posar a l'attachment + template_id = imd_obj.get_object_reference( + cursor, uid, 'poweremail', 'default_template_poweremail' + )[1] + + # Hem de posar 'enforce_from_account' al template perque és required + pw_account_id = pw_account_obj.create(cursor, uid, { + 'name': 'test', + 'user': 1, + 'email_id': 'test@email', + 'smtpserver': 'smtp.gmail.com', + 'smtpport': '587', + 'company': 'no', + 'state': 'approved', + }) + + # Agafem un report de demo + report_id = imd_obj.get_object_reference( + cursor, uid, 'base', 'report_test' + )[1] + + # Escribim el que necessitem al template + template_vals = { + 'enforce_from_account': pw_account_id, + 'report_template': report_id + } + pm_tmp_obj.write(cursor, uid, template_id, template_vals) + + # Busquem els attachments que hi ha creats i no n'hi hauria d'haver cap + attach_ids = ir_attachment_obj.search(cursor, uid, []) + self.assertEqual(len(attach_ids), 0) + + # Cridem el mètode per generar el mail a partir del template que té no té attachments però té un report. + # Ens hauria de crear un attachment que és el report + pm_tmp_obj.generate_mail(cursor, uid, template_id, [template_id]) + + attach_ids = ir_attachment_obj.search(cursor, uid, []) + self.assertEqual(len(attach_ids), 1) + + @mock.patch('poweremail.poweremail_template.poweremail_templates.create_report') + def generate_mail_with_attachments_and_report_multi_users(self, mock_function): + with Transaction().start(self.database) as txn: + uid = txn.user + cursor = txn.cursor + mailbox_obj = self.openerp.pool.get('poweremail.mailbox') + pm_tmp_obj = self.openerp.pool.get('poweremail.templates') + ir_attachment_obj = self.openerp.pool.get('ir.attachment') + imd_obj = self.openerp.pool.get('ir.model.data') + pw_account_obj = self.openerp.pool.get('poweremail.core_accounts') + + mock_function.return_value = ("Result", "provapdf") + + # Agafem un template de prova per posar a l'attachment + template_id = imd_obj.get_object_reference( + cursor, uid, 'poweremail', 'default_template_poweremail' + )[1] + + # Hem de posar 'enforce_from_account' al template perque és required + pw_account_id = pw_account_obj.create(cursor, uid, { + 'name': 'test', + 'user': 1, + 'email_id': 'test@email', + 'smtpserver': 'smtp.gmail.com', + 'smtpport': '587', + 'company': 'no', + 'state': 'approved', + }) + + # Agafem un report de demo + report_id = imd_obj.get_object_reference( + cursor, uid, 'base', 'report_test' + )[1] + + # Escribim el que necessitem als templates + template_vals = { + 'enforce_from_account': pw_account_id, + 'report_template': report_id + } + pm_tmp_obj.write(cursor, uid, template_id, template_vals) + + + # Creem dos attachments de prova + ir_vals = { + 'name': 'filename_prova_1', + 'datas': base64.b64encode(b'attachment test content'), + 'datas_fname': 'filename_prova.txt', + 'res_model': 'poweremail.templates', + 'res_id': template_id, + } + attachment_id = ir_attachment_obj.create(cursor, uid, ir_vals) + + ir_vals_2 = { + 'name': 'filename_prova_2', + 'datas': base64.b64encode(b'attachment test content'), + 'datas_fname': 'filename_prova.txt', + 'res_model': 'poweremail.templates', + 'res_id': template_id, + } + attachment_id_2 = ir_attachment_obj.create(cursor, uid, ir_vals_2) + + # Busquem els attachments que hi ha creats i hauriem de trobar els que acabem de crear + attach_ids = ir_attachment_obj.search(cursor, uid, []) + self.assertEqual(len(attach_ids), 2) + self.assertIn(attachment_id, attach_ids) + self.assertIn(attachment_id_2, attach_ids) + + # Cridem el mètode per generar el mail a partir dels templates que tenen un attachment i un report. + # Ens hauria de crear un segon attachment al crear el poweremail.mailbox + # I també ens hauria de crear un tercer attachment que és el report + pm_tmp_obj.generate_mail(cursor, uid, template_id, [template_id]) + + attach_ids = ir_attachment_obj.search(cursor, uid, []) + self.assertEqual(len(attach_ids), 5) + + + + + + @mock.patch('poweremail.poweremail_send_wizard.poweremail_send_wizard.add_template_attachments') + @mock.patch('poweremail.poweremail_send_wizard.poweremail_send_wizard.add_attachment_documents') + @mock.patch('poweremail.poweremail_send_wizard.poweremail_send_wizard.process_extra_attachment_in_template') + @mock.patch('poweremail.poweremail_send_wizard.poweremail_send_wizard.create_report_attachment') + @mock.patch('poweremail.poweremail_send_wizard.poweremail_send_wizard.create_mail') + @mock.patch('poweremail.poweremail_send_wizard.poweremail_send_wizard.check_lang') + def test_save_to_mailbox(self, mock_function, mock_function_2, mock_function_3, mock_function_4, mock_function_5, mock_function_6): + self.openerp.install_module('giscedata_facturacio') + with Transaction().start(self.database) as txn: + uid = txn.user + cursor = txn.cursor + mailbox_obj = self.openerp.pool.get('poweremail.mailbox') + pm_tmp_obj = self.openerp.pool.get('poweremail.templates') + ir_attachment_obj = self.openerp.pool.get('ir.attachment') + imd_obj = self.openerp.pool.get('ir.model.data') + pw_account_obj = self.openerp.pool.get('poweremail.core_accounts') + send_wizard_obj = self.openerp.pool.get('poweremail.send.wizard') + + fact_id = imd_obj.get_object_reference(cursor, uid, 'giscedata_facturacio', 'factura_0006')[1] + # Agafem un template de prova per posar a l'attachment + template_id = imd_obj.get_object_reference( + cursor, uid, 'poweremail', 'default_template_poweremail' + )[1] + + # Creem un wizard 'poweremail_send_wizard' + body_text = "" \ + "" \ + "" \ + "" \ + "Querid@ Agrolait,
" \ + "
" \ + "El importe de su factura de electricidad que comprende el periodo del 2021/06/01 al 2021/06/30 es de 14.54€.
" \ + "
" \ + "Por favor, encuentre adjunta la factura en formato PDF.
" \ + "
" \ + "
" \ + "Atentamente,
" \ + "
" \ + "Tiny sprl" \ + "" \ + "" + + wizard_vals = { + 'rel_model_ref': fact_id, + 'requested': 1, + 'from': 1, + 'attachment_ids': [], + 'body_text': body_text, + 'cc' : False, + 'body_html': False, + 'bcc': False, + 'priority': '1', + 'to': 'aorellana@gisce.net', + 'state': 'single', + 'ref_template': template_id, + 'single_email': 0, + 'rel_model': 301, + 'signature': 0, + 'report': False, + 'subject': 'Factura electricidad False', + 'generated': False, + 'full_success': False, + } + + # Creem un mailbox + wizard_id = send_wizard_obj.create(cursor, uid, wizard_vals) + + # Hem de posar 'enforce_from_account' al template perque és required + pw_account_id = pw_account_obj.create(cursor, uid, { + 'name': 'test', + 'user': 1, + 'email_id': 'test@email', + 'smtpserver': 'smtp.gmail.com', + 'smtpport': '587', + 'company': 'no', + 'state': 'approved', + }) + + # Agafem un report de demo + report_id = imd_obj.get_object_reference( + cursor, uid, 'base', 'report_test' + )[1] + + # Escribim el que necessitem als templates + template_vals = { + 'enforce_from_account': pw_account_id, + 'report_template': report_id + } + pm_tmp_obj.write(cursor, uid, template_id, template_vals) + + # Creem un attachments de prova + ir_vals = { + 'name': 'filename_prova_1', + 'datas': base64.b64encode(b'attachment test content'), + 'datas_fname': 'filename_prova.txt', + 'res_model': 'poweremail.templates', + 'res_id': template_id, + } + attachment_id = ir_attachment_obj.create(cursor, uid, ir_vals) + + mail_vals = { + 'pem_from': 'test@email', + 'pem_to': 'aorellana@gisce.net', + 'pem_cc': False, + 'pem_bcc': False, + 'pem_subject': 'Factura electricidad False', + 'pem_body_text': body_text, + 'pem_body_html': False, + 'pem_account_id': 1, + 'priority': '1', + 'state': 'na', + 'mail_type': 'multipart/alternative' + } + + mail_id = mailbox_obj.create(cursor, uid, mail_vals) + + attach_vals = { + 'name': 'Factura electricidad False(adjunto correo electrónico)', + 'datas': "datas_test", + 'datas_fname': "False.pdf", + 'description': body_text, + 'res_model': 'poweremail.mailbox', + 'res_id': mail_id + } + attachment_report_id = ir_attachment_obj.create(cursor, uid, attach_vals) + + mock_function.return_value = "es_ES" + mock_function_2.return_value = mail_id + mock_function_3.return_value = attachment_report_id + mock_function_4.return_value = [] + mock_function_5.return_value = [] + mock_function_6.return_value = [attachment_id] + + + + context = {} + context['template_id'] = template_id + context['lang'] = False + context['src_rec_id'] = fact_id + context['tz'] = False + context['src_rec_ids'] = [fact_id] + context['active_ids'] = [fact_id] + context['type'] = 'out_invoice' + context['template_id'] = template_id + context['active_id'] = fact_id + + mail_ids = send_wizard_obj.save_to_mailbox(cursor, uid, [wizard_id], context=context) + mail_created_vals = mailbox_obj.read(cursor, uid, mail_ids[0], []) + self.assertEqual(len(mail_created_vals['pem_attachments_ids']), 2) + self.assertIn(attachment_report_id, mail_created_vals['pem_attachments_ids']) + self.assertIn(attachment_id, mail_created_vals['pem_attachments_ids']) + + + + + diff --git a/tests/test_poweremail_templates.py b/tests/test_poweremail_templates.py new file mode 100644 index 0000000..dc1b2f0 --- /dev/null +++ b/tests/test_poweremail_templates.py @@ -0,0 +1,99 @@ +# coding=utf-8 +import base64 +import mock +from destral import testing +from destral.transaction import Transaction + + +class TestPoweremailTemplates(testing.OOTestCaseWithCursor): + + def create_account(self, extra_vals=None): + acc_obj = self.openerp.pool.get('poweremail.core_accounts') + cursor = self.cursor + uid = self.uid + + vals = { + 'name': 'Test account', + 'user': self.uid, + 'email_id': 'test@example.com', + 'smtpserver': 'smtp.example.com', + 'smtpport': 587, + 'smtpuname': 'test', + 'smtppass': 'test', + 'company': 'yes' + } + if extra_vals: + vals.update(extra_vals) + + acc_id = acc_obj.create(cursor, uid, vals) + return acc_id + + def create_template(self, extra_vals=None): + + imd_obj = self.openerp.pool.get('ir.model.data') + tmpl_obj = self.openerp.pool.get('poweremail.templates') + cursor = self.cursor + uid = self.uid + acc_id = self.create_account() + + model_partner = imd_obj.get_object_reference( + cursor, uid, 'base', 'model_res_partner' + )[1] + + vals = { + 'name': 'Test template', + 'object_name': model_partner, + 'enforce_from_account': acc_id, + 'template_language': 'mako', + 'def_priority': '2' + } + if extra_vals: + vals.update(extra_vals) + + tmpl_id = tmpl_obj.create(cursor, uid, vals) + return tmpl_id + + def test_creating_email_gets_default_priority(self): + + tmpl_obj = self.openerp.pool.get('poweremail.templates') + mail_obj = self.openerp.pool.get('poweremail.mailbox') + imd_obj = self.openerp.pool.get('ir.model.data') + + cursor = self.cursor + uid = self.uid + partner_id = imd_obj.get_object_reference( + cursor, uid, 'base', 'res_partner_asus' + )[1] + + tmpl_id = self.create_template() + + template = tmpl_obj.browse(cursor, uid, tmpl_id) + + mailbox_id = tmpl_obj._generate_mailbox_item_from_template( + cursor, uid, template, partner_id + ) + + mail = mail_obj.browse(cursor, uid, mailbox_id) + self.assertEqual(mail.priority, '2') + + def test_send_wizards_gets_default_priority_from_template(self): + imd_obj = self.openerp.pool.get('ir.model.data') + send_obj = self.openerp.pool.get('poweremail.send.wizard') + + cursor = self.cursor + uid = self.uid + partner_id = imd_obj.get_object_reference( + cursor, uid, 'base', 'res_partner_asus' + )[1] + + tmpl_id = self.create_template() + + wiz_id = send_obj.create(cursor, uid, {}, context={ + 'active_id': partner_id, + 'active_ids': [partner_id], + 'src_rec_ids': [partner_id], + 'src_model': 'res.partner', + 'template_id': tmpl_id + }) + wiz = send_obj.browse(cursor, uid, wiz_id) + self.assertEqual(wiz.priority, '2') \ No newline at end of file