[FIX] Schedule jobs even if their next time has passed.
[odoo/odoo.git] / addons / crm_profiling / crm_profiling.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution   
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22 from osv import fields,osv
23 from osv import orm
24
25 from tools.translate import _
26
27 def _get_answers(cr, uid, ids):
28     query = """
29     select distinct(answer)
30     from profile_question_yes_rel
31     where profile in %s"""
32
33     cr.execute(query, (tuple(ids),))
34     ans_yes = [x[0] for x in cr.fetchall()]
35
36     query = """
37     select distinct(answer)
38     from profile_question_no_rel
39     where profile in %s"""
40
41     cr.execute(query, (tuple(ids),))
42     ans_no = [x[0] for x in cr.fetchall()]
43
44     return [ans_yes, ans_no]
45
46
47 def _get_parents(cr, uid, ids):
48     ids_to_check = ids
49     cr.execute("""
50      select distinct(parent_id)
51      from crm_segmentation
52      where parent_id is not null
53      and id in %s""",
54                (tuple(ids),))
55
56     parent_ids = [x[0] for x in cr.fetchall()]
57
58     trigger = False
59     for x in parent_ids:
60         if x not in ids_to_check:
61             ids_to_check.append(x)
62             trigger = True
63
64     if trigger:
65         ids_to_check = _get_parents(cr, uid, ids_to_check)
66
67     return ids_to_check
68
69
70 def test_prof(cr, uid, seg_id, pid, answers_ids = []):
71 #return True if the partner pid fetch the segmentation rule seg_id
72     ids_to_check = _get_parents(cr, uid, [seg_id])
73     [yes_answers, no_answers] = _get_answers(cr, uid, ids_to_check)
74     temp = True
75     for y_ans in yes_answers:
76         if y_ans not in answers_ids:
77             temp = False
78             break
79     if temp:
80         for ans in answers_ids:
81             if ans in no_answers:
82                 temp = False
83                 break
84     if temp:
85         return True
86     return False
87
88
89 def _recompute_categ(self, cr, uid, pid, answers_ids):
90     cr.execute('''
91         select r.category_id
92         from res_partner_category_rel r left join crm_segmentation s on (r.category_id = s.categ_id) 
93         where r.partner_id = %s and (s.exclusif = false or s.exclusif is null)
94         ''', (pid,))
95     categories = [x[0] for x in cr.fetchall()]
96
97     query = '''
98         select id, categ_id
99         from crm_segmentation
100         where profiling_active = true'''
101     if not categories:
102         query_params = ()
103     else:
104         query += ' and categ_id not in %s'
105         query_params = (tuple(categories),)
106     query += ' order by id '
107
108     cr.execute(query, query_params)
109     segm_cat_ids = cr.fetchall()
110
111     for (segm_id, cat_id) in segm_cat_ids:
112         if test_prof(cr, uid, segm_id, pid, answers_ids):
113             categories.append(cat_id)
114     return categories
115
116
117 class question(osv.osv):
118     _name="crm_profiling.question"
119     _description= "Question"
120     _columns={
121         'name': fields.char("Question",size=128, required=True),
122         'answers_ids': fields.one2many("crm_profiling.answer","question_id","Avalaible answers",),
123         }
124
125 question()
126
127
128 class questionnaire(osv.osv):
129     _name="crm_profiling.questionnaire"
130     _description= "Questionnaire"
131
132     def build_form(self, cr, uid, data, context):
133         query = """
134         select name, id
135         from crm_profiling_question
136         where id in ( select question from profile_questionnaire_quest_rel where questionnaire = %s)"""
137         res = cr.execute(query, (data['form']['questionnaire_name'],))
138         result = cr.fetchall()
139         quest_fields={}
140         quest_form='''<?xml version="1.0"?>
141             <form string="%s">''' % _('Questionnaire')
142         for name, oid in result:
143             quest_form = quest_form + '<field name="quest_form%d"/><newline/>' % (oid,)
144             quest_fields['quest_form%d' % (oid,)] = {'string': name, 'type': 'many2one', 'relation': 'crm_profiling.answer', 'domain': [('question_id','=',oid)] }
145         quest_form = quest_form + '''</form>'''      
146         return quest_form, quest_fields
147
148     _columns = {
149         'name': fields.char("Questionnaire",size=128, required=True),
150         'description':fields.text("Description", required=True),
151         'questions_ids': fields.many2many('crm_profiling.question','profile_questionnaire_quest_rel','questionnaire', 'question', "Questions"),
152     }
153
154 questionnaire()
155
156
157 class answer(osv.osv):
158     _name="crm_profiling.answer"
159     _description="Answer"
160     _columns={
161         "name": fields.char("Answer",size=128, required=True),
162         "question_id": fields.many2one('crm_profiling.question',"Question"),
163         }
164 answer()
165
166
167 class partner(osv.osv):
168     _inherit="res.partner"
169     _columns={
170         "answers_ids": fields.many2many("crm_profiling.answer","partner_question_rel","partner","answer","Answers"),
171         }
172
173     def _questionnaire_compute(self, cr, uid, data, context):
174         temp = []
175         for x in data['form']:
176             if x.startswith("quest_form") and data['form'][x] != 0 :
177                 temp.append(data['form'][x])
178
179         query = "select answer from partner_question_rel where partner=%s"
180         cr.execute(query, (data['id'],))
181         for x in cr.fetchall():
182             temp.append(x[0])
183
184         self.write(cr, uid, [data['id']],{'answers_ids':[[6,0,temp]]}, context)
185         return {}
186
187
188     def write(self, cr, uid, ids, vals, context=None):
189         if not context:
190             context={}
191         if 'answers_ids' in vals:
192             vals['category_id']=[[6, 0, _recompute_categ(self, cr, uid, ids[0], vals['answers_ids'][0][2])]]
193         return super(partner, self).write(cr, uid, ids, vals, context=context)
194
195 partner()
196
197
198 class crm_segmentation(osv.osv):
199     _inherit="crm.segmentation"
200     _columns={
201         "answer_yes": fields.many2many("crm_profiling.answer","profile_question_yes_rel","profile","answer","Included Answers"),
202         "answer_no": fields.many2many("crm_profiling.answer","profile_question_no_rel","profile","answer","Excluded Answers"),
203         'parent_id': fields.many2one('crm.segmentation', 'Parent Profile'),
204         'child_ids': fields.one2many('crm.segmentation', 'parent_id', 'Child Profiles'),
205         'profiling_active': fields.boolean('Use The Profiling Rules', help='Check this box if you want to use this tab as part of the segmentation rule. If not checked, the criteria beneath will be ignored')
206         }
207     _constraints = [
208         (orm.orm.check_recursion, 'Error ! You can not create recursive profiles.', ['parent_id'])
209     ]
210
211     def process_continue(self, cr, uid, ids, start=False):
212         categs = self.read(cr,uid,ids,['categ_id','exclusif','partner_id', 'sales_purchase_active', 'profiling_active'])
213         for categ in categs:
214             if start:
215                 if categ['exclusif']:
216                     cr.execute('delete from res_partner_category_rel where category_id=%s', (categ['categ_id'][0],))
217
218             id = categ['id']            
219
220             cr.execute('select id from res_partner order by id ')
221             partners = [x[0] for x in cr.fetchall()]
222
223             if categ['sales_purchase_active']:
224                 to_remove_list=[]
225                 cr.execute('select id from crm_segmentation_line where segmentation_id=%s', (id,))
226                 line_ids = [x[0] for x in cr.fetchall()]
227
228                 for pid in partners:
229                     if (not self.pool.get('crm.segmentation.line').test(cr, uid, line_ids, pid)):
230                         to_remove_list.append(pid)
231                 for pid in to_remove_list:
232                     partners.remove(pid)
233
234             if categ['profiling_active']:
235                 to_remove_list=[]
236                 for pid in partners:
237
238                     cr.execute('select distinct(answer) from partner_question_rel where partner=%s',(pid,))
239                     answers_ids = [x[0] for x in cr.fetchall()]
240
241                     if (not test_prof(cr, uid, id, pid, answers_ids)):
242                         to_remove_list.append(pid)
243                 for pid in to_remove_list:
244                     partners.remove(pid)
245
246             for partner_id in partners:
247                 cr.execute('insert into res_partner_category_rel (category_id,partner_id) values (%s,%s)', (categ['categ_id'][0],partner_id))
248             cr.commit()
249
250             self.write(cr, uid, [id], {'state':'not running', 'partner_id':0})
251             cr.commit()
252         return True
253
254 crm_segmentation()
255 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
256