'Match a Request\'s Items with a Site\'s Inventory'

@staticmethod
def inv_match(r, **attr):

    T = current.T
    db = current.db
    s3db = current.s3db
    response = current.response
    s3 = response.s3
    output = dict(title=T('Check    Request'), rheader=req_rheader(r, check_page=True), subtitle=T('Requested    Items'))
    table = s3db.req_req_item
    query = ((table.req_id == r.id) & (table.deleted == False))
    req_items = db(query).select(table.id, table.item_id, table.quantity, table.item_pack_id, table.quantity_commit, table.quantity_transit, table.quantity_fulfil)
    if len(req_items):
        site_id = (r.get_vars.get('site_id') or current.auth.user.site_id)
        if site_id:
            site_name = s3db.org_site_represent(site_id, show_link=False)
            qty_in_label = (s3_unicode(T('Quantity    in    %s')) % site_name)
        else:
            qty_in_label = T('Quantity    Available')
        row = TR(TH(table.item_id.label), TH(table.quantity.label), TH(table.item_pack_id.label), TH(T('Quantity    Oustanding')), TH(qty_in_label), TH(T('Match?')))
        items = TABLE(THEAD(row), _id='list', _class='dataTable    display')
        if site_id:
            stable = s3db.org_site
            ltable = s3db.gis_location
            query = ((stable.id == site_id) & (stable.location_id == ltable.id))
            location_r = db(query).select(ltable.lat, ltable.lon, limitby=(0, 1)).first()
            query = ((stable.id == r.record.site_id) & (stable.location_id == ltable.id))
            req_location_r = db(query).select(ltable.lat, ltable.lon, limitby=(0, 1)).first()
            try:
                distance = current.gis.greatCircleDistance(location_r.lat, location_r.lon, req_location_r.lat, req_location_r.lon)
                output['rheader'][0].append(TR(TH((s3_unicode(T('Distance    from    %s:')) % site_name)), TD((T('%.1f    km') % distance))))
            except:
                pass
            if len(req_items):
                iitable = s3db.inv_inv_item
                query = ((((iitable.site_id == site_id) & (iitable.deleted == False)) & ((iitable.expiry_date >= r.now) | (iitable.expiry_date == None))) & (iitable.status == 0))
                inv_items_dict = {}
                inv_items = db(query).select(iitable.item_id, iitable.quantity, iitable.item_pack_id)
                for item in inv_items:
                    item_id = item.item_id
                    if (item_id in inv_items_dict):
                        inv_items_dict[item_id] += (item.quantity * item.pack_quantity())
                    else:
                        inv_items_dict[item_id] = (item.quantity * item.pack_quantity())
                supply_item_represent = table.item_id.represent
                item_pack_represent = table.item_pack_id.represent
                no_match = True
                for req_item in req_items:
                    req_quantity = req_item.quantity
                    quantity_outstanding = (req_quantity - max(req_item.quantity_fulfil, req_item.quantity_transit))
                    if quantity_outstanding:
                        item_id = req_item.item_id
                        if (item_id in inv_items_dict):
                            inv_quantity = (inv_items_dict[item_id] / req_item.pack_quantity())
                        else:
                            inv_quantity = 0
                        if (inv_quantity != 0):
                            no_match = False
                            if (inv_quantity < req_quantity):
                                status = SPAN(T('Partial'), _class='req_status_partial')
                            else:
                                status = SPAN(T('YES'), _class='req_status_complete')
                        else:
                            status = (SPAN(T('NO'), _class='req_status_none'),)
                    else:
                        inv_quantity = T('N/A')
                        status = (SPAN(T('N/A'), _class='req_status_none'),)
                    items.append(TR(supply_item_represent(req_item.item_id), req_quantity, item_pack_represent(req_item.item_pack_id), quantity_outstanding, inv_quantity, status))
                if no_match:
                    response.warning = (s3_unicode(T('%(site_name)s    has    no    items    exactly    matching    this    request.    Use    Alternative    Items    if    wishing    to    use    other    items    to    fulfill    this    request!')) % dict(site_name=site_name))
                else:
                    commit_btn = A((s3_unicode(T('Send    from    %s')) % site_name), _href=URL(f='send_req', args=[r.id], vars=dict(site_id=site_id)), _class='action-btn')
                    s3.rfooter = TAG[''](commit_btn)
        else:
            response.error = T('User    has    no    Site    to    check    against!')
        output['items'] = items
        s3.no_sspag = True
        s3.no_formats = True
    else:
        output['items'] = s3.crud_strings.req_req_item.msg_list_empty
    response.view = 'list.html'
    return output
