1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
27 from osv import fields, osv, orm
28 from osv.orm import except_orm
29 from tools.translate import _
31 class base_action_rule(osv.osv):
32 """ Base Action Rules """
34 _name = 'base.action.rule'
35 _description = 'Action Rules'
37 def _state_get(self, cr, uid, context={}):
39 @param self: The object pointer
40 @param cr: the current row, from the database cursor,
41 @param uid: the current user’s ID for security checks,
42 @param context: A standard dictionary for contextual values """
44 return self.state_get(cr, uid, context=context)
47 def state_get(self, cr, uid, context={}):
49 @param self: The object pointer
50 @param cr: the current row, from the database cursor,
51 @param uid: the current user’s ID for security checks,
52 @param context: A standard dictionary for contextual values """
56 def priority_get(self, cr, uid, context={}):
58 @param self: The object pointer
59 @param cr: the current row, from the database cursor,
60 @param uid: the current user’s ID for security checks,
61 @param context: A standard dictionary for contextual values """
66 'name': fields.many2one('ir.model', 'Object', required=True),
67 'max_level': fields.integer('Max Level', help='Specifies maximum level.'),
68 'create_date': fields.datetime('Create Date', readonly=1),
69 'active': fields.boolean('Active', help="If the active field is set to true,\
70 it will allow you to hide the rule without removing it."),
71 'sequence': fields.integer('Sequence', help="Gives the sequence order \
72 when displaying a list of rules."),
73 'trg_date_type': fields.selection([
75 ('create', 'Creation Date'),
76 ('action_last', 'Last Action Date'),
78 ('deadline', 'Deadline'),
79 ], 'Trigger Date', size=16),
80 'trg_date_range': fields.integer('Delay after trigger date', \
81 help="Delay After Trigger Date,\
82 specifies you can put a negative number. If you need a delay before the \
83 trigger date, like sending a reminder 15 minutes before a meeting."),
84 'trg_date_range_type': fields.selection([('minutes', 'Minutes'), ('hour', 'Hours'), \
85 ('day', 'Days'), ('month', 'Months')], 'Delay type'),
88 'trg_user_id': fields.many2one('res.users', 'Responsible'),
90 'trg_partner_id': fields.many2one('res.partner', 'Partner'),
91 'trg_partner_categ_id': fields.many2one('res.partner.category', 'Partner Category'),
92 'trg_state_from': fields.selection(_state_get, 'State', size=16),
93 'trg_state_to': fields.selection(_state_get, 'Button Pressed', size=16),
95 'act_method': fields.char('Call Object Method', size=64),
96 'act_user_id': fields.many2one('res.users', 'Set Responsible to'),
97 'act_state': fields.selection(_state_get, 'Set State to', size=16),
98 'act_email_cc': fields.char('Add Watchers (Cc)', size=250, help="\
99 These people will receive a copy of the future communication between partner \
100 and users by email"),
101 'act_remind_partner': fields.boolean('Remind Partner', help="Check \
102 this if you want the rule to send a reminder by email to the partner."),
103 'act_remind_user': fields.boolean('Remind Responsible', help="Check \
104 this if you want the rule to send a reminder by email to the user."),
105 'act_reply_to': fields.char('Reply-To', size=64),
106 'act_remind_attach': fields.boolean('Remind with Attachment', help="Check this if you want that all documents attached to the object be attached to the reminder email sent."),
107 'act_mail_to_user': fields.boolean('Mail to Responsible', help="Check\
108 this if you want the rule to send an email to the responsible person."),
109 'act_mail_to_watchers': fields.boolean('Mail to Watchers (CC)',
110 help="Check this if you want \
111 the rule to mark CC(mail to any other person defined in actions)."),
112 'act_mail_to_email': fields.char('Mail to these emails', size=128, \
113 help="Email-id of the persons whom mail is to be sent"),
114 'act_mail_body': fields.text('Mail body', help="Content of mail"),
115 'regex_name': fields.char('Regular Expression on Model Name', size=128),
116 'server_action_id': fields.many2one('ir.actions.server', 'Server Action', help="Describes the action name.\neg:on which object which action to be taken on basis of which condition"),
117 'filter_id':fields.many2one('ir.filters', 'Filter', required=False),
118 'domain':fields.char('Domain', size=124, required=False, readonly=False),
122 'active': lambda *a: True,
123 'max_level': lambda *a: 15,
124 'trg_date_type': lambda *a: 'none',
125 'trg_date_range_type': lambda *a: 'day',
126 'act_mail_to_user': lambda *a: 0,
127 'act_remind_partner': lambda *a: 0,
128 'act_remind_user': lambda *a: 0,
129 'act_mail_to_watchers': lambda *a: 0,
130 'domain': lambda *a: '[]'
135 def format_body(self, body):
136 """ Foramat Action rule's body
137 @param self: The object pointer """
139 return body and tools.ustr(body) or ''
141 def format_mail(self, obj, body):
143 @param self: The object pointer """
147 'object_subject': hasattr(obj, 'name') and obj.name or False,
148 'object_date': hasattr(obj, 'date') and obj.date or False,
149 'object_description': hasattr(obj, 'description') and obj.description or False,
150 'object_user': hasattr(obj, 'user_id') and (obj.user_id and obj.user_id.name) or '/',
151 'object_user_email': hasattr(obj, 'user_id') and (obj.user_id and \
152 obj.user_id.address_id and obj.user_id.address_id.email) or '/',
153 'object_user_phone': hasattr(obj, 'user_id') and (obj.user_id and\
154 obj.user_id.address_id and obj.user_id.address_id.phone) or '/',
155 'partner': hasattr(obj, 'partner_id') and (obj.partner_id and obj.partner_id.name) or '/',
156 'partner_email': hasattr(obj, 'partner_address_id') and (obj.partner_address_id and\
157 obj.partner_address_id.email) or '/',
159 return self.format_body(body % data)
161 def email_send(self, cr, uid, obj, emails, body, emailfrom=tools.config.get('email_from', False), context={}):
163 @param self: The object pointer
164 @param cr: the current row, from the database cursor,
165 @param uid: the current user’s ID for security checks,
166 @param email: pass the emails
167 @param emailfrom: Pass name the email From else False
168 @param context: A standard dictionary for contextual values """
170 body = self.format_mail(obj, body)
172 if hasattr(obj, 'user_id') and obj.user_id and obj.user_id.address_id and\
173 obj.user_id.address_id.email:
174 emailfrom = obj.user_id.address_id.email
176 name = '[%d] %s' % (obj.id, tools.ustr(obj.name))
177 emailfrom = tools.ustr(emailfrom)
180 raise osv.except_osv(_('Error!'),
181 _("No E-Mail ID Found for your Company address!"))
182 return tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, openobject_id=str(obj.id))
185 def do_check(self, cr, uid, action, obj, context={}):
187 @param self: The object pointer
188 @param cr: the current row, from the database cursor,
189 @param uid: the current user’s ID for security checks,
190 @param context: A standard dictionary for contextual values """
193 if eval(action.domain):
194 obj_ids = obj._table.search(cr, uid, eval(action.domain), context=context)
195 if not obj.id in obj_ids:
197 if hasattr(obj, 'user_id'):
198 ok = ok and (not action.trg_user_id.id or action.trg_user_id.id==obj.user_id.id)
199 if hasattr(obj, 'partner_id'):
200 ok = ok and (not action.trg_partner_id.id or action.trg_partner_id.id==obj.partner_id.id)
202 not action.trg_partner_categ_id.id or
204 obj.partner_id.id and
205 (action.trg_partner_categ_id.id in map(lambda x: x.id, obj.partner_id.category_id or []))
208 state_to = context.get('state_to', False)
209 if hasattr(obj, 'state'):
210 ok = ok and (not action.trg_state_from or action.trg_state_from==obj.state)
212 ok = ok and (not action.trg_state_to or action.trg_state_to==state_to)
214 reg_name = action.regex_name
217 ptrn = re.compile(str(reg_name))
218 _result = ptrn.search(str(obj.name))
221 regex_n = not reg_name or result_name
225 def do_action(self, cr, uid, action, model_obj, obj, context={}):
227 @param self: The object pointer
228 @param cr: the current row, from the database cursor,
229 @param uid: the current user’s ID for security checks,
230 @param action: pass action
231 @param model_obj: pass Model object
232 @param context: A standard dictionary for contextual values """
234 if action.server_action_id:
235 context.update({'active_id':obj.id, 'active_ids':[obj.id]})
236 self.pool.get('ir.actions.server').run(cr, uid, [action.server_action_id.id], context)
238 if hasattr(obj, 'user_id') and action.act_user_id:
239 obj.user_id = action.act_user_id
240 write['user_id'] = action.act_user_id.id
241 if hasattr(obj, 'date_action_last'):
242 write['date_action_last'] = time.strftime('%Y-%m-%d %H:%M:%S')
243 if hasattr(obj, 'state') and action.act_state:
244 obj.state = action.act_state
245 write['state'] = action.act_state
247 if hasattr(obj, 'categ_id') and action.act_categ_id:
248 obj.categ_id = action.act_categ_id
249 write['categ_id'] = action.act_categ_id.id
251 model_obj.write(cr, uid, [obj.id], write, context)
253 if hasattr(model_obj, 'remind_user') and action.act_remind_user:
254 model_obj.remind_user(cr, uid, [obj.id], context, attach=action.act_remind_attach)
255 if hasattr(model_obj, 'remind_partner') and action.act_remind_partner:
256 model_obj.remind_partner(cr, uid, [obj.id], context, attach=action.act_remind_attach)
257 if action.act_method:
258 getattr(model_obj, 'act_method')(cr, uid, [obj.id], action, context)
260 if hasattr(obj, 'user_id') and action.act_mail_to_user:
261 if obj.user_id and obj.user_id.address_id:
262 emails.append(obj.user_id.address_id.email)
264 if action.act_mail_to_watchers:
265 emails += (action.act_email_cc or '').split(',')
266 if action.act_mail_to_email:
267 emails += (action.act_mail_to_email or '').split(',')
268 emails = filter(None, emails)
269 if len(emails) and action.act_mail_body:
270 emails = list(set(emails))
271 self.email_send(cr, uid, obj, emails, action.act_mail_body)
274 def _action(self, cr, uid, ids, objects, scrit=None, context={}):
276 @param self: The object pointer
277 @param cr: the current row, from the database cursor,
278 @param uid: the current user’s ID for security checks,
279 @param ids: List of Basic Action Rule’s IDs,
280 @param objects: pass objects
281 @param context: A standard dictionary for contextual values """
285 cr.execute("select id from base_action_rule order by sequence")
286 rule_ids = map(lambda x: x[0], cr.fetchall())
287 for action in self.browse(cr, uid, rule_ids):
288 level = action.max_level
291 model_obj = self.pool.get(action.name.model)
293 ok = self.do_check(cr, uid, action, obj, context=context)
298 if hasattr(obj, 'create_date') and action.trg_date_type=='create':
299 base = mx.DateTime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
300 elif hasattr(obj, 'create_date') and action.trg_date_type=='action_last':
301 if hasattr(obj, 'date_action_last') and obj.date_action_last:
302 base = mx.DateTime.strptime(obj.date_action_last, '%Y-%m-%d %H:%M:%S')
304 base = mx.DateTime.strptime(obj.create_date[:19], '%Y-%m-%d %H:%M:%S')
305 elif hasattr(obj, 'date_deadline') and action.trg_date_type=='deadline' \
306 and obj.date_deadline:
307 base = mx.DateTime.strptime(obj.date_deadline, '%Y-%m-%d %H:%M:%S')
308 elif hasattr(obj, 'date') and action.trg_date_type=='date' and obj.date:
309 base = mx.DateTime.strptime(obj.date, '%Y-%m-%d %H:%M:%S')
312 'minutes': lambda interval: mx.DateTime.RelativeDateTime(minutes=interval),
313 'day': lambda interval: mx.DateTime.RelativeDateTime(days=interval),
314 'hour': lambda interval: mx.DateTime.RelativeDateTime(hours=interval),
315 'month': lambda interval: mx.DateTime.RelativeDateTime(months=interval),
317 d = base + fnct[action.trg_date_range_type](action.trg_date_range)
318 dt = d.strftime('%Y-%m-%d %H:%M:%S')
320 if hasattr(obj, 'date_action_last') and hasattr(obj, 'date_action_next'):
321 ok = (dt <= time.strftime('%Y-%m-%d %H:%M:%S')) and \
322 ((not obj.date_action_next) or \
323 (dt >= obj.date_action_next and \
324 obj.date_action_last < obj.date_action_next))
326 if not obj.date_action_next or dt < obj.date_action_next:
327 obj.date_action_next = dt
328 model_obj.write(cr, uid, [obj.id], {'date_action_next': dt}, context)
330 ok = action.trg_date_type=='none'
333 self.do_action(cr, uid, action, model_obj, obj, context)
338 def _check_mail(self, cr, uid, ids, context=None):
340 @param self: The object pointer
341 @param cr: the current row, from the database cursor,
342 @param uid: the current user’s ID for security checks,
343 @param ids: List of Action Rule’s IDs
344 @param context: A standard dictionary for contextual values """
346 empty = orm.browse_null()
347 rule_obj = self.pool.get('base.action.rule')
348 for rule in self.browse(cr, uid, ids):
349 if rule.act_mail_body:
351 rule_obj.format_mail(empty, rule.act_mail_body)
352 except (ValueError, KeyError, TypeError):
357 (_check_mail, 'Error: The mail is not well formated', ['act_mail_body']),
362 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: