Assigning lots following FEFO

Hi All,

I’m creating a custom code to force the assignation of stock moves using FEFO sorting. In order to do so, I added the following code:

class Move(metaclass=PoolMeta)
    __name__ = 'stock.move'

    @classmethod
    def assign_try(cls, moves, with_childs=True, grouping=('product', 'lot')):
        "Override default grouping to product and lot"
        return super().assign_try(
            moves, with_childs=with_childs, grouping=grouping)

    def pick_product(self, quantities):
        pool = Pool()
        Lot = pool.get('stock.lot')

        def get_lot(key):
            if len(key[0]) > 2 and key[0][2] is not None:
                return key[0][2]
            return None

        lot2expiry = {}
        def fefo_sorting(key):
            expiry = None
            lot = get_lot(key)
            if lot:
                expiry = lot2expiry.get(lot)
            return expiry or datetime.datetime.max

        lot_ids = set()
        for key in quantities:
            lot = get_lot(key)
            if lot:
                lot_ids.add(key[0][2])
        if lot_ids:
            lot2expiry.update({l.id: l.shelf_life_expiration_date
                    for l in Lot.browse(lot_ids)})
            quantities = list(sorted(quantities, key=fefo_sorting))
        return super().pick_product(quantities)

This works well but I’m not very happy with all the hard-coded indexes of the key (each place I use 2 I want to say “the lot part of the key”). As the grouping is forced to (‘product’, ‘lot’) this work well, but my code will crash I another variable is introduced on the grouping.

Is there any better way to achieve FEFO assignation?
Does it sound like a good idea to add the grouping keyword to the pick product, so from there we are able to pick the correct index for the lot (if required).

Any comments will be much appreciated.

I guess we should either pass the grouping to pick_product or add an extendable method to customize the sort of pbl_items based on grouping.
The later has the advantage to make a single sort.

https://bugs.tryton.org/issue10814