1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
22 from osv import fields,osv,orm
27 class crm_segmentation(osv.osv):
29 A segmentation is a tool to automatically assign categories on partners.
30 These assignations are based on criterions.
32 _name = "crm.segmentation"
33 _description = "Partner Segmentation"
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')
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
82 def process_continue(self, cr, uid, ids, start=False):
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"""
89 categs = self.read(cr, uid, ids, ['categ_id', 'exclusif', 'partner_id',\
90 'sales_purchase_active', 'profiling_active'])
94 cr.execute('delete from res_partner_category_rel \
95 where category_id=%s', (categ['categ_id'][0],))
99 cr.execute('select id from res_partner order by id ')
100 partners = [x[0] for x in cr.fetchall()]
102 if categ['sales_purchase_active']:
104 cr.execute('select id from crm_segmentation_line where segmentation_id=%s', (id,))
105 line_ids = [x[0] for x in cr.fetchall()]
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:
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))
117 self.write(cr, uid, [id], {'state':'not running', 'partner_id':0})
120 def process_stop(self, cr, uid, ids, *args):
122 """ @param self: The object pointer
123 @param cr: the current row, from the database cursor,
124 @param uid: the current user’s ID for security checks,
125 @param ids: List of Process stop’s IDs"""
127 return self.write(cr, uid, ids, {'state':'not running', 'partner_id':0})
129 def process_start(self, cr, uid, ids, *args):
131 """ @param self: The object pointer
132 @param cr: the current row, from the database cursor,
133 @param uid: the current user’s ID for security checks,
134 @param ids: List of Process start’s IDs """
136 self.write(cr, uid, ids, {'state':'running', 'partner_id':0})
137 return self.process_continue(cr, uid, ids, start=True)
140 class crm_segmentation_line(osv.osv):
141 """ Segmentation line """
142 _name = "crm.segmentation.line"
143 _description = "Segmentation line"
146 'name': fields.char('Rule Name', size=64, required=True),
147 'segmentation_id': fields.many2one('crm.segmentation', 'Segmentation'),
148 'expr_name': fields.selection([('sale','Sale Amount'),('som','State of Mind'),\
149 ('purchase','Purchase Amount')], 'Control Variable', size=64, required=True),
150 'expr_operator': fields.selection([('<','<'),('=','='),('>','>')], 'Operator', required=True),
151 'expr_value': fields.float('Value', required=True),
152 'operator': fields.selection([('and','Mandatory Expression'),\
153 ('or','Optional Expression')],'Mandatory / Optional', required=True),
156 'expr_name': lambda *a: 'sale',
157 'expr_operator': lambda *a: '>',
158 'operator': lambda *a: 'and'
160 def test(self, cr, uid, ids, partner_id):
162 """ @param self: The object pointer
163 @param cr: the current row, from the database cursor,
164 @param uid: the current user’s ID for security checks,
165 @param ids: List of Test’s IDs """
167 expression = {'<': lambda x,y: x<y, '=':lambda x,y:x==y, '>':lambda x,y:x>y}
169 lst = self.read(cr, uid, ids)
171 cr.execute('select * from ir_module_module where name=%s and state=%s', ('account','installed'))
173 if l['expr_name']=='som':
174 datas = self.pool.get('crm.segmentation').read(cr, uid, [l['segmentation_id'][0]],
175 ['som','som_interval','som_interval_max',\
176 'som_interval_default', 'som_interval_decrease'])
177 value = crm_operators.som(cr, uid, partner_id, datas[0])
178 elif l['expr_name']=='sale':
179 cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
180 'FROM account_invoice_line l, account_invoice i ' \
181 'WHERE (l.invoice_id = i.id) ' \
182 'AND i.partner_id = %s '\
183 'AND i.type = \'out_invoice\'',
185 value = cr.fetchone()[0] or 0.0
186 cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
187 'FROM account_invoice_line l, account_invoice i ' \
188 'WHERE (l.invoice_id = i.id) ' \
189 'AND i.partner_id = %s '\
190 'AND i.type = \'out_refund\'',
192 value -= cr.fetchone()[0] or 0.0
193 elif l['expr_name']=='purchase':
194 cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
195 'FROM account_invoice_line l, account_invoice i ' \
196 'WHERE (l.invoice_id = i.id) ' \
197 'AND i.partner_id = %s '\
198 'AND i.type = \'in_invoice\'',
200 value = cr.fetchone()[0] or 0.0
201 cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
202 'FROM account_invoice_line l, account_invoice i ' \
203 'WHERE (l.invoice_id = i.id) ' \
204 'AND i.partner_id = %s '\
205 'AND i.type = \'in_refund\'',
207 value -= cr.fetchone()[0] or 0.0
208 res = expression[l['expr_operator']](value, l['expr_value'])
209 if (not res) and (l['operator']=='and'):
215 crm_segmentation_line()
217 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: