[MERGE]
[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-today OpenERP SA (<http://www.openerp.com>)
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 base_status.base_stage import base_stage
23 import binascii
24 from crm import crm
25 from osv import fields, osv
26 import time
27 import tools
28 from tools.translate import _
29
30 CRM_CLAIM_PENDING_STATES = (
31     crm.AVAILABLE_STATES[2][0], # Cancelled
32     crm.AVAILABLE_STATES[3][0], # Done
33     crm.AVAILABLE_STATES[4][0], # Pending
34 )
35
36 class crm_claim_stage(osv.osv):
37     """ Model for claim stages. This models the main stages of a claim
38         management flow. Main CRM objects (leads, opportunities, project 
39         issues, ...) will now use only stages, instead of state and stages.
40         Stages are for example used to display the kanban view of records.
41     """
42     _name = "crm.claim.stage"
43     _description = "Claim stages"
44     _rec_name = 'name'
45     _order = "sequence"
46
47     _columns = {
48         'name': fields.char('Stage Name', size=64, required=True, translate=True),
49         'sequence': fields.integer('Sequence', help="Used to order stages. Lower is better."),
50         'section_ids':fields.many2many('crm.case.section', 'section_claim_stage_rel', 'stage_id', 'section_id', string='Sections',
51                         help="Link between stages and sales teams. When set, this limitate the current stage to the selected sales teams."),
52         'state': fields.selection(crm.AVAILABLE_STATES, 'State', required=True, help="The related state for the stage. The state of your document will automatically change regarding the selected stage. For example, if a stage is related to the state 'Close', when your document reaches this stage, it will be automatically have the 'closed' state."),
53         'case_refused': fields.boolean('Refused stage',
54                         help='Refused stages are specific stages for done.'),
55         'case_default': fields.boolean('Common to All Teams',
56                         help="If you check this field, this stage will be proposed by default on each sales team. It will not assign this stage to existing teams."),
57         'fold': fields.boolean('Hide in Views when Empty',
58                         help="This stage is not visible, for example in status bar or kanban view, when there are no records in that stage to display."),
59     }
60
61     _defaults = {
62         'sequence': lambda *args: 1,
63         'state': 'draft',
64         'fold': False,
65         'case_refused': False,
66     }
67
68 class crm_claim(base_stage, osv.osv):
69     """ Crm claim
70     """
71     _name = "crm.claim"
72     _description = "Claim"
73     _order = "priority,date desc"
74     _inherit = ['mail.thread']
75
76     _columns = {
77         'id': fields.integer('ID', readonly=True),
78         'name': fields.char('Claim Subject', size=128, required=True),
79         'active': fields.boolean('Active'),
80         'action_next': fields.char('Next Action', size=200),
81         'date_action_next': fields.datetime('Next Action Date'),
82         'description': fields.text('Description'),
83         'resolution': fields.text('Resolution'),
84         'create_date': fields.datetime('Creation Date' , readonly=True),
85         'write_date': fields.datetime('Update Date' , readonly=True),
86         'date_deadline': fields.date('Deadline'),
87         'date_closed': fields.datetime('Closed', readonly=True),
88         'date': fields.datetime('Claim Date', select=True),
89         'ref' : fields.reference('Reference', selection=crm._links_get, size=128),
90         'categ_id': fields.many2one('crm.case.categ', 'Category', \
91                             domain="[('section_id','=',section_id),\
92                             ('object_id.model', '=', 'crm.claim')]"),
93         'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'),
94         'type_action': fields.selection([('correction','Corrective Action'),('prevention','Preventive Action')], 'Action Type'),
95         'user_id': fields.many2one('res.users', 'Responsible'),
96         'user_fault': fields.char('Trouble Responsible', size=64),
97         'section_id': fields.many2one('crm.case.section', 'Sales Team', \
98                         select=True, help="Sales team to which Case belongs to."\
99                                 "Define Responsible user and Email account for"\
100                                 " mail gateway."),
101         'company_id': fields.many2one('res.company', 'Company'),
102         'partner_id': fields.many2one('res.partner', 'Partner'),
103         '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"),
104         'email_from': fields.char('Email', size=128, help="These people will receive email."),
105         'partner_phone': fields.char('Phone', size=32),
106         'stage_id': fields.many2one ('crm.claim.stage', 'Stage',
107                         domain="['|', ('section_ids', '=', section_id), ('case_default', '=', True)]"), 
108         'cause': fields.text('Root Cause'),
109         'state': fields.related('stage_id', 'state', type="selection", store=True,
110                 selection=crm.AVAILABLE_STATES, string="State", readonly=True,
111                 help='The state is set to \'Draft\', when a case is created.\
112                       If the case is in progress the state is set to \'Open\'.\
113                       When the case is over, the state is set to \'Done\'.\
114                       If the case needs to be reviewed then the state is \
115                       set to \'Pending\'.'),
116     }
117
118     _defaults = {
119         'user_id':  lambda s, cr, uid, c: s._get_default_user(cr, uid, c),
120         'partner_id':  lambda s, cr, uid, c: s._get_default_partner(cr, uid, c),
121         'email_from': lambda s, cr, uid, c: s._get_default_email(cr, uid, c),
122         'section_id': lambda s, cr, uid, c: s._get_default_section_id(cr, uid, c),
123         'date': fields.datetime.now,
124         'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.case', context=c),
125         'priority': lambda *a: crm.AVAILABLE_PRIORITIES[2][0],
126         'active': lambda *a: 1
127     }
128
129     def stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None):
130         """ Override of the base.stage method
131             Parameter of the stage search taken from the lead:
132             - section_id: if set, stages must belong to this section or
133               be a default case
134         """
135         if isinstance(cases, (int, long)):
136             cases = self.browse(cr, uid, cases, context=context)
137         # collect all section_ids
138         section_ids = []
139         if section_id:
140             section_ids.append(section_id)
141         for claim in cases:
142             if claim.section_id:
143                 section_ids.append(claim.section_id.id)
144         # OR all section_ids and OR with case_default
145         search_domain = []
146         if section_ids:
147             search_domain += [('|')] * len(section_ids)
148             for section_id in section_ids:
149                 search_domain.append(('section_ids', '=', section_id))
150         search_domain.append(('case_default', '=', True))
151         # AND with the domain in parameter
152         search_domain += list(domain)
153         # perform search, return the first found
154         stage_ids = self.pool.get('crm.claim.stage').search(cr, uid, search_domain, order=order, context=context)
155         if stage_ids:
156             return stage_ids[0]
157         return False
158
159     def create(self, cr, uid, vals, context=None):
160         obj_id = super(crm_claim, self).create(cr, uid, vals, context)
161         self.create_send_note(cr, uid, [obj_id], context=context)
162         return obj_id
163
164     def case_refuse(self, cr, uid, ids, context=None):
165         """ Mark the case as refused: state=done and case_refused=True """
166         for lead in self.browse(cr, uid, ids):
167             stage_id = self.stage_find(cr, uid, [lead], lead.section_id.id or False, ['&', ('state', '=', 'done'), ('case_refused', '=', True)], context=context)
168             if stage_id:
169                 self.case_set(cr, uid, [lead.id], values_to_update={}, new_stage_id=stage_id, context=context)
170         return self.case_refuse_send_note(cr, uid, ids, context=context)
171
172     def onchange_partner_id(self, cr, uid, ids, part, email=False):
173         """This function returns value of partner address based on partner
174            :param part: Partner's id
175            :param email: ignored
176         """
177         if not part:
178             return {'value': {'email_from': False,
179                               'partner_phone': False
180                             }
181                    }
182         address = self.pool.get('res.partner').browse(cr, uid, part)
183         return {'value': {'email_from': address.email, 'partner_phone': address.phone}}
184
185     # -------------------------------------------------------
186     # Mail gateway
187     # -------------------------------------------------------
188
189     def message_new(self, cr, uid, msg, custom_values=None, context=None):
190         """ Overrides mail_thread message_new that is called by the mailgateway
191             through message_process.
192             This override updates the document according to the email.
193         """
194         if custom_values is None: custom_values = {}
195         custom_values.update({
196             'name': msg.get('subject') or _("No Subject"),
197             'description': msg.get('body'),
198             'email_from': msg.get('from'),
199             'email_cc': msg.get('cc'),
200         })
201         if msg.get('priority'):
202             custom_values['priority'] = msg.get('priority')
203         return super(crm_claim,self).message_new(cr, uid, msg, custom_values=custom_values, context=context)
204
205     def message_update(self, cr, uid, ids, msg, update_vals=None, context=None):
206         """ Overrides mail_thread message_update that is called by the mailgateway
207             through message_process.
208             This method updates the document according to the email.
209         """
210         if isinstance(ids, (str, int, long)):
211             ids = [ids]
212         if update_vals is None: update_vals = {}
213
214         if msg.get('priority') in dict(crm.AVAILABLE_PRIORITIES):
215             update_vals['priority'] = msg.get('priority')
216
217         maps = {
218             'cost':'planned_cost',
219             'revenue': 'planned_revenue',
220             'probability':'probability'
221         }
222         for line in msg['body'].split('\n'):
223             line = line.strip()
224             res = tools.misc.command_re.match(line)
225             if res and maps.get(res.group(1).lower()):
226                 key = maps.get(res.group(1).lower())
227                 update_vals[key] = res.group(2).lower()
228
229         return  super(crm_claim,self).message_update(cr, uid, ids, msg, update_vals=update_vals, context=context)
230
231     # ---------------------------------------------------
232     # OpenChatter methods and notifications
233     # ---------------------------------------------------
234
235     def case_get_note_msg_prefix(self, cr, uid, id, context=None):
236         """ Override of default prefix for notifications. """
237         return 'Claim'
238
239     def create_send_note(self, cr, uid, ids, context=None):
240         msg = _('Claim has been <b>created</b>.')
241         return self.message_post(cr, uid, ids, body=msg, context=context)
242
243     def case_refuse_send_note(self, cr, uid, ids, context=None):
244         msg = _('Claim has been <b>refused</b>.')
245         return self.message_post(cr, uid, ids, body=msg, context=context)
246
247     def stage_set_send_note(self, cr, uid, ids, stage_id, context=None):
248         """ Override of the (void) default notification method. """
249         stage_name = self.pool.get('crm.claim.stage').name_get(cr, uid, [stage_id], context=context)[0][1]
250         return self.message_post(cr, uid, ids, body= _("Stage changed to <b>%s</b>.") % (stage_name), context=context)
251
252
253 class res_partner(osv.osv):
254     _inherit = 'res.partner'
255     _columns = {
256         'claims_ids': fields.one2many('crm.claim', 'partner_id', 'Claims'),
257     }
258
259 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: