[FIX] crm_helpdesk: change test's email data
[odoo/odoo.git] / addons / sale_crm / sale_crm.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 datetime import date
23 from openerp import tools
24 from dateutil.relativedelta import relativedelta
25 from openerp.osv import osv, fields
26
27 MONTHS = {
28     "monthly": 1,
29     "semesterly": 3,
30     "semiannually": 6,
31     "annually": 12
32 }
33
34 class sale_order(osv.osv):
35     _inherit = 'sale.order'
36     _columns = {
37         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
38         'categ_ids': fields.many2many('crm.case.categ', 'sale_order_category_rel', 'order_id', 'category_id', 'Categories', \
39             domain="['|',('section_id','=',section_id),('section_id','=',False), ('object_id.model', '=', 'crm.lead')]")
40     }
41
42     def _make_invoice(self, cr, uid, order, lines, context=None):
43         if order.section_id:
44             context = dict(context or {}, default_section_id= order.section_id.id)
45         return super(sale_order, self)._make_invoice(cr, uid, order, lines, context=context)
46
47
48 class crm_case_section(osv.osv):
49     _inherit = 'crm.case.section'
50
51     def _get_created_quotation_per_duration(self, cr, uid, ids, field_name, arg, context=None):
52         res = dict.fromkeys(ids, [])
53         obj = self.pool.get('sale.order')
54         first_day = date.today().replace(day=1)
55
56         for section in self.browse(cr, uid, ids, context=context):
57             dates = [first_day + relativedelta(months=-(MONTHS[section.target_duration]*(key+1)-1)) for key in range(0, 5)]
58             rate_invoice = []
59             for when in range(0, 5):
60                 domain = [("section_id", "=", section.id), ('state', 'in', ['draft', 'sent']), ('date_order', '>=', dates[when].strftime(tools.DEFAULT_SERVER_DATE_FORMAT))]
61                 if when:
62                     domain += [('date_order', '<', dates[when-1].strftime(tools.DEFAULT_SERVER_DATE_FORMAT))]
63                 rate = 0
64                 order_ids = obj.search(cr, uid, domain, context=context)
65                 for order in obj.browse(cr, uid, order_ids, context=context):
66                     rate += order.amount_total
67                 rate_invoice.append(rate)
68             rate_invoice.reverse()
69             res[section.id] = rate_invoice
70         return res
71
72     def _get_validate_saleorder_per_duration(self, cr, uid, ids, field_name, arg, context=None):
73         res = dict.fromkeys(ids, [])
74         obj = self.pool.get('sale.order')
75         first_day = date.today().replace(day=1)
76
77         for section in self.browse(cr, uid, ids, context=context):
78             dates = [first_day + relativedelta(months=-(MONTHS[section.target_duration]*(key+1)-1)) for key in range(0, 5)]
79             rate_invoice = []
80             for when in range(0, 5):
81                 domain = [("section_id", "=", section.id), ('state', 'not in', ['draft', 'sent']), ('date_confirm', '>=', dates[when].strftime(tools.DEFAULT_SERVER_DATE_FORMAT))]
82                 if when:
83                     domain += [('date_confirm', '<', dates[when-1].strftime(tools.DEFAULT_SERVER_DATE_FORMAT))]
84                 rate = 0
85                 order_ids = obj.search(cr, uid, domain, context=context)
86                 for order in obj.browse(cr, uid, order_ids, context=context):
87                     rate += order.amount_total
88                 rate_invoice.append(rate)
89             rate_invoice.reverse()
90             res[section.id] = rate_invoice
91         return res
92
93     def _get_sent_invoice_per_duration(self, cr, uid, ids, field_name, arg, context=None):
94         res = dict.fromkeys(ids, [])
95         obj = self.pool.get('account.invoice.report')
96         first_day = date.today().replace(day=1)
97
98         for section in self.browse(cr, uid, ids, context=context):
99             dates = [first_day + relativedelta(months=-(MONTHS[section.target_duration]*(key+1)-1)) for key in range(0, 5)]
100             rate_invoice = []
101             for when in range(0, 5):
102                 domain = [("section_id", "=", section.id), ('state', 'not in', ['draft', 'cancel']), ('date', '>=', dates[when].strftime(tools.DEFAULT_SERVER_DATE_FORMAT))]
103                 if when:
104                     domain += [('date', '<', dates[when-1].strftime(tools.DEFAULT_SERVER_DATE_FORMAT))]
105                 rate = 0
106                 invoice_ids = obj.search(cr, uid, domain, context=context)
107                 for invoice in obj.browse(cr, uid, invoice_ids, context=context):
108                     rate += invoice.price_total
109                 rate_invoice.append(rate)
110             rate_invoice.reverse()
111             res[section.id] = rate_invoice
112         return res
113
114     _columns = {
115         'quotation_ids': fields.one2many('sale.order', 'section_id',
116             string='Quotations', readonly=True,
117             domain=[('state', 'in', ['draft', 'sent', 'cancel'])]),
118         'sale_order_ids': fields.one2many('sale.order', 'section_id',
119             string='Sale Orders', readonly=True,
120             domain=[('state', 'not in', ['draft', 'sent', 'cancel'])]),
121         'invoice_ids': fields.one2many('account.invoice', 'section_id',
122             string='Invoices', readonly=True,
123             domain=[('state', 'not in', ['draft', 'cancel'])]),
124
125         'forecast': fields.integer(string='Total forecast'),
126         'target_invoice': fields.integer(string='Invoicing Target'),
127         'created_quotation_per_duration': fields.function(_get_created_quotation_per_duration, string='Rate of created quotation per duration', type="string", readonly=True),
128         'validate_saleorder_per_duration': fields.function(_get_validate_saleorder_per_duration, string='Rate of validate sales orders per duration', type="string", readonly=True),
129         'sent_invoice_per_duration': fields.function(_get_sent_invoice_per_duration, string='Rate of sent invoices per duration', type="string", readonly=True),
130     }
131
132     def action_forecast(self, cr, uid, id, value, context=None):
133         return self.write(cr, uid, [id], {'forecast': value}, context=context)
134
135 class res_users(osv.Model):
136     _inherit = 'res.users'
137     _columns = {
138         'default_section_id': fields.many2one('crm.case.section', 'Default Sales Team'),
139     }
140
141
142 class sale_crm_lead(osv.Model):
143     _inherit = 'crm.lead'
144
145     def on_change_user(self, cr, uid, ids, user_id, context=None):
146         """ Override of on change user_id on lead/opportunity; when having sale
147             the new logic is :
148             - use user.default_section_id
149             - or fallback on previous behavior """
150         if user_id:
151             user = self.pool.get('res.users').browse(cr, uid, user_id, context=context)
152             if user.default_section_id and user.default_section_id.id:
153                 return {'value': {'section_id': user.default_section_id.id}}
154         return super(sale_crm_lead, self).on_change_user(cr, uid, ids, user_id, context=context)
155
156
157 class account_invoice(osv.osv):
158     _inherit = 'account.invoice'
159     _columns = {
160         'section_id': fields.many2one('crm.case.section', 'Sales Team'),
161     }
162     _defaults = {
163         'section_id': lambda self, cr, uid, c=None: self.pool.get('res.users').browse(cr, uid, uid, c).default_section_id.id or False,
164     }
165
166 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: