def cron_account_analytic_account(self, cr, uid, context=None): domain = [ ('name', 'not ilike', 'maintenance'), ('partner_id', '!=', False), ('user_id', '!=', False), ('user_id.email', '!=', False), ('state', 'in', ('draft', 'open')), '|', ('date', '<', time.strftime('%Y-%m-%d')), ('date', '=', False), ] account_ids = self.search(cr, uid, domain, context=context, order='name asc') accounts = self.browse(cr, uid, account_ids, context=context) users = dict() for account in accounts: users.setdefault(account.user_id, dict()).setdefault(account.partner_id, []).append(account) account.write({'state' : 'pending'}, context=context) for user, data in users.iteritems(): subject = '[OPENERP] Reporting: Analytic Accounts' body = Template(MAKO_TEMPLATE).render_unicode(user=user, partners=data) tools.email_send('*****@*****.**', [user.email, ], subject, body) return True
def send_new_login_form(self, contact_ids, template_id, force_existing, email_from, email_to=''): res_sended = [] res_no_email = [] res_existing = [] # template_obj = self.env['email.template'] # templates = template_obj.browse(cr,uid,[template_id]) if template_id: template = template_id tags = re.compile('{PERSO .*?}', re.IGNORECASE) # contact_obj = self.pool.get('res.partner.contact') # contacts = contact_obj.browse(cr,uid,contact_ids) for contact in self.browse(contact_ids): if contact.premium_login and contact.premium_mp and not force_existing: res_existing.append(contact.id) else: if not email_to: # search the email_address for the sending : if perso, select first, else select first job email if contact.email: email_premium = contact.email else: email_premium = '' if contact.other_contact_ids: job_emails = [] for job in contact.other_contact_ids: if job.email: job_emails.append({ 'sequence': job.sequence_contact, 'email': job.email }) if job_emails: job_emails = sorted( job_emails, key=lambda k: k['sequence']) email_premium = job_emails[0]['email'] else: email_premium = email_to.strip() # if email address for sending, compose texts if email_premium: full_texts = personalize_texts( contact, tags, [template.subject, template.body_html]) # sending of the email tools.email_send(email_from, [ email_premium, ], full_texts[0], full_texts[1]) res_sended.append(email_premium) else: res_no_email.append(contact.id) return (res_sended, res_no_email, res_existing)
def notice_by_email(self, cr, uid, ids, context=None): mail_to='' mUsr = self.pool.get("res.users") for leave in self.read(cr, uid, ids, ['designer_id','name'], context=context): user = mUsr.browse(cr, uid, leave['designer_id']) mail_to=user.email mail_subject=u"Giao mẫu thiết kế" mail_from='*****@*****.**' mail_body=u'THÔNG BÁO </br> Bạn nhận được yêu cầu thiết kế cho mẫu: ' tools.email_send(mail_from, mail_to, mail_subject, mail_body) return True
def read_xml_file(self, local_filename, invoice): parser = parse(local_filename) vals = {} file_data = open(local_filename, "rb").read() vals.update({'name': invoice.id, 'xml_content': file_data}) for tags in parser.getElementsByTagName("esito"): for node in tags.getElementsByTagName("timestamp"): for value in node.childNodes: date = self.convert_timestamp(value.data) vals.update({'date': date}) for node in tags.getElementsByTagName("stato"): for value in node.childNodes: vals.update({'status_code': value.data}) for node in tags.getElementsByTagName("msgErrore"): for value in node.childNodes: vals.update({'status_desc': value.data}) for node in tags.getElementsByTagName("nomeFileSdi"): for value in node.childNodes: note = "Nome file firmato: " + value.data vals.update({'note': note}) invoice.sdi_file_name = value.data for node in tags.getElementsByTagName("codStato"): for value in node.childNodes: note = "Codice SDI: " + value.data vals.update({'note': note}) for tags in parser.getElementsByTagName('DataOraRicezione'): for node in tags.childNodes: vals.update({'date': node.data[:19].replace('T', ' ')}) for tags in parser.getElementsByTagName('ListaErrori'): errori = "" for node in tags.getElementsByTagName('Errore'): descrizione = 'N/A' if node.getElementsByTagName('Descrizione'): descrizione = node.getElementsByTagName( 'Descrizione')[0].firstChild.data if node.getElementsByTagName('Codice'): codice = node.getElementsByTagName( 'Codice')[0].firstChild.data errori = '%s: %s\n%s' % (codice, descrizione, errori) if errori: vals.update({'status_desc': errori, 'status_code': 'ERRORE!'}) if 'date' not in vals: vals.update({'date': datetime.now().strftime('%Y-%m-%d')}) tools.email_send( invoice.company_id.email, [invoice.company_id.email], 'Controllo Fatture Elettroniche', 'Fattura: %s - Messaggio %s' % (invoice.internal_number, vals.get('status_desc', '')), subtype='plain') return vals
def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None): partners = self.browse(cr, uid, ids) for partner in partners: if partner.email: tools.email_send(email_from, [partner.email], subject, body, on_error) return True
def button_send_scrum_email(self, cr, uid, ids, context=None): if context is None: context = {} active_id = context.get('active_id', False) scrum_meeting_pool = self.pool.get('project.scrum.meeting') user_pool = self.pool.get('res.users') meeting = scrum_meeting_pool.browse(cr, uid, active_id, context=context) # wizard data data_id = ids and ids[0] or False if not data_id or not active_id: return False data = self.browse(cr, uid, data_id, context=context) email_from = tools.config.get('email_from', False) user = user_pool.browse(cr, uid, uid, context=context) #BUG in v7 address_id does not exit, today its alias_id but we don't find address in the db user_email = email_from or user.alias_id.email body = "%s\n" % (data.message) body += "\n%s\n" % _('Tasks since yesterday') body += "_______________________\n" body += "\n%s\n" % (meeting.question_yesterday or _('None')) body += "\n%s\n" % _("Task for Today") body += "_______________________ \n" body += "\n%s\n" % (meeting.question_today or _('None')) body += "\n%s\n" % _('Blocking points encountered:') body += "_______________________ \n" body += "\n%s\n" % (meeting.question_blocks or _('None')) body += "\n%s\n%s" % (_('Thank you,'), user.name) if user.signature: body += "\n%s" % (user.signature) if data.scrum_master_email == data.product_owner_email: data.product_owner_email = False if data.scrum_master_email: tools.email_send(user_email, [data.scrum_master_email], data.subject, body, reply_to=user_email) if data.product_owner_email: tools.email_send(user_email, [data.product_owner_email], data.subject, body, reply_to=user_email) return {'type': 'ir.actions.act_window_close'}
def mass_mail_send(self): nbr = 0 partner_ids = self.env.context.get('active_ids', []) if partner_ids: partners = self.env['res.partner'].browse(partner_ids) for partner in partners: for adr in partner.child_ids: if adr.email: name = adr.name or partner.name to = '%s <%s>' % (name, adr.email) # TODO: add some tests to check for invalid email addresses # CHECKME: maybe we should use res.partner/email_send res = tools.email_send(self.email_from, [to], self.subject, self.text, subtype='html') nbr += 1 # pooler.get_pool(cr.dbname).get('res.partner.event').create(cr, uid, # TODO: Need to complete # {'name': 'Email sent through mass mailing', # 'partner_id': partner.id, # 'description': data['form']['text'], }) ctx = self.env.context.copy() ctx.update({'nbr': nbr}) if self.event: return self.open_partners() return self.nbr_mail()
def email_send(self, cr, uid, ids, email, context=None): email_from = tools.config.get('email_from', False) meeting_id = self.browse(cr, uid, ids, context=context)[0] user = self.pool.get('res.users').browse(cr, uid, uid, context=context) user_email = email_from or user.address_id.email or email_from body = _( 'Hello ' ) + meeting_id.sprint_id.scrum_master_id.name + ",\n" + " \n" + _( 'I am sending you Daily Meeting Details of date') + ' %s ' % ( meeting_id.date) + _( 'for the Sprint') + ' %s\n' % (meeting_id.sprint_id.name) body += "\n" + _( '*Tasks since yesterday:') + '\n_______________________%s' % ( meeting_id.question_yesterday) + '\n' + _( "*Task for Today:") + '\n_______________________ %s\n' % ( meeting_id.question_today) + '\n' + _( '*Blocks encountered:' ) + '\n_______________________ %s' % ( meeting_id.question_blocks or _('No Blocks')) body += "\n\n" + _('Thank you') + ",\n" + user.name sub_name = meeting_id.name or _( 'Scrum Meeting of %s') % meeting_id.date flag = tools.email_send(user_email, [email], sub_name, body, reply_to=None, openobject_id=str(meeting_id.id)) if not flag: return False return True
def send_data(self): text = u'''Suite à votre demande, voici votre login et votre mot de passe pour vous connecter sur le site de la CCI Connect : www.cciconnect.be. Login : %s Mot de passe : %s %s Bienvenue.''' str_to = '*****@*****.**' str_from = '' partner_id = self.env.context.get('active_id', False) if partner_id: partner = self.env['res.partner'].browse(partner_id) str_from = self.from_email or '*****@*****.**' # # the field is required, this not usefull str_to = partner.email or str_to # TODO check email address from if str_to and str_from: if partner.login_name and not partner.login_name in [ 'jamais', 'autrezone', 'double_email' ]: text = text % (partner.login_name, partner.password, tools.ustr(self.perso_message or '')) text = tools.ustr(text) res = tools.email_send(str_from, [str_to], 'CCIConnect login et mot de passe', text) if res: res_message = "The login-password has been resend to the email address '%s'" % str_to else: res_message = "Error: Mail not sent, Contact '%s %s' does not have a valid address mail : '%s' or the mail cannot be send" % ( partner.name, partner.first_name, str_to) else: res_message = "Error: Contact '%s %s' has no valid login_name : '%s'" % ( partner.name, partner.first_name, partner.login_name) view = self.env.ref('cci_base_contact.view_send_website_message_form') ctx = self.env.context.copy() ctx.update({'message': res_message}) return { 'name': _('Result'), 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'send.website.message', 'views': [(view.id, 'form')], 'view_id': view.id, 'target': 'new', 'context': ctx, }
def send_new_login_form(self,contact_ids,template_id,force_existing,email_from,email_to=''): res_sended = [] res_no_email = [] res_existing = [] # template_obj = self.env['email.template'] # templates = template_obj.browse(cr,uid,[template_id]) if template_id: template = template_id tags = re.compile('{PERSO .*?}',re.IGNORECASE) # contact_obj = self.pool.get('res.partner.contact') # contacts = contact_obj.browse(cr,uid,contact_ids) for contact in self.browse(contact_ids): if contact.premium_login and contact.premium_mp and not force_existing: res_existing.append(contact.id) else: if not email_to: # search the email_address for the sending : if perso, select first, else select first job email if contact.email: email_premium = contact.email else: email_premium = '' if contact.other_contact_ids: job_emails = [] for job in contact.other_contact_ids: if job.email: job_emails.append({'sequence':job.sequence_contact,'email':job.email}) if job_emails: job_emails = sorted(job_emails, key=lambda k: k['sequence']) email_premium = job_emails[0]['email'] else: email_premium = email_to.strip() # if email address for sending, compose texts if email_premium: full_texts = personalize_texts(contact,tags,[template.subject,template.body_html]) # sending of the email tools.email_send(email_from, [email_premium,], full_texts[0], full_texts[1]) res_sended.append(email_premium) else: res_no_email.append(contact.id) return (res_sended,res_no_email,res_existing)
def email_send(self, cr, uid, ids, email, context=None): email_from = tools.config.get('email_from', False) meeting_id = self.browse(cr, uid, ids, context=context)[0] user = self.pool.get('res.users').browse(cr, uid, uid, context=context) user_email = email_from or user.address_id.email or email_from body = _('Hello ') + meeting_id.sprint_id.scrum_master_id.name + ",\n" + " \n" +_('I am sending you Daily Meeting Details of date')+ ' %s ' % (meeting_id.date)+ _('for the Sprint')+ ' %s\n' % (meeting_id.sprint_id.name) body += "\n"+ _('*Tasks since yesterday:')+ '\n_______________________%s' % (meeting_id.question_yesterday) + '\n' +_("*Task for Today:")+ '\n_______________________ %s\n' % (meeting_id.question_today )+ '\n' +_('*Blocks encountered:') +'\n_______________________ %s' % (meeting_id.question_blocks or _('No Blocks')) body += "\n\n"+_('Thank you')+",\n"+ user.name sub_name = meeting_id.name or _('Scrum Meeting of %s') % meeting_id.date flag = tools.email_send(user_email , [email], sub_name, body, reply_to=None, openobject_id=str(meeting_id.id)) if not flag: return False return True
def button_send_scrum_email(self, cr, uid, ids, context=None): if context is None: context = {} active_id = context.get('active_id', False) scrum_meeting_pool = self.pool.get('project.scrum.meeting') user_pool = self.pool.get('res.users') meeting = scrum_meeting_pool.browse(cr, uid, active_id, context=context) # wizard data data_id = ids and ids[0] or False if not data_id or not active_id: return False data = self.browse(cr, uid, data_id, context=context) email_from = tools.config.get('email_from', False) user = user_pool.browse(cr, uid, uid, context=context) #BUG in v7 address_id does not exit, today its alias_id but we don't find address in the db user_email = email_from or user.alias_id.email body = "%s\n" %(data.message) body += "\n%s\n" %_('Tasks since yesterday') body += "_______________________\n" body += "\n%s\n" %(meeting.question_yesterday or _('None')) body += "\n%s\n" %_("Task for Today") body += "_______________________ \n" body += "\n%s\n" %(meeting.question_today or _('None')) body += "\n%s\n" % _('Blocking points encountered:') body += "_______________________ \n" body += "\n%s\n" %(meeting.question_blocks or _('None')) body += "\n%s\n%s" %(_('Thank you,'), user.name) if user.signature: body += "\n%s" %(user.signature) if data.scrum_master_email == data.product_owner_email: data.product_owner_email = False if data.scrum_master_email: tools.email_send(user_email, [data.scrum_master_email], data.subject, body, reply_to=user_email) if data.product_owner_email: tools.email_send(user_email, [data.product_owner_email], data.subject, body, reply_to=user_email) return {'type': 'ir.actions.act_window_close'}
def cron_account_analytic_account(self, cr, uid, context=None): domain = [ ('name', 'not ilike', 'maintenance'), ('partner_id', '!=', False), ('user_id', '!=', False), ('user_id.email', '!=', False), ('state', 'in', ('draft', 'open')), '|', ('date', '<', time.strftime('%Y-%m-%d')), ('date', '=', False), ] account_ids = self.search(cr, uid, domain, context=context, order='name asc') accounts = self.browse(cr, uid, account_ids, context=context) users = dict() for account in accounts: users.setdefault(account.user_id, dict()).setdefault(account.partner_id, []).append(account) account.write({'state': 'pending'}, context=context) for user, data in users.iteritems(): subject = '[OPENERP] Reporting: Analytic Accounts' body = Template(MAKO_TEMPLATE).render_unicode(user=user, partners=data) tools.email_send('*****@*****.**', [ user.email, ], subject, body) return True
def run(self, cr, uid): """ find the reminder recipients and send them an email """ #get all companies companies = self.pool.get('res.company').browse(cr, uid, self.pool.get('res.company').search(cr, uid, [])) #for each company, get all recipients recipients = [] for c in companies: recipients += self.get_recipients(cr, uid, {}, c) #get the message to send message_id = self.get_message_id(cr, uid, {}) message_data = self.browse(cr, uid, message_id) #send them email if they have an email defined emails = [] for r in recipients: if r.work_email: emails.append(r.work_email) if emails : tools.email_send(message_data.reply_to, [], message_data.subject, message_data.message, email_bcc=emails)
def send_data(self): text = u'''Suite à votre demande, voici votre login et votre mot de passe pour vous connecter sur le site de la CCI Connect : www.cciconnect.be. Login : %s Mot de passe : %s %s Bienvenue.''' str_to = '*****@*****.**' str_from = '' partner_id = self.env.context.get('active_id', False) if partner_id: partner = self.env['res.partner'].browse(partner_id) str_from = self.from_email or '*****@*****.**' # # the field is required, this not usefull str_to = partner.email or str_to # TODO check email address from if str_to and str_from: if partner.login_name and not partner.login_name in ['jamais', 'autrezone', 'double_email']: text = text % (partner.login_name, partner.password, tools.ustr(self.perso_message or '')) text = tools.ustr(text) res = tools.email_send(str_from, [str_to], 'CCIConnect login et mot de passe', text) if res: res_message = "The login-password has been resend to the email address '%s'" % str_to else: res_message = "Error: Mail not sent, Contact '%s %s' does not have a valid address mail : '%s' or the mail cannot be send" % (partner.name, partner.first_name, str_to) else: res_message = "Error: Contact '%s %s' has no valid login_name : '%s'" % (partner.name, partner.first_name, partner.login_name) view = self.env.ref('cci_base_contact.view_send_website_message_form') ctx = self.env.context.copy() ctx.update({'message': res_message}) return { 'name': _('Result'), 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'send.website.message', 'views': [(view.id, 'form')], 'view_id': view.id, 'target': 'new', 'context': ctx, }
def send_onchange_user_id(self, cr, uid, ids, user_id): user_obj=self.pool.get('res.users') user_br = user_obj.browse(cr,uid,[user_id]) for usr in user_br: task_br = self.browse(cr,uid,ids) for t in task_br: project = t.project_id subject = _("Task '%s' has been assigned to you") % t.name if usr.id and usr.address_id and usr.address_id.email: to_adr = usr.address_id.email signature = usr.signature else: raise osv.except_osv(_('Error'), _("Couldn't send mail because your email address is not configured!")) from_adr = tools.config.get('email_from', False) or usr.address_id.email task_name = u'Task name: %s' %(tools.ustr(t.name)) project_code = u'Project code: %s' %(tools.ustr(t.project_complete_wbs_name)) task_id = u'Task id: %s' %(tools.ustr(t.id)) vals = [task_name, project_code, task_id] header = u'\n'.join(vals) footer = '' body = u'%s\n%s\n%s\n\n-- \n%s' % (header, t.description, footer, signature) mail_id = tools.email_send(from_adr, to_adr, subject, tools.ustr(body), email_bcc=[from_adr]) if not mail_id: raise osv.except_osv(_('Error'), _("Couldn't send mail! Check the email ids and smtp configuration settings")) msg_dict = {'new': 'Send', 'reply': 'Reply', 'forward': 'Forward'} self.history(cr, uid,[t], _(msg_dict['new']), history=True,email=to_adr, details=body,subject=subject, email_from=from_adr, message_id=None, references=None, attach=None) return {}
def _send_by_email(self, cr, uid, export_file, localdict): email_to = _render_unicode(export_file.email_to, localdict) email_subject = _render_unicode(export_file.email_subject, localdict) email_body = _render_unicode(export_file.email_body, localdict) email_cc = _render_unicode(export_file.email_cc, localdict) attachments = [] context = localdict.get('localcontext', {}) export = self.pool.get('ir.model.export').browse( cr, uid, context.get('attach_export_id', 0), context) if export_file.email_attach_export_file: attachments.append((localdict['filename'], localdict['file'])) if export_file.exception_logging == 'file' and export_file.email_attach_exceptions_file: attachments.append( (export.exceptions_filename, export.exceptions_file)) return tools.email_send(False, email_to, email_subject, email_body, email_cc, attachments=attachments, cr=cr, uid=uid)
def count_premium(self,max_changed=2000): # cronline_id = self.pool.get('cci_logs.cron_line')._start(cr,uid,'CountPremium') final_result = True errors = [] # Before checking the count of premiums for partners, checks for validity of premium contact : today, we keep only premium linked to a at least one partner in 5... zip code non-members contact_obj = self.env['res.partner'] contact_ids = contact_obj.search(['|',('premium_begin','>','2000-01-01'),('premium_special','=','no')]) losts = [] recups = [] if contact_ids: contacts = contact_ids #contact_obj.browse(cr,uid,contact_ids) for contact in contacts: # calculate the good state if contact.premium_special == 'yes': new_special = 'yes' else: new_special = 'no' if contact.other_contact_ids: for job in contact.other_contact_ids: if job.address_id and job.address_id.parent_id and job.address_id.zip_id: if job.address_id.zip_id.name[0:1] == '5' and ( job.address_id.parent_id.membership_state not in ['free','invoiced','paid'] ) and job.address_id.partner_id.state_id.id == 1: new_special = 'normal' if new_special != contact.premium_special: # modify the current state and save it to send as email at the end of the control contact.write({'premium_special':new_special}) if new_special == 'no': losts.append([str(contact.id),contact.name,contact.first_name or '']) else: recups.append([str(contact.id),contact.name,contact.first_name or '']) if losts or recups: # send mail to premium supervisors # parameter_obj = self.pool.get('cci_parameters.cci_value') parameter_obj = self.env['ir.config_parameter'] param_values = parameter_obj.search([('key','=','SupervisorsPremiumEmail')])[0].value if param_values: email_text = u"""<p>Certains premiums ont été désactivés ou certains ont été réactivés. En voici la liste :</p> <p>Désactivés :<br/><ul><li> %s </li></ul></p> <p>Réactivés :<br/><ul><li> %s </li></ul></p> """ % (losts and '</li><li>'.join(x[1]+' '+x[2]+' ['+x[0]+']' for x in losts) or '--Aucun--', recups and '</li><li>'.join(x[1]+' '+x[2]+' ['+x[0]+']' for x in recups) or '--Aucun--') tools.email_send('*****@*****.**', param_values, u'Changement dans les Premiums', email_text, subtype='html') # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,'\nChanged Contacts :\n\nPremium Losts : \n- %s\n\nRecovered Premium : \n- %s' % ('\n- '.join(x[1]+' '+x[2]+' ['+x[0]+']' for x in losts), # '\n- '.join(x[1]+' '+x[2]+' ['+x[0]+']' for x in recups)) ) # For each of current premium members, we check if he has a free cci mag subscription and a free revue de presse subscription # TODO : this part of the medthod introduce a dependancy problem : this part use 'premium_subscription' object and the 'premium_subscription' # module depends of the 'premium' module. Be better to regroup the two modules into one or to split this part of the wizard into # a separate wizard today = datetime.datetime.today().strftime('%Y-%m-%d') # contact_obj = self.pool.get('res.partner.contact') contact_ids = contact_obj.search([('is_premium','=','OUI')]) if contact_ids: contacts = contact_ids #contact_obj.browse(cr,uid,contact_ids) obj_sub = self.env['premium_subscription'] obj_product = self.env['product.product'] obj_sub_type = self.env['premium_subscription.type'] for contact in contacts: already_mag = False already_rdp = False if contact.subscription_ids: for subscription in contact.subscription_ids: if subscription.type_id.code == 'CCIMAG': already_mag = True elif subscription.type_id.code == 'RDP': already_rdp = True if not already_mag: # free subscription for two cci mag issues new_id_sub = False type_ids = obj_sub_type.search([('code','=','CCIMAG')]) if type_ids: data_sub = {} data_sub['name'] = u"Abonnement gratuit à deux parutions" data_sub['date'] = datetime.datetime.today().strftime('%Y-%m-%d') data_sub['begin'] = datetime.datetime.today().strftime('%Y-%m-%d') end_date = datetime.datetime.today() + datetime.timedelta(days=62) data_sub['end'] = end_date.strftime('%Y-%m-%d') data_sub['contact_id'] = contact.id data_sub['partner_id'] = False data_sub['type_id'] = type_ids[0].id data_sub['product_id'] = False data_sub['price'] = 0.0 data_sub['source'] = 'Auto free' data_sub['usages'] = 2 data_sub['left_usages'] = 2 data_sub['state'] = 'current' data_sub['invoice_id'] = False new_id_sub = obj_sub.create(data_sub) # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNew free CCI Mag subscription for %s %s' % (contact.name,contact.first_name or '') ) if not already_rdp: # free subscription to 'Revue de Presse' for 14 days new_id_sub = False type_ids = obj_sub_type.search([('code','=','RDP')]) if type_ids: data_sub = {} data_sub['name'] = u"Abonnement gratuit à la Revue de Presse pour 14 jours" data_sub['date'] = datetime.datetime.today().strftime('%Y-%m-%d') data_sub['begin'] = datetime.datetime.today().strftime('%Y-%m-%d') end_date = datetime.datetime.today() + datetime.timedelta(days=15) data_sub['end'] = end_date.strftime('%Y-%m-%d') data_sub['contact_id'] = contact.id data_sub['partner_id'] = False data_sub['type_id'] = type_ids[0].id data_sub['product_id'] = False data_sub['price'] = 0.0 data_sub['source'] = 'Auto free' data_sub['usages'] = 0 data_sub['left_usages'] = 0 data_sub['state'] = 'current' data_sub['invoice_id'] = False new_id_sub = obj_sub.create(data_sub) # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNew free RDP subscription for %s %s' % (contact.name,contact.first_name or '') ) # We check for current 'répertoire électronique' subscriptions on non-premium contacts to transfert them to invoiced partner as partner_subscription # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nCheck if necessary to transfert premium subscriptions to company subscriptions' ) contact_sub_type_obj = self.env['premium_subscription.type'] contact_sub_type_ids = contact_sub_type_obj.search([('code','=','REPMEMBRE')]) if contact_sub_type_ids: partner_sub_type_obj = self.env['partner_subscription.type'] partner_sub_type_ids = partner_sub_type_obj.search([('code','=','SOCREPELEC')]) if partner_sub_type_ids: product_obj = self.env['product.product'] product_ids = product_obj.search([('partner_subscription_type_id','=',partner_sub_type_ids[0].id)]) if product_ids: contact_sub_obj = self.env['premium_subscription'] contact_sub_ids = contact_sub_obj.search([('state','=','current'),('type_id','in',contact_sub_type_ids)]) if contact_sub_ids: contact_subs = contact_sub_ids #contact_sub_obj.browse(cr,uid,contact_sub_ids) for contact_sub in contact_subs: if contact_sub.contact_id and contact_sub.contact_id.is_premium <> 'OUI': # try to transfert to partner if possible (patrner_id or through invoice_id.partner_id data = {} data['name'] = contact_sub.name or '' data['end'] = contact_sub.end data['invoice_id'] = contact_sub.invoice_id and contact_sub.invoice_id.id or 0 if contact_sub.partner_id: data['partner_id'] = contact_sub.partner_id.id elif contact_sub.invoice_id: data['partner_id'] = contact_sub.invoice_id.partner_id.id data['type_id'] = partner_sub_type_ids[0] data['product_id'] = product_ids[0] data['price'] = contact_sub.price or 0.0 data['source'] = 'Transfert From Contact' data['state'] = 'current' partner_sub_obj = self.env['partner_subscription'] new_id = partner_sub_obj.create(data) if new_id: contact_sub.button_close() contact_sub.write({'close_source':'Transfert'}) else: pass # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNo contract to transfert.' ) else: errors.append('0') # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNo product defined for partner subscriptions of type \'REPMEMBRE\'.' ) else: errors.append('0') # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNo type of partner subscriptions found with the code \'SOCREPELEC\'.' ) else: errors.append('0') # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNo type of premium subscriptions found with the code \'REPMEMBRE\'.' ) # Now we can recount the count_premium of each partner partner_obj = self.env['res.partner'] partner_ids = partner_obj.search([]) changed = 0 checked = 0 if partner_ids: index = 0 part = 500 while index < len(partner_ids) and ( changed < max_changed ): partners = partner_ids[index:index+part] for partner in partners: max_premium = 0 nbr_premium = 0 for addr in partner.child_ids: for job in addr.other_contact_ids: max_premium += 1 if addr.is_premium: nbr_premium += 1 new_value = '%i/%i' % (nbr_premium,max_premium) checked += 1 if partner.count_premium != new_value: try: partner.write({'count_premium':new_value}) changed += 1 except Exception: errors.append(str(partner.id)) index += part # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,'\n\nChecked : %d' % checked ) # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,'\nChanged : %d' % changed ) if errors: # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,'\nPartners not changed - errors : [%s]' % (','.join(errors)) ) final_result = False # self.pool.get('cci_logs.cron_line')._stop(cr,uid,cronline_id,final_result,'\n---end---') return True
def send_onchange_user_id(self, cr, uid, ids, user_id): user_obj = self.pool.get('res.users') user_br = user_obj.browse(cr, uid, [user_id]) for usr in user_br: task_br = self.browse(cr, uid, ids) for t in task_br: project = t.project_id subject = _("Task '%s' has been assigned to you") % t.name if usr.id and usr.address_id and usr.address_id.email: to_adr = usr.address_id.email signature = usr.signature else: raise osv.except_osv( _('Error'), _("Couldn't send mail because your email address is not configured!" )) from_adr = tools.config.get('email_from', False) or usr.address_id.email task_name = u'Task name: %s' % (tools.ustr(t.name)) project_code = u'Project code: %s' % (tools.ustr( t.project_complete_wbs_name)) task_id = u'Task id: %s' % (tools.ustr(t.id)) vals = [task_name, project_code, task_id] header = u'\n'.join(vals) footer = '' body = u'%s\n%s\n%s\n\n-- \n%s' % (header, t.description, footer, signature) mail_id = tools.email_send(from_adr, to_adr, subject, tools.ustr(body), email_bcc=[from_adr]) if not mail_id: raise osv.except_osv( _('Error'), _("Couldn't send mail! Check the email ids and smtp configuration settings" )) msg_dict = { 'new': 'Send', 'reply': 'Reply', 'forward': 'Forward' } self.history(cr, uid, [t], _(msg_dict['new']), history=True, email=to_adr, details=body, subject=subject, email_from=from_adr, message_id=None, references=None, attach=None) return {}
def send_emails(self): parameter_obj = self.env['cci_parameters.cci_value'] param_values = parameter_obj.get_value_from_names([ 'DirMemberTemplateID', 'DirMemberOptionalID', 'DirMemberOptionalItemID' ]) if param_values.has_key( 'DirMemberTemplateID') and param_values.has_key( 'DirMemberOptionalID') and param_values.has_key( 'DirMemberOptionalItemID'): template_obj = self.env['cci_email_template'] template = template_obj.browse( cr, uid, [param_values['DirMemberTemplateID']])[0] add_message = template_obj.browse( cr, uid, [param_values['DirMemberOptionalID']])[0].body base_item = template_obj.browse( cr, uid, [param_values['DirMemberOptionalItemID']])[0].body # addr_proxy_obj = self.env['directory.address.proxy'] if self.type == 'initial': addr_proxy_ids = addr_proxy_obj.search([ ('user_validated', '=', False), ('send_initial_mail', '=', False), ('sending_address', '<>', False) ]) elif selftype == '1followup': addr_proxy_ids = addr_proxy_obj.search([ ('user_validated', '=', False), ('send_initial_mail', '>', '1980-01-01'), ('send_first_followup', '=', False), ('sending_address', '<>', False) ]) else: addr_proxy_ids = [] sended_emails = [] sended_ids = [] errors = [] if addr_proxy_ids: proxies = addr_proxy_ids.read([ 'id', 'link_id', 'sending_courtesy', 'sending_name', 'sending_courtesy', 'sending_address', 'partner_id' ]) for proxy in proxies: email_content = template.body.replace( '[courtesy]', proxy['sending_courtesy'] or '').replace( '[name]', proxy['sending_name'] or 'cher Membre').replace('[link_id]', proxy['link_id']) if '[others_data]' in template.body and proxy['partner_id']: other_ids = addr_proxy_obj.search([ ('partner_id', '=', proxy['partner_id'][0]), ('id', '<>', proxy['id']), ('sending_address', '<>', False), ('user_validated', '=', False) ]) if other_ids: others = other_ids.read([ 'complete_name', 'sending_courtesy', 'sending_name', 'sending_address', 'link_id' ]) others_list = [] for other in others: others_list.append( base_item % (other['complete_name'], other['sending_name'] and (u'"' + other['sending_courtesy'] + ' ' + other['sending_name'] + '"') or u'l\'adresse du siège', other['sending_address'], other['link_id'], other['link_id'])) optional_message = add_message % u'</li><li>'.join( others_list) email_content = email_content.replace( '[others_data]', optional_message) # print email_content else: email_content = email_content.replace( '[others_data]', '') email_address = proxy['sending_address'] # email_address = '*****@*****.**' ## TODO delete try: tools.email_send(data['form']['from'], [email_address], data['form']['title'], email_content, subtype='html') # print '---email content---' # print email_content except: errors.append(email_address) else: sended_emails.append(email_address) sended_ids.append(proxy['id']) # recording of the sending after each one, so, if we have a problem, we can determine what is already sent... if data['form']['type'] == 'initial': addr_proxy_obj.write( cr, uid, [ proxy['id'], ], { 'send_initial_mail': datetime.date.today().strftime('%Y-%m-%d') }) elif data['form']['type'] == '1followup': addr_proxy_obj.write( cr, uid, [ proxy['id'], ], { 'send_first_followup': datetime.date.today().strftime('%Y-%m-%d') }) results = 'Sended emails : %s\nErrors : %s' % (str( len(sended_emails)), str(len(errors))) else: results = 'You MUST define template "DirMemberTemplate" and "DirMemberTemplateID"' ctx = self.env.context.copy() ctx.update({'results': results}) view = self.env.ref( 'cci_memberdirectory.view_cci_memberdirectory_send_email_msg') return { 'name': _('Notification'), 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'cci.memberdirectory.send.email.msg', 'views': [(view.id, 'form')], 'view_id': view.id, 'target': 'new', 'context': ctx, }
def create_data(self): part_id = self.env.context.get('active_id', False) if part_id: contact = self.env['res.partner'].browse(part_id) newlogin = contact.email or False if newlogin: same = self.env['res.partner'].search([('login_name', '=', newlogin)]) if not same: random.seed() if contact.name and contact.first_name: newpw = contact.name[0:2].lower() + str(int(random.random() * 1000000)).rjust(6, '0') + contact.first_name[0:2].lower() else: if contact.name and len(contact.name) > 3: newpw = contact.name[0:2].lower() + str(int(random.random() * 1000000)).rjust(6, '0') + contact.name[2:4].lower() else: newpw = contact.name[0:2].lower() + str(int(random.random() * 1000000)).rjust(6, '0') + 'am' if not newpw.isalpha(): newpw = newpw.replace('.', '').replace('-', '.') same = True while same: newtoken = hex(random.getrandbits(128))[2:34] same = self.env['res.partner'].search([('token', '=', newtoken)]) res = contact.write({'login_name': newlogin, 'password': newpw, 'token': newtoken}) if res: res_message = "Login-pw created '%s' / '%s' / '%s'" % (newlogin, newpw, newtoken) if self.send_email and self.from_email: text = u'''Suite à votre demande, voici votre login et votre mot de passe pour vous connecter sur le site de la CCI Connect : www.cciconnect.be. Login : %s Mot de passe : %s %s Bienvenue.''' str_to = '*****@*****.**' str_from = '' str_from = self.from_email or '*****@*****.**' # # the field is required, this not usefull str_to = contact.email or str_to # TODO check email address from if str_to and str_from: text = text % (newlogin, newpw, tools.ustr(self.perso_message or '')) text = tools.ustr(text) res = tools.email_send(str_from, [str_to], 'CCIConnect login et mot de passe', text) if res: res_message += "\nThe login-password has been send to the email address '%s'" % str_to else: res_message += "\nError: Mail not sent, Contact '%s %s' does not have a valid address mail : '%s' or the mail cannot be send" % (contact.name, contact.first_name, str_to) else: res_message = "Error while registering new login-password-token" else: res_message = 'An other contact already have the same login : '******'cci_base_contact.view_create_website_message_form') ctx = self.env.context.copy() ctx.update({'message': res_message}) return { 'name': _('Result'), 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'create.website.message', 'views': [(view.id, 'form')], 'view_id': view.id, 'target': 'new', 'context': ctx, }
def action_send(self, cr, uid, ids,type, context=None): """ This sends an email to respective heads requesting for leave """ mail_obj = self.pool.get('crm.send.mail') Addr_obj = self.pool.get('res.partner') user = self.pool.get('res.users').browse(cr, uid,uid) for case in self.browse(cr,uid,ids): subtype = 'plain' comp_email = '' if case.company_id: addr_id = Addr_obj.search(cr,uid,[('partner_id','=',case.company_id.id)])[0] comp_email = Addr_obj.browse(cr,uid,addr_id).email email_to = case.work_email email_from = comp_email email_cc = comp_email # if not email_from: # raise osv.except_osv(_('Error'), _("Please enter " + str(case.user_id.name) + "'s Email id!")) # # if not email_to: # raise osv.except_osv(_('Error'), _("Please enter " + str(case.employee_id.name) + "'s Email id!")) # emails = re.findall(r'([^ ,<@]+@[^> ,]+)', email_to or '') email_cc = re.findall(r'([^ ,<@]+@[^> ,]+)', email_cc or '') emails = filter(None, emails) if type == 'leave': subject = 'Remainder for Leave Requests to be Approved' body = "" body += """\n\n Dear """ + (case.name or '-') body += """ there are Leave Records which have to be Approved""" if type == 'timeoff': subject = 'Remainder for Time Off Requests to be Approved' body = "" body += """ Dear """ + (case.name or '-') body += """ there are Time Off records which have to be Approved """ if type == 'absent': subject = 'Absent Records' body = "" body += """\n\nDear """ + (case.name or '-') body += """ there are absent Attendance Records please apply Leave for the same""" if emails and email_from: flag = tools.email_send( email_from, emails, subject, body, email_cc = email_cc, attach = [], subtype = subtype, reply_to = email_from, openobject_id = str(case.id), x_headers = {} ) if not flag: raise osv.except_osv(_('Error!'), _('Unable to send mail. Please check SMTP is configured properly.')) return True
def count_premium(self, max_changed=2000): # cronline_id = self.pool.get('cci_logs.cron_line')._start(cr,uid,'CountPremium') final_result = True errors = [] # Before checking the count of premiums for partners, checks for validity of premium contact : today, we keep only premium linked to a at least one partner in 5... zip code non-members contact_obj = self.env['res.partner'] contact_ids = contact_obj.search([ '|', ('premium_begin', '>', '2000-01-01'), ('premium_special', '=', 'no') ]) losts = [] recups = [] if contact_ids: contacts = contact_ids #contact_obj.browse(cr,uid,contact_ids) for contact in contacts: # calculate the good state if contact.premium_special == 'yes': new_special = 'yes' else: new_special = 'no' if contact.other_contact_ids: for job in contact.other_contact_ids: if job.address_id and job.address_id.parent_id and job.address_id.zip_id: if job.address_id.zip_id.name[0:1] == '5' and ( job.address_id.parent_id. membership_state not in ['free', 'invoiced', 'paid'] ) and job.address_id.partner_id.state_id.id == 1: new_special = 'normal' if new_special != contact.premium_special: # modify the current state and save it to send as email at the end of the control contact.write({'premium_special': new_special}) if new_special == 'no': losts.append([ str(contact.id), contact.name, contact.first_name or '' ]) else: recups.append([ str(contact.id), contact.name, contact.first_name or '' ]) if losts or recups: # send mail to premium supervisors # parameter_obj = self.pool.get('cci_parameters.cci_value') parameter_obj = self.env['ir.config_parameter'] param_values = parameter_obj.search([ ('key', '=', 'SupervisorsPremiumEmail') ])[0].value if param_values: email_text = u"""<p>Certains premiums ont été désactivés ou certains ont été réactivés. En voici la liste :</p> <p>Désactivés :<br/><ul><li> %s </li></ul></p> <p>Réactivés :<br/><ul><li> %s </li></ul></p> """ % ( losts and '</li><li>'.join( x[1] + ' ' + x[2] + ' [' + x[0] + ']' for x in losts) or '--Aucun--', recups and '</li><li>'.join(x[1] + ' ' + x[2] + ' [' + x[0] + ']' for x in recups) or '--Aucun--') tools.email_send('*****@*****.**', param_values, u'Changement dans les Premiums', email_text, subtype='html') # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,'\nChanged Contacts :\n\nPremium Losts : \n- %s\n\nRecovered Premium : \n- %s' % ('\n- '.join(x[1]+' '+x[2]+' ['+x[0]+']' for x in losts), # '\n- '.join(x[1]+' '+x[2]+' ['+x[0]+']' for x in recups)) ) # For each of current premium members, we check if he has a free cci mag subscription and a free revue de presse subscription # TODO : this part of the medthod introduce a dependancy problem : this part use 'premium_subscription' object and the 'premium_subscription' # module depends of the 'premium' module. Be better to regroup the two modules into one or to split this part of the wizard into # a separate wizard today = datetime.datetime.today().strftime('%Y-%m-%d') # contact_obj = self.pool.get('res.partner.contact') contact_ids = contact_obj.search([('is_premium', '=', 'OUI')]) if contact_ids: contacts = contact_ids #contact_obj.browse(cr,uid,contact_ids) obj_sub = self.env['premium_subscription'] obj_product = self.env['product.product'] obj_sub_type = self.env['premium_subscription.type'] for contact in contacts: already_mag = False already_rdp = False if contact.subscription_ids: for subscription in contact.subscription_ids: if subscription.type_id.code == 'CCIMAG': already_mag = True elif subscription.type_id.code == 'RDP': already_rdp = True if not already_mag: # free subscription for two cci mag issues new_id_sub = False type_ids = obj_sub_type.search([('code', '=', 'CCIMAG')]) if type_ids: data_sub = {} data_sub[ 'name'] = u"Abonnement gratuit à deux parutions" data_sub['date'] = datetime.datetime.today().strftime( '%Y-%m-%d') data_sub['begin'] = datetime.datetime.today().strftime( '%Y-%m-%d') end_date = datetime.datetime.today( ) + datetime.timedelta(days=62) data_sub['end'] = end_date.strftime('%Y-%m-%d') data_sub['contact_id'] = contact.id data_sub['partner_id'] = False data_sub['type_id'] = type_ids[0].id data_sub['product_id'] = False data_sub['price'] = 0.0 data_sub['source'] = 'Auto free' data_sub['usages'] = 2 data_sub['left_usages'] = 2 data_sub['state'] = 'current' data_sub['invoice_id'] = False new_id_sub = obj_sub.create(data_sub) # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNew free CCI Mag subscription for %s %s' % (contact.name,contact.first_name or '') ) if not already_rdp: # free subscription to 'Revue de Presse' for 14 days new_id_sub = False type_ids = obj_sub_type.search([('code', '=', 'RDP')]) if type_ids: data_sub = {} data_sub[ 'name'] = u"Abonnement gratuit à la Revue de Presse pour 14 jours" data_sub['date'] = datetime.datetime.today().strftime( '%Y-%m-%d') data_sub['begin'] = datetime.datetime.today().strftime( '%Y-%m-%d') end_date = datetime.datetime.today( ) + datetime.timedelta(days=15) data_sub['end'] = end_date.strftime('%Y-%m-%d') data_sub['contact_id'] = contact.id data_sub['partner_id'] = False data_sub['type_id'] = type_ids[0].id data_sub['product_id'] = False data_sub['price'] = 0.0 data_sub['source'] = 'Auto free' data_sub['usages'] = 0 data_sub['left_usages'] = 0 data_sub['state'] = 'current' data_sub['invoice_id'] = False new_id_sub = obj_sub.create(data_sub) # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNew free RDP subscription for %s %s' % (contact.name,contact.first_name or '') ) # We check for current 'répertoire électronique' subscriptions on non-premium contacts to transfert them to invoiced partner as partner_subscription # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nCheck if necessary to transfert premium subscriptions to company subscriptions' ) contact_sub_type_obj = self.env['premium_subscription.type'] contact_sub_type_ids = contact_sub_type_obj.search([('code', '=', 'REPMEMBRE')]) if contact_sub_type_ids: partner_sub_type_obj = self.env['partner_subscription.type'] partner_sub_type_ids = partner_sub_type_obj.search([ ('code', '=', 'SOCREPELEC') ]) if partner_sub_type_ids: product_obj = self.env['product.product'] product_ids = product_obj.search([ ('partner_subscription_type_id', '=', partner_sub_type_ids[0].id) ]) if product_ids: contact_sub_obj = self.env['premium_subscription'] contact_sub_ids = contact_sub_obj.search([ ('state', '=', 'current'), ('type_id', 'in', contact_sub_type_ids) ]) if contact_sub_ids: contact_subs = contact_sub_ids #contact_sub_obj.browse(cr,uid,contact_sub_ids) for contact_sub in contact_subs: if contact_sub.contact_id and contact_sub.contact_id.is_premium <> 'OUI': # try to transfert to partner if possible (patrner_id or through invoice_id.partner_id data = {} data['name'] = contact_sub.name or '' data['end'] = contact_sub.end data[ 'invoice_id'] = contact_sub.invoice_id and contact_sub.invoice_id.id or 0 if contact_sub.partner_id: data[ 'partner_id'] = contact_sub.partner_id.id elif contact_sub.invoice_id: data[ 'partner_id'] = contact_sub.invoice_id.partner_id.id data['type_id'] = partner_sub_type_ids[0] data['product_id'] = product_ids[0] data['price'] = contact_sub.price or 0.0 data['source'] = 'Transfert From Contact' data['state'] = 'current' partner_sub_obj = self.env[ 'partner_subscription'] new_id = partner_sub_obj.create(data) if new_id: contact_sub.button_close() contact_sub.write( {'close_source': 'Transfert'}) else: pass # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNo contract to transfert.' ) else: errors.append('0') # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNo product defined for partner subscriptions of type \'REPMEMBRE\'.' ) else: errors.append('0') # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNo type of partner subscriptions found with the code \'SOCREPELEC\'.' ) else: errors.append('0') # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,u'\nNo type of premium subscriptions found with the code \'REPMEMBRE\'.' ) # Now we can recount the count_premium of each partner partner_obj = self.env['res.partner'] partner_ids = partner_obj.search([]) changed = 0 checked = 0 if partner_ids: index = 0 part = 500 while index < len(partner_ids) and (changed < max_changed): partners = partner_ids[index:index + part] for partner in partners: max_premium = 0 nbr_premium = 0 for addr in partner.child_ids: for job in addr.other_contact_ids: max_premium += 1 if addr.is_premium: nbr_premium += 1 new_value = '%i/%i' % (nbr_premium, max_premium) checked += 1 if partner.count_premium != new_value: try: partner.write({'count_premium': new_value}) changed += 1 except Exception: errors.append(str(partner.id)) index += part # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,'\n\nChecked : %d' % checked ) # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,'\nChanged : %d' % changed ) if errors: # self.pool.get('cci_logs.cron_line')._addComment(cr,uid,cronline_id,'\nPartners not changed - errors : [%s]' % (','.join(errors)) ) final_result = False # self.pool.get('cci_logs.cron_line')._stop(cr,uid,cronline_id,final_result,'\n---end---') return True