[IMP] Removed usage of method date.today() in xml files.
[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 class crm_segmentation(osv.osv):
25     '''
26         A segmentation is a tool to automatically assign categories on partners.
27         These assignations are based on criterions.
28     '''
29     _name = "crm.segmentation"
30     _description = "Partner Segmentation"
31
32     _columns = {
33         'name': fields.char('Name', size=64, required=True, help='The name of the segmentation.'),
34         'description': fields.text('Description'),
35         'categ_id': fields.many2one('res.partner.category', 'Partner Category',\
36                          required=True, help='The partner category that will be \
37 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.\
39                         \nIf checked, remove the category from partners that doesn\'t match segmentation criterions'),
40         'state': fields.selection([('not running','Not Running'),\
41                     ('running','Running')], 'Execution Status', readonly=True),
42         'partner_id': fields.integer('Max Partner ID processed'),
43         'segmentation_line': fields.one2many('crm.segmentation.line', \
44                             'segmentation_id', 'Criteria', required=True),
45         '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')
46     }
47     _defaults = {
48         'partner_id': lambda *a: 0,
49         'state': lambda *a: 'not running',
50     }
51
52     def process_continue(self, cr, uid, ids, start=False):
53
54         """ @param self: The object pointer
55             @param cr: the current row, from the database cursor,
56             @param uid: the current user’s ID for security checks,
57             @param ids: List of Process continue’s IDs"""
58
59         partner_obj = self.pool.get('res.partner')
60         categs = self.read(cr, uid, ids, ['categ_id', 'exclusif', 'partner_id',\
61                                  'sales_purchase_active', 'profiling_active'])
62         for categ in categs:
63             if start:
64                 if categ['exclusif']:
65                     cr.execute('delete from res_partner_res_partner_category_rel \
66                             where category_id=%s', (categ['categ_id'][0],))
67
68             id = categ['id']
69
70             cr.execute('select id from res_partner order by id ')
71             partners = [x[0] for x in cr.fetchall()]
72
73             if categ['sales_purchase_active']:
74                 to_remove_list=[]
75                 cr.execute('select id from crm_segmentation_line where segmentation_id=%s', (id,))
76                 line_ids = [x[0] for x in cr.fetchall()]
77
78                 for pid in partners:
79                     if (not self.pool.get('crm.segmentation.line').test(cr, uid, line_ids, pid)):
80                         to_remove_list.append(pid)
81                 for pid in to_remove_list:
82                     partners.remove(pid)
83
84             for partner in partner_obj.browse(cr, uid, partners):
85                 category_ids = [categ_id.id for categ_id in partner.category_id]
86                 if categ['categ_id'][0] not in category_ids:
87                     cr.execute('insert into res_partner_res_partner_category_rel (category_id,partner_id) \
88                             values (%s,%s)', (categ['categ_id'][0], partner.id))
89
90             self.write(cr, uid, [id], {'state':'not running', 'partner_id':0})
91         return True
92
93     def process_stop(self, cr, uid, ids, *args):
94
95         """ @param self: The object pointer
96             @param cr: the current row, from the database cursor,
97             @param uid: the current user’s ID for security checks,
98             @param ids: List of Process stop’s IDs"""
99
100         return self.write(cr, uid, ids, {'state':'not running', 'partner_id':0})
101
102     def process_start(self, cr, uid, ids, *args):
103
104         """ @param self: The object pointer
105             @param cr: the current row, from the database cursor,
106             @param uid: the current user’s ID for security checks,
107             @param ids: List of Process start’s IDs """
108
109         self.write(cr, uid, ids, {'state':'running', 'partner_id':0})
110         return self.process_continue(cr, uid, ids, start=True)
111 crm_segmentation()
112
113 class crm_segmentation_line(osv.osv):
114     """ Segmentation line """
115     _name = "crm.segmentation.line"
116     _description = "Segmentation line"
117
118     _columns = {
119         'name': fields.char('Rule Name', size=64, required=True),
120         'segmentation_id': fields.many2one('crm.segmentation', 'Segmentation'),
121         'expr_name': fields.selection([('sale','Sale Amount'),
122                         ('purchase','Purchase Amount')], 'Control Variable', size=64, required=True),
123         'expr_operator': fields.selection([('<','<'),('=','='),('>','>')], 'Operator', required=True),
124         'expr_value': fields.float('Value', required=True),
125         'operator': fields.selection([('and','Mandatory Expression'),\
126                         ('or','Optional Expression')],'Mandatory / Optional', required=True),
127     }
128     _defaults = {
129         'expr_name': lambda *a: 'sale',
130         'expr_operator': lambda *a: '>',
131         'operator': lambda *a: 'and'
132     }
133     def test(self, cr, uid, ids, partner_id):
134
135         """ @param self: The object pointer
136             @param cr: the current row, from the database cursor,
137             @param uid: the current user’s ID for security checks,
138             @param ids: List of Test’s IDs """
139
140         expression = {'<': lambda x,y: x<y, '=':lambda x,y:x==y, '>':lambda x,y:x>y}
141         ok = False
142         lst = self.read(cr, uid, ids)
143         for l in lst:
144             cr.execute('select * from ir_module_module where name=%s and state=%s', ('account','installed'))
145             if cr.fetchone():
146                 if l['expr_name']=='sale':
147                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
148                             'FROM account_invoice_line l, account_invoice i ' \
149                             'WHERE (l.invoice_id = i.id) ' \
150                                 'AND i.partner_id = %s '\
151                                 'AND i.type = \'out_invoice\'',
152                             (partner_id,))
153                     value = cr.fetchone()[0] or 0.0
154                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
155                             'FROM account_invoice_line l, account_invoice i ' \
156                             'WHERE (l.invoice_id = i.id) ' \
157                                 'AND i.partner_id = %s '\
158                                 'AND i.type = \'out_refund\'',
159                             (partner_id,))
160                     value -= cr.fetchone()[0] or 0.0
161                 elif l['expr_name']=='purchase':
162                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
163                             'FROM account_invoice_line l, account_invoice i ' \
164                             'WHERE (l.invoice_id = i.id) ' \
165                                 'AND i.partner_id = %s '\
166                                 'AND i.type = \'in_invoice\'',
167                             (partner_id,))
168                     value = cr.fetchone()[0] or 0.0
169                     cr.execute('SELECT SUM(l.price_unit * l.quantity) ' \
170                             'FROM account_invoice_line l, account_invoice i ' \
171                             'WHERE (l.invoice_id = i.id) ' \
172                                 'AND i.partner_id = %s '\
173                                 'AND i.type = \'in_refund\'',
174                             (partner_id,))
175                     value -= cr.fetchone()[0] or 0.0
176                 res = expression[l['expr_operator']](value, l['expr_value'])
177                 if (not res) and (l['operator']=='and'):
178                     return False
179                 if res:
180                     return True
181         return True
182
183 crm_segmentation_line()
184
185 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
186