'Check that we have sufficient inv_item in stock to build the kits'

@staticmethod
def inv_kitting_onvalidate(form):

    form_vars = form.vars
    item_id = form_vars.item_id
    item_pack_id = form_vars.item_pack_id
    quantity = form_vars.quantity
    site_id = form_vars.site_id
    db = current.db
    s3db = current.s3db
    ktable = s3db.supply_kit_item
    ptable = db.supply_item_pack
    iitable = s3db.inv_inv_item
    query = (ktable.parent_item_id == item_id)
    rows = db(query).select(ktable.item_id, ktable.quantity, ktable.item_pack_id)
    p_id_field = ptable.id
    p_qty_field = ptable.quantity
    pack_qty = db((p_id_field == item_pack_id)).select(p_qty_field, limitby=(0, 1)).first().quantity
    quantity = (quantity * pack_qty)
    max_kits = None
    ii_pack_field = iitable.item_pack_id
    ii_qty_field = iitable.quantity
    ii_expiry_field = iitable.expiry_date
    squery = ((((iitable.site_id == site_id) & (iitable.deleted == False)) & ((ii_expiry_field >= current.request.now) | (ii_expiry_field == None))) & (iitable.status == 0))
    for record in rows:
        pack_qty = db((p_id_field == record.item_pack_id)).select(p_qty_field, limitby=(0, 1)).first().quantity
        one_kit = (record.quantity * pack_qty)
        stock_amount = 0
        query = (squery & (iitable.item_id == record.item_id))
        wh_items = db(query).select(ii_qty_field, ii_pack_field)
        for wh_item in wh_items:
            pack_qty = db((p_id_field == wh_item.item_pack_id)).select(p_qty_field, limitby=(0, 1)).first().quantity
            amount = (wh_item.quantity * pack_qty)
            stock_amount += amount
        kits = (stock_amount / one_kit)
        if (max_kits is None):
            max_kits = kits
        elif (kits < max_kits):
            max_kits = kits
    if (max_kits < quantity):
        form.errors.quantity = (current.T('You    can    only    make    %d    kit(s)    with    the    available    stock') % int(max_kits))
