~unifield-team/unifield-wm/us-826

0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
1
# -*- coding: utf-8 -*-
2
##############################################################################
3
#
4
#    OpenERP, Open Source Management Solution
5
#    Copyright (C) 2011 TeMPO Consulting, MSF 
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 osv, fields
23
24
import time
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
25
import re
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
26
27
from tools.translate import _
28
from dateutil.relativedelta import relativedelta
0.11.3 by Quentin THEURET
UF-73: [IMP] Added yearly planification in scheduler
29
from datetime import date, datetime
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
30
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
31
from mx.DateTime import *
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
32
import math
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
33
34
35
WEEK_DAYS = [('sunday', 'Sunday'), ('monday', 'Monday'),
36
             ('tuesday', 'Tuesday'), ('wednesday', 'Wednesday'),
37
             ('thursday', 'Thursday'), ('friday', 'Friday'), 
38
             ('saturday', 'Saturday')]
39
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
40
FREQUENCY = [(1, 'The first'), (2, 'The second'),
41
             (3, 'The third'), (4, 'The fourth'), (5, 'The fifth'),
42
             (-1, 'The last')]
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
43
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
44
MONTHS = [(1, 'January'), (2, 'February'), (3,'March'),
45
          (4, 'April'), (5, 'May'), (6, 'June'),
46
          (7, 'July'), (8, 'August'), (9, 'September'),
47
          (10, 'October'), (11, 'November'), (12, 'December'),]
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
48
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
49
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
50
class stock_frequence(osv.osv):
51
    _name = 'stock.frequence'
52
    _description = 'Stock scheduler'
53
    
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
54
    def get_selection(self, cr, uid, o, field):
55
        """
56
        Returns the field.selection label
57
        """
58
        sel = self.pool.get(o._name).fields_get(cr, uid, [field])
59
        res = dict(sel[field]['selection']).get(getattr(o,field),getattr(o,field))
60
        name = '%s,%s' % (o._name, field)
61
        tr_ids = self.pool.get('ir.translation').search(cr, uid, [('type', '=', 'selection'), ('name', '=', name),('src', '=', res)])
62
        if tr_ids:
63
            return self.pool.get('ir.translation').read(cr, uid, tr_ids, ['value'])[0]['value']
64
        else:
65
            return res
66
    
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
67
    def get_datetime_day(self, monthly_choose_day):
68
        '''
0.11.3 by Quentin THEURET
UF-73: [IMP] Added yearly planification in scheduler
69
        Return the good Date value according to the type of the day param.
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
70
        '''
71
        # Get the day number of the selected day
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
72
        data = {'sunday': 6, 'monday':0, 'tuesday': 1, 'wednesday': 2, 'thursday': 3, 'friday': 4, 'saturday': 5}
73
        return data.get(monthly_choose_day, 6)
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
74
    
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
75
    def check_data(self, data):
76
        '''
77
        Check if all required data aren't empty
78
        '''
559.30.10 by Quentin THEURET
UF-873 [FIX] Fix error on daily configuration
79
        if data['name'] == 'weekly':
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
80
            if (not 'weekly_sunday_ok' in data or not data.get('weekly_sunday_ok', False)) and \
81
               (not 'weekly_monday_ok' in data or not data.get('weekly_monday_ok', False)) and \
82
               (not 'weekly_tuesday_ok' in data or not data.get('weekly_tuesday_ok', False)) and \
83
               (not 'weekly_wednesday_ok' in data or not data.get('weekly_wednesday_ok', False)) and \
84
               (not 'weekly_thursday_ok' in data or not data.get('weekly_thursday_ok', False)) and \
85
               (not 'weekly_friday_ok' in data or not data.get('weekly_friday_ok', False)) and \
86
               (not 'weekly_saturday_ok' in data or not data.get('weekly_saturday_ok', False)):
87
                raise osv.except_osv(_('Error'), _('You should choose at least one day of week !'))
88
        elif data['name'] == 'monthly':
89
            if (not 'monthly_one_day' in data or not data.get('monthly_one_day', False)) and \
90
               (not 'monthly_repeating_ok' in data or not data.get('monthly_repeating_ok', False)):
91
                raise osv.except_osv(_('Error'), _('You should make a choice for the Monthly configuration'))
92
            elif 'monthly_repeating_ok' in data and data.get('monthly_repeating_ok', False):
93
                # Check if at least one day of month is selected
94
                test = False
95
                i = 0
96
                while i < 32 and not test:
97
                    i += 1
0.11.5 by Quentin THEURET
UF-73: [FIX] Fixed a bug on monthly next date computation
98
                    if i <10:
99
                        field = 'monthly_day0%s' %str(i)
100
                    else:
101
                        field = 'monthly_day%s' %str(i)
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
102
                    if field in data and data.get(field, False):
103
                        test = True
104
                if not test:
105
                    raise osv.except_osv(_('Error'), _('You should select at least one day of the month !'))
106
        elif data['name'] == 'yearly':
107
            if (not 'yearly_day_ok' in data or not data.get('yearly_day_ok', False)) and \
108
               (not 'yearly_date_ok' in data or not data.get('yearly_date_ok', False)):
109
                raise osv.except_osv(_('Error'), _('You should make a choice for the Yearly configuration'))
110
        
111
        if (not 'no_end_date' in data or not data.get('no_end_date', False)) and \
112
           (not 'end_date_ok' in data or not data.get('end_date_ok', False)) and \
113
           (not 'recurrence_ok' in data or not data.get('recurrence_ok', False)):
114
            raise osv.except_osv(_('Error'), _('You should make a choice for the Replenishment repeating !'))
115
        
116
        return
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
117
  
118
    def copy(self, cr, uid, id, default=None, context=None):
119
        if not default:
120
            default = {}
121
        default['last_run'] = False
122
        return super(stock_frequence, self).copy(cr, uid, id, default, context)
123
706 by jf
[FIX] context None
124
    def create(self, cr, uid, data, context=None):
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
125
        '''
126
        Check if all required data aren't empty
127
        '''
128
        self.check_data(data)
129
        
130
        return super(stock_frequence, self).create(cr, uid, data, context=context)
131
    
706 by jf
[FIX] context None
132
    def write(self, cr, uid, ids, data, context=None):
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
133
        '''
134
        Check if all required data aren't empty
135
        '''
0.11.8 by Quentin THEURET
UF-73: [IMP] Modified stock frequence view to be use with a wizard
136
        if isinstance(ids, (int, long)):
137
            ids = [ids]
138
            
0.11.16 by Quentin THEURET
UF-73: [FIX] Fixed some bugs (search product by category, store function for refresh next date, sequence not incremented...
139
        data_bis = data.copy()
140
            
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
141
        for field in self._columns:
0.11.16 by Quentin THEURET
UF-73: [FIX] Fixed some bugs (search product by category, store function for refresh next date, sequence not incremented...
142
            if field not in data_bis:
143
                data_bis[field] = self.read(cr, uid, ids, [field])[0][field]
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
144
        
0.11.16 by Quentin THEURET
UF-73: [FIX] Fixed some bugs (search product by category, store function for refresh next date, sequence not incremented...
145
        self.check_data(data_bis)
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
146
        
147
        return super(stock_frequence, self).write(cr, uid, ids, data, context=context)
148
    
706 by jf
[FIX] context None
149
    def _compute_end_date(self, cr, uid, ids, field, arg, context=None):
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
150
        '''
151
        Compute the end date of the frequence according to the field of the object
152
        '''
153
        if isinstance(ids, (int, long)):
154
            ids = [ids]
155
            
156
        res = {}
157
            
158
        for obj in self.browse(cr, uid, ids):
159
            res[obj.id] = False
160
            if obj.end_date_ok:
161
                res[obj.id] = obj.end_date
162
            if obj.recurrence_ok:
163
                start_date = datetime.strptime(obj.start_date, '%Y-%m-%d')
164
                if obj.recurrence_type == 'day':
165
                    res[obj.id] = (start_date + relativedelta(days=obj.recurrence_nb)).strftime('%Y-%m-%d')
166
                elif obj.recurrence_type == 'week':
167
                    res[obj.id] = (start_date + relativedelta(weeks=obj.recurrence_nb)).strftime('%Y-%m-%d')
168
                elif obj.recurrence_type == 'month':
169
                    res[obj.id] = (start_date + relativedelta(months=obj.recurrence_nb)).strftime('%Y-%m-%d')
170
                elif obj.recurrence_type == 'year':
171
                    res[obj.id] = (start_date + relativedelta(years=obj.recurrence_nb)).strftime('%Y-%m-%d')
172
            
173
        return res
174
    
175
    def _compute_next_daily_date(self, cr, uid, frequence_id):
176
        '''
177
        Compute the next date when the frequence is a daily frequence
178
        '''
179
        if not isinstance(frequence_id, (int, long)):
180
            raise osv.except_osv(_('Error'), _('You should pass a integer to the _compute_next_daily_date'))
181
        
182
        frequence = self.browse(cr, uid, frequence_id)
183
        if frequence.name != 'daily':
184
            return False
185
        else:
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
186
            start_date = strptime(frequence.start_date, '%Y-%m-%d')
187
            if start_date > today():
188
                return start_date
189
190
            if not frequence.last_run:
191
                return today()
192
                #numdays = (today() - start_date).day
193
                #modulo = math.ceil(numdays/frequence.daily_frequency_ok)*frequence.daily_frequency_ok
194
                #return start_date+RelativeDate(days=modulo)
195
            return max(today(), strptime(frequence.last_run, '%Y-%m-%d')+RelativeDate(days=frequence.daily_frequency))
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
196
        
197
    def _compute_next_weekly_date(self, cr, uid, frequence_id):
198
        '''
199
        Compute the next date when the frequence is a weekly frequence
200
        '''
201
        if not isinstance(frequence_id, (int, long)):
202
            raise osv.except_osv(_('Error'), _('You should pass a integer to the _compute_next_weekly_date'))
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
203
        
204
        frequence = self.browse(cr, uid, frequence_id)
205
        if frequence.name != 'weekly':
206
            return False
207
        else:
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
208
            data = ['monday','tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
209
210
            if not frequence.weekly_sunday_ok and not frequence.weekly_monday_ok and not frequence.weekly_tuesday_ok \
211
                and not frequence.weekly_wednesday_ok and not frequence.weekly_thursday_ok and not frequence.weekly_friday_ok \
212
                and not frequence.weekly_saturday_ok:
213
                   raise osv.except_osv(_('Error'), _('You should choose at least one day of week !'))
0.11.3 by Quentin THEURET
UF-73: [IMP] Added yearly planification in scheduler
214
            
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
215
            if not frequence.last_run:
216
                start_date = strptime(frequence.start_date, '%Y-%m-%d')
217
                if start_date < today():
218
                    start_date = today()
219
                while True:
220
                    i = start_date.weekday()
221
                    if getattr(frequence, 'weekly_%s_ok'%(data[i])):
222
                        return start_date
223
                    start_date += RelativeDate(days=1)
224
225
            next_date = strptime(frequence.last_run, '%Y-%m-%d')+RelativeDate(days=1)
226
            while True:
227
                if getattr(frequence, 'weekly_%s_ok'%(data[next_date.weekday()])):
228
                    return max(today(), next_date)
229
                next_date += RelativeDate(days=1)
230
                if next_date.weekday() == 0:
231
                    next_date += RelativeDate(weeks=frequence.weekly_frequency-1) 
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
232
        
233
        return False
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
234
    
235
    def _compute_next_monthly_date(self, cr, uid, frequence_id):
236
        '''
237
        Compute the next date when the frequence is a monthly frequence
238
        '''
239
        if not isinstance(frequence_id, (int, long)):
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
240
            raise osv.except_osv(_('Error'), _('You should pass a integer to the _compute_next_weekly_date'))
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
241
        
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
242
        frequence = self.browse(cr, uid, frequence_id)
243
        if frequence.name != 'monthly':
244
            return False
245
        else:
246
            if frequence.monthly_one_day:
247
                day = self.get_datetime_day(frequence.monthly_choose_day)
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
248
                if frequence.last_run:
249
                    from_date = strptime(frequence.last_run, '%Y-%m-%d')
250
                    return max(today(), from_date + RelativeDate(months=+frequence.monthly_frequency, weekday=(day,frequence.monthly_choose_freq)))
251
                else:
252
                    start_date = strptime(frequence.start_date, '%Y-%m-%d')
253
                    if start_date < today():
254
                        start_date = today()
255
                    next_date = start_date + RelativeDate(weekday=(day,frequence.monthly_choose_freq))
358.4.4 by Quentin THEURET
UF-519-520 [FIX] Fixed the domain on locations on AMC calculation method
256
                    while next_date < start_date:
257
                        next_date = next_date + RelativeDate(months=1, weekday=(day,frequence.monthly_choose_freq))
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
258
                    return next_date
259
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
260
            elif frequence.monthly_repeating_ok:
261
                days_ok = []
262
                # Get all fields for choosen days
263
                fields = []
264
                for col in self._columns:
265
                    if re.match('^monthly_day[0-9]', col):
266
                        fields.append(col)
267
                frequence_read = self.read(cr, uid, [frequence_id], fields)[0]
268
                for f in fields:
269
                    if frequence_read[f]:
270
                        days_ok.append(int(f[-2:]))
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
271
                days_ok.sort()
272
273
                if frequence.last_run:
274
                    from_date = strptime(frequence.last_run, '%Y-%m-%d')+RelativeDateTime(days=1)
275
                    force = True
276
                else:
277
                    from_date = strptime(frequence.start_date, '%Y-%m-%d')
278
                    if from_date < today():
279
                        from_date = today()
280
                    force = False
281
               
282
                if from_date.day > days_ok[-1]:
283
                    # switch to next month
284
                    if force:
285
                        from_date += RelativeDate(day=days_ok[0], months=frequence.monthly_frequency)
286
                        return max(today(), from_date)
287
                    else:
288
                        from_date += RelativeDate(day=days_ok[0], months=1)
289
                        return from_date
290
291
                days = filter(lambda a: a>=from_date.day , days_ok)
292
                from_date += RelativeDate(day=days[0])
293
                if force:
294
                    return max(today(), from_date)
295
                return from_date
296
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
297
        return False
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
298
        
299
    def _compute_next_yearly_date(self, cr, uid, frequence_id):
300
        '''
301
        Compute the next date when the frequence is a yearly frequence
302
        '''
303
        if not isinstance(frequence_id, (int, long)):
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
304
            raise osv.except_osv(_('Error'), _('You should pass a integer to the _compute_next_weekly_date'))
305
        
306
        frequence = self.browse(cr, uid, frequence_id)
307
        if frequence.name != 'yearly':
308
            return False
309
        else:
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
310
            start_date = strptime(frequence.start_date, '%Y-%m-%d')
311
            if start_date < today():
312
                start_date = today()
313
            if not frequence.last_run:
314
                if frequence.yearly_day_ok:
315
                    next_date = start_date + RelativeDate(month=frequence.yearly_choose_month, day=frequence.yearly_day)
316
                    if next_date < start_date:
317
                        return start_date + RelativeDate(month=frequence.yearly_choose_month, day=frequence.yearly_day, years=1)
318
                    return next_date
319
                if frequence.yearly_date_ok:
320
                    day = self.get_datetime_day(frequence.yearly_choose_day)
321
                    next_date = start_date + RelativeDate(month=frequence.yearly_choose_month_freq, weekday=(day, frequence.yearly_choose_freq))
322
                    if next_date < start_date:
323
                        return start_date + RelativeDate(years=1, month=frequence.yearly_choose_month_freq, weekday=(day, frequence.yearly_choose_freq))
324
                    return next_date
325
326
            next_date = strptime(frequence.last_run, '%Y-%m-%d')
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
327
            if frequence.yearly_day_ok:
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
328
                next_date += RelativeDate(years=frequence.yearly_frequency, month=frequence.yearly_choose_month, day=frequence.yearly_day)
329
            else:
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
330
                day = self.get_datetime_day(frequence.yearly_choose_day)
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
331
                next_date += RelativeDate(years=frequence.yearly_frequency, month=frequence.yearly_choose_month_freq, weekday=(day, frequence.yearly_choose_freq)) 
332
            return max(today(), next_date)
333
0.11.2 by Quentin THEURET
UF-73: [IMP] Added computed next date for daily, weekly and monthly parameter
334
        return False
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
335
        
706 by jf
[FIX] context None
336
    def _compute_next_date(self, cr, uid, ids, field, arg, context=None):
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
337
        '''
338
        Compute the next date matching with the parameter of the frequency
339
        '''
340
        if isinstance(ids, (int, long)):
341
            ids = [ids]
342
            
343
        res = {}
344
            
345
        for frequence in self.browse(cr, uid, ids):
346
            if frequence.calculated_end_date and datetime.strptime(frequence.calculated_end_date, '%Y-%m-%d') < datetime.now():
347
                res[frequence.id] = False
348
            else:
349
                if frequence.name == 'daily':
0.11.4 by Quentin THEURET
UF-73: [IMP] Added a message in next date if the end date is in the past
350
                    next_date = self._compute_next_daily_date(cr, uid, frequence.id).strftime('%Y-%m-%d')
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
351
                elif frequence.name == 'weekly':
0.11.4 by Quentin THEURET
UF-73: [IMP] Added a message in next date if the end date is in the past
352
                    next_date = self._compute_next_weekly_date(cr, uid, frequence.id).strftime('%Y-%m-%d')
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
353
                elif frequence.name == 'monthly':
0.11.4 by Quentin THEURET
UF-73: [IMP] Added a message in next date if the end date is in the past
354
                    next_date = self._compute_next_monthly_date(cr, uid, frequence.id).strftime('%Y-%m-%d')
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
355
                elif frequence.name == 'yearly':
0.11.4 by Quentin THEURET
UF-73: [IMP] Added a message in next date if the end date is in the past
356
                    next_date = self._compute_next_yearly_date(cr, uid, frequence.id).strftime('%Y-%m-%d')
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
357
                else:
358
                    res[frequence.id] = False
0.11.4 by Quentin THEURET
UF-73: [IMP] Added a message in next date if the end date is in the past
359
                    
73.1.4 by jf
UF-73
360
                if frequence.calculated_end_date and datetime.strptime(next_date, '%Y-%m-%d') >= datetime.strptime(frequence.calculated_end_date, '%Y-%m-%d'):
361
                    res[frequence.id] = False
0.11.4 by Quentin THEURET
UF-73: [IMP] Added a message in next date if the end date is in the past
362
                else:
363
                    res[frequence.id] = next_date
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
364
        
365
        return res
366
    
706 by jf
[FIX] context None
367
    def choose_frequency(self, cr, uid, ids, context=None):
0.11.8 by Quentin THEURET
UF-73: [IMP] Modified stock frequence view to be use with a wizard
368
        '''
369
        Empty method. Override this method to implement your own features
370
        '''
371
        return {'type': 'ir.actions.act_window_close'}
372
    
706 by jf
[FIX] context None
373
    def name_get(self, cr, uid, ids, context=None):
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
374
        '''
375
        Returns a description of the frequence
376
        '''
377
        res = super(stock_frequence, self).name_get(cr, uid, ids, context=context)
378
        
379
        # TODO: Modif of name_get method to return a comprehensive name for frequence
380
        res = []
381
        
382
        for freq in self.browse(cr, uid, ids):
383
            if freq.name == 'daily':
384
                if freq.daily_frequency_ok:
656 by jf
[FIX] translate format
385
                    title = _('Every %d day(s)') % (freq.daily_frequency,)
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
386
            if freq.name == 'weekly':
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
387
                sunday = monday = tuesday = wednesday = thursday = friday = saturday = ''
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
388
                if freq.weekly_sunday_ok:
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
389
                    sunday = 'sunday '
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
390
                if freq.weekly_monday_ok:
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
391
                    monday = 'monday '
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
392
                if freq.weekly_tuesday_ok:
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
393
                    tuesday = 'tuesday '
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
394
                if freq.weekly_wednesday_ok:
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
395
                    wednesday = 'wednesday '
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
396
                if freq.weekly_thursday_ok:
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
397
                    thursday = 'thursday '
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
398
                if freq.weekly_friday_ok:
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
399
                    friday = 'friday '
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
400
                if freq.weekly_saturday_ok:
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
401
                    saturday = 'saturday '
656 by jf
[FIX] translate format
402
                title = _('Every %d week(s) on %s%s%s%s%s%s%s') %(freq.weekly_frequency, sunday, monday, tuesday, \
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
403
                                                                 wednesday, thursday, \
656 by jf
[FIX] translate format
404
                                                                 friday, saturday)
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
405
            if freq.name == 'monthly':
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
406
                if freq.monthly_one_day:
407
                    choose_freq = self.get_selection(cr, uid, freq, 'monthly_choose_freq')
408
                    choose_day = self.get_selection(cr, uid, freq, 'monthly_choose_day')
656 by jf
[FIX] translate format
409
                    title = _('%s %s - Every %s month(s)') % (choose_freq, choose_day, freq.monthly_frequency)
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
410
                elif freq.monthly_repeating_ok:
73.1.4 by jf
UF-73
411
                    title = _('On ')
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
412
                    i = 1
413
                    # For each days
414
                    while i < 32:
415
                        day_f = 'th'
416
                        field = i < 10 and '0%s' %i or '%s' %i
417
                        if i in (1, 21, 31):
418
                            day_f = 'st'
419
                        elif i in (2, 22):
420
                            day_f = 'nd'
421
                        elif i in (3, 23):
422
                            day_f = 'rd'
423
                        day_ok = self.read(cr, uid, [freq.id], ['monthly_day%s' %field])[0]['monthly_day%s' %field]
424
                        title += day_ok and 'the %s%s, ' %(i, day_f) or ''
425
                        i += 1
426
                    # Remove the last comma
427
                    title = title[:-2]
656 by jf
[FIX] translate format
428
                    title += _(' - Every %s month(s)') % (freq.monthly_frequency,)
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
429
            if freq.name == 'yearly':
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
430
                if freq.yearly_day_ok:
431
                    month = self.get_selection(cr, uid, freq, 'yearly_choose_month')
432
                    day_f = 'th'
433
                    if freq.yearly_day in (1, 21, 31):
434
                        day_f = 'st'
435
                    elif freq.yearly_day in (2, 22):
436
                        day_f = 'nd'
437
                    elif freq.yearly_day in (3, 23):
438
                        day_f = 'rd'
656 by jf
[FIX] translate format
439
                    title = _('All %s, the %s%s') %(month, freq.yearly_day, day_f)
2.17.7 by Quentin THEURET
UF-73: [IMP] Added name_get function to stock.frequence
440
                elif freq.yearly_date_ok:
441
                    frequence = self.get_selection(cr, uid, freq, 'yearly_choose_freq')
442
                    day = self.get_selection(cr, uid, freq, 'yearly_choose_day')
443
                    month = self.get_selection(cr, uid, freq, 'yearly_choose_month_freq')
656 by jf
[FIX] translate format
444
                    title = _('All %s %s in %s') % (frequence, day, month)
445
                title += _(' - Every %s year(s)') %(freq.yearly_frequency)
2.17.6 by Quentin THEURET
UF-73: [IMP] Fixed error on quantity computation
446
                
447
            res.append((freq.id, title))
448
        
449
        return res
450
    
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
451
    _columns = {
452
        'name': fields.selection([('daily', 'Daily'), ('weekly', 'Weekly'),
453
                                  ('monthly', 'Monthly'), ('yearly', 'Yearly')],
454
                                  string='Frequence', required=True),
455
                                  
456
        # Daily configuration
457
        'daily_frequency_ok': fields.boolean(string='Frequence'),
73.1.4 by jf
UF-73
458
        'daily_frequency': fields.integer(string='Every'),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
459
        
460
        # Weekly configuration
73.1.4 by jf
UF-73
461
        'weekly_frequency': fields.integer(string='Every'),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
462
        'weekly_sunday_ok': fields.boolean(string="Sunday"),
463
        'weekly_monday_ok': fields.boolean(string="Monday"),
464
        'weekly_tuesday_ok': fields.boolean(string="Tuesday"),
465
        'weekly_wednesday_ok': fields.boolean(string="Wednesday"),
466
        'weekly_thursday_ok': fields.boolean(string="Thursday"),
467
        'weekly_friday_ok': fields.boolean(string="Friday"),
0.11.7 by Quentin THEURET
UF-73: [ADD] Added security file
468
        'weekly_saturday_ok': fields.boolean(string="Saturday"),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
469
        
470
        # Monthly configuration
73.1.4 by jf
UF-73
471
        'monthly_frequency': fields.integer(string='Every'),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
472
        'monthly_one_day': fields.boolean(string='One day'),
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
473
        'monthly_choose_freq': fields.selection(FREQUENCY, string='Choose frequence', size=-1),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
474
        'monthly_choose_day': fields.selection(WEEK_DAYS,string='Choose days'),
475
        'monthly_repeating_ok': fields.boolean(string='Repeatition'),
73.1.4 by jf
UF-73
476
        'monthly_day01': fields.boolean(string='1st'),
477
        'monthly_day02': fields.boolean(string='2nd'),
478
        'monthly_day03': fields.boolean(string='3rd'),
479
        'monthly_day04': fields.boolean(string='4th'),
480
        'monthly_day05': fields.boolean(string='5th'),
481
        'monthly_day06': fields.boolean(string='6th'),
482
        'monthly_day07': fields.boolean(string='7th'),
483
        'monthly_day08': fields.boolean(string='8th'),
484
        'monthly_day09': fields.boolean(string='9th'),
485
        'monthly_day10': fields.boolean(string='10th'),
486
        'monthly_day11': fields.boolean(string='11th'),
487
        'monthly_day12': fields.boolean(string='12th'),
488
        'monthly_day13': fields.boolean(string='13th'),
489
        'monthly_day14': fields.boolean(string='14th'),
490
        'monthly_day15': fields.boolean(string='15th'),
491
        'monthly_day16': fields.boolean(string='16th'),
492
        'monthly_day17': fields.boolean(string='17th'),
493
        'monthly_day18': fields.boolean(string='18th'),
494
        'monthly_day19': fields.boolean(string='19th'),
495
        'monthly_day20': fields.boolean(string='20th'),
496
        'monthly_day21': fields.boolean(string='21st'),
497
        'monthly_day22': fields.boolean(string='22nd'),
498
        'monthly_day23': fields.boolean(string='23rd'),
499
        'monthly_day24': fields.boolean(string='24th'),
500
        'monthly_day25': fields.boolean(string='25th'),
501
        'monthly_day26': fields.boolean(string='26th'),
502
        'monthly_day27': fields.boolean(string='27th'),
503
        'monthly_day28': fields.boolean(string='28th'),
504
        'monthly_day29': fields.boolean(string='29th'),
505
        'monthly_day30': fields.boolean(string='30th'),
506
        'monthly_day31': fields.boolean(string='31st'),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
507
        
508
        # Yearly configuration
73.1.4 by jf
UF-73
509
        'yearly_frequency': fields.integer(string='Every'),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
510
        'yearly_day_ok': fields.boolean(string='Days'),
511
        'yearly_day': fields.integer(string='Day'),
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
512
        'yearly_choose_month': fields.selection(MONTHS, string='Choose a month', size=-1),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
513
        'yearly_date_ok': fields.boolean(string='Date'),
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
514
        'yearly_choose_freq': fields.selection(FREQUENCY, string='Choose frequence', size=-1),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
515
        'yearly_choose_day': fields.selection(WEEK_DAYS, string='Choose day'),
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
516
        'yearly_choose_month_freq': fields.selection(MONTHS, string='Choose a month', size=-1),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
517
        
518
        # Recurrence configuration
519
        'start_date': fields.date(string='Start date', required=True),
520
        'end_date_ok': fields.boolean(string='End date'),
73.1.4 by jf
UF-73
521
        'end_date': fields.date(string='Until'),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
522
        'no_end_date': fields.boolean(string='No end date'),
523
        'recurrence_ok': fields.boolean(string='Reccurence'),
524
        'recurrence_nb': fields.integer(string='Continuing for'),
525
        'recurrence_type': fields.selection([('day', 'Day(s)'), ('week', 'Week(s)'),
526
                                             ('month', 'Month(s)'), ('year', 'Year(s)')],
527
                                             string='Type of reccurence'),
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
528
529
        'last_run': fields.date(string='Last run', readonly=True),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
530
        'calculated_end_date': fields.function(_compute_end_date, method=True, type='date', string='End date', store=False),
0.11.14 by Quentin THEURET
UF-73: [IMP] Added store function to recompute next_date on Automatic Supply
531
        'next_date': fields.function(_compute_next_date, method=True, type='date', string='Next date', store=False),
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
532
    }
533
    
534
    _defaults = {
535
        'name': lambda *a: 'daily',
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
536
        'monthly_choose_freq': lambda *a: 1,
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
537
        'monthly_choose_day': lambda *a: 'monday',
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
538
        'yearly_choose_month': lambda *a: 1,
539
        'yearly_choose_freq': lambda *a: 1,
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
540
        'yearly_choose_day': lambda *a: 'monday',
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
541
        'yearly_choose_month_freq': lambda *a: 1,
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
542
        'daily_frequency': lambda *a: 1,
543
        'weekly_frequency': lambda *a: 1,
544
        'monthly_frequency': lambda *a: 1,
545
        'yearly_frequency': lambda *a: 1,
546
        'yearly_day': lambda *a: 1,
547
        'recurrence_nb': lambda *a: 1,
548
        'recurrence_type': lambda *a: 'day',
549
        'no_end_date': lambda *a: True,
550
        'yearly_day_ok': lambda *a: True,
551
        'monthly_one_day': lambda *a: True,
552
        'daily_frequency_ok': lambda *a: True,
553
        'weekly_monday_ok': lambda *a: True,
554
        'start_date': lambda *a: time.strftime('%Y-%m-%d'),
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
555
        'last_run': lambda *a: False,
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
556
    }
557
    
0.11.6 by Quentin THEURET
UF-73: [FIX] Fixed a bug on yearly next date computation
558
    def check_date_in_month(self, cr, uid, ids, day, month):
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
559
        '''
560
        Checks if the date in parameter is higher than 1 and smaller than 31 
561
        '''
0.11.6 by Quentin THEURET
UF-73: [FIX] Fixed a bug on yearly next date computation
562
        warning = True
563
        warn = {}
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
564
        
0.11.6 by Quentin THEURET
UF-73: [FIX] Fixed a bug on yearly next date computation
565
        if day < 1:
566
            day = 1
73.1.6 by jf
UF-73: [FIX] months as integer
567
        elif month == 2 and day > 29:
0.11.6 by Quentin THEURET
UF-73: [FIX] Fixed a bug on yearly next date computation
568
            day = 28
73.1.6 by jf
UF-73: [FIX] months as integer
569
        elif month in [4, 6, 9, 11] and day > 30:
0.11.6 by Quentin THEURET
UF-73: [FIX] Fixed a bug on yearly next date computation
570
            day = 30
571
        elif day > 31:
572
            day = 31
73.1.6 by jf
UF-73: [FIX] months as integer
573
        elif month == 2 and day == 29:
0.11.6 by Quentin THEURET
UF-73: [FIX] Fixed a bug on yearly next date computation
574
            warn = {'title': _('Warning'), 
575
                    'message': _('You have selected February, the 29th as shedule date. For non leap years, the action will be run on March, the 1st !')}
576
        else:
577
            warning = False
578
            
579
#        if warning:
580
#            warn = {'title': _('Error'), 
581
#                    'message': _('The entered number is not a valid number of day')}
582
#        
583
        return {'warning': warn, 'value': {'yearly_day': day}}
0.11.1 by Quentin THEURET
UF-78: [ADD] Added scheduler views and object
584
    
585
    
586
    def monthly_freq_change(self, cr, uid, ids, monthly_one_day=False, monthly_repeating_ok=False):
587
        '''
588
        Uncheck automatically the other choose when one is choosing
589
        '''
590
        if monthly_one_day:
591
            return {'value': {'monthly_repeating_ok': False}}
592
        if monthly_repeating_ok:
593
            return {'value': {'monthly_one_day': False}}
594
        
595
        return {}
596
    
597
    def yearly_freq_change(self, cr, uid, ids, yearly_day_ok=False, yearly_date_ok=False):
598
        '''
599
        Uncheck automatically the other choose when one is choosing
600
        '''
601
        if yearly_day_ok:
602
            return {'value': {'yearly_date_ok': False}}
603
        if yearly_date_ok:
604
            return {'value': {'yearly_day_ok': False}}
605
        
606
        return {}
607
    
608
    def change_recurrence(self, cr, uid, ids, field, no_end_date=False, end_date_ok=False, recurrence_ok=False):
609
        '''
610
        Uncheck automatically the other choose when one is choosing
611
        '''
612
        if no_end_date and field == 'no_end_date':
613
            return {'value': {'end_date_ok': False, 'recurrence_ok': False}}
614
        if end_date_ok and field == 'end_date_ok':
615
            return {'value': {'no_end_date': False, 'recurrence_ok': False}}
616
        if recurrence_ok and field == 'recurrence_ok':
617
            return {'value': {'end_date_ok': False, 'no_end_date': False}}
618
        
619
        return {}
620
    
621
stock_frequence()
622
73.1.3 by jf
UF-43 [FIX] bugs, rewrite of compute next date
623
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: