557f048a3eb51c09c3bd0e2fe9ff6ad689913135
[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 base_status.base_stage import base_stage
23 from osv import fields, osv
24 from crm import crm
25 import time
26 from crm import wizard
27 import binascii
28 import tools
29 from tools.translate import _
30
31 wizard.mail_compose_message.SUPPORTED_MODELS.append('crm.claim')
32 CRM_CLAIM_PENDING_STATES = (
33     crm.AVAILABLE_STATES[2][0], # Cancelled
34     crm.AVAILABLE_STATES[3][0], # Done
35     crm.AVAILABLE_STATES[4][0], # Pending
36 )
37
38
39 class crm_claim(base_stage, osv.osv):
40     """ Crm claim
41     """
42     _name = "crm.claim"
43     _description = "Claim"
44     _order = "priority,date desc"
45     _inherit = ['mail.thread']
46     _columns = {
47         'id': fields.integer('ID', readonly=True),
48         'name': fields.char('Claim Subject', size=128, required=True),
49         'active': fields.boolean('Active'),
50         'action_next': fields.char('Next Action', size=200),
51         'date_action_next': fields.datetime('Next Action Date'),
52         'description': fields.text('Description'),
53         'resolution': fields.text('Resolution'),
54         'create_date': fields.datetime('Creation Date' , readonly=True),
55         'write_date': fields.datetime('Update Date' , readonly=True),
56         'date_deadline': fields.date('Deadline'),
57         'date_closed': fields.datetime('Closed', readonly=True),
58         'date': fields.datetime('Claim Date', select=True),
59         'ref' : fields.reference('Reference', selection=crm._links_get, size=128),
60         'categ_id': fields.many2one('crm.case.categ', 'Category', \
61                             domain="[('section_id','=',section_id),\
62                             ('object_id.model', '=', 'crm.claim')]"),
63         'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'),
64         'type_action': fields.selection([('correction','Corrective Action'),('prevention','Preventive Action')], 'Action Type'),
65         'user_id': fields.many2one('res.users', 'Responsible'),
66         'user_fault': fields.char('Trouble Responsible', size=64),
67         'section_id': fields.many2one('crm.case.section', 'Sales Team', \
68                         select=True, help="Sales team to which Case belongs to."\
69                                 "Define Responsible user and Email account for"\
70                                 " mail gateway."),
71         'company_id': fields.many2one('res.company', 'Company'),
72         'partner_id': fields.many2one('res.partner', 'Partner'),
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="[('section_ids', '=', section_id)]"), 
77         'cause': fields.text('Root Cause'),
78         'state': fields.related('stage_id', 'state', type="selection", store=True,
79                 selection=crm.AVAILABLE_STATES, string="State", readonly=True,
80                 help='The state is set to \'Draft\', when a case is created.\
81                       If the case is in progress the state is set to \'Open\'.\
82                       When the case is over, the state is set to \'Done\'.\
83                       If the case needs to be reviewed then the state is \
84                       set to \'Pending\'.'),
85         'message_ids': fields.one2many('mail.message', 'res_id', 'Messages', domain=[('model','=',_name)]),
86     }
87
88     _defaults = {
89         'user_id':  lambda s, cr, uid, c: s._get_default_user(cr, uid, c),
90         'partner_id':  lambda s, cr, uid, c: s._get_default_partner(cr, uid, c),
91         'email_from': lambda s, cr, uid, c: s._get_default_email(cr, uid, c),
92         'section_id': lambda s, cr, uid, c: s._get_default_section_id(cr, uid, c),
93         'date': fields.datetime.now,
94         'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.case', context=c),
95         'priority': lambda *a: crm.AVAILABLE_PRIORITIES[2][0],
96         'active': lambda *a: 1
97     }
98
99     def stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None):
100         """ Override of the base.stage method
101             Parameter of the stage search taken from the lead:
102             - type: stage type must be the same or 'both'
103             - section_id: if set, stages must belong to this section or
104               be a default case
105         """
106         if isinstance(cases, (int, long)):
107             cases = self.browse(cr, uid, cases, context=context)
108         domain = list(domain)
109         if section_id:
110                 domain += ['|', ('section_ids', '=', section_id), ('case_default', '=', True)]
111         for lead in cases:
112             lead_section_id = lead.section_id.id if lead.section_id else None
113             if lead_section_id:
114                 domain += ['|', ('section_ids', '=', lead_section_id), ('case_default', '=', True)]
115         stage_ids = self.pool.get('crm.case.stage').search(cr, uid, domain, order=order, context=context)
116         if stage_ids:
117             return stage_ids[0]
118         return False
119
120     def case_get_note_msg_prefix(self, cr, uid, id, context=None):
121         return 'Claim'
122
123     def onchange_partner_id(self, cr, uid, ids, part, email=False):
124         """This function returns value of partner address based on partner
125            :param part: Partner's id
126            :param email: ignored
127         """
128         if not part:
129             return {'value': {'email_from': False,
130                               'partner_phone': False
131                             }
132                    }
133         address = self.pool.get('res.partner').browse(cr, uid, part)
134         return {'value': {'email_from': address.email, 'partner_phone': address.phone}}
135     
136     def message_new(self, cr, uid, msg, custom_values=None, context=None):
137         """Automatically called when new email message arrives"""
138         res_id = super(crm_claim,self).message_new(cr, uid, msg, custom_values=custom_values, context=context)
139         subject = msg.get('subject')
140         body = msg.get('body_text')
141         msg_from = msg.get('from')
142         priority = msg.get('priority')
143         vals = {
144             'name': subject,
145             'email_from': msg_from,
146             'email_cc': msg.get('cc'),
147             'description': body,
148             'user_id': False,
149         }
150         if priority:
151             vals['priority'] = priority
152         vals.update(self.message_partner_by_email(cr, uid, msg.get('from', False)))
153         self.write(cr, uid, [res_id], vals, context=context)
154         return res_id
155
156     def message_update(self, cr, uid, ids, msg, vals={}, default_act='pending', context=None):
157         if isinstance(ids, (str, int, long)):
158             ids = [ids]
159
160         res_id = super(crm_claim,self).message_update(cr, uid, ids, msg, context=context)
161
162         if msg.get('priority') in dict(crm.AVAILABLE_PRIORITIES):
163             vals['priority'] = msg.get('priority')
164
165         maps = {
166             'cost':'planned_cost',
167             'revenue': 'planned_revenue',
168             'probability':'probability'
169         }
170         vls = {}
171         for line in msg['body_text'].split('\n'):
172             line = line.strip()
173             res = tools.misc.command_re.match(line)
174             if res and maps.get(res.group(1).lower()):
175                 key = maps.get(res.group(1).lower())
176                 vls[key] = res.group(2).lower()
177         vals.update(vls)
178
179         # Unfortunately the API is based on lists
180         # but we want to update the state based on the
181         # previous state, so we have to loop:
182         for case in self.browse(cr, uid, ids, context=context):
183             values = dict(vals)
184             if case.state in CRM_CLAIM_PENDING_STATES:
185                 values.update(state=crm.AVAILABLE_STATES[1][0]) #re-open
186             res = self.write(cr, uid, [case.id], values, context=context)
187         return res
188
189 class res_partner(osv.osv):
190     _inherit = 'res.partner'
191     _columns = {
192         'claims_ids': fields.one2many('crm.claim', 'partner_id', 'Claims'),
193     }
194
195 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: