1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>)
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 ##############################################################################
23 from datetime import date, datetime
24 from dateutil import relativedelta
26 from openerp import tools
27 from openerp.osv import fields
28 from openerp.osv import osv
30 AVAILABLE_PRIORITIES = [
38 class crm_case_channel(osv.osv):
39 _name = "crm.case.channel"
40 _description = "Channels"
43 'name': fields.char('Channel Name', size=64, required=True),
44 'active': fields.boolean('Active'),
47 'active': lambda *a: 1,
50 class crm_case_stage(osv.osv):
51 """ Model for case stages. This models the main stages of a document
52 management flow. Main CRM objects (leads, opportunities, project
53 issues, ...) will now use only stages, instead of state and stages.
54 Stages are for example used to display the kanban view of records.
56 _name = "crm.case.stage"
57 _description = "Stage of case"
62 'name': fields.char('Stage Name', size=64, required=True, translate=True),
63 'sequence': fields.integer('Sequence', help="Used to order stages. Lower is better."),
64 'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"),
65 'on_change': fields.boolean('Change Probability Automatically', help="Setting this stage will change the probability automatically on the opportunity."),
66 'requirements': fields.text('Requirements'),
67 'section_ids': fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', string='Sections',
68 help="Link between stages and sales teams. When set, this limitate the current stage to the selected sales teams."),
69 'case_default': fields.boolean('Default to New Sales Team',
70 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."),
71 'fold': fields.boolean('Folded in Kanban View',
72 help='This stage is folded in the kanban view when'
73 'there are no records in that stage to display.'),
74 'type': fields.selection([('lead', 'Lead'),
75 ('opportunity', 'Opportunity'),
77 string='Type', size=16, required=True,
78 help="This field is used to distinguish stages related to Leads from stages related to Opportunities, or to specify stages available for both types."),
91 class crm_case_section(osv.osv):
92 """ Model for sales teams. """
93 _name = "crm.case.section"
94 _inherits = {'mail.alias': 'alias_id'}
95 _inherit = "mail.thread"
96 _description = "Sales Teams"
97 _order = "complete_name"
98 # number of periods for lead/opportunities/... tracking in salesteam kanban dashboard/kanban view
101 def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
102 return dict(self.name_get(cr, uid, ids, context=context))
104 def __get_bar_values(self, cr, uid, obj, domain, read_fields, value_field, groupby_field, context=None):
105 """ Generic method to generate data for bar chart values using SparklineBarWidget.
106 This method performs obj.read_group(cr, uid, domain, read_fields, groupby_field).
108 :param obj: the target model (i.e. crm_lead)
109 :param domain: the domain applied to the read_group
110 :param list read_fields: the list of fields to read in the read_group
111 :param str value_field: the field used to compute the value of the bar slice
112 :param str groupby_field: the fields used to group
114 :return list section_result: a list of dicts: [
115 { 'value': (int) bar_column_value,
116 'tootip': (str) bar_column_tooltip,
120 month_begin = date.today().replace(day=1)
123 'tooltip': (month_begin + relativedelta.relativedelta(months=-i)).strftime('%B'),
124 } for i in range(self._period_number - 1, -1, -1)]
125 group_obj = obj.read_group(cr, uid, domain, read_fields, groupby_field, context=context)
126 for group in group_obj:
127 group_begin_date = datetime.strptime(group['__domain'][0][2], tools.DEFAULT_SERVER_DATE_FORMAT)
128 month_delta = relativedelta.relativedelta(month_begin, group_begin_date)
129 section_result[self._period_number - (month_delta.months + 1)] = {'value': group.get(value_field, 0), 'tooltip': group_begin_date.strftime('%B')}
130 return section_result
132 def _get_opportunities_data(self, cr, uid, ids, field_name, arg, context=None):
133 """ Get opportunities-related data for salesteam kanban view
134 monthly_open_leads: number of open lead during the last months
135 monthly_planned_revenue: planned revenu of opportunities during the last months
137 obj = self.pool.get('crm.lead')
138 res = dict.fromkeys(ids, False)
139 month_begin = date.today().replace(day=1)
140 date_begin = month_begin - relativedelta.relativedelta(months=self._period_number - 1)
141 date_end = month_begin.replace(day=calendar.monthrange(month_begin.year, month_begin.month)[1])
142 date_domain = [('create_date', '>=', date_begin.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)), ('create_date', '<=', date_end.strftime(tools.DEFAULT_SERVER_DATE_FORMAT))]
145 lead_domain = date_domain + [('type', '=', 'lead'), ('section_id', '=', id)]
146 res[id]['monthly_open_leads'] = self.__get_bar_values(cr, uid, obj, lead_domain, ['create_date'], 'create_date_count', 'create_date', context=context)
147 opp_domain = date_domain + [('type', '=', 'opportunity'), ('section_id', '=', id)]
148 res[id]['monthly_planned_revenue'] = self.__get_bar_values(cr, uid, obj, opp_domain, ['planned_revenue', 'create_date'], 'planned_revenue', 'create_date', context=context)
152 'name': fields.char('Sales Team', size=64, required=True, translate=True),
153 'complete_name': fields.function(get_full_name, type='char', size=256, readonly=True, store=True),
154 'code': fields.char('Code', size=8),
155 'active': fields.boolean('Active', help="If the active field is set to "\
156 "true, it will allow you to hide the sales team without removing it."),
157 'change_responsible': fields.boolean('Reassign Escalated', help="When escalating to this team override the salesman with the team leader."),
158 'user_id': fields.many2one('res.users', 'Team Leader'),
159 'member_ids': fields.many2many('res.users', 'sale_member_rel', 'section_id', 'member_id', 'Team Members'),
160 'reply_to': fields.char('Reply-To', size=64, help="The email address put in the 'Reply-To' of all emails sent by OpenERP about cases in this sales team"),
161 'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
162 'child_ids': fields.one2many('crm.case.section', 'parent_id', 'Child Teams'),
163 'resource_calendar_id': fields.many2one('resource.calendar', "Working Time", help="Used to compute open days"),
164 'note': fields.text('Description'),
165 'working_hours': fields.float('Working Hours', digits=(16, 2)),
166 'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
167 'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="restrict", required=True,
168 help="The email address associated with this team. New emails received will automatically "
169 "create new leads assigned to the team."),
170 'color': fields.integer('Color Index'),
171 'use_leads': fields.boolean('Leads',
172 help="The first contact you get with a potential customer is a lead you qualify before converting it into a real business opportunity. Check this box to manage leads in this sales team."),
174 'monthly_open_leads': fields.function(_get_opportunities_data,
175 type="string", readonly=True, multi='_get_opportunities_data',
176 string='Open Leads per Month'),
177 'monthly_planned_revenue': fields.function(_get_opportunities_data,
178 type="string", readonly=True, multi='_get_opportunities_data',
179 string='Planned Revenue per Month')
182 def _get_stage_common(self, cr, uid, context):
183 ids = self.pool.get('crm.case.stage').search(cr, uid, [('case_default', '=', 1)], context=context)
188 'stage_ids': _get_stage_common,
193 ('code_uniq', 'unique (code)', 'The code of the sales team must be unique !')
197 (osv.osv._check_recursion, 'Error ! You cannot create recursive Sales team.', ['parent_id'])
200 def name_get(self, cr, uid, ids, context=None):
201 """Overrides orm name_get method"""
202 if not isinstance(ids, list):
207 reads = self.read(cr, uid, ids, ['name', 'parent_id'], context)
210 name = record['name']
211 if record['parent_id']:
212 name = record['parent_id'][1] + ' / ' + name
213 res.append((record['id'], name))
216 def create(self, cr, uid, vals, context=None):
219 create_context = dict(context, alias_model_name='crm.lead', alias_parent_model_name=self._name)
220 section_id = super(crm_case_section, self).create(cr, uid, vals, context=create_context)
221 section = self.browse(cr, uid, section_id, context=context)
222 self.pool.get('mail.alias').write(cr, uid, [section.alias_id.id], {'alias_parent_thread_id': section_id, 'alias_defaults': {'section_id': section_id, 'type': 'lead'}}, context=context)
225 def unlink(self, cr, uid, ids, context=None):
226 # Cascade-delete mail aliases as well, as they should not exist without the sales team.
227 mail_alias = self.pool.get('mail.alias')
228 alias_ids = [team.alias_id.id for team in self.browse(cr, uid, ids, context=context) if team.alias_id]
229 res = super(crm_case_section, self).unlink(cr, uid, ids, context=context)
230 mail_alias.unlink(cr, uid, alias_ids, context=context)
233 class crm_case_categ(osv.osv):
234 """ Category of Case """
235 _name = "crm.case.categ"
236 _description = "Category of Case"
238 'name': fields.char('Name', size=64, required=True, translate=True),
239 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
240 'object_id': fields.many2one('ir.model', 'Object Name'),
242 def _find_object_id(self, cr, uid, context=None):
243 """Finds id for case object"""
244 context = context or {}
245 object_id = context.get('object_id', False)
246 ids = self.pool.get('ir.model').search(cr, uid, ['|',('id', '=', object_id),('model', '=', context.get('object_name', False))])
247 return ids and ids[0] or False
249 'object_id' : _find_object_id
252 class crm_case_resource_type(osv.osv):
253 """ Resource Type of case """
254 _name = "crm.case.resource.type"
255 _description = "Campaign"
258 'name': fields.char('Campaign Name', size=64, required=True, translate=True),
259 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
262 class crm_payment_mode(osv.osv):
263 """ Payment Mode for Fund """
264 _name = "crm.payment.mode"
265 _description = "CRM Payment Mode"
267 'name': fields.char('Name', size=64, required=True),
268 'section_id': fields.many2one('crm.case.section', 'Sales Team'),
272 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: