edd063df809bffd820955f30960dc798580c6e97
[odoo/odoo.git] / addons / crm / crm_segmentation.py
1 ##############################################################################
2 #
3 # Copyright (c) 2004-2006 TINY SPRL. (http://tiny.be) All Rights Reserved.
4 #
5 # WARNING: This program as such is intended to be used by professional
6 # programmers who take the whole responsability of assessing all potential
7 # consequences resulting from its eventual inadequacies and bugs
8 # End users who are looking for a ready-to-use solution with commercial
9 # garantees and support are strongly adviced to contract a Free Software
10 # Service Company
11 #
12 # This program is Free Software; you can redistribute it and/or
13 # modify it under the terms of the GNU General Public License
14 # as published by the Free Software Foundation; either version 2
15 # of the License, or (at your option) any later version.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
21 #
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 #
26 ##############################################################################
27
28 from osv import fields,osv,orm
29
30 import crm_operators
31
32
33 class crm_segmentation(osv.osv):
34         '''
35                 A segmentation is a tool to automatically assign categories on partners.
36                 These assignations are based on criterions.
37         '''
38         _name = "crm.segmentation"
39         _description = "Partner Segmentation"
40         _columns = {
41                 'name': fields.char('Name', size=64, required=True, help='The name of the segmentation.'),
42                 'description': fields.text('Description'),
43                 'categ_id': fields.many2one('res.partner.category', 'Partner Category', required=True, help='The partner category that will be added to partners that match the segmentation criterions after computation.'),
44                 'exclusif': fields.boolean('Exclusive', help='Check if the category is limited to partners that match the segmentation criterions. If checked, remove the category from partners that doesn\'t match segmentation criterions'),
45                 'state': fields.selection([('not running','Not Running'),('running','Running')], 'Execution State', readonly=True),
46                 'partner_id': fields.integer('Max Partner ID processed'),
47                 'segmentation_line': fields.one2many('crm.segmentation.line', 'segmentation_id', 'Criteria', required=True),
48                 'som_interval': fields.integer('Days per Periode', help="A period is the average number of days between two cycle of sale or purchase for this segmentation. It's mainly used to detect if a partner has not purchased or buy for a too long time, so we suppose that his state of mind has decreased because he probably bought goods to another supplier. Use this functionnality for recurring businesses."),
49                 'som_interval_max': fields.integer('Max Interval', help="The computation is made on all events that occured during this interval, the past X periods."),
50                 'som_interval_decrease': fields.float('Decrease (0>1)', help="If the partner has not purchased (or buied) during a period, decrease the state of mind by this factor. It\'s a multiplication"),
51                 'som_interval_default': fields.float('Default (0=None)', help="Default state of mind for period preceeding the 'Max Interval' computation. This is the starting state of mind by default if the partner has no event."),
52                 'sales_purchase_active': fields.boolean('Use The Sales Purchase Rules', help='Check if you want to use this tab as part of the segmentation rule. If not checked, the criteria beneath will be ignored')
53         }
54         _defaults = {
55                 'partner_id': lambda *a: 0,
56                 'state': lambda *a: 'not running',
57                 'som_interval_max': lambda *a: 3,
58                 'som_interval_decrease': lambda *a: 0.8,
59                 'som_interval_default': lambda *a: 0.5
60         }
61
62         def process_continue(self, cr, uid, ids, start=False):
63                 categs = self.read(cr,uid,ids,['categ_id','exclusif','partner_id', 'sales_purchase_active', 'profiling_active'])
64                 for categ in categs:
65                         if start:
66                                 if categ['exclusif']:
67                                         cr.execute('delete from res_partner_category_rel where category_id=%d', (categ['categ_id'][0],))
68
69                         id = categ['id']                        
70
71                         cr.execute('select id from res_partner order by id ')
72                         partners = [x[0] for x in cr.fetchall()]
73
74                         if categ['sales_purchase_active']:
75                                 to_remove_list=[]
76                                 cr.execute('select id from crm_segmentation_line where segmentation_id=%d', (id,))
77                                 line_ids = [x[0] for x in cr.fetchall()]
78
79                                 for pid in partners:
80                                         if (not self.pool.get('crm.segmentation.line').test(cr, uid, line_ids, pid)):
81                                                 to_remove_list.append(pid)
82                                 for pid in to_remove_list:
83                                         partners.remove(pid)
84
85                         for partner_id in partners:
86                                 cr.execute('insert into res_partner_category_rel (category_id,partner_id) values (%d,%d)', (categ['categ_id'][0],partner_id))
87                         cr.commit()
88
89                         self.write(cr, uid, [id], {'state':'not running', 'partner_id':0})
90                         cr.commit()
91                 return True
92
93 #       def process_continue(self, cr, uid, ids, start=False):
94 #               categs = self.read(cr,uid,ids,['categ_id','exclusif','partner_id'])
95 #               for categ in categs:
96 #                       if start:
97 #                               if categ['exclusif']:
98 #                                       cr.execute('delete from res_partner_category_rel where category_id=%d', (categ['categ_id'][0],))
99 #                       id = categ['id']
100 #                       cr.execute('select id from crm_segmentation_line where segmentation_id=%d', (id,))
101 #                       line_ids = [x[0] for x in cr.fetchall()]
102 #                       cr.execute('select id from res_partner order by id limit 100 offset %d', (categ['partner_id'],))
103 #                       partners = cr.fetchall()
104 #                       ok = []
105 #                       for (pid,) in partners:
106 #                               if self.pool.get('crm.segmentation.line').test(cr, uid, line_ids, pid):
107 #                                       ok.append(pid)
108 #
109 #                       for partner_id in ok:
110 #                               cr.execute('insert into res_partner_category_rel (category_id,partner_id) values (%d,%d)', (categ['categ_id'][0],partner_id))
111 #                       cr.commit()
112 #
113 #                       if len(partners)==100:
114 #                               self.write(cr, uid, [id], {'partner_id':categ['partner_id']+100})
115 #                               self.process_continue(cr, uid, [id])
116 #                       self.write(cr, uid, [id], {'state':'not running', 'partner_id':0})
117 #                       cr.commit()
118 #               return True
119
120         def process_stop(self, cr, uid, ids, *args):
121                 return self.write(cr, uid, ids, {'state':'not running', 'partner_id':0})
122
123         def process_start(self, cr, uid, ids, *args):
124                 self.write(cr, uid, ids, {'state':'running', 'partner_id':0})
125                 return self.process_continue(cr, uid, ids, start=True)
126 crm_segmentation()
127
128 class crm_segmentation_line(osv.osv):
129         _name = "crm.segmentation.line"
130         _description = "Segmentation line"
131         _columns = {
132                 'name': fields.char('Rule Name', size=64, required=True),
133                 'segmentation_id': fields.many2one('crm.segmentation', 'Segmentation'),
134                 'expr_name': fields.selection([('sale','Sale Amount'),('som','State of Mind'),('purchase','Purchase Amount')], 'Control Variable', size=64, required=True),
135                 'expr_operator': fields.selection([('<','<'),('=','='),('>','>')], 'Operator', required=True),
136                 'expr_value': fields.float('Value', required=True),
137                 'operator': fields.selection([('and','Mandatory Expression'),('or','Optional Expression')],'Mandatory / Optionnal', required=True),
138         }
139         _defaults = {
140                 'expr_name': lambda *a: 'sale',
141                 'expr_operator': lambda *a: '>',
142                 'operator': lambda *a: 'and'
143         }
144         def test(self, cr, uid, ids, partner_id):
145                 expression = {'<': lambda x,y: x<y, '=':lambda x,y:x==y, '>':lambda x,y:x>y}
146                 ok = False
147                 lst = self.read(cr, uid, ids)
148                 for l in lst:
149                         if l['expr_name']=='som':
150                                 datas = self.pool.get('crm.segmentation').read(cr, uid, [l['segmentation_id'][0]], ['som','som_interval','som_interval_max','som_interval_default', 'som_interval_decrease'])
151                                 value = crm_operators.som(cr, uid, partner_id, datas[0])
152                         elif l['expr_name']=='sale':
153                                 cr.execute('select sum(l.price_unit*l.quantity) from account_invoice_line l left join account_invoice i on (l.invoice_id=i.id) where i.partner_id=%d', (partner_id,))
154                                 value = cr.fetchone()[0] or 0.0
155                         elif l['expr_name']=='purchase':
156                                 cr.execute('select sum(l.price_unit*l.quantity) from account_invoice_line l left join account_invoice i on (l.invoice_id=i.id) where i.partner_id=%d', (partner_id,))
157                                 value = cr.fetchone()[0] or 0.0
158                         res = expression[l['expr_operator']](value, l['expr_value'])
159                         if (not res) and (l['operator']=='and'):
160                                 return False
161                         if res:
162                                 return True
163                 return True
164 crm_segmentation_line()
165
166
167