This file is indexed.

/usr/lib/python2.7/dist-packages/trytond/modules/stock_lot_sled/stock.py is in tryton-modules-stock-lot-sled 3.8.0-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import datetime

from sql import Union, Join, Select, Table, Null
from sql.conditionals import Greatest

from trytond.pool import PoolMeta, Pool
from trytond.model import ModelView, Workflow, fields
from trytond.pyson import Eval
from trytond.transaction import Transaction
from trytond.tools import grouped_slice

__all__ = ['Configuration', 'Lot', 'Move', 'Period']
__metaclass__ = PoolMeta

DATE_STATE = [
    ('none', 'None'),
    ('optional', 'Optional'),
    ('required', 'Required'),
    ]


class Configuration:
    __name__ = 'stock.configuration'

    shelf_life_delay = fields.Property(fields.Integer('Shelf Life Delay',
            help='The delay in number of days before '
            'removal from the forecast'))


class Lot:
    __name__ = 'stock.lot'

    shelf_life_expiration_date = fields.Date('Shelf Life Expiration Date',
        states={
            'required': (
                Eval('shelf_life_expiration_state', 'none') == 'required'),
            'invisible': Eval('shelf_life_expiration_state', 'none') == 'none',
            },
        depends=['shelf_life_expiration_state'])
    shelf_life_expiration_state = fields.Function(
        fields.Selection(DATE_STATE, 'Shelf Life Expiration State'),
        'on_change_with_shelf_life_expiration_state')
    expiration_date = fields.Date('Expiration Date',
        states={
            'required': Eval('expiration_state', 'none') == 'required',
            'invisible': Eval('expiration_state', 'none') == 'none',
            },
        depends=['expiration_state'])
    expiration_state = fields.Function(
        fields.Selection(DATE_STATE, 'Expiration State'),
        'on_change_with_expiration_state')

    @classmethod
    def __setup__(cls):
        super(Lot, cls).__setup__()
        cls._error_messages.update({
                'period_closed_expiration_dates': ('You can not modify '
                    'the expiration dates of lot "%(lot)s" because '
                    'it is used on a move "%(move)s" in a closed period'),
                })

    @fields.depends('product')
    def on_change_with_shelf_life_expiration_state(self, name=None):
        if self.product:
            return self.product.shelf_life_state
        return 'none'

    @fields.depends('product')
    def on_change_with_expiration_state(self, name=None):
        if self.product:
            return self.product.expiration_state
        return 'none'

    @fields.depends('product')
    def on_change_product(self):
        pool = Pool()
        Date = pool.get('ir.date')
        try:
            super(Lot, self).on_change_product()
        except AttributeError:
            pass
        if self.product:
            today = Date.today()
            if (self.product.shelf_life_state != 'none'
                    and self.product.shelf_life_time):
                self.shelf_life_expiration_date = (today
                    + datetime.timedelta(days=self.product.shelf_life_time))
            if (self.product.expiration_state != 'none'
                    and self.product.expiration_time):
                self.expiration_date = (today
                    + datetime.timedelta(days=self.product.expiration_time))

    @classmethod
    def write(cls, *args):
        super(Lot, cls).write(*args)

        actions = iter(args)
        for lots, values in zip(actions, actions):
            if any(f in ['shelf_life_expiration_date', 'expiration_date']
                    for f in values):
                cls.check_sled_period_closed(lots)

    @classmethod
    def check_sled_period_closed(cls, lots):
        Period = Pool().get('stock.period')
        Move = Pool().get('stock.move')
        periods = Period.search([
                ('state', '=', 'closed'),
                ], order=[('date', 'DESC')], limit=1)
        if not periods:
            return
        period, = periods
        for lots in grouped_slice(lots):
            lot_ids = [l.id for l in lots]
            moves = Move.search([
                    ('lot', 'in', lot_ids),
                    ['OR', [
                            ('effective_date', '=', None),
                            ('planned_date', '<=', period.date),
                            ],
                        ('effective_date', '<=', period.date),
                        ]], limit=1)
            if moves:
                move, = moves
                cls.raise_user_error('period_closed_expiration_dates', {
                        'lot': move.lot.rec_name,
                        'move': move.rec_name,
                        })


class Move:
    __name__ = 'stock.move'

    @classmethod
    def __setup__(cls):
        super(Move, cls).__setup__()
        cls._error_messages.update({
                'expiration_dates': ('The lot "%(lot)s" '
                    'on move "%(move)s" is expired'),
                })

    @classmethod
    @ModelView.button
    @Workflow.transition('done')
    def do(cls, moves):
        super(Move, cls).do(moves)
        cls.check_expiration_dates(moves)

    @classmethod
    def check_expiration_dates_types(cls):
        "Location types to check for expiration dates"
        return ['supplier', 'customer', 'production']

    @classmethod
    def check_expiration_dates_locations(cls):
        pool = Pool()
        Location = pool.get('stock.location')
        # Prevent pack expired products
        warehouses = Location.search([
                ('type', '=', 'warehouse'),
                ])
        return [w.output_location for w in warehouses]

    @property
    def to_check_expiration(self):
        if (self.lot
                and self.lot.shelf_life_expiration_date
                and self.effective_date > self.lot.shelf_life_expiration_date):
            return True
        return False

    @classmethod
    def check_expiration_dates(cls, moves):
        pool = Pool()
        Group = pool.get('res.group')
        User = pool.get('res.user')
        ModelData = pool.get('ir.model.data')

        types = cls.check_expiration_dates_types()
        locations = cls.check_expiration_dates_locations()

        def in_group():
            group = Group(ModelData.get_id('stock_lot_sled',
                    'group_stock_force_expiration'))
            transition = Transaction()
            user_id = transition.user
            if user_id == 0:
                user_id = transition.context.get('user', user_id)
            if user_id == 0:
                return True
            user = User(user_id)
            return group in user.groups

        for move in moves:
            if not move.to_check_expiration:
                continue
            if (move.from_location.type in types
                    or move.to_location.type in types
                    or move.from_location in locations
                    or move.to_location in locations):
                values = {
                    'move': move.rec_name,
                    'lot': move.lot.rec_name if move.lot else '',
                    }
                if not in_group():
                    cls.raise_user_error('expiration_dates', values)
                else:
                    cls.raise_user_warning('%s.check_expiration_dates' % move,
                        'expiration_dates', values)

    @classmethod
    def compute_quantities_query(cls, location_ids, with_childs=False,
            grouping=('product',), grouping_filter=None):
        pool = Pool()
        Date = pool.get('ir.date')
        Lot = pool.get('stock.lot')
        Config = pool.get('stock.configuration')

        query = super(Move, cls).compute_quantities_query(
            location_ids, with_childs=with_childs, grouping=grouping,
            grouping_filter=grouping_filter)

        context = Transaction().context
        today = Date.today()

        stock_date_end = context.get('stock_date_end') or datetime.date.max
        if query and ((stock_date_end == today and context.get('forecast'))
                or stock_date_end > today):
            lot = Lot.__table__()

            config = Config(1)
            if config.shelf_life_delay:
                expiration_date = stock_date_end + datetime.timedelta(
                    days=config.shelf_life_delay)
            else:
                expiration_date = stock_date_end

            def join(move):
                return move.join(lot, 'LEFT',
                    condition=move.lot == lot.id)

            def find_table(join):
                if not isinstance(join, Join):
                    return
                for pos in ['left', 'right']:
                    item = getattr(join, pos)
                    if isinstance(item, Table):
                        if item._name == cls._table:
                            return join, pos, getattr(join, pos)
                    else:
                        return find_table(item)

            def find_queries(query):
                if isinstance(query, Union):
                    for sub_query in query.queries:
                        for q in find_queries(sub_query):
                            yield q
                elif isinstance(query, Select):
                    yield query

            union, = query.from_
            for sub_query in find_queries(union):
                # Find move table
                for i, table in enumerate(sub_query.from_):
                    if isinstance(table, Table) and table._name == cls._table:
                        sub_query.from_[i] = join(table)
                        break
                    found = find_table(table)
                    if found:
                        join_, pos, table = found
                        setattr(join_, pos, join(table))
                        break
                else:
                    # Not query on move table
                    continue
                sub_query.where &= ((lot.shelf_life_expiration_date == Null)
                    | (lot.shelf_life_expiration_date >= expiration_date))
        return query


class Period:
    __name__ = 'stock.period'

    @classmethod
    def __setup__(cls):
        super(Period, cls).__setup__()
        cls._error_messages.update({
                'close_period_sled': ('You can not close a period '
                    'before the Shelf Live Expiration Date "%(date)s" '
                    'of Lot "%(lot)s"'),
                })

    @classmethod
    @ModelView.button
    def close(cls, periods):
        pool = Pool()
        Move = pool.get('stock.move')
        Lot = pool.get('stock.lot')
        Date = pool.get('ir.date')
        Lang = pool.get('ir.lang')
        cursor = Transaction().cursor
        move = Move.__table__()
        lot = Lot.__table__()

        super(Period, cls).close(periods)

        # Don't allow to close a period if all products at this date
        # are not yet expired
        recent_date = max(period.date for period in periods)
        today = Date.today()

        query = move.join(lot, 'INNER',
            condition=move.lot == lot.id).select(lot.id,
                where=(Greatest(move.effective_date, move.planned_date)
                    <= recent_date)
                & (lot.shelf_life_expiration_date >= today)
                )
        cursor.execute(*query)
        lot_id = cursor.fetchone()
        if lot_id:
            lot_id, = lot_id
            lot = Lot(lot_id)
            lang, = Lang.search([
                    ('code', '=', Transaction().language),
                    ])
            date = Lang.strftime(
                lot.shelf_life_expiration_date, lang.code, lang.date)
            cls.raise_user_error('close_period_sled', {
                    'date': date,
                    'lot': lot.rec_name,
                    })