[FIX] psycopg2: %d -> %s
[odoo/odoo.git] / addons / crm / crm_segmentation.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution   
5 #    Copyright (C) 2004-2008 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 from osv import fields,osv,orm
24
25 import crm_operators
26
27
28 class crm_segmentation(osv.osv):
29     '''
30         A segmentation is a tool to automatically assign categories on partners.
31         These assignations are based on criterions.
32     '''
33     _name = "crm.segmentation"
34     _description = "Partner Segmentation"
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', required=True, help='The partner category that will be added to partners that match the segmentation criterions after computation.'),
39         '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'),
40         'state': fields.selection([('not running','Not Running'),('running','Running')], 'Execution Status', readonly=True),
41         'partner_id': fields.integer('Max Partner ID processed'),
42         'segmentation_line': fields.one2many('crm.segmentation.line', 'segmentation_id', 'Criteria', required=True),
43         '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."),
44         'som_interval_max': fields.integer('Max Interval', help="The computation is made on all events that occured during this interval, the past X periods."),
45         '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"),
46         '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."),
47         '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')
48     }
49     _defaults = {
50         'partner_id': lambda *a: 0,
51         'state': lambda *a: 'not running',
52         'som_interval_max': lambda *a: 3,
53         'som_interval_decrease': lambda *a: 0.8,
54         'som_interval_default': lambda *a: 0.5
55     }
56
57     def process_continue(self, cr, uid, ids, start=False):
58         categs = self.read(cr,uid,ids,['categ_id','exclusif','partner_id', 'sales_purchase_active', 'profiling_active'])
59         for categ in categs:
60             if start:
61                 if categ['exclusif']:
62                     cr.execute('delete from res_partner_category_rel where category_id=%s', (categ['categ_id'][0],))
63
64             id = categ['id']
65
66             cr.execute('select id from res_partner order by id ')
67             partners = [x[0] for x in cr.fetchall()]
68
69             if categ['sales_purchase_active']:
70                 to_remove_list=[]
71                 cr.execute('select id from crm_segmentation_line where segmentation_id=%s', (id,))
72                 line_ids = [x[0] for x in cr.fetchall()]
73
74                 for pid in partners:
75                     if (not self.pool.get('crm.segmentation.line').test(cr, uid, line_ids, pid)):
76                         to_remove_list.append(pid)
77                 for pid in to_remove_list:
78                     partners.remove(pid)
79
80             for partner_id in partners:
81                 cr.execute('insert into res_partner_category_rel (category_id,partner_id) values (%s,%s)', (categ['categ_id'][0],partner_id))
82             cr.commit()
83
84             self.write(cr, uid, [id], {'state':'not running', 'partner_id':0})
85             cr.commit()
86         return True
87
88     def process_stop(self, cr, uid, ids, *args):
89         return self.write(cr, uid, ids, {'state':'not running', 'partner_id':0})
90
91     def process_start(self, cr, uid, ids, *args):
92         self.write(cr, uid, ids, {'state':'running', 'partner_id':0})
93         return self.process_continue(cr, uid, ids, start=True)
94 crm_segmentation()
95
96 class crm_segmentation_line(osv.osv):
97     _name = "crm.segmentation.line"
98     _description = "Segmentation line"
99     _columns = {
100         'name': fields.char('Rule Name', size=64, required=True),
101         'segmentation_id': fields.many2one('crm.segmentation', 'Segmentation'),
102         'expr_name': fields.selection([('sale','Sale Amount'),('som','State of Mind'),('purchase','Purchase Amount')], 'Control Variable', size=64, required=True),
103         'expr_operator': fields.selection([('<','<'),('=','='),('>','>')], 'Operator', required=True),
104         'expr_value': fields.float('Value', required=True),
105         'operator': fields.selection([('and','Mandatory Expression'),('or','Optional Expression')],'Mandatory / Optionnal', required=True),
106     }
107     _defaults = {
108         'expr_name': lambda *a: 'sale',
109         'expr_operator': lambda *a: '>',
110         'operator': lambda *a: 'and'
111     }
112     def test(self, cr, uid, ids, partner_id):
113         expression = {'<': lambda x,y: x<y, '=':lambda x,y:x==y, '>':lambda x,y:x>y}
114         ok = False
115         lst = self.read(cr, uid, ids)
116         for l in lst:
117             cr.execute('select * from ir_module_module where name=%s and state=%s', ('account','installed'))
118             if cr.fetchone():
119                 if l['expr_name']=='som':
120                     datas = self.pool.get('crm.segmentation').read(cr, uid, [l['segmentation_id'][0]],
121                             ['som','som_interval','som_interval_max','som_interval_default', 'som_interval_decrease'])
122                     value = crm_operators.som(cr, uid, partner_id, datas[0])
123                 elif l['expr_name']=='sale':
124                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
125                             'FROM account_invoice_line l, account_invoice i ' \
126                             'WHERE (l.invoice_id = i.id) ' \
127                                 'AND i.partner_id = %s '\
128                                 'AND i.type = \'out_invoice\'',
129                             (partner_id,))
130                     value = cr.fetchone()[0] or 0.0
131                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
132                             'FROM account_invoice_line l, account_invoice i ' \
133                             'WHERE (l.invoice_id = i.id) ' \
134                                 'AND i.partner_id = %s '\
135                                 'AND i.type = \'out_refund\'',
136                             (partner_id,))
137                     value -= cr.fetchone()[0] or 0.0
138                 elif l['expr_name']=='purchase':
139                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
140                             'FROM account_invoice_line l, account_invoice i ' \
141                             'WHERE (l.invoice_id = i.id) ' \
142                                 'AND i.partner_id = %s '\
143                                 'AND i.type = \'in_invoice\'',
144                             (partner_id,))
145                     value = cr.fetchone()[0] or 0.0
146                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
147                             'FROM account_invoice_line l, account_invoice i ' \
148                             'WHERE (l.invoice_id = i.id) ' \
149                                 'AND i.partner_id = %s '\
150                                 'AND i.type = \'in_refund\'',
151                             (partner_id,))
152                     value -= cr.fetchone()[0] or 0.0
153                 res = expression[l['expr_operator']](value, l['expr_value'])
154                 if (not res) and (l['operator']=='and'):
155                     return False
156                 if res:
157                     return True
158         return True
159 crm_segmentation_line()
160
161
162
163
164 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
165