1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 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"
35 'name': fields.char('Name', size=64, required=True, help='The name of the segmentation.'),
36 'description': fields.text('Description'),
37 '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.'),
38 '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'),
39 'state': fields.selection([('not running','Not Running'),('running','Running')], 'Execution State', readonly=True),
40 'partner_id': fields.integer('Max Partner ID processed'),
41 'segmentation_line': fields.one2many('crm.segmentation.line', 'segmentation_id', 'Criteria', required=True),
42 '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 functionality for recurring businesses."),
43 'som_interval_max': fields.integer('Max Interval', help="The computation is made on all events that occured during this interval, the past X periods."),
44 '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"),
45 '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."),
46 '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')
49 'partner_id': lambda *a: 0,
50 'state': lambda *a: 'not running',
51 'som_interval_max': lambda *a: 3,
52 'som_interval_decrease': lambda *a: 0.8,
53 'som_interval_default': lambda *a: 0.5
56 def process_continue(self, cr, uid, ids, start=False):
57 categs = self.read(cr,uid,ids,['categ_id','exclusif','partner_id', 'sales_purchase_active', 'profiling_active'])
61 cr.execute('delete from res_partner_category_rel where category_id=%s', (categ['categ_id'][0],))
65 cr.execute('select id from res_partner order by id ')
66 partners = [x[0] for x in cr.fetchall()]
68 if categ['sales_purchase_active']:
70 cr.execute('select id from crm_segmentation_line where segmentation_id=%s', (id,))
71 line_ids = [x[0] for x in cr.fetchall()]
74 if (not self.pool.get('crm.segmentation.line').test(cr, uid, line_ids, pid)):
75 to_remove_list.append(pid)
76 for pid in to_remove_list:
79 for partner_id in partners:
80 cr.execute('insert into res_partner_category_rel (category_id,partner_id) values (%s,%s)', (categ['categ_id'][0],partner_id))
83 self.write(cr, uid, [id], {'state':'not running', 'partner_id':0})
87 def process_stop(self, cr, uid, ids, *args):
88 return self.write(cr, uid, ids, {'state':'not running', 'partner_id':0})
90 def process_start(self, cr, uid, ids, *args):
91 self.write(cr, uid, ids, {'state':'running', 'partner_id':0})
92 return self.process_continue(cr, uid, ids, start=True)
95 class crm_segmentation_line(osv.osv):
96 _name = "crm.segmentation.line"
97 _description = "Segmentation line"
99 'name': fields.char('Rule Name', size=64, required=True),
100 'segmentation_id': fields.many2one('crm.segmentation', 'Segmentation'),
101 'expr_name': fields.selection([('sale','Sale Amount'),('som','State of Mind'),('purchase','Purchase Amount')], 'Control Variable', size=64, required=True),
102 'expr_operator': fields.selection([('<','<'),('=','='),('>','>')], 'Operator', required=True),
103 'expr_value': fields.float('Value', required=True),
104 'operator': fields.selection([('and','Mandatory Expression'),('or','Optional Expression')],'Mandatory / Optional', required=True),
107 'expr_name': lambda *a: 'sale',
108 'expr_operator': lambda *a: '>',
109 'operator': lambda *a: 'and'
111 def test(self, cr, uid, ids, partner_id):
112 expression = {'<': lambda x,y: x<y, '=':lambda x,y:x==y, '>':lambda x,y:x>y}
114 lst = self.read(cr, uid, ids)
116 cr.execute('select * from ir_module_module where name=%s and state=%s', ('account','installed'))
118 if l['expr_name']=='som':
119 datas = self.pool.get('crm.segmentation').read(cr, uid, [l['segmentation_id'][0]],
120 ['som','som_interval','som_interval_max','som_interval_default', 'som_interval_decrease'])
121 value = crm_operators.som(cr, uid, partner_id, datas[0])
122 elif l['expr_name']=='sale':
123 cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
124 'FROM account_invoice_line l, account_invoice i ' \
125 'WHERE (l.invoice_id = i.id) ' \
126 'AND i.partner_id = %s '\
127 'AND i.type = \'out_invoice\'',
129 value = cr.fetchone()[0] or 0.0
130 cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
131 'FROM account_invoice_line l, account_invoice i ' \
132 'WHERE (l.invoice_id = i.id) ' \
133 'AND i.partner_id = %s '\
134 'AND i.type = \'out_refund\'',
136 value -= cr.fetchone()[0] or 0.0
137 elif l['expr_name']=='purchase':
138 cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
139 'FROM account_invoice_line l, account_invoice i ' \
140 'WHERE (l.invoice_id = i.id) ' \
141 'AND i.partner_id = %s '\
142 'AND i.type = \'in_invoice\'',
144 value = cr.fetchone()[0] or 0.0
145 cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
146 'FROM account_invoice_line l, account_invoice i ' \
147 'WHERE (l.invoice_id = i.id) ' \
148 'AND i.partner_id = %s '\
149 'AND i.type = \'in_refund\'',
151 value -= cr.fetchone()[0] or 0.0
152 res = expression[l['expr_operator']](value, l['expr_value'])
153 if (not res) and (l['operator']=='and'):
158 crm_segmentation_line()
163 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: