[MERGE] config-rework2, rpa apr
[odoo/odoo.git] / addons / crm_claim / crm_claim.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
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.
11 #
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.
16 #
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/>.
19 #
20 ##############################################################################
21
22 from osv import fields, osv
23 from crm import crm
24 import time
25 import binascii
26 import tools
27 from tools.translate import _
28
29 CRM_CLAIM_PENDING_STATES = (
30     crm.AVAILABLE_STATES[2][0], # Cancelled
31     crm.AVAILABLE_STATES[3][0], # Done
32     crm.AVAILABLE_STATES[4][0], # Pending
33 )
34
35
36 class crm_claim(crm.crm_case, osv.osv):
37     """
38     Crm claim
39     """
40     _name = "crm.claim"
41     _description = "Claim"
42     _order = "priority,date desc"
43     _inherit = ['mailgate.thread']
44     _columns = {
45         'id': fields.integer('ID', readonly=True), 
46         'name': fields.char('Claim Subject', size=128, required=True), 
47         'action_next': fields.char('Next Action', size=200),
48         'date_action_next': fields.datetime('Next Action Date'),
49         'description': fields.text('Description'), 
50         'resolution': fields.text('Resolution'), 
51         'create_date': fields.datetime('Creation Date' , readonly=True), 
52         'write_date': fields.datetime('Update Date' , readonly=True), 
53         'date_deadline': fields.date('Deadline'), 
54         'date_closed': fields.datetime('Closed', readonly=True), 
55         'date': fields.datetime('Claim Date'), 
56         'ref' : fields.reference('Reference', selection=crm._links_get, size=128), 
57         'categ_id': fields.many2one('crm.case.categ', 'Category', \
58                             domain="[('section_id','=',section_id),\
59                             ('object_id.model', '=', 'crm.claim')]"), 
60         'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'), 
61         'type_action': fields.selection([('correction','Corrective Action'),('prevention','Preventive Action')], 'Action Type'),
62         'user_id': fields.many2one('res.users', 'Responsible'), 
63         'user_fault': fields.char('Trouble Responsible', size=64), 
64         'section_id': fields.many2one('crm.case.section', 'Sales Team', \
65                         select=True, help="Sales team to which Case belongs to."\
66                                 "Define Responsible user and Email account for"\
67                                 " mail gateway."), 
68         'company_id': fields.many2one('res.company', 'Company'), 
69         'partner_id': fields.many2one('res.partner', 'Partner'), 
70         'partner_address_id': fields.many2one('res.partner.address', 'Partner Contact', \
71                                 # domain="[('partner_id','=',partner_id)]"
72                                  ), 
73         'email_cc': fields.text('Watchers Emails', size=252, help="These email addresses will be added to the CC field of all inbound and outbound emails for this record before being sent. Separate multiple email addresses with a comma"), 
74         'email_from': fields.char('Email', size=128, help="These people will receive email."), 
75         'partner_phone': fields.char('Phone', size=32), 
76         'stage_id': fields.many2one ('crm.case.stage', 'Stage', domain="[('type','=','claim')]"), 
77         'cause': fields.text('Root Cause'), 
78         'state': fields.selection(crm.AVAILABLE_STATES, 'State', size=16, readonly=True, 
79                                   help='The state is set to \'Draft\', when a case is created.\
80                                   \nIf the case is in progress the state is set to \'Open\'.\
81                                   \nWhen the case is over, the state is set to \'Done\'.\
82                                   \nIf the case needs to be reviewed then the state is set to \'Pending\'.'), 
83         'message_ids': fields.one2many('mailgate.message', 'res_id', 'Messages', domain=[('model','=',_name)]),
84     }
85     
86     def stage_next(self, cr, uid, ids, context=None):
87         stage = super(crm_claim, self).stage_next(cr, uid, ids, context=context)
88         if stage:
89             stage_obj = self.pool.get('crm.case.stage').browse(cr, uid, stage, context=context)
90             self.history(cr, uid, ids, _("Changed Stage to: ") + stage_obj.name)
91         return stage
92
93     def stage_previous(self, cr, uid, ids, context=None):
94         stage = super(crm_claim, self).stage_previous(cr, uid, ids, context=context)
95         if stage:
96             stage_obj = self.pool.get('crm.case.stage').browse(cr, uid, stage, context=context)
97             self.history(cr, uid, ids, _("Changed Stage to: ") + stage_obj.name)
98         return stage
99     
100     def _get_stage_id(self, cr, uid, context=None):
101         """Finds type of stage according to object.
102         @param self: The object pointer
103         @param cr: the current row, from the database cursor,
104         @param uid: the current user’s ID for security checks,
105         @param context: A standard dictionary for contextual values
106         """
107         if context is None:
108             context = {}
109         type = context and context.get('stage_type', '')
110         stage_ids = self.pool.get('crm.case.stage').search(cr, uid, [('type','=',type),('sequence','>=',1)])
111         return stage_ids and stage_ids[0] or False
112
113     _defaults = {
114         'user_id': crm.crm_case._get_default_user, 
115         'partner_id': crm.crm_case._get_default_partner, 
116         'partner_address_id': crm.crm_case._get_default_partner_address, 
117         'email_from':crm.crm_case. _get_default_email, 
118         'state': lambda *a: 'draft', 
119         'section_id':crm.crm_case. _get_section, 
120         'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
121         'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.case', context=c), 
122         'priority': lambda *a: crm.AVAILABLE_PRIORITIES[2][0],
123         #'stage_id': _get_stage_id, 
124     }
125     
126     def onchange_partner_id(self, cr, uid, ids, part, email=False):
127         """This function returns value of partner address based on partner
128         @param self: The object pointer
129         @param cr: the current row, from the database cursor,
130         @param uid: the current user’s ID for security checks,
131         @param ids: List of case IDs
132         @param part: Partner's id
133         @email: Partner's email ID
134         """
135         if not part:
136             return {'value': {'partner_address_id': False,
137                             'email_from': False, 
138                             'partner_phone': False,
139                             'partner_mobile': False
140                             }}
141         addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['contact'])
142         data = {'partner_address_id': addr['contact']}
143         data.update(self.onchange_partner_address_id(cr, uid, ids, addr['contact'])['value'])
144         return {'value': data}
145
146     def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
147         """This function returns value of partner email based on Partner Address
148         @param self: The object pointer
149         @param cr: the current row, from the database cursor,
150         @param uid: the current user’s ID for security checks,
151         @param ids: List of case IDs
152         @param add: Id of Partner's address
153         @email: Partner's email ID
154         """
155         if not add:
156             return {'value': {'email_from': False}}
157         address = self.pool.get('res.partner.address').browse(cr, uid, add)
158         return {'value': {'email_from': address.email, 'partner_phone': address.phone, 'partner_mobile': address.mobile}}
159         
160     def case_open(self, cr, uid, ids, *args):
161         """
162             Opens Claim
163         """
164         res = super(crm_claim, self).case_open(cr, uid, ids, *args)
165         claims = self.browse(cr, uid, ids)
166         
167         for i in xrange(0, len(ids)):
168             if not claims[i].stage_id :
169                 stage_id = self._find_first_stage(cr, uid, 'claim', claims[i].section_id.id or False)
170                 self.write(cr, uid, [ids[i]], {'stage_id' : stage_id})
171         
172         return res
173     
174     def message_new(self, cr, uid, msg, context=None):
175         """
176         Automatically calls when new email message arrives
177
178         @param self: The object pointer
179         @param cr: the current row, from the database cursor,
180         @param uid: the current user’s ID for security checks
181         """
182         mailgate_pool = self.pool.get('email.server.tools')
183
184         subject = msg.get('subject') or _("No Subject")
185         body = msg.get('body')
186         msg_from = msg.get('from')
187         priority = msg.get('priority')
188
189         vals = {
190             'name': subject,
191             'email_from': msg_from,
192             'email_cc': msg.get('cc'),
193             'description': body,
194             'user_id': False,
195         }
196         if msg.get('priority', False):
197             vals['priority'] = priority
198
199         res = mailgate_pool.get_partner(cr, uid, msg.get('from') or msg.get_unixfrom())
200         if res:
201             vals.update(res)
202
203         res = self.create(cr, uid, vals, context)
204         attachents = msg.get('attachments', [])
205         for attactment in attachents or []:
206             data_attach = {
207                 'name': attactment,
208                 'datas':binascii.b2a_base64(str(attachents.get(attactment))),
209                 'datas_fname': attactment,
210                 'description': 'Mail attachment',
211                 'res_model': self._name,
212                 'res_id': res,
213             }
214             self.pool.get('ir.attachment').create(cr, uid, data_attach)
215
216         return res
217
218     def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context=None):
219         """
220         @param self: The object pointer
221         @param cr: the current row, from the database cursor,
222         @param uid: the current user’s ID for security checks,
223         @param ids: List of update mail’s IDs 
224         """
225         if isinstance(ids, (str, int, long)):
226             ids = [ids]
227
228         if msg.get('priority') in dict(crm.AVAILABLE_PRIORITIES):
229             vals['priority'] = msg.get('priority')
230
231         maps = {
232             'cost':'planned_cost',
233             'revenue': 'planned_revenue',
234             'probability':'probability'
235         }
236         vls = {}
237         for line in msg['body'].split('\n'):
238             line = line.strip()
239             res = tools.misc.command_re.match(line)
240             if res and maps.get(res.group(1).lower()):
241                 key = maps.get(res.group(1).lower())
242                 vls[key] = res.group(2).lower()
243         vals.update(vls)
244
245         # Unfortunately the API is based on lists
246         # but we want to update the state based on the
247         # previous state, so we have to loop:
248         for case in self.browse(cr, uid, ids, context=context):
249             values = dict(vals)
250             if case.state in CRM_CLAIM_PENDING_STATES:
251                 values.update(state=crm.AVAILABLE_STATES[1][0]) #re-open
252             res = self.write(cr, uid, [case.id], values, context=context)
253         return res
254
255     def msg_send(self, cr, uid, id, *args, **argv):
256
257         """ Send The Message
258             @param self: The object pointer
259             @param cr: the current row, from the database cursor,
260             @param uid: the current user’s ID for security checks,
261             @param ids: List of email’s IDs
262             @param *args: Return Tuple Value
263             @param **args: Return Dictionary of Keyword Value
264         """
265         return True
266
267 crm_claim()
268
269 class res_partner(osv.osv):
270    
271     _inherit = 'res.partner'
272     _columns = {
273         'claims_ids': fields.one2many('crm.claim', 'partner_id', 'Claims'),
274     }
275 res_partner()
276
277 class crm_stage_claim(osv.osv):
278     
279     def _get_type_value(self, cr, user, context):
280         list = super(crm_stage_claim, self)._get_type_value(cr, user, context)
281         list.append(('claim','Claim'))
282         return list
283     
284     _inherit = "crm.case.stage"
285     _columns = {
286             'type': fields.selection(_get_type_value, 'Type'),
287     }
288    
289     
290 crm_stage_claim()
291
292
293 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: