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))
118 self.write(cr, uid, [id], {'state':'not running', 'partner_id':0})
122 def process_stop(self, cr, uid, ids, *args):
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"""
129 return self.write(cr, uid, ids, {'state':'not running', 'partner_id':0})
131 def process_start(self, cr, uid, ids, *args):
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 """
138 self.write(cr, uid, ids, {'state':'running', 'partner_id':0})
139 return self.process_continue(cr, uid, ids, start=True)
142 class crm_segmentation_line(osv.osv):
143 """ Segmentation line """
144 _name = "crm.segmentation.line"
145 _description = "Segmentation line"
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),
158 'expr_name': lambda *a: 'sale',
159 'expr_operator': lambda *a: '>',
160 'operator': lambda *a: 'and'
162 def test(self, cr, uid, ids, partner_id):
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 """
169 expression = {'<': lambda x,y: x<y, '=':lambda x,y:x==y, '>':lambda x,y:x>y}
171 lst = self.read(cr, uid, ids)
173 cr.execute('select * from ir_module_module where name=%s and state=%s', ('account','installed'))
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\'',
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\'',
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\'',
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\'',
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'):
217 crm_segmentation_line()
219 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: