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