[IMP]: crm: Apply doc string + optimization
[odoo/odoo.git] / addons / crm / crm_segmentation.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 osv import fields,osv,orm
23
24 import crm_operators
25
26
27 class crm_segmentation(osv.osv):
28     '''
29         A segmentation is a tool to automatically assign categories on partners.
30         These assignations are based on criterions.
31     '''
32     _name = "crm.segmentation"
33     _description = "Partner Segmentation"
34
35     _columns = {
36         'name': fields.char('Name', size=64, required=True, help='The name of the segmentation.'),
37         'description': fields.text('Description'),
38         'categ_id': fields.many2one('res.partner.category', 'Partner Category',\
39                          required=True, help='The partner category that will be \
40                          added to partners that match the segmentation criterions after computation.'),
41         'exclusif': fields.boolean('Exclusive', help='Check if the category is \
42                         limited to partners that match the segmentation criterions.\
43                         If checked, remove the category from partners that doesn\'t \
44                         match segmentation criterions'),
45         'state': fields.selection([('not running','Not Running'),\
46                     ('running','Running')], 'Execution Status', readonly=True),
47         'partner_id': fields.integer('Max Partner ID processed'),
48         'segmentation_line': fields.one2many('crm.segmentation.line', \
49                             'segmentation_id', 'Criteria', required=True),
50         'som_interval': fields.integer('Days per Periode', help="A period is the \
51                         average number of days between two cycle of sale or\
52                         purchase for this segmentation. It's mainly used to\
53                         detect if a partner has not purchased or buy for a too \
54                         long time, so we suppose that his state of mind has \
55                         decreased because he probably bought goods to another \
56                         supplier. Use this functionality for recurring businesses."),
57         'som_interval_max': fields.integer('Max Interval', help="The computation \
58                             is made on all events that occured during this \
59                             interval, the past X periods."),
60         'som_interval_decrease': fields.float('Decrease (0>1)', help="If the \
61                                      partner has not purchased (or bought) \
62                                      during a period, decrease the state of \
63                                      mind by this factor. It\'s a multiplication"),
64         'som_interval_default': fields.float('Default (0=None)', help="Default \
65                                      state of mind for period preceeding the \
66                                      'Max Interval' computation. This is the \
67                                      starting state of mind by default if the \
68                                      partner has no event."),
69         'sales_purchase_active': fields.boolean('Use The Sales Purchase Rules',\
70                                      help='Check if you want to use this tab as\
71                                     part of the segmentation rule. If not \
72                                     checked, the criteria beneath will be ignored')
73     }
74     _defaults = {
75         'partner_id': lambda *a: 0,
76         'state': lambda *a: 'not running',
77         'som_interval_max': lambda *a: 3,
78         'som_interval_decrease': lambda *a: 0.8,
79         'som_interval_default': lambda *a: 0.5
80     }
81
82     def process_continue(self, cr, uid, ids, start=False):
83
84         """ @param self: The object pointer
85             @param cr: the current row, from the database cursor,
86             @param uid: the current user’s ID for security checks,
87             @param ids: List of Process continue’s IDs"""
88
89         categs = self.read(cr, uid, ids, ['categ_id', 'exclusif', 'partner_id',\
90                                  'sales_purchase_active', 'profiling_active'])
91         for categ in categs:
92             if start:
93                 if categ['exclusif']:
94                     cr.execute('delete from res_partner_category_rel \
95                             where category_id=%s', (categ['categ_id'][0],))
96
97             id = categ['id']
98
99             cr.execute('select id from res_partner order by id ')
100             partners = [x[0] for x in cr.fetchall()]
101
102             if categ['sales_purchase_active']:
103                 to_remove_list=[]
104                 cr.execute('select id from crm_segmentation_line where segmentation_id=%s', (id,))
105                 line_ids = [x[0] for x in cr.fetchall()]
106
107                 for pid in partners:
108                     if (not self.pool.get('crm.segmentation.line').test(cr, uid, line_ids, pid)):
109                         to_remove_list.append(pid)
110                 for pid in to_remove_list:
111                     partners.remove(pid)
112
113             for partner_id in partners:
114                 cr.execute('insert into res_partner_category_rel (category_id,partner_id) \
115                         values (%s,%s)', (categ['categ_id'][0], partner_id))
116             cr.commit()
117
118             self.write(cr, uid, [id], {'state':'not running', 'partner_id':0})
119             cr.commit()
120         return True
121
122     def process_stop(self, cr, uid, ids, *args):
123
124         """ @param self: The object pointer
125             @param cr: the current row, from the database cursor,
126             @param uid: the current user’s ID for security checks,
127             @param ids: List of Process stop’s IDs"""
128
129         return self.write(cr, uid, ids, {'state':'not running', 'partner_id':0})
130
131     def process_start(self, cr, uid, ids, *args):
132
133         """ @param self: The object pointer
134             @param cr: the current row, from the database cursor,
135             @param uid: the current user’s ID for security checks,
136             @param ids: List of Process start’s IDs """
137
138         self.write(cr, uid, ids, {'state':'running', 'partner_id':0})
139         return self.process_continue(cr, uid, ids, start=True)
140 crm_segmentation()
141
142 class crm_segmentation_line(osv.osv):
143     """ Segmentation line """
144     _name = "crm.segmentation.line"
145     _description = "Segmentation line"
146
147     _columns = {
148         'name': fields.char('Rule Name', size=64, required=True),
149         'segmentation_id': fields.many2one('crm.segmentation', 'Segmentation'),
150         'expr_name': fields.selection([('sale','Sale Amount'),('som','State of Mind'),\
151                         ('purchase','Purchase Amount')], 'Control Variable', size=64, required=True),
152         'expr_operator': fields.selection([('<','<'),('=','='),('>','>')], 'Operator', required=True),
153         'expr_value': fields.float('Value', required=True),
154         'operator': fields.selection([('and','Mandatory Expression'),\
155                         ('or','Optional Expression')],'Mandatory / Optional', required=True),
156     }
157     _defaults = {
158         'expr_name': lambda *a: 'sale',
159         'expr_operator': lambda *a: '>',
160         'operator': lambda *a: 'and'
161     }
162     def test(self, cr, uid, ids, partner_id):
163
164         """ @param self: The object pointer
165             @param cr: the current row, from the database cursor,
166             @param uid: the current user’s ID for security checks,
167             @param ids: List of Test’s IDs """
168
169         expression = {'<': lambda x,y: x<y, '=':lambda x,y:x==y, '>':lambda x,y:x>y}
170         ok = False
171         lst = self.read(cr, uid, ids)
172         for l in lst:
173             cr.execute('select * from ir_module_module where name=%s and state=%s', ('account','installed'))
174             if cr.fetchone():
175                 if l['expr_name']=='som':
176                     datas = self.pool.get('crm.segmentation').read(cr, uid, [l['segmentation_id'][0]],
177                             ['som','som_interval','som_interval_max',\
178                              'som_interval_default', 'som_interval_decrease'])
179                     value = crm_operators.som(cr, uid, partner_id, datas[0])
180                 elif l['expr_name']=='sale':
181                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
182                             'FROM account_invoice_line l, account_invoice i ' \
183                             'WHERE (l.invoice_id = i.id) ' \
184                                 'AND i.partner_id = %s '\
185                                 'AND i.type = \'out_invoice\'',
186                             (partner_id,))
187                     value = cr.fetchone()[0] or 0.0
188                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
189                             'FROM account_invoice_line l, account_invoice i ' \
190                             'WHERE (l.invoice_id = i.id) ' \
191                                 'AND i.partner_id = %s '\
192                                 'AND i.type = \'out_refund\'',
193                             (partner_id,))
194                     value -= cr.fetchone()[0] or 0.0
195                 elif l['expr_name']=='purchase':
196                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
197                             'FROM account_invoice_line l, account_invoice i ' \
198                             'WHERE (l.invoice_id = i.id) ' \
199                                 'AND i.partner_id = %s '\
200                                 'AND i.type = \'in_invoice\'',
201                             (partner_id,))
202                     value = cr.fetchone()[0] or 0.0
203                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
204                             'FROM account_invoice_line l, account_invoice i ' \
205                             'WHERE (l.invoice_id = i.id) ' \
206                                 'AND i.partner_id = %s '\
207                                 'AND i.type = \'in_refund\'',
208                             (partner_id,))
209                     value -= cr.fetchone()[0] or 0.0
210                 res = expression[l['expr_operator']](value, l['expr_value'])
211                 if (not res) and (l['operator']=='and'):
212                     return False
213                 if res:
214                     return True
215         return True
216
217 crm_segmentation_line()
218
219 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
220