Launchpad automatic translations update.
[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 limited to partners that match the segmentation criterions.\
42                         \nIf checked, remove the category from partners that doesn\'t match segmentation criterions'),
43         'state': fields.selection([('not running','Not Running'),\
44                     ('running','Running')], 'Execution Status', readonly=True),
45         'partner_id': fields.integer('Max Partner ID processed'),
46         'segmentation_line': fields.one2many('crm.segmentation.line', \
47                             '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.\
49                  \nIt's mainly used to detect if a partner has not purchased or buy for a too long time, \
50                  \nso we suppose that his state of mind has decreased because he probably bought goods to another supplier. \
51                  \nUse this functionality for recurring businesses."),
52         'som_interval_max': fields.integer('Max Interval', help="The computation is made on all events that occured during this interval, the past X periods."),
53         'som_interval_decrease': fields.float('Decrease (0>1)', help="If the "\
54                             "partner has not purchased (or bought) during a "\
55                             "period, decrease the state of mind by this factor. It\'s a multiplication"),
56         'som_interval_default': fields.float('Default (0=None)', help="Default \
57 state of mind for period preceeding the 'Max Interval' computation. \
58 This is the starting state of mind by default if the partner has no event."),
59         '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')
60     }
61     _defaults = {
62         'partner_id': lambda *a: 0,
63         'state': lambda *a: 'not running',
64         'som_interval_max': lambda *a: 3,
65         'som_interval_decrease': lambda *a: 0.8,
66         'som_interval_default': lambda *a: 0.5
67     }
68
69     def process_continue(self, cr, uid, ids, start=False):
70
71         """ @param self: The object pointer
72             @param cr: the current row, from the database cursor,
73             @param uid: the current user’s ID for security checks,
74             @param ids: List of Process continue’s IDs"""
75
76         categs = self.read(cr, uid, ids, ['categ_id', 'exclusif', 'partner_id',\
77                                  'sales_purchase_active', 'profiling_active'])
78         for categ in categs:
79             if start:
80                 if categ['exclusif']:
81                     cr.execute('delete from res_partner_category_rel \
82                             where category_id=%s', (categ['categ_id'][0],))
83
84             id = categ['id']
85
86             cr.execute('select id from res_partner order by id ')
87             partners = [x[0] for x in cr.fetchall()]
88
89             if categ['sales_purchase_active']:
90                 to_remove_list=[]
91                 cr.execute('select id from crm_segmentation_line where segmentation_id=%s', (id,))
92                 line_ids = [x[0] for x in cr.fetchall()]
93
94                 for pid in partners:
95                     if (not self.pool.get('crm.segmentation.line').test(cr, uid, line_ids, pid)):
96                         to_remove_list.append(pid)
97                 for pid in to_remove_list:
98                     partners.remove(pid)
99
100             for partner_id in partners:
101                 cr.execute('insert into res_partner_category_rel (category_id,partner_id) \
102                         values (%s,%s)', (categ['categ_id'][0], partner_id))
103
104             self.write(cr, uid, [id], {'state':'not running', 'partner_id':0})
105         return True
106
107     def process_stop(self, cr, uid, ids, *args):
108
109         """ @param self: The object pointer
110             @param cr: the current row, from the database cursor,
111             @param uid: the current user’s ID for security checks,
112             @param ids: List of Process stop’s IDs"""
113
114         return self.write(cr, uid, ids, {'state':'not running', 'partner_id':0})
115
116     def process_start(self, cr, uid, ids, *args):
117
118         """ @param self: The object pointer
119             @param cr: the current row, from the database cursor,
120             @param uid: the current user’s ID for security checks,
121             @param ids: List of Process start’s IDs """
122
123         self.write(cr, uid, ids, {'state':'running', 'partner_id':0})
124         return self.process_continue(cr, uid, ids, start=True)
125 crm_segmentation()
126
127 class crm_segmentation_line(osv.osv):
128     """ Segmentation line """
129     _name = "crm.segmentation.line"
130     _description = "Segmentation line"
131
132     _columns = {
133         'name': fields.char('Rule Name', size=64, required=True),
134         'segmentation_id': fields.many2one('crm.segmentation', 'Segmentation'),
135         'expr_name': fields.selection([('sale','Sale Amount'),('som','State of Mind'),\
136                         ('purchase','Purchase Amount')], 'Control Variable', size=64, required=True),
137         'expr_operator': fields.selection([('<','<'),('=','='),('>','>')], 'Operator', required=True),
138         'expr_value': fields.float('Value', required=True),
139         'operator': fields.selection([('and','Mandatory Expression'),\
140                         ('or','Optional Expression')],'Mandatory / Optional', required=True),
141     }
142     _defaults = {
143         'expr_name': lambda *a: 'sale',
144         'expr_operator': lambda *a: '>',
145         'operator': lambda *a: 'and'
146     }
147     def test(self, cr, uid, ids, partner_id):
148
149         """ @param self: The object pointer
150             @param cr: the current row, from the database cursor,
151             @param uid: the current user’s ID for security checks,
152             @param ids: List of Test’s IDs """
153
154         expression = {'<': lambda x,y: x<y, '=':lambda x,y:x==y, '>':lambda x,y:x>y}
155         ok = False
156         lst = self.read(cr, uid, ids)
157         for l in lst:
158             cr.execute('select * from ir_module_module where name=%s and state=%s', ('account','installed'))
159             if cr.fetchone():
160                 if l['expr_name']=='som':
161                     datas = self.pool.get('crm.segmentation').read(cr, uid, [l['segmentation_id'][0]],
162                             ['som','som_interval','som_interval_max',\
163                              'som_interval_default', 'som_interval_decrease'])
164                     value = crm_operators.som(cr, uid, partner_id, datas[0])
165                 elif l['expr_name']=='sale':
166                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
167                             'FROM account_invoice_line l, account_invoice i ' \
168                             'WHERE (l.invoice_id = i.id) ' \
169                                 'AND i.partner_id = %s '\
170                                 'AND i.type = \'out_invoice\'',
171                             (partner_id,))
172                     value = cr.fetchone()[0] or 0.0
173                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
174                             'FROM account_invoice_line l, account_invoice i ' \
175                             'WHERE (l.invoice_id = i.id) ' \
176                                 'AND i.partner_id = %s '\
177                                 'AND i.type = \'out_refund\'',
178                             (partner_id,))
179                     value -= cr.fetchone()[0] or 0.0
180                 elif l['expr_name']=='purchase':
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 = \'in_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 = \'in_refund\'',
193                             (partner_id,))
194                     value -= cr.fetchone()[0] or 0.0
195                 res = expression[l['expr_operator']](value, l['expr_value'])
196                 if (not res) and (l['operator']=='and'):
197                     return False
198                 if res:
199                     return True
200         return True
201
202 crm_segmentation_line()
203
204 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
205